branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>pauloed99/PO-atividade4<file_sep>/quickSort.py from random import randint import timeit import matplotlib as mpl import matplotlib.pyplot as plt from random import randrange def geraLista(tam): lista =[] while tam: lista.append(tam) tam-=1 return lista def particao(lista, comeco, fim, pivo): lista[pivo], lista[fim] = lista[fim], lista[pivo] s = comeco for i in range(comeco, fim): if lista[i] < lista[fim]: lista[i], lista[s] = lista[s], lista[i] s =s+1 lista[s], lista[fim] = lista[fim], lista[s] return s def quickSort(lista, comeco, fim): if comeco >= fim: return lista pivo = randrange(comeco, fim + 1) novoPivo = particao(lista, comeco, fim, pivo) quickSort(lista, comeco, novoPivo - 1) quickSort(lista, novoPivo + 1, fim) def quickSort2(lista): quickSort(lista, 0, len(lista) - 1) return lista mpl.use('Agg') def desenhaGrafico(x, y, file_name, xl="Entradas", yl="Saídas"): fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111) ax.plot(x, y, label="Lista Invertida") ax.legend(bbox_to_anchor=(1, 1), bbox_transform=plt.gcf().transFigure) plt.ylabel(yl) plt.xlabel(xl) fig.savefig(file_name) y = [] tempo = [] x = [100000, 200000, 300000, 400000, 500000, 1000000, 2000000] for k in range(len(x)): y.append(geraLista(x[k])) for a in range(len(x)): tempo.append(timeit.timeit("quickSort2({})".format(y[a]), setup="from __main__ import quickSort2", number=1)) desenhaGrafico(x, tempo, "graphTempo.png")
962859c5b2f130bc423abc2c08acde611bae3117
[ "Python" ]
1
Python
pauloed99/PO-atividade4
7194dd63a453195deda5df45d0662a33a5d45a2f
3e5242a70bed72ad55abbf5facb18b687d3f0505
refs/heads/master
<repo_name>jrullan/HackUPRM20160409<file_sep>/arduino/hackcommand.h #ifndef HACKCOMMAND_H #define HACKCOMMAND_H typedef struct hackcommand{ String cmd; String msg; String cli; String tok; }; /* class Command{ public: Command(); ~Command(); String cmd; String msg; String cli; String tok; private: }; */ #endif <file_sep>/webServer/testwebsock.php #!/usr/bin/env php <?php // Set no time limit set_time_limit ( 0 ); require_once('./websockets.php'); require_once ('./functions.php'); class echoServer extends WebSocketServer { //protected $maxBufferSize = 1048576; //1MB... overkill for an echo server, but potentially plausible for other applications. protected function validateUser($user, $message){ $token =''; //$query = "SELECT token FROM devices WHERE token = '$token' " ; //print_r($user); $parameters = json_decode($message); // print "user id: " . $user->id . " Token: " . $parameters->token ."\n"; // print_r($this); if (isset($parameters->token)){ if(trim($parameters->token) != '') { $this->token[$user->id] = $parameters->token; } } } protected function process($user, $message) { //$this->send($user, "hola : " . $message); // Verificamos que el device esta en la base de datos y lo actualizamos. !! $this->validateUser($user, $message); print "Data From User: " . $message . "\n"; $this->protocol($user, $message); } protected function connected($user) { // Do nothing: This is just an echo server, there's no need to track the user. // However, if we did care about the users, we would probably have a cookie to // parse at this step, would be looking them up in permanent storage, etc //verify that the client is the the database.. } protected function closed($user) { // Do nothing: This is where cleanup would go, in case the user had any sort of // open files or other objects associated with them. This runs after the socket // has been closed, so there is no need to clean up the socket itself here. } protected function protocol ($user, $message ){ //Rompemos el mensaje porque llegan en un json !! $parameters = json_decode($message); // print_r($parameters). "\n" ; switch ($parameters->cmd ) { case "ID": $this->send($user, $this->createMsg('ACK','',"Connected")); break; case "msg": $this->send($user, $this->createMsg('ACK','',"MSG Received")); break; case "getUsers": $this->send($user, $this->createMsg('users','',$this->getUsers() )); break; case "digitalWriteOn": $this->send($this->users[$parameters->client], $this->createMsg($parameters->cmd,'',$parameters->msg )); print " ENVIANDO MENSAJE A: " .$parameters->client ; break; case "digitalWriteOff": $this->send($this->users[$parameters->client], $this->createMsg($parameters->cmd,'',$parameters->msg )); print " ENVIANDO MENSAJE A: " .$parameters->client ; break; } switch ($parameters->msg ){ case "totalUsers": $this->send($user, "Total de Usuarios"); break; case "identify": break; /* default: print $message . "\n" ; $this->send($user, $this->createMsg('msg','',$message)); */ } } protected function getUsers(){ $clients = array(); foreach ($this->users as $key => $value) { $clients[] = $value->id ; } //print_r($this->users); return json_encode($clients); } protected function createMsg($cmd,$client,$msg){ //create the json that is going to be send to the client. $parameters = array(); $parameters["cmd"] = $cmd; $parameters["msg"] = $msg; $parameters["client"] = $client; //$parameters["token"] = $token; print json_encode($parameters,JSON_UNESCAPED_SLASHES) . "\n"; return json_encode($parameters,JSON_UNESCAPED_SLASHES); } } $server = 'vidal.ws'; $serverIP = gethostbyname($server); $internalIP = "10.0.0.10"; print $serverIP; //$echo = new echoServer($server,"9000"); $echo = new echoServer($internalIP,"443"); try { $echo->run(); } catch (Exception $e) { $echo->stdout($e->getMessage()); } <file_sep>/README.md # HackUPRM20160409 Proyecto de MakerspacePR en HackUPRM <file_sep>/arduino/NodeMCU_WebSocketClient.ino /* * This sketch is part of MakerspacePR team participation * in the HackUPRM hackathon @ 2016-04-09 12hrs hackathon * * The project consisted of developing an IoT (Internet of Things) service * similar to Blynk.cc (sans the mobile app) via a Websocket protocol server. * The main components of the project are: * * 1. A Websocket server - We implemented this in PHP on a remote server * 2. An Arduino sketch running on an ESP8266 board (NodeMCU v1.0) * 3. A web application running on a local web server * 4. A communications protocol * * Both the Arduino sketch and the web application are subscribed to the * Websocket server in order to achieve full-duplex (quasi real-time) * communications. A communications protocol was implemented to provide * web-to-device (W2D) and device-to-web (D2W) communications with acknowledges. * * The includes in this sketch are required for an ESP8266 board. * In particular, we are using the WebSockets library from * https://github.com/Links2004/arduinoWebSockets to implement the websocket * client in the ESP8266. * (Note: We had to modify this library's Hash.h file with an <Arduino.h> include * because the Arduino compiler complained about invalid declarations.) * * The original implementation of the communications protocol was done in json, * so we used a JSON parser library from blanchon: * https://github.com/bblanchon/ArduinoJson. We only used it to parse the json * sent from the Web application. The json sent to the websocket server * is created in a custom function createJson. One optimization is to use the * library's createObject(); * * Finally we defined a data structure for the messages in the * file hackcommand.h. It was meant to be a class, but at the end * to simplify we simply used a struct. */ #include <Arduino.h> #include <ESP8266WiFi.h> #include <WebSocketsClient.h> #include <Hash.h> #include <ArduinoJson.h> #include "hackcommand.h" #define TOKEN "ESP8266_1" //Unique identifier for this device messages WebSocketsClient webSocket; long timeSinceLastConnection; struct hackcommand inCmd = {"","","",TOKEN}; struct hackcommand outCmd = {"","","",TOKEN}; //not used void setup() { Serial.begin(115200); for(uint8_t t = 4; t > 0; t--) { delay(1000); } WiFi.begin("HACKUPRM","hackathonuprm"); while(WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("."); } Serial.println("Connecting socket"); webSocket.begin("192.168.127.12", 443); webSocket.onEvent(webSocketEvent); } void loop() { webSocket.loop(); } //================================================= // Functions //================================================= // This is the function called when the webSocket receives a message // from the server void webSocketEvent(WStype_t type, uint8_t * payload, size_t lenght) { Serial.println("Event detected"); String payloadString; for(int i = 0; i < lenght; i++){ payloadString += (char)payload[i]; } String message; switch(type) { case WStype_DISCONNECTED: Serial.print("Event: Disconnected! "); Serial.print((millis()-timeSinceLastConnection)/1000); Serial.println("s"); timeSinceLastConnection = millis(); break; case WStype_CONNECTED: Serial.println("Event: Connected!"); // send message to server when Connected message = createJson("ID","","",TOKEN); webSocket.sendTXT(message); break; case WStype_TEXT: Serial.print("Event: TEXT! "); Serial.print(payloadString); Serial.println(); if(parseJson(payloadString)){ Serial.print("Cmd: "); Serial.println(inCmd.cmd); Serial.print("Msg: "); Serial.println(inCmd.msg); Serial.print("Client: "); Serial.println(inCmd.cli); Serial.print("Token: "); Serial.println(inCmd.tok); parseCommand(&inCmd); } break; case WStype_BIN: Serial.print("Event: BIN! "); Serial.print(payloadString); Serial.println(); break; default: Serial.println("Event: No known event"); } } // This is a pin mapping function to correctly // address the pins in the NodeMCU board. The pin // numbers in the board labels do not match the // GPIO pin numbers which are the ones used by // Arduino. int pinMap(int pin){ switch(pin){ case 0: return 16; case 1: return 5; case 2: return 4; case 3: return 0; case 4: return 2; case 5: return 14; case 6: return 12; case 7: return 13; case 8: return 15; case 9: return 3; case 10: return 1; default: return 16; } } // This function parses the command received in the websocket // message to execute the requested action. Every action generates // an ACK response even if there is an error. void parseCommand(struct hackcommand *cmd){ if(cmd->cmd == "digitalWriteOn"){ int pin = cmd->msg.toInt(); if(pin > 10 && pin < 0){ String message = createJson("ACK","Wrong Pin","",TOKEN); webSocket.sendTXT(message); return; } pin = pinMap(pin); Serial.print("Turn ON pin "); Serial.println(pin); pinMode(pin,OUTPUT); digitalWrite(pin,HIGH); String message = createJson("ACK",cmd->cmd,"",TOKEN); webSocket.sendTXT(message); } if(cmd->cmd == "digitalWriteOff"){ int pin = cmd->msg.toInt(); if(pin > 10 && pin < 0){ String message = createJson("ACK","Wrong Pin","",TOKEN); webSocket.sendTXT(message); return; } pin = pinMap(pin); Serial.print("Turn OFF pin "); Serial.println(pin); pinMode(pin,OUTPUT); digitalWrite(pin,LOW); String message = createJson("ACK",cmd->cmd,"",TOKEN); webSocket.sendTXT(message); } } // This function uses the library to parse the json message // and decompose it into our command data structure. bool parseJson(String payloadString){ StaticJsonBuffer<400> jsonBuffer; JsonObject& root = jsonBuffer.parseObject(payloadString); if(!root.success()){ Serial.print("Could not parse JSON object: "); Serial.println(payloadString); return false; }else{ inCmd.cmd = root["cmd"].as<String>(); inCmd.msg = root["msg"].as<String>(); inCmd.cli = root["cli"].as<String>(); inCmd.tok = root["tok"].as<String>(); } return true; } // This function creates the json response or message to be sent // to the websocket server. String createJson(String cmd, String msg, String cli, String tok){ String json = ""; json += "{"; json += "\"cmd\":"; json += "\""; json += cmd; json += "\""; json += ","; json += "\"msg\":"; json += "\""; json += msg; json += "\""; json += ","; json += "\"client\":"; json += "\""; json += cli; json += "\""; json += ","; json += "\"token\":"; json += "\""; json += tok; json += "\""; //json += ","; json += "}"; return json; }
a16a85078d08708d9bfd40d7c0cd96a78272cc1a
[ "Markdown", "C++", "PHP" ]
4
C++
jrullan/HackUPRM20160409
8a58fc4cfd2a2a4f746419c4687ba38f05d31c92
d91544e0e569ff47015c5eee74960fa827838ef3
refs/heads/master
<file_sep>import * as actions from '../todos/actions'; import Component from '../components/component.react'; import React from 'react'; // import {FormattedMessage} from 'react-intl'; import {msg} from '../intl/store'; class ToCheck extends Component { render() { return ( <div className="buttons"> <button children={msg('todos.clearAll')} disabled={!this.props.clearAllEnabled} onClick={actions.clearAll} /> <button children={msg('todos.add100')} onClick={actions.addHundredTodos} /> {/* TODO: Reimplement undo. */} {/*<button disabled={undoStates.length === 1} onClick={() => this.undo()} ><FormattedMessage message={msg('todos.undo')} steps={undoStates.length - 1} /></button>*/} </div> ); } } ToCheck.propTypes = { clearAllEnabled: React.PropTypes.bool.isRequired }; export default ToCheck; <file_sep>import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import React from 'react'; import {Link} from 'react-router'; import {msg} from '../intl/store'; export default class Home extends Component { render() { return ( <DocumentTitle title={msg('home.title')}> <div className="home-page"> <p> App starter kit for <a href="https://github.com/steida/este"> Este.js</a>. Check <Link to="todos">todos</Link>. </p> </div> </DocumentTitle> ); } } <file_sep>export default { en: { auth: { title: 'Login', form: { legend: 'Login / Sign Up', placeholder: { email: '<EMAIL>', password: '<PASSWORD>' }, button: { login: 'Login', signup: 'Sign up' }, hint: 'Hint: <PASSWORD>' }, logout: { button: 'Logout' } }, buttons: { cancel: 'Cancel', edit: 'Edit', save: 'Save' }, confirmations: { cancelEdit: `You have unsaved changes. Are you sure you want to cancel them?` }, home: { title: 'Este.js App' }, me: { title: 'Me', welcome: `Hi {email}. This is your secret page.` }, notFound: { title: 'Page Not Found', header: 'This page isn\'t available', message: 'The link may be broken, or the page may have been removed.', continueMessage: 'Continue here please.' }, todos: { add100: 'Add 100 Todos', clearAll: 'Clear All', emptyList: 'Nothing. Go outside and enjoy world.', newTodoPlaceholder: 'What needs to be done?', title: 'Todos', undo: `Undo {steps, plural, =0 {} other {(#)} }` }, validation: { required: `Please fill out {prop, select, email {email} password {<PASSWORD>} other {'{prop}'} }.`, email: `Email address is not valid.`, password: `<PASSWORD> {min<PASSWORD>.` } } }; <file_sep>// import * as actions from './actions'; // import {appCursor} from '../state'; // import {register} from '../dispatcher'; // export const dispatchToken = register(({action, data}) => { // // switch (action) { // // case actions.someAppAction: // // appCursor(app => { // // return app.set... // // }) // // break // // } // }); <file_sep>import express from './express'; express(); <file_sep>import * as actions from './actions'; import Todo from './todo'; import {Range} from 'immutable'; import {getRandomString} from '../../lib/getrandomstring'; import {register} from '../dispatcher'; import {todosCursor} from '../state'; export const dispatchToken = register(({action, data}) => { switch (action) { case actions.addHundredTodos: todosCursor(todos => { return todos.update('list', list => { return list.withMutations(list => { Range(0, 100).forEach(i => { const id = getRandomString(); list.push(new Todo({ id: id, title: `Item #${id}` })); }); }); }); }); break; case actions.addTodo: todosCursor(todos => { return todos .update('list', (list) => { // Always denote what data represents. Favour readability over wtf. // Try to resist being smart ass. Fuck pride. // https://www.youtube.com/watch?v=ruhFmBrl4GM const todo = data; const newTodo = todo.merge({ id: getRandomString() }); return list.push(newTodo); }) .set('newTodo', new Todo); }); break; case actions.clearAll: todosCursor(todos => { return todos .update('list', list => list.clear()) .set('newTodo', new Todo); }); break; case actions.deleteTodo: todosCursor(todos => { const todo = data; return todos.update('list', list => list.delete(list.indexOf(todo))); }); break; case actions.onEditableState: todosCursor(todos => { const {id, name, state} = data; return todos.setIn(['editables', id, name], state); }); break; case actions.onNewTodoFieldChange: todosCursor(todos => { const {name, value} = data; return todos.setIn(['newTodo', name], value); }); break; case actions.saveTitle: todosCursor(todos => { // najit todo podle id, a zmenit mu title const {id, title} = data; return todos.update('list', list => { const idx = list.findIndex(todo => todo.id === id); return list.setIn([idx, 'title'], title); }); }); break; } }); <file_sep>import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import Logout from '../auth/logout.react'; import React from 'react'; import immutable from 'immutable'; import requireAuth from '../auth/requireauth.react'; import {msg} from '../intl/store'; class Me extends Component { render() { const email = this.props.auth.get('data').email; return ( <DocumentTitle title={msg('me.title')}> <div className="me-page"> <p> {msg('me.welcome', {email: email})} </p> <Logout /> </div> </DocumentTitle> ); } } Me.propTypes = { auth: React.PropTypes.instanceOf(immutable.Map).isRequired }; export default requireAuth(Me); <file_sep>import * as actions from './actions'; import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import React from 'react'; import exposeRouter from '../components/exposerouter.react'; import immutable from 'immutable'; import {focusInvalidField} from '../../lib/validation'; import {msg} from '../intl/store'; require('./login.styl'); class Login extends Component { getForm() { return this.props.auth.get('form'); } onFormSubmit(e) { e.preventDefault(); const fields = this.getForm().fields.toJS(); actions.login(fields) .then(() => { this.redirectAfterLogin(); }) .catch(focusInvalidField(this)); } redirectAfterLogin() { const nextPath = this.props.router.getCurrentQuery().nextPath; this.props.router.replaceWith(nextPath || '/'); } render() { const form = this.getForm(); return ( <DocumentTitle title={msg('auth.title')}> <div className="login"> <form onSubmit={e => this.onFormSubmit(e)}> <fieldset disabled={actions.login.pending}> <legend>{msg('auth.form.legend')}</legend> <input autoFocus name="email" onChange={actions.updateFormField} placeholder={msg('auth.form.placeholder.email')} value={form.fields.email} /> <br /> <input name="password" onChange={actions.updateFormField} placeholder={msg('auth.form.placeholder.password')} type="password" value={form.fields.password} /> <br /> <button children={msg('auth.form.button.login')} disabled={actions.login.pending} type="submit" /> {/* <button type="submit">{msg('auth.form.button.signup')}</button> */} {form.error && <span className="error-message">{form.error.message}</span> } <div>{msg('auth.form.hint')}</div> </fieldset> </form> </div> </DocumentTitle> ); } } Login.propTypes = { auth: React.PropTypes.instanceOf(immutable.Map).isRequired, router: React.PropTypes.func }; export default exposeRouter(Login); <file_sep>import IntlMessageFormat from 'intl-messageformat'; import IntlRelativeFormat from 'intl-relativeformat'; import {i18nCursor} from '../state'; import {register} from '../dispatcher'; const cachedInstances = Object.create(null); const intlRelativeFormat = new IntlRelativeFormat; function getCachedInstanceOf(message) { if (message in cachedInstances) return cachedInstances[message]; // TODO: Add locales support. cachedInstances[message] = new IntlMessageFormat(message); return cachedInstances[message]; } // This store can export getters, because messages are constants. export function msg(path, values = null): string { const pathParts = ['messages'].concat(path.split('.')); const message = i18nCursor(pathParts); if (message == null) throw new ReferenceError('Could not find Intl message: ' + path); if (!values) return message; return getCachedInstanceOf(message).format(values); } export function relativeDateFormat(date, options?): string { return intlRelativeFormat.format(date, options); } export function dateFormat(date, locales?, options?): string { const dateTimeFormat = new Intl.DateTimeFormat(locales, options); return dateTimeFormat.format(date); } export const dispatchToken = register(({action, data}) => { // TODO: Allow changing locale without app reload. Reset cache, force update // root app component and PureComponents as well. }); <file_sep>// import config from './config'; import messages from '../client/messages'; // TODO: Language switching. const initialLocale = 'en'; export default { // Each key represents one app feature/store. app: {}, auth: { data: null, form: null }, i18n: { formats: {}, locales: initialLocale, messages: messages[initialLocale] }, pendingActions: {}, todos: { editables: {}, // New Todo data. Imagine new, not yet saved Todo, is being edited, and // changes are persisted on server. Therefore we need to revive it as well. newTodo: { title: '' }, // Initial state can contain prefetched lists and maps. List for array, map // for object. We can also use sortedByTitle list, if we need sorted data. list: [ {id: 1, title: 'consider ‘stop doing’ app'}, {id: 2, title: 'relax'} ] }, user: { // User can be authenticated on server, and then isLoggedIn must be true. isLoggedIn: false } }; <file_sep>import Promise from 'bluebird'; import setToString from '../../lib/settostring'; import {dispatch} from '../dispatcher'; export const MAX_TODO_TITLE_LENGTH = 42; export function addHundredTodos() { dispatch(addHundredTodos); } export function addTodo(todo) { const title = todo.title.trim(); if (!title) return; dispatch(addTodo, todo); } export function clearAll() { dispatch(clearAll); } export function deleteTodo(todo) { dispatch(deleteTodo, todo); } export function onEditableState(id, name, state) { dispatch(onEditableState, {id, name, state}); } export function onNewTodoFieldChange({target: {name, value}}) { switch (name) { case 'title': value = value.slice(0, MAX_TODO_TITLE_LENGTH); break; } dispatch(onNewTodoFieldChange, {name, value}); } export function saveTitle(id, title) { // Simulate async saving. const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve({id, title}); }, 300); }); return dispatch(saveTitle, promise); } // Override toString methods. Pretty useful for dispatched actions monitoring. setToString('todos', { addHundredTodos, addTodo, clearAll, deleteTodo, onEditableState, onNewTodoFieldChange, saveTitle }); <file_sep>import Promise from 'bluebird'; import setToString from '../../lib/settostring'; import {ValidationError} from '../../lib/validation'; import {dispatch} from '../dispatcher'; import {validate} from '../validation'; export function login(fields) { // Promise, because we don't know whether fields are valid etc. const promise = validateForm(fields) .then(() => { return validateCredentials(fields); }) .catch(error => { loginError(error); throw error; }); // With promise, we can use pending actions to temporally disable form. // It's the easiest way to prevent submitting form multiple times, and we can // show it in user interface easily with `actions.foo.pending` property. return dispatch(login, promise); } function validateForm(fields) { // This validate function is just dumb wrapper over node-validator providing // promise api, so we can mix client sync and server async validation easily. return validate(fields) // Of course you can add your own validation helpers. Easily. .prop('email').required().email() .prop('password').required().simplePassword() .promise; } function validateCredentials(fields) { // Simulate lengthy async action. return new Promise((resolve, reject) => { setTimeout(() => { if (fields.password === '<PASSWORD>') resolve(fields); else reject(new ValidationError('Wrong password', 'password')); }, 1000); }); } export function loginError(error) { dispatch(loginError, error); } export function logout() { // Always reload app on logout for security reasons. location.href = '/'; } export function updateFormField({target: {name, value}}) { // Both email and password max length is 100. value = value.slice(0, 100); dispatch(updateFormField, {name, value}); } setToString('auth', { login, loginError, logout, updateFormField }); <file_sep>import Component from '../components/component.react'; import React from 'react'; import {Link} from 'react-router'; class Menu extends Component { render() { return ( <header> <h1> <a href="https://github.com/steida/este">Este.js</a> App </h1> <ul> <li><Link to="home">Home</Link></li> <li><Link to="todos">Todos</Link></li> <li><Link to="me">Me (protected)</Link></li> {/* Note simple rule: Never put HTML and JS into the same line.*/} {!this.props.isLoggedIn && <li><Link to="login">Login</Link></li> } </ul> </header> ); } } Menu.propTypes = { isLoggedIn: React.PropTypes.bool }; export default Menu; <file_sep>import Component from '../components/component.react'; import React from 'react'; import Todo from './todo.react'; import immutable from 'immutable'; import {msg} from '../intl/store'; class List extends Component { render() { const todos = this.props.todos; if (!todos.size) return ( <p>{msg('todos.emptyList')}</p> ); return ( <ol className="todo-list"> {todos.map((todo, i) => <Todo editable={this.props.editables.get(todo.id)} key={todo.id} /* TODO: Pass concrete pending action. */ pendingActions={this.props.pendingActions} todo={todo} /> )} </ol> ); } } List.propTypes = { editables: React.PropTypes.instanceOf(immutable.Map).isRequired, pendingActions: React.PropTypes.instanceOf(immutable.Map).isRequired, todos: React.PropTypes.instanceOf(immutable.List) }; export default List; <file_sep>/*eslint-disable no-console */ import compression from 'compression'; import config from './config'; import express from 'express'; // import favicon from 'serve-favicon'; import render from './render'; export default function() { const app = express(); app.use(compression()); // TODO: Add favicon. // app.use(favicon('assets/img/favicon.ico')) // TODO: Move to CDN. app.use('/build', express.static('build')); app.use('/assets', express.static('assets')); app.get('*', (req, res) => { const acceptsLanguages = req.acceptsLanguages(config.appLocales); render(req, res, acceptsLanguages || config.defaultLocale) .catch((error) => { const msg = error.stack || error; console.log(msg); res.status(500).send('500: ' + msg); }); }); app.listen(config.port); console.log(`App started on port ${config.port}`); } <file_sep>import Validation from '../lib/validation'; import {msg} from './intl/store'; class AppValidation extends Validation { getRequiredMessage(prop) { return msg('validation.required', {prop}); } getEmailMessage(prop) { return msg('validation.email', {prop}); } getSimplePasswordMessage(minLength) { return msg('validation.password', {minLength}); } } export function validate(object: Object) { return new AppValidation(object); } <file_sep>import React from 'react'; import Router from 'react-router'; import routes from './routes'; // Never render to body. Everybody updates it. // https://medium.com/@dan_abramov/two-weird-tricks-that-fix-react-7cf9bbdef375 const app = document.getElementById('app'); Router.run(routes, Router.HistoryLocation, (Handler) => { console.time('app render on route change'); // eslint-disable-line no-console React.render(<Handler />, app, () => { console.timeEnd('app render on route change'); // eslint-disable-line no-console }); }); // if ('production' === process.env.NODE_ENV) { // // TODO: Report app errors. // } <file_sep>import {Record} from 'immutable'; const DataRecord = Record({ email: '', password: '' }); export default class Data extends DataRecord {} <file_sep>import Buttons from './buttons.react'; import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import List from '../todos/list.react'; import NewTodo from '../todos/newtodo.react'; import React from 'react'; import ToCheck from './tocheck.react'; import immutable from 'immutable'; import {msg} from '../intl/store'; // Leverage webpack require goodness. require('./todos.styl'); class Todos extends Component { render() { const editables = this.props.todos.get('editables'); const newTodo = this.props.todos.get('newTodo'); const todos = this.props.todos.get('list'); return ( <DocumentTitle title={msg('todos.title')}> <section className="todos-page"> <NewTodo todo={newTodo} /> <List editables={editables} pendingActions={this.props.pendingActions} todos={todos} /> <Buttons clearAllEnabled={todos.size > 0} /> <ToCheck /> </section> </DocumentTitle> ); } } Todos.propTypes = { app: React.PropTypes.instanceOf(immutable.Map).isRequired, pendingActions: React.PropTypes.instanceOf(immutable.Map).isRequired, todos: React.PropTypes.instanceOf(immutable.Map).isRequired }; export default Todos; <file_sep>import Component from '../components/component.react'; import React from 'react'; import {userCursor} from '../state'; // Higher order component. // https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750 export default function requireAuth(WrappedComponent) { class Authenticated extends Component { static willTransitionTo(transition) { const isLoggedIn = userCursor().get('isLoggedIn'); if (isLoggedIn) return; transition.redirect('/login', {}, { nextPath: transition.path }); } render() { return <WrappedComponent {...this.props} />; } } Authenticated.displayName = `${WrappedComponent.name}Authenticated`; return Authenticated; } <file_sep>import * as actions from './actions'; import Data from './data.js'; import {authCursor} from '../state'; import {register} from '../dispatcher'; export const dispatchToken = register(({action, data}) => { switch (action) { case actions.login: authCursor(auth => { return auth.setIn(['data'], new Data(data)); }); break; case actions.loginError: authCursor(auth => { const error = data; return auth.setIn(['form', 'error'], error); }); break; case actions.updateFormField: authCursor(auth => { const {name, value} = data; return auth.setIn(['form', 'fields', name], value); }); break; } }); <file_sep>import * as actions from './actions'; import Component from '../components/component.react'; import React from 'react'; import immutable from 'immutable'; import {msg} from '../intl/store'; class NewTodo extends Component { addTodoOnEnter(e) { if (e.key === 'Enter') actions.addTodo(this.props.todo); } render() { return ( <input autoFocus className="new-todo" name="title" onChange={actions.onNewTodoFieldChange} onKeyDown={(e) => this.addTodoOnEnter(e)} placeholder={msg('todos.newTodoPlaceholder')} value={this.props.todo.title} /> ); } } NewTodo.propTypes = { todo: React.PropTypes.instanceOf(immutable.Record) }; export default NewTodo; <file_sep>// import * as actions from './actions'; import * as authActions from '../auth/actions'; import {register} from '../dispatcher'; import {userCursor} from '../state'; export const dispatchToken = register(({action, data}) => { switch (action) { // See how user store can handle auth action. case authActions.login: userCursor(user => { return user.setIn(['isLoggedIn'], true); }); break; } }); <file_sep>/*eslint-disable no-console */ import {pendingActionsCursor} from './state'; import {Dispatcher} from 'flux'; const dispatcher = new Dispatcher; const isDev = 'production' !== process.env.NODE_ENV; export function register(callback: Function): string { return dispatcher.register(callback); } export function dispatch(action: Function, data: ?Object, options: ?Object) { if (isDev && action.toString === Function.prototype.toString) throw new Error(`Action ${action} toString method has to be overridden by setToString.`); const looksLikePromise = data && typeof data.then === 'function'; if (looksLikePromise) return dispatchAsync(action, data, options); else dispatchSync(action, data); } export function waitFor(ids: Array) { dispatcher.waitFor(ids); } export function isPending(actionName) { return pendingActionsCursor().has(actionName); } function dispatchAsync(action: Function, promise: Object, options: ?Object) { const actionName = action.toString(); // Pending property is defined lazily. if (!action.hasOwnProperty('pending')) Object.defineProperty(action, 'pending', { get: () => isPending(actionName) }); if (isPending(actionName)) if (isDev) console.warn(`Warning: Action ${actionName} is already pending.`); if (isDev) console.log(`pending ${actionName}`); setPending(actionName, true); return promise.then( (data) => { setPending(actionName, false); dispatchSync(action, data); return data; }, (reason) => { if (isDev) console.log(`reject ${actionName}`); setPending(actionName, false); throw reason; } ); } function setPending(actionName: string, pending: boolean) { pendingActionsCursor(pendingActions => pending ? pendingActions.set(actionName, true) : pendingActions.delete(actionName) ); } function dispatchSync(action: Function, data: ?Object) { // To log dispatched data, uncomment comment. if (isDev) console.log(action.toString()); // , data dispatcher.dispatch({action, data}); } <file_sep>import Component from '../components/component.react'; import React from 'react'; import {Link} from 'react-router'; class ToCheck extends Component { render() { return ( <div className="tocheck"> <h3> Things to Check </h3> <ul> <li> View page source, take a look how HTML is server rendered with initial data. </li> <li>Open console, take a look how actions are logged from <code>src/client/dispatcher.js</code>.</li> <li> Development mode (<code>gulp</code>), try edit styles or react component to see <a href="https://www.youtube.com/watch?v=pw4fKkyPPg8"> live-editing</a> without app reload. </li> <li> Production mode (<code>gulp -p</code>), to check built app performance and size. </li> <li> Isomorphic <Link to="/this-is-not-the-web-page-you-are-looking-for"> 404</Link> page. </li> <li>Undo button. (temporally disabled)</li> <li>Edit todo: Click to edit, esc to cancel, enter to save.</li> <li> Global immutable app state, have you seen this <a href="https://www.youtube.com/watch?v=5yHFTN-_mOo"> video</a>? Try <b>ctrl+shift+s</b> to save app state, and <b> ctrl+shift+l</b> to load. </li> <li> <a href="http://facebook.github.io/react/docs/advanced-performance.html"> Advanced performance</a> with PureComponent. Always use PureComponent and everything will be faster and simpler. </li> <li>... and much more.</li> </ul> </div> ); } } export default ToCheck; <file_sep>// import setToString from '../../lib/settostring'; // import {dispatch} from '../dispatcher'; // export function someAppAction() { // dispatch(someAppAction) // } // setToString('app', { // someAppAction // })
0e129231eb6488fc6b7d027bcdda58b657df8f0c
[ "JavaScript" ]
26
JavaScript
gaearon/este
2a69aa4dbd1d075972ac4ca6b2cd62e9756af60d
a95fb835e71bfd432f149575794f7bf166f649f8
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Jogador : MonoBehaviour { float velAtual; public float velMaxima = 3.0f; public float acelInicial = 0.2f; public float acel = 0.01f; public float des = 0.07f; public float velRotacao = 130.0f; Animator anim; void Awake() { anim = GetComponent<Animator>(); } void Update() { float v = Input.GetAxisRaw("Vertical"); //print(v); if (v >0 && velAtual < velMaxima) { velAtual += (velAtual == 0f) ? acelInicial : acel; } else if (v == 0 && velAtual > 0) { velAtual -= des; } velAtual = Mathf.Clamp(velAtual, 0, velMaxima); transform.Translate(Vector3.forward * velAtual * Time.deltaTime); //rotação float h = Input.GetAxisRaw("Horizontal"); Vector3 rotacao = Vector3.up * h * velRotacao * Time.deltaTime; if (velAtual > 0) { transform.Rotate(rotacao); } float valorAnim = Mathf.Clamp(velAtual / velMaxima, 0, 1); anim.SetFloat("Speed", valorAnim); } }
11e8ef02f1511080fb16c5db9358d6168766dd40
[ "C#" ]
1
C#
WilliamBotura/23__04_BlendTree
270ce0463b0bc2ea4c8e199cefe80a368059d4c1
40dcea5bc53d3a2fdda996db27a426dd3d34a729
refs/heads/master
<file_sep>## The script bellow writes to disk the plot3.png file which reconstructs ./figure/unnamed-chunk-4.png ## The output is a 480x480 transparent png as required, though the sample is 504x504 ## The script does the following steps ## (1) Downloads and unzips data from UC Irvine Machine Learning Repository if not yet in working directory ## (2) Reads txt file to dataset and subsets 2 days data ## (3) Calculates a new DateTime variable from Data and Time ## (4) Writes plot for 3 measures of Energy sub metering vs DateTime in png graphic device ## Usage: ## (1) Run the script "plot3.R" ## Download and unzip data from repository to ./data/ directory if not downloaded yet ## This code is common for the four files of the assignment DownloadURL <- 'https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip' LocalZipPath <- './data/household_power_consumption.zip' LocalCsvPath <- './data/household_power_consumption.txt' if(!dir.exists('./data/')) dir.create('./data/') if(!file.exists(LocalZipPath)) download.file(DownloadURL, destfile = LocalZipPath) if(!file.exists(basename(LocalCsvPath))) unzip(LocalZipPath, basename(LocalCsvPath), exdir = './data/') ## Read txt file to dataset with 2,075,259 rows and 9 columns Dataset <- read.csv2(LocalCsvPath, na.strings='?', dec = ".", colClasses=c('Date'='character', 'Time'='character')) ## Filter Dataset to dates we are working with Dataset <- subset(Dataset, Date %in% c('1/2/2007','2/2/2007')) ## Calculate DateTime from Date and Time variables and add to new variable in dataset Dataset$DateTime <- strptime(paste0(Dataset$Date, ' ',Dataset$Time), '%d/%m/%Y %H:%M:%S') ## Open png graphic device with right options png(filename = 'plot3.png', width = 480, height = 480, bg = 'transparent') ## Print graph in png graphic device plot(Dataset$DateTime, Dataset$Sub_metering_1, ylab = 'Energy sub metering', type='l', xlab = '') lines(Dataset$DateTime, Dataset$Sub_metering_2, col='red') lines(Dataset$DateTime, Dataset$Sub_metering_3, col='blue') legend("topright", col = c('black', 'red', 'blue'), legend = c('Sub_metering_1', 'Sub_metering_2', 'Sub_metering_3'), lty = 1) ## close device dev.off() <file_sep>## The script bellow writes to disk the plot1.png file which reconstructs ./figure/unnamed-chunk-2.png ## The output is a 480x480 transparent png as required, though the sample is 504x504 ## The script does the following steps ## (1) Downloads and unzips data from UC Irvine Machine Learning Repository if not yet in working directory ## (2) Reads txt file to dataset and subsets 2 days data ## (3) Writes histogram for Global_active_power variable in png graphic device ## Usage: ## (1) Run the script "plot1.R" ## Download and unzip data from repository to ./data/ directory if not downloaded yet ## This code is common for the four files of the assignment DownloadURL <- 'https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip' LocalZipPath <- './data/household_power_consumption.zip' LocalCsvPath <- './data/household_power_consumption.txt' if(!dir.exists('./data/')) dir.create('./data/') if(!file.exists(LocalZipPath)) download.file(DownloadURL, destfile = LocalZipPath) if(!file.exists(basename(LocalCsvPath))) unzip(LocalZipPath, basename(LocalCsvPath), exdir = './data/') ## Read txt file to dataset with 2,075,259 rows and 9 columns Dataset <- read.csv2(LocalCsvPath, na.strings='?', dec = ".", colClasses=c('Date'='character', 'Time'='character')) ## Filter rows for the dates we are working with: 2007-02-01 and 2007-02-02 Dataset <- subset(Dataset, Date %in% c('1/2/2007','2/2/2007')) ## Open png graphic device with right options png(filename = 'plot1.png', width = 480, height = 480, bg = 'transparent') ## Print graph in png graphic device hist(Dataset$Global_active_power, main='Global Active Power', xlab = 'Global Active Power (kilowatts)', col = 'red') ## close device dev.off() <file_sep>## Introduction The overall goal here is to reconstruct the four plots provided in the sample respository, all of which were constructed using the base plotting system. The results include: 1. Four separate R code files (plot1.R, plot2.R, etc.) that construct the corresponding plot, i.e. code in plot1.R constructs the plot1.png plot. 2. Four separate files (plot1.png, plot2.png, etc.) with the sample graphs in a 480x480 transparent png file. The scripts include code for reading the data from the [UC Irvine Machine Learning Repository](http://archive.ics.uci.edu/ml/), so that the plot can be fully reproduced. The four original plots are shown below above the corresponding generated versions. Note that the legend for datetime variable is in spanish due to local configuration of computer that generated the plots. ### Plot 1 (Original) ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-2.png) ### Plot 1 (Generated with plot1.R) ![Generated Plot 1](plot1.png) ### Plot 2 (Original) ![plot of chunk unnamed-chunk-3](figure/unnamed-chunk-3.png) ### Plot 2 (Generated with plot2.R) ![Generated Plot 2](plot2.png) ### Plot 3 (Original) ![plot of chunk unnamed-chunk-4](figure/unnamed-chunk-4.png) ### Plot 3 (Generated with plot3.R) ![Generated Plot 3](plot3.png) ### Plot 4 (Original) ![plot of chunk unnamed-chunk-5](figure/unnamed-chunk-5.png) ### Plot 4 (Generated with plot4.R) ![Generated Plot 4](plot4.png)
47a088cbc5671cc689a7f16bdbd9421ede9ee7e4
[ "Markdown", "R" ]
3
R
jluismarin/ExData_Plotting1
257d048f12fb4657baa22a5299d216d3d0fa6da4
b449aa5151dec6276c8bff92fb4e29ff1d656580
refs/heads/master
<file_sep># Changelog ## [0.1.1] - 2018-11-4 ### Added - Added .npmignore to reduce package size ## [0.1.0] - 2018-11-4 Initial Release <file_sep>import fs from 'fs'; import path from 'path'; import { promisify } from 'util'; import { default as archiver } from 'archiver'; import { info, error } from './utils'; export const archive = (packageName: any): Promise<number> => new Promise((resolve) => { // Create an output stream and set up the archive const output = fs.createWriteStream(path.join(process.cwd(), `${packageName}.zip`)); const zip = archiver('zip', { zlib: { level: 9 }, // Sets the compression level. }); // When the zip file is finished resolve the promise output.on('close', () => { resolve(zip.pointer()); }); // If there is an error writing the zip file, throw zip.on('error', (err) => { throw err; }); // Pipe the archive data to the output (stay non thread-blocking) zip.pipe(output); // Add the "lib" folder at the root of the zip folder info('Adding lib'); zip.directory('lib/', false); // Add the "node_modules" folder info('Adding node_modules'); zip.directory('node_modules', 'node_modules'); info('Bundling Everything Up'); zip.finalize(); }); const bundle = async () => { const packageName = await promisify(fs.readFile)('package.json') .then(res => JSON.parse(res.toString('utf8')).name) .catch((err) => { error('An unexpected error occurred while reading your package.json'); error(err.message); return; }); if (packageName === undefined) { process.exit(1); return; } await archive(packageName) .then((size) => { info(`\nBundle successfully written to ${packageName}.zip with size ${size}`); process.exit(0); }) .catch((err: Error) => { error('An unexpected error occurred while packaging your bundle'); error(err.message); process.exit(1); }); }; export default bundle; <file_sep>import fs from 'fs'; import * as bundle from './bundle'; describe('bundle.ts', () => { describe('default', () => { let exitSpy: jest.SpyInstance; beforeEach(() => { exitSpy = jest.spyOn(process, 'exit'); exitSpy.mockImplementation((code: number) => code); }); afterEach(() => { exitSpy.mockRestore(); }); test('should exit with code 1 if reading the package.json fails', async () => { const readFileSpy = jest.spyOn(fs, 'readFile'); readFileSpy.mockImplementation(() => { throw new Error('read file failed'); }); await bundle.default(); expect(exitSpy).toHaveBeenCalledWith(1); expect(readFileSpy).toHaveBeenCalledTimes(1); readFileSpy.mockReset(); }); test('should exit with code 1 if archiving fails', async () => { const readFileSpy = jest.spyOn(fs, 'readFile'); readFileSpy.mockImplementation((filePath: string, callback) => { callback(null, Buffer.from(JSON.stringify({ name: 'foo' }))); }); const archiveSpy = jest.spyOn(bundle, 'archive'); archiveSpy.mockImplementation(async () => { throw new Error('archive failed'); }); await bundle.default(); expect(exitSpy).toHaveBeenCalledWith(1); expect(readFileSpy).toHaveBeenCalledTimes(1); expect(archiveSpy).toHaveBeenCalledTimes(1); expect(archiveSpy).toHaveBeenCalledWith('foo'); readFileSpy.mockRestore(); archiveSpy.mockRestore(); }); test('should exit with code 0 if archiving succeeds', async () => { const readFileSpy = jest.spyOn(fs, 'readFile'); readFileSpy.mockImplementation((filePath: string, callback) => { callback(null, Buffer.from(JSON.stringify({ name: 'foo' }))); }); const archiveSpy = jest.spyOn(bundle, 'archive'); archiveSpy.mockImplementation(async () => 10); await bundle.default(); expect(exitSpy).toHaveBeenCalledWith(0); expect(readFileSpy).toHaveBeenCalledTimes(1); expect(archiveSpy).toHaveBeenCalledTimes(1); expect(archiveSpy).toHaveBeenCalledWith('foo'); readFileSpy.mockRestore(); archiveSpy.mockRestore(); }); }); // TODO: Write tests for the archiving function describe.skip('archive', () => {}); }); <file_sep>> **DEPRECATED** This package has been deprecated, and will receive no further updates or support from Kienle Holdings. # bundle-lambda > CLI to package up a lambda function and its node modules in a zip folder ## Prerequisites * Node LTS * NPM or yarn ## Installation 1. `npm install -g bundle-lambda` or `yarn global add bundle-lambda` ## Usage ```text Usage: bundle-lambda [<args>] [<options>] Commands: bundle-lambda bundle create a bundle of your project's files and node modules Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] ``` ## Development 1. `yarn install` 2. `yarn run build` <file_sep>import yargs from 'yargs'; describe('index.ts', () => { test('should call each function in the yargs chain', () => { let finishedChain = false; const finishChain = () => { finishedChain = true; return; }; const mockYargs = { alias: () => mockYargs, argv: finishChain(), command: () => mockYargs, demandCommand: () => mockYargs, help: () => mockYargs, scriptName: () => mockYargs, version: () => mockYargs, }; const usageSpy = jest.spyOn(yargs, 'usage'); usageSpy.mockImplementation(() => mockYargs); require('./'); expect(usageSpy).toHaveBeenCalledTimes(1); expect(finishedChain).toEqual(true); usageSpy.mockRestore(); }); });
f4003ca678964e622b1b77092808780e38bbb35d
[ "Markdown", "TypeScript" ]
5
Markdown
kienleholdings/bundle-lambda
3cac5e6cf2188cfbaef576b8406fc6580da2cba6
5e2f0348c9ea386aa588f1d2cfa233a00d1b8f02
refs/heads/main
<repo_name>Visrutha/SoftComputing-Assign_1<file_sep>/UniformCostSearch.py import pandas as pd import numpy as np import matplotlib.pyplot as plt from networkx.drawing.nx_agraph import graphviz_layout import networkx as nx def display_graph(path): G = nx.Graph() G.add_edges_from(path) pos = graphviz_layout(G, prog="dot") nx.draw(G, pos, with_labels=True) plt.show() def uniform_cost_search(edges, initial_node, goal_node): priority_queue = pd.DataFrame([['R',initial_node,0]], columns=['from','to','weights']) traversed = pd.DataFrame(columns=['from','to','weights']) closed = [] parent = { initial_node:'R' } success = False while not priority_queue.empty: from_node = priority_queue.iloc[0]['from'] current_node = priority_queue.iloc[0]['to'] current_weight = priority_queue.iloc[0]['weights'] priority_queue = priority_queue.iloc[1:] if current_node not in closed: parent[current_node] = from_node traversed = traversed.append(pd.DataFrame([[from_node, current_node, current_weight]], columns=['from','to','weights'])) if current_node == goal_node: success = True break closed.append(current_node) next_rows = edges.loc[(edges['from']==current_node) |(edges['to']==current_node)] next_rows = next_rows.apply(lambda row: reversal_node(row, current_node, current_weight), axis=1) next_rows = next_rows[~next_rows.to.isin(closed)] priority_queue = priority_queue.append(next_rows) priority_queue = priority_queue.sort_values(by=['weights']).reset_index(drop=True) shortest_path = [current_node] while current_node != 'R': parent_node = traversed.loc[(traversed['to']==current_node)].iloc[0]['from'] shortest_path.insert(0,parent_node) current_node = parent_node search_space = [] for row in traversed.iterrows(): search_space.append((row[1]['from'],row[1]['to'])) display_graph(search_space) total_weight = traversed.loc[(traversed['to']==goal_node)].iloc[0]['weights'] return { "success":success, "path": shortest_path[1:], "weights": total_weight} if __name__ == '__main__': edges = pd.read_csv('Graph.csv') initial_node = 'A' goal_node = 'M' print(uniform_cost_search(edges, initial_node, goal_node))
5da0b174da44eedad2e8aefdfa80a4cbdc6586a8
[ "Python" ]
1
Python
Visrutha/SoftComputing-Assign_1
c831a2f8a7207c438a5ac1adcaa5438d1bd95524
629e990ac2dadba46a52b661de496cac063732e2
refs/heads/master
<repo_name>rdpeng/plumberdemo<file_sep>/confmedian_client.R library(aws.s3) library(jsonlite) library(curl) library(glue) ## Need to have AWS credentials set in .Renviron already! ## Compute the 95% confidence interval for the median using ## a remote server median_CI <- function(x, N = 1000) { bucket <- "confint" buckets_available <- bucketlist()$Bucket if(bucket %in% buckets_available) { message("using '", bucket, "' bucket") } else { stop("'", bucket, "' bucket not available") } ## Upload the data to AWS S3 bucket ## Key for storing data on AWS key <- "xdata" val <- s3saveRDS(x, key, bucket) if(!val) { stop("problem saving data to S3") } ## Call the function on the remote server ## Construct API URL and open connection to the web server cmd <- glue("http://172.16.58.3:8000/confint?", "key={key}&bucket={bucket}&N={N}") con <- curl(cmd) ## Read the answer from the server message("connecting to server") tryCatch({ ans <- readLines(con, 1, warn = FALSE) }, finally = { ## Close server connection close(con) }) ## Convert answer from JSON and return fromJSON(ans) } <file_sep>/confmedian_server.R library(aws.s3) ## Return 95% confidence interval for the median confint_median <- function(x, N = 1000) { ## Coerce to numeric x <- as.numeric(x) ## Remove missing values x <- x[!is.na(x)] if(length(x) == 0L) stop("no non-missing data values") nobs <- length(x) med <- replicate(N, { x.new <- sample(x, nobs, replace = TRUE) median(x.new) }) quantile(med, c(0.025, 0.975)) } #* Compute the 95% bootstrap confidence interval for the median #* @param key the S3 key for the data #* @param bucket the name of the bucket where the data live #* @param N the number of bootstrap iterations #* @get /confint confint_median_compute <- function(key, bucket, N) { ## Make sure data is proper type key <- as.character(key) bucket <- as.character(bucket) N <- as.integer(N) ## Read data from S3 x <- s3readRDS(key, bucket = bucket) ## Compute the confidence interval confint_median(x, N) } <file_sep>/ozone_client.R ## Ozone client function library(jsonlite) library(curl) library(glue) ozone_predict_remote <- function(temp) { ## Construct API URL cmd <- glue("http://192.168.3.11:8000/ozone?", "temp={temp}") ## Open connection to the web server con <- curl(cmd) ## Read the answer from the server ans <- readLines(con, 1, warn = FALSE) ## Close server connection close(con) ## Convert answer from JSON and return fromJSON(ans) } ozone_vpredict_remote <- function(temp) { temp <- paste(temp, collapse = ",") ## Construct API URL cmd <- glue("http://67.205.166.80:8000/ozone_v?", "temp={temp}") ## Open connection to the web server message("connecting to server...") con <- curl(cmd) ## Read the answer from the server ans <- readLines(con, 1, warn = FALSE) ## Close server connection close(con) ## Convert answer from JSON and return fromJSON(ans) } <file_sep>/ozone_server.R # # This is a Plumber API. In RStudio 1.2 or newer you can run the API by # clicking the 'Run API' button above. # # In RStudio 1.1 or older, see the Plumber documentation for details # on running the API. # # Find out more about building APIs with Plumber here: # # https://www.rplumber.io/ # library(plumber) ## Predict Ozone Levels Given Temperature library(splines) library(datasets) fit <- lm(Ozone ~ ns(Temp, 2), data = airquality) #* Predict Ozone from a Single Temperature #* @param temp The temperature input #* @get /ozone ozone_predict <- function(temp) { ## Check input type temp <- as.numeric(temp) ## Make prediction from fitted model p <- predict(fit, data.frame(Temp = temp)) ## Return predicted value as.numeric(p) } ## temp is specified as temp1,temp2,temp3 #* Predict Ozone from a Single Temperature #* @param temp The temperature input #* @get /ozone_v ozone_vpredict <- function(temp) { temp <- URLdecode(temp) temp <- strsplit(temp, ",", fixed = TRUE)[[1]] ## Check input type temp <- as.numeric(temp) ## Make prediction from fitted model p <- predict(fit, data.frame(Temp = temp)) ## Return predicted value as.numeric(p) }
d901a66e0e119a4d9cd1545770887cfce7defa0f
[ "R" ]
4
R
rdpeng/plumberdemo
8d1ef76238a4c62c29a51a832ead58b769889dc4
c932fbd156d7d7bb663fa421b3cc33abca9599c3
refs/heads/master
<repo_name>huangyangquang/Algorithm<file_sep>/中等/300. 最长上升子序列.js // 300. 最长上升子序列 // 给定一个无序的整数数组,找到其中最长上升子序列的长度。 // 示例: // 输入: [10,9,2,5,3,7,101,18] // 输出: 4 // 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。 function longest(arr) { if(arr === null || arr.length === 0) return var len = arr.length, res = [], max = 0 for(var i = 0; i < len; i ++) { res[i] = 1 for(var j = 0; j < i; j ++) { if(arr[i] > arr[j]) { res[i] = Math.max(res[i], res[j] + 1) } } max = Math.max(max, res[res.length - 1]) } return max } console.log( longest([10,9,2,5,3,7,101,18]) ) console.log( longest([10,9,2,5,3,4]) ) // 基本思路: // [10, 9, 2, 5, 3, 4, 100] // [1, 1, 1, 2, 1, 3, 7] // 但是会发现,100时,就出错了,我们要找的时递增的子序列 // // 所以,如何判断递增才是主要的矛盾。 // 我们会发现,如果在判断时递增时,100,最多比当前正在比较的数多1 // j: 就是当前比较的数据的索引 // i: 就是当前数的索引 // 所以就可以解释为什么是: Math.max(res[i], res[j] + 1) // 2020.11.04 function longest1(arr) { if(arr === null || arr.length === 0) return 0 var len = arr.length, res = [], max = 0 for(var i = 0; i < len; i ++) { res[i] = 1 for(var j = 0; j < i; j ++) { if(arr[j] < arr[i]) { res[i] = Math.max(res[i], res[j] + 1) } } max = Math.max(max, res[i]) } return max; } console.log( longest1([10,9,2,5,3,7,101,18]) ) console.log( longest1([10,9,2,5,3,4]) ) <file_sep>/twoSum.js // 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 // 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 // 示例: // 给定 nums = [2, 7, 11, 15], target = 9 // 因为 nums[0] + nums[1] = 2 + 7 = 9 // 所以返回 [0, 1] // 暴力解法: function twoSum(arr, target) { if(arr == null || arr.length == 0 || target == null) return; var temp = []; var len = arr.length; for(var i = 0; i < len; i ++) { for(var j = i + 1; j < len; j ++) { if(arr[i] + arr[j] == target) { if(temp.indexOf(i) == -1 && temp.indexOf(j)) { temp.push(i); temp.push(j); } } } } return temp; } console.log( twoSum([2, 7, 11, 15], 9) ); // 两遍哈希表: function twoSum1(arr, target) { if(arr == null || arr.length == 0 || target == null) return; var map = new Map(); var len = arr.length; for(var i = 0; i < len; i ++) { map.set(arr[i], i); } for(var j = 0; j < len; j ++) { var temp = target - arr[j]; if(map.has(temp) && map.get(temp) != j) { return [j, map.get(temp)]; } } return []; } console.log( twoSum1([2, 7, 11, 15], 9) ); // 一遍哈希表: function twoSum2(arr, target) { if(arr == null || arr.length == 0 || target == null) return; var map = new Map(); var len = arr.length; for(var i = 0; i < len; i ++) { var temp = target - arr[i]; if(map.has(temp)) { return [map.get(temp), i]; } map.set(arr[i], i); } return []; } console.log( twoSum2([2, 7, 11, 15], 9) )<file_sep>/简单/查找字符串相邻重复项/1047. 删除字符串中的所有相邻重复项.js // 1047. 删除字符串中的所有相邻重复项 // 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。 // 在 S 上反复执行重复项删除操作,直到无法继续删除。 // 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 // 示例: // 输入:"abbaca" // 输出:"ca" // 解释: // 例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。 // 提示: // 1 <= S.length <= 20000 // S 仅由小写英文字母组成。 // 时间复杂度,空间复杂度:O(n) var removeDuplicates = function(S) { var stack = [] for(c of S) { // 遍历字符串的每一个字符 var prev = stack.pop() // 获取栈头元素 if(prev !== c) { // 判断两个字符是否不相同 stack.push(prev) // 入栈 (入栈顺序) stack.push(c) // 入栈(入栈顺序) } } return stack.join('') }; // 正则 var removeDuplicates = function(S) { var reg = /(\w)\1/g; while(S.match(reg) !== null) { S = S.replace(reg, ''); } return S; }; // 总结: // 我原先的思路是遍历一边就删除里面的重复项,但是发现这样得保存删除后字符串得结果。 // 然后重新在遍历一边,得不断地循环遍历,直到没有重复项的时候停止 // 这样就使得我必须: // 1.在删除操作之后得保存字符串结果 // 2.得多次遍历字符串 // 3.得判断字符串中是否还存在重复项(作为多次循环的出口) // 很显然,就第三点就很难实现 // 而使用遍历 + 栈就可以很好解决这些问题,遍历还是正常去遍历字符串,但是操作围绕栈来控制。 // 操作包括: // 保存元素 // 删除元素 // 获取栈头元素和最新元素比较<file_sep>/数组比较-查找/最长公共前缀(腾讯一面).js // 14. 最长公共前缀 // 编写一个函数来查找字符串数组中的最长公共前缀。 // 如果不存在公共前缀,返回空字符串 ""。 // 示例 1: // 输入: ["flower","flow","flight"] // 输出: "fl" // 示例 2: // 输入: ["dog","racecar","car"] // 输出: "" // 解释: 输入不存在公共前缀。 // 说明: // 所有输入只包含小写字母 a-z 。 // 参数: 数组 // 元素: 字符串 // 默认以第一个字符串为标准,遍历这个字符串的长度,获取字符 // 方法二: function longestCommonPrefix(arr) { if(arr == null || arr.length == 0) return ""; var prefix = arr[0]; for(var i = 1; i < arr.length; i ++) { while(arr[i].indexOf(prefix) !== 0) { prefix = prefix.substring(0, prefix.length - 1); if(prefix == "") return ""; } } return prefix; } // 方法一: // function longestCommonPrefix(arr) { // if(arr == null || arr.length == 0) return ''; // var template = arr[0]; // var index = -1; // for(var i = 0; i < template.length; i ++) { // var sub = template.substring(0, i + 1); // var has = arr.every(function(ele, index, self) { // return ele.indexOf(sub) == 0; // }) // console.log(has, sub, i); // if(has) index = i; // } // return index == -1 ? '' : template.substring(0, index + 1); // } var commonPrefix = longestCommonPrefix(["c","ccc"]); console.log(commonPrefix);<file_sep>/简单/53. 最大子序和(20200802).js // 53. 最大子序和 // 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 // 示例: // 输入: [-2,1,-3,4,-1,2,1,-5,4] // 输出: 6 // 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 // 方法一: 正数增益 // 因为找最大和的连续子数组, 所以负数无增益效果,所以,直接赋值即可。 // 但是正数有增益的效果,所以得进行累加。 // // 时间复杂度:O(n),其中 nn 为 nums 数组的长度。我们只需要遍历一遍数组即可求得答案。 // 空间复杂度:O(1),我们只需要常数空间存放若干变量。 /** * @param {number[]} nums * @return {number} */ var arr = [-2,1,-3,4,-1,2,1,-5,4]; var maxSubArray = function(nums) { let ans = nums[0]; // 结果初始化 let sum = 0; // 初始化是无增益结果的 for(const num of nums) { // 为什么是 sum > 0 呢? // 如果 sum > 0,则说明 sum 对结果有增益效果,则 sum 保留并加上当前遍历数字 // 如果 sum <= 0,则说明 sum 对结果无增益效果,需要舍弃,则 sum 直接更新为当前遍历数字 // 所以,这个解法是以当前遍历的项为最大值,判断sum对当前的项有没有增益效果。 // 所以,主体是当前遍历的项,sum是用来产生增益效果 if(sum > 0) { // sum 有增益效果 sum += num; } else { // 无增益效果 sum = num; } ans = Math.max(ans, sum); // 每一次循环都进行结果的比较,避免出现当前项是负数,而又增益效果的出现,导致这次产生的结果变小 } return ans; }; console.log( maxSubArray(arr) ); // 分治法: 暂时不了解 // 2020.10.16 function findMax(arr) { if(arr === null || arr.length == 0) return; var max = 0, res = arr[0], len = arr.length; for(var i = 1; i < len; i ++) { if(max > 0) { max = max + arr[i] } else { max = arr[i] } res = Math.max(max, res); } return res; } console.log( findMax([-2,1,-3,4,-1,2,1,-5,4]) ); <file_sep>/中等/LCP 19. 秋叶收藏集(不理解).js // LCP 19. 秋叶收藏集 // 小扣出去秋游,途中收集了一些红叶和黄叶,他利用这些叶子初步整理了一份秋叶收藏集 leaves, // 字符串 leaves 仅包含小写字符 r 和 y, 其中字符 r 表示一片红叶,字符 y 表示一片黄叶。 // 出于美观整齐的考虑,小扣想要将收藏集中树叶的排列调整成「红、黄、红」三部分。每部分树叶 // 数量可以不相等,但均需大于等于 1。每次调整操作,小扣可以将一片红叶替换成黄叶或者将一片 // 黄叶替换成红叶。请问小扣最少需要多少次调整操作才能将秋叶收藏集调整完毕。 // 示例 1: // 输入:leaves = "rrryyyrryyyrr" // 输出:2 // 解释:调整两次,将中间的两片红叶替换成黄叶,得到 "rrryyyyyyyyrr" // 示例 2: // 输入:leaves = "ryr" // 输出:0 // 解释:已符合要求,不需要额外操作 // 思路: // 1.动态规划 // 2.使用 3 个 dp 数组记录状态 // dp[0][i] 代表从头开始全部修改成红色(纯红)需要修改几次 // dp[1][i] 代表从头开始是红色,然后现在是黄色(红黄),需要修改几次 // dp[2][i] 代表从头开始是红色,然后变成黄色,又变成红色(红黄红),需要修改几次 // 3.根据 i 是红是黄,判断转移情况 // dp[0][i] 就很简单,如果是黄的,就比之前加一 // dp[1][i] 可以从上一个纯红状态变化过来,也可以从上一个本身状态变化过来 // dp[2][i] 可以从上一个红黄状态变化过来,也可以从上一个本身状态变化过来 // 4.所以最后要求的答案即:dp[2].back() var minimumOperations = function (leaves) { var len = leaves.length; // 初始状态不可能为 2, 3,设置为 Infinity var dp = [leaves[0] === 'r' ? 0 : 1, Infinity, Infinity]; for (var i = 1; i < len; i++) { var isRed = (leaves[i] === 'r'); dp = [ dp[0] + (isRed ? 0 : 1), Math.min(dp[0], dp[1]) + (isRed ? 1 : 0), Math.min(dp[1], dp[2]) + (isRed ? 0 : 1), ]; } return dp[2]; }; <file_sep>/树/简单/606. 根据二叉树创建字符串.js // 606. 根据二叉树创建字符串 // 你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。 // 空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。 // 示例 1: // 输入: 二叉树: [1,2,3,4] // 1 // / \ // 2 3 // / // 4 // 输出: "1(2(4))(3)" // 解释: 原本将是“1(2(4)())(3())”, // 在你省略所有不必要的空括号对之后, // 它将是“1(2(4))(3)”。 // 示例 2: // 输入: 二叉树: [1,2,3,null,4] // 1 // / \ // 2 3 // \ // 4 // 输出: "1(2()(4))(3)" // 解释: 和第一个示例相似, // 除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。 const Node = require('./node.js') const node1 = new Node(1) const node2 = new Node(2) const node3 = new Node(3) const node4 = new Node(4) node1.left = node2 node1.right = node3 node2.left = node4 // node2.right = node4 // 递归: // 复杂度分析: // 时间复杂度:O(N),其中 NN 是二叉树中的节点数目。 // 空间复杂度:O(N),在最坏情况下,会递归 N 层,需要 O(N) 的栈空间。 const tree2str = function(root) { if(root === null) { return '' } if(root.left === null && root.right === null) { return root.val + '' } else if (root.right == null) { return root.val + '(' + tree2str(root.left) + ')' } else { return root.val + '(' + tree2str(root.left) + ')(' + tree2str(root.right) + ')' } }; console.log( tree2str(node1) ) // 递归 前序遍历 function ergodicTree (root) { if (root === null) { return '' } if (root.left === null && root.right === null) { return root.val + "" }else if (root.right === null) { return root.val + "" + ergodicTree(root.left) } else { return root.val + "" + ergodicTree(root.left) + "" + ergodicTree(root.right) } } console.log( ergodicTree(node1) )<file_sep>/动态规划/最长回文子串.js // 5. 最长回文子串 // 给你一个字符串 s,找到 s 中最长的回文子串。 // 示例 1: // 输入:s = "babad" // 输出:"bab" // 解释:"aba" 同样是符合题意的答案。 // 示例 2: // 输入:s = "cbbd" // 输出:"bb" // 示例 3: // 输入:s = "a" // 输出:"a" // 示例 4: // 输入:s = "ac" // 输出:"a" // 动态规划: /** * @param {string} s * @return {string} */ // 时间复杂度是 O(n^2) var longestPalindrome1 = function (s) { if (s === null) return ''; var len = s.length; var mLen = 1 // 存储最长回文子串的长度 var begin = 0 // 存储最长回文子串的起始点 var tempArr = new Array(len) // 初始化二位数组 for (var i = 0; i < len; i ++) { tempArr[i] = new Array(len) } for (var j = 0; j < len; j ++) { for (var i = 0; i <= j; i ++) { if (s[j] !== s[i]) { tempArr[i][j] = false } else { if (j - i < 2) { // 当两个值是相邻 或者是 同一个值时 tempArr[i][j] = true } else { // 或者 如果目前的子串成立,必须时这个子串里边的子串也处理,比如:'abbba'是子串, 那么'bbb' 也必须是子串;'bbb'是子串, 'b'也必须是子串 tempArr[i][j] = tempArr[i + 1][j - 1] } if (tempArr[i][j] === true && j - i + 1 >= mLen) { // 更新 最长回文子串的起始点 和 长度 mLen = j - i + 1 begin = i } } } } return s.slice(begin, begin + mLen) }; console.log(longestPalindrome1("babaaaaabd")); console.log(longestPalindrome1("cbbd")); console.log(longestPalindrome1("q")); console.log(longestPalindrome1("ac")); console.log(longestPalindrome1("acdd")); console.log(longestPalindrome1("acdddc")); console.log(longestPalindrome1("abbajjjjjjooopoooppppoooppooo")); <file_sep>/baidu_school2.js <table id="jsLayout"> <tbody> <tr><td class="current"></td><td class="wrap"></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <tr><td class="wrap"></td><td class="wrap"></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> </tbody> </table> body, html { margin: 0; } table { border-collapse: collapse; table-layout: fixed; margin: 10px auto; } td { border: 1px solid #E1E1E1; padding: 0; width: 30px; height: 30px; cursor: pointer; } .current { background: #1D2088; } .wrap { background: #00A0E9; }<file_sep>/levelOrder.js // 102. 二叉树的层序遍历 // 给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 // (即逐层地,从左到右访问所有节点)。 // 示例: // 二叉树:[3,9,20,null,null,15,7], // 3 // / \ // 9 20 // / \ // 15 7 // 返回其层次遍历结果: // [ // [3], // [9,20], // [15,7] // ] // 递归 function levelOrder(root) { if(root == null) return []; function _helper(node, level) { if(levels.length == level) levels.push([]); levels[level].push(node.val); if (node.left != null) _helper(node.left, level + 1); if (node.right != null) _helper(node.right, level + 1); } var levels = []; _helper(root, 0); return levels; } function levelOrder(root) { if(root == null) return []; var arr = []; var _helper = function(node, nowlevel) { if(arr.length == nowlevel) arr.push([]); arr[nowlevel].push(node.val); // 出口 node.left && _helper(node.left, nowlevel + 1); node.right && _helper(node.right, nowlevel + 1); } _helper(root, 0); return arr; } // 迭代 function levelOrder(root) { if(root == null) return []; var arr = []; var queue = [root]; while(queue.length > 0) { var tempArr = []; var tempQ = []; for(var node of queue) { tempArr.push(node.val); if(node.left) { tempQ.push(node.left); } if(node.right) { tempQ.push(node.right); } } queue = tempQ; arr.push(tempArr); } return arr; }<file_sep>/merge.js // 88. 合并两个有序数组 // 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。 // 说明: // 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。 // 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 // 示例: // 输入: // nums1 = [1,2,3,0,0,0], m = 3 // nums2 = [2,5,6], n = 3 // 输出: [1,2,2,3,5,6] // 1.合并后排序 function merge(arr1, m, arr2, n) { if(arr1 == null || m == null || arr2 == null || n == null) return; if(arr1.length == 0 && arr2.length != 0) return arr2; if(arr1.length != 0 && arr2.length == 0) return arr1; // 1.1 // var i = 0; // arr1.forEach(function(ele, index, self) { // if(ele == 0 && i < n) { // self[index] = arr2[i]; // i ++; // } // }); // return arr1.sort(function(a, b) { // return a - b; // }); // 1.2 var newArr = arr1.slice(0, m).concat(arr2); return newArr.sort(function(a, b) { return a - b; }) } // console.log( merge([-10,1,2,0,3,0,0,0], 5, [2, 5, 6], 3) ); // 2.双指针 / 从前往后 function merge1(arr1, m, arr2, n) { if(arr1 == null || m == null || arr2 == null || n == null) return; var smallArr1 = arr1.slice(0, m); var p1 = 0; var p2 = 0; var sP = 0; while( (p2 < n) && (sP < m) ) { if(arr2[p2] > smallArr1[sP]) { arr1[p1 ++] = smallArr1[sP]; sP ++; } else { arr1[p1 ++] = arr2[p2]; p2 ++; } } if(p2 < n) { var tempArr = arr2.slice(p2); arr1.splice(m + n - p2 - 1, p2 + 1); } if(sP < m) { var tempArr = smallArr1.slice(sP) arr1.splice(m + n - sP - 1, sP + 1); } return arr1.concat(tempArr); } console.log( merge1([1,2,3,0,0,0], 3, [2, 5, 6], 3) ); console.log( merge1([0], 0, [2], 1) ); // 3.双指针 / 从后往前 function merge2(arr1, m, arr2, n) { if(arr1 == null || m == null || arr2 == null || n == null) return; var len = m + n - 1; var p1 = m - 1; var p2 = n - 1; while(p1 >= -1 && p2 >= 0) { if(arr1[p1] > arr2[p2]) { arr1[len --] = arr1[p1]; p1 --; } else { arr1[len --] = arr2[p2]; p2 --; } } return arr1; } <file_sep>/简单/561. 数组拆分 I.js // 561. 数组拆分 I // 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) , // 使得从1 到 n 的 min(ai, bi) 总和最大。 // 示例 1: // 输入: [1,4,3,2] // 输出: 4 // 解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4). // 2020.10.11 function arrayPairSum(arr) { if(arr === null || arr.length % 2 !== 0) return; var rightArr = arr.sort((a, b) => (a - b)).filter(function(ele, index) { if(index % 2 === 0) { return true; } }); var sum = rightArr.reduce(function(a, b) { return a + b; }); return sum; } console.log( arrayPairSum([1,4,3,2]) ) <file_sep>/数组比较-查找/1365. 有多少小于当前数字的数字.js // 1365. 有多少小于当前数字的数字 // 给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。 // 换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。 // 以数组形式返回答案。 // 示例 1: // 输入:nums = [8,1,2,2,3] // 输出:[4,0,1,1,3] // 解释: // 对于 nums[0]=8 存在四个比它小的数字:(1,2,2 和 3)。 // 对于 nums[1]=1 不存在比它小的数字。 // 对于 nums[2]=2 存在一个比它小的数字:(1)。 // 对于 nums[3]=2 存在一个比它小的数字:(1)。 // 对于 nums[4]=3 存在三个比它小的数字:(1,2 和 2)。 // 示例 2: // 输入:nums = [6,5,4,8] // 输出:[2,1,0,3] // 示例 3: // 输入:nums = [7,7,7,7] // 输出:[0,0,0,0] function smallSum(nums) { var res = [], len = nums.length, cur = 0 for(var i = 0; i < len; i ++) { cur = 0 for(var j = 0; j < len; j ++) { if(nums[i] > nums[j]) { cur ++ } } res[i] = cur } return res } console.log( smallSum([8,1,2,2,3]) ) console.log( smallSum([6,5,4,8]) ) console.log( smallSum([7,7,7,7]) ) <file_sep>/491. 递增子序列.js // 491. 递增子序列 // 给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。 // 示例: // 输入: [4, 6, 7, 7] // 输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]] // 说明: // 给定数组的长度不会超过15。 // 数组中的整数范围是 [-100,100]。 // 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。 // 去重 + 深度优先搜索(递归) + 节点切换(栈) function findSub(nums) { if(nums === null || nums.length <= 1) return nums; // 严谨性判断 const res = [], set = new Set(), len = nums.length; function dfs(start, path) { if(path.length >= 2) { // 递增子序列的长度至少是2 const str = path.join(','); if(!set.has(str)) { // 判断重复 set.add(str); res.push(path.slice()); // 拷贝副本 } } for(let i = start; i < len; i ++) { const prev = path[path.length - 1]; const cur = nums[i]; if(path.length === 0 || prev <= cur) { // 边缘判断:初始化时 / 递增情况 path.push(cur); // 切入当前节点, 初始化时就是数组的第一个 dfs(i + 1, path); // 深入优先搜索 path.pop(); // 切出当前节点 } } } dfs(0, []); return res; } console.log( findSub([4, 6, 7, 7]) ) <file_sep>/RegExp.js // 正则表达式: // 默认是贪婪匹配:可以匹配多不匹配少 // reg方法: // reg.test(str); // reg.exec(str); // 量词: // 要匹配的表达式的的连续的个数: // X{n} n 个表达式连起来 // X{n,m} n至m 个表达式连起来 // X{n,} n至无穷 个表达式连接起来 // 即:总表达式 = 表达式 + 表达式 + ..... + 表达式 // var str = 'ccccccccccc'; // var reg = /c{3}/g; // console.log(str.match(reg)); // var str = 'ccccccccccc'; // var reg = /c{3,6}/g; // console.log(str.match(reg)); // var str = 'ccccccccccc'; // var reg = /c{3,}/g; // console.log(str.match(reg)); // 简写: // * ==》 X{0,} // + ==》 X{1,} // ? ==》 X{0,1} // var str = 'kkkiikkkkkiiii'; // var reg = /k*/g; // console.log(str.match(reg)); // var str = 'kkkiikkkkkiiii'; // var reg = /k+/g; // console.log(str.match(reg)); // var str = 'kkkiikkkkkiiii'; // var reg = /k?/g; // console.log(str.match(reg)); // 非贪婪匹配: 可以匹配少不匹配多 // 以在表示量词后面加上一个? // var str = 'kkkiikkkkkiiii'; // var reg = /k*?/g; // console.log(str.match(reg)); // var str = 'kkkiikkkkkiiii'; // var reg = /k+?/g; // console.log(str.match(reg)); // var str = 'kkkiikkkkkiiii'; // var reg = /k??/g; //? : 一个表示量词,一个表示非贪婪匹配 // console.log(str.match(reg)); // 在举个例子: // 贪婪匹配: // var str = 'kkkkkkkkkkkk'; // var reg = /k{3,4}/g; // console.log( str.match(reg) ); // // 非贪婪匹配: // var str = 'kkkkkkkkkkkk'; // var reg = /k{3,4}?/g; // console.log( str.match(reg) ); // ^X: 匹配以X开头的表达式 // X$: 匹配以X结尾的表达式 // var str = 'aaaabdfssss'; // var reg = /^a/g; // var reg = /s$/g; // var reg = /^a*?/g; // var reg = /^a?/g; // var reg = /^a{3,}?/g; // var reg = /^a{3,}/g; // console.log( str.match(reg) ); // 元字符: // .: 用于查找单个字符,除了换行和行结束符。 // var str = 'aj\nid a\ri sxh'; // var reg = /./g; // console.log( str.match(reg) ); // var str = 'aj\nid a\ri ssalnjlsns'; // var reg = /.{1,}/g; // console.log( str.match(reg) ); // |: 表示或 (即 表达式1 或者 表达式2 或者 表示式3) // var str = 'sasbbbaaaakl'; // var reg = /^a|b+/g; // console.log( str.match(reg) ); // var str = 'bbsasbbbaaaakl'; // var reg = /^b+|a+/g; // console.log( str.match(reg) ); // var str = 'ccbbsasbbbaaaakl'; // var reg = /b+|a+|^c+?/g; // console.log( str.match(reg) ); // 括号(): 表示一个表达式 // var str = 'asbbbaaaakljabba'; // var reg = /^a.|b./g; // console.log( str.match(reg) ); // var str = 'asbbbaaaaklbaai'; // var reg = /^(a.|b.)/g; // var reg = /(a.|b.)$/g; // console.log( str.match(reg) ); // 大括号[]: 字符集合 // var str = 'asbb567qr38dadjaa_??klj__ab??ba'; // var reg = /a/g; // var reg = /a+/g; // var reg = /[ab]/g; //等同于 var reg = /a|b/g; 就是一个查找的范围 // var reg = /[a-z0-9_]{6}/g; // console.log( str.match(reg) ); //[^]中的^: 表示非 // var str = 'asbBBHJHG38dadjaa_??klj__ab??ba'; // var reg = /^a.{20}|[^a-z0-9_]{2}/g; // console.log( str.match(reg) ); // 边界\b与非边界\B block // 数字\d与非数字\D digit // 空白 \f匹配换页符,\n匹配换行符,\r匹配回车,\t匹配制表符,\v匹配垂直制表符。 // \s匹配单个空格,等同于[\f\n\r\t\v]。 space // 单词字符\w与非单纯字符\W word // 反向引用: // \数字: “\数字”就叫做反向引用,它表示的是第n个括号内的子正则表达式匹配的内容。 // var str = 'aaaasasadklalkkl'; // var reg = /(\w)(\w)\1\2/g; // var reg = /(\w)(\w)\2\1/g; // var reg = /\w\w\2\1/g; //必须要有括号(),表示子表达式 // var reg = /[a]\1/g; //必须要有括号(),表示子表达式 // var reg = /a\1/g; //必须要有括号(),表示子表达式 // // 所以,可以看出,实际上, // // . // // \w \W \d \D \b \B \s // // [] // // a b .... 1 2 3.... // // 都是在同一个层面的东西 // // 使用 () 括起来的 是一个子表达式 // console.log( str.match(reg) ); // 不记录子正则表达式的匹配结果 // 使用形如(?:pattern)的正则就可以避免保存括号内的匹配结果。 // 正向预查: // 正向预查 形式:(?=pattern) 所谓正向预查, // 意思就是:要匹配的字符串,后面必须紧跟着pattern! // ?! // 形式(?!pattern)和?=恰好相反,要求字符串的后面不能紧跟着某个pattern // 匹配元字符* + ? ....: // var str = '**dja**??'; // var reg = /^\*+|\?+/g; // console.log(str.match(reg)); // var str = "(sajk)[asjk]"; // var reg = /^\(\w+\)/g; // console.log(str.match(reg)); // var str = "(sajk])[asjk]"; // var reg = /^\(\w+\]/g; // console.log(str.match(reg)); // var str = ")sajk]op)[asjk]"; // var reg = /\).+\](?=\w)/g; // console.log(str.match(reg)); // var reg = /\)\w+(?=\])/g; // console.log(str.match(reg)); // // var str = ")sajk]op)[asjk]]]"; // . 不是 代表 \w 表示的范围不同 // var reg = /\).+(?=\])/g; // console.log(str.match(reg)); // 正则表达式的修饰符 g i m // 在replace函数中使用$引用子正则表达式匹配内容 // var str = 's0bH2s33s43jjshahuk*'; // var reg = /(\w)(\d)/g; // var newStr = str.replace(reg, '--'); // console.log(newStr); // var newStr = str.replace(reg, '-$1-$2'); // console.log(newStr); // // 由于在替换文本里$有了特殊的含义,所以我们如果想要是用$这个字符的话,需要写成$$, // var newStr = str.replace(reg, '$$'); // console.log(newStr); <file_sep>/baidu_school1.js // 用js实现一个用户行收集器,功能如下: // 1,收集用户在页面中的所有click行为,并使用log方法发送日志,包含触发事件的节点xpath信息 // 2,xpath需包含tagName、id、class、同级同名节点索引(从1开始),如 // <body> // <div id=“container”> // <p>something</p> // <a id=“link1” class=“link-class”></a> // <a id=“link2” class=“link-class current”>target link</a> // </div> // </body> // 点击target link时,xpath为 // body[1]/ // div[1][@id=“container”]/ // a[2][@id=“link2”][contains(@class, “link-class")][contains(@class, “current")] // 3,不侵入、不影响其他业务代码的执行 var obody = document.getElementsByTagName('body')[0]; obody.addEventListener('click', function(e) { console.log(getXPath(e.target)); }, false); // 获取它的 上级节点至根节点body // 每一个节点都得获取: // 获取它的ID // 获取它的class // 获取它在同级同名节点中排老几 function getXPath(target) { if(target.localName == 'body') return 'body[1]'; var index = 1; var tempTarget = target; var str = ''; var localName = target.localName; var id = target.id; var classList = target.classList; while(tempTarget.previousElementSibling != null && tempTarget.previousElementSibling.localName == localName) { index ++; tempTarget = tempTarget.previousElementSibling; } str = '/' + localName + '[' + index + '][@id="' + id + '"]'; classList.forEach(function(ele, index, self) { str += '[contains(@class,"' + ele + '")]'; }) return getXPath(target.parentNode) + str; } <file_sep>/reverse.js // 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 // 示例 1: // 输入: 123 // 输出: 321 //  示例 2: // 输入: -123 // 输出: -321 // 示例 3: // 输入: 120 // 输出: 21 // 注意: // 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31,  2^31 − 1]。 // 请根据这个假设,如果反转后整数溢出那么就返回 0。 function zeng(x) { return x > 0 ? Math.floor(x / 10) : Math.ceil(x / 10); } function reverse(x) { var max_value = Math.pow(2, 31) - 1; var min_value = -Math.pow(2, 31); var zMax = zeng(max_value); var zMin = zeng(min_value); var rev = 0; while(x != 0) { var pop = x % 10; x = zeng(x); if (rev > zMax || (rev == zMax && pop > 7)) return 0; if (rev < zMin || (rev == zMin && pop < -8)) return 0; rev = rev * 10 + pop; } return rev; } console.log( reverse(-2147483412) ); console.log( reverse(-213) ); console.log( reverse(83412) ); console.log( reverse(1563847412) ); console.log( reverse(-1563847412) ); <file_sep>/简单/1. 两数之和.js // 1. 两数之和 // 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数, // 并返回他们的数组下标。 // 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 // 示例: // 给定 nums = [2, 7, 11, 15], target = 9 // 因为 nums[0] + nums[1] = 2 + 7 = 9 // 所以返回 [0, 1] var twoSum = function(nums, target) { if(nums === null || target === null) return []; var len = nums.length; for(var i = 0; i < len - 1; i ++) { for(var j = i + 1; j < len; j ++) { if(nums[i] + nums[j] === target) { return [i, j]; } } } }; console.log( twoSum([2, 7, 11, 15], 9) ); var _twoSum = function(nums, target) { if(nums === null || target === null) return []; var own = {}, // hash表 len = nums.length; for(var i = 0; i < len; i ++) { if(own[target - nums[i]] !== undefined) { return [own[target - nums[i]], i]; // 添加hash表上的值 } else { own[nums[i]] = i; } } } console.log( _twoSum([2, 7, 11, 15], 9) ); <file_sep>/中等/15. 三数之和.js // 15. 三数之和 // 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c , // 使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。 // 注意:答案中不可以包含重复的三元组。 // 示例: // 给定数组 nums = [-1, 0, 1, 2, -1, -4], // 满足要求的三元组集合为: // [ // [-1, 0, 1], // [-1, -1, 2] // ] // 排序 + 双指针 + 双层循环 var threeSum = function(nums) { if(nums === null || nums.length < 3) return []; var res = [], len = nums.length; nums.sort((a, b) => (a - b)); // 排序,数组是递增的,以 数字0 为一个特殊的节点 for(var i = 0; i < len; i ++) { // 循环,确定起点 if(nums[i] > 0) break; if(i > 0 && nums[i] === nums[i - 1]) continue; // 去重 var L = i + 1, // 左指针 R = len - 1; // 右指针 while(L < R) { var sum = nums[i] + nums[L] + nums[R]; // 求和 if(sum === 0) { // 和为零 res.push([nums[i], nums[L], nums[R]]); // 保存结果 while(L < R && nums[L] == nums[L + 1]) L ++; // 去重 while(L < R && nums[R] == nums[R - 1]) R --; // 去重 L ++; R --; } else if(sum < 0) { L ++ } else if(sum > 0) { R --; } } } return res; }; console.log( threeSum([-1, 0, 1, 2, -1, -4]) ); // 2020.10.10 (默写,全对) var _threeSum = function(arr) { if(arr === null || arr.length < 3) return []; arr.sort((a, b) => (a - b)); var len = arr.length, res = []; for(var i = 0; i < len; i ++) { if(arr[i] > 0) break; if(i > 0 && arr[i] === arr[i - 1]) continue; var l = i + 1, r = len - 1; while(l < r) { var sum = arr[i] + arr[l] + arr[r]; if(sum === 0) { res.push([arr[i], arr[l], arr[r]]); while(l < r && arr[l] === arr[l + 1]) l ++; while(l < r && arr[r] === arr[r - 1]) r --; l ++; r --; } else if(sum < 0) { l ++; } else if(sum > 0) { r --; } } } return res; } console.log( _threeSum([-1, 0, 1, 2, -1, -4]) ); console.log( _threeSum([-1, 0, 2, 2, -1, -4]) ); <file_sep>/isPalindrom.js // 9. 回文数 // 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 // 示例 1: // 输入: 121 // 输出: true // 示例 2: // 输入: -121 // 输出: false // 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 // 示例 3: // 输入: 10 // 输出: false // 解释: 从右向左读, 为 01 。因此它不是一个回文数。 // 进阶: // 你能不将整数转为字符串来解决这个问题吗? // 使用字符串则会创建空间 function isPalindrome0(x) { if(x == null) return false; if(x < 0) return false; if(x % 10 == 0 && x != 0) return false; x = x + ''; var reserveX = x.split("").reverse().join(''); return x == reserveX; } console.log( isPalindrome0(123) ); console.log( isPalindrome0(121) ); // 反转全部的数: function isPalindrome(x) { if(x == null) return false; if(x < 0) return false; if(x % 10 == 0 && x != 0) return false; var rev = 0; var temp = x; while(x != 0) { var pop = x % 10; x = Math.floor(x / 10); rev = rev * 10 + pop; } return rev === temp; }//有溢出的风险(js有溢出吗?) // console.log( isPalindrome(123) ); // console.log( isPalindrome(-123) ); // console.log( isPalindrome(121) ); // console.log( isPalindrome(101) ); // 反转一半的数: function isPalindrome1(x) { if(x == null) return false; if(x < 0) return false; // 如果数字的最后一位是 0,为了使该数字为回文 if(x % 10 == 0 && x != 0) return false; var rev = 0; while(x > rev) { var pop = x % 10; rev = rev * 10 + pop; x = Math.floor(x / 10); } return x == rev || x == Math.floor(rev / 10); // 1221 0 // 122 1 // 12 12 // 121 0 // 12 1 // 1 12 } // console.log( isPalindrome1(123) ); // console.log( isPalindrome1(-123) ); // console.log( isPalindrome1(1221) ); // console.log( isPalindrome1(101) ); function isPalindrome2(x) { if(x == null) return false; if(x < 0) return false; // 如果数字的最后一位是 0,为了使该数字为回文 if(x % 10 == 0 && x != 0) return false; var rev = 0; while(x > rev) { var pop = x % 10; rev = rev * 10 + pop; x = ~~(x / 10); } return x == rev || x == ~~(rev / 10); } // console.log( isPalindrome2(123) ); // console.log( isPalindrome2(-123) ); // console.log( isPalindrome2(1221) ); // console.log( isPalindrome2(101) ); var num = 12546; // pop操作: var pop = num % 10; num = ~~ (num / 10); // console.log(num); // 1254 // push操作: num = num * 10 + pop; // console.log(num); // 12546<file_sep>/中等/456. 132模式(不理解).js // 456. 132模式 // 给定一个整数序列:a1, a2, ..., an,一个132模式的子序列 ai, aj, ak // 被定义为:当 i < j < k 时,ai < ak < aj。设计一个算法,当给定有 n // 个数字的序列时,验证这个序列中是否含有132模式的子序列。 // 注意:n 的值小于15000。 // 示例1: // 输入: [1, 2, 3, 4] // 输出: False // 解释: 序列中不存在132模式的子序列。 // 示例 2: // 输入: [3, 1, 4, 2] // 输出: True // 解释: 序列中有 1 个132模式的子序列: [1, 4, 2]. // 示例 3: // 输入: [-1, 3, 2, 0] // 输出: True // 解释: 序列中有 3 个132模式的的子序列: [-1, 3, 2], [-1, 3, 0] 和 [-1, 2, 0]. var find132pattern = function(nums) { if(nums === null || nums.length < 3) return false; }; console.log( find132pattern([-1, 3, 2, 0]) ); console.log( find132pattern([3,5,0,3,4]) ); <file_sep>/290. 单词规律.js // 290. 单词规律 // 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 // 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。 // 示例1: // 输入: pattern = "abba", str = "dog cat cat dog" // 输出: true // 示例 2: // 输入:pattern = "abba", str = "dog cat cat fish" // 输出: false // 示例 3: // 输入: pattern = "aaaa", str = "dog cat cat dog" // 输出: false // 示例 4: // 输入: pattern = "abba", str = "dog dog dog dog" // 输出: false // 说明: // 你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。 // indexOf 下标索引 const wordPattern1 = function(pattern, str) { if(pattern == null || str == null) return false; const strArr = str.split(" "), patternLen = pattern.length, strLen = strArr.length; if(patternLen !== strLen) return false; for(let i = 0; i < patternLen; i ++) { if(strArr.indexOf(strArr[i]) !== pattern.indexOf(pattern[i])) { return false; } } return true; } console.log( wordPattern1("abba", "dog c d dog") ); // Map映射 const wordPattern2 = function(pattern, str) { if(pattern == null || str == null) return; const strArr = str.split(' '), len = strArr.length, strMap = new Map(), patternMap = new Map(); if(len !== pattern.length) return false; for(let i = 0; i < len; i ++) { if(strMap.has(strArr[i])) { if(strMap.get(strArr[i]) !== pattern[i]) { return false; } } else { strMap.set(strArr[i], pattern[i]); } if(patternMap.has(pattern[i])) { if(patternMap.get(pattern[i]) !== strArr[i]) { return false; } } else { patternMap.set(pattern[i], strArr[i]); } } return true; } console.log( wordPattern2("abbac", "dog d d dog") )<file_sep>/canCompleteCircuit.js // 134. 加油站 // 在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。 // 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。 // 你从其中的一个加油站出发,开始时油箱为空。 // 如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。 // 说明: // 如果题目有解,该答案即为唯一答案。 // 输入数组均为非空数组,且长度相同。 // 输入数组中的元素均为非负数。 // 示例 1: // 输入: // gas = [1,2,3,4,5] // cost = [3,4,5,1,2] // 输出: 3 // 解释: // 从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油 // 开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油 // 开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油 // 开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油 // 开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油 // 开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。 // 因此,3 可为起始索引。 // 示例 2: // 输入: // gas = [2,3,4] // cost = [3,4,3] // 输出: -1 // 解释: // 你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。 // 我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油 // 开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油 // 开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油 // 你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。 // 因此,无论怎样,你都不可能绕环路行驶一周。 function canCompleteCircuit(gas, cost) { var len = gas.length; var total_tank = 0; var cur_tank = 0; var nowStation = 0; // 默认从索引为0的位置开始 for(var i = 0; i < len; i ++) { total_tank += gas[i] - cost[i]; cur_tank += gas[i] - cost[i]; if(cur_tank < 0) { nowStation = i + 1; cur_tank = 0; } } return total_tank >= 0 ? nowStation : -1; } var nowStation = canCompleteCircuit([1,2,3,4,5], [3,4,5,1,2]) console.log(nowStation); // 环路一圈 // 拥有的总有数 和 需要花费的总油数的比较 // 如果 >, 肯定可以环路一圈;这个时候只是需要找出从那个点开始就可以了 // 如果 <, 就肯定不可以,直接返回 -1 // 那么怎么确定这个开始的点呢? // 可以通过当前剩下的油量来判断 // 如果 >, 表示以这个点为起点的基础上还是可以继续走 // 如果 <, 表示以这个点为起点的基础上不可以继续走 <file_sep>/动态规划/62. 不同路径.js // 62. 不同路径 // 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 // 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 // 问总共有多少条不同的路径? // 示例 1: // 输入: m = 3, n = 2 // 输出: 3 // 解释: // 从左上角开始,总共有 3 条路径可以到达右下角。 // 1. 向右 -> 向右 -> 向下 // 2. 向右 -> 向下 -> 向右 // 3. 向下 -> 向右 -> 向右 // 示例 2: // 输入: m = 7, n = 3 // 输出: 28 // 动态规划: // 时间复杂度: O(n * m). dp[i][j] = dp[i][j - 1] + dp[i - 1][j]; 运行了 ( n - 1 ) * ( m - 1 ) 次. // 空间复杂度: O(n * m). 二维数组 dp 包含 n 个一维数组, 每个一维数组里有 m 个元素. function path(m, n) { var res = [] for(var i = 0; i < n; i ++) { res[i] = [] res[i][0] = 1 } for(var j = 0; j < m; j ++) { res[0][j] = 1 } for(var i = 1; i < n; i ++) { for(var j = 1; j < m; j ++) { res[i][j] = res[i - 1][j] + res[i][j - 1] } } return res[n - 1][m - 1] } console.log(path(3, 2)) console.log(path(7, 3)) // 2020.11.13 function path1(m, n) { var res = [] for(var i = 0; i < n; i ++) { res[i] = [] res[i][0] = 1 } for(var j = 0; j < m; j ++) { res[0][j] = 1 } for(var i = 1; i < n; i ++) { for(var j = 1; j < m; j ++) { res[i][j] = res[i - 1][j] + res[i][j - 1] } } return res[n - 1][m - 1]; } // console.log(path1(3, 2)) // console.log(path1(7, 3)) // 2020.11.13(默写) function path2(m, n) { var res = [] for(var i = 0; i < n; i ++) { res[i] = [] res[i][0] = 1 } for(var j = 0; j < m; j ++) { res[0][j] = 1 } for(var i = 1; i < n; i ++) { for(var j = 1; j < m; j ++) { res[i][j] = res[i - 1][j] + res[i][j - 1] } } return res[n - 1][m - 1] } // console.log(path2(3, 2)) // console.log(path2(7, 3))<file_sep>/百度19校招.js // [编程题]探险安排 // 小明要为n个人计划一次火星的探险,其中一个重要的任务是为每个参与者安排食物。 // 仓库里面有m个能用一天的食物包裹,每个食物包裹有不同的类型ai。 // 每个人每天必须用且只能用一个食物包裹。由于某些原因,在整个过程中, // 每个人只能用同一种类型的食物包裹,但是不同的人用的食物包裹可以不一样。 // 给出人数以及食物包裹的情况,请你求出这趟探险最多可以持续多少天。 // 输入描述: // 第一行两个整数,n和m,表示人数和食物包裹的个数。 // 第二行m个整数,表示每个食物包裹的类型。 // 满足1 <= n <= 100,1 <= m <= 100,1 <= ai <= 100。 // 输出描述: // 一个整数,表示最多持续的天数;如果一天都无法持续,输出0。 // 输入例子1: // 4 10 4个人 10个包裹 // 1 5 2 1 1 1 2 5 7 2 食物包裹的类型 4个1、 3个2、 2个5、 1个7 // 输出例子1: // 2 最多持续的天数(1,1,2,5) function traval(n, m, typeArr) { if(n == null || n == 0 || m == null || m == 0 || typeArr == null || typeArr.length == 0) return 0; var days = new Map(); for(var i = 0; i < typeArr.length; i ++) { if(days.get(typeArr[i]) == null) { days.set(typeArr[i], 1); } else { days.set(typeArr[i], days.get(typeArr[i]) + 1); } } var typeNum = Math.floor(m / n); var baseNum = m % n; var count = 0; for(var value of days) { console.log(value[1]); if(value[1] >= baseNum) count ++; } } traval(4, 10, [1, 5, 2, 1, 1, 1, 2, 5, 7, 2]);<file_sep>/38. 外观数列.js // 38. 外观数列 // 给定一个正整数 n(1 ≤ n ≤ 30),输出外观数列的第 n 项。 // 注意:整数序列中的每一项将表示为一个字符串。 // 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。前五项如下: // 1. 1 // 2. 11 // 3. 21 // 4. 1211 // 5. 111221 // 第一项是数字 1 // 描述前一项,这个数是 1 即 “一个 1 ”,记作 11 // 描述前一项,这个数是 11 即 “两个 1 ” ,记作 21 // 描述前一项,这个数是 21 即 “一个 2 一个 1 ” ,记作 1211 // 描述前一项,这个数是 1211 即 “一个 1 一个 2 两个 1 ” ,记作 111221 // 示例 1: // 输入: 1 // 输出: "1" // 解释:这是一个基本样例。 // 示例 2: // 输入: 4 // 输出: "1211" // 解释:当 n = 3 时,序列是 "21",其中我们有 "2" 和 "1" 两组,"2" 可以读作 "12",也就是出现频次 = 1 而 值 = 2;类似 "1" 可以读作 "11"。所以答案是 "12" 和 "11" 组合在一起,也就是 "1211"。 /** * @param {number} n * @return {string} */ var countAndSay = function(n) { let prev = '1'; for(let i = 1; i < n; i ++) { prev = prev.replace(/(\d)\1*/g, item => `${item.length}${item[0]}`); // \1 是反向引用 } return prev; }; console.log( countAndSay(1) ) console.log( countAndSay(2) ) console.log( countAndSay(3) ) console.log( countAndSay(4) ) console.log( countAndSay(5) )<file_sep>/简单/455. 分发饼干.js // 455. 分发饼干 // 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 // 对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。 // 如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子, // 并输出这个最大数值。 // 注意: // 你可以假设胃口值为正。 // 一个小朋友最多只能拥有一块饼干。 // 示例 1: // 输入: [1,2,3], [1,1] // 输出: 1 // 解释: // 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。 // 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。 // 所以你应该输出1。 // 示例 2: // 输入: [1,2], [1,2,3] // 输出: 2 // 解释: // 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 // 你拥有的饼干数量和尺寸都足以让所有孩子满足。 // 所以你应该输出2. // 2021.05.06 (新思路) // 排序 + 贪心算法: // 《算法导论》: // 贪心算法(greedy algorithm)就是这样的算法,它在每一步都做出当时看起来最佳的选择。 // 也就是说,它总是做出局部最优的选择,寄希望这样的选择能导致全局最优解。 function cookieNew (kids, cookies) { if(kids === null || cookies === null) return kids.sort((a, b) => { return a - b }) cookies.sort((a, b) => { return a - b }) let num = 0 cookies.forEach(cookie => { if(cookie >= kids[num]) { num ++ } }) return num } console.log( cookieNew([1,2,3], [1,1]) ) console.log( cookieNew([1,2], [1,2,3]) ) // 2021.05.06 function cookie(kids, cookies) { if(kids === null || cookies === null) return kids.sort((a, b) => { return a - b }) cookies.sort((a, b) => { return a - b }) let sum = 0 let k = 0 let c = 0 while(k <= kids.length && c <= cookies.length) { if(kids[k] <= cookies[c]) { sum ++ c ++ k ++ } else { c ++ } } return sum } console.log( cookie([1,2,3], [1,1]) ) console.log( cookie([1,2], [1,2,3]) ) // 第一版 function findContentChildren(kids, cookies) { if(kids === null || cookies === null) return; kids.sort((a, b) => (a - b)); cookies.sort((a, b) => (a - b)); var sum = 0, k = 0, c = 0; while(k <= kids.length && c <= cookies.length) { if(kids[k] <= cookies[c]) { sum ++; k ++; c ++; } else { c ++; } } return sum; } console.log( findContentChildren([1,2,3], [1,1]) ) console.log( findContentChildren([1,2], [1,2,3]) ) // 2020.10.28 function find(kids, cookies) { kids.sort((a, b) => (a - b)) cookies.sort((a, b) => (a - b)) var k = 0, c = 0, sum = 0; while(k <= kids.length && c <= cookies.length) { if(cookies[c] >= kids[k]) { c ++ k ++ sum ++ } else { c ++ } } return sum; } console.log( find([1,2,3], [1,1]) ) console.log( find([1,2], [1,2,3]) ) <file_sep>/验证回文串.js // 125. 验证回文串 // 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 // 说明:本题中,我们将空字符串定义为有效的回文串。 // 示例 1: // 输入: "A man, a plan, a canal: Panama" // 输出: true // 示例 2: // 输入: "race a car" // 输出: false function isPalindrome(str) { if(str == null) return false; let = flag = true; const reg = /[a-zA-Z0-9]{1}/g; const wordArr = str.match(reg); if(!wordArr) return true; const len = wordArr.length; const left = wordArr.slice(0, Math.floor(len / 2)); const right = wordArr.slice(Math.ceil(len / 2), len).reverse(); left.forEach((ele, index, self) => { if(ele.toUpperCase() !== right[index].toUpperCase()) { flag = false; } }) return flag; } // console.log( isPalindrome(".,") ); // console.log( isPalindrome("A man, a plan, a canal: Panama") ); function isPalindrome1(s) { if(s == null) return false; const reg = /[^a-zA-Z0-9]+/g const str = s.replace(reg, '').toUpperCase(); return str == str.split('').reverse().join('').toUpperCase(); } // console.log( isPalindrome1("A man, a plan, a canal: Panama") ); // 双指针 function isPalindrome2(s) { if(s == null) return false; const reg = /[^a-zA-Z0-9]+/g const str = s.replace(reg, '').toUpperCase(); let left = 0; let right = str.length - 1; while(left < right) { if(str[left] !== str[right]) { return false; } left ++; right --; } return true; } // console.log( isPalindrome2(";;") ); <file_sep>/isSameTree.js // 100. 相同的树 // 给定两个二叉树,编写一个函数来检验它们是否相同。 // 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 // 示例 1: // 输入: 1 1 // / \ / \ // 2 3 2 3 // [1,2,3], [1,2,3] // 输出: true // 示例 2: // 输入: 1 1 // / \ // 2 2 // [1,2], [1,null,2] // 输出: false // 示例 3: // 输入: 1 1 // / \ / \ // 2 1 1 2 // [1,2,1], [1,1,2] // 输出: false // 以例子2,3来讲解: // 深度优先搜索 function isSameTree(p, q) { // 这一句必须写在最前面 if(p == null && q == null) return true; if(p == null || q == null) return false; // 为什么不能单纯的判断if(p.val == q.val) return true; ?? if(p.val !== q.val) return false; return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); // return // isSameTree(p.left.left, p.left.right) && // isSameTree(q.left.left, q.left.right) && // isSameTree(q.left.left, q.left.right) && // isSameTree(p.right.left, p.right.right) && } function Node(val) { this.val = val; this.left = null; this.right = null; } var p = new Node(1); p.left = new Node(2); p.right = new Node(3); var q = new Node(1); q.left = new Node(2); q.right = new Node(3); // console.log(p, q); console.log( isSameTree1(p, q) ); // 迭代: // 判断两个节点是不是一样的(左右孩子, 值) function check(p, q) { if(p == null && q == null) return true; if(p == null || q == null) return false; if(p.val != q.val) return false; return true; } function isSameTree1(p, q) { if (p == null && q == null) return true; // 判断根节点 if (!check(p, q)) return false; // 根节点放入队列中 var depP = [p]; var depQ = [q]; // 循环 while(depP.length !== 0) { // 取出队头元素 p = depP.shift(); q = depQ.shift(); // console.log(p, q); // 判断两个节点是不是相等 if (!check(p, q)) return false; // console.log(1); if(p !== null) { // 如果两棵树的左孩子都相等,就继续往下判断 // 两颗树的左孩子相等有两种情况:都是null 或者是 值val 相等 if (!check(p.left, q.left)) return false; if (p.left != null) { depP.push(p.left); depQ.push(q.left); } // 同上 if (!check(p.right, q.right)) return false; if (p.right != null) { depP.push(p.right); depQ.push(q.right); } } } return true; }<file_sep>/hasPathSum.js // 112. 路径总和 // 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。 // 说明: 叶子节点是指没有子节点的节点。 // 示例: // 给定如下二叉树,以及目标和 sum = 22, // 5 // / \ // 4 8 // / / \ // 11 13 4 // / \ \ // 7 2 1 // 返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。 // 递归 function hasPathSum(root, sum) { if(root == null || sum == null) return false; var leftS = false, rightS = false; if(root.left) leftS = hasPathSum(root.left, sum - root.val); if(root.right) rightS = hasPathSum(root.right, sum - root.val); if(root.val == sum && !root.left && !root.right) { return true; } else { return leftS || rightS; } } // 迭代 function hasPathSum(root, sum) { if(root == null || sum == null) return false; if(root.val == sum && !root.left && !root.right) return true; var queue = [root]; while(queue.length > 0) { var tempQ = [] for(var node of queue) { if(node.left) { tempQ.push(node.left); node.left.val += node.val if(node.left.val == sum && !node.left.left && !node.left.right) return true } if(node.right) { tempQ.push(node.right); node.right.val += node.val if(node.right.val == sum && !node.right.left && !node.right.right) return true } } queue = tempQ; } return false; }<file_sep>/腾讯17实习编程题1.js // 小Q最近遇到了一个难题:把一个字符串的大写字母放到字符串的后面, // 各个字符的相对位置不变,且不能申请额外的空间。 // 输入描述: // 输入数据有多组,每组包含一个字符串s,且保证:1<=s.length<=1000. // 输出描述: // 对于每组数据,输出移位后的字符串。 // 输入例子1: // AkleBiCeilD // 输出例子1: // kleieilABCD // 通过,但是我创建了一个空间 // while(line=readline()){ // if(line.length >= 1 && line.length <= 1000) { // var strArr = line.trim().split(''); // var len = strArr.length; // for(var i = 0; i < len; i ++) { // if(strArr[i] >= 'A' && strArr[i] <= 'Z') { // strArr.push(strArr[i]) // strArr.splice(i, 1, ""); // } // } // console.log(strArr.join("")); // } // } // xain:868599228 // yuan:182114273 // 通过 while(line = readline()) { if(line.length >= 1 && line.length <= 1000) { //先去掉字符串前面的制表符 line = line.trim(); //字符串长度 var len = line.length; //遍历每一个出字符元素 for(var i = 0; i < len; i ++) { if(line[i] >= 'A' && line[i] <= 'Z') { //如果是大写的字母,,就拼接在字符串的后面 line += line[i]; //大写字符原来的位置使用空字符串替换掉,(不是空格字符串) line = line.replace(line[i], ''); //因为大写字母被替换掉了,所以原来字符串长度会减少一个;而且这个i 的代表的是下一个循环的i的值,所以 i 要 --;与 i++ 互相抵消 len --; i --; } } } // 最后输出 console.log(line); }<file_sep>/数组比较-查找/26. 删除排序数组中的重复项.js // 26. 删除排序数组中的重复项 // 给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 // 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。 // 示例 1: // 给定数组 nums = [1,1,2], // 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 // 你不需要考虑数组中超出新长度后面的元素。 // 示例 2: // 给定 nums = [0,0,1,1,1,2,2,3,3,4], // 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。 // 你不需要考虑数组中超出新长度后面的元素。 // 双指针 function deleteArr(arr) { if(arr === null || arr.length === 0) return 0 var r = 0, l = 1 while(l < arr.length) { if(arr[r] == arr[l]) { arr.splice(l, 1) } else { r ++ l ++ } } return arr.length } console.log( deleteArr([1,1,2]) ) console.log( deleteArr([0,0,1,1,1,2,2,3,3,4]) ) <file_sep>/剑指offer/简单/剑指 Offer 42. 连续子数组的最大和.js // 剑指 Offer 42. 连续子数组的最大和 // 输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。 // 要求时间复杂度为O(n)。 // 示例1: // 输入: nums = [-2,1,-3,4,-1,2,1,-5,4] // 输出: 6 // 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 // 动态规划 var maxSubArray = function(nums) { if(nums === null) return; var res = nums[0], len = nums.length; for(var i = 1; i < len; i ++) { nums[i] = nums[i] + Math.max(nums[i - 1], 0); res = Math.max(res, nums[i]); } return res; }; console.log( maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) );<file_sep>/index.js //题目:求字符串的字节长度 function getLen(str) { var len = str.length; var count = 0; for(var i = 0; i < len; i ++) { if(str.charCodeAt(i) > 255) { count ++; } count ++; } return count; } // console.log( getLen('huang') ); function getLen1(str) { var len = str.length; var count = len; for(var i = 0; i < len; i ++) { if(str.charCodeAt(i) > 255) { count ++; } } return count; } // console.log( getLen1('huang') ); // 原型(prototype)是函数的一个属性,是这个函数构造出来的对象的共有祖先 // 对像通过__proto__找到原型,__proto__链接到我的原型 // constructor是在原型上的 // 原型表示: // 构造函数上: Fn.prototy // 构造函数构造出来的对象上: obj.__proto__ // function Dad() { this.name = 'huangfengquan'; } var dad = new Dad(); Person.prototype = dad; Person.prototype.age = 18; function Person() { } var per = new Person(); // console.log(per); // console.log(per.name, per.age); // console.log(Person.prototype); // console.log(per.__proto__); // console.log(per.constructor); // 1.原型链 // 2.借用他人的构造函数 // 3.共有原型 function inherit(Target, Origin) { // 构造函数Target的原型就是构造函数Origin的原型 // 两个构造函数共享同一个原型 // 因为原型是一个对象,是引用值 Target.prototype = Origin.prototype; } // 4.圣杯模式 function inherit1(Target, Origin) { function F() {} F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constructor = Target; Target.prototype.uber = Origin.prototype; } function Son() { } function Father() { } // inherit(Son, Father); inherit1(Son, Father); var son = new Son(); var father = new Father(); // call 、 apply 、 bind的区别? // 都是改变this指向 // 1.call传递的参数是散列的 // 2.apply传递的参数是一个数组 // 3.bind是由call或者apply来实现的, // 是函数的一个属性 // 但是不会修改函数本的this,是直接返回一个this被修改后的函数。 // bind传递的参数是按传递的顺序一位一个拼接的, // new 操作时,不会改变this, 构造出来的对象的构造函数是原来的函数 // bind的实现: Function.prototype.newBind = function(target) { var self = this; var _args = [].slice.call(arguments, 1); var temp = function () {}; var f = function() { var args = [].slice.call(arguments, 0); return self.apply(this instanceof temp ? this : (target || window), _args.concat(args)); } temp.prototype = self.prototype; f.prototype = new temp(); return f; } function Parent(name) { this.name = name; } Parent.prototype.getName = function() { return this.name; } Children.prototype = new Parent(); function Children(name) { Parent.call(this, name) } var chil = new Children('kkk'); console.log(chil.getName()) // function show(a, b, c) { // console.log(this, a, b, c); // } // var obj = { // name: 'huangfengquan' // } // var nShow = show.mBind(obj, 'a'); // show(1, 2, 3); // nShow(2, 3); // var obj1 = new nShow(); // 封装一个ajax: // <input type="text" id="demo"> // <div id="show"></div> // 简单的数据劫持 const oInp = document.getElementById('demo'); const oDiv = document.getElementById('show'); let data = { obj: { value: 'ffff', age: 19, }, sex: 1 } oInp.oninput = function() { console.log(this); data.obj.value = this.value; } function update() { oDiv.innerText = data.obj.value; } function Observer(data) { if(!data || typeof data != 'object') return; Object.keys(data).forEach(function(key) { defineR(data, key, data[key]); }) } function defineR(data, key, val) { Observer(val); Object.defineProperty(data, key, { get() { return val; }, set(newVal) { if(newVal == val) return; val = newVal; update(); } }) } update(); Observer(data); // 对数组做数据劫持,重写数组的方法 let arr = []; let push = Array.prototype.push; function updateArr() { console.log('更新了'); } Object.defineProperty(Array.prototype, 'push', { value: (function() { return function() { push.apply(arr, arguments); updateArr(); } })() }) // proxy(代理) and reflect(映射) // 可以实现对对象和数组更好的监控; // 针对对象新增的属性也可以监控到 // 代理模式: let oData = { val: 'duyi' } //实现对oData的代理 let oProxyData = new Proxy(oData, { set (target, key, value, receiver) { console.log(target, key, value, receiver); // 一般是配套使用的: 更新值 Reflect.set(target, key, value); }, get (target, key, receiver) { console.log(target, key, receiver); // return oData.val; // 一般是配套使用的:返回值 return Reflect.get(target, key); } }); // 读 写的控制, 一定要在上面实现代理的时候添加参数{get.., set..} console.log( oProxyData.val ); oProxyData.val = 'huang'; let oArr = ['a']; // 实现对数组数据的监控 let oProxyData1 = new Proxy(oArr, { // 写: set (target, key, value, receiver) { Reflect.set(target, key, value); upData(); }, // 读: get (target, key, receiver) { return Reflect.get(target, key); } }); console.log(oProxyData1[0]); oProxyData1[1] = 'cccc'; function upData () { console.log('更新啦啦~~~'); } // 发布订阅模式: function Event() { this.cache = {}; } Event.prototype.on = function(type, handle) { if(this.cache[type]) { this.cache[type].push(handle); } else { this.cache[type] = [handle]; } } Event.prototype.emmit = function() { var type = arguments[0]; var params = [].slice.call(arguments, 1); for(var i = 0; i < this.cache[type].length; i ++) { this.cache[type][i].apply(this, params); } } Event.prototype.empty = function(type) { this.cache[type] = []; } Event.prototype.remove = function(type, handle) { this.cache[type] = this.cache[type].filter(function(ele) { return !(ele == handle); }) } Event.prototype.once = function() { } // promise化: // 一个: function promisify (func) { return function (...arg) {//...arg 收集作用 return new Promise((res, rej) => { func(...arg, (err, data) => {//...arg 展开作用 if(err) { rej(err); } else { res(data); } }); }); } } // 多个: function promiseAll (obj) { for(let key in obj) { let fn = obj[key]; if(typeof fn == 'function') { obj[key + 'Async'] = promisify(fn); } } } // async + await 的使用: // 解决回调地狱: async function read (url) { let val1 = await readFile(url); let val2 = await readFile(val1); let val3 = await readFile(val2); return val3; } // 解决try catch捕获不到异步的代码的错误: async function read (url) { try { let val1 = await readFile(url); let val2 = await readFile(val1); let val3 = await readFile(val2); return val3; } catch (e) { console.log('在158行'); return e; } } // 解决同步并发的异步结果 let fs = require('fs'); function readFile (path) { return new Promise((res, rej) => { fs.readFile(path, 'utf-8', (err, data) => { if(err) { rej(err); } else { res(data); } }) }) } function dealReadFile(callBackSuccess, callBackFail, ...arg) { return async function () { let val = null; try { val = await readFile(...arg); callBackSuccess && callBackSuccess(val); } catch(e) { callBackFail && callBackFail(e); } } } function successDeal (val) { console.log(val); } function failDeal (reason) { console.log(reason); } let read1 = dealReadFile(successDeal, failDeal, './data/number.txt'); let read2 = dealReadFile(successDeal, failDeal, './data/num.txt'); let read3 = dealReadFile(successDeal, failDeal, './data/name.txt'); function readAll(...arg) { arg.forEach(ele => { ele(); }) } readAll(read1, read2, read3); /** url: string params: obj cb: function cbN: string **/ // jsonp函数 function jsonp(url, params, cb, cbN) { // 兼容处理 let queryString = url.indexOf('?') === -1 ? '?' : '&'; // 拼接参数 for(let k in params) { if(params.hasOwnProperty(k)) { queryString += `${k}=${params[k]}&`; } } // 产生回调函数名子 const cbName = 'jsonp' + Math.random().toString().replace('.', ''); // 生成script标签 const oScript = document.createElement('script'); // 请求资源 oScript.src = `${url}${queryString}${cbN}=${cbName}`; // 全局注册回调函数 window[cbName] = function() { // 调用回调 cb(...arguments); // 从body中删除 document.body.removeChild(oScript) } // 插入到body里 document.body.appendChild(oScript); } <file_sep>/树/简单/637. 二叉树的层平均值.js // 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。 // 输入: // 3 // / \ // 9 20 // / \ // 15 7 // 输出:[3, 14.5, 11] // 解释: // 第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。 function Node (val) { this.val = val this.left = null this.right = null } var node3 = new Node(3) var node9 = new Node(9) var node20 = new Node(20) var node15 = new Node(15) var node7 = new Node(7) node3.left = node9 node3.right = node20 node20.left = node15 node20.right = node7 // 2021.05.08: 广度优先遍历 var averageOfLevels = function(root) { if (root === null) return; var queue = [root] var sum = 0 var len = 0 var temp = 0 var res = [] while(queue.length > 0) { sum = 0 len = queue.length temp = queue.length while(temp > 0) { sum = sum + queue[0].val if(queue[0].left !== null) { queue.push(queue[0].left) } if(queue[0].right !== null) { queue.push(queue[0].right) } queue.shift() temp -- } res.push(sum / len) } return res; }; console.log( averageOfLevels(node3) ) <file_sep>/数组比较-查找/455. 分发饼干.js // 455. 分发饼干 // 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 // 对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。 // 如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子, // 并输出这个最大数值。 // 注意: // 你可以假设胃口值为正。 // 一个小朋友最多只能拥有一块饼干。 // 示例 1: // 输入: [1,2,3], [1,1] // 输出: 1 // 解释: // 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。 // 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。 // 所以你应该输出1。 // 示例 2: // 输入: [1,2], [1,2,3] // 输出: 2 // 解释: // 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 // 你拥有的饼干数量和尺寸都足以让所有孩子满足。 // 所以你应该输出2. function findContentChildren(kids, cookies) { if(kids === null || cookies === null) return; kids.sort((a, b) => (a - b)); cookies.sort((a, b) => (a - b)); var sum = 0, k = 0, c = 0; while(k <= kids.length && c <= cookies.length) { if(kids[k] <= cookies[c]) { sum ++; k ++; c ++; } else { c ++; } } return sum; } console.log( findContentChildren([1,2,3], [1,1]) ) console.log( findContentChildren([1,2], [1,2,3]) ) <file_sep>/剑指offer/中等/剑指 Offer 45. 把数组排成最小的数.js // 剑指 Offer 45. 把数组排成最小的数 // 输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 // 示例 1: // 输入: [10,2] // 输出: "102" // 示例 2: // 输入: [3,30,34,5,9] // 输出: "3033459" var minNumber = function(nums) { if(nums === null) return; nums.sort(function(a, b) { var n1 = '' + a + b, n2 = '' + b + a; return n1 - n2 + 0; }) return nums; }; console.log( minNumber([3,30,34,5,9]) );<file_sep>/isHappy.js // 202. 快乐数 // 编写一个算法来判断一个数是不是“快乐数”。 // 一个“快乐数”定义为: // 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和, // 然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。 // 如果可以变为 1,那么这个数就是快乐数。 // 示例: // 输入: 19 // 输出: true // 解释: // 1^2 + 9^2 = 82 // 8^2 + 2^2 = 68 // 6^2 + 8^2 = 100 // 1^2 + 0^2 + 0^2 = 1 // function isHappy0(num) { // if(num == null) return false; // if(num < 0) return false; // if(num == 1) return true; // var result = 0; // while(num != 0) { // var pop = num % 10; // num = Math.floor(num / 10); // result += Math.pow(pop, 2); // } // if(result != 1) { // return isHappy0(result); // } // return false; // } // // 上面怎么判断是无限循环呢? 无法判断,会导致栈溢出 // console.log( isHappy0(19) ); // console.log( isHappy0(23) ); // console.log( isHappy0(24) ); // console.log( isHappy0(254) ); // console.log( isHappy0(267) ); // 快慢指针: function bitSquareSum(n) { var sum = 0; while(n > 0) { var pop = n % 10; sum += pop * pop; n = Math.floor(n / 10); } return sum; } function isHappy(n) { var slow = n, fast = n; do{ slow = bitSquareSum(slow); fast = bitSquareSum(fast); fast = bitSquareSum(fast); }while(slow != fast); return slow == 1; } console.log( isHappy(29) ); console.log( isHappy(23) ); console.log( isHappy(24) ); console.log( isHappy(254) ); console.log( isHappy(267) ); <file_sep>/isSymmetric.js // 101. 对称二叉树 // 给定一个二叉树,检查它是否是镜像对称的。 // 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 // 1 // / \ // 2 2 // / \ / \ // 3 4 4 3 // 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: // 1 // / \ // 2 2 // \ \ // 3 3 // 说明: // 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。 function Node(val) { this.val = val; this.left = this.right = null; } var node1 = new Node(1); var node2_1 = new Node(2); var node2_2 = new Node(2); var node3_1 = new Node(3); var node3_2 = new Node(3); var node4_1 = new Node(4); var node4_2 = new Node(4); node1.left = node2_1; node1.right = node2_2; // node1.right = node3_1 node2_1.left = node3_1; node2_2.right = node3_2; node2_1.right = node4_1; node2_2.left = node4_2; function isSymmetric(root) { if(root == null) return true; var children = [root.left, root.right]; while(children.length > 0) { var temp = []; var len = children.length; console.log(children); for(var i = 0; i < len; i ++) { var curOne = children[i]; var sideOne = children[len - 1 - i]; if((curOne == null && sideOne !== null) || (curOne !== null && sideOne == null)) { return false; } else { if(curOne && sideOne && curOne.val !== sideOne.val) { return false; } else if(curOne && sideOne && curOne.val == sideOne.val) { temp.push(curOne.left); temp.push(curOne.right); } } } children = temp; } return true; } // console.log( isSymmetric(node1) ); // 递归写法 function isSymmetric1(root) { if(root == null) return true; var left = root.left; var right = root.right; // 两个都为真 if (left == null && right == null) return true; // 两个或者一个为真 if (left == null || right == null) return false; // 值不一样时 if (left.val !== right.val) return false; return isSymmetric1({left: left.left, right: right.right}) && isSymmetric1({left: left.right, right: right.left}); } console.log( isSymmetric1(node1) ); // 迭代写法 function isSymmetric(root) { if(root == null) return true; var temp = [root, root]; while(temp.length > 0) { var r = temp.pop(); var l = temp.pop(); if(r == null && l == null) continue; if(r == null || l == null) return false; if(r.val !== l.val) return false; // 镜像 temp.push(l.left); temp.push(r.right); temp.push(l.right); temp.push(r.left); } return true; } <file_sep>/简单/121. 买卖股票的最佳时机(20200802).js // 121. 买卖股票的最佳时机 // 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 // 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。 // 注意:你不能在买入股票前卖出股票。 // 示例 1: // 输入: [7,1,5,3,6,4] // 输出: 5 // 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 // 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。 // 示例 2: // 输入: [7,6,4,3,1] // 输出: 0 // 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 // // 一次遍历,寻找最低点 // 时间复杂度:O(n),只需要遍历一次。 // 空间复杂度:O(1),只使用了常数个变量。 const nums = [7,1,5,3,6,4]; function greatTime(nums) { if(nums === null || nums.length === 0) return 0; let minPoint = Number.MAX_VALUE, max = 0, len = nums.length; for(let i = 0; i < len; i ++) { if(nums[i] < minPoint) { minPoint = nums[i]; } else if(nums[i] - minPoint > max) { max = nums[i] - minPoint; } } return max; } console.log( greatTime(nums) ); // 暴力解法: // 时间复杂度:O(n^2) // 空间复杂度:O(1)。 只使用了常数个变量。 const nums = [7,1,5,3,6,4]; function greatTime(nums) { if(nums === null || nums.length === 0) return 0; let res = 0; for(let i = 0; i < nums.length; i ++) { for(let j = i + 1; j < nums.length; j ++) { if(nums[j] - nums[i] > res) { res = nums[j] - nums[i]; } } } return res; } console.log( greatTime(nums) ); <file_sep>/中等/最长回文子串.js // 5. 最长回文子串 // 给你一个字符串 s,找到 s 中最长的回文子串。 // 示例 1: // 输入:s = "babad" // 输出:"bab" // 解释:"aba" 同样是符合题意的答案。 // 示例 2: // 输入:s = "cbbd" // 输出:"bb" // 示例 3: // 输入:s = "a" // 输出:"a" // 示例 4: // 输入:s = "ac" // 输出:"a" /** * @param {string} s * @return {string} */ // 中心扩展法: var longestPalindrome = function(s) { var len = s.length var res = '' if (len < 2) { return s } for(var i = 0; i < len; i ++) { helper(i, i) helper(i, i + 1) } function helper (m, n) { // m >= 0 && n < len: 这里的限制是为了使得m,n符合字符串的索引, 保证s[m],s[n]可以取到值 while(m >= 0 && n < len && s[m] === s[n]) { m -- n ++ } // 为什么是n - m - 1呢? // 因为跳出while时,就表示m, n两个值是不符合要求的。 // m,n两个边界不能取 所以应该取m+1到n-1的区间,所以长度是 (m + 1) - (n - 1) + 1 = m - n - 1 // 这里 最后要 + 1,是因为我是计算字符串的个数(长度)的 // 比如:'abc', 当m = 0, n = 2时,是不满足要求的,所以符合要求的字符串只有'a', 长度为1; 故为 n - m - 1 if(n - m - 1 > res.length) { res = s.slice(m + 1, n) } } return res } console.log(longestPalindrome('babad')); console.log(longestPalindrome('cbbd')); console.log(longestPalindrome('q')); console.log(longestPalindrome('ac')); console.log(longestPalindrome('acdd')); console.log(longestPalindrome('acddc')); console.log(longestPalindrome('abbajjjjjjooopoooppppoooooo')); <file_sep>/mySqrt.js // 69. x 的平方根 // 实现 int sqrt(int x) 函数。 // 计算并返回 x 的平方根,其中 x 是非负整数。 // 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 // 示例 1: // 输入: 4 // 输出: 2 // 示例 2: // 输入: 8 // 输出: 2 // 说明: 8 的平方根是 2.82842..., // 由于返回类型是整数,小数部分将被舍去。 // 1.直接使用平方根函数Math.sqrt() function mySqrt(x) { if(x == null) return; if(x < 2) return x; return ~~Math.sqrt(x); } // console.log( mySqrt(4) ); // console.log( mySqrt(8) ); // 2.二分查找 / 折半查找 function mySqrt1(x) { if(x == null) return; if(x < 2) return x; var num = 0; pivot = 0; left = 2; right = Math.floor(x / 2); while(left <= right) { // right - left: 就是从left 到 right 中有多少个数(可理解为距离) // (right - left) / 2: 就是获取到从left 到 right 一半的数(可理解为1/2的距离) // 所以left + Math.floor((right - left) / 2): 就left 到 right 之间的中心点 pivot = left + Math.floor((right - left) / 2) ; num = pivot * pivot; // 去掉右半部分的数 if (num > x) right = pivot - 1; // 去掉左半部分的数 else if (num < x) left = pivot + 1; else return pivot; } // 因为 left > rigt时才跳出循环,此时的left已经是在我们的判断范围之外,只有right符合 return right; } // console.log( mySqrt1(15) ); // console.log( mySqrt1(9) ); // console.log( mySqrt1(7) ); // 递归 + 位移动操作 function mySqrt2(x) { if(x == null) return; if(x < 2) return x; var left = mySqrt2(x >> 2) << 1; var right = left + 1; return right * right > x ? left : right; } // console.log( mySqrt2(15) ); // console.log( mySqrt2(9) ); // 位移动操作 // >> 右移动 << 左移动 // eg: 5 >> 2 // 5 ===> 二进制:0000 0101 // 右移动 2 为: 0000 0001 ==> 十进制: 1 // 牛顿法:(暂时没理解) <file_sep>/3. 无重复字符的最长子串.js // 3. 无重复字符的最长子串 // 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 // 示例 1: // 输入: "abcabcbb" // 输出: 3 // 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 // 示例 2: // 输入: "bbbbb" // 输出: 1 // 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 // 示例 3: // 输入: "pwwkew" // 输出: 3 // 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 // 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。 // 时间复杂度:O(N)O(N),其中 NN 是字符串的长度。左指针和右指针分别会遍历整个字符串一次: var lengthOfLongestSubstring = function(s) { // 哈希集合,记录每个字符是否出现过 const occ = new Set(); const len = s.length; // 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动 let rk = -1, res = 0; // i是左指针 for (let i = 0; i < len; ++i) { if (i != 0) { // 左指针向右移动一格,移除一个字符 occ.delete(s.charAt(i - 1)); } while (rk + 1 < len && !occ.has(s.charAt(rk + 1))) { // 不断地移动右指针 occ.add(s.charAt(rk + 1)); ++rk; } // 第 i 到 rk 个字符是一个极长的无重复字符子串 res = Math.max(res, rk - i + 1); } return res; }; console.log(lengthOfLongestSubstring("pwwkew")) console.log(lengthOfLongestSubstring("abcabcbb")) console.log(lengthOfLongestSubstring("ppppppp")) // 2020.11.06 function longest(str) { if(str === null || str.length === 0) return 0 let r = -1, len = str.length, set = new Set(), max = 0 for(var i = 0; i < len; i ++) { if(i != 0) { set.delete(str[i - 1]) } while(r + 1 < len && !set.has(str[r + 1])) { set.add(str[r + 1]) r ++ } max = Math.max(max, r - i + 1) } return max } <file_sep>/简单/1002. 查找常用字符.js // 1002. 查找常用字符 // 给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。 // 例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。 // 你可以按任意顺序返回答案。 // 示例 1: // 输入:["bella","label","roller"] // 输出:["e","l","l"] // 示例 2: // 输入:["cool","lock","cook"] // 输出:["c","o"] function getCommon(a, b) { const map = new Map(), aLen = a.length, bLen = b.length, res = []; for(let i = 0; i < aLen; i ++) { let aNum = map.get(a[i]); if(aNum) { map.set(a[i], aNum + 1) } else { map.set(a[i], 1) } } for(let j = 0; j < bLen; j ++) { let bNum = map.get(b[j]); if(bNum) { res.push(b[j]); map.set(b[j], bNum - 1); } } return res; } function findStr(A) { return A.reduce((a, b) => { return getCommon(a, b); }) } console.log( findStr(["cool","lock","cook"]) ); console.log( findStr(["bella","label","roller"]) ); <file_sep>/92. 反转链表 II.js // 92. 反转链表 II // 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 // 说明: // 1 ≤ m ≤ n ≤ 链表长度。 // 示例: // 输入: 1->2->3->4->5->NULL, m = 2, n = 4 // 输出: 1->4->3->2->5->NULL /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @param {number} m * @param {number} n * @return {ListNode} */ let reverseBetween = function(head, m, n) { }; <file_sep>/中等/两数相加.js // 2. 两数相加 // 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。 // 请你将两个数相加,并以相同形式返回一个表示和的链表。 // 你可以假设除了数字 0 之外,这两个数都不会以 0 开头。 // 示例 1: // 输入:l1 = [2,4,3], l2 = [5,6,4] // 输出:[7,0,8] // 解释:342 + 465 = 807. // 示例 2: // 输入:l1 = [0], l2 = [0] // 输出:[0] // 示例 3: // 输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] // 输出:[8,9,9,9,0,0,0,1] // 提示: // 每个链表中的节点数在范围 [1, 100] 内 // 0 <= Node.val <= 9 // 题目数据保证列表表示的数字不含前导零 /** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ function ListNode (val, next) { this.val = (val === undefined ? 0 : val) this.next = (next === undefined ? null : next) } var node1_2 = new ListNode(2) var node1_4 = new ListNode(4) var node1_3 = new ListNode(3) node1_2.next = node1_4 node1_4.next = node1_3 var node2_5 = new ListNode(5) var node2_6 = new ListNode(6) var node2_4 = new ListNode(4) node2_5.next = node2_6 node2_6.next = node2_4 var addTwoNumbers = function(l1, l2) { if (l1 === null || l2 == null) return var curNode = new ListNode(0) var curr = curNode var carry = 0 while (l1 !== null || l2 !== null) { var x = l1 === null ? 0 : l1.val var y = l2 === null ? 0 : l2.val var sum = carry + x + y var curVal = (sum) % 10 carry = Math.floor( (sum) / 10 ) curr.next = new ListNode(curVal) curr = curr.next if (l1) l1 = l1.next if (l2) l2 = l2.next } if (carry > 0) { curr.next = new ListNode(carry) } return curNode.next }; var resVal = addTwoNumbers(node1_2, node2_5) console.log('resVal: ', resVal);<file_sep>/longestPalindrome.js // 5. 最长回文子串 // 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 // 示例 1: // 输入: "babad" // 输出: "bab" // 注意: "aba" 也是一个有效答案。 // 示例 2: // 输入: "cbbd" // 输出: "bb" // 方法: 中心扩展法 + 双指针 function longest(str) { if(str == null || str.length < 1) return ''; var strat = 0; var end = 0; for(var i = 0; i < str.length; i ++) { // 遍历所有的字符,以每个字符str[i]为中心向两边拓展, i为中心index var len1 = center(str, i, i); // 最长回文串长度为奇数,从中心一直向两边拓展,从而使回文子串 var len2 = center(str, i, i + 1); // 最长回文串长度为偶数,从两个相邻的数出发,同时向两边拓展 var len = Math.max(len1, len2); if(len > end - strat) { strat = i - Math.floor((len - 1) / 2); // 回文子串-开头i 为中心索引 (-1 ???) end = i + Math.floor(len / 2); // 回文子串-结尾 } } return str.substring(strat, end + 1); } function center(str, left, right) { var l = left; var r = right; while(l >= 0 && r < str.length && str.charAt(l) == str.charAt(r)) { l --; r ++; } return r - l - 1; // 为什么 -1??? } var newStr = longest('aabbbbhaalaa'); console.log(newStr); // 2020.08.07(全对) function longest_2(str) { if(str === null) return ''; let len = str.length, start = 0, end = 0; for(let i = 0; i < len; i ++) { let len1 = center_2(str, i, i), len2 = center_2(str, i, i + 1), max = Math.max(len1, len2); if(max > end - start) { start = i - Math.floor((max - 1) / 2); end = i + Math.floor(max / 2); } } return str.substring(start, end + 1); } function center_2(str, left, right) { let l = left, r = right; while(l >= 0 && r < str.length && str.charAt(l) === str.charAt(r)) { l --; r ++; } return r - l - 1; } console.log( longest_2('aabbbbhaalaabbbbbbbbbbbaabbb') ); // 2020.07.14(默写 全对) function longest(str) { if(str == null || str.length == 0) return ''; var start = 0, end = 0, len = str.length; for(var i = 0; i < len; i ++) { var len1 = center(str, i, i); var len2 = center(str, i , i + 1); var maxLen = Math.max(len1, len2); if(maxLen > end -start) { start = i - Math.floor((maxLen - 1) / 2); end = i + Math.floor(maxLen / 2); } } return str.substring(start, end + 1); } function center(str, left, right) { var l = left, r = right; while(l >= 0 && r < str.length && str[l] === str[r]) { l --; r ++; } return r - l - 1; } // var long = longest('aahuauhbs'); // console.log(long); // 2020.08.05(默写 对了80%) function longestText(str) { if(str == null) return ''; let len = str.length, start = 0, end = 0; for(let i = 0; i < len; i ++) { let len1 = centerPoint(str, i, i), len2 = centerPoint(str, i, i + 1), maxLen = Math.max(len1, len2); if(maxLen > end - start) { start = i - Math.floor((maxLen - 1) / 2); end = i + Math.floor(maxLen / 2); } } return str.substring(start, end + 1); } function centerPoint(str, left, right) { let l = left, r = right; while(l >= 0 && r < str.length && str.charAt(l) === str.charAt(r)) { l --; r ++; } return r - l - 1; } // console.log( longestText("abcdcba") ); // 中心扩展法 // function longestPalindrome(str) { // if(str == null || str.length < 1) return ""; // // 游标初始化 // var start = 0, // end = 0; // for(var i = 0; i < str.length; i ++) { // // 中心为一个字符 // var len1 = expandAroundCenter(str, i, i); // // 中心为两个字符 // var len2 = expandAroundCenter(str, i, i + 1); // // 取出最长的长度 // var len = Math.max(len1, len2); // // 与原来的长度进行比较 // if(len > end - start) { // start = i - Math.floor((len - 1) / 2); // end = i + Math.floor(len / 2); // } // } // return str.substring(start, end + 1); // } // function expandAroundCenter(s, left, right) { // var l = left, // r = right; // while(l >= 0 && r < s.length && s.charAt(l) == s.charAt(r)) { // l --; // r ++; // } // return r - l - 1; // } // console.log( longestPalindrome('lklkkkkjojkkkklopoop') ); <file_sep>/二叉树的diff算法.js function Node(value) { this.value = value; this.left = null; this.right = null; } var a = new Node('a'); var b = new Node('b'); var c = new Node('c'); var d = new Node('d'); var e = new Node('e'); var f = new Node('f'); var g = new Node('g'); var h = new Node('h'); a.left = c; a.right = b; c.left = f; c.right = g; b.left = d; b.right = e; e.right = h; var a1 = new Node('a'); var b1 = new Node('b'); var c1 = new Node('修改看看'); var d1 = new Node('d'); var e1 = new Node('e'); var f1 = new Node('修改来来'); var g1 = new Node('g'); var h1 = new Node('h'); var i1 = new Node('i, 新增的'); a1.left = c1; a1.right = b1; c1.left = f1; c1.right = g1; // b1.left = d1; b1.right = e1; e1.left = i1; e1.right = h1; // diff算法: function diffTree(root1, root2, diffList) { // console.log(root1.value, root2.value); if(root1 == root2) return diffList; if(root1 == null && root2 != null) { //新增了节点 diffList.push({ type: '新增', origin: null, now: root2 }) } else if(root1 != null && root2 == null){//删除了节点 diffList.push({ type: '删除', origin: root1, now: null }) } else if(root1.value != root2.value) {//相同位置的节点不同了,修改了节点 diffList.push({ type: '修改', origin: root1, now: root2 }) diffTree(root1.left, root2.left, diffList); diffTree(root1.right, root2.right, diffList); } else { diffTree(root1.left, root2.left, diffList); diffTree(root1.right, root2.right, diffList); } return diffList; } var diffList = []; diffTree(a, a1, diffList); console.log(diffList);<file_sep>/README.md # 基础算法题 - javaScript版算法练习 - 一天一种新解法 / 新题目 <file_sep>/剑指offer/中等/剑指 Offer 56 - I. 数组中数字出现的次数.js // 剑指 Offer 56 - I. 数组中数字出现的次数 // 一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。 // 请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。 // 示例 1: // 输入:nums = [4,1,4,6] // 输出:[1,6] 或 [6,1] // 示例 2: // 输入:nums = [1,2,10,4,1,4,3,3] // 输出:[2,10] 或 [10,2] var singleNumbers = function(nums) { if(nums === null) return; } // 一次全员异或: function single(nums) { if(nums === null) return; var res = 0; for(var k of nums) { res ^= k; } return res; } console.log( single([1, 2, 3, 3, 2]) ); console.log( single([1, 2, 3, 3, 2, 1, 7]) );<file_sep>/39. 组合总和.js // 39. 组合总和 // 给定一个无重复元素的数组 arr 和一个目标数 target ,找出 arr 中所有可以使数字和为 target 的组合。 // arr 中的数字可以无限制重复被选取。 // 说明: // 所有数字(包括 target)都是正整数。 // 解集不能包含重复的组合。 // 示例 1: // 输入:arr = [2,3,6,7], target = 7, // 所求解集为: // [ // [7], // [2,2,3] // ] // 示例 2: // 输入:arr = [2,3,5], target = 8, // 所求解集为: // [ // [2,2,2,2], // [2,3,3], // [3,5] // ] var combinationSum = function(arr, target) { const res = []; const dfs = (target, combine, index) => { if (index === arr.length) { return; } if (target === 0) { res.push(combine); return; } // 直接跳过 dfs(target, combine, index + 1); // 选择当前数 if (target - arr[index] >= 0) { dfs(target - arr[index], [...combine, arr[index]], index); } } dfs(target, [], 0); return res; }; <file_sep>/demo.js // 冒泡排序 function sort(arr) { if(arr == null || arr.length == 0) return; for(var i = 0; i < arr.length; i ++) { for(var j = 0; j < arr.length - 1 - i; j ++) { if(arr[j] > arr[j + 1]) { var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } // 选择排序 function sort1(arr) { if(arr == null || arr.length == 0) return; for(var i = 0; i < arr.length; i ++) { var max = 0; for(var j = i + 1; j < arr.length; j ++) { if(arr[max] < arr[j]) { max = j; } } var temp = arr[max]; arr[max] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } } // 快速排序 function sort2(arr) { if(arr == null || arr.length) return; var temp = arr[0]; var left = []; var right = []; for(var i = 1; i < arr.length; i ++) { if(arr[i] < temp) { left.push(arr[i]) } else { right.push(arr[i]); } } left = sort2(left); right = sort2(right); return left.concat([temp], right); } // var arr = [2, 8, 3, 4, 9, 0, 1]; // console.log(sort2(arr)); // console.log(arr); <file_sep>/2. 两数相加.js // 2. 两数相加 // 给出两个 非空 的链表用来表示两个非负的整数。 // 其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 // 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 // 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 // 示例: // 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) // 输出:7 -> 0 -> 8 // 原因:342 + 465 = 807 // function ListNode(val) { this.val = val; this.next = null; } var node2 = new ListNode(2); var node4_1 = new ListNode(4); var node3 = new ListNode(3); var node5 = new ListNode(5); var node6 = new ListNode(6); var node4_2 = new ListNode(4); node2.next = node4_1; node4_1.next = node3; node5.next = node6; node6.next = node4_2; function add(head1, head2) { if(head1 == null || head2 == null) return; var dummyHead = new ListNode(0); var curr = dummyHead; var carry = 0; while (head1 != null || head2 != null) { // head1, head2 中存在一个,即以最长链为准 var x = (head1 != null) ? head1.val : 0; // 短链中,相对长链不存在的部分,默认为0 var y = (head2 != null) ? head2.val : 0; var sum = carry + x + y; carry = Math.floor( sum / 10 ); // 商值 curr.next = new ListNode(sum % 10); // 创建新节点,赋值为余数 curr = curr.next; // 切换链表,就是切换到下个节点 if (head1 != null) head1 = head1.next; if (head2 != null) head2 = head2.next; } if (carry > 0) { // 如果还有余数 curr.next = new ListNode(carry); // 添加新节点 } return dummyHead.next; // 因为链表的头部的val为0 } var addNode = add(node2, node5); console.log(addNode); // 复杂度分析: // 时间复杂度:O(max(m, n)),假设 m 和 n 分别表示 l1 和 l2 的长度,上面的算法最多重复 max(m, n)次。 // 空间复杂度:O(max(m, n)), 新列表的长度最多为 max(m,n) + 1。 <file_sep>/数组比较-查找/56. 合并区间(字节一面).js // 56. 合并区间 // 给出一个区间的集合,请合并所有重叠的区间。 // 示例 1: // 输入: arr = [[1,3],[2,6],[8,10],[15,18]] // 输出: [[1,6],[8,10],[15,18]] // 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. // 示例 2: // 输入: arr = [[1,4],[4,5]] // 输出: [[1,5]] // 解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。 var merge = function(arr) { if(arr === null || arr.length === 0) return []; var arrSort = arr.sort((a, b) => a[0] - b[0]), // 排序 len = arrSort.length, res = [arrSort[0]]; for(var i = 0; i < len; i ++) { if(arrSort[i][0] > res[res.length - 1][1]) { res.push(arrSort[i]); } else { res[res.length - 1][1] = Math.max(arrSort[i][1], res[res.length - 1][1]); } } return res; }; console.log( merge([[1,4],[4,5]]) ) console.log( merge([[1,3],[2,6],[8,10],[15,18]]) ) // 2020.10.10 function _merge(arr) { if(arr === null) return; var arrSort = arr.sort((a, b) => a - b), len = arr.length, res = [arrSort[0]]; for(var i = 1; i < len; i ++) { if(res[res.length - 1][1] < arr[i][0]) { res.push(arr[i]); } else { res[res.length - 1][1] = Math.max(res[res.length - 1][1], arr[i][1]); } } return res; } console.log( _merge([[1,4],[4,5]]) ) console.log( _merge([[1,3],[2,6],[8,10],[15,18]]) ) // 2020.11.04 function merge1(arr) { if(arr === null || arr.length === 0) return null; arr.sort((a, b) => { return a[0] - b[0] }) const len = arr.length, res = [arr[0]] for(let i = 1; i < len; i ++) { if(res[res.length - 1][1] < arr[i][0]) { res.push(arr[i]) } else { res[res.length - 1][1] = Math.max(res[res.length - 1][1], arr[i][1]) } } return res } console.log( merge1([[1,4],[4,5]]) ) console.log( merge1([[1,3],[2,6],[8,10],[15,18]]) ) function merge2(arr) { if(arr === null || arr.length === 0) return arr.sort((a, b) => { return a[0] - b[0] }) const len = arr.length, res = [arr[0]] for(let i = 1; i < len; i ++) { if(res[res.length - 1][1] < arr[i][0]) { res.push(arr[i]) } else { res[res.length - 1][1] = Math.max(res[res.length - 1][1], arr[i][1]); } } return res } console.log( merge2([[1,4],[4,5]]) ) console.log( merge2([[1,3],[2,6],[8,10],[15,18]]) ) <file_sep>/romanToInt.js // 13. 罗马数字转整数 // 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。 // 字符 数值 // I 1 // V 5 // X 10 // L 50 // C 100 // D 500 // M 1000 // 例如, // 罗马数字 2 写做 II ,即为两个并列的 1。 // 12 写做 XII ,即为 X + II 。 // 27 写做 XXVII, 即为 XX + V + II 。 // 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例, // 例如 4 不写做 IIII,而是 IV。 // 数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。 // 同样地,数字 9 表示为 IX。 // 这个特殊的规则只适用于以下六种情况: // I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。 // X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 // C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。 // 给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。 // 示例 1: // 输入: "III" // 输出: 3 // 示例 2: // 输入: "IV" // 输出: 4 // 示例 3: // 输入: "IX" // 输出: 9 // 示例 4: // 输入: "LVIII" // 输出: 58 // 解释: L = 50, V= 5, III = 3. // 示例 5: // 输入: "MCMXCIV" // 输出: 1994 // 解释: M = 1000, CM = 900, XC = 90, IV = 4. // var flect = { // 'I': 1, // 'V': 5, // 'X': 10, // 'L': 50, // 'C': 100, // 'D': 500, // 'M': 1000 // } // function romanToInt(str) { // if(str == null || str == '') return 0; // var strArr = str.split(''); // var num = flect[strArr[0]]; // var preNum = flect[strArr[0]]; // for(var i = 1; i < strArr.length; i ++) { // var curNum = flect[strArr[i]]; // if(curNum > preNum) { // num = num + curNum - preNum * 2; // } else { // num += curNum; // } // preNum = curNum; // } // return num; // } // console.log( romanToInt('CMIC') ); // console.log( romanToInt('MCMXCIV') ); // var romanToInt = function (s) { // let arr = s.split('') // let res = 0 // let obj = { // 'I': 1, // 'V': 5, // 'X': 10, // 'L': 50, // 'C': 100, // 'D': 500, // 'M': 1000 // } // for (let i = 0; i < arr.length; i++) { // if (i < arr.length - 1 && obj[arr[i]] < obj[arr[i + 1]]) { // res -= obj[arr[i]] // } else { // res += obj[arr[i]] // } // console.log(res, obj[arr[i]]); // } // return res // }; function roman2Int(str) { if(str == null || str == '') return 0; var strArr = str.split(''); var flect = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } var num = 0; for(var i = 0; i < strArr.length; i ++) { if(i < str.length && flect[strArr[i]] < flect[strArr[i + 1]]) { num -= flect[strArr[i]]; } else { num += flect[strArr[i]]; } } return num; } console.log( roman2Int('MCMXCIV') );<file_sep>/isBalanced.js // 110. 平衡二叉树 // 给定一个二叉树,判断它是否是高度平衡的二叉树。 // 本题中,一棵高度平衡二叉树定义为: // 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 // 示例 1: // 给定二叉树 [3,9,20,null,null,15,7] // 3 // / \ // 9 20 // / \ // 15 7 // 返回 true 。 // 示例 2: // 给定二叉树 [1,2,2,3,3,null,null,4,4] // 1 // / \ // 2 2 // / \ // 3 3 // / \ // 4 4 // 返回 false 。 // 方法一: function getDeep(root) { if(root == null) return 0; let numl = getDeep(root.left); let numr = getDeep(root.right); return Math.max(numl, numr) + 1; } function isBalanced(root) { if(root == null) return true; const leftDeep = getDeep(root.left); const rightDeep = getDeep(root.right); if(Math.abs(leftDeep - rightDeep) > 1) { return false; } return isBalanced(root.left) && isBalanced(root.right); } // 方法二: var isBalanced1 = function(root) { return checkBalanced(root) != -1; }; var checkBalanced = function(root){ if (root == null) return 0; let left = checkBalanced(root.left); if (left == -1) return -1; let right = checkBalanced(root.right); if (right == -1) return -1; return Math.abs(left - right) < 2 ? Math.max(left,right) + 1 : -1; }; <file_sep>/数组比较-查找/二分法/35. 搜索插入位置.js // 35. 搜索插入位置 // 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 // 你可以假设数组中无重复元素。 // 示例 1: // 输入: [1,3,5,6], 5 // 输出: 2 // 示例 2: // 输入: [1,3,5,6], 2 // 输出: 1 // 示例 3: // 输入: [1,3,5,6], 7 // 输出: 4 // 示例 4: // 输入: [1,3,5,6], 0 // 输出: 0 // 二分法: 因为是有序的所以可以直接使用二分法;同时因为需要判断出插入位置或者是所在位置,就可以直接去查找大于或等于的数字的下标即可 // 时间复杂度:O(logn),其中 nn 为数组的长度。二分查找所需的时间复杂度为 O(logn)。 // 空间复杂度:O(1)。我们只需要常数空间存放若干变量。 function twoSearch(arr, target) { var l = 0, r = arr.length - 1, res = arr.length while(l <= r) { // console.log(l, r) var mid = Math.floor((l + r) / 2) if(target <= arr[mid]) { res = mid r = mid - 1 } else { l = mid + 1 } } return res; } // console.log( twoSearch([1,3,5,6], 5) ) // console.log( twoSearch([1,3,5,6], 2) ) // console.log( twoSearch([1,3,5,6], 7) ) // console.log( twoSearch([1,3,5,6], 0) ) // console.log( twoSearch([1], 0) ) // 遍历: function searchFind(arr, target) { var len = arr.length for(var i = 0; i < len; i ++) { if(arr[i] === target) { return i } else if(arr[i] < target && target < arr[i + 1]) { return i + 1 } else if(i === len - 1 && arr[i] < target) { return len } else if(i === 0 && arr[i] > target) { return i } } } // console.log( searchFind([1,3,5,6], 5) ) // console.log( searchFind([1,3,5,6], 2) ) // console.log( searchFind([1,3,5,6], 7) ) // console.log( searchFind([1,3,5,6], 0) ) // console.log( searchFind([1], 0) )<file_sep>/orangesRotting.js // 994. 腐烂的橘子 // 在给定的网格中,每个单元格可以有以下三个值之一: // 值 0 代表空单元格; // 值 1 代表新鲜橘子; // 值 2 代表腐烂的橘子。 // 每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。 // 返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。 // 示例 1: // 输入:[[2,1,1],[1,1,0],[0,1,1]] // 输出:4 // 示例 2: // 输入:[[2,1,1],[0,1,1],[1,0,1]] // 输出:-1 // 解释:左下角的橘子(第 2 行, 第 0 列)永远不会腐烂,因为腐烂只会发生在 4 个正向上。 // 示例 3: // 输入:[[0,2]] // 输出:0 // 解释:因为 0 分钟时已经没有新鲜橘子了,所以答案就是 0 。 // 提示: // 1 <= grid.length <= 10 // 1 <= grid[0].length <= 10 // grid[i][j] 仅为 0、1 或 2 // 高阶版 function orangesRotting(grid) { if(grid == null || grid.length == 0 || grid[0].length == 0) return -1; const a = [0, 1, 0, -1]; const b = [1, 0, -1, 0]; let minute = 0; let fresh = 0; const R = grid.length; const C = grid[0].length; let queue = []; for(let r = 0; r < R; r ++) { for(let c = 0; c < C; c ++) { if(grid[r][c] == 2) { queue.push([r, c]); } else if(grid[r][c] == 1){ fresh ++; } } } while(queue.length != 0 && fresh) { let nextQueue = []; while(queue.length != 0) { let badOrange = queue.shift(); for(let k = 0; k < 4; k ++) { let i = badOrange[0] + a[k]; let j = badOrange[1] + b[k]; if(i >= 0 && i < R && j >= 0 && j < C && grid[i][j] == 1) { grid[i][j] = 2; nextQueue.push([i, j]); fresh --; } } } minute ++; queue = nextQueue; } return fresh == 0 ? minute : -1; } // 进阶版 function orangesRotting2(grid) { if(grid == null || grid.length == 0) return -1; // 用来扩大橘子的腐烂范围(上下左右) // eg: [2, 3]是腐烂的橘子 // 那么就可以可能使[2, 4],[2, 1],[1, 3],[3, 3]这四个位置上的新鲜橘子腐烂 var a = [-1, 0, 1, 0]; var b = [0, -1, 0, 1]; var ans = 0; var r = grid.length; var c = grid[0].length; var map = new Map(); var queue = new Array(); for(var i = 0; i < r; i ++) { for(var j = 0; j < c; j ++) { if(grid[i][j] == 2) { var code = i * c + j; // 把腐烂橘子排到队列的最后面 queue.push(code); map.set(code, 0); } } } while(queue.length != 0) { // 把队列的第一个给拿出来 var code = queue.shift(); // 计算出这个橘子的位置 i = Math.floor(code / c); j = code % c; for(var k = 0; k < 4; k ++) { // 寻找橘子上下左右的位置 var nI = i + a[k]; var nJ = j + b[k]; if(nI < r && nI >= 0 && nJ >= 0 && nJ < c && grid[nI][nJ] == 1) { // 使新鲜橘子腐烂 grid[nI][nJ] = 2; var ncode = nI * c + nJ; // 把腐烂橘子排到队列最后面 queue.push(ncode); map.set(ncode, map.get(code) + 1); ans = map.get(ncode) > ans ? map.get(ncode) : ans; } } } // 判断是否还有新鲜的橘子 for(var i = 0; i < r; i ++) { for(var j = 0; j < c; j ++) { if(grid[i][j] == 1) { return -1 } } } return ans; } // 简单版 function orangesRotting1(grid) { if(grid == 0 || grid.length == 0) return 0; var minute = 1; var flag = true; var r = grid.length; var c = grid[0].length; var note = new Array(r); for(var i = 0; i < r; i ++) { note[i] = new Array(c); for(var j = 0; j < c; j ++) { if(grid[i][j] == 2) { note[i][j] = minute; } else { note[i][j] = 0; } } } while(flag) { flag = false; for(var i = 0; i < r; i ++) { for(var j = 0; j < c; j ++) { if(grid[i][j] == 2 && note[i][j] == minute) { // console.log(i, j) if(i > 0 && grid[i - 1][j] == 1) { grid[i - 1][j] = 2; note[i - 1][j] = minute + 1; flag = true; } if(i < r - 1 && grid[i + 1][j] == 1) { grid[i + 1][j] = 2; note[i + 1][j] = minute + 1; flag = true; } if(j > 0 && grid[i][j - 1] == 1) { grid[i][j - 1] = 2; note[i][j - 1] = minute + 1; flag = true; } if(j < c - 1 && grid[i][j + 1] == 1) { grid[i][j + 1] = 2; note[i][j + 1] = minute + 1; flag = true; } } } } flag && minute ++; // console.log(note); } for(var i = 0; i < r; i ++) { for(var j = 0; j < c; j ++) { if(grid[i][j] == 1) { return -1; } } } return minute - 1; } // console.log( orangesRotting1([[2,1,1],[1,1,0],[0,1,1]]) ); // console.log( orangesRotting1([[2,1,1],[0,1,1],[1,0,1]]) ); <file_sep>/中等/228. 汇总区间.js // 228. 汇总区间 // 给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。 // 示例 1: // 输入: [0,1,2,4,5,7] // 输出: ["0->2","4->5","7"] // 解释: 0,1,2 可组成一个连续的区间; 4,5 可组成一个连续的区间。 // 示例 2: // 输入: [0,2,3,4,6,8,9] // 输出: ["0","2->4","6","8->9"] // 解释: 2,3,4 可组成一个连续的区间; 8,9 可组成一个连续的区间。 let summaryRanges = function(nums) { let start = 0 let end = 0 let ans = [] nums.push(Infinity) //我他妈直接抄小路因为我们要判断nums[i+1],只能遍历到nums.length-1。后续处理比较麻烦,不如直接给它加个无穷大 for(let i=0;i<nums.length-1;i++){ //扩大区间 end = i if(nums[i]+1!=nums[i+1]){ // 这里需要断开一个区间 if(start===end){ //相等,那就只保存这个数 ans.push(nums[end]+'') }else{ ans.push(nums[start]+'->'+nums[end]) } //重置新区间,新区间要从下一个开始 start = end = i+1 } } return ans }; var res = summaryRanges([0,1,2,4,5,7]) console.log(res); // 总结: // 区间查找,可以使用双指针来解决
5c4b014a588e0646024cb8fcc909be57835391f7
[ "JavaScript", "Markdown" ]
59
JavaScript
huangyangquang/Algorithm
66ff2015cff706ba7bdbc435ddd8e42b06fb7ac6
2b31bb19b20930e5ed69acca9073d9d2df1c6fda
refs/heads/master
<file_sep><nav class="nav"> <ul class="nav__list container"> <?php foreach ($categories_list as $key): ?> <li class="nav__item"> <a href="all-lots.php?category=<?= $key['id']; ?>"><?= $key['category_name']; ?></a> </li> <?php endforeach; ?> </ul> </nav> <file_sep><?php include_once('top-nav.php'); ?> <section class="lot-item container"> <h2><?= htmlspecialchars($lot_data['lot_name']); ?></h2> <div class="lot-item__content"> <div class="lot-item__left"> <div class="lot-item__image"> <img src="img/<?= $lot_data['image']; ?>" width="730" height="548" alt="<?= htmlspecialchars($lot_data['lot_name']); ?>"> </div> <p class="lot-item__category">Категория: <span><?= $lot_data['category_name']; ?></span></p> <p class="lot-item__description"><?= htmlspecialchars($lot_data['description']); ?></p> </div> <div class="lot-item__right"> <?php if (isset($_SESSION['user'])): $spend_time = strtotime($lot_data['end_date']); if ($lot_data['users_id'] !== $_SESSION['user']['id'] && !$total_count && time() < $spend_time):?> <div class="lot-item__state"> <div class="lot-item__timer timer"> <?= time_to_end($lot_data['end_date']) ?> </div> <div class="lot-item__cost-state"> <div class="lot-item__rate"> <span class="lot-item__amount">Текущая цена</span> <span class="lot-item__cost"><?= htmlspecialchars($current_price); ?></span> </div> <div class="lot-item__min-cost"> Мин. ставка <span><?= htmlspecialchars($lot_data['lot_step']); ?></span> </div> </div> <form class="lot-item__form" action="" method="post"> <p class="lot-item__form-item"> <label for="cost">Ваша ставка</label> <?php $placeholder = isset($error_bet) ? $error_bet : htmlspecialchars($lot_data['lot_step'] + $current_price); ?> <input id="cost" type="number" name="cost" placeholder="<?= $placeholder; ?>"> </p> <button type="submit" class="button">Сделать ставку</button> </form> </div> <?php endif; ?> <div class="history"> <?php $bet_count = count($bet_list); ?> <h3>История ставок (<span><?= $bet_count; ?></span>)</h3> <table class="history__list"> <?php foreach ($bet_list as $key): ?> <tr class="history__item"> <td class="history__name"><?= htmlspecialchars($key['user_name']); ?></td> <td class="history__price"><?= htmlspecialchars(transform_format($key['amount'])); ?></td> <td class="history__time"><?= time_left($key['bet_date']); ?></td> </tr> <?php endforeach; ?> </table> </div> <?php endif; ?> </div> </div> </section> <file_sep><?php session_start(); require_once('db.php'); require_once('functions.php'); $title = 'Регистрация'; //вызовы функции $categories_list = get_data_db($link, $categories_sql, 'list'); $content = include_template('reg.php', compact('categories_list', 'reg')); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['reg']) and !empty($_POST['reg'])) { $reg = $_POST['reg']; } $dict = [ 'email' => 'Почта', 'password' => '<PASSWORD>', 'name' => 'Имя', 'contacts' => 'Контакт', 'file' => 'Изображение' ]; $is_register = register($_POST['reg'], $link); if ($is_register === true) { // редирект header("Location: /login.php"); } else { if (count($is_register) > 0) { $content = include_template('reg.php', compact('categories_list', 'reg', 'is_register', 'dict')); } } } $layout_content = include_template('layout.php', compact('content', 'categories_list', 'title')); print($layout_content); <file_sep><?php session_start(); $title = "YetiCave"; date_default_timezone_set("Europe/Moscow"); require_once('db.php'); require_once('functions.php'); require_once('getwinner.php'); $lots_list_sql = 'SELECT lots.id, creation_date, end_date, lot_name, image, start_price, category_name FROM lots JOIN categories ON categories.id = lots.categories_id ORDER BY creation_date DESC'; $categories_list = get_data_db($link, $categories_sql, 'list'); $lots_list = get_data_db($link, $lots_list_sql, 'list'); $content = include_template('index.php', compact('lots_list', 'categories_list')); $layout_content = include_template('layout.php', compact('content', 'categories_list', 'title')); print($layout_content); <file_sep><?php // установка локальной зоны date_default_timezone_set("Europe/Moscow"); //запрос для вывода категорий по всем вложенным страницам $categories_sql = 'SELECT id, category_name, class_name FROM categories'; /** * Вставляет переменные в шаблон * @param integer $name название шаблона * @param array $data данные для шаблона * @return string возвращает щаблон с данными */ function include_template($name, $data) { $name = 'templates/' . $name; $result = ''; if (!file_exists($name)) { return $result; } ob_start(); extract($data); require $name; $result = ob_get_clean(); return $result; } /** * Фрпматирование, округление, деление по разрядам чисел, добавление знака ₽ * @param integer $number Входное число * @return string отформатированная сторка */ function transform_format($number) { $integer = ceil($number); if ($integer > 1000) { $integer = number_format($integer, 0, '', ' '); } return $integer .= ' ₽'; } // функция времени существования лота /** * Вычисление сколько осталось времени до входящей даты * @param datetime $lot_time_end Входное время * @return string возвращаемое время */ function time_to_end($lot_time_end) { if (strtotime($lot_time_end) < time()) { return '00:00'; } $dt_end = new DateTime($lot_time_end); $remain = $dt_end->diff(new DateTime()); if ($remain->d > 0) { return $remain->d . ' дней'; } else { if ($remain->h > 0) { return $remain->h . ' часов'; } else { if ($remain->i > 0) { return $remain->i . ' мин.'; } else { return $remain->s . ' сек.'; } } } } // функция вывода ошибок /** * Вывод ошибок * @param string $content контент * @param string $error ошибки */ function show_error(&$content, $error) { $content = include_template('error.php', ['error' => $error]); } /** * Подключение к БД * @param mysqli $link Ресурс соединения * @param string $sql SQL - запрос * @return object Объект соединения */ function get_link_db($link, $sql) { if (!isset($link)) { $error = mysqli_connect_error(); show_error($content, $error); } else { $result = mysqli_query($link, $sql); if (!$result) { $error = mysqli_error($link); show_error($content, $error); } else { return $result; } } } /** * Получения данных из БД * @param mysqli $link Ресурс соединения * @param string $sql SQL - запрос * @param array $flag Ключи: list - маиив данных, item - одна запись из таблицы * @return array Список или одну запись */ function get_data_db($link, $sql, $flag) { $link_result = get_link_db($link, $sql); if ($flag === 'list') { return $list = mysqli_fetch_all($link_result, MYSQLI_ASSOC); } if ($flag === 'item') { return $list = mysqli_fetch_assoc($link_result); } } /** * Создает подготовленное выражение на основе готового SQL запроса и переданных данных * * @param mysqli $link Ресурс соединения * @param string $sql SQL запрос с плейсхолдерами вместо значений * @param array $data Данные для вставки на место плейсхолдеров * * @return mysqli_stmt Подготовленное выражение */ function db_get_prepare_stmt($link, $sql, $data = []) { $stmt = mysqli_prepare($link, $sql); if ($stmt === false) { die("<pre>MYSQL ERROR:" . mysqli_error($link) . PHP_EQL . $sql . "</pre>"); } if ($data) { $types = ''; $stmt_data = []; foreach ($data as $value) { $type = null; if (is_int($value)) { $type = 'i'; } else { if (is_string($value)) { $type = 's'; } else { if (is_double($value)) { $type = 'd'; } } } if ($type) { $types .= $type; $stmt_data[] = $value; } } $values = array_merge([$stmt, $types], $stmt_data); $func = 'mysqli_stmt_bind_param'; $func(...$values); } return $stmt; } /** * Валидации * @param array $data массив данных для валидации * @param mysqli $link Ресурс соединения * @return string имя файла или ошибку валидации */ function validate_register($data, $link) { $required = ['email', 'password', 'name', 'contacts']; $errors = []; foreach ($required as $key) { if (empty($data[$key])) { $errors[$key] = 'Это поле надо заполнить'; } } if (!empty($data['email'])) { $email = mysqli_real_escape_string($link, $data['email']); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = 'Email должен быть корректным'; } else { $sql = "SELECT id FROM users WHERE email = '$email'"; $res = mysqli_query($link, $sql); if (mysqli_num_rows($res) > 0) { $errors['email'] = 'Пользователь с этим email уже зарегистрирован'; } } } if (!empty($_FILES['jpg_image']['name'])) { $tmp_name = $_FILES['jpg_image']['tmp_name']; $finfo = finfo_open(FILEINFO_MIME_TYPE); $file_type = finfo_file($finfo, $tmp_name); if (!in_array($file_type, ['image/jpeg', 'image/png'])) { $errors['file'] = 'Загрузите картинку в формате JPEG или PNG'; } else { $filename = uniqid() . '.jpg'; move_uploaded_file($tmp_name, 'img/' . $filename); } } else { $filename = ''; } if (empty($errors)) { return $filename; } else { return $errors; } } /** * Регистрации * @param array $data массив данных для валидации * @param mysqli $link Ресурс соединения * @return string true или ошибку валидации */ function register($data, $link) { $validate = validate_register($data, $link); if (!is_array($validate)) { $data['path'] = $validate; $password = password_hash($data['password'], PASSWORD_DEFAULT); $sql = 'INSERT INTO users (registration_date, email, user_name, password, avatar, contacts) VALUES (NOW(), ?, ?, ?, ?, ?)'; $stmt = db_get_prepare_stmt($link, $sql, [$data['email'], $data['name'], $password, $data['path'], $data['contacts']]); $res = mysqli_stmt_execute($stmt); return true; } else { return $validate; } } /** * Формат времени для списка ставок * @param datetime $time_in время в любом формате * @return string Форматированное время */ function time_left($time_in) { $time = strtotime($time_in); $month = date('n', $time); // присваиваем месяц от timestamp $day = date('j', $time); $year = date('Y', $time); $hour = date('G', $time); $min = date('i', $time); $date = $day . '.' . $month . '.' . $year . ' в ' . $hour . ':' . $min; $diff = time() - $time; // от текущего времени отнимает время ставки (в секундах) if ($diff < 59) { // если разница меньше 59сек return $diff . " сек. назад"; //то возвращаем разницу с "сек. назад" } elseif ($diff / 60 > 1 and $diff / 60 < 59) { // если от 1 до 60 минут return round($diff / 60) . " мин. назад"; //то возвращаем разницу } elseif ($diff / 3600 > 1 and $diff / 3600 < 23) { // если от 1 до 23 часов return round($diff / 3600) . " час. назад"; } else { return $date; } } /** * Определяет количество ставок пользователя * @param array $bets_array массив ставок * @param integer $user_id ID пользователя * @return integer количество ставок */ function count_users_bets($bets_array, $user_id) { $count = 0; foreach ($bets_array as $key) { if ($key['users_id'] === $user_id) { $count++; } } return $count; } /** * Разрезает массив * @param array $array массив лотов * @param integer $items_on_page Колтчество лотов на странице * @param integer $current_page Текущая страница * @return array Часть массива */ function get_array_slice($array, $items_on_page, $current_page) { $offset = ($current_page - 1) * $items_on_page; $result = array_slice($array, $offset, $items_on_page); return $result; } /** * Проверяет пользователя и его пароль * @param mysqli $link Ресурс соединения * @param integer $login Полученный логин * @param integer $password Полученный пароль * @return array Ошибку проверки */ function user_verify ($link, $login, $password) { $email = mysqli_real_escape_string($link, $login); $sql = "SELECT * FROM users WHERE email = '$email'"; $result = mysqli_query($link, $sql); $error =[]; $user = $result ? mysqli_fetch_array($result, MYSQLI_ASSOC) : null; if ($user) { if (password_verify($password, $user['password'])) { $_SESSION['user'] = $user; } else { $error['password'] = '<PASSWORD>'; return $error; } } else { $error['email'] = 'Такой пользователь не найден'; return $error; } } <file_sep><?php include('top-nav.php'); ?> <?php $class_name = isset($errors) ? "form--invalid" : ""; ?> <form class="form form--add-lot container <?= $class_name; ?>" action="" method="post" enctype="multipart/form-data"> <!-- form--invalid --> <h2>Добавление лота</h2> <div class="form__container-two"> <?php $class_name = isset($errors['name']) ? "form__item--invalid" : ""; $value = isset($lot['name']) ? $lot['name'] : ""; ?> <div class="form__item <?= $class_name; ?>"> <label for="lot-name">Наименование</label> <input id="lot-name " type="text" name="lot[name]" placeholder="Введите наименование лота" value="<?= $value; ?>" required> <span class="form__error">Введите наименование лота</span> </div> <?php $class_name = isset($errors['category']) ? "form__item--invalid" : ""; $value = isset($lot['category']) ? $lot['category'] : ""; ?> <div class="form__item <?= $class_name; ?>"> <label for="category">Категория</label> <select id="category" name="lot[category]" required> <option value=""> Выбирете категорию</option> <?php foreach ($categories_list as $key): ?> <option value="<?= $key['id'] ?>" <?= (isset($lot) and isset($lot['category']) and $lot['category'] == $key['id']) ? 'selected' : '' ?>><?= $key['category_name']; ?></option> <?php endforeach; ?> </select> <span class="form__error">Выберите категорию</span> </div> </div> <?php $class_name = isset($errors['message']) ? "form__item--invalid" : ""; $value = isset($lot['message']) ? $lot['message'] : ""; ?> <div class="form__item form__item--wide <?= $class_name; ?>"> <label for="message">Описание</label> <textarea id="message" name="lot[message]" placeholder="Напишите описание лота" required><?= $value; ?></textarea> <span class="form__error">Напишите описание лота</span> </div> <div class="form__item form__item--file"> <!-- form__item--uploaded --> <label>Изображение</label> <div class="preview"> <button class="preview__remove" type="button">x</button> <div class="preview__img"> <img src="img/avatar.jpg" width="113" height="113" alt="Изображение лота"> </div> </div> <div class="form__input-file"> <input class="visually-hidden" type="file" name="jpg_image" id="photo2" value=""> <label for="photo2"> <span>+ Добавить</span> </label> </div> </div> <div class="form__container-three"> <?php $class_name = isset($errors['price']) ? "form__item--invalid" : ""; $value = isset($lot['price']) ? $lot['price'] : ""; ?> <div class="form__item form__item--small <?= $class_name; ?>"> <label for="lot-rate">Начальная цена</label> <input id="lot-rate" type="number" name="lot[price]" placeholder="0" value="<?= $value; ?>" required> <span class="form__error">Введите начальную цену</span> </div> <?php $class_name = isset($errors['step']) ? "form__item--invalid" : ""; $value = isset($lot['step']) ? $lot['step'] : ""; ?> <div class="form__item form__item--small <?= $class_name; ?>"> <label for="lot-step">Шаг ставки</label> <input id="lot-step" type="number" name="lot[step]" placeholder="0" value="<?= $value; ?>" required> <span class="form__error">Введите шаг ставки</span> </div> <?php $class_name = isset($errors['date']) ? "form__item--invalid" : ""; $value = isset($lot['date']) ? $lot['date'] : ""; ?> <div class="form__item <?= $class_name; ?>"> <label for="lot-date">Дата окончания торгов</label> <input class="form__input-date" id="lot-date" type="date" name="lot[date]" value="<?= $value; ?>" required> <span class="form__error">Введите дату завершения торгов</span> </div> </div> <!-- начало вставки--> <?php if (isset($errors)): ?> <span class="form__error form__error--bottom">Пожалуйста, исправьте ошибки в форме.</span> <ul> <?php foreach ($errors as $err => $val): ?> <li><strong><?= $dict[$err]; ?>:</strong> <?= $val; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <!-- конец--> <button type="submit" class="button">Добавить лот</button> </form> <file_sep><?php session_start(); require_once('db.php'); require_once('functions.php'); //вызовы функции показа списка категорий $categories_list = get_data_db($link, $categories_sql, 'list'); $content = include_template('search.php', compact('categories_list')); $error = ''; $search = trim($_GET['search']) ?? ''; $cur_page = intval($_GET['page'] ?? 1); $offset = intval($_GET['offset'] ?? 0); // проверяем пустой ли запрос if (!strlen($search)) { $pages_count = 0; $error = 'Не ввели поисковый запрос'; } else { // если не пустой создаем sql - запрос $search_sql = "SELECT lots.id, creation_date, end_date, lot_name, image, start_price, category_name FROM lots JOIN categories ON categories.id = lots.categories_id WHERE MATCH (lot_name, description) AGAINST (?) ORDER BY creation_date DESC"; // проверка подключения к БД $result = get_link_db($link, $search_sql); // подготавливаем и выполняем запрос if (!$result) { $stmt = db_get_prepare_stmt($link, $search_sql, [$search]); mysqli_stmt_execute($stmt); $link_result = mysqli_stmt_get_result($stmt); } // проверяем кол-во записей по запросу $all_rows = mysqli_num_rows($link_result); // если есть записи предаем их в массив if ($all_rows) { $search_list = mysqli_fetch_all($link_result, MYSQLI_ASSOC); // пагинация поиска $page_items = 6; //вызываем функцию обрезания массива / на входе массив, кол-во элементов на странице, текущая страница $slice_list = get_array_slice($search_list, $page_items, $cur_page); $pages_count = ceil($all_rows / $page_items); $pages = range(1, $pages_count); } else { $error = 'Ничего не найдено'; } } if (!$error) { $title = $search; $content = include_template('search.php', compact('categories_list', 'slice_list', 'search', 'error', 'pages', 'pages_count', 'cur_page')); } else { $title = $error; $content = include_template('search.php', compact('categories_list', 'error')); } $layout_content = include_template('layout.php', compact('content', 'categories_list', 'title')); print($layout_content); <file_sep><?php session_start(); require_once('db.php'); require_once('functions.php'); $title = 'Вход'; $categories_list = get_data_db($link, $categories_sql, 'list'); $content = include_template('login.php', compact('categories_list')); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['login']) and !empty($_POST['login'])) { $login = $_POST['login']; } $required = ['email', 'password']; $dict = ['email' => 'Почта', 'password' => '<PASSWORD>']; $errors = []; foreach ($required as $key) { if (empty($login[$key])) { $errors[$key] = 'Это поле надо заполнить'; } } if (!count($errors)) { $errors = user_verify($link, $login['email'], $login['password']); } if (count($errors) > 0) { $content = include_template('login.php', compact('categories_list', 'login', 'errors', 'dict')); } else { header("Location: /login.php"); exit(); } } else { if (isset($_SESSION['user']) and !empty($_SESSION['user'])) { $username = $_SESSION['user']['user_name']; header("Location: /"); } else { $content = include_template('login.php', compact('categories_list')); } } $layout_content = include_template('layout.php', compact('content', 'categories_list', 'title')); print($layout_content); <file_sep>CREATE DATABASE yeticave DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci; USE yeticave; CREATE TABLE categories ( id INT AUTO_INCREMENT PRIMARY KEY, category_name CHAR(64), class_name CHAR(64) ); CREATE TABLE lots ( id INT AUTO_INCREMENT PRIMARY KEY, creation_date DATETIME, lot_name CHAR(128), description TEXT, image CHAR(128), start_price INT(16), end_date DATETIME, lot_step CHAR(128), users_id INT(8), winners_id INT(8), categories_id INT(8) ); CREATE FULLTEXT INDEX search_lot ON lots(lot_name, description) CREATE TABLE bets ( id INT AUTO_INCREMENT PRIMARY KEY, bet_date DATETIME, amount INT(16), users_id INT(8), lots_id INT(8) ); CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, registration_date DATETIME, email CHAR(64), user_name CHAR(128), password CHAR(64), avatar CHAR(128), contacts TEXT ); <file_sep><?php include('top-nav.php'); ?> <main class="container"> <div class="content__main-col"> <header class="content__header"> <h2 class="content__header-text">Добро пожаловать, <?= $username; ?></h2> </header> </div> </main> <file_sep><?php include('top-nav.php'); ?> <?php $class_name = isset($errors) ? "form--invalid" : ""; ?> <form class="form container <?= $class_name; ?>" action="" method="post"> <!-- form--invalid --> <h2>Вход</h2> <?php $class_name = isset($errors['email']) ? "form__item--invalid" : ""; $value = isset($reg['email']) ? $reg['email'] : ""; ?> <div class="form__item <?= $class_name; ?>"> <!-- form__item--invalid --> <label for="email">E-mail*</label> <input id="email" type="text" name="login[email]" placeholder="Введите e-mail" value="<?= $value; ?>"> <span class="form__error">Введите e-mail</span> </div> <?php $class_name = isset($errors['password']) ? "form__item--invalid" : ""; $value = isset($reg['password']) ? $reg['password'] : ""; ?> <div class="form__item form__item--last <?= $class_name; ?>"> <label for="password">Пароль*</label> <input id="password" type="text" name="login[password]" placeholder="<PASSWORD> <PASSWORD>" value="<?= $value; ?>"> <span class="form__error">Введите пароль</span> </div> <!-- начало вставки--> <?php if (isset($errors)): ?> <span class="form__error form__error--bottom">Пожалуйста, исправьте ошибки в форме.</span> <ul> <?php foreach ($errors as $err => $val): ?> <li><strong><?= $dict[$err]; ?>:</strong> <?= $val; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <!-- конец--> <button type="submit" class="button">Войти</button> </form> <file_sep><?php session_start(); if (isset($_GET['lot']) and !empty($_GET['lot'])) { $lot_show = intval($_GET['lot']); } require_once('db.php'); require_once('functions.php'); // Запросы $lot_data_sql = 'SELECT lots.id, creation_date, lot_name, description, image, start_price, end_date, lot_step, users_id, category_name FROM lots JOIN categories ON categories.id = lots.categories_id WHERE lots.id = ' . $lot_show; $bet_sql = 'SELECT bets.id, bet_date, amount, users_id, user_name FROM bets JOIN users ON users.id = bets.users_id WHERE lots_id = ' . $lot_show . ' ORDER BY bet_date DESC'; $max_price_sql = 'SELECT MAX(amount) FROM bets WHERE lots_id = ' . $lot_show . ''; //вызовы функции список категорий, данные для лота, список ставок, максимальная ставка $categories_list = get_data_db($link, $categories_sql, 'list'); $lot_data = get_data_db($link, $lot_data_sql, 'item'); $bet_list = get_data_db($link, $bet_sql, 'list'); $max_price = get_data_db($link, $max_price_sql, 'item'); $error = ''; // узнаем id залогиненого пользователя if (isset($_SESSION['user']) and !empty($_SESSION['user'])) { $user_id = $_SESSION['user']['id']; // вызов функции посчета ставок по залогиненому id в отдельном лоте $total_count = count_users_bets($bet_list, $user_id); } // выделяем из возвращенного массива цену и шаг if (isset($lot_data)) { $start_price = $lot_data['start_price']; $step = $lot_data['lot_step']; $max = $max_price['MAX(amount)']; } $current_price = 0; if ($max > $start_price) { $current_price = $max; } else { $current_price = $start_price; } if (isset($_SESSION['user']['id']) and !empty($_SESSION['user']['id'])) { $user_id = $_SESSION['user']['id']; } // проверяем данные в массиве POST if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['cost']) and !empty($_POST['cost'])) { $cost = $_POST['cost']; } if (empty($cost)) { $error_bet = 'Надо заполнить'; } else {//если не пуст $error_bet = ''; if (!filter_var($cost, FILTER_VALIDATE_INT)) { $error_bet = 'Это не число'; $flag = 0; } else { $flag = 1; } if ($cost < $current_price + $step and $flag) { //проверяем что больше чем цена + шаг $error_bet = 'Увеличте ставку'; } } if (!$error_bet) { $bet_sql = 'INSERT INTO bets (bet_date, amount, users_id, lots_id) VALUES (NOW(), ?, ' . $user_id . ', ' . $lot_show . ')'; //подготавливаем выражение и выполняем $stmt = db_get_prepare_stmt($link, $bet_sql, [$cost]); $result = mysqli_stmt_execute($stmt); if ($result) { header("Location: lot.php?lot=" . $lot_show); } else { $content = include_template('error.php', ['error' => mysqli_error($link)]); } } } if (!isset($lot_data)) { http_response_code(404); $error = 'Ошибка 404'; } else { $content = include_template('lot.php', compact('lot_data', 'bet_list', 'categories_list', 'error_bet', 'total_count', 'current_price')); } if ($error) { $content = include_template('error.php', compact('error')); } if (isset($lot_data['lot_name'])) { $title = $lot_data['lot_name']; } $layout_content = include_template('layout.php', compact('content', 'categories_list', 'title')); print($layout_content); <file_sep>-- Добавление данных USE yeticave; INSERT INTO categories SET category_name = 'Доски и лыжи', class_name = 'boards'; INSERT INTO categories SET category_name = 'Крепления', class_name = 'attachment'; INSERT INTO categories SET category_name = 'Ботинки', class_name = 'boots'; INSERT INTO categories SET category_name = 'Одежда', class_name = 'clothing'; INSERT INTO categories SET category_name = 'Инструменты', class_name = 'tools'; INSERT INTO categories SET category_name = 'Разное', class_name = 'other'; INSERT INTO lots SET creation_date = '2018-09-24 21:10:01', lot_name = '2014 Rossignol District Snowboard', description = 'Описание лота', image = 'lot-1.jpg', start_price = 10999, end_date = '2018-09-25', lot_step = 5, users_id = 1, winners_id = 1, categories_id = 1; INSERT INTO lots SET creation_date = '2018-09-22 21:10:01', lot_name = 'DC Ply Mens 2016/2017 Snowboard', description = 'Легкий маневренный сноуборд, готовый дать жару в любом парке, растопив снег мощным щелчкоми четкими дугами. Стекловолокно Bi-Ax, уложенное в двух направлениях, наделяет этот снаряд отличной гибкостью и отзывчивостью, а симметричная геометрия в сочетании с классическим прогибом кэмбер позволит уверенно держать высокие скорости. А если к концу катального дня сил совсем не останется, просто посмотрите на Вашу доску и улыбнитесь, крутая графика от <NAME> еще никого не оставляла равнодушным.', image = 'lot-2.jpg', start_price = 159999, end_date = '2018-09-25', lot_step = 3, users_id = 2, winners_id = 2, categories_id = 1; INSERT INTO lots SET creation_date = '2018-09-22 21:10:01', lot_name = 'Крепления Union Contact Pro 2015 года размер L/XL', description = 'Описание лота3', image = 'lot-3.jpg', start_price = 8000, end_date = '2018-09-25', lot_step = 3, users_id = 2, winners_id = 2, categories_id = 2; INSERT INTO lots SET creation_date = '2018-09-22 21:10:01', lot_name = 'Ботинки для сноуборда DC Mutiny Charocal', description = 'Описание лота4', image = 'lot-4.jpg', start_price = 10999, end_date = '2018-09-25', lot_step = 3, users_id = 2, winners_id = 2, categories_id = 3; INSERT INTO lots SET creation_date = '2018-09-22 21:10:01', lot_name = 'Куртка для сноуборда DC Mutiny Charocal', description = 'Описание лота5', image = 'lot-5.jpg', start_price = 7500, end_date = '2018-09-25', lot_step = 3, users_id = 2, winners_id = 2, categories_id = 4; INSERT INTO lots SET creation_date = '2018-09-22 21:10:01', lot_name = '<NAME>', description = 'Описание лота6', image = 'lot-6.jpg', start_price = 5400, end_date = '2018-09-25', lot_step = 3, users_id = 2, winners_id = 2, categories_id = 6; INSERT INTO bets SET bet_date = '2018-09-22 21:10:01', amount = 1000, users_id = 1, lots_id = 1; INSERT INTO bets SET bet_date = '2018-09-23 23:10:01', amount = 2000, users_id = 2, lots_id = 2; INSERT INTO users SET registration_date = '2018-09-22 21:10:01', email = '<EMAIL>', user_name = 'Константин', password = '<PASSWORD>', avatar = 'avatar.jpg', contacts = 'тел 79183304040'; INSERT INTO users SET registration_date = '2018-09-22 21:10:02', email = '<EMAIL>', user_name = 'Сергей', password = '<PASSWORD>', avatar = 'avatar-2.jpg', contacts = 'тел 7918123456'; -- SQL- запросы -- получить все категории SELECT * FROM categories; /* получить самые новые, открытые лоты. Каждый лот должен включать название, стартовую цену, ссылку на изображение, цену, количество ставок, название категории */ SELECT lots.id, lots.lot_name, lots.description, lots.start_price, categories.category_name, lots.image, COUNT(bets.id) AS count_bets FROM lots JOIN bets ON bets.lots_id = lots.id JOIN categories ON lots.categories_id = categories.id GROUP BY lots.id ORDER BY creation_date DESC; -- показать лот по его id. Получите также название категории, к которой принадлежит лот SELECT creation_date, lot_name, description, image, start_price, end_date, lot_step, category_name FROM lots JOIN categories ON categories.id = lots.id WHERE lots.id = 1; -- обновить название лота по его идентификатору UPDATE lots SET lot_name = 'Название лота 3' WHERE id = 1; -- получить список самых свежих ставок для лота по его идентификатору SELECT * FROM bets WHERE lots_id = 1 ORDER BY bet_date DESC; <file_sep><main class="container"> <div class="content__main-col"> <header class="content__header"> <h2 class="content__header-text"><?= $error; ?></h2> </header> </div> </main> <file_sep><h1>Поздравляем с победой</h1><p>Здравствуйте, <?= $user; ?></p><p>Ваша ставка для лота <a href="http://yeticave/lot.php?lot=<?= $lot; ?>"><?= $lot_name; ?></a> победила.</p><p>Перейдите по ссылке <a href="http://yeticave/my-lots.php">мои ставки</a>, чтобы связаться с автором объявления</p> <small>Интернет Аукцион "YetiCave"</small> <file_sep><?php include('top-nav.php'); ?> <div class="container"> <section class="lots"> <?php if ($error): ?> <h2><span><?= $error; ?></span></h2> <?php else: ?> <h2>Результаты поиска по запросу «<span><?= $search; ?></span>»</h2> <ul class="lots__list"> <?php foreach ($slice_list as $key): ?> <li class="lots__item lot"> <div class="lot__image"> <img src="img/<?= $key['image']; ?>" width="350" height="260" alt=""> </div> <div class="lot__info"> <span class="lot__category"><?= $key['category_name']; ?></span> <h3 class="lot__title"><a class="text-link" href="lot.php?lot=<?= htmlspecialchars($key['id']); ?>"><?= htmlspecialchars($key['lot_name']); ?></a> </h3> <div class="lot__state"> <div class="lot__rate"> <span class="lot__amount">Стартовая цена</span> <span class="lot__cost"><?= transform_format(htmlspecialchars($key['start_price'])); ?></span> </div> <div class="lot__timer timer"><?= time_to_end($key['end_date']); ?> </div> </div> </div> </li> <?php endforeach; ?> </ul> </section> <?php if ($pages_count > 1): ?> <?= include_template('pagination_block2.php', [ 'pages' => $pages, 'pages_count' => $pages_count, 'cur_page' => $cur_page, 'search' => $search ]); ?><?php endif; ?> <?php endif; ?> </div> <file_sep><?php session_start(); require_once('db.php'); require_once('functions.php'); //вызовы функции $categories_list = get_data_db($link, $categories_sql, 'list'); $content = include_template('all-lots.php', compact('categories_list')); // ждем запроса с id категории $category_id = intval($_GET['category'] ?? 1); $cur_page = intval($_GET['page'] ?? 1); // если данных не пришло page = 1 $page_items = 6; // кол-во лотов на странице if ($category_id) { // добываем нужное нам имя из таблицы категорий $category_result = mysqli_query($link, 'SELECT category_name FROM categories WHERE id =' . $category_id . ''); $category_name = mysqli_fetch_assoc($category_result)['category_name']; $title = 'Все лоты в категории «' . $category_name . '»'; $category_sql = 'SELECT lots.id, creation_date, end_date, lot_name, image, start_price, category_name FROM lots JOIN categories ON categories.id = lots.categories_id WHERE lots.categories_id = ? ORDER BY creation_date DESC'; $stmt = db_get_prepare_stmt($link, $category_sql, [$category_id]); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $lots_list = mysqli_fetch_all($result, MYSQLI_ASSOC); $error = ''; // пагинация поиска $page_items = 6; $count = 0; //проверка времени истечения foreach ($lots_list as $key) { $time = time_to_end($key['end_date']); if ($time !== '00:00') { $count++; } } $all_rows = $count; $slice_list = get_array_slice($lots_list, $page_items, $cur_page); $pages_count = ceil($all_rows / $page_items); $pages = range(1, $pages_count); if (count($slice_list) > 0) { $content = include_template('all-lots.php', compact('slice_list', 'categories_list', 'pages', 'pages_count', 'cur_page', 'category_id', 'category_name')); } else { $error = 'Нет запрашиваемого документа'; } } else { $error = 'Документ не найден'; } if ($error) { http_response_code(404); $content = include_template('error.php', compact('error')); } $layout_content = include_template('layout.php', compact('content', 'categories_list', 'title')); print($layout_content); <file_sep><?php session_start(); require_once('db.php'); require_once('functions.php'); $title = 'Мои ставки'; if (isset($_SESSION['user']['id']) and !empty($_SESSION['user']['id'])) { $user_id = $_SESSION['user']['id']; } //вызовы функции $categories_list = get_data_db($link, $categories_sql, 'list'); $bet_sql = 'SELECT bets.id, bet_date, end_date, amount, lots.id as lot_id, winners_id, lot_name, image, category_name, contacts FROM bets JOIN lots ON lots.id = bets.lots_id JOIN categories ON categories.id = categories_id JOIN users ON users.id = bets.users_id WHERE bets.users_id = ' . $user_id . ' ORDER BY bet_date ASC'; $bet_list = get_data_db($link, $bet_sql, 'list'); // var_dump($bet_list); $content = include_template('my-lots.php', compact('categories_list', 'bet_list', 'user_id')); $layout_content = include_template('layout.php', compact('content', 'categories_list', 'title')); print($layout_content); <file_sep><?php session_start(); if (!isset($_SESSION['user'])) { http_response_code(403); header("Location: /add.php"); } require_once('db.php'); require_once('functions.php'); $title = 'Добавление лота'; //вызовы функции $categories_list = get_data_db($link, $categories_sql, 'list'); $content = include_template('add.php', compact('categories_list')); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['lot']) and !empty($_POST['lot'])) { $lot = $_POST['lot']; } $required = ['name', 'message', 'category', 'price', 'step', 'date']; $dict = [ 'name' => 'Наименование', 'message' => 'Описание', 'category' => 'Категория', 'price' => 'Начальная цена', 'step' => 'Шаг ставки', 'date' => 'Дата окончания торгов', 'file' => 'Изображение' ]; $errors = []; // проверка числа $required_int = ['price', 'step']; foreach ($required_int as $key) { if (!filter_var($lot[$key], FILTER_VALIDATE_INT)) { $errors[$key] = 'Это не число'; } } // проверка на заполнение foreach ($required as $key) { if (empty($lot[$key])) { $errors[$key] = 'Это поле надо заполнить'; } } // проверка файла if (!empty($_FILES['jpg_image']['name'])) { $tmp_name = $_FILES['jpg_image']['tmp_name']; $file_type = mime_content_type($tmp_name); if (!in_array($file_type, ['image/jpeg', 'image/png'])) { $errors['file'] = 'Загрузите картинку в формате JPEG или PNG'; } else { $filename = uniqid() . '.jpg'; move_uploaded_file($tmp_name, 'img/' . $filename); $lot['path'] = $filename; } } else { $errors['file'] = 'Вы не загрузили файл'; } //проверка даты if (isset($lot['date']) and (strtotime($lot['date']) < (time() + (60 * 60 * 24)))) { $errors['date'] = 'Дата должна быть больше'; } if (count($errors) > 0) { $content = include_template('add.php', compact('categories_list', 'lot', 'errors', 'dict')); } else { // Если не ошибок добавляем в базу if (isset($_SESSION['user']['id']) and !empty($_SESSION['user']['id'])) { $user_id = $_SESSION['user']['id']; } $sql = 'INSERT INTO lots (creation_date, categories_id, lot_name, description, image, start_price, lot_step, users_id, end_date) VALUES (NOW(), ?, ?, ?, ?, ?, ?, ' . $user_id . ', ?)'; $lot_data = $lot['date'] . ' ' . date("H:i:s"); $stmt = db_get_prepare_stmt($link, $sql, [ $lot['category'], $lot['name'], $lot['message'], $lot['path'], $lot['price'], $lot['step'], $lot_data ]); $result = mysqli_stmt_execute($stmt); // выполняем подготовленное выражение if ($result) { $lot_id = mysqli_insert_id($link); //присваивает последний, добавленный id header("Location: lot.php?lot=" . $lot_id); //пренаправляет на последний id } else { $content = include_template('error.php', ['error' => mysqli_error($link)]); } } } $layout_content = include_template('layout.php', compact('content', 'categories_list', 'title')); print($layout_content); <file_sep><?php require_once 'vendor/autoload.php'; // Создаем объект класса Swift_SmtpTransport и передаем туда, через вызовы методов имя и пароль $transport = new Swift_SmtpTransport("phpdemo.ru", 25); $transport->setUsername("<EMAIL>"); $transport->setPassword("<PASSWORD>"); //содаем объект Swift_Mailer и пердадим в него переменную с объектом Swift_SmtpTransport $mailer = new Swift_Mailer($transport); //создаем объект Swift_Plugins_Loggers_ArrayLogger логгер что-бы иметь подробную информацию о процессе отправки $logger = new Swift_Plugins_Loggers_ArrayLogger(); $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger)); // этим запросом получаем сводную таблицу о выйграном лоте пользовтелем $sql = 'SELECT lots_id, lot_name, users.id as user_id, user_name, email FROM bets JOIN users ON users.id = users_id JOIN lots ON lots.id = lots_id WHERE bets.id IN (SELECT MAX(Id) FROM bets WHERE bets.lots_id IN (SELECT lots.id FROM lots WHERE winners_id IS NULL AND end_date < NOW()) GROUP BY lots_id)'; // создаем массив с результатом из запроса sql $result = get_data_db($link, $sql, 'list'); if (count($result) > 0) { foreach ($result as $item) { // создаем объект Swift_Message $message = new Swift_Message(); // Тема сообщения $message->setSubject("Ваша ставка победила"); // Отправитель в виде массива email -> имя $message->setFrom(['<EMAIL>' => 'Yeticave']); // получатели $message->setBcc([$item['email'] => $item['user_name']]); $msg_content = include_template('email.php', ['user' => $item['user_name'], 'lot' => $item['lots_id'], 'lot_name' => $item['lot_name']]); $message->setBody($msg_content, 'text/html'); $update_sql = 'UPDATE lots SET winners_id = ' . $item['user_id'] . ' WHERE id = ' . $item['lots_id'] . ''; $update_result = mysqli_query($link, $update_sql); if ($update_result) { $send_result = $mailer->send($message); } } if ($send_result) { print("Рассылка успешно отправлена"); } else { print("Не удалось отправить рассылку: " . $logger->dump()); } }
3994edeaf7ff97de7e988beb93bb18a3c893a0df
[ "SQL", "PHP" ]
20
PHP
Grebenev/536017-yeticave
ea40d83c099b8a02a05c84835fbf56de7661acd4
ff25122d7c62cba85e1bf406050b549b6d48cdc5
refs/heads/master
<file_sep>#include <iostream> #include <fstream> #include <string> #include <bits/basic_string.h> #include <stdlib.h> using namespace std; const int MAX_ALU = 40; struct Alumno { int dni; int edad; string nombre; string dir; }; // Declaracion del registro alumnos y sus campos. void intrcmb(Alumno &a, Alumno &b) { Alumno aux; aux = a; a = b; b = aux; } // Funcion que intercambia a por b, utilizada en el ordenamiento. void OrdxBur(Alumno alu[],short card) { int i,j; for(i = 1; i < card; i++) { for(j = 1; j<card-1; j++) { if(alu[j].dni>alu[j+1].dni) { intrcmb(alu[j+1],alu[j]); } } } } // Ordena el registro en base a numeros de dni para poder utilizar busqueda binaria. void guardarArch(Alumno alu[],ofstream &arch,short card) { arch.open("alumnos.txt"); for(int i = 1; i < card; i++) { //cout << "j"; arch << alu[i].dni << endl;; arch << alu[i].edad << endl; arch << alu[i].nombre << endl; arch << alu[i].dir << endl; } arch.close(); } // Guarda los datos de los alumnos en alumnos.txt. void guarda_card(ofstream &archCardO,short &card) { archCardO.open("card.txt"); archCardO << card; archCardO.close(); } // Guarda en el archivo card.txt la cardinalidad. void carga_card(ifstream &archCardI,short &card) { string cardS; archCardI.open("card.txt"); if(archCardI.is_open()) { while(!archCardI.eof()) { getline(archCardI,cardS); } } card = atoi(cardS.c_str()); archCardI.close(); } // Carga del archivo card.txt el dato del cardinal. bool leerArch(Alumno alu[],ifstream &arch, short card) { arch.open("alumnos.txt"); string dniS,edadS,nombreS,dirS; int i = 1; if(arch.is_open()) { while(!arch.eof()) { getline(arch,dniS); getline(arch,edadS); getline(arch,nombreS); getline(arch,dirS); alu[i].dni=atoi(dniS.c_str()); alu[i].edad=atoi(edadS.c_str()); alu[i].nombre=nombreS; alu[i].dir=dirS; cout << alu[i].dni << endl; cout << alu[i].edad << endl; cout << alu[i].nombre << endl; cout << alu[i].dir << endl; i++; } arch.close(); return true; }else { return false; } } // Lee el archivo llamado alumnos.txt. int busquedaBinaria(Alumno alu[], short card,int auxDNI) { int prim=1; int medio=0; int ult = card; while(prim <= ult) { medio = (prim+ult)/2; if(auxDNI == alu[medio].dni) { return medio; }else { if(alu[medio].dni > auxDNI) { ult = medio - 1; }else { prim = medio + 1; } } } return -1; } // Busca el alumno en base a un numero de dni y devuelve su posicion. void cantidadAlumnos(Alumno alu[],short &card) { ofstream archCardO; cout << "Ingrese la cantidad de alumnos" << endl; cin >> card; card+=1; guarda_card(archCardO,card); for (int i = 1; i < card ; i++) { cout << "Ingrese dni para el " << i << " alumno" << endl; cin >> alu[i].dni; cout << "Ingrese edad para el " << i << " alumno" << endl; cin >> alu[i].edad; cout << "Ingrese nombre para el " << i << " alumno" << endl; getline(cin,alu[i].nombre); getline(cin,alu[i].nombre); cout << "Ingrese direccion para el " << i << " alumno" << endl; getline(cin,alu[i].dir); } OrdxBur(alu,card); } // Toma un numero de alumnos y pide los datos en base a ese numero(cardinal). bool eliminarAlumno(Alumno alu[], short card,int posicion) { if(posicion == -1) return false; alu[posicion].dni=-1; alu[posicion].nombre=""; alu[posicion].edad=-1; alu[posicion].dir=""; OrdxBur(alu,card); return true; } // Deja en blanco los campos del alumno deseado y vuelve a ordenar el array. void busquedaAlumno(Alumno alu[],int dniAux,short card) { int aux; aux = busquedaBinaria(alu,card,dniAux); if(aux==-1) { cout << "No se encontro el alumno" << endl; }else { cout << "Nombre: " << alu[aux].nombre << endl; cout << "Edad: " << alu[aux].edad << endl; cout << "Direccion: " << alu[aux].dir << endl; } } // Busca un alumno por numero de dni. bool editarAlumno(Alumno alu[],int dniAux,short card) { char opc; int aux = busquedaBinaria(alu,card,dniAux); if(aux==-1) return false; else { do { cout << "Ingrese dato a editar (D) DNI, (I) Direccion, (N) Nombre, (E) Edad." << endl; cout << "(S) Salir." << endl; cin >> opc; switch(opc) { case 'D': cout << "Ingrese nuevo DNI." << endl; cin >> alu[aux].dni; break; case 'I': cout << "Ingrese nueva direccion." << endl; getline(cin,alu[aux].dir); getline(cin,alu[aux].dir); break; case 'N': cout << "Ingrese nuevo nombre." << endl; getline(cin,alu[aux].nombre); getline(cin,alu[aux].nombre); break; case 'E': cout << "Ingrese nueva edad." << endl; cin >> alu[aux].edad; break; case 'S': cout << "Saliendo..." << endl; break; default: cout << "Opcion equivocada."<< endl; break; } }while(opc!='S'); OrdxBur(alu,card); return true; } } // Edita datos de un alumno en base a su DNI. void agregarAlumno(Alumno alu[],short &card) { ofstream archCardO; card+=1; guarda_card(archCardO,card); cout << "Ingrese DNI." << endl; cin >> alu[card-1].dni; cout << "Ingrese edad." << endl; cin >> alu[card-1].edad; cout << "Ingrese nombre." << endl; getline(cin,alu[card-1].nombre); getline(cin,alu[card-1].nombre); cout << "Ingrese direccion." << endl; getline(cin,alu[card-1].dir); OrdxBur(alu,card); } // Agrega un alumno al final del array. void mostrarAlumnos(Alumno alu[],short card) { cout << "Mostrando alumnos..." << endl; for(int i = 1; i < card; i++) { if(alu[i].dni!=-1) { cout << "DNI: " << alu[i].dni << endl; cout << "EDAD: " << alu[i].edad << endl; cout << "NOMBRE: " << alu[i].nombre << endl; cout << "DIRECCION: " << alu[i].dir << endl; cout << "-----------------" << endl; } } } // Muestra todos los alumnos del archivo. void menu() { cout << "Ingrese una opcion." << endl; cout << "1. Ver datos de un alumno." << endl; cout << "2. Eliminar datos." << endl; cout << "3. Ver todos los alumnos." << endl; cout << "4. Editar alumno." << endl; cout << "5. Agregar alumno." << endl; cout << "6. Finalizar." << endl; } // Menu de opciones. int main(int argc, char const *argv[]) { short card,opc; int dniAux; Alumno alu[MAX_ALU]; ofstream archO; ifstream archI,archCardI; carga_card(archCardI,card); if(leerArch(alu,archI,card)) { cout << "Archivo leido.." << endl; }else { cout << "Se deben cargar datos.. Presione enter" << endl; cin.get(); cantidadAlumnos(alu,card); } // Se asegura de que si no esta creado el archivo se carguen datos. do { menu(); cin >> opc; switch(opc) { case 1: cout << "Ingrese el numero de dni a buscar" << endl; cin >> dniAux; busquedaAlumno(alu,dniAux,card); break; case 2: cout << "Ingrese el dni del alumno a eliminar" << endl; cin >> dniAux; if(eliminarAlumno(alu,card,busquedaBinaria(alu,card,dniAux))) { cout << "Eliminado exitosamente" << endl; }else { cout << "DNI invalido" << endl; } break; case 3: mostrarAlumnos(alu,card); break; case 4: cout << "Ingrese DNI del alumno a editar" << endl; cin >> dniAux; if(editarAlumno(alu,dniAux,card)) cout << "Editado correctamente" << endl; else { cout << "No se pudo encontrar el DNI ingresado." << endl; } break; case 5: agregarAlumno(alu,card); break; case 6: cout << "Finalizando..." << endl; guardarArch(alu,archO,card); // Al salir del programa se guarda en el archivo. break; default: cout << "Opcion invalida"; break; } } while(opc!=6); // Seleccion multiple. return 0; } // Funcion principal.<file_sep># ProgramaAlumnos Programa de fichaje de alumnos.
80d15ccf425a2e58d0644e33131bad322449e591
[ "Markdown", "C++" ]
2
C++
GastonAQS/ProgramaAlumnos
a61f8148e7ccc0c6d22e93420d871f3797f04ac5
3204119f2e84dc22abc17808deea62cd1401a5f3
refs/heads/master
<repo_name>open-mpi/ompi-tests-public<file_sep>/sessions/sessions_test1.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" void print_error(const char *msg, int rc) { char err_str[MPI_MAX_ERROR_STRING]; int resultlen = sizeof(err_str) - 1; MPI_Error_string(rc, err_str, &resultlen); fprintf (stderr, "%s return err code = %d (%s)\n", msg, rc, err_str); } void my_session_errhandler (MPI_Session *foo, int *bar, ...) { fprintf(stderr, "errhandler called with error %d\n", *bar); } int main (int argc, char *argv[]) { MPI_Session session, session1; MPI_Errhandler errhandler; MPI_Group group; MPI_Comm comm_world, comm_self; MPI_Info info; int rc, npsets, one = 1, sum, i; rc = MPI_Session_create_errhandler (my_session_errhandler, &errhandler); if (MPI_SUCCESS != rc) { print_error("Error handler creation failed", rc); return -1; } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { print_error("Info creation failed", rc); return -1; } rc = MPI_Info_set(info, "mpi_thread_support_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { print_error("Info key/val set failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session); if (MPI_SUCCESS != rc) { print_error("Session initialization failed", rc); return -1; } rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); if (MPI_SUCCESS != rc) { print_error("Session get num psets failed", rc); return -1; } for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); fprintf (stderr, " PSET %d: %s (len: %d)\n", i, name, psetlen); } rc = MPI_Group_from_session_pset (session, "mpi://WORLD", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://WORLD", rc); return -1; } rc = MPI_Comm_create_from_group (group, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world); if (MPI_SUCCESS != rc) { print_error("Could not get a comm from group", rc); return -1; } MPI_Group_free (&group); MPI_Allreduce (&one, &sum, 1, MPI_INT, MPI_SUM, comm_world); fprintf (stderr, "World Comm Sum (1): %d\n", sum); rc = MPI_Group_from_session_pset (session, "mpi://SELF", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://SELF", rc); return -1; } MPI_Comm_create_from_group (group, "myself", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_self); if (MPI_SUCCESS != rc) { print_error("Could not get a comm from group", rc); return -1; } MPI_Group_free (&group); MPI_Allreduce (&one, &sum, 1, MPI_INT, MPI_SUM, comm_self); fprintf (stderr, "Self Comm Sum (1): %d\n", sum); MPI_Errhandler_free (&errhandler); MPI_Info_free (&info); MPI_Comm_free (&comm_world); MPI_Comm_free (&comm_self); rc = MPI_Session_finalize (&session); if (MPI_SUCCESS != rc) { print_error("Session finalize returned error", rc); return -1; } fprintf(stderr, "Finished first finalize\n"); rc = MPI_Session_create_errhandler (my_session_errhandler, &errhandler); if (MPI_SUCCESS != rc) { print_error("Error handler creation failed", rc); return -1; } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { print_error("Info creation failed", rc); return -1; } rc = MPI_Info_set(info, "mpi_thread_support_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { print_error("Info key/val set failed", rc); return -1; } printf("Starting second init\n"); rc = MPI_Session_init (info, errhandler, &session); printf("Finished second init\n"); if (MPI_SUCCESS != rc) { print_error("Session initialization failed", rc); return -1; } rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); fprintf (stderr, " PSET %d: %s (len: %d)\n", i, name, psetlen); } rc = MPI_Group_from_session_pset (session, "mpi://WORLD", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://WORLD", rc); return -1; } MPI_Comm_create_from_group (group, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world); MPI_Group_free (&group); MPI_Allreduce (&one, &sum, 1, MPI_INT, MPI_SUM, comm_world); fprintf (stderr, "World Comm Sum (1): %d\n", sum); rc = MPI_Group_from_session_pset (session, "mpi://SELF", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://SELF ", rc); return -1; } MPI_Comm_create_from_group (group, "myself", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_self); MPI_Group_free (&group); MPI_Allreduce (&one, &sum, 1, MPI_INT, MPI_SUM, comm_self); fprintf (stderr, "Self Comm Sum (1): %d\n", sum); MPI_Errhandler_free (&errhandler); MPI_Info_free (&info); MPI_Comm_free (&comm_world); MPI_Comm_free (&comm_self); MPI_Session_finalize (&session); return 0; } <file_sep>/singleton/Makefile CC=mpicc CFLAGS=-Wall -g -O0 PROGS=hello_c simple_spawn simple_spawn_multiple all: $(PROGS) hello_c: hello_c.c $(CC) hello_c.c $(CFLAGS) -o hello_c simple_spawn: simple_spawn.c $(CC) simple_spawn.c $(CFLAGS) -o simple_spawn simple_spawn_multiple: simple_spawn_multiple.c $(CC) simple_spawn_multiple.c $(CFLAGS) -o simple_spawn_multiple clean: $(RM) $(PROGS) *.o <file_sep>/events/events_source.c /* * events_source.c * * Test events source functions * */ #include "events_common.h" // Test flags int event_source_get_num_success = 0; int event_source_get_info_success = 0; int event_source_get_timestamp_success = 0; void print_results() { if ( 0 != rank ) return; print_pf_result("MPI_T_source_get_num", "Get Number of Sources Success", event_source_get_num_success); print_pf_result("MPI_T_source_get_info", "Get Source Info Success", event_source_get_info_success); print_pf_result("MPI_T_source_get_timestamp", "Get Source Timestamp Success", event_source_get_timestamp_success); if ( do_failure_tests ) { } fprintf(outstream, "%-*s - %-*s : %6d\n", func_width, "TOTAL ERROR COUNT", metric_width, "", error_count); } void test_source() { int retval; int num_sources, source_index; MPI_Count timestamp; char name[MAX_STRING], desc[MAX_STRING]; int name_len, desc_len; MPI_Count ticks_per_second, max_ticks; MPI_Info info; MPI_T_source_order ordering; /* * * int MPI_T_source_get_num(int *num_sources) * int MPI_T_source_get_info(int source_index, char *name, int *name_len, * char *desc, int *desc_len, MPI_T_source_order *ordering, * MPI_Count *ticks_per_second, MPI_Count *max_ticks, * MPI_Info *info) * int MPI_T_source_get_timestamp(int source_index, MPI_Count *timestamp) */ retval = MPI_T_source_get_num(&num_sources); if ( retval != MPI_SUCCESS ) print_error("MPI_T_source_get_num did not return MPI_SUCCESS", retval, TEST_CONTINUE); else event_source_get_num_success = 1; print_debug("num_sources is %d\n", num_sources); if ( num_sources > 0 ) source_index = 0; retval = MPI_T_source_get_info(source_index, name, &name_len, desc, &desc_len, &ordering, &ticks_per_second, &max_ticks, &info); if ( retval != MPI_SUCCESS ) print_error("MPI_T_source_get_info did not return MPI_SUCCESS", retval, TEST_CONTINUE); else { event_source_get_info_success = 1; print_debug("source %3d : %s : %s : %lu : %lu\n", source_index, name, desc, ticks_per_second, max_ticks); } retval = MPI_T_source_get_timestamp(source_index, &timestamp); if ( retval != MPI_SUCCESS ) print_error("MPI_T_source_get_timestamp did not return MPI_SUCCESS", retval, TEST_CONTINUE); else event_source_get_timestamp_success = 1; if ( do_failure_tests ) { } } int main (int argc, char** argv) { test_init("MPI_T Events Source Tests", argc, argv); test_source(); print_results(); MPI_T_finalize(); MPI_Finalize(); return 0; } <file_sep>/README.md # Open MPI Public Tests Repo This repository is a loose collection of tests used by the Open MPI developer community. Note that this repository, as a whole, is not a production-quality, releasable software product intended for general users. That being said, individual test and/or test suites in this repository may well be suitable for wider audiences. <file_sep>/singleton/hello_c.c #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include "mpi.h" int main(int argc, char* argv[]) { int mcw_rank, mcw_size, len; char name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &mcw_rank); MPI_Comm_size(MPI_COMM_WORLD, &mcw_size); MPI_Get_processor_name(name, &len); MPI_Barrier( MPI_COMM_WORLD ); printf("%3d/%3d) [%s] %d Hello, world!\n", mcw_rank, mcw_size, name, (int)getpid()); fflush(NULL); MPI_Finalize(); return 0; } <file_sep>/status/README.md # Test MPI_Status conversion functions MPI-4:18.2.5 has a good diagram showing all the possible conversion functions for an MPI_Status. We need to test each edge in that diagram. ``` MPI_Status / ^ \ ^ C types and / / \ \ functions / / \ \ (1)/ /(2) (3)\ \(4) / / (5) \ \ / / <-------- ' \ MPI_F08_status ' --------------> \ MPI_Fint array (6) (7) TYPE(MPI_Status) <-------------- INTEGER array of size --------------> MPI_STATUS_SIZE (in Fortran) (8) ``` 1. MPI_Status_c2f08() 1. MPI_Status_f082c() 1. MPI_Status_c2f() 1. MPI_Status_f2c() 1. MPI_Status_f2f08() (in C) 1. MPI_Status_f082f() (in C) 1. MPI_Status_f2f08() (in Fortran) 1. In the `mpi` module 1. In the `mpi_f08` module 1. MPI_Status_f082f() (in Fortran) 1. In the `mpi` module 1. In the `mpi_f08` module By transitive property, if we test each leg in the above diagram, then we effectively certify the conversion journey of a status across any combination of the legs in the diagram (i.e., any possible correct status conversion). <file_sep>/collective-big-count/test_scan.c /* * Copyright (c) 2022 IBM Corporation. All rights reserved. * * $COPYRIGHT$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mpi.h> #include "common.h" int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking); int main(int argc, char** argv) { /* * Initialize the MPI environment */ int ret = 0; MPI_Init(NULL, NULL); init_environment(argc, argv); // Run the tests #ifndef TEST_UNIFORM_COUNT // Each rank contribues: V_SIZE_INT elements // Largest buffer is : V_SIZE_INT elements ret += my_c_test_core(MPI_INT, V_SIZE_INT, true); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, true); if (allow_nonblocked) { ret += my_c_test_core(MPI_INT, V_SIZE_INT, false); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, false); } #else size_t proposed_count; // Each rank contribues: TEST_UNIFORM_COUNT elements // Largest buffer is : TEST_UNIFORM_COUNT elements proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_INT, proposed_count, true); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, true); if (allow_nonblocked) { proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_INT, proposed_count, false); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, false); } #endif /* * All done */ MPI_Finalize(); return ret; } int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking) { int ret = 0; size_t i; MPI_Request request; char *mpi_function = blocking ? "MPI_Scan" : "MPI_Iscan"; // Actual payload size as divisible by the sizeof(dt) size_t payload_size_actual; /* * Initialize vector */ int *my_int_recv_vector = NULL; int *my_int_send_vector = NULL; double _Complex *my_dc_recv_vector = NULL; double _Complex *my_dc_send_vector = NULL; double _Complex testValue; size_t num_wrong = 0; assert(MPI_INT == dtype || MPI_C_DOUBLE_COMPLEX == dtype); assert(total_num_elements <= INT_MAX); if( MPI_INT == dtype ) { payload_size_actual = total_num_elements * sizeof(int); my_int_recv_vector = (int*)safe_malloc(payload_size_actual); my_int_send_vector = (int*)safe_malloc(payload_size_actual); } else { payload_size_actual = total_num_elements * sizeof(double _Complex); my_dc_recv_vector = (double _Complex*)safe_malloc(payload_size_actual); my_dc_send_vector = (double _Complex*)safe_malloc(payload_size_actual); } printf("total %ld size %ld\n", total_num_elements, payload_size_actual); /* * Assign each input array element the value of its array index modulo some * prime as an attempt to assign unique values to each array elements and catch * errors where array elements get updated with wrong values. Use a prime * number in order to avoid problems related to powers of 2. */ for(i = 0; i < total_num_elements; ++i) { if( MPI_INT == dtype ) { my_int_send_vector[i] = i % PRIME_MODULUS; } else { my_dc_send_vector[i] = (i % PRIME_MODULUS) - (i % PRIME_MODULUS)*I; } } if (world_rank == 0) { printf("---------------------\nResults from %s(%s x %zu = %zu or %s):\n", mpi_function, (MPI_INT == dtype ? "int" : "double _Complex"), total_num_elements, payload_size_actual, human_bytes(payload_size_actual)); } if (blocking) { if( MPI_INT == dtype ) { MPI_Scan(my_int_send_vector, my_int_recv_vector, (int)total_num_elements, dtype, MPI_SUM, MPI_COMM_WORLD); } else { MPI_Scan(my_dc_send_vector, my_dc_recv_vector, (int)total_num_elements, dtype, MPI_SUM, MPI_COMM_WORLD); } } else { if( MPI_INT == dtype ) { MPI_Iscan(my_int_send_vector, my_int_recv_vector, (int)total_num_elements, dtype, MPI_SUM, MPI_COMM_WORLD, &request); } else { MPI_Iscan(my_dc_send_vector, my_dc_recv_vector, (int)total_num_elements, dtype, MPI_SUM, MPI_COMM_WORLD, &request); } MPI_Wait(&request, MPI_STATUS_IGNORE); } /* * Check results. * Each output array element must have the value such that * out[i] == (in[i] % PRIME_MODULO) * (my_rank + 1) since out[i] is the sum of * in[i] for all ranks less than or equal to our rank and in[i] for all * ranks is set to * i % PRIME_MODULO */ for (i = 0; i < total_num_elements; ++i) { if( MPI_INT == dtype ) { if(my_int_recv_vector[i] != my_int_send_vector[i] * (world_rank + 1)) { ++num_wrong; } } else { testValue = (i % PRIME_MODULUS) * (world_rank + 1) - (i % PRIME_MODULUS) * (world_rank + 1) * I; if (my_dc_recv_vector[i] != testValue) { ++num_wrong; } } } if( 0 == num_wrong) { printf("Rank %2d: PASSED\n", world_rank); } else { printf("Rank %2d: ERROR: DI in %14zu of %14zu slots (%6.1f %% wrong)\n", world_rank, num_wrong, total_num_elements, ((num_wrong * 1.0)/total_num_elements)*100.0); ret = 1; } if( NULL != my_int_send_vector ) { free(my_int_send_vector); } if( NULL != my_int_recv_vector ){ free(my_int_recv_vector); } if( NULL != my_dc_send_vector ) { free(my_dc_send_vector); } if( NULL != my_dc_recv_vector ){ free(my_dc_recv_vector); } fflush(NULL); MPI_Barrier(MPI_COMM_WORLD); return ret; } <file_sep>/runtime/bin/pretty-print-hwloc/autogen.sh #!/bin/bash -e autoreconf -ivf <file_sep>/collective-big-count/test_reduce.c /* * Copyright (c) 2021-2022 IBM Corporation. All rights reserved. * * $COPYRIGHT$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mpi.h> #include "common.h" int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking); int main(int argc, char** argv) { /* * Initialize the MPI environment */ int ret = 0; MPI_Init(NULL, NULL); init_environment(argc, argv); #ifndef TEST_UNIFORM_COUNT // Each rank contribues: V_SIZE_INT elements // Largest buffer is : V_SIZE_INT elements ret += my_c_test_core(MPI_INT, V_SIZE_INT, true); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, true); if (allow_nonblocked) { ret += my_c_test_core(MPI_INT, V_SIZE_INT, false); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, false); } #else size_t proposed_count; // Each rank contribues: TEST_UNIFORM_COUNT elements // Largest buffer is : TEST_UNIFORM_COUNT elements proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_INT, proposed_count, true); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, true); if (allow_nonblocked) { proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_INT, proposed_count, false); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, false); } #endif /* * All done */ MPI_Finalize(); return ret; } int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking) { int ret = 0; size_t i; MPI_Request request; char *mpi_function = blocking ? "MPI_Reduce" : "MPI_Ireduce"; // Actual payload size as divisible by the sizeof(dt) size_t payload_size_actual; /* * Initialize vector */ int *my_int_recv_vector = NULL; int *my_int_send_vector = NULL; double _Complex *my_dc_recv_vector = NULL; double _Complex *my_dc_send_vector = NULL; size_t num_wrong = 0; assert(MPI_INT == dtype || MPI_C_DOUBLE_COMPLEX == dtype); assert(total_num_elements <= INT_MAX); if( MPI_INT == dtype ) { payload_size_actual = total_num_elements * sizeof(int); if (world_rank == 0) { my_int_recv_vector = (int*)safe_malloc(payload_size_actual); } my_int_send_vector = (int*)safe_malloc(payload_size_actual); } else { payload_size_actual = total_num_elements * sizeof(double _Complex); if (world_rank == 0) { my_dc_recv_vector = (double _Complex*)safe_malloc(payload_size_actual); } my_dc_send_vector = (double _Complex*)safe_malloc(payload_size_actual); } for(i = 0; i < total_num_elements; ++i) { if( MPI_INT == dtype ) { my_int_send_vector[i] = 1; if (world_rank == 0) { my_int_recv_vector[i] = -1; } } else { my_dc_send_vector[i] = 1.0 - 1.0*I; if (world_rank == 0) { my_dc_recv_vector[i] = -1.0 + 1.0*I; } } } /* * MPI_Allreduce fails when size of my_int_vector is large */ if (world_rank == 0) { printf("---------------------\nResults from %s(%s x %zu = %zu or %s):\n", mpi_function, (MPI_INT == dtype ? "int" : "double _Complex"), total_num_elements, payload_size_actual, human_bytes(payload_size_actual)); } if (blocking) { if( MPI_INT == dtype ) { MPI_Reduce(my_int_send_vector, my_int_recv_vector, (int)total_num_elements, dtype, MPI_SUM, 0, MPI_COMM_WORLD); } else { MPI_Reduce(my_dc_send_vector, my_dc_recv_vector, (int)total_num_elements, dtype, MPI_SUM, 0, MPI_COMM_WORLD); } } else { if( MPI_INT == dtype ) { MPI_Ireduce(my_int_send_vector, my_int_recv_vector, (int)total_num_elements, dtype, MPI_SUM, 0, MPI_COMM_WORLD, &request); } else { MPI_Ireduce(my_dc_send_vector, my_dc_recv_vector, (int)total_num_elements, dtype, MPI_SUM, 0, MPI_COMM_WORLD, &request); } MPI_Wait(&request, MPI_STATUS_IGNORE); } /* * Check results. * The exact result = (size*number_of_processes, -size*number_of_processes) */ if (world_rank == 0) { for(i = 0; i < total_num_elements; ++i) { if( MPI_INT == dtype ) { if(my_int_recv_vector[i] != world_size) { ++num_wrong; } } else { if(my_dc_recv_vector[i] != 1.0*world_size - 1.0*world_size*I) { ++num_wrong; } } } if( 0 == num_wrong) { printf("Rank %2d: PASSED\n", world_rank); } else { printf("Rank %2d: ERROR: DI in %14zu of %14zu slots (%6.1f %% wrong)\n", world_rank, num_wrong, total_num_elements, ((num_wrong * 1.0)/total_num_elements)*100.0); ret = 1; } } if( NULL != my_int_send_vector ) { free(my_int_send_vector); } if( NULL != my_int_recv_vector ){ free(my_int_recv_vector); } if( NULL != my_dc_send_vector ) { free(my_dc_send_vector); } if( NULL != my_dc_recv_vector ){ free(my_dc_recv_vector); } fflush(NULL); MPI_Barrier(MPI_COMM_WORLD); return ret; } <file_sep>/runtime/bin/pretty-print-hwloc/README.md # Pretty Print HWLOC Process Binding ## Building ```shell ./autogen.sh ./configure --prefix=${YOUR_INSTALL_DIR} --with-hwloc=${HWLOC_INSTALL_PATH} make make install ```` ## Running ### Default: Print HWLOC bitmap ```shell shell$ get-pretty-cpu 0/ 0 on c660f5n18) Process Bound : 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff ``` ```shell shell$ hwloc-bind core:2 get-pretty-cpu 0/ 0 on c660f5n18) Process Bound : 0x00ff0000 ``` ```shell shell$ mpirun -np 2 get-pretty-cpu 0/ 2 on c660f5n18) Process Bound : 0x000000ff 1/ 2 on c660f5n18) Process Bound : 0x0000ff00 ``` ### Full descriptive output ```shell shell$ get-pretty-cpu -b -f 0/ 0 on c660f5n18) Process Bound : socket 0[core 0[hwt 0-7]],socket 0[core 1[hwt 0-7]],socket 0[core 2[hwt 0-7]],socket 0[core 3[hwt 0-7]],socket 0[core 4[hwt 0-7]],socket 0[core 5[hwt 0-7]],socket 0[core 6[hwt 0-7]],socket 0[core 7[hwt 0-7]],socket 0[core 8[hwt 0-7]],socket 0[core 9[hwt 0-7]],socket 1[core 10[hwt 0-7]],socket 1[core 11[hwt 0-7]],socket 1[core 12[hwt 0-7]],socket 1[core 13[hwt 0-7]],socket 1[core 14[hwt 0-7]],socket 1[core 15[hwt 0-7]],socket 1[core 16[hwt 0-7]],socket 1[core 17[hwt 0-7]],socket 1[core 18[hwt 0-7]],socket 1[core 19[hwt 0-7]] ``` ```shell shell$ hwloc-bind core:2 get-pretty-cpu -b -f 0/ 0 on c660f5n18) Process Bound : socket 0[core 2[hwt 0-7]] ``` ```shell shell$ mpirun -np 2 get-pretty-cpu -b -f 1/ 2 on c660f5n18) Process Bound : socket 0[core 1[hwt 0-7]] 0/ 2 on c660f5n18) Process Bound : socket 0[core 0[hwt 0-7]] ``` ### Full descriptive bracketed output ```shell shell$ get-pretty-cpu -b -m 0/ 0 on c660f5n18) Process Bound : [BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB][BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB/BBBBBBBB] ``` ```shell shell$ hwloc-bind core:2 get-pretty-cpu -b -m 0/ 0 on c660f5n18) Process Bound : [......../......../BBBBBBBB/......../......../......../......../......../......../........][......../......../......../......../......../......../......../......../......../........] ``` ```shell shell$ mpirun -np 2 get-pretty-cpu -b -m 1/ 2 on c660f5n18) Process Bound : [......../BBBBBBBB/......../......../......../......../......../......../......../........][......../......../......../......../......../......../......../......../......../........] 0/ 2 on c660f5n18) Process Bound : [BBBBBBBB/......../......../......../......../......../......../......../......../........][......../......../......../......../......../......../......../......../......../........] ``` <file_sep>/sessions/Makefile # # Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana # University Research and Technology # Corporation. All rights reserved. # Copyright (c) 2004-2018 The University of Tennessee and The University # of Tennessee Research Foundation. All rights # reserved. # Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, # University of Stuttgart. All rights reserved. # Copyright (c) 2004-2005 The Regents of the University of California. # All rights reserved. # Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved. # Copyright (c) 2011-2016 Cisco Systems, Inc. All rights reserved. # Copyright (c) 2012 Los Alamos National Security, Inc. All rights reserved. # Copyright (c) 2013 Mellanox Technologies, Inc. All rights reserved. # Copyright (c) 2017-2018 Research Organization for Information Science # and Technology (RIST). All rights reserved. # Copyright (c) 2019 Triad National Security, LLC. All rights # reserved. # # $COPYRIGHT$ # # Additional copyrights may follow # # $HEADER$ # # Use the Open MPI-provided wrapper compilers. MPICC = mpicc MPIFC = mpifort # Example programs to build EXAMPLES = \ sessions_ex1.o \ sessions_ex2 \ sessions_ex3 \ sessions_ex4 \ sessions_test \ sessions_test1 \ sessions_test2 \ sessions_test3 \ sessions_test5 \ sessions_test6 \ sessions_test7 \ sessions_test8 \ sessions_test9 \ sessions_test10 \ sessions_test11 \ sessions_test12 \ sessions_test13 \ sessions_test15 \ sessions_test16 # Default target. Always build the C MPI examples. Only build the # others if we have the appropriate Open MPI / OpenSHMEM language # bindings. all: sessions_ex1.o sessions_ex2 sessions_test sessions_test1 sessions_test2 sessions_test3 sessions_test5 \ sessions_test6 sessions_test7 sessions_test8 sessions_test9 sessions_test10 sessions_test11 sessions_test12 sessions_test13 \ sessions_test15 sessions_test16 @ if which ompi_info >/dev/null 2>&1 ; then \ $(MAKE) mpi; \ fi mpi: @ if ompi_info --parsable | grep -q bindings:use_mpi_f08:yes >/dev/null; then \ $(MAKE) sessions_ex3 ; \ fi @ if ompi_info --parsable | egrep -q bindings:use_mpi:\"\?yes >/dev/null; then \ $(MAKE) sessions_ex4 ; \ fi # The usual "clean" target clean: rm -f $(EXAMPLES) *~ *.o # Don't rely on default rules for the Fortran and Java examples sessions_ex1.o: sessions_ex1.c $(MPICC) -c $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_ex2: sessions_ex2.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_ex3: sessions_ex3.f90 $(MPIFC) $(FCFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_ex4: sessions_ex4.f90 $(MPIFC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test: sessions_test.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test1: sessions_test1.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test2: sessions_test2.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test3: sessions_test3.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test5: sessions_test5.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test6: sessions_test6.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test7: sessions_test7.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test8: sessions_test8.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test9: sessions_test9.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test10: sessions_test10.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test11: sessions_test11.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test12: sessions_test12.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test13: sessions_test13.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test15: sessions_test15.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ sessions_test16: sessions_test16.c $(MPICC) $(CFLAGS) $(LDFLAGS) $? $(LDLIBS) -o $@ <file_sep>/events/events_example.c /* * events_example.c * * Events example that registers callback, generates callback activity, and reports event data * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <mpi.h> char *cb_user_data; int rank, wsize; int event_index = 0; char user_data_string[256] = "Test String"; MPI_T_event_registration event_registration; void event_cb_function(MPI_T_event_instance event, MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data) { MPI_Count event_timestamp; int sequence_index = 3; short seq; MPI_T_event_get_timestamp(event, &event_timestamp); MPI_T_event_read(event, sequence_index, &seq); if ( !rank ) fprintf(stdout, "In %s %s %d ts=%lu idx=%hd\n", __func__, __FILE__, __LINE__, (unsigned long)event_timestamp, seq); } void free_event_cb_function(MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data) { if ( !rank ) fprintf(stdout, "In %s %s %d\n", __func__, __FILE__, __LINE__); } void register_callback() { int name_len, desc_len, num_elements; char *name, *desc; // int MPI_T_event_get_info(int event_index, char *name, int *name_len, // int *verbosity, MPI_Datatype *array_of_datatypes, // MPI_Aint *array_of_displacements, int *num_elements, // MPI_T_enum *enumtype, MPI_Info* info, // char *desc, int *desc_len, int *bind) // MPI_T_event_get_info ( event_index, NULL, &name_len, NULL, NULL, NULL, &num_elements, NULL, NULL, NULL, &desc_len, NULL ); name = (char*) malloc(name_len+1); desc = (char*) malloc(desc_len+1); MPI_T_event_get_info ( event_index, name, &name_len, NULL, NULL, NULL, NULL, NULL, NULL, desc, &desc_len, NULL ); if ( !rank ) fprintf(stdout, "Registering event index %d : %s : %s\n", event_index, name, desc); MPI_T_event_handle_alloc(event_index, MPI_COMM_WORLD, MPI_INFO_NULL, &event_registration) ; cb_user_data = (void*)user_data_string; MPI_T_event_register_callback(event_registration, MPI_T_CB_REQUIRE_ASYNC_SIGNAL_SAFE, MPI_INFO_NULL, cb_user_data, event_cb_function); free(name); free(desc); } void free_event() { MPI_T_event_handle_free(event_registration, cb_user_data, free_event_cb_function); } void generate_callback_activity() { #define GENERATE_BUFFER_SIZE 32 char buf[GENERATE_BUFFER_SIZE]; int i, lim = 5; MPI_Status stat; MPI_Request req; for ( i = 0; i < lim; i++ ) { if ( rank == 0 ) { strcpy(cb_user_data, "Irecv"); MPI_Irecv(buf, GENERATE_BUFFER_SIZE, MPI_CHAR, 1, 27, MPI_COMM_WORLD, &req); } else { strcpy(buf, "cat"); strcpy(cb_user_data, "Isend"); MPI_Isend(buf, GENERATE_BUFFER_SIZE, MPI_CHAR, 0, 27, MPI_COMM_WORLD, &req); } strcpy(cb_user_data, "Wait"); MPI_Wait(&req, &stat); strcpy(cb_user_data, "Barrier"); MPI_Barrier(MPI_COMM_WORLD); } } int main (int argc, char** argv) { MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &wsize); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int required = MPI_THREAD_SINGLE; int provided = 0; if ( argc > 1 ) event_index = atoi(argv[1]); else event_index = 0; MPI_T_init_thread(required, &provided); register_callback(); if ( !rank ) fprintf(stdout,"Registered callback, Generate callback activity.\n"); generate_callback_activity(); free_event(); if ( !rank ) fprintf(stdout,"Freed callback, should not generate callback activity.\n"); generate_callback_activity(); MPI_T_finalize(); MPI_Finalize(); return 0; } <file_sep>/runtime/bin/pretty-print-hwloc/configure.ac # # # ###################### # Project Information ###################### AC_INIT([HWLOC Tools], [0.1]) AC_PREREQ(2.63) ###################### # Utilities ###################### _show_title() { cat <<EOF ============================================================================ == ${1} ============================================================================ EOF } ###################### # Setup Makefile ###################### _show_title "Setup Basic Information" # Initialize automake AM_INIT_AUTOMAKE([foreign dist-bzip2 subdir-objects no-define 1.10.1 -Wall -Werror]) # Make becomes a bit more quiet m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) # Set the language CFLAGS_save="$CFLAGS" AC_LANG([C]) CFLAGS="$CFLAGS_save" ###################### # Create a configure header file ###################### AH_TOP([/* * This file is automatically generated by configure. Edits will be lost * the next time you run configure! */ #ifndef HWLOC_TOOLS_H #define HWLOC_TOOLS_H #include <autogen/hwloc_tools_config_top.h> ]) AH_BOTTOM([ #include <autogen/hwloc_tools_config_bottom.h> #endif /* HWLOC_TOOLS_CONFIG_H */ ]) AC_CONFIG_HEADERS([src/include/autogen/config.h]) ###################### # Make automake clean emacs ~ files for "make clean" ###################### CLEANFILES="*~ .\#*" AC_SUBST(CLEANFILES) ###################### # C Compiler ###################### _show_title "Setup C Compiler" CFLAGS_save="$CFLAGS" AC_PROG_CC CFLAGS="$CFLAGS_save" AC_SUBST(CFLAGS) AC_SUBST(CXXFLAGS) AC_SUBST(CPPFLAGS) AC_SUBST(LDFLAGS) AC_SUBST(LIBS) ###################### # HWLOC Install ###################### _show_title "Setup HWLOC" # # --with-hwloc=DIR # --with-hwloc-libdir=DIR # AC_ARG_WITH([hwloc], [AC_HELP_STRING([--with-hwloc=DIR], [Search for hwloc headers and libraries in DIR ])]) AC_ARG_WITH([hwloc-libdir], [AC_HELP_STRING([--with-hwloc-libdir=DIR], [Search for hwloc libraries in DIR ])]) # HWLOC is required AS_IF([test "$with_hwloc" = "no"], [AC_MSG_WARN([HWLOC is required. --without-hwloc is not supported.]) AC_MSG_ERROR([Cannot continue])]) AS_IF([test -z "$with_hwloc" || test "$with_hwloc" == "yes"], [AC_MSG_WARN([HWLOC is required. Default search functionality not supported.]) AC_MSG_ERROR([Cannot continue])]) AC_MSG_CHECKING([HWLOC Location]) AC_MSG_RESULT([$with_hwloc]) CFLAGS="-I$with_hwloc/include $CFLAGS" # Do we really need '-ludev'? #LDFLAGS="-ludev $LDFLAGS" AC_MSG_CHECKING([If static HWLOC library is available]) AS_IF([test -f "$with_hwloc/lib/libhwloc.a" ], [AC_MSG_RESULT([yes]) LIBS="$with_hwloc/lib/libhwloc.a $LIBS"], [LDFLAGS="-L$with_hwloc/lib $LDFLAGS" LIBS="-lhwloc $LIBS"]) AC_MSG_CHECKING([Final CFLAGS]) AC_MSG_RESULT([$CFLAGS]) AC_MSG_CHECKING([Final LDFLAGS]) AC_MSG_RESULT([$LDFLAGS]) AC_MSG_CHECKING([Final LIBS]) AC_MSG_RESULT([$LIBS]) ###################### # Makefile ###################### AC_CONFIG_FILES([Makefile src/Makefile]) ###################### # Done ###################### _show_title "All Done" AC_OUTPUT <file_sep>/collective-big-count/common.h /* * Copyright (c) 2021-2022 IBM Corporation. All rights reserved. * * $COPYRIGHT$ */ /* * Default: Testing (TEST_PAYLOAD_SIZE / sizeof(type)) + 1 * * Adjust TEST_PAYLOAD_SIZE from default value: * -DTEST_PAYLOAD_SIZE=# * TEST_PAYLOAD_SIZE value is used as the numerator for each datatype. * The count used for that datatype is calculated as: * (1 + (TEST_PAYLOAD_SIZE / sizeof(datatype))) * Using this variable one can test any code that guards against * a payload size that is too large. * * Adjust an individual size: * -DV_SIZE_DOUBLE_COMPLEX=123 * * Set the same count for all types: * -DTEST_UNIFORM_COUNT=123 */ #include <errno.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <limits.h> #include <complex.h> #include <stdbool.h> #include <assert.h> #include <string.h> #include <unistd.h> #define PRIME_MODULUS 997 /* * Debugging messages * 0 = off * 1 = show displacements at root * 2 = show all checks */ int debug = 0; /* * Valid after MPI_Init */ #ifndef MPI_MAX_PROCESSOR_NAME #define MPI_MAX_PROCESSOR_NAME 255 #endif int world_size = 0, world_rank = 0, local_size = 0; char my_hostname[MPI_MAX_PROCESSOR_NAME]; /* * Limit how much total memory a collective can take on the system * across all processes. */ int max_sys_mem_gb = 0; /* * Total memory on the system (for reference) */ int total_sys_mem_gb = 0; /* * Tolerate this number of GB difference between systems */ int mem_diff_tolerance = 0; /* * Percent of memory to allocate */ int mem_percent = 0; /* * Allow the nonblocking tests to run */ bool allow_nonblocked = true; /* * Algorithm expected inflation multiplier */ double alg_inflation = 1.0; /* * 'v' collectives have two modes * Packed: contiguous packing of data * Skip : a 'disp_stride' is created between every rank's contribution */ enum { MODE_PACKED = 1, MODE_SKIP = 2 }; /* * Displacement between elements when not PACKED */ int disp_stride = 2; /* * Define count paramters to use in the tests */ // Default: UINT_MAX 4294967295 // INT_MAX 2147483647 #ifndef TEST_PAYLOAD_SIZE #define TEST_PAYLOAD_SIZE UINT_MAX #endif #ifndef TEST_UNIFORM_COUNT #ifndef V_SIZE_DOUBLE_COMPLEX // double _Complex = 16 bytes x 268435455.9375 #define V_SIZE_DOUBLE_COMPLEX (int)(TEST_PAYLOAD_SIZE / sizeof(double _Complex)) #endif #ifndef V_SIZE_DOUBLE // double = 8 bytes x 536870911.875 #define V_SIZE_DOUBLE (int)(TEST_PAYLOAD_SIZE / sizeof(double)) #endif #ifndef V_SIZE_FLOAT_COMPLEX // float _Complex = 8 bytes x 536870911.875 #define V_SIZE_FLOAT_COMPLEX (int)(TEST_PAYLOAD_SIZE / sizeof(float _Complex)) #endif #ifndef V_SIZE_FLOAT // float = 4 bytes x 1073741823.75 #define V_SIZE_FLOAT (int)(TEST_PAYLOAD_SIZE / sizeof(float)) #endif #ifndef V_SIZE_INT // int = 4 bytes x 1073741823.75 #define V_SIZE_INT (int)(TEST_PAYLOAD_SIZE / sizeof(int)) #endif #else #define V_SIZE_DOUBLE_COMPLEX TEST_UNIFORM_COUNT #define V_SIZE_DOUBLE TEST_UNIFORM_COUNT #define V_SIZE_FLOAT_COMPLEX TEST_UNIFORM_COUNT #define V_SIZE_FLOAT TEST_UNIFORM_COUNT #define V_SIZE_INT TEST_UNIFORM_COUNT #define V_SIZE_CHAR TEST_UNIFORM_COUNT #endif /* * Wrapper around 'malloc' that errors out if we cannot allocate the buffer. * * @param sz size of the buffer * @return pointer to the memory. Does not return on error. */ static inline void * safe_malloc(size_t sz) { void * ptr = NULL; ptr = malloc(sz); if( NULL == ptr ) { fprintf(stderr, "Rank %d on %s) Error: Failed to malloc(%zu)\n", world_rank, my_hostname, sz); #ifdef MPI_VERSION MPI_Abort(MPI_COMM_WORLD, 3); #else exit(ENOMEM); #endif } return ptr; } /* * Convert a value in whole bytes to the abbreviated form * * @param value size in whole bytes * @return static string representation of the whole bytes in the nearest abbreviated form */ static inline const char * human_bytes(size_t value) { static char *suffix[] = {"B", "KB", "MB", "GB", "TB"}; static int s_len = 5; static char h_out[30]; int s_idx = 0; double d_value = value; if( value > 1024 ) { for( s_idx = 0; s_idx < s_len && d_value > 1024; ++s_idx ) { d_value = d_value / 1024.0; } } snprintf(h_out, 30, "%2.1f %s", d_value, suffix[s_idx]); return h_out; } /* * Determine amount of memory to use, in GBytes as a percentage of total physical memory * * @return Amount of memory to use (in GB) */ static int get_max_memory(void) { char *mem_percent_str; char *endp; FILE *meminfo_file; char *proc_data; char *token; size_t bufsize; int mem_to_use; int rc; mem_percent_str = getenv("BIGCOUNT_MEMORY_PERCENT"); if (NULL == mem_percent_str) { mem_percent_str = "80"; } mem_percent = strtol(mem_percent_str, &endp, 10); if ('\0' != *endp) { fprintf(stderr, "BIGCOUNT_MEMORY_PERCENT is not numeric\n"); exit(1); } meminfo_file = fopen("/proc/meminfo", "r"); if (NULL == meminfo_file) { fprintf(stderr, "Unable to open /proc/meminfo file: %s\n", strerror(errno)); exit(1); } bufsize = 0; proc_data = NULL; mem_to_use = 0; rc = getline(&proc_data, &bufsize, meminfo_file); while (rc > 0) { token = strtok(proc_data, " "); if (NULL != token) { if (!strcmp(token, "MemTotal:")) { token = strtok(NULL, " "); total_sys_mem_gb = strtol(token, NULL, 10); total_sys_mem_gb = (int)(total_sys_mem_gb / 1048576.0); /* /proc/meminfo specifies memory in KBytes, convert to GBytes */ mem_to_use = (int)(total_sys_mem_gb * (mem_percent / 100.0)); break; } } rc = getline(&proc_data, &bufsize, meminfo_file); } if (0 == mem_to_use) { fprintf(stderr, "Unable to determine memory to use\n"); exit(1); } free(proc_data); fclose(meminfo_file); return mem_to_use; } /* * Display a diagnostic table */ static inline void display_diagnostics(void) { printf("----------------------:-----------------------------------------\n"); printf("Total Memory Avail. : %4d GB\n", total_sys_mem_gb); printf("Percent memory to use : %4d %%\n", mem_percent); printf("Tolerate diff. : %4d GB\n", mem_diff_tolerance); printf("Max memory to use : %4d GB\n", max_sys_mem_gb); printf("----------------------:-----------------------------------------\n"); printf("INT_MAX : %20zu\n", (size_t)INT_MAX); printf("UINT_MAX : %20zu\n", (size_t)UINT_MAX); printf("SIZE_MAX : %20zu\n", (size_t)SIZE_MAX); printf("----------------------:-----------------------------------------\n"); printf(" : Count x Datatype size = Total Bytes\n"); #ifndef TEST_UNIFORM_COUNT printf("TEST_PAYLOAD_SIZE : %20zu = %10s\n", (size_t)TEST_PAYLOAD_SIZE, human_bytes((size_t)TEST_PAYLOAD_SIZE)); #else printf("TEST_UNIFORM_COUNT : %20zu\n", (size_t)TEST_UNIFORM_COUNT); #endif printf("V_SIZE_DOUBLE_COMPLEX : %20zu x %3zu = %10s\n", (size_t)V_SIZE_DOUBLE_COMPLEX, sizeof(double _Complex), human_bytes(V_SIZE_DOUBLE_COMPLEX * sizeof(double _Complex))); printf("V_SIZE_DOUBLE : %20zu x %3zu = %10s\n", (size_t)V_SIZE_DOUBLE, sizeof(double), human_bytes(V_SIZE_DOUBLE * sizeof(double))); printf("V_SIZE_FLOAT_COMPLEX : %20zu x %3zu = %10s\n", (size_t)V_SIZE_FLOAT_COMPLEX, sizeof(float _Complex), human_bytes(V_SIZE_FLOAT_COMPLEX * sizeof(float _Complex))); printf("V_SIZE_FLOAT : %20zu x %3zu = %10s\n", (size_t)V_SIZE_FLOAT, sizeof(float), human_bytes(V_SIZE_FLOAT * sizeof(float))); printf("V_SIZE_INT : %20zu x %3zu = %10s\n", (size_t)V_SIZE_INT, sizeof(int), human_bytes(V_SIZE_INT * sizeof(int))); printf("----------------------:-----------------------------------------\n"); } /* * Initialize the unit testing environment * Note: Must be called after MPI_Init() * * @param argc Argument count * @param argv Array of string arguments * @return 0 on success */ int init_environment(int argc, char** argv) { max_sys_mem_gb = get_max_memory(); #ifdef MPI_VERSION int i; int *per_local_sizes = NULL; int *local_max_mem = NULL; char *mem_diff_tolerance_str = NULL; char *env_str = NULL; int min_mem = 0; MPI_Comm_size(MPI_COMM_WORLD, &world_size); MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); MPI_Get_processor_name(my_hostname, &i); if( NULL != getenv("OMPI_COMM_WORLD_LOCAL_SIZE") ) { local_size = (int)strtol(getenv("OMPI_COMM_WORLD_LOCAL_SIZE"), NULL, 10); } else { local_size = world_size; } if( NULL != (env_str = getenv("BIGCOUNT_ENABLE_NONBLOCKING")) ) { if( 'y' == env_str[0] || 'Y' == env_str[0] || '1' == env_str[0] ) { allow_nonblocked = true; } else { allow_nonblocked = false; } } if( NULL != (env_str = getenv("BIGCOUNT_ALG_INFLATION")) ) { alg_inflation = strtod(env_str, NULL); } // Make sure that the local size is uniform if( 0 == world_rank ) { per_local_sizes = (int*)safe_malloc(sizeof(int) * world_size); } MPI_Gather(&local_size, 1, MPI_INT, per_local_sizes, 1, MPI_INT, 0, MPI_COMM_WORLD); if( 0 == world_rank ) { for(i = 0; i < world_size; ++i) { if( local_size != per_local_sizes[i] ) { printf("Error: Non-uniform local size at peer %d : actual %d vs expected %d\n", i, per_local_sizes[i], local_size); assert(local_size == per_local_sizes[i]); } } free(per_local_sizes); } // Make sure max memory usage is the same for all tasks if( 0 == world_rank ) { local_max_mem = (int*)safe_malloc(sizeof(int) * world_size); } mem_diff_tolerance_str = getenv("BIGCOUNT_MEMORY_DIFF"); if (NULL != mem_diff_tolerance_str) { mem_diff_tolerance = strtol(mem_diff_tolerance_str, NULL, 10); } MPI_Gather(&max_sys_mem_gb, 1, MPI_INT, local_max_mem, 1, MPI_INT, 0, MPI_COMM_WORLD); if( 0 == world_rank ) { min_mem = max_sys_mem_gb; for(i = 0; i < world_size; ++i) { if( max_sys_mem_gb != local_max_mem[i] ) { if( (max_sys_mem_gb < local_max_mem[i] && max_sys_mem_gb + mem_diff_tolerance < local_max_mem[i]) || (max_sys_mem_gb > local_max_mem[i] && max_sys_mem_gb > mem_diff_tolerance + local_max_mem[i]) ) { printf("Error: Non-uniform max memory usage at peer %d : actual %d vs expected %d (+/- %d)\n", i, local_max_mem[i], max_sys_mem_gb, mem_diff_tolerance); assert(max_sys_mem_gb == local_max_mem[i]); } if( min_mem > local_max_mem[i] ) { min_mem = local_max_mem[i]; } } } free(local_max_mem); if( min_mem != max_sys_mem_gb ) { printf("Warning: Detected difference between local and remote available memory. Adjusting to: %d GB\n", min_mem); max_sys_mem_gb = min_mem; } } // Agree on the max memory usage value to use across all processes MPI_Bcast(&max_sys_mem_gb, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); #else world_size = world_rank = local_size = -1; snprintf(my_hostname, MPI_MAX_PROCESSOR_NAME, "localhost"); #endif if( 0 == world_rank || -1 == world_rank ) { display_diagnostics(); } return 0; } /* * Calculate the uniform count for this collective given the datatype size, * number of processes (local and global), expected inflation in memory during * the collective, and the amount of memory we are limiting this test to consuming * on the system. * * @param datateye_size size of the datatype * @param proposed_count the count that the caller wishes to use * @param mult_root memory multiplier at root (useful in gather-like operations where the root gathers N times the count) * @param mult_peer memory multiplier at non-roots (useful in allgather-like operations where the buffer is N times count) * @return proposed count to use in the collective */ size_t calc_uniform_count(size_t datatype_size, size_t proposed_count, size_t mult_root, size_t mult_peer) { size_t orig_proposed_count = proposed_count; size_t orig_mult_root = mult_root; size_t orig_mult_peer = mult_peer; size_t payload_size_root; size_t payload_size_peer; size_t payload_size_all; double perc = 1.0; char *cpy_root = NULL, *cpy_peer = NULL; mult_root = (size_t)(mult_root * alg_inflation); mult_peer = (size_t)(mult_peer * alg_inflation); payload_size_root = datatype_size * proposed_count * mult_root; payload_size_peer = datatype_size * proposed_count * mult_peer; payload_size_all = payload_size_root + (payload_size_peer * (local_size-1)); while( (payload_size_all / ((size_t)1024 * 1024 * 1024)) > max_sys_mem_gb ) { if( 2 == debug && 0 == world_rank ) { fprintf(stderr, "----DEBUG---- Adjusting count. Try count of %10zu (payload_size %4zu GB) to fit in %4d GB limit (perc %6.2f)\n", proposed_count, payload_size_all/((size_t)1024 * 1024 * 1024), max_sys_mem_gb, perc); } perc -= 0.05; // It is possible that we are working with extremely limited memory // so the percentage dropped below 0. In this case just make the // percentage equal to the max_sys_mem_gb. if( perc <= 0.0 ) { proposed_count = (max_sys_mem_gb * (size_t)1024 * 1024 * 1024) / (datatype_size * mult_root + datatype_size * mult_peer * (local_size-1)); perc = proposed_count / (double)orig_proposed_count; if( 2 == debug && 0 == world_rank ) { fprintf(stderr, "----DEBUG---- Adjusting count. Try count of %10zu (from %10zu) to fit in %4d GB limit (perc %6.9f) -- FINAL\n", proposed_count, orig_proposed_count, max_sys_mem_gb, perc); } } else { proposed_count = orig_proposed_count * perc; } assert(perc > 0.0); payload_size_root = datatype_size * proposed_count * mult_root; payload_size_peer = datatype_size * proposed_count * mult_peer; payload_size_all = payload_size_root + (payload_size_peer * (local_size-1)); } if(proposed_count != orig_proposed_count ) { if( 0 == world_rank ) { printf("--------------------- Adjust count to fit in memory: %10zu x %5.1f%% = %10zu\n", orig_proposed_count, (proposed_count / (double)orig_proposed_count)*100, proposed_count); cpy_root = strdup(human_bytes(payload_size_root)); printf("Root : payload %14zu %8s = %3zu dt x %10zu count x %3zu peers x %5.1f inflation\n", payload_size_root, cpy_root, datatype_size, proposed_count, orig_mult_root, alg_inflation); cpy_peer = strdup(human_bytes(payload_size_peer)); printf("Peer : payload %14zu %8s = %3zu dt x %10zu count x %3zu peers x %5.1f inflation\n", payload_size_peer, cpy_peer, datatype_size, proposed_count, orig_mult_peer, alg_inflation); printf("Total : payload %14zu %8s = %8s root + %8s x %3d local peers\n", payload_size_all, human_bytes(payload_size_all), cpy_root, cpy_peer, local_size-1); free(cpy_root); free(cpy_peer); } } return proposed_count; } <file_sep>/singleton/simple_spawn_multiple.c #include <mpi.h> #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { MPI_Comm parent, intercomm; int maxprocs[2]; char *command[2]; char **spawn_argv[2]; char *argv0[2]; char *argv1[2]; MPI_Info info[2]; MPI_Init(NULL, NULL); MPI_Comm_get_parent(&parent); if (MPI_COMM_NULL != parent) { printf("Hello from a Child (%s)\n", argv[1]); fflush(NULL); MPI_Barrier(parent); MPI_Comm_disconnect(&parent); } else if(argc > 1) { maxprocs[0] = 1; maxprocs[1] = 2; command[0] = strdup(argv[1]); command[1] = strdup(argv[1]); spawn_argv[0] = argv0; spawn_argv[1] = argv1; argv0[0] = strdup("A"); argv0[1] = NULL; argv1[0] = strdup("B"); argv1[1] = NULL; info[0] = MPI_INFO_NULL; info[1] = MPI_INFO_NULL; printf("Spawning Multiple '%s' ... ", argv[1]); MPI_Comm_spawn_multiple(2, command, spawn_argv, maxprocs, info, 0, MPI_COMM_SELF, &intercomm, MPI_ERRCODES_IGNORE); MPI_Barrier(intercomm); MPI_Comm_disconnect(&intercomm); printf("OK\n"); } MPI_Finalize(); } <file_sep>/runtime/bin/cleanup.sh #!/bin/bash clean_server() { SERVER=$1 ITER=$2 MAX=$3 QUIET=$4 SCRIPTDIR=$PWD/`dirname $0`/ if [[ $QUIET == 0 ]] ; then echo "Cleaning server ($ITER / $MAX): $SERVER" fi ssh -oBatchMode=yes ${SERVER} ${SCRIPTDIR}/cleanup-scrub-local.sh } if [[ "x" != "x$CI_HOSTFILE" && -f "$CI_HOSTFILE" ]] ; then ALLHOSTS=(`cat $CI_HOSTFILE | sort | uniq`) else ALLHOSTS=(`hostname`) fi LEN=${#ALLHOSTS[@]} # Use a background mode if running at scale USE_BG=0 if [ $LEN -gt 10 ] ; then USE_BG=1 fi for (( i=0; i<${LEN}; i++ )); do if [ $USE_BG == 1 ] ; then if [ $(($i % 100)) == 0 ] ; then echo "| $i" else if [ $(($i % 10)) == 0 ] ; then echo -n "|" else echo -n "." fi fi fi if [ $USE_BG == 1 ] ; then clean_server ${ALLHOSTS[$i]} $i $LEN $USE_BG & sleep 0.25 else clean_server ${ALLHOSTS[$i]} $i $LEN $USE_BG echo "-------------------------" fi done if [ $USE_BG == 1 ] ; then echo "" echo "------------------------- Waiting" wait fi echo "------------------------- Done" exit 0 <file_sep>/status/configure.ac # -*- shell-script -*- # # Copyright (c) 2012-2020 Cisco Systems, Inc. All rights reserved. # # $COPYRIGHT$ # dnl dnl Init autoconf dnl AC_PREREQ([2.67]) AC_INIT([mpi-status-test], [1.0], [http://www.open-mpi.org]) AC_CONFIG_AUX_DIR([config]) AC_CONFIG_MACRO_DIR([config]) AC_CONFIG_SRCDIR([.]) echo "Configuring MPI_Status test" AM_INIT_AUTOMAKE([1.11 foreign -Wall -Werror]) # If Automake supports silent rules, enable them. m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) AH_TOP([/* -*- c -*- * * MPI_Status test suite configuation header file. * See the top-level LICENSE file for license and copyright * information. */ #ifndef MPI_STATUS_TEST_CONFIG_H #define MPI_STATUS_TEST_CONFIG_H ]) AH_BOTTOM([#endif /* MPI_STATUS_TEST_CONFIG_H */]) dnl dnl Make automake clean emacs ~ files for "make clean" dnl CLEANFILES="*~" AC_SUBST(CLEANFILES) dnl dnl Get various programs dnl Bias towards mpicc/mpic++/mpif77 dnl C compiler dnl if test "$CC" != ""; then BASE="`basename $CC`" else BASE= fi if test "$BASE" = "" -o "$BASE" = "." -o "$BASE" = "cc" -o \ "$BASE" = "gcc" -o "$BASE" = "xlc" -o "$BASE" = "pgcc" -o \ "$BASE" = "icc"; then AC_CHECK_PROG(HAVE_MPICC, mpicc, yes, no) if test "$HAVE_MPICC" = "yes"; then CC=mpicc export CC fi fi CFLAGS_save=$CFLAGS AC_PROG_CC CFLAGS=$CFLAGS_save dnl dnl Fortran compiler dnl if test "$FC" != ""; then BASE="`basename $FC`" else BASE= fi if test "$BASE" = "" -o "$BASE" = "." -o "$BASE" = "f77" -o \ "$BASE" = "g77" -o "$BASE" = "f90" -o "$BASE" = "g90" -o \ "$BASE" = "xlf" -o "$BASE" = "ifc" -o "$BASE" = "pgf77"; then AC_CHECK_PROG(HAVE_MPIFORT, mpifort, yes, no) AS_IF([test "$HAVE_MPIFORT" = "yes"], [FC=mpifort], [AC_CHECK_PROG([HAVE_MPIF90], mpif90, yes, no) AS_IF([test "$HAVE_MPIF90" = "yes"], [FC=mpif90], [AC_CHECK_PROG([HAVE_MPIF77], mpif77, yes, no) AS_IF([test "$HAVE_MPIF77" = "yes"], [FC=mpif77], [AC_MSG_WARN([Cannot find a suitable MPI compiler]) AC_MSG_ERROR([Cannot continue]) ]) ]) ]) export FC fi FCFLAGS_save=$FCFLAGS AC_PROG_FC FCFLAGS=$FCFLAGS_save dnl dnl Because these are meant to be used for debugging, after all dnl if test -z "$CFLAGS"; then CFLAGS="-g" fi if test -z "$FCFLAGS"; then FCFLAGS="-g"; fi AC_SUBST(FCFLAGS) if test -z "$FFLAGS"; then FFLAGS="-g"; fi AC_SUBST(FFLAGS) dnl dnl Ensure that we can compile and link a C MPI program dnl AC_LANG_PUSH([C]) AC_CHECK_HEADERS(mpi.h) AC_MSG_CHECKING([if linking MPI program works]) AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <mpi.h> ]], [[MPI_Comm a = MPI_COMM_WORLD]])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]) AC_MSG_WARN([Simple MPI program fails to link]) AC_MSG_ERROR([Cannot continue]) ]) AC_LANG_POP([C]) dnl dnl Make sure we have the C type MPI_F08_status dnl AC_CHECK_TYPES([MPI_F08_status], [], [AC_MSG_WARN([Cannot find MPI_F08_status type]) AC_MSG_ERROR([Cannot continue])], [#include <mpi.h>]) dnl dnl Check for the different Fortran bindings dnl AC_LANG_PUSH([Fortran]) AC_MSG_CHECKING([for mpif.h]) AC_LINK_IFELSE([AC_LANG_PROGRAM(, [[ include 'mpif.h' integer a a = MPI_COMM_WORLD]])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]) AC_MSG_WARN([Cannot compile an mpif.h program]) AC_MSG_ERROR([Cannot continue]) ]) AC_MSG_CHECKING([for mpi module]) AC_LINK_IFELSE([AC_LANG_PROGRAM(, [[ use mpi integer a a = MPI_COMM_WORLD]])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]) AC_MSG_WARN([Cannot compile a 'use mpi' program]) AC_MSG_ERROR([Cannot continue]) ]) AC_MSG_CHECKING([for mpi_f08 module]) AC_LINK_IFELSE([AC_LANG_PROGRAM(, [[ use mpi_f08 Type(MPI_Comm) :: a a = MPI_COMM_WORLD]])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]) AC_MSG_WARN([Cannot compile a 'use mpi_f08' program]) AC_MSG_ERROR([Cannot continue]) ]) AC_LANG_POP([Fortran]) dnl dnl Party on dnl AC_CONFIG_FILES([ Makefile src/Makefile ]) AC_OUTPUT <file_sep>/comm_split_type/cmsplit_type.c /* * Modified / Simplified version of MPICH MPI test suite version * for Open MPI specific split_topo values: * mpich-testsuite-4.1a1/comm/cmsplit_type.c * */ #include "mpi.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define MAX_NUM_LEVELS 32 static const char *split_topo[] = { "mpi_shared_memory", "hwthread", "core", "l1cache", "l2cache", "l3cache", "socket", "numanode", "board", "host", "cu", "cluster", NULL }; int verbose = 0; int mcw_rank = 0; int mcw_size = 0; static void sync_hr(void) { if (verbose) { fflush(NULL); MPI_Barrier(MPI_COMM_WORLD); if (mcw_rank == 0) { printf("-----------------------------------\n"); usleep(1000000); } fflush(NULL); MPI_Barrier(MPI_COMM_WORLD); } } int main(int argc, char *argv[]) { int rank, size, errs = 0, tot_errs = 0; int i; MPI_Comm comm; MPI_Info info; int ret; int value = 0; int expected_value = 3; MPI_Comm hwcomm[MAX_NUM_LEVELS]; int level_num = 0; char resource_type[100] = ""; int has_key = 0; int old_size; int new_size, new_rank; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &mcw_rank); MPI_Comm_size(MPI_COMM_WORLD, &mcw_size); /* * Verbosity */ if (getenv("MPITEST_VERBOSE")) { verbose = 1; } MPI_Bcast(&verbose, 1, MPI_INT, 0, MPI_COMM_WORLD); /* * Check to see if MPI_COMM_TYPE_SHARED works correctly */ MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, &comm); if (comm == MPI_COMM_NULL) { printf("MPI_COMM_TYPE_SHARED (no hint): got MPI_COMM_NULL\n"); errs++; } else { MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); if (rank == 0 && verbose) { printf("MPI_COMM_TYPE_SHARED (no hint): Created shared subcommunicator of size %d\n", size); } MPI_Comm_free(&comm); } sync_hr(); /* * Test MPI_COMM_TYPE_HW_GUIDED: * - Test with "mpi_hw_resource_type" = "mpi_shared_memory" */ MPI_Info_create(&info); MPI_Info_set(info, "mpi_hw_resource_type", "mpi_shared_memory"); if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying MPI Standard value %s\n", "mpi_shared_memory"); } ret = MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_HW_GUIDED, 0, info, &comm); if (ret != MPI_SUCCESS) { printf("MPI_COMM_TYPE_HW_GUIDED (%s) failed\n", split_topo[i]); errs++; } else if (comm != MPI_COMM_NULL) { MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); if (rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED (%s): Created shared subcommunicator of size %d\n", "mpi_shared_memory", size); } MPI_Comm_free(&comm); } MPI_Info_free(&info); sync_hr(); /* * Test MPI_COMM_TYPE_HW_GUIDED: * - Test with a variety of supported info values */ for (i = 0; split_topo[i]; i++) { MPI_Info_create(&info); MPI_Info_set(info, "mpi_hw_resource_type", split_topo[i]); if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying value %s\n", split_topo[i]); } ret = MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_HW_GUIDED, 0, info, &comm); /* result will depend on platform and process bindings, just check returns */ if (ret != MPI_SUCCESS) { printf("MPI_COMM_TYPE_HW_GUIDED (%s) failed\n", split_topo[i]); errs++; } else if (comm != MPI_COMM_NULL) { MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); if (rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED (%s): Created shared subcommunicator of size %d\n", split_topo[i], size); } MPI_Comm_free(&comm); } MPI_Info_free(&info); sync_hr(); } /* * Test MPI_COMM_TYPE_HW_GUIDED: * - pass MPI_INFO_NULL, it must return MPI_COMM_NULL. */ if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying MPI_INFO_NULL\n"); } info = MPI_INFO_NULL; MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_HW_GUIDED, 0, info, &comm); if (comm != MPI_COMM_NULL) { printf("MPI_COMM_TYPE_HW_GUIDED with MPI_INFO_NULL didn't return MPI_COMM_NULL\n"); errs++; MPI_Comm_free(&comm); } else { if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying MPI_INFO_NULL - Passed\n"); } } sync_hr(); /* * Test MPI_COMM_TYPE_HW_GUIDED: * - info without correct key, it must return MPI_COMM_NULL. */ if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying invalid key\n"); } MPI_Info_create(&info); MPI_Info_set(info, "bogus_key", split_topo[0]); MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_HW_GUIDED, 0, info, &comm); if (comm != MPI_COMM_NULL) { printf("MPI_COMM_TYPE_HW_GUIDED without correct key didn't return MPI_COMM_NULL\n"); errs++; MPI_Comm_free(&comm); } else { if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying invalid key - Passed\n"); } } MPI_Info_free(&info); sync_hr(); /* * Test MPI_COMM_TYPE_HW_GUIDED: * - Test with "mpi_hw_resource_type" = "mpi_shared_memory" * - Mix in some MPI_UNDEFINED values to make sure those are handled properly */ expected_value = 3; if (expected_value > mcw_size) { expected_value = mcw_size; } MPI_Info_create(&info); MPI_Info_set(info, "mpi_hw_resource_type", "mpi_shared_memory"); if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying MPI Standard value %s with some MPI_UNDEFINED\n", "mpi_shared_memory"); } if (mcw_rank < expected_value) { ret = MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_HW_GUIDED, 0, info, &comm); } else { ret = MPI_Comm_split_type(MPI_COMM_WORLD, MPI_UNDEFINED, 0, info, &comm); } if (ret != MPI_SUCCESS) { printf("MPI_COMM_TYPE_HW_GUIDED (%s) failed\n", split_topo[i]); errs++; } else if (comm != MPI_COMM_NULL) { MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); value = 1; if (rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED (%s): %d/%d Created shared subcommunicator of size %d\n", "mpi_shared_memory", mcw_rank, mcw_size, size); } MPI_Comm_free(&comm); } else if (verbose) { value = 0; printf("MPI_COMM_TYPE_HW_GUIDED (%s): %d/%d Returned MPI_COMM_NULL\n", "mpi_shared_memory", mcw_rank, mcw_size); } MPI_Info_free(&info); if (mcw_rank == 0) { MPI_Reduce(MPI_IN_PLACE, &value, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (expected_value != value) { printf("MPI_COMM_TYPE_HW_GUIDED (%s): Failed: Verify expected %d == actual %d\n", "mpi_shared_memory", expected_value, value); } else if (verbose) { printf("MPI_COMM_TYPE_HW_GUIDED (%s): Passed: Verify expected %d == actual %d\n", "mpi_shared_memory", expected_value, value); } } else { MPI_Reduce(&value, NULL, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); } MPI_Barrier(MPI_COMM_WORLD); sync_hr(); /* * Test MPI_COMM_TYPE_HW_GUIDED: * - info with correct key, but different values a different ranks, it must throw an error */ #if 0 for (i = 0; NULL != split_topo[i]; i++) { ; } if (i < 2) { if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying mismatched values -- SKIPPED not enough valid values (%d)\n", i); } } else { if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying mismatched values\n"); } MPI_Info_create(&info); if (mcw_rank == 0) { MPI_Info_set(info, "mpi_hw_resource_type", split_topo[0]); } else { MPI_Info_set(info, "mpi_hw_resource_type", split_topo[1]); } MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_HW_GUIDED, 0, info, &comm); if (comm != MPI_COMM_NULL) { printf("MPI_COMM_TYPE_HW_GUIDED with mismatched values key didn't return MPI_COMM_NULL\n"); errs++; MPI_Comm_free(&comm); } MPI_Info_free(&info); } #endif /* Test MPI_COMM_TYPE_HW_GUIDED: * - info with semantically matching split_types and keys, it must throw an error */ #if 0 if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_GUIDED: Trying mismatched keys but semantically matching\n"); } if (mcw_rank == 0) { MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, &comm); } else { MPI_Info_create(&info); MPI_Info_set(info, "mpi_hw_resource_type", "mpi_shared_memory"); MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_HW_GUIDED, 0, info, &comm); } if (comm != MPI_COMM_NULL) { printf("MPI_COMM_TYPE_HW_GUIDED with mismatched values key didn't return MPI_COMM_NULL\n"); errs++; MPI_Comm_free(&comm); } MPI_Info_free(&info); #endif /* Test MPI_COMM_TYPE_HW_UNGUIDED: * - Simple single iteration */ if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_UNGUIDED: Trying basic\n"); } MPI_Info_create(&info); MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_HW_UNGUIDED, 0, info, &comm); if (comm != MPI_COMM_NULL) { resource_type[0] = '\0'; has_key = 0; MPI_Comm_size(comm, &new_size); MPI_Comm_rank(comm, &new_rank); if (!(new_size < mcw_size)) { printf("MPI_COMM_TYPE_HW_UNGUIDED: Expected comm to be a proper sub communicator\n"); errs++; } MPI_Info_get(info, "mpi_hw_resource_type", 100, resource_type, &has_key); if (!has_key || strlen(resource_type) == 0) { printf("MPI_COMM_TYPE_HW_UNGUIDED: info for mpi_hw_resource_type not returned\n"); errs++; } if (new_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_UNGUIDED (%s): %d/%d -> %d/%d Created shared subcommunicator\n", resource_type, mcw_rank, mcw_size, new_rank, new_size); } MPI_Comm_free(&comm); } else if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_UNGUIDED: Returned MPI_COMM_NULL\n"); } MPI_Barrier(MPI_COMM_WORLD); sync_hr(); /* Test MPI_COMM_TYPE_HW_UNGUIDED: * - Loop until all are NULL * Example 7.4 from MPI 4.0 standard */ hwcomm[level_num] = MPI_COMM_WORLD; while((hwcomm[level_num] != MPI_COMM_NULL) && (level_num < MAX_NUM_LEVELS-1)) { MPI_Comm_rank(hwcomm[level_num], &rank); if (rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_UNGUIDED: (iter = %d) %d/%d Trying loop\n", level_num, mcw_rank, mcw_size); } MPI_Info_create(&info); MPI_Comm_split_type(hwcomm[level_num], MPI_COMM_TYPE_HW_UNGUIDED, rank, info, &hwcomm[level_num+1]); if (hwcomm[level_num+1] == MPI_COMM_NULL) { printf("MPI_COMM_TYPE_HW_UNGUIDED: (iter = %d) %d/%d Returned MPI_COMM_NULL\n", level_num, mcw_rank, mcw_size); } else if (hwcomm[level_num+1] == MPI_COMM_SELF) { printf("MPI_COMM_TYPE_HW_UNGUIDED: (iter = %d) %d/%d Returned MPI_COMM_SELF\n", level_num, mcw_rank, mcw_size); } else { MPI_Comm_rank(hwcomm[level_num+1], &rank); MPI_Comm_size(hwcomm[level_num], &old_size); MPI_Comm_size(hwcomm[level_num+1], &size); if (!(size < old_size)) { printf("MPI_COMM_TYPE_HW_UNGUIDED: Expected comm to be a proper sub communicator\n"); errs++; } resource_type[0] = '\0'; has_key = 0; MPI_Info_get(info, "mpi_hw_resource_type", 100, resource_type, &has_key); if (!has_key || strlen(resource_type) == 0) { printf("MPI_COMM_TYPE_HW_UNGUIDED: info for mpi_hw_resource_type not returned\n"); errs++; } if (rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_UNGUIDED: (iter = %d) %d/%d -> %d/%d Returned subcommunicator of (%s)\n", level_num, mcw_rank, mcw_size, rank, size, resource_type); } } level_num++; } MPI_Barrier(MPI_COMM_WORLD); sync_hr(); /* * Test MPI_COMM_TYPE_HW_UNGUIDED: * - Single step * - Mix in some MPI_UNDEFINED values to make sure those are handled properly */ expected_value = 3; if (expected_value > mcw_size) { expected_value = mcw_size; } MPI_Info_create(&info); if (mcw_rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_UNGUIDED: Trying MPI Standard value %s with some MPI_UNDEFINED\n", "mpi_shared_memory"); } if (mcw_rank < expected_value) { ret = MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_HW_UNGUIDED, 0, info, &comm); } else { ret = MPI_Comm_split_type(MPI_COMM_WORLD, MPI_UNDEFINED, 0, info, &comm); } if (ret != MPI_SUCCESS) { printf("MPI_COMM_TYPE_HW_UNGUIDED (%s) failed\n", split_topo[i]); errs++; } else if (comm != MPI_COMM_NULL) { resource_type[0] = '\0'; has_key = 0; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &new_size); if (!(new_size < mcw_size)) { printf("MPI_COMM_TYPE_HW_UNGUIDED: Expected comm to be a proper sub communicator\n"); errs++; } MPI_Info_get(info, "mpi_hw_resource_type", 100, resource_type, &has_key); if (!has_key || strlen(resource_type) == 0) { printf("MPI_COMM_TYPE_HW_UNGUIDED: info for mpi_hw_resource_type not returned\n"); errs++; } if (rank == 0 && verbose) { printf("MPI_COMM_TYPE_HW_UNGUIDED: %d/%d -> %d/%d Created shared subcommunicator of (%s)\n", mcw_rank, mcw_size, rank, new_size, resource_type); } MPI_Comm_free(&comm); value = 1; } else if (verbose) { value = 0; printf("MPI_COMM_TYPE_HW_UNGUIDED: %d/%d Returned MPI_COMM_NULL\n", mcw_rank, mcw_size); } MPI_Info_free(&info); MPI_Barrier(MPI_COMM_WORLD); sync_hr(); /* * All done - figure out if we passed */ done: MPI_Reduce(&errs, &tot_errs, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); MPI_Finalize(); return tot_errs; } <file_sep>/sessions/sessions_ex2.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" int main(int argc, char *argv[]) { int i, n_psets, psetlen, rc, ret; int valuelen; int flag = 0; char *pset_name = NULL; char *info_val = NULL; MPI_Session shandle = MPI_SESSION_NULL; MPI_Info sinfo = MPI_INFO_NULL; MPI_Group pgroup = MPI_GROUP_NULL; if (argc < 2) { fprintf(stderr, "A process set name fragment is required\n"); return -1; } rc = MPI_Session_init(MPI_INFO_NULL, MPI_ERRORS_RETURN, &shandle); if (rc != MPI_SUCCESS) { fprintf(stderr, "Could not initialize session, bailing out\n"); return -1; } MPI_Session_get_num_psets(shandle, MPI_INFO_NULL, &n_psets); for (i=0, pset_name=NULL; i<n_psets; i++) { psetlen = 0; MPI_Session_get_nth_pset(shandle, MPI_INFO_NULL, i, &psetlen, NULL); pset_name = (char *)malloc(sizeof(char) * psetlen); MPI_Session_get_nth_pset(shandle, MPI_INFO_NULL, i, &psetlen, pset_name); if (strstr(pset_name, argv[1]) != NULL) break; free(pset_name); pset_name = NULL; } /* * get instance of an info object for this Session */ MPI_Session_get_pset_info(shandle, pset_name, &sinfo); MPI_Info_get_valuelen(sinfo, "size", &valuelen, &flag); info_val = (char *)malloc(valuelen+1); MPI_Info_get(sinfo, "size", valuelen, info_val, &flag); free(info_val); /* * create a group from the process set */ rc = MPI_Group_from_session_pset(shandle, pset_name, &pgroup); ret = (rc == MPI_SUCCESS) ? 0 : -1; free(pset_name); MPI_Group_free(&pgroup); MPI_Info_free(&sinfo); MPI_Session_finalize(&shandle); fprintf(stderr, "Test completed ret = %d\n", ret); return ret; } <file_sep>/sessions/sessions_test3.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" void print_error(const char *msg, int rc) { char err_str[MPI_MAX_ERROR_STRING]; int resultlen = sizeof(err_str) - 1; MPI_Error_string(rc, err_str, &resultlen); fprintf (stderr, "%s return err code = %d (%s)\n", msg, rc, err_str); } void my_session_errhandler (MPI_Session *foo, int *bar, ...) { fprintf(stderr, "errhandler called with error %d\n", *bar); } int main (int argc, char *argv[]) { MPI_Session session; MPI_Errhandler errhandler; MPI_Group group; MPI_Info info; int rc, npsets, i; rc = MPI_Session_create_errhandler (my_session_errhandler, &errhandler); if (MPI_SUCCESS != rc) { print_error ("Error handler creation failed", rc); return -1; } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { print_error ("Info creation failed", rc); return -1; } rc = MPI_Info_set(info, "mpi_thread_support_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { print_error ("Info key/val set failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session); if (MPI_SUCCESS != rc) { print_error ("Session initialization failed", rc); return -1; } rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Group_from_session_pset (session, "mpi://INVALID", &group); if (MPI_SUCCESS != rc) { print_error ("Could not get a group for mpi://INVALID. ", rc); printf("sessions_test3 passed\n"); MPI_Errhandler_free (&errhandler); MPI_Info_free (&info); MPI_Session_finalize (&session); return 0; } else { printf("Use of invalid pset failed to throw an error!\n"); printf("sessions_test3 failed\n"); MPI_Errhandler_free (&errhandler); MPI_Info_free (&info); MPI_Session_finalize (&session); return -1; } }<file_sep>/singleton/run.sh #!/bin/bash -e echo "=====================" echo "Testing: Hello with mpirun" echo "=====================" mpirun --np 1 ./hello_c echo "=====================" echo "Testing: Hello as a singleton" echo "=====================" ./hello_c echo "=====================" echo "Testing: MPI_Comm_spawn with mpirun" echo "=====================" mpirun --np 1 ./simple_spawn ./simple_spawn echo "=====================" echo "Testing: MPI_Comm_spawn as a singleton" echo "=====================" ./simple_spawn ./simple_spawn echo "=====================" echo "Testing: MPI_Comm_spawn_multiple with mpirun" echo "=====================" mpirun --np 1 ./simple_spawn_multiple ./simple_spawn_multiple echo "=====================" echo "Testing: MPI_Comm_spawn_multiple as a singleton" echo "=====================" ./simple_spawn_multiple ./simple_spawn_multiple echo "=====================" echo "Success" echo "=====================" <file_sep>/comm_split_type/Makefile CFLAGS = -g -O0 MPICC = mpicc PROGS = cmsplit_type all: $(PROGS) cmsplit_type: cmsplit_type.c $(MPICC) cmsplit_type.c $(CFLAGS) -o cmsplit_type clean: rm $(PROGS) <file_sep>/status/src/Makefile.am # # Copyright (c) 2020 Cisco Systems, Inc. All rights reserved # # $COPYRIGHT$ # noinst_PROGRAMS = status_test status_test_SOURCES = \ status_fortran.F90 \ status_c.c <file_sep>/packaging/Makefile.am # # Copyright (c) 2020 IBM Corporation. All rights reserved. # # $COPYRIGHT$ # noinst_PROGRAMS = \ run_nmcheck EXTRA_DIST = nmcheck_prefix.pl <file_sep>/sessions/README.md # Tests for MPI Sessions extensions to the MPI API To build these tests you will need the following package: - MPI Sessions prototype ## Installing the prototype ``` git clone --recursive <EMAIL>:hpc/ompi.git cd ompi git checkout sessions_new ./autogen.pl ./configure --prefix=my_sandbox make -j install ``` ## Installing the tests ``` export PATH=my_sandbox/bin:$PATH git clone https://github.com/open-mpi/ompi-tests-public.git cd ompi-tests-public/sessions make ``` ## Running the tests Assuming the checkout of the prototype occurred after 6/26/20, the tests can be run using either the ```mpirun``` installed as part of the build of the prototype, or prte/prun can be used. When using prte, the tests can be run as follows: ``` prte --daemonize prun -n 4 ./sessions_ex2 mpi://world prun -n 4 ./sessions_ex3 prun -n 4 ./sessions_ex4 prun -n 4 ./sessions_test ``` To run using mpirun: ``` mpirun -np 4 ./sessions_ex2 mpi://world mpirun -np 4 ./sessions_ex3 mpirun -np 4 ./sessions_ex4 mpirun -np 4 ./sessions_test ``` This example assumes your system has at least 4 slots available for MPI processes. Note the third example may not have been built if you are using an old Fortran compiler that isn't able to generate the ```mpi_f08``` Fortran module. ## Special instructions for using prte/prun on a Cray XC and SLURM On Cray XE/XC systems running SLURM, prte has to use a different procedure for launching processes on the first node of a SLURM allocation. Namely, prte launches a prte daemon using the local slurmd daemon. As a consequence, there are effectively two prte daemons on the head node, the prte launched on the command line and a second launched via slurmd. To avoid annoying things like loss of stdout/stdin from the processes launched on the head node owing to having two prte daemons running on the node, additional arguments most be added to the prte and prun commands: ``` prte --daemonize --system-server prun -n 4 --system-server-first (additional arguments) ``` # Old instructions These instructions are applicable if you are working with a checkout of the MPI Sessions prototype prior to 6/26/20. To build these tests you will need the following several packages: - most recent version of PMIx - most recent version of prrte - MPI Sessions prototype ## Installing PMIx ``` git clone <EMAIL>:pmix/pmix.git cd pmix ./autogen.pl ./configure --prefix=my_sandbox --with-libevent make -j install ``` ## Installing prrte ``` git clone <EMAIL>:pmix/prrte.git cd prrte ./autogen.pl ./configure --prefix=my_sandbox --with-libevent --with-pmix=my_sandbox make -j install ``` ## Installing the prototype ``` git clone <EMAIL>:hpc/ompi.git cd ompi git checkout sessions_new ./autogen.pl ./configure --prefix=my_sandbox --with-libevent --with-pmix=my_sandbox make -j install ``` ## Installing and running these tests ``` export PATH=my_sandbox/bin:$PATH make prte --daemonize prun -n 4 ./sessions_ex2 mpi://world prun -n 4 ./sessions_ex3 prun -n 4 ./sessions_ex4 prun -n 4 ./sessions_test ``` This example assumes your system has at least 4 slots available for MPI processes. ## Special instructions for Cray XC and SLURM On Cray XE/XC systems running SLURM, prte has to use a different procedure for launching processes on the first node of a SLURM allocation. Namely, prte launches a prte daemon using the local slurmd daemon. As a consequence, there are effectively two prte daemons on the head node, the prte launched on the command line and a second launched via slurmd. To avoid annoying things like loss of stdout/stdin from the processes launched on the head node owing to having two prte daemons running on the node, additional arguments most be added to the prte and prun commands: ``` prte --daemonize --system-server prun -n 4 --system-server-first (additional arguments) ``` ## Test documentation sessions_test1: Initialize one session, finalize that sessions, then initialize another session sessions_test2: Initialize two sessions and perform operations with each session simultaneously, then finalize both sessions sessions_test3: Try to make a group from an invalid pset (should fail) sessions_test4: Try to make a group from a pset using MPI_GROUP_NULL (should fail) sessions_test5: Initialize two sessions, perform functions with one session and finalize that session, then perform functions with the other session after the first has been finalized sessions_test6: Same as sessions_test1 but with the sessions using different names sessions_test7: Initialize two sessions, perform operations with one and finalize it, then perform operations with the other and finalize it sessions_test8: Initialize two sessions, create one comm in each, and compare them (should fail because objects from different sessions shall not be intermixed with each other in a single MPI procedure call per the MPI standard) sessions_test9: Initialize the World model and Sessions model, make a comm using the sessions and split it, then make an intercomm using the split comm from the session and MPI_COMM_WORLD (should fail because MPI objects derived from the Sessions model shall not be intermixed in a single MPI procedure call with MPI objects derived from the World model per the MPI standard) sessions_test10: Initialize World model, initialize Sessions model, finalize Sessions model, finalize World model sessions_test11: Initialize World model, initialize Sessions model, finalize World model, finalize Sessions model sessions_test12: Initialize Sessions model, initialize World model, finalize Sessions model, finalize World model sessions_test13: Initialize Sessions model, initialize World model, finalize World model, finalize Sessions model sessions_test14: Initialize a session, create a comm, then try to use that comm with a comm from MPI_Comm_get_parent (should fail because MPI objects derived from the Sessions Model shall not be intermixed in a single MPI procedure call with MPI objects derived from the communicator obtained from a call to MPI_COMM_GET_PARENT or MPI_COMM_JOIN) sessions_test15: Initialize two sessions, create MPI_Requests using comms from different sessions, then include MPI_Requests from different sessions in one call to each of the following functions: MPI_Waitall(), MPI_Waitsome(), MPI_Waitany(), MPI_Testall(), MPI_Testsome(), and MPI_Testany() sessions_test16: Initialize a sessions, create a comm from the session, then attempt to access the values of the default attributes usually attached to MPI_COMM_WORLD (MPI_TAG_UB, MPI_HOST, MPI_IO, and MPI_WTIME_IS_GLOBAL). Per the MPI Standard, only the MPI_TAG_UB attribute should be accessible when using the Sessions model. <file_sep>/sessions/sessions_test16.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" void print_error(const char *msg, int rc) { char err_str[MPI_MAX_ERROR_STRING]; int resultlen = sizeof(err_str) - 1; MPI_Error_string(rc, err_str, &resultlen); fprintf (stderr, "%s return err code = %d (%s)\n", msg, rc, err_str); } void my_session_errhandler (MPI_Session *foo, int *bar, ...) { fprintf(stderr, "errhandler called with error %d\n", *bar); } int main (int argc, char *argv[]) { MPI_Session session; MPI_Errhandler errhandler; MPI_Group group; MPI_Comm comm_world; MPI_Info info; int rc, npsets, one = 1, sum, i; rc = MPI_Session_create_errhandler (my_session_errhandler, &errhandler); if (MPI_SUCCESS != rc) { print_error("Error handler creation failed", rc); return -1; } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { print_error("Info creation failed", rc); return -1; } rc = MPI_Info_set(info, "mpi_thread_support_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { print_error("Info key/val set failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session); if (MPI_SUCCESS != rc) { print_error("Session initialization failed", rc); return -1; } rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Group_from_session_pset (session, "mpi://WORLD", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://WORLD. ", rc); return -1; } MPI_Comm_create_from_group (group, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world); MPI_Group_free (&group); int *val, flag; MPI_Comm_get_attr(comm_world, MPI_TAG_UB, &val, &flag); if (flag) { printf("attr val found for index: %d\n", MPI_TAG_UB); } else { printf("attr val not found for index: %d\n", MPI_TAG_UB); return -1; } MPI_Comm_get_attr(comm_world, MPI_HOST, &val, &flag); if (flag) { printf("attr val found for index: %d but should not have\n", MPI_HOST); return -1; } else { printf("attr val not found for index: %d\n", MPI_HOST); } MPI_Comm_get_attr(comm_world, MPI_IO, &val, &flag); if (flag) { printf("attr val found for index: %d but should not have\n", MPI_IO); return -1; } else { printf("attr val not found for index: %d\n", MPI_IO); } MPI_Comm_get_attr(comm_world, MPI_WTIME_IS_GLOBAL, &val, &flag); if (flag) { printf("attr val found for index: %d but should not have\n", MPI_WTIME_IS_GLOBAL); return -1; } else { printf("attr val not found for index: %d\n", MPI_WTIME_IS_GLOBAL); } MPI_Errhandler_free (&errhandler); MPI_Info_free (&info); MPI_Comm_free (&comm_world); MPI_Session_finalize (&session); return 0; } <file_sep>/events/events_dropped.c /* * events_dropped.c * * Test dropped event callback registration and execution * */ #include "events_common.h" char user_data_string[256] = "Test String"; // Test flags int event_cb_success = 0; int event_free_cb_success = 0; int event_free_cb_user_data_access = 1; int event_handle_get_info_success = 1; int event_handle_set_info_success = 1; int event_handle_set_info_updated = 0; int event_callback_get_info_success = 1; int event_callback_set_info_success = 1; int event_callback_set_info_updated = 0; int event_handle_alloc_event_index_exceed_handled = 1; int event_handle_alloc_event_index_negative_handled = 1; int event_set_dropped_handler_success = 0; int event_dropped_cb_success = 0; void print_results() { if ( 0 != rank ) return; if ( 0 == event_dropped_cb_success ) error_count++; print_pf_result("MPI_T_event_set_dropped_handler", "Event Set Dropped Callback Success", event_set_dropped_handler_success); print_pf_result("MPI_T_event_set_dropped_handler", "Event Set Dropped Callback Called", event_dropped_cb_success); fprintf(outstream, "%-*s - %-*s : %6d\n", func_width, "TOTAL ERROR COUNT", metric_width, "", error_count); } void test_event_dropped_cb_function(MPI_Count count, MPI_T_event_registration event_registration, int source_index, MPI_T_cb_safety cb_safety, void *user_data) { print_debug("In dropped_cb_function : %s %s %d\n", __func__, __FILE__, __LINE__); //print_debug("user_data is :%s:\n", (char*)user_data); //print_debug("user_data_string is :%s:\n", (char*)user_data_string); event_dropped_cb_success = 1; if ( NULL == user_data || strcmp(user_data, user_data_string) ) print_error("test_event_cb_function could not access user_data", NO_MPI_ERROR_CODE, TEST_CONTINUE); } void test_dropped() { int i, retval; /* * int MPI_T_event_set_dropped_handler( * MPI_T_event_registration event_registration, * MPI_T_event_dropped_cb_function dropped_cb_function) * * typedef void MPI_T_event_dropped_cb_function(MPI_Count count, * MPI_T_event_registration event_registration, int source_index, * MPI_T_cb_safety cb_safety, void *user_data); * */ int event_index; MPI_T_event_registration event_registration; for ( i = 0; i < 1; i++ ) { event_index = i; print_debug("Testing expected success for index %d\n", event_index); retval = MPI_T_event_handle_alloc(event_index, MPI_COMM_WORLD, MPI_INFO_NULL, &event_registration) ; if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_handle_alloc did not return MPI_SUCCESS", retval, TEST_EXIT); /* * int MPI_T_event_set_dropped_handler( * MPI_T_event_registration event_registration, * MPI_T_event_dropped_cb_function dropped_cb_function) */ cb_user_data = (void*)user_data_string; print_debug("cb_user_data is %s\n", cb_user_data); print_debug("Testing expected MPI_T_event_register_callback success for index %d\n", event_index); retval = MPI_T_event_set_dropped_handler(event_registration, test_event_dropped_cb_function); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_set_dropped_handler did not return MPI_SUCCESS", retval, TEST_EXIT); else event_set_dropped_handler_success = 1; if ( do_failure_tests ) { } generate_callback_activity(); } } int main (int argc, char** argv) { test_init("MPI_T Events Callback Tests", argc, argv); test_dropped(); print_results(); MPI_T_finalize(); MPI_Finalize(); return 0; } <file_sep>/collective-big-count/diagnostic.c /* * Copyright (c) 2021-2022 IBM Corporation. All rights reserved. * * $COPYRIGHT$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <complex.h> #include <limits.h> #include "common.h" int main(int argc, char** argv) { init_environment(argc, argv); return 0; } <file_sep>/collective-big-count/test_bcast.c /* * Copyright (c) 2021-2022 IBM Corporation. All rights reserved. * * $COPYRIGHT$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mpi.h> #include "common.h" int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking); int main(int argc, char** argv) { /* * Initialize the MPI environment */ int ret = 0; MPI_Init(NULL, NULL); init_environment(argc, argv); #ifndef TEST_UNIFORM_COUNT // Each rank contribues: V_SIZE_INT elements // Largest buffer is : V_SIZE_INT elements ret += my_c_test_core(MPI_INT, V_SIZE_INT, true); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, true); if (allow_nonblocked) { ret += my_c_test_core(MPI_INT, V_SIZE_INT, false); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, false); } #else size_t proposed_count; // Each rank contribues: TEST_UNIFORM_COUNT elements // Largest buffer is : TEST_UNIFORM_COUNT elements proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_INT, proposed_count, true); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, true); if (allow_nonblocked) { proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_INT, proposed_count, false); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, false); } #endif /* * All done */ MPI_Finalize(); return ret; } int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking) { int ret = 0; int i; MPI_Request request; char *mpi_function = blocking ? "MPI_Bcast" : "MPI_Ibcast"; // Actual payload size as divisible by the sizeof(dt) size_t payload_size_actual; /* * Initialize vector */ int *my_int_vector = NULL; double _Complex *my_dc_vector = NULL; void *buff_ptr = NULL; unsigned int num_wrong = 0; assert(MPI_INT == dtype || MPI_C_DOUBLE_COMPLEX == dtype); assert(total_num_elements <= INT_MAX); if( MPI_INT == dtype ) { payload_size_actual = total_num_elements * sizeof(int); my_int_vector = (int*)safe_malloc(payload_size_actual); buff_ptr = my_int_vector; } else { payload_size_actual = total_num_elements * sizeof(double _Complex); my_dc_vector = (double _Complex*)safe_malloc(payload_size_actual); buff_ptr = my_dc_vector; } for(i = 0; i < total_num_elements; ++i) { if( MPI_INT == dtype ) { if (world_rank == 0) { my_int_vector[i] = i; } else { my_int_vector[i] = -1; } } else { if (world_rank == 0) { my_dc_vector[i] = 1.0*i - 1.0*i*I; } else { my_dc_vector[i] = -1.0 - 1.0*I; } } } if (world_rank == 0) { printf("---------------------\nResults from %s(%s x %zu = %zu or %s):\n", mpi_function, (MPI_INT == dtype ? "int" : "double _Complex"), total_num_elements, payload_size_actual, human_bytes(payload_size_actual)); } if (blocking) { MPI_Bcast(buff_ptr, (int)total_num_elements, dtype, 0, MPI_COMM_WORLD); } else { MPI_Ibcast(buff_ptr, (int)total_num_elements, dtype, 0, MPI_COMM_WORLD, &request); MPI_Wait(&request, MPI_STATUS_IGNORE); } /* * Check results. */ for(i = 0; i < total_num_elements; ++i) { if( MPI_INT == dtype ) { if(my_int_vector[i] != i) { ++num_wrong; } } else { if(my_dc_vector[i] != 1.0*i - 1.0*i*I) { ++num_wrong; } } } if( 0 == num_wrong) { printf("Rank %2d: Passed\n", world_rank); } else { printf("Rank %2d: ERROR: DI in %14u of %14zu slots (%6.1f %% wrong)\n", world_rank, num_wrong, total_num_elements, ((num_wrong * 1.0)/total_num_elements)*100.0); ret = 1; } if(NULL != my_int_vector) { free(my_int_vector); } if(NULL != my_dc_vector) { free(my_dc_vector); } fflush(NULL); MPI_Barrier(MPI_COMM_WORLD); return ret; } <file_sep>/runtime/bin/pretty-print-hwloc/Makefile.am # # High level Makefile # headers = sources = nodist_headers = EXTRA_DIST = SUBDIRS = . src <file_sep>/sessions/sessions_test9.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" void print_error(const char *msg, int rc) { char err_str[MPI_MAX_ERROR_STRING]; int resultlen = sizeof(err_str) - 1; MPI_Error_string(rc, err_str, &resultlen); fprintf (stderr, "%s return err code = %d (%s)\n", msg, rc, err_str); } void my_session_errhandler (MPI_Session *foo, int *bar, ...) { fprintf(stderr, "errhandler called with error %d\n", *bar); } int main (int argc, char *argv[]) { MPI_Session session; MPI_Errhandler errhandler; MPI_Group group; MPI_Comm comm_world; MPI_Info info; int rc, npsets, one = 1, sum, i; MPI_Init(&argc, &argv); rc = MPI_Session_create_errhandler (my_session_errhandler, &errhandler); if (MPI_SUCCESS != rc) { print_error("Error handler creation failed", rc); return -1; } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { print_error("Info creation failed", rc); return -1; } rc = MPI_Info_set(info, "mpi_thread_support_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { print_error("Info key/val set failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session); if (MPI_SUCCESS != rc) { print_error("Session initialization failed", rc); return -1; } rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Group_from_session_pset (session, "mpi://WORLD", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://WORLD. ", rc); return -1; } MPI_Comm_create_from_group (group, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world); MPI_Group_free (&group); MPI_Comm myComm; /* intra-communicator of local sub-group */ MPI_Comm myFirstComm; /* inter-communicator */ MPI_Comm mySecondComm; /* second inter-communicator (group 1 only) */ int membershipKey; int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); /* User code must generate membershipKey in the range [0, 1, 2] */ membershipKey = rank % 3; /* Build intra-communicator for local sub-group */ MPI_Comm_split(comm_world, membershipKey, rank, &myComm); /* Build inter-communicators. Tags are hard-coded. */ if (membershipKey == 0) { /* Group 0 communicates with group 1. */ MPI_Intercomm_create( myComm, 0, MPI_COMM_WORLD, 1, 1, &myFirstComm); } else if (membershipKey == 1) { /* Group 1 communicates with groups 0 and 2. */ MPI_Intercomm_create( myComm, 0, MPI_COMM_WORLD, 0, 1, &myFirstComm); MPI_Intercomm_create( myComm, 0, MPI_COMM_WORLD, 2, 12, &mySecondComm); } else if (membershipKey == 2) { /* Group 2 communicates with group 1. */ MPI_Intercomm_create( myComm, 0, MPI_COMM_WORLD, 1, 12, &myFirstComm); } /* Do work ... */ switch(membershipKey) /* free communicators appropriately */ { case 1: MPI_Comm_free(&mySecondComm); case 0: case 2: MPI_Comm_free(&myFirstComm); break; } MPI_Errhandler_free (&errhandler); MPI_Info_free (&info); MPI_Comm_free (&comm_world); MPI_Session_finalize (&session); printf("Done\n"); MPI_Finalize(); return 0; } <file_sep>/collective-big-count/Makefile # # Copyright (c) 2021-2022 IBM Corporation. All rights reserved. # # $COPYRIGHT$ # ###################################################################### # Utilities ###################################################################### .PHONY: default help CC = mpicc F77 = mpif77 F90 = mpif90 MPIRUN = mpirun RM = /bin/rm -f # GCC CC_FLAGS = -g -O0 -Wall -Werror # Clang #CC_FLAGS = -g -O0 -Wall -Wshorten-64-to-32 -Werror F90_FLAGS = F77_FLAGS = $(F90_FLAGS) ###################################################################### # TEST_UNIFORM_COUNT: (Default defined here) # The 'count' size to be used regardless of the datatype # This should never exceed that of INT_MAX (2147483647) which # is the maximum count allowed by the MPI Interface in MPI 3 ###################################################################### # Test at the limit of INT_MAX : 2147483647 TEST_UNIFORM_COUNT=2147483647 ###################################################################### # TEST_PAYLOAD_SIZE: (Default in common.h) # This value is the total payload size the collective should perform. # The 'count' is calculated as relative to the datatype size so # as to target this payload size as closely as possible: # count = TEST_PAYLOAD_SIZE / sizeof(datatype) ###################################################################### # INT_MAX : == 2 GB so guard will not trip (INT_MAX == 2GB -1byte) TEST_PAYLOAD_SIZE=2147483647 ###################################################################### # Binaries ###################################################################### BINCC = \ test_alltoall \ test_alltoallv \ test_allgather test_allgatherv \ test_allreduce \ test_bcast \ test_exscan \ test_gather test_gatherv \ test_reduce \ test_reduce_scatter \ test_scan \ test_scatter test_scatterv \ diagnostic BIN = $(BINCC) ###################################################################### # Targets ###################################################################### all: $(BIN) clean: $(RM) $(BIN) *.o *_uniform_count *_uniform_payload diagnostic: common.h diagnostic.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. diagnostic.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. diagnostic.c test_allgather: common.h test_allgather.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_allgather.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_allgather.c test_allgatherv: common.h test_allgatherv.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_allgatherv.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_allgatherv.c test_allreduce: common.h test_allreduce.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_allreduce.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_allreduce.c test_alltoall: common.h test_alltoall.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_alltoall.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_alltoall.c test_alltoallv: common.h test_alltoallv.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_alltoallv.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_alltoallv.c test_bcast: common.h test_bcast.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_bcast.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_bcast.c test_exscan: common.h test_exscan.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_exscan.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_exscan.c test_gather: common.h test_gather.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_gather.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_gather.c test_gatherv: common.h test_gatherv.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_gatherv.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_gatherv.c test_reduce: common.h test_reduce.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_reduce.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_reduce.c test_reduce_scatter: common.h test_reduce_scatter.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_reduce_scatter.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_reduce_scatter.c test_scan: common.h test_scan.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_scan.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_scan.c test_scatter: common.h test_scatter.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_scatter.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_scatter.c test_scatterv: common.h test_scatterv.c $(CC) $(CC_FLAGS) -DTEST_PAYLOAD_SIZE=$(TEST_PAYLOAD_SIZE) -o $@ -I. test_scatterv.c $(CC) $(CC_FLAGS) -DTEST_UNIFORM_COUNT=$(TEST_UNIFORM_COUNT) -o $@_uniform_count -I. test_scatterv.c <file_sep>/collective-big-count/test_alltoallv.c /* * Copyright (c) 2022 IBM Corporation. All rights reserved. * * $COPYRIGHT$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mpi.h> #include "common.h" int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking); int main(int argc, char** argv) { // Initialize the MPI environment int ret = 0; MPI_Init(NULL, NULL); init_environment(argc, argv); // Run the tests #ifndef TEST_UNIFORM_COUNT // Buffer size: 2 GB // V_SIZE_INT tells us how many elements are needed to reach 2GB payload // Each rank will send/recv a count of V_SIZE_INT / world_size // The function will try to get as close to that as possible. // // Each rank contribues: V_SIZE_INT / world_size elements // Largest buffer is : V_SIZE_INT elements ret += my_c_test_core(MPI_INT, V_SIZE_INT, true); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, true); if (allow_nonblocked) { ret += my_c_test_core(MPI_INT, V_SIZE_INT, false); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, false); } #else size_t proposed_count; // Each rank contribues: TEST_UNIFORM_COUNT elements // Largest buffer is : TEST_UNIFORM_COUNT x world_size proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, (size_t)world_size, (size_t)world_size); ret += my_c_test_core(MPI_INT, proposed_count * (size_t)world_size, true); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, (size_t)world_size, (size_t)world_size); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count * (size_t)world_size, true); if (allow_nonblocked) { proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, (size_t)world_size, (size_t)world_size); ret += my_c_test_core(MPI_INT, proposed_count * (size_t)world_size, false); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, (size_t)world_size, (size_t)world_size); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count * (size_t)world_size, false); } #endif /* * All done */ MPI_Finalize(); return ret; } int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking) { int ret = 0; size_t i; size_t j; // Actual payload size as divisible by the sizeof(dt) size_t payload_size_actual; size_t excess_size_actual; int *my_int_recv_vector = NULL; int *my_int_send_vector = NULL; double _Complex *my_dc_recv_vector = NULL; double _Complex *my_dc_send_vector = NULL; MPI_Request request; int exp; size_t num_wrong; int excess_count; size_t current_base; int receive_counts[world_size]; int receive_offsets[world_size]; int send_counts[world_size]; int send_offsets[world_size]; char *mpi_function = blocking ? "MPI_Alltoallv" : "MPI_Ialltoallv"; assert(MPI_INT == dtype || MPI_C_DOUBLE_COMPLEX == dtype); if (total_num_elements > INT_MAX) { total_num_elements = INT_MAX; } // Force unequal distribution of data across ranks if ((total_num_elements % world_size) == 0) { total_num_elements = total_num_elements - 1; } excess_count = total_num_elements % world_size; // The value of total_num_elements passed to this function should not exceed // INT_MAX. By adding an extra element to force unequal distribution, // total_num_elements may exceed INT_MAX so the value must be adjusted // downward. if ((total_num_elements + excess_count) > INT_MAX) { total_num_elements = total_num_elements - world_size; } // Data sent by all ranks to all ranks other than highest rank is // (total_num_elements / world_size) elements. All ranks send that // data plus the excess (total_num_elements % world_size) to the // highest rank. All ranks must receive exactly the number of elements // they were sent. current_base = 0; for (i = 0; i < world_size; i++) { send_counts[i] = total_num_elements / world_size; receive_counts[i] = total_num_elements / world_size; send_offsets[i] = current_base; receive_offsets[i] = current_base; current_base = current_base + send_counts[i]; } send_counts[world_size - 1] += excess_count; // Since the highest rank receives excess elements due to unequal distribution, // the receive counts and receive offsets need to be adjusted by that count. if (world_rank == (world_size - 1)) { current_base = 0; for (i = 0; i < world_size; i++) { receive_offsets[i] = current_base; receive_counts[i] = (total_num_elements / world_size) + excess_count; current_base = current_base + receive_counts[i]; } } // Allocate send and receive buffers. The send buffer for each rank is // allocated to hold the total_num_elements sent to all ranks. Since // total_num_elements is forced to a value not evenly divisible by the // world_size, and the excess elements are sent by each rank to the last // rank, the receive buffer for the last rank must be larger than the // send buffer by excess_count * world_size. For the other ranks, allocating // send and receive buffers identically is sufficient. if( MPI_INT == dtype ) { payload_size_actual = total_num_elements * sizeof(int); if (world_rank == (world_size - 1)) { excess_size_actual = world_size * excess_count * sizeof(int); my_int_recv_vector = (int*)safe_malloc(payload_size_actual + excess_size_actual); } else { my_int_recv_vector = (int*)safe_malloc(payload_size_actual); } my_int_send_vector = (int*)safe_malloc(payload_size_actual); } else { payload_size_actual = total_num_elements * sizeof(double _Complex); if (world_rank == (world_size - 1)) { excess_size_actual = world_size * excess_count * sizeof(double _Complex); my_dc_recv_vector = (double _Complex*)safe_malloc(payload_size_actual + excess_size_actual); } else { my_dc_recv_vector = (double _Complex*)safe_malloc(payload_size_actual); } my_dc_send_vector = (double _Complex*)safe_malloc(payload_size_actual); } // Initialize blocks of data to be sent to each rank to a unique range of values // using array index modulo prime and offset by prime * rank if (MPI_INT == dtype) { for (i = 0; i < world_size; ++i) { for (j = 0; j < send_counts[i]; j++) { exp = (j % PRIME_MODULUS) + (PRIME_MODULUS * world_rank); my_int_send_vector[j + send_offsets[i]] = exp; } } } else { for (i = 0; i < world_size; ++i) { for (j = 0; j < send_counts[i]; j++) { exp = (j % PRIME_MODULUS) + (PRIME_MODULUS * world_rank); my_dc_send_vector[j + send_offsets[i]] = (1.0 * exp - 1.0 * exp * I); } } } if (world_rank == 0) { printf("---------------------\nResults from %s(%s x %zu = %zu or %s): MPI_IN_PLACE\n", mpi_function, (MPI_INT == dtype ? "int" : "double _Complex"), total_num_elements, payload_size_actual, human_bytes(payload_size_actual)); } // Perform the MPI_Alltoallv operation if (blocking) { if( MPI_INT == dtype ) { MPI_Alltoallv(my_int_send_vector, send_counts, send_offsets, dtype, my_int_recv_vector, receive_counts, receive_offsets, dtype, MPI_COMM_WORLD); } else { MPI_Alltoallv(my_dc_send_vector, send_counts, send_offsets, dtype, my_dc_recv_vector, receive_counts, receive_offsets, dtype, MPI_COMM_WORLD); } } else { if( MPI_INT == dtype ) { MPI_Ialltoallv(my_int_send_vector, send_counts, send_offsets, dtype, my_int_recv_vector, receive_counts, receive_offsets, dtype, MPI_COMM_WORLD, &request); } else { MPI_Ialltoallv(my_dc_send_vector, send_counts, send_offsets, dtype, my_dc_recv_vector, receive_counts, receive_offsets, dtype, MPI_COMM_WORLD, &request); } MPI_Wait(&request, MPI_STATUS_IGNORE); } // Check results. Each receive buffer segment must match the // values in the send buffer segment it was sent. num_wrong = 0; current_base = 0; if (MPI_INT == dtype) { for (i = 0; i < world_size; i++) { for (j = 0; j < receive_counts[i]; j++) { exp = (j % PRIME_MODULUS) + (PRIME_MODULUS * i); if (my_int_recv_vector[current_base + j] != exp) { num_wrong = num_wrong + 1; } } current_base = current_base + receive_counts[i]; } } else { for (i = 0; i < world_size; i++) { for (j = 0; j < receive_counts[i]; j++) { exp = (j % PRIME_MODULUS) + (PRIME_MODULUS * i); if (my_dc_recv_vector[current_base + j] != (1.0 * exp - 1.0 * exp * I)) { num_wrong = num_wrong + 1; } } current_base = current_base + receive_counts[i]; } } if (0 == num_wrong) { printf("Rank %2d: PASSED\n", world_rank); } else { printf("Rank %2d: ERROR: DI in %14zu of %14zu slots (%6.1f %% wrong)\n", world_rank, num_wrong, total_num_elements, ((num_wrong * 1.0) / total_num_elements * 100.0)); ret = 1; } if (NULL != my_int_send_vector) { free(my_int_send_vector); } if (NULL != my_int_recv_vector){ free(my_int_recv_vector); } if (NULL != my_dc_send_vector) { free(my_dc_send_vector); } if (NULL != my_dc_recv_vector){ free(my_dc_recv_vector); } fflush(NULL); MPI_Barrier(MPI_COMM_WORLD); return ret; } <file_sep>/runtime/bin/pretty-print-hwloc/src/get-pretty-cpu.c #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <hwloc.h> #include "include/utils.h" static hwloc_topology_t topology; static int global_rank, global_size; static int local_rank, local_size; static char hostname[HOST_NAME_MAX] = { '\0' }; static void display_message(char * fmt, ...); bool is_verbose = false; bool is_quiet = false; bool report_smallest = false; bool report_full = false; bool report_full_map = false; bool report_hwloc_bind = true; int main(int argc, char **argv) { hwloc_topology_t topology; hwloc_bitmap_t bound_set; hwloc_obj_t obj; char type[64]; int i; char pretty_str[PRETTY_LEN]; char *buffer_str = NULL; char whoami_str[PRETTY_LEN]; /* * Simple arg parsing */ if( argc > 0 ) { for( i = 1; i < argc; ++i ) { if( 0 == strcmp(argv[i], "-v") || 0 == strcmp(argv[i], "--v") || 0 == strcmp(argv[i], "-verbose") || 0 == strcmp(argv[i], "--verbose") ) { is_verbose = true; } else if( 0 == strcmp(argv[i], "-q") || 0 == strcmp(argv[i], "--q") || 0 == strcmp(argv[i], "-quiet") || 0 == strcmp(argv[i], "--quiet") ) { is_quiet = true; } else if( 0 == strcmp(argv[i], "-s") || 0 == strcmp(argv[i], "--s") || 0 == strcmp(argv[i], "-smallest") || 0 == strcmp(argv[i], "--smallest") ) { report_smallest = true; } else if( 0 == strcmp(argv[i], "-f") || 0 == strcmp(argv[i], "--f") || 0 == strcmp(argv[i], "-full") || 0 == strcmp(argv[i], "--full") ) { report_full = true; } else if( 0 == strcmp(argv[i], "-m") || 0 == strcmp(argv[i], "--m") || 0 == strcmp(argv[i], "-map") || 0 == strcmp(argv[i], "--map") ) { report_full_map = true; } else if( 0 == strcmp(argv[i], "-b") || 0 == strcmp(argv[i], "--b") || 0 == strcmp(argv[i], "-no-bind") || 0 == strcmp(argv[i], "--no-bind") ) { report_hwloc_bind = false; } } } gethostname(hostname, HOST_NAME_MAX); /* Get rank/size information from the launching environment */ get_rank_size_info(&global_rank, &global_size, &local_rank, &local_size); sprintf(whoami_str, "%3d/%3d on %s) ", global_rank, global_size, hostname); /* Allocate and initialize topology object. */ hwloc_topology_init(&topology); /* Perform the topology detection. */ hwloc_topology_load(topology); /* retrieve the CPU binding of the current entire process */ bound_set = hwloc_bitmap_alloc(); hwloc_get_cpubind(topology, bound_set, HWLOC_CPUBIND_PROCESS); /* print the smallest object covering the current process binding */ if( report_smallest ) { obj = hwloc_get_obj_covering_cpuset(topology, bound_set); if( NULL == obj ) { display_message("Not bound\n"); } else { hwloc_obj_type_snprintf(type, sizeof(type), obj, 0); display_message("Bound to \"%s\" logical index %u (physical index %u)\n", type, obj->logical_index, obj->os_index); } } /* print the full descriptive output */ if( report_full ) { opal_hwloc_base_cset2str(pretty_str, PRETTY_LEN, topology, bound_set, true ); if( is_verbose ) { printf("%s Process Bound :\n%s\n", whoami_str, pretty_str); } else { printf("%s Process Bound : %s\n", whoami_str, pretty_str); } } /* print the full bracketed map output */ if( report_full_map ) { opal_hwloc_base_cset2mapstr(pretty_str, PRETTY_LEN, topology, bound_set); if( is_verbose ) { printf("%s Process Bound :\n%s\n", whoami_str, pretty_str); } else { printf("%s Process Bound : %s\n", whoami_str, pretty_str); } } /* print the hwloc binding bitmap */ if( report_hwloc_bind ) { hwloc_bitmap_asprintf(&buffer_str, bound_set); if( is_verbose ) { printf("%s Process Bound :\n%s\n", whoami_str, buffer_str); } else { printf("%s Process Bound : %s\n", whoami_str, buffer_str); } free(buffer_str); } /* Destroy topology object. */ hwloc_topology_destroy(topology); return 0; } static void display_message(char *fmt, ...) { va_list args; printf("%3d/%3d on %s (%3d/%3d): ", global_rank, global_size, hostname, local_rank, local_size); va_start(args, fmt); vprintf(fmt, args); if( '\n' != fmt[strlen(fmt)-1] ) { printf("\n"); } va_end(args); } <file_sep>/events/events_common.h /* * events_common.h * * Common functionality available for all events tests * */ #if !defined INCLUDE_EVENT_COMMON #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <assert.h> #include <mpi.h> #define MAX_STRING 4096 enum { TEST_CONTINUE = 0, TEST_EXIT = 1 }; typedef struct event_info_t { int event_index; char *name; int name_len; int verbosity; MPI_Datatype *array_of_datatypes; MPI_Aint *array_of_displacements; int num_elements; MPI_T_enum enumtype; MPI_Info info; char *desc; int desc_len; int bind; } EVENT_INFO; extern FILE* errout; extern int error_count; extern int print_events; extern int debug_level; extern int print_errors; extern int do_failure_tests; extern int event_index; extern char *cb_user_data; extern int rank; extern int wsize; extern FILE *outstream; extern int func_width; extern int metric_width; extern char *pass_str; extern char *fail_str; enum { NO_MPI_ERROR_CODE = -1 }; extern char* bind_str(int b); extern void print_error(char *errstr, int errcode, int exit_flag); extern void print_debug(const char * format, ... ); extern void generate_callback_activity(void); extern void generate_callback_activity_1proc(void); extern void test_init(char *test_name, int ac, char**av); extern void print_pf_result(char* function, char *testname, int flag); #define INCLUDE_EVENT_COMMON #endif <file_sep>/sessions/sessions_test13.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" void print_error(const char *msg, int rc) { char err_str[MPI_MAX_ERROR_STRING]; int resultlen = sizeof(err_str) - 1; MPI_Error_string(rc, err_str, &resultlen); fprintf (stderr, "%s return err code = %d (%s)\n", msg, rc, err_str); } void my_session_errhandler (MPI_Session *foo, int *bar, ...) { fprintf(stderr, "errhandler called with error %d\n", *bar); } int main (int argc, char *argv[]) { MPI_Session session; MPI_Errhandler errhandler; MPI_Group group; MPI_Comm comm_world; MPI_Info info; int rc, npsets, one = 1, sum, i; rc = MPI_Session_create_errhandler (my_session_errhandler, &errhandler); if (MPI_SUCCESS != rc) { print_error("Error handler creation failed", rc); return -1; } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { print_error("Info creation failed", rc); return -1; } rc = MPI_Info_set(info, "mpi_thread_support_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { print_error("Info key/val set failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session); if (MPI_SUCCESS != rc) { print_error("Session initialization failed", rc); return -1; } MPI_Init(&argc, &argv); rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Group_from_session_pset (session, "mpi://WORLD", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://WORLD. ", rc); return -1; } MPI_Comm_create_from_group (group, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world); MPI_Group_free (&group); MPI_Errhandler_free (&errhandler); MPI_Info_free (&info); MPI_Comm_free (&comm_world); MPI_Finalize(); MPI_Session_finalize (&session); return 0; } <file_sep>/sessions/sessions_test8.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" void print_error(const char *msg, int rc) { char err_str[MPI_MAX_ERROR_STRING]; int resultlen = sizeof(err_str) - 1; MPI_Error_string(rc, err_str, &resultlen); fprintf (stderr, "%s return err code = %d (%s)\n", msg, rc, err_str); } void my_session_errhandler (MPI_Session *foo, int *bar, ...) { fprintf(stderr, "errhandler called with error %d\n", *bar); } int main (int argc, char *argv[]) { MPI_Session session, session1; MPI_Errhandler errhandler; MPI_Group group, group1; MPI_Comm comm_world, comm_world1; MPI_Info info; int rc, npsets, npsets1, i; rc = MPI_Session_create_errhandler (my_session_errhandler, &errhandler); if (MPI_SUCCESS != rc) { print_error("Error handler creation failed", rc); return -1; } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { print_error("Info creation failed", rc); return -1; } rc = MPI_Info_set(info, "mpi_thread_support_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { print_error("Info key/val set failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session); if (MPI_SUCCESS != rc) { print_error("Session initialization failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session1); if (MPI_SUCCESS != rc) { print_error("Session1 initialization failed", rc); return -1; } rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Session_get_num_psets (session1, MPI_INFO_NULL, &npsets1); for (i = 0 ; i < npsets1 ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session1, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session1, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Group_from_session_pset (session, "mpi://WORLD", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://WORLD. ", rc); return -1; } rc = MPI_Group_from_session_pset (session1, "mpi://WORLD", &group1); if (MPI_SUCCESS != rc) { print_error("Could not get a group1 for mpi://WORLD. ", rc); return -1; } MPI_Comm_create_from_group (group, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world); MPI_Group_free (&group); MPI_Comm_create_from_group (group1, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world1); MPI_Group_free (&group1); int result; rc = MPI_Comm_compare(comm_world, comm_world1, &result); if (MPI_SUCCESS != rc) { fprintf(stderr, "Comparing comms from different sessions failed\n"); MPI_Comm_free (&comm_world); MPI_Comm_free (&comm_world1); MPI_Session_finalize (&session); MPI_Session_finalize (&session1); return 0; } else { fprintf(stderr, "Comparing comms from different sessions should have failed but didn't\n"); MPI_Comm_free (&comm_world); MPI_Comm_free (&comm_world1); MPI_Session_finalize (&session); MPI_Session_finalize (&session1); return -1; } } <file_sep>/collective-big-count/test_gather.c /* * Copyright (c) 2021-2022 IBM Corporation. All rights reserved. * * $COPYRIGHT$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mpi.h> #include "common.h" int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking); int main(int argc, char** argv) { /* * Initialize the MPI environment */ int ret = 0; MPI_Init(NULL, NULL); init_environment(argc, argv); #ifndef TEST_UNIFORM_COUNT // Each rank contribues: V_SIZE_INT / world_size elements // Largest buffer is : V_SIZE_INT elements ret += my_c_test_core(MPI_INT, V_SIZE_INT, true); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, true); if (allow_nonblocked) { ret += my_c_test_core(MPI_INT, V_SIZE_INT, false); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, false); } #else size_t proposed_count; // Each rank contribues: TEST_UNIFORM_COUNT elements // Largest buffer is : TEST_UNIFORM_COUNT x world_size proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, (size_t)world_size, 1); ret += my_c_test_core(MPI_INT, proposed_count * (size_t)world_size, true); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, (size_t)world_size, 1); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count * (size_t)world_size, true); if (allow_nonblocked) { proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, (size_t)world_size, 1); ret += my_c_test_core(MPI_INT, proposed_count * (size_t)world_size, false); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, (size_t)world_size, 1); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count * (size_t)world_size, false); } #endif /* * All done */ MPI_Finalize(); return ret; } int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking) { int ret = 0; size_t i; MPI_Request request; char *mpi_function = blocking ? "MPI_Gather" : "MPI_Igather"; // Actual payload size as divisible by the sizeof(dt) size_t payload_size_actual; /* * Initialize vector */ int *my_int_recv_vector = NULL; int *my_int_send_vector = NULL; double _Complex *my_dc_recv_vector = NULL; double _Complex *my_dc_send_vector = NULL; size_t recv_count = 0; size_t send_count = 0; int exp; size_t num_wrong = 0; assert(MPI_INT == dtype || MPI_C_DOUBLE_COMPLEX == dtype); send_count = total_num_elements / (size_t)world_size; recv_count = total_num_elements / (size_t)world_size; assert(send_count <= INT_MAX); assert(recv_count <= INT_MAX); // total_num_elements must be a multiple of world_size. Drop any remainder total_num_elements = send_count * (size_t)world_size; if( MPI_INT == dtype ) { if (world_rank == 0) { payload_size_actual = total_num_elements * sizeof(int); my_int_recv_vector = (int*)safe_malloc(payload_size_actual); } my_int_send_vector = (int*)safe_malloc(send_count * sizeof(int)); } else { if (world_rank == 0) { payload_size_actual = total_num_elements * sizeof(double _Complex); my_dc_recv_vector = (double _Complex*)safe_malloc(payload_size_actual); } my_dc_send_vector = (double _Complex*)safe_malloc(send_count * sizeof(double _Complex)); } for(i = 0; i < send_count; ++i) { exp = 1 + world_rank; if( MPI_INT == dtype ) { my_int_send_vector[i] = exp; } else { my_dc_send_vector[i] = 1.0*exp - 1.0*exp*I; } } if (world_rank == 0) { for(i = 0; i < total_num_elements; ++i) { if( MPI_INT == dtype ) { my_int_recv_vector[i] = -1; } else { my_dc_recv_vector[i] = 1.0 + 1.0*I; } } } if (world_rank == 0) { printf("---------------------\nResults from %s(%s x %zu = %zu or %s):\n", mpi_function, (MPI_INT == dtype ? "int" : "double _Complex"), total_num_elements, payload_size_actual, human_bytes(payload_size_actual)); } if (blocking) { if( MPI_INT == dtype ) { MPI_Gather(my_int_send_vector, (int)send_count, dtype, my_int_recv_vector, (int)recv_count, dtype, 0, MPI_COMM_WORLD); } else { MPI_Gather(my_dc_send_vector, (int)send_count, dtype, my_dc_recv_vector, (int)recv_count, dtype, 0, MPI_COMM_WORLD); } } else { if( MPI_INT == dtype ) { MPI_Igather(my_int_send_vector, (int)send_count, dtype, my_int_recv_vector, (int)recv_count, dtype, 0, MPI_COMM_WORLD, &request); } else { MPI_Igather(my_dc_send_vector, (int)send_count, dtype, my_dc_recv_vector, (int)recv_count, dtype, 0, MPI_COMM_WORLD, &request); } MPI_Wait(&request, MPI_STATUS_IGNORE); } /* * Check results. */ if (world_rank == 0) { exp = 0; for(i = 0; i < total_num_elements; ++i) { exp = (int)(1 + (i / (size_t)recv_count)); if( MPI_INT == dtype ) { if(my_int_recv_vector[i] != exp) { ++num_wrong; } } else { if(my_dc_recv_vector[i] != 1.0*exp - 1.0*exp*I) { ++num_wrong; } } } if( 0 == num_wrong) { printf("Rank %2d: PASSED\n", world_rank); } else { printf("Rank %2d: ERROR: DI in %14zu of %14zu slots (%6.1f %% wrong)\n", world_rank, num_wrong, total_num_elements, ((num_wrong * 1.0)/total_num_elements)*100.0); ret = 1; } } if( NULL != my_int_send_vector ) { free(my_int_send_vector); } if( NULL != my_int_recv_vector ){ free(my_int_recv_vector); } if( NULL != my_dc_send_vector ) { free(my_dc_send_vector); } if( NULL != my_dc_recv_vector ){ free(my_dc_recv_vector); } fflush(NULL); MPI_Barrier(MPI_COMM_WORLD); return ret; } <file_sep>/runtime/bin/pretty-print-hwloc/src/include/utils.h /* * */ #ifndef _UTILS_H #define _UTILS_H #include <limits.h> #include <stdbool.h> #ifndef HOST_NAME_MAX #define HOST_NAME_MAX 64 #endif #define PRETTY_LEN 1024 // Configure header #include "include/autogen/config.h" /* * Access the global/local rank/size from environment variables set by the launcher */ int get_rank_size_info(int *global_rank, int *global_size, int *local_rank, int *local_size); /* * Create a string representation of the binding * 0/2 on node18) Process Bound : socket 0[core 1[hwt 0-7]],socket 1[core 10[hwt 0-7]] */ int opal_hwloc_base_cset2str(char *str, int len, hwloc_topology_t topo, hwloc_cpuset_t cpuset, bool is_full); /* * Create a string representation of the binding using a bracketed notion * 0/2 on node18) Process Bound : [......../BBBBBBBB/......../......../......../......../......../......../......../........][BBBBBBBB/......../......../......../......../......../......../......../......../........] */ int opal_hwloc_base_cset2mapstr(char *str, int len, hwloc_topology_t topo, hwloc_cpuset_t cpuset); #endif /* _UTILS_H */ <file_sep>/status/Makefile.am # # Copyright (c) 2020 Cisco Systems, Inc. All rights reserved # # $COPYRIGHT$ # SUBDIRS = src <file_sep>/collective-big-count/test_allgatherv.c /* * Copyright (c) 2021-2022 IBM Corporation. All rights reserved. * * $COPYRIGHT$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mpi.h> #include "common.h" int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, int mode, bool in_place, bool blocking); int main(int argc, char** argv) { /* * Initialize the MPI environment */ int ret = 0; MPI_Init(NULL, NULL); init_environment(argc, argv); // Run the tests #ifndef TEST_UNIFORM_COUNT // Each rank contribues: V_SIZE_INT / world_size elements // Largest buffer is : V_SIZE_INT elements ret += my_c_test_core(MPI_INT, V_SIZE_INT, MODE_PACKED, true, true); // Adjust these to be V_SIZE_INT - displacement strides so it will pass ret += my_c_test_core(MPI_INT, (V_SIZE_INT - disp_stride*world_size), MODE_SKIP, true, true); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, MODE_PACKED, true, true); // Adjust these to be V_SIZE_INT - displacement strides so it will pass ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, (V_SIZE_DOUBLE_COMPLEX - disp_stride*world_size), MODE_SKIP, true, true); if (allow_nonblocked) { ret += my_c_test_core(MPI_INT, V_SIZE_INT, MODE_PACKED, true, false); // Adjust these to be V_SIZE_INT - displacement strides so it will pass ret += my_c_test_core(MPI_INT, (V_SIZE_INT - disp_stride*world_size), MODE_SKIP, true, false); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, MODE_PACKED, true, false); // Adjust these to be V_SIZE_INT - displacement strides so it will pass ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, (V_SIZE_DOUBLE_COMPLEX - disp_stride*world_size), MODE_SKIP, true, false); } #else size_t proposed_count; // Each rank contribues: TEST_UNIFORM_COUNT elements // Largest buffer is : TEST_UNIFORM_COUNT x world_size // Note: Displacement is an int, so the recv buffer cannot be too large as to overflow the int // As such divide by the world_size proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT / (size_t)world_size, (size_t)world_size, (size_t)world_size); ret += my_c_test_core(MPI_INT, proposed_count * (size_t)world_size, MODE_PACKED, true, true); // Adjust these to be V_SIZE_INT - displacement strides so it will pass ret += my_c_test_core(MPI_INT, (proposed_count - disp_stride*world_size) * (size_t)world_size, MODE_SKIP, true, true); // Note: Displacement is an int, so the recv buffer cannot be too large as to overflow the int // As such divide by the world_size proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT / (size_t)world_size, (size_t)world_size, (size_t)world_size); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count * (size_t)world_size, MODE_PACKED, true, true); // Adjust these to be V_SIZE_INT - displacement strides so it will pass ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, (proposed_count - disp_stride*world_size) * (size_t)world_size, MODE_SKIP, true, true); if (allow_nonblocked) { proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT / (size_t)world_size, (size_t)world_size, (size_t)world_size); ret += my_c_test_core(MPI_INT, proposed_count * (size_t)world_size, MODE_PACKED, true, false); // Adjust these to be V_SIZE_INT - displacement strides so it will pass ret += my_c_test_core(MPI_INT, (proposed_count - disp_stride*world_size) * (size_t)world_size, MODE_SKIP, true, false); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT / (size_t)world_size, (size_t)world_size, (size_t)world_size); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count * (size_t)world_size, MODE_PACKED, true, false); // Adjust these to be V_SIZE_INT - displacement strides so it will pass ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, (proposed_count - disp_stride*world_size) * (size_t)world_size, MODE_SKIP, true, false); } #endif /* * All done */ MPI_Finalize(); return ret; } int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, int mode, bool in_place, bool blocking) { int ret = 0; size_t i; // Actual payload size as divisible by the sizeof(dt) size_t payload_size_actual; /* * Initialize vector */ int *my_int_send_vector = NULL; int *my_int_recv_vector = NULL; int int_exp; double _Complex *my_dc_send_vector = NULL; double _Complex *my_dc_recv_vector = NULL; double _Complex dc_exp; int *my_recv_counts = NULL; int *my_recv_disp = NULL; int send_count = 0; int d_idx, r_idx; size_t last_disp, last_count; size_t num_wrong = 0; size_t v_size, v_rem; MPI_Request request; char *mpi_function = blocking ? "MPI_Allgatherv" : "MPI_Iallgatherv"; assert(MPI_INT == dtype || MPI_C_DOUBLE_COMPLEX == dtype); // total_num_elements = final recv count // send_count = final send count v_size = total_num_elements / world_size; v_rem = total_num_elements % world_size; assert(send_count <= INT_MAX); send_count = (int)v_size; if (0 != v_rem && world_rank == world_size-1) { send_count += v_rem; } if( MODE_PACKED == mode ) { /* Strategy for testing: * - Displacement should skip 0 elements producing a tightly packed buffer * - Count will be the same at all ranks * - buffer can be v_size elements in size * * NP = 4 and total_num_elements = 9 then the final buffer will be: * [1, 1, 2, 2, 3, 3, 4, 4, 4] */ if( MPI_INT == dtype ) { payload_size_actual = total_num_elements * sizeof(int); my_int_recv_vector = (int*)safe_malloc(payload_size_actual); for(i = 0; i < total_num_elements; ++i) { my_int_recv_vector[i] = -1; } } else { payload_size_actual = total_num_elements * sizeof(double _Complex); my_dc_recv_vector = (double _Complex*)safe_malloc(payload_size_actual); for(i = 0; i < total_num_elements; ++i) { my_dc_recv_vector[i] = 1.0 - 1.0*I; } } my_recv_counts = (int*)safe_malloc(sizeof(int) * world_size); my_recv_disp = (int*)safe_malloc(sizeof(int) * world_size); last_disp = 0; last_count = v_size; for(d_idx = 0; d_idx < world_size; ++d_idx) { if (0 != v_rem && d_idx == world_size-1) { last_count += v_rem; } assert(last_count <= INT_MAX); my_recv_counts[d_idx] = (int)last_count; assert(last_disp <= INT_MAX); my_recv_disp[d_idx] = (int)last_disp; if( debug > 0 ) { printf("d_idx %3d / last_disp %9d / last_count %9d | total_count %10zu / payload_size %10zu\n", d_idx, (int)last_disp, (int)last_count, total_num_elements, payload_size_actual); } // Shift displacement by the count for tightly packed buffer last_disp += last_count; } } else { /* Strategy for testing: * - Displacement should skip 2 elements before first element and between each peer making a small gap * - Count will be the same at all ranks +/- and divisible by v_size * - buffer can be v_size + gaps for displacements * * NP = 4 and total_num_elements = 9 (17 with stride) then the final buffer will be: * [-1, -1, 1, 1, -1, -1, 2, 2, -1, -1, 3, 3, -1, -1, 4, 4, 4] */ total_num_elements += disp_stride * (size_t)world_size; if( MPI_INT == dtype ) { payload_size_actual = total_num_elements * sizeof(int); my_int_recv_vector = (int*)safe_malloc(payload_size_actual); for(i = 0; i < total_num_elements; ++i) { my_int_recv_vector[i] = -1; } } else { payload_size_actual = total_num_elements * sizeof(double _Complex); my_dc_recv_vector = (double _Complex*)safe_malloc(payload_size_actual); for(i = 0; i < total_num_elements; ++i) { my_dc_recv_vector[i] = -1.0 - 1.0*I; } } my_recv_counts = (int*)safe_malloc(sizeof(int) * world_size); my_recv_disp = (int*)safe_malloc(sizeof(int) * world_size); last_disp = disp_stride; last_count = v_size; for(d_idx = 0; d_idx < world_size; ++d_idx) { if (0 != v_rem && d_idx == world_size-1) { last_count += v_rem; } assert(last_count <= INT_MAX); my_recv_counts[d_idx] = (int)last_count; assert(last_disp <= INT_MAX); my_recv_disp[d_idx] = (int)last_disp; if( debug > 0) { printf("d_idx %3d / last_disp %9d / last_count %9d | total_count %10zu / payload_size %10zu\n", d_idx, (int)last_disp, (int)last_count, total_num_elements, payload_size_actual); } // Shift displacement by the count for tightly packed buffer last_disp += last_count + disp_stride; } } if( in_place ) { if( MPI_INT == dtype ) { for(i = 0; i < send_count; ++i) { my_int_recv_vector[i+my_recv_disp[world_rank]] = 1 + world_rank; } } else { for(i = 0; i < send_count; ++i) { my_dc_recv_vector[i+my_recv_disp[world_rank]] = 1.0*(1+world_rank) + 1.0*(1+world_rank)*I; } } } else { if( MPI_INT == dtype ) { my_int_send_vector = (int*)safe_malloc(sizeof(int) * send_count); for(i = 0; i < send_count; ++i) { my_int_send_vector[i] = 1 + world_rank; } } else { my_dc_send_vector = (double _Complex*)safe_malloc(sizeof(double _Complex) * send_count); for(i = 0; i < send_count; ++i) { my_dc_send_vector[i] = 1.0*(1+world_rank) + 1.0*(1+world_rank)*I; } } } if (world_rank == 0) { printf("---------------------\nResults from %s(%s x %zu = %zu or %s): Mode: %s%s\n", mpi_function, (MPI_INT == dtype ? "int" : "double _Complex"), total_num_elements, payload_size_actual, human_bytes(payload_size_actual), ((MODE_PACKED == mode) ? "PACKED" : "SKIPPY"), ((in_place) ? " MPI_IN_PLACE" : "")); } if (blocking) { if( MPI_INT == dtype ) { MPI_Allgatherv(in_place ? MPI_IN_PLACE : my_int_send_vector, send_count, dtype, my_int_recv_vector, my_recv_counts, my_recv_disp, dtype, MPI_COMM_WORLD); } else { MPI_Allgatherv(in_place ? MPI_IN_PLACE : my_dc_send_vector, send_count, dtype, my_dc_recv_vector, my_recv_counts, my_recv_disp, dtype, MPI_COMM_WORLD); } } else { if( MPI_INT == dtype ) { MPI_Iallgatherv(in_place ? MPI_IN_PLACE : my_int_send_vector, send_count, dtype, my_int_recv_vector, my_recv_counts, my_recv_disp, dtype, MPI_COMM_WORLD, &request); } else { MPI_Iallgatherv(in_place ? MPI_IN_PLACE : my_dc_send_vector, send_count, dtype, my_dc_recv_vector, my_recv_counts, my_recv_disp, dtype, MPI_COMM_WORLD, &request); } MPI_Wait(&request, MPI_STATUS_IGNORE); } /* * Check results. */ int_exp = 0; d_idx = 0; r_idx = 0; if( world_size > 1 ) { last_disp = my_recv_counts[r_idx] + my_recv_disp[r_idx]; } else { last_disp = 0; } if( MODE_PACKED == mode ) { for(i = 0; i < total_num_elements; ++i) { if( world_size > r_idx+1 && i == last_disp ) { ++r_idx; last_disp = my_recv_counts[r_idx] + my_recv_disp[r_idx]; } int_exp = 1 + r_idx; if( MPI_INT == dtype ) { if( debug > 1) { printf("CHECK: %2zu : %3d vs %3d [%3d : %3d + %3d = %3d]\n", i, my_int_recv_vector[i], int_exp, r_idx, my_recv_counts[r_idx], my_recv_disp[r_idx], (int)last_disp); } if(my_int_recv_vector[i] != int_exp) { ++num_wrong; } } else { dc_exp = 1.0*int_exp + 1.0*int_exp*I; if( debug > 1) { printf("CHECK: %2zu : (%14.0f,%14.0fi) vs (%14.0f,%14.0fi) [%3d : %3d + %3d = %3d]\n", i, creal(my_dc_recv_vector[i]), cimag(my_dc_recv_vector[i]), creal(dc_exp), cimag(dc_exp), r_idx, my_recv_counts[r_idx], my_recv_disp[r_idx], (int)last_disp); } if(my_dc_recv_vector[i] != dc_exp) { ++num_wrong; } } } } else { for(i = 0; i < total_num_elements; ++i) { if( world_size > r_idx+1 && i == last_disp ) { ++r_idx; last_disp = my_recv_counts[r_idx] + my_recv_disp[r_idx]; } if( i < my_recv_disp[r_idx] ) { int_exp = -1; } else { int_exp = 1 + r_idx; } if( MPI_INT == dtype ) { if( debug > 1) { printf("CHECK: %2zu : %3d vs %3d [%3d : %3d + %3d = %3d]\n", i, my_int_recv_vector[i], int_exp, r_idx, my_recv_counts[r_idx], my_recv_disp[r_idx], (int)last_disp); } if(my_int_recv_vector[i] != int_exp) { ++num_wrong; } } else { dc_exp = 1.0*int_exp + 1.0*int_exp*I; if( debug > 1) { printf("CHECK: %2zu : (%14.0f,%14.0fi) vs (%14.0f,%14.0fi) [%3d : %3d + %3d = %3d]\n", i, creal(my_dc_recv_vector[i]), cimag(my_dc_recv_vector[i]), creal(dc_exp), cimag(dc_exp), r_idx, my_recv_counts[r_idx], my_recv_disp[r_idx], (int)last_disp); } if(my_dc_recv_vector[i] != dc_exp) { ++num_wrong; } } } } if( 0 == num_wrong) { printf("Rank %2d: PASSED\n", world_rank); } else { printf("Rank %2d: ERROR: DI in %14zu of %14zu slots (%6.1f %% wrong)\n", world_rank, num_wrong, total_num_elements, ((num_wrong * 1.0)/total_num_elements)*100.0); ret = 1; } if( NULL != my_int_send_vector ) { free(my_int_send_vector); } if( NULL != my_int_recv_vector ){ free(my_int_recv_vector); } if( NULL != my_dc_send_vector ) { free(my_dc_send_vector); } if( NULL != my_dc_recv_vector ){ free(my_dc_recv_vector); } fflush(NULL); MPI_Barrier(MPI_COMM_WORLD); return ret; } <file_sep>/sessions/sessions_test.c #include <stdlib.h> #include <stdio.h> #include <mpi.h> void my_session_errhandler (MPI_Session *foo, int *bar, ...) { fprintf (stderr, "my error handler called here with error %d\n", *bar); } int main (int argc, char *argv[]) { MPI_Session session; MPI_Errhandler test; MPI_Group group; MPI_Comm comm_world, comm_self; MPI_Info info; int rc, npsets, one = 1, sum, i; rc = MPI_Session_create_errhandler (my_session_errhandler, &test); if (MPI_SUCCESS != rc) { fprintf (stderr, "Error handler creation failed with rc = %d\n", rc); abort (); } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { fprintf (stderr, "Info creation failed with rc = %d\n", rc); abort (); } rc = MPI_Info_set(info, "thread_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { fprintf (stderr, "Info key/val set failed with rc = %d\n", rc); abort (); } rc = MPI_Session_init (info, test, &session); if (MPI_SUCCESS != rc) { fprintf (stderr, "Session initialization failed with rc = %d\n", rc); abort (); } rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); fprintf (stderr, " PSET %d: %s (len: %d)\n", i, name, psetlen); } rc = MPI_Group_from_session_pset (session, "mpi://WORLD", &group); if (MPI_SUCCESS != rc) { fprintf (stderr, "Could not get a group for mpi://WORLD. rc = %d\n", rc); abort (); } MPI_Comm_create_from_group (group, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world); MPI_Group_free (&group); MPI_Allreduce (&one, &sum, 1, MPI_INT, MPI_SUM, comm_world); fprintf (stderr, "World Comm Sum (1): %d\n", sum); rc = MPI_Group_from_session_pset (session, "mpi://SELF", &group); if (MPI_SUCCESS != rc) { fprintf (stderr, "Could not get a group for mpi://SELF. rc = %d\n", rc); abort (); } MPI_Comm_create_from_group (group, "myself", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_self); MPI_Group_free (&group); MPI_Allreduce (&one, &sum, 1, MPI_INT, MPI_SUM, comm_self); fprintf (stderr, "Self Comm Sum (1): %d\n", sum); MPI_Errhandler_free (&test); MPI_Info_free (&info); MPI_Comm_free (&comm_world); MPI_Comm_free (&comm_self); MPI_Session_finalize (&session); return 0; } <file_sep>/events/events_read_data.c /* * events_read_data.c * * Test events data access functions for success and behavior * */ #include "events_common.h" #define ELEMENT_BUFFER_SIZE 256 char user_data_string[MAX_STRING] = "Test String"; // Test flags int event_read_data_success = 0; int event_read_data_confirm = 0; int event_copy_data_success = 1; int event_copy_data_match = 1; int event_element_index_exceed_handled = 0; int event_element_index_negative_handled = 0; void print_results() { if ( 0 != rank ) return; print_pf_result("MPI_T_event_read", "Event Read Data Success", event_read_data_success); print_pf_result("MPI_T_event_read", "Event Read Data Confirm", event_read_data_confirm); print_pf_result("MPI_T_event_copy", "Event Copy Data Success", event_copy_data_success); print_pf_result("MPI_T_event_copy", "Event Copy Data Verified", event_copy_data_match); if ( do_failure_tests ) { print_pf_result("MPI_T_event_read", "Handled element index too large", event_element_index_exceed_handled); print_pf_result("MPI_T_event_read", "Handled negative element index", event_element_index_negative_handled); } fprintf(outstream, "%-*s - %-*s : %6d\n", func_width, "TOTAL ERROR COUNT", metric_width, "", error_count); } /* * typedef void (*MPI_T_event_cb_function) (MPI_T_event_instance event, MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data); */ void test_event_cb_function(MPI_T_event_instance event, MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data) { int i, retval, num_elements, event_idx = 0; void *element_buffer, *element_test_buffer; int element_buffer_length; MPI_Datatype *array_of_datatypes; MPI_Aint *array_of_displacements; char type_name[MPI_MAX_OBJECT_NAME]; int resultlen, type_size; static int seq_num = 1; print_debug("In cb_function : %s %s %d\n", __func__, __FILE__, __LINE__); if ( rank != 0 ) return; /* Get data element count */ retval = MPI_T_event_get_info ( event_idx, NULL, NULL, NULL, NULL, NULL, &num_elements, NULL, NULL, NULL, NULL, NULL ); if (MPI_SUCCESS != retval) { print_error("MPI_T_event_get_info failed", NO_MPI_ERROR_CODE, TEST_CONTINUE); } array_of_datatypes = (MPI_Datatype*)malloc(sizeof(MPI_Datatype)*num_elements); array_of_displacements = (MPI_Aint*)malloc(sizeof(MPI_Aint)*num_elements); retval = MPI_T_event_get_info ( event_idx, NULL, NULL, NULL, array_of_datatypes, array_of_displacements, &num_elements, NULL, NULL, NULL, NULL, NULL ); element_buffer = malloc(ELEMENT_BUFFER_SIZE); element_test_buffer = malloc(ELEMENT_BUFFER_SIZE); event_read_data_success = 1; event_read_data_confirm = 1; for ( i = 0; i < num_elements; i++ ) { print_debug("Testing callback event_read for element %d\n", i); retval = MPI_T_event_read(event, i, element_buffer); if (MPI_SUCCESS != retval) { print_error("MPI_T_event_read failed", retval, TEST_CONTINUE); event_read_data_success = 0; error_count++; } // Event index 0 uses match header names static char *mca_pml_ob1_match_hdr_names[] = { "context id", "source", "tag", "sequence number", NULL, }; if ( array_of_datatypes[i] != 0 ) { MPI_Type_get_name( array_of_datatypes[i], type_name, &resultlen); MPI_Type_size(array_of_datatypes[i], &type_size); if ( type_size == 2 ) { print_debug(" [%d] Datatype : %20s Displacement : %2lu Size : %d : name : %20s val %hd\n", i, type_name, (unsigned long)array_of_displacements[i], type_size, mca_pml_ob1_match_hdr_names[i], *(short*)element_buffer); } else if ( type_size == 4 ) { print_debug(" [%d] Datatype : %20s Displacement : %2lu Size : %d : name : %20s val %d\n", i, type_name, (unsigned long)array_of_displacements[i], type_size, mca_pml_ob1_match_hdr_names[i], *(int*)element_buffer); } print_debug("element_test_buffer copy is at %d of size %d\n", (array_of_displacements[i]-type_size), type_size); memcpy(element_test_buffer+(array_of_displacements[i]), element_buffer, type_size); // Check sequence number for increasing integers // Specific to OMPI event ID 0, counter index 3 with current MPI activity if ( 3 == i ) print_debug("i is %d, seq_num is %d, sequence counter is %d\n", i, seq_num, *(short*)element_buffer); if ( 3 == i && 1 == event_read_data_confirm && seq_num != *(short*)element_buffer ) { event_read_data_confirm = 0; error_count++; } } } seq_num++; // For MPI_T_EVENT_COPY, the argument array_of_displacements returns an array of byte displacements in the event buffer in ascending order starting with zero. retval = MPI_T_event_copy(event, element_buffer); if (MPI_SUCCESS != retval) { print_error("MPI_T_event_failed failed", retval, TEST_CONTINUE); if ( 1 == event_copy_data_success ) { event_copy_data_success = 0; error_count++; } } for ( i = 0; i < 12; i++ ) { print_debug(" %d : %x - %x \n", i, *(char*)(element_test_buffer+i), *(char*)(element_buffer+i)); } // Length of buffer is last offset + size of last element MPI_Type_size(array_of_datatypes[num_elements-1], &type_size); element_buffer_length = array_of_displacements[num_elements-1] + type_size; if ( 0 == memcmp(element_test_buffer, element_buffer, element_buffer_length) ) { print_debug("event_copy buffers match for length %d!\n", element_buffer_length); } else { print_error("event_copy buffers do not match!\n", NO_MPI_ERROR_CODE, TEST_CONTINUE); event_copy_data_match = 0; } if ( do_failure_tests ) { retval = MPI_T_event_read(event, num_elements+1, element_buffer); if (MPI_SUCCESS != retval) { event_element_index_exceed_handled = 1; } else { print_error("MPI_T_event_read invalid event element index num_elements+1 not handled", retval, TEST_CONTINUE); } retval = MPI_T_event_read(event, -1, element_buffer); if (MPI_SUCCESS != retval) { event_element_index_negative_handled = 1; } else { print_error("MPI_T_event_read invalid event element index -1 not handled", retval, TEST_CONTINUE); } } free(array_of_datatypes); free(array_of_displacements); free(element_buffer); free(element_test_buffer); } void test_free_event_cb_function(MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data) { print_debug("In cb_function : %s %s %d\n", __func__, __FILE__, __LINE__); } void test_handle_alloc_register_generate_free() { int retval; int event_index; MPI_T_event_registration event_registration; char *event_name = "ompi_pml_ob1_message_arrived"; print_debug("Event Name is %s\n", event_name); retval = MPI_T_event_get_index(event_name, &event_index); // TEST MPI_T_event_handle_alloc // print_debug("Testing expected success for index %d\n", event_index); //retval = MPI_T_event_handle_alloc(event_index, NULL, MPI_INFO_NULL, &event_registration) ; retval = MPI_T_event_handle_alloc(event_index, MPI_COMM_WORLD, MPI_INFO_NULL, &event_registration) ; if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_handle_alloc did not return MPI_SUCCESS", retval, TEST_EXIT); // TEST MPI_T_event_register_callback // cb_user_data = user_data_string; print_debug("Testing expected MPI_T_event_register_callback success for index %d\n", event_index); retval = MPI_T_event_register_callback(event_registration, MPI_T_CB_REQUIRE_ASYNC_SIGNAL_SAFE, MPI_INFO_NULL, cb_user_data, test_event_cb_function); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_register_callback did not return MPI_SUCCESS", retval, TEST_EXIT); generate_callback_activity(); // TEST MPI_T_event_handle_free // retval = MPI_T_event_handle_free(event_registration, cb_user_data, test_free_event_cb_function); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_handle_free did not return MPI_SUCCESS", retval, TEST_EXIT); } int main (int argc, char** argv) { test_init("MPI_T Events Read Event Data Tests", argc, argv); test_handle_alloc_register_generate_free(); print_results(); MPI_T_finalize(); MPI_Finalize(); return 0; } <file_sep>/events/events_common.c /* * events_common.c * * Common functionality available for all events tests * */ #include "events_common.h" #include <getopt.h> FILE* errout; int error_count = 0; int print_events = 0; int print_errors = 0; int debug_level = 0; int do_failure_tests = 0; int event_index = 0; char *cb_user_data; int rank, wsize; FILE *outstream; int func_width = 35; int metric_width = 35; char *pass_str = "PASS"; char *fail_str = "FAIL"; char* bind_str(int b) { switch(b) { case MPI_T_BIND_NO_OBJECT: return "No Binding"; break; case MPI_T_BIND_MPI_COMM: return "Communicator Binding"; break; case MPI_T_BIND_MPI_DATATYPE: return "Datatype Binding"; break; case MPI_T_BIND_MPI_ERRHANDLER: return "Errorhandler Binding"; break; case MPI_T_BIND_MPI_FILE: return "File Binding"; break; case MPI_T_BIND_MPI_GROUP: return "Group Binding"; break; case MPI_T_BIND_MPI_OP: return "Reduction Op Binding"; break; case MPI_T_BIND_MPI_REQUEST: return "Request Binding"; break; case MPI_T_BIND_MPI_WIN: return "Windows Binding"; break; case MPI_T_BIND_MPI_MESSAGE: return "Message Binding"; break; case MPI_T_BIND_MPI_INFO: return "Info Binding"; break; } return "Undefined binding"; } void generate_callback_activity() { #define GENERATE_BUFFER_SIZE 32 char buf[GENERATE_BUFFER_SIZE]; int i, lim = 4; MPI_Status stat; MPI_Request req; print_debug("In %s %s %d\n", __func__, __FILE__, __LINE__); if ( wsize < 2 ) { print_error("Need at least 2 MPI processes to generate activity", NO_MPI_ERROR_CODE, TEST_CONTINUE); return; } for ( i = 0; i < lim; i++ ) { if ( rank == 0 ) { strcpy(cb_user_data, "Irecv"); MPI_Irecv(buf, GENERATE_BUFFER_SIZE, MPI_CHAR, 1, 27, MPI_COMM_WORLD, &req); } else { strcpy(buf, "cat"); strcpy(cb_user_data, "Isend"); MPI_Isend(buf, GENERATE_BUFFER_SIZE, MPI_CHAR, 0, 27, MPI_COMM_WORLD, &req); } strcpy(cb_user_data, "Wait"); MPI_Wait(&req, &stat); strcpy(cb_user_data, "Barrier"); MPI_Barrier(MPI_COMM_WORLD); } } void print_error(char *errstr, int errcode, int exit_flag) { FILE* errout = stderr; char mpi_err_msg[MPI_MAX_ERROR_STRING]; int mpi_err_msg_len = MPI_MAX_ERROR_STRING - 1; if ( rank > 0 ) return; error_count++; if ( print_errors ) { if ( errcode != NO_MPI_ERROR_CODE ) { if ( errcode != -18 ) { MPI_Error_string(errcode, mpi_err_msg, &mpi_err_msg_len); } else { strcpy(mpi_err_msg, "Encountered error with code -18"); } fprintf(errout, "*** ERROR: %s - %s\n", errstr, mpi_err_msg); } else { fprintf(errout, "*** ERROR: %s\n", errstr); } } if ( 0 != exit_flag ) { fprintf(errout, "Exiting.\n"); exit(-1); } } void print_debug(const char * format, ... ) { va_list args; va_start (args, format); if ( rank > 0 ) return; if ( debug_level ) { fprintf (errout, "DEBUG: "); vfprintf (errout, format, args); } va_end (args); } void get_options(int ac, char **av) { int c; while (1) { static struct option long_options[] = { {"print-debug", no_argument, 0, 'd'}, {"print-errors", no_argument, 0, 'e'}, {"do-failure-tests", no_argument, 0, 'f'}, {"event-index", required_argument, 0, 'i'}, {"print-events", no_argument, 0, 'l'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (ac, av, "defi:l", long_options, &option_index); if (c == -1) break; switch (c) { case 'd': debug_level = 1; break; case 'e': print_errors = 1; break; case 'f': do_failure_tests = 1; break; case 'i': event_index = atoi(optarg); break; case 'l': print_events = 1; break; case '?': break; default: break; } } } void test_init(char *test_name, int ac, char**av) { int retval; errout = stderr; outstream = stdout; retval = MPI_Init(&ac, &av); if (MPI_SUCCESS != retval) { print_error("Failed to initialize MPI", retval, TEST_EXIT); } get_options(ac, av); MPI_Comm_size(MPI_COMM_WORLD, &wsize); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int required = MPI_THREAD_SINGLE; int provided = 0; retval = MPI_T_init_thread(required, &provided); if (MPI_SUCCESS != retval) { print_error("Failed to initialize MPI tool interface", retval, TEST_EXIT); } if ( 0 == rank ) { fprintf(outstream, "\n\n%s\n\n", test_name); } } void print_pf_result(char* function, char *testname, int flag) { fprintf(outstream, "%-*s - %-*s : %6s\n", func_width, function, metric_width, testname, flag ? pass_str : fail_str); } <file_sep>/collective-big-count/README.md # Big Count Collectives Tests This test suite is for testing with large **count** payload operations. Large payload is defined as: > total payload size (count x sizeof(datatype)) is greater than UINT_MAX (4294967295 =~ 4 GB) | Test Suite | Count | Datatype | | ---------- | ----- | -------- | | N/A | small | small | | BigCount | **LARGE** | small | | [BigMPI](https://github.com/jeffhammond/BigMPI) | small | **LARGE** | * Assumes: - Roughly the same amount of memory per node - Same number of processes per node ## Building ``` make clean make all ``` ## Running For each unit test two different binaries are generated: * `test_FOO` : Run with a total payload size as close to `INT_MAX` as possible relative to the target datatype. * `test_FOO_uniform_count` : Run with a uniform count regardless of the datatype. Default `count = 2147483647 (INT_MAX)` Currently, the unit tests use the `int` and `double _Complex` datatypes in the MPI collectives. ``` mpirun --np 8 --map-by ppr:2:node --host host01:2,host02:2,host03:2,host04:2 \ -mca coll basic,inter,libnbc,self ./test_allreduce mpirun --np 8 --map-by ppr:2:node --host host01:2,host02:2,host03:2,host04:2 \ -x BIGCOUNT_MEMORY_PERCENT=15 -x BIGCOUNT_MEMORY_DIFF=10 \ --mca coll basic,inter,libnbc,self ./test_allreduce mpirun --np 8 --map-by ppr:2:node --host host01:2,host02:2,host03:2,host04:2 \ -x BIGCOUNT_MEMORY_PERCENT=15 -x BIGCOUNT_MEMORY_DIFF=10 \ --mca coll basic,inter,libnbc,self ./test_allreduce_uniform_count ``` Expected output will look something like the following. Notice that depending on the `BIGCOUNT_MEMORY_PERCENT` environment variable you might see the collective `Adjust count to fit in memory` message as the test harness is trying to honor that parameter. ``` shell$ mpirun --np 4 --map-by ppr:1:node --host host01,host02,host03,host04 \ -x BIGCOUNT_MEMORY_PERCENT=6 -x BIGCOUNT_MEMORY_DIFF=10 \ --mca coll basic,inter,libnbc,self ./test_allreduce_uniform_count ----------------------:----------------------------------------- Total Memory Avail. : 567 GB Percent memory to use : 6 % Tolerate diff. : 10 GB Max memory to use : 34 GB ----------------------:----------------------------------------- INT_MAX : 2147483647 UINT_MAX : 4294967295 SIZE_MAX : 18446744073709551615 ----------------------:----------------------------------------- : Count x Datatype size = Total Bytes TEST_UNIFORM_COUNT : 2147483647 V_SIZE_DOUBLE_COMPLEX : 2147483647 x 16 = 32.0 GB V_SIZE_DOUBLE : 2147483647 x 8 = 16.0 GB V_SIZE_FLOAT_COMPLEX : 2147483647 x 8 = 16.0 GB V_SIZE_FLOAT : 2147483647 x 4 = 8.0 GB V_SIZE_INT : 2147483647 x 4 = 8.0 GB ----------------------:----------------------------------------- --------------------- Results from MPI_Allreduce(int x 2147483647 = 8589934588 or 8.0 GB): Rank 3: PASSED Rank 2: PASSED Rank 1: PASSED Rank 0: PASSED --------------------- Adjust count to fit in memory: 2147483647 x 50.0% = 1073741823 Root : payload 34359738336 32.0 GB = 16 dt x 1073741823 count x 2 peers x 1.0 inflation Peer : payload 34359738336 32.0 GB = 16 dt x 1073741823 count x 2 peers x 1.0 inflation Total : payload 34359738336 32.0 GB = 32.0 GB root + 32.0 GB x 0 local peers --------------------- Results from MPI_Allreduce(double _Complex x 1073741823 = 17179869168 or 16.0 GB): Rank 3: PASSED Rank 2: PASSED Rank 0: PASSED Rank 1: PASSED --------------------- Results from MPI_Iallreduce(int x 2147483647 = 8589934588 or 8.0 GB): Rank 2: PASSED Rank 0: PASSED Rank 3: PASSED Rank 1: PASSED --------------------- Adjust count to fit in memory: 2147483647 x 50.0% = 1073741823 Root : payload 34359738336 32.0 GB = 16 dt x 1073741823 count x 2 peers x 1.0 inflation Peer : payload 34359738336 32.0 GB = 16 dt x 1073741823 count x 2 peers x 1.0 inflation Total : payload 34359738336 32.0 GB = 32.0 GB root + 32.0 GB x 0 local peers --------------------- Results from MPI_Iallreduce(double _Complex x 1073741823 = 17179869168 or 16.0 GB): Rank 2: PASSED Rank 0: PASSED Rank 3: PASSED Rank 1: PASSED ``` ## Environment variables * `BIGCOUNT_MEMORY_DIFF` (Default: `0`): Maximum difference (as integer in GB) in total available memory between processes. * `BIGCOUNT_MEMORY_PERCENT` (Default: `80`): Maximum percent (as integer) of memory to consume. * `BIGCOUNT_ENABLE_NONBLOCKING` (Default: `1`): Enable/Disable the nonblocking collective tests. `y`/`Y`/`1` means Enable, otherwise disable. * `BIGCOUNT_ALG_INFLATION` (Default: `1.0`): Memory overhead multiplier for a given algorithm. Some algorithms use internal buffers relative to the size of the payload and/or communicator size. This envar allow you to account for that to help avoid Out-Of-Memory (OOM) scenarios. ## Missing Collectives (to do list) Collectives missing from this test suite: * Barrier (N/A) * Alltoallv <file_sep>/sessions/sessions_ex1.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" static MPI_Session lib_shandle = MPI_SESSION_NULL; static MPI_Comm lib_comm = MPI_COMM_NULL; int library_foo_init(void) { int rc, flag; int ret = 0; const char pset_name[] = "mpi://WORLD"; const char mt_key[] = "thread_level"; const char mt_value[] = "MPI_THREAD_MULTIPLE"; char out_value[100]; /* large enough */ MPI_Group wgroup = MPI_GROUP_NULL; MPI_Info sinfo = MPI_INFO_NULL; MPI_Info tinfo = MPI_INFO_NULL; MPI_Info_create(&sinfo); MPI_Info_set(sinfo, mt_key, mt_value); rc = MPI_Session_init(sinfo, MPI_ERRORS_RETURN, &lib_shandle); if (rc != MPI_SUCCESS) { ret = -1; goto fn_exit; } /* * check we got thread support level foo library needs */ rc = MPI_Session_get_info(lib_shandle, &tinfo); if (rc != MPI_SUCCESS) { ret = -1; goto fn_exit; } MPI_Info_get(tinfo, mt_key, sizeof(out_value), out_value, &flag); if (flag != 1) { printf("Could not find key %s\n", mt_key); ret = -1; goto fn_exit; } if (strcmp(out_value, mt_value)) { printf("Did not get thread multiple support, got %s\n", out_value); ret = -1; goto fn_exit; } /* * create a group from the WORLD process set */ rc = MPI_Group_from_session_pset(lib_shandle, pset_name, &wgroup); if (rc != MPI_SUCCESS) { ret = -1; goto fn_exit; } /* * get a communicator */ rc = MPI_Comm_create_from_group(wgroup, "mpi.forum.mpi-v4_0.example-ex10_8", MPI_INFO_NULL, MPI_ERRORS_RETURN, &lib_comm); if (rc != MPI_SUCCESS) { ret = -1; goto fn_exit; } /* * free group, library doesn't need it. */ fn_exit: MPI_Group_free(&wgroup); if (sinfo != MPI_INFO_NULL) { MPI_Info_free(&sinfo); } if (tinfo != MPI_INFO_NULL) { MPI_Info_free(&tinfo); } if (ret != 0) { MPI_Session_finalize(&lib_shandle); } return ret; } <file_sep>/runtime/README.md # Test suite for Open MPI runtime This test suite is meant to be able to be run stand-alone or under CI. All of the tests that are intended for CI must be listed in the `.ci-tests` file. If the Open MPI build needs additional `configure` options those can be added to the `.ci-configure` file. ## Running tests stand alone 1. Make sure that Open MPI and other required libraries are in your `PATH`/`LD_LIBRARY_PATH` 2. Drop into a directory: - Use the `build.sh` script to build any test articles - Use the `run.sh` script to run the test program ## CI Environment Variables The CI infrastructure defines the following environment variables to be used in the test programs. These are defined during the `run.sh` phase and not the `build.sh` phase. * `CI_HOSTFILE` : Absolute path to the hostfile for this run. * `CI_NUM_NODES` : Number of nodes in this cluster. * `CI_OMPI_SRC` : top level directory of the Open MPI repository checkout. * `CI_OMPI_TESTS_PUBLIC_DIR` : Top level directory of the [Open MPI Public Test](https://github.com/open-mpi/ompi-tests-public) repository checkout * `OMPI_ROOT` : Open MPI install directory. ### Adding a new test for CI 1. Create a directory with your test. - **Note**: Please make your test scripts such that they can be easily run with or without the CI environment variables. 2. Create a build script named `build.sh` - CI will call this exactly one time (with a timeout in case it hangs). - If the script returns `0` then it is considered successful. Otherwise it is considered failed. 3. Create a run script named `run.sh` - The script is responsible for running your test including any runtime setup/shutdown and test result inspection. - CI will call this exactly one time (with a timeout in case it hangs). - If the script returns `0` then it is considered successful. Otherwise it is considered failed. 4. Add your directory name to the `.ci-tests` file in this directory in the order that they should be executed. - Note that adding the directory is not sufficient to have CI run the test, it must be in the `.ci-tests` file. - Comments (starting with `#`) are allowed. <file_sep>/runtime/bin/pretty-print-hwloc/src/Makefile.am # # # headers = sources = nodist_headers = EXTRA_DIST = AM_CPPFLAGS = -I./include/ AM_LDFLAGS = -lm # Headers headers += include/utils.h # Source sources += \ get-pretty-cpu.c \ support.c bin_PROGRAMS = get-pretty-cpu get_pretty_cpu_SOURCES = $(sources) $(headers) #get_pretty_cpu_CFLAGS = $(CFLAGS_HWLOC) #get_pretty_cpu_LDADD = $(LIBS_HWLOC) <file_sep>/packaging/README.md # Test for exported symbol name pollution This runs from inside a rank and uses ldd on itself to figure out what libraries to examine (it looks for a libmpi.so in the ldd output, and then decides that any other libraries that come from the same directory as libmpi.so must also be part of OMPI and should be examined too), then nm on those MPI libraries to look for symbols without some accepted OMPI prefix. Example runs with good/bad output:: ``` % export OPAL_PREFIX=/some/path % export OLDPATH=$PATH % export PATH=$OPAL_PREFIX/bin:${PATH} % export LD_LIBRARY_PATH=$OPAL_PREFIX/lib % autoreconf -i % make ------------------------------------------------ *** Example of a passing run: % $OPAL_PREFIX/bin/mpirun -np 1 ./run_nmcheck > Checking for bad symbol names: > *** checking /some/path/lib/libpmix.so.0 > *** checking /some/path/lib/libopen-pal.so.0 > *** checking /some/path/lib/libmpi.so.0 > *** checking /some/path/lib/libmpi_mpifh.so > *** checking /some/path/lib/libmpi_usempif08.so > *** checking /some/path/lib/libmpi_usempi_ignore_tkr.so ------------------------------------------------ *** Example of a failing run: Then if I edit one of the opal C files to add a couple extraneous globally exported symbols int myfunction() { return 0; } int myglobal = 123; and rerun the test: % $OPAL_PREFIX/bin/mpirun -np 1 ./run_nmcheck > Checking for bad symbol names: > *** checking /u/markalle/space/Projects/OMPIDev.m/install/lib/libmpi.so.0 > *** checking /u/markalle/space/Projects/OMPIDev.m/install/lib/libpmix.so.0 > *** checking /u/markalle/space/Projects/OMPIDev.m/install/lib/libopen-pal.so.0 > [error] myfunction > [error] myglobal > *** checking /u/markalle/space/Projects/OMPIDev.m/install/lib/libmpi_mpifh.so > *** checking /u/markalle/space/Projects/OMPIDev.m/install/lib/libmpi_usempif08.so > *** checking /u/markalle/space/Projects/OMPIDev.m/install/lib/libmpi_usempi_ignore_tkr.so > -------------------------------------------------------------------------- > MPI_ABORT was invoked on rank 0 in communicator MPI_COMM_WORLD > Proc: [[27901,1],0] > Errorcode: 16 > > NOTE: invoking MPI_ABORT causes Open MPI to kill all MPI processes. > You may or may not see output from other processes, depending on > exactly when Open MPI kills them. > -------------------------------------------------------------------------- ``` <file_sep>/runtime/hello_world/build.sh #!/bin/bash -e # Wrapper compiler _MPICC=mpicc echo "==========================" echo "Wrapper compiler: $_MPICC" echo "==========================" ${_MPICC} --showme echo "==========================" echo "Building MPI Hello World" echo "==========================" cp ${CI_OMPI_SRC}/examples/hello_c.c . ${_MPICC} hello_c.c -o hello echo "==========================" echo "Success" echo "==========================" exit 0 <file_sep>/events/README.md # MPI_T Events Tests If the MPI implementation includes support for the MPI_T Events functions as defined in [MPI Standard 4.0](https://www.mpi-forum.org/docs/mpi-4.0/mpi40-report.pdf) and includes some implemented events, these tests will confirm basic functionality as well as some error checking. ## Events Callback Test Requirements In order to confirm the MPI_T Events callback functionality, a callback must be registered and triggered by performing relevant MPI activity. The events_types test will print the list of events available by providing the command line '-l' flag. The events_callbacks event index can be set for the events_callbacks test with the `-i [number]` flag. If the default MPI activity in the function generate\_callback\_activity() in events_common.c does not trigger the event callback, custom MPI activity will need to be added. ## Test Behavior The behavior of each test can be modified with the following command line arguments: - -d : print internal debugging messages [default: off] - -e : print error messages [default: off] - -f : perform failure tests [default: off] - -i [number] : event index for specific tests [default: 0] - -l : list available events (events_types only) [default: off] ## Test Descriptions - events_callbacks - Register and free a callback function for an event - Get and set event handle and callback info - events_dropped - Register a callback function for dropped events - events\_meta_data - Get event timestamp and source - events\_read_data - Read and copy event data - events_source - Get number of source, source info object, and source timestamp - events_types - Get number of events and event info object ## Event Callback and Read Data Example The events_example.c file has been provided as an example of registering an event callback and reading event data. ## Test Suite And MPI Implementations Tested with [Open MPI PR #8057](https://github.com/open-mpi/ompi/pull/8057) with pml ob1 module events.<file_sep>/collective-big-count/test_reduce_scatter.c /* * Copyright (c) 2021 IBM Corporation. All rights reserved. * * $COPYRIGHT$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mpi.h> #include "common.h" int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, int world_size, bool blocking); int main(int argc, char** argv) { /* * Initialize the MPI environment */ int ret = 0; MPI_Init(NULL, NULL); init_environment(argc, argv); // Run the tests #ifndef TEST_UNIFORM_COUNT // Each rank contribues: V_SIZE_INT elements // Largest buffer is : V_SIZE_INT elements ret += my_c_test_core(MPI_INT, V_SIZE_INT, world_size, true); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, world_size, true); if (allow_nonblocked) { ret += my_c_test_core(MPI_INT, V_SIZE_INT, world_size, false); ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, world_size, false); } #else size_t proposed_count; // Each rank contribues: TEST_UNIFORM_COUNT elements // Largest buffer is : TEST_UNIFORM_COUNT elements proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_INT, proposed_count, world_size, true); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, world_size, true); if (allow_nonblocked) { proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_INT, proposed_count, world_size, false); proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT, 2, 2); // 1 send, 1 recv buffer each ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, world_size, false); } #endif /* * All done */ MPI_Finalize(); return ret; } int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, int world_size, bool blocking) { int ret = 0; size_t i; int count_for_task[world_size]; size_t in_lbound; MPI_Request request; char *mpi_function = blocking ? "MPI_Reduce_scatter" : "MPI_Ireduce_scatter"; // Actual payload size as divisible by the sizeof(dt) size_t payload_size_actual; size_t recv_size_actual; // Assign same number of results to each task, last task gets excess for (i = 0; i < world_size; i++) { count_for_task[i] = total_num_elements / world_size; } count_for_task[world_size - 1] += total_num_elements % world_size; /* * Initialize vector */ int *my_int_recv_vector = NULL; int *my_int_send_vector = NULL; double _Complex *my_dc_recv_vector = NULL; double _Complex *my_dc_send_vector = NULL; size_t num_wrong = 0; assert(MPI_INT == dtype || MPI_C_DOUBLE_COMPLEX == dtype); assert(total_num_elements <= INT_MAX); if( MPI_INT == dtype ) { payload_size_actual = total_num_elements * sizeof(int); recv_size_actual = count_for_task[world_rank] * sizeof(int); my_int_recv_vector = (int*)safe_malloc(recv_size_actual); my_int_send_vector = (int*)safe_malloc(payload_size_actual); } else { payload_size_actual = total_num_elements * sizeof(double _Complex); recv_size_actual = count_for_task[world_rank] * sizeof(double _Complex); my_dc_recv_vector = (double _Complex*)safe_malloc(recv_size_actual); my_dc_send_vector = (double _Complex*)safe_malloc(payload_size_actual); } /* * Assign each input array element the value of its array index modulo some * prime as an attempt to assign unique values to each array elements and catch * errors where array elements get updated with wrong values. Use a prime * number in order to avoid problems related to powers of 2. */ for(i = 0; i < total_num_elements; ++i) { if( MPI_INT == dtype ) { my_int_send_vector[i] = i % PRIME_MODULUS; } else { my_dc_send_vector[i] = i * PRIME_MODULUS - i * PRIME_MODULUS*I; } } for(i = 0; i < count_for_task[world_rank]; ++i) { if( MPI_INT == dtype ) { my_int_recv_vector[i] = -1; } else { my_dc_recv_vector[i] = -1.0 + 1.0*I; } } if (world_rank == 0) { printf("---------------------\nResults from %s(%s x %zu = %zu or %s):\n", mpi_function, (MPI_INT == dtype ? "int" : "double _Complex"), total_num_elements, payload_size_actual, human_bytes(payload_size_actual)); } if (blocking) { if( MPI_INT == dtype ) { MPI_Reduce_scatter(my_int_send_vector, my_int_recv_vector, count_for_task, dtype, MPI_SUM, MPI_COMM_WORLD); } else { MPI_Reduce_scatter(my_dc_send_vector, my_dc_recv_vector, count_for_task, dtype, MPI_SUM, MPI_COMM_WORLD); } } else { if( MPI_INT == dtype ) { MPI_Ireduce_scatter(my_int_send_vector, my_int_recv_vector, count_for_task, dtype, MPI_SUM, MPI_COMM_WORLD, &request); } else { MPI_Ireduce_scatter(my_dc_send_vector, my_dc_recv_vector, count_for_task, dtype, MPI_SUM, MPI_COMM_WORLD, &request); } MPI_Wait(&request, MPI_STATUS_IGNORE); } /* * Check results. * The reduce-scatter operation performs a reduction (sum) for all elements * of the input array then scatters the reduction result such that each task * gets the number of elements specified by count_for_task[world_rank]. * The input array element for each task is set to the value of its array index * modulo a prime number, so the output value for each array element must be * the corresponding input array element value * number of tasks in the application. */ in_lbound = (total_num_elements / world_size) * world_rank; for (i = 0; i < count_for_task[world_rank]; ++i) { if (MPI_INT == dtype) { if (my_int_recv_vector[i] != my_int_send_vector[in_lbound + i] * world_size) { ++num_wrong; } } else { if (my_dc_recv_vector[i] != my_dc_send_vector[in_lbound + i] * world_size) { ++num_wrong; } } } if( 0 == num_wrong) { printf("Rank %2d: PASSED\n", world_rank); } else { printf("Rank %2d: ERROR: DI in %14zu of %14u slots (%6.1f %% wrong)\n", world_rank, num_wrong, count_for_task[world_rank], ((num_wrong * 1.0) / count_for_task[world_rank])*100.0); ret = 1; } if( NULL != my_int_send_vector ) { free(my_int_send_vector); } if( NULL != my_int_recv_vector ){ free(my_int_recv_vector); } if( NULL != my_dc_send_vector ) { free(my_dc_send_vector); } if( NULL != my_dc_recv_vector ){ free(my_dc_recv_vector); } fflush(NULL); MPI_Barrier(MPI_COMM_WORLD); return ret; } <file_sep>/sessions/sessions_test15.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" void print_error(const char *msg, int rc) { char err_str[MPI_MAX_ERROR_STRING]; int resultlen = sizeof(err_str) - 1; MPI_Error_string(rc, err_str, &resultlen); fprintf (stderr, "%s return err code = %d (%s)\n", msg, rc, err_str); } void my_session_errhandler (MPI_Session *foo, int *bar, ...) { fprintf(stderr, "errhandler called with error %d\n", *bar); } int main (int argc, char *argv[]) { MPI_Session session, session1; MPI_Errhandler errhandler; MPI_Group group, group1; MPI_Comm comm_world, comm_world1; MPI_Info info; int rc, npsets, npsets1, one = 1, i, nprocs; int rank, buffer; rc = MPI_Session_create_errhandler (my_session_errhandler, &errhandler); if (MPI_SUCCESS != rc) { print_error("Error handler creation failed", rc); return -1; } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { print_error("Info creation failed", rc); return -1; } rc = MPI_Info_set(info, "mpi_thread_support_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { print_error("Info key/val set failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session); if (MPI_SUCCESS != rc) { print_error("Session initialization failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session1); if (MPI_SUCCESS != rc) { print_error("Session1 initialization failed", rc); return -1; } rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Session_get_num_psets (session1, MPI_INFO_NULL, &npsets1); for (i = 0 ; i < npsets1 ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session1, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session1, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Group_from_session_pset (session, "mpi://WORLD", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://WORLD. ", rc); return -1; } rc = MPI_Group_from_session_pset (session1, "mpi://WORLD", &group1); if (MPI_SUCCESS != rc) { print_error("Could not get a group1 for mpi://WORLD. ", rc); return -1; } MPI_Comm_create_from_group (group, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world); MPI_Group_free (&group); MPI_Comm_size(comm_world, &nprocs); MPI_Comm_rank(comm_world, &rank); if (nprocs < 4) { if (rank ==0) { fprintf(stderr, "Test requires at least 4 processes\n"); } MPI_Abort(comm_world, -1); } MPI_Comm_create_from_group (group1, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world1); MPI_Group_free (&group1); MPI_Comm_rank(comm_world, &rank); /* Check MPI_Waitall */ if (rank == 0) { buffer = 1; MPI_Request requests[3]; MPI_Isend(&buffer, 1, MPI_INT, 1, 0, comm_world, &requests[0]); MPI_Isend(&buffer, 1, MPI_INT, 2, 0, comm_world1, &requests[1]); MPI_Isend(&buffer, 1, MPI_INT, 3, 0, comm_world, &requests[2]); rc = MPI_Waitall(3, requests, MPI_STATUSES_IGNORE); if (rc == MPI_SUCCESS) { fprintf(stderr, "Using MPI_Waitall with requests from different sessions should have thrown an error\n"); return -1; } } else if (rank == 2) { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world1, MPI_STATUS_IGNORE); } else { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world, MPI_STATUS_IGNORE); } /* Check MPI_Waitany */ if (rank == 0) { buffer = 1; MPI_Request requests[3]; int request_ranks[3]; MPI_Isend(&buffer, 1, MPI_INT, 1, 0, comm_world, &requests[0]); request_ranks[0] = 1; MPI_Isend(&buffer, 1, MPI_INT, 2, 0, comm_world1, &requests[1]); request_ranks[0] = 2; MPI_Isend(&buffer, 1, MPI_INT, 3, 0, comm_world, &requests[2]); request_ranks[0] = 3; int index; rc = MPI_Waitany(3, requests, &index, MPI_STATUSES_IGNORE); if (rc == MPI_SUCCESS) { fprintf(stderr, "Using MPI_Waitany with requests from different sessions should have thrown an error\n"); return -1; } } else if (rank == 2) { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world1, MPI_STATUS_IGNORE); } else { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world, MPI_STATUS_IGNORE); } /* Check MPI_Waitsome */ if (rank == 0) { buffer = 1; MPI_Request requests[3]; int request_ranks[3]; MPI_Isend(&buffer, 1, MPI_INT, 1, 0, comm_world, &requests[0]); request_ranks[0] = 1; MPI_Isend(&buffer, 1, MPI_INT, 2, 0, comm_world1, &requests[1]); request_ranks[0] = 2; MPI_Isend(&buffer, 1, MPI_INT, 3, 0, comm_world, &requests[2]); request_ranks[0] = 3; int index_count; int indices[3]; rc = MPI_Waitsome(3, requests, &index_count, indices, MPI_STATUSES_IGNORE); if (rc == MPI_SUCCESS) { fprintf(stderr, "Using MPI_Waitsome with requests from different sessions should have thrown an error\n"); return -1; } } else if (rank == 2) { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world1, MPI_STATUS_IGNORE); } else { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world, MPI_STATUS_IGNORE); } /* Check MPI_Testall */ if (rank == 0) { buffer = 1; MPI_Request requests[3]; MPI_Isend(&buffer, 1, MPI_INT, 1, 0, comm_world, &requests[0]); MPI_Isend(&buffer, 1, MPI_INT, 2, 0, comm_world1, &requests[1]); MPI_Isend(&buffer, 1, MPI_INT, 3, 0, comm_world, &requests[2]); int flag; rc = MPI_Testall(3, requests, &flag, MPI_STATUSES_IGNORE); if (rc == MPI_SUCCESS) { fprintf(stderr, "Using MPI_Testall with requests from different sessions should have thrown an error\n"); return -1; } } else if (rank == 2) { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world1, MPI_STATUS_IGNORE); } else { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world, MPI_STATUS_IGNORE); } /* Check MPI_Testany */ if (rank == 0) { buffer = 1; MPI_Request requests[3]; int request_ranks[3]; MPI_Isend(&buffer, 1, MPI_INT, 1, 0, comm_world, &requests[0]); request_ranks[0] = 1; MPI_Isend(&buffer, 1, MPI_INT, 2, 0, comm_world1, &requests[1]); request_ranks[0] = 2; MPI_Isend(&buffer, 1, MPI_INT, 3, 0, comm_world, &requests[2]); request_ranks[0] = 3; int index, flag; rc = MPI_Testany(3, requests, &index, &flag, MPI_STATUSES_IGNORE); if (rc == MPI_SUCCESS) { fprintf(stderr, "Using MPI_Testany with requests from different sessions should have thrown an error\n"); return -1; } } else if (rank == 2) { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world1, MPI_STATUS_IGNORE); } else { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world, MPI_STATUS_IGNORE); } /* Check MPI_Testsome */ if (rank == 0) { buffer = 1; MPI_Request requests[3]; int request_ranks[3]; MPI_Isend(&buffer, 1, MPI_INT, 1, 0, comm_world, &requests[0]); request_ranks[0] = 1; MPI_Isend(&buffer, 1, MPI_INT, 2, 0, comm_world1, &requests[1]); request_ranks[0] = 2; MPI_Isend(&buffer, 1, MPI_INT, 3, 0, comm_world, &requests[2]); request_ranks[0] = 3; int index_count; int indices[3]; rc = MPI_Testsome(3, requests, &index_count, indices, MPI_STATUSES_IGNORE); if (rc == MPI_SUCCESS) { fprintf(stderr, "Using MPI_Testsome with requests from different sessions should have thrown an error\n"); return -1; } } else if (rank == 2) { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world1, MPI_STATUS_IGNORE); } else { buffer = 0; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, comm_world, MPI_STATUS_IGNORE); } MPI_Errhandler_free (&errhandler); MPI_Info_free (&info); MPI_Comm_free (&comm_world); MPI_Comm_free (&comm_world1); MPI_Session_finalize (&session); MPI_Session_finalize (&session1); return 0; } <file_sep>/events/events_meta_data.c /* * events_meta_data.c * * Test events metadata functions for timestamp and source * */ #include "events_common.h" char user_data_string[MAX_STRING] = "Test String"; // Test flags int event_read_time_success = 0; int event_increasing_time_success = 0; int event_get_source_success = 0; void print_results() { if ( 0 == rank ) { print_pf_result("MPI_T_event_get_timestamp", "Successful return", event_read_time_success); print_pf_result("MPI_T_event_get_timestamp", "Increasing timestamps", event_increasing_time_success); print_pf_result("MPI_T_event_get_source", "Successful return", event_get_source_success); fprintf(outstream, "%-*s - %-*s : %6d\n", func_width, "TOTAL ERROR COUNT", metric_width, "", error_count); } } /* * typedef void (*MPI_T_event_cb_function) (MPI_T_event_instance event, MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data); */ void test_event_cb_function(MPI_T_event_instance event, MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data) { int retval; MPI_Count event_timestamp, previous_timestamp = 0; int source_index; print_debug("In cb_function : %s %s %d\n", __func__, __FILE__, __LINE__); retval = MPI_T_event_get_timestamp(event, &event_timestamp); if ( retval != MPI_SUCCESS ) { print_error("MPI_T_event_get_timestamp did not return MPI_SUCCESS", retval, TEST_CONTINUE); event_read_time_success = 0; } else { print_debug("MPI_T_event_get_timestamp provided MPI_Count %lu\n", event_timestamp); event_read_time_success = 1; previous_timestamp = event_timestamp; } if ( previous_timestamp > 0 && previous_timestamp <= event_timestamp ) event_increasing_time_success = 1; retval = MPI_T_event_get_source(event, &source_index); if ( retval != MPI_SUCCESS ) { print_error("MPI_T_event_get_source did not return MPI_SUCCESS", retval, TEST_CONTINUE); event_get_source_success = 0; } else { print_debug("MPI_T_event_get_source provided source_index %d\n", source_index); event_get_source_success = 1; } } void test_free_event_cb_function(MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data) { print_debug("In cb_function : %s %s %d\n", __func__, __FILE__, __LINE__); } void test_meta_data() { int retval; int event_index; MPI_T_event_registration event_registration; char *event_name = "ompi_pml_ob1_request_complete"; retval = MPI_T_event_get_index(event_name, &event_index); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_get_index did not return MPI_SUCCESS", retval, TEST_EXIT); retval = MPI_T_event_handle_alloc(event_index, MPI_COMM_WORLD, MPI_INFO_NULL, &event_registration) ; if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_handle_alloc did not return MPI_SUCCESS", retval, TEST_EXIT); cb_user_data = user_data_string; print_debug("Testing expected MPI_T_event_register_callback success for index %d\n", event_index); retval = MPI_T_event_register_callback(event_registration, MPI_T_CB_REQUIRE_ASYNC_SIGNAL_SAFE, MPI_INFO_NULL, cb_user_data, test_event_cb_function); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_register_callback did not return MPI_SUCCESS", retval, TEST_EXIT); if ( do_failure_tests ) { } generate_callback_activity(); } int main (int argc, char** argv) { test_init("MPI_T Events Event Meta Data Tests", argc, argv); test_meta_data(); print_results(); MPI_T_finalize(); MPI_Finalize(); return 0; } <file_sep>/runtime/bin/pretty-print-hwloc/src/support.c /* * */ #include <stdio.h> #include <stdlib.h> #include <hwloc.h> #include "include/utils.h" static int build_map(int *num_sockets_arg, int *num_cores_arg, hwloc_cpuset_t cpuset, int ***map, hwloc_topology_t topo); static char *bitmap2rangestr(int bitmap); int get_rank_size_info(int *global_rank, int *global_size, int *local_rank, int *local_size) { char *envar = NULL; *global_rank = 0; *global_size = 0; *local_rank = 0; *local_size = 0; // JSM if( NULL != getenv("JSM_NAMESPACE_SIZE") ) { envar = getenv("JSM_NAMESPACE_RANK"); *global_rank = atoi(envar); envar = getenv("JSM_NAMESPACE_SIZE"); *global_size = atoi(envar); envar = getenv("JSM_NAMESPACE_LOCAL_RANK"); *local_rank = atoi(envar); envar = getenv("JSM_NAMESPACE_LOCAL_SIZE"); *local_size = atoi(envar); } // ORTE/PRRTE else if( NULL != getenv("OMPI_COMM_WORLD_SIZE") ) { envar = getenv("OMPI_COMM_WORLD_RANK"); *global_rank = atoi(envar); envar = getenv("OMPI_COMM_WORLD_SIZE"); *global_size = atoi(envar); envar = getenv("OMPI_COMM_WORLD_LOCAL_RANK"); *local_rank = atoi(envar); envar = getenv("OMPI_COMM_WORLD_LOCAL_SIZE"); *local_size = atoi(envar); } // MVAPICH2 else if( NULL != getenv("MV2_COMM_WORLD_SIZE") ) { envar = getenv("MV2_COMM_WORLD_RANK"); *global_rank = atoi(envar); envar = getenv("MV2_COMM_WORLD_SIZE"); *global_size = atoi(envar); envar = getenv("MV2_COMM_WORLD_LOCAL_RANK"); *local_rank = atoi(envar); envar = getenv("MV2_COMM_WORLD_LOCAL_SIZE"); *local_size = atoi(envar); } return 0; } int opal_hwloc_base_cset2str(char *str, int len, hwloc_topology_t topo, hwloc_cpuset_t cpuset, bool is_full) { bool first; int num_sockets, num_cores; int ret, socket_index, core_index; char tmp[BUFSIZ]; const int stmp = sizeof(tmp) - 1; int **map=NULL; //hwloc_obj_t root; //opal_hwloc_topo_data_t *sum; str[0] = tmp[stmp] = '\0'; /* if the cpuset is all zero, then not bound */ if (hwloc_bitmap_iszero(cpuset)) { return -1; } if (0 != (ret = build_map(&num_sockets, &num_cores, cpuset, &map, topo))) { return ret; } /* Iterate over the data matrix and build up the string */ first = true; for (socket_index = 0; socket_index < num_sockets; ++socket_index) { for (core_index = 0; core_index < num_cores; ++core_index) { if (map[socket_index][core_index] > 0) { if (!first) { if( is_full ) { //strncat(str, ",\n", len - strlen(str)); strncat(str, ",", len - strlen(str)); } else { strncat(str, ",", len - strlen(str)); } } first = false; if( is_full ) { snprintf(tmp, stmp, "socket %d[core %2d[hwt %s]]", socket_index, core_index, bitmap2rangestr(map[socket_index][core_index])); } else { snprintf(tmp, stmp, "%2d", core_index); } strncat(str, tmp, len - strlen(str)); } } } if (NULL != map) { if (NULL != map[0]) { free(map[0]); } free(map); } return 0; } int opal_hwloc_base_cset2mapstr(char *str, int len, hwloc_topology_t topo, hwloc_cpuset_t cpuset) { char tmp[BUFSIZ]; int core_index, pu_index; const int stmp = sizeof(tmp) - 1; hwloc_obj_t socket, core, pu; //hwloc_obj_t root; //opal_hwloc_topo_data_t *sum; str[0] = tmp[stmp] = '\0'; /* if the cpuset is all zero, then not bound */ if (hwloc_bitmap_iszero(cpuset)) { return -1; //OPAL_ERR_NOT_BOUND; } /* Iterate over all existing sockets */ for (socket = hwloc_get_obj_by_type(topo, HWLOC_OBJ_SOCKET, 0); NULL != socket; socket = socket->next_cousin) { strncat(str, "[", len - strlen(str)); /* Iterate over all existing cores in this socket */ core_index = 0; for (core = hwloc_get_obj_inside_cpuset_by_type(topo, socket->cpuset, HWLOC_OBJ_CORE, core_index); NULL != core; core = hwloc_get_obj_inside_cpuset_by_type(topo, socket->cpuset, HWLOC_OBJ_CORE, ++core_index)) { if (core_index > 0) { strncat(str, "/", len - strlen(str)); } /* Iterate over all existing PUs in this core */ pu_index = 0; for (pu = hwloc_get_obj_inside_cpuset_by_type(topo, core->cpuset, HWLOC_OBJ_PU, pu_index); NULL != pu; pu = hwloc_get_obj_inside_cpuset_by_type(topo, core->cpuset, HWLOC_OBJ_PU, ++pu_index)) { /* Is this PU in the cpuset? */ if (hwloc_bitmap_isset(cpuset, pu->os_index)) { strncat(str, "B", len - strlen(str)); } else { strncat(str, ".", len - strlen(str)); } } } strncat(str, "]", len - strlen(str)); } return 0; } /* * Make a map of socket/core/hwthread tuples */ static int build_map(int *num_sockets_arg, int *num_cores_arg, hwloc_cpuset_t cpuset, int ***map, hwloc_topology_t topo) { int num_sockets, num_cores; int socket_index, core_index, pu_index; hwloc_obj_t socket, core, pu; int **data; /* Find out how many sockets we have */ num_sockets = hwloc_get_nbobjs_by_type(topo, HWLOC_OBJ_SOCKET); /* some systems (like the iMac) only have one * socket and so don't report a socket */ if (0 == num_sockets) { num_sockets = 1; } /* Lazy: take the total number of cores that we have in the topology; that'll be more than the max number of cores under any given socket */ num_cores = hwloc_get_nbobjs_by_type(topo, HWLOC_OBJ_CORE); *num_sockets_arg = num_sockets; *num_cores_arg = num_cores; /* Alloc a 2D array: sockets x cores. */ data = malloc(num_sockets * sizeof(int *)); if (NULL == data) { return -1; //OPAL_ERR_OUT_OF_RESOURCE; } data[0] = calloc(num_sockets * num_cores, sizeof(int)); if (NULL == data[0]) { free(data); return -1; //OPAL_ERR_OUT_OF_RESOURCE; } for (socket_index = 1; socket_index < num_sockets; ++socket_index) { data[socket_index] = data[socket_index - 1] + num_cores; } /* Iterate the PUs in this cpuset; fill in the data[][] array with the socket/core/pu triples */ for (pu_index = 0, pu = hwloc_get_obj_inside_cpuset_by_type(topo, cpuset, HWLOC_OBJ_PU, pu_index); NULL != pu; pu = hwloc_get_obj_inside_cpuset_by_type(topo, cpuset, HWLOC_OBJ_PU, ++pu_index)) { /* Go upward and find the core this PU belongs to */ core = pu; while (NULL != core && core->type != HWLOC_OBJ_CORE) { core = core->parent; } core_index = 0; if (NULL != core) { core_index = core->logical_index; } /* Go upward and find the socket this PU belongs to */ socket = pu; while (NULL != socket && socket->type != HWLOC_OBJ_SOCKET) { socket = socket->parent; } socket_index = 0; if (NULL != socket) { socket_index = socket->logical_index; } /* Save this socket/core/pu combo. LAZY: Assuming that we won't have more PU's per core than (sizeof(int)*8). */ data[socket_index][core_index] |= (1 << pu->sibling_rank); } *map = data; return 0; } /* * Turn an int bitmap to a "a-b,c" range kind of string */ static char *bitmap2rangestr(int bitmap) { size_t i; int range_start, range_end; bool first, isset; char tmp[BUFSIZ]; const int stmp = sizeof(tmp) - 1; static char ret[BUFSIZ]; memset(ret, 0, sizeof(ret)); first = true; range_start = -999; for (i = 0; i < sizeof(int) * 8; ++i) { isset = (bitmap & (1 << i)); /* Do we have a running range? */ if (range_start >= 0) { if (isset) { continue; } else { /* A range just ended; output it */ if (!first) { strncat(ret, ",", sizeof(ret) - strlen(ret) - 1); } else { first = false; } range_end = i - 1; if (range_start == range_end) { snprintf(tmp, stmp, "%d", range_start); } else { snprintf(tmp, stmp, "%d-%d", range_start, range_end); } strncat(ret, tmp, sizeof(ret) - strlen(ret) - 1); range_start = -999; } } /* No running range */ else { if (isset) { range_start = i; } } } /* If we ended the bitmap with a range open, output it */ if (range_start >= 0) { if (!first) { strncat(ret, ",", sizeof(ret) - strlen(ret) - 1); first = false; } range_end = i - 1; if (range_start == range_end) { snprintf(tmp, stmp, "%d", range_start); } else { snprintf(tmp, stmp, "%d-%d", range_start, range_end); } strncat(ret, tmp, sizeof(ret) - strlen(ret) - 1); } return ret; } <file_sep>/sessions/sessions_test5.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpi.h" void print_error(const char *msg, int rc) { char err_str[MPI_MAX_ERROR_STRING]; int resultlen = sizeof(err_str) - 1; MPI_Error_string(rc, err_str, &resultlen); fprintf (stderr, "%s return err code = %d (%s)\n", msg, rc, err_str); } void my_session_errhandler (MPI_Session *foo, int *bar, ...) { fprintf(stderr, "errhandler called with error %d\n", *bar); } int main (int argc, char *argv[]) { MPI_Session session, session1; MPI_Errhandler errhandler; MPI_Group group, group1; MPI_Comm comm_world, comm_self, comm_world1, comm_self1; MPI_Info info; int rc, npsets, npsets1, one = 1, sum, sum1, i; rc = MPI_Session_create_errhandler (my_session_errhandler, &errhandler); if (MPI_SUCCESS != rc) { print_error("Error handler creation failed", rc); return -1; } rc = MPI_Info_create (&info); if (MPI_SUCCESS != rc) { print_error("Info creation failed", rc); return -1; } rc = MPI_Info_set(info, "mpi_thread_support_level", "MPI_THREAD_MULTIPLE"); if (MPI_SUCCESS != rc) { print_error("Info key/val set failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session); if (MPI_SUCCESS != rc) { print_error("Session initialization failed", rc); return -1; } rc = MPI_Session_init (info, errhandler, &session1); if (MPI_SUCCESS != rc) { print_error("Session1 initialization failed", rc); return -1; } rc = MPI_Session_get_num_psets (session, MPI_INFO_NULL, &npsets); for (i = 0 ; i < npsets ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Session_get_num_psets (session1, MPI_INFO_NULL, &npsets1); for (i = 0 ; i < npsets1 ; ++i) { int psetlen = 0; char name[256]; MPI_Session_get_nth_pset (session1, MPI_INFO_NULL, i, &psetlen, NULL); MPI_Session_get_nth_pset (session1, MPI_INFO_NULL, i, &psetlen, name); } rc = MPI_Group_from_session_pset (session, "mpi://WORLD", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://WORLD. ", rc); return -1; } rc = MPI_Group_from_session_pset (session1, "mpi://WORLD", &group1); if (MPI_SUCCESS != rc) { print_error("Could not get a group1 for mpi://WORLD. ", rc); return -1; } MPI_Comm_create_from_group (group, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world); MPI_Group_free (&group); MPI_Comm_create_from_group (group1, "my_world", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_world1); MPI_Group_free (&group1); MPI_Allreduce (&one, &sum, 1, MPI_INT, MPI_SUM, comm_world); rc = MPI_Group_from_session_pset (session, "mpi://SELF", &group); if (MPI_SUCCESS != rc) { print_error("Could not get a group for mpi://SELF. ", rc); return -1; } rc = MPI_Group_from_session_pset (session1, "mpi://SELF", &group1); if (MPI_SUCCESS != rc) { print_error("Could not get a group1 for mpi://SELF. ", rc); return -1; } MPI_Comm_create_from_group (group, "myself", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_self); MPI_Group_free (&group); MPI_Allreduce (&one, &sum, 1, MPI_INT, MPI_SUM, comm_self); MPI_Comm_create_from_group (group1, "myself", MPI_INFO_NULL, MPI_ERRORS_RETURN, &comm_self1); MPI_Group_free (&group1); MPI_Errhandler_free (&errhandler); MPI_Info_free (&info); MPI_Comm_free (&comm_world); MPI_Comm_free (&comm_self); MPI_Session_finalize (&session); MPI_Allreduce (&one, &sum1, 1, MPI_INT, MPI_SUM, comm_world1); MPI_Allreduce (&one, &sum1, 1, MPI_INT, MPI_SUM, comm_self1); MPI_Comm_free (&comm_world1); MPI_Comm_free (&comm_self1); MPI_Session_finalize (&session1); return 0; } <file_sep>/singleton/simple_spawn.c #include <mpi.h> #include <stdio.h> int main(int argc, char *argv[]) { MPI_Comm parent, intercomm; MPI_Init(NULL, NULL); MPI_Comm_get_parent(&parent); if (MPI_COMM_NULL != parent) MPI_Comm_disconnect(&parent); if (argc > 1) { printf("Spawning '%s' ... ", argv[1]); MPI_Comm_spawn(argv[1], MPI_ARGV_NULL, 1, MPI_INFO_NULL, 0, MPI_COMM_SELF, &intercomm, MPI_ERRCODES_IGNORE); MPI_Comm_disconnect(&intercomm); printf("OK\n"); } MPI_Finalize(); } <file_sep>/status/src/status_c.c /* * Copyright (C) 2020 Cisco Systems, Inc. * * $COPYRIGHT$ */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <alloca.h> #include "mpi.h" // Globals in this file, for convenience. static int rank = -1; static MPI_Fint f_mpi_status_size = -1; static MPI_Fint f_mpi_source = -1; static MPI_Fint f_mpi_tag = -1; static MPI_Fint f_mpi_error = -1; // Prototype the Fortran functions that we'll call from here in C void check_cancelled_f_wrapper(MPI_Fint *f_status, MPI_Fint *expected_value, const char *msg); void check_count_f(MPI_Fint *f_status, MPI_Fint *expected_tag, const char *msg); void check_cancelled_f08_wrapper(MPI_F08_status *f08_status, MPI_Fint *expected_value, const char *msg); void check_count_f08(MPI_F08_status *f08_status, MPI_Fint *expected_tag, const char *msg); ///////////////////////////////////////////////////////////////////////// // The first argument is either an MPI_Fint or something that can be // upcasted to an MPI_Fint (i.e., a C int, but sizeof(int)==4 and // sizeof(MPI_Fint)==8). static void check_int(MPI_Fint fint, int cint, const char *msg) { if (fint != cint) { printf("Error: %s: %d != %d\n", msg, fint, cint); exit(1); } } ///////////////////////////////////////////////////////////////////////// static void check_cancelled_c(MPI_Status *status, int expected_value, const char *msg) { int value; MPI_Test_cancelled(status, &value); if (value != expected_value) { printf("Error: %s: %d != %d\n", msg, value, expected_value); exit(1); } } static void check_count_c(MPI_Status *status, MPI_Datatype type, int expected_count, const char *msg) { int count; MPI_Get_count(status, MPI_INTEGER, &count); check_int(count, expected_count, msg); } ///////////////////////////////////////////////////////////////////////// static void test_f082c(MPI_F08_status *f08_status, MPI_Fint f08_tag, MPI_Fint expected_count) { MPI_Status c_status; printf("Testing C MPI_Status_f082c\n"); // NOTE: The f08_status has "cancelled" set to true. MPI_Status_f082c(f08_status, &c_status); check_int(c_status.MPI_SOURCE, rank, "f082c source"); check_int(c_status.MPI_TAG, (int) f08_tag, "f082c tag"); check_int(c_status.MPI_ERROR, MPI_SUCCESS, "f082c success"); check_cancelled_c(&c_status, 1, "f082c cancelled=.true."); check_count_c(&c_status, MPI_INTEGER, (int) expected_count, "f082c count"); } ///////////////////////////////////////////////////////////////////////// static void test_c2f08(MPI_Status *c_status, int c_tag, int expected_count) { MPI_Fint temp; MPI_F08_status f08_status; printf("Testing C MPI_Status_c2f08\n"); // First test with cancelled=0 MPI_Status_set_cancelled(c_status, 0); MPI_Status_c2f08(c_status, &f08_status); check_int(f08_status.MPI_SOURCE, rank, "c2f08 source"); check_int(f08_status.MPI_TAG, c_tag, "c2f08 tag"); check_int(f08_status.MPI_ERROR, MPI_SUCCESS, "c2f08 success"); temp = 0; check_cancelled_f08_wrapper(&f08_status, &temp, "c2f08 cancelled=0"); temp = (MPI_Fint) expected_count; check_count_f08(&f08_status, &temp, "c2f08 count"); // Then test with cancelled=1 MPI_Status_set_cancelled(c_status, 1); MPI_Status_c2f08(c_status, &f08_status); check_int(f08_status.MPI_SOURCE, rank, "c2f08 source"); check_int(f08_status.MPI_TAG, c_tag, "c2f08 tag"); check_int(f08_status.MPI_ERROR, MPI_SUCCESS, "c2f08 success"); temp = (MPI_Fint) 1; check_cancelled_f08_wrapper(&f08_status, &temp, "c2f08 cancelled=1"); temp = (MPI_Fint) expected_count; check_count_f08(&f08_status, &temp, "c2f08 count"); } ///////////////////////////////////////////////////////////////////////// static void test_f2c(MPI_Fint *f_status, MPI_Fint f_tag, MPI_Fint expected_count) { MPI_Status c_status; printf("Testing C MPI_Status_f2c\n"); // NOTE: The f_status has "cancelled" set to true. MPI_Status_f2c(f_status, &c_status); check_int(c_status.MPI_SOURCE, rank, "f2c source"); check_int(c_status.MPI_TAG, (int) f_tag, "f2c tag"); check_int(c_status.MPI_ERROR, MPI_SUCCESS, "f2c success"); check_cancelled_c(&c_status, 1, "f2c cancelled=.true."); check_count_c(&c_status, MPI_INTEGER, (int) expected_count, "f2c count"); } ///////////////////////////////////////////////////////////////////////// static void test_c2f(MPI_Status *c_status, int c_tag, int expected_count) { MPI_Fint temp; MPI_Fint *f_status = alloca((size_t) f_mpi_status_size * sizeof(MPI_Fint)); printf("Testing C MPI_Status_c2f\n"); // First test with cancelled=0 MPI_Status_set_cancelled(c_status, 0); MPI_Status_c2f(c_status, f_status); check_int(f_status[f_mpi_source], rank, "c2f source"); check_int(f_status[f_mpi_tag], c_tag, "c2f tag"); check_int(f_status[f_mpi_error], MPI_SUCCESS, "c2f success"); temp = 0; check_cancelled_f_wrapper(f_status, &temp, "c2f cancelled=0"); temp = (MPI_Fint) expected_count; check_count_f(f_status, &temp, "c2f count"); // Then test with cancelled=1 MPI_Status_set_cancelled(c_status, 1); MPI_Status_c2f(c_status, f_status); check_int(f_status[f_mpi_source], rank, "c2f source 2"); check_int(f_status[f_mpi_tag], c_tag, "c2f tag 2"); check_int(f_status[f_mpi_error], MPI_SUCCESS, "c2f success 2"); temp = (MPI_Fint) 1; check_cancelled_f_wrapper(f_status, &temp, "c2f cancelled=1"); temp = (MPI_Fint) expected_count; check_count_f(f_status, &temp, "c2f count 2"); } ///////////////////////////////////////////////////////////////////////// static void test_f082f(MPI_F08_status *f08_status, MPI_Fint f08_tag, MPI_Fint expected_count) { MPI_Fint temp; MPI_Fint *f_status = alloca((size_t) f_mpi_status_size * sizeof(MPI_Fint)); printf("Testing C MPI_Status_f082f\n"); // NOTE: The f08_status has "cancelled" set to true. MPI_Status_f082f(f08_status, f_status); check_int(f_status[f_mpi_source], rank, "f082f source"); check_int(f_status[f_mpi_tag], f08_tag, "f082f tag"); check_int(f_status[f_mpi_error], MPI_SUCCESS, "f082f success"); temp = 1; check_cancelled_f_wrapper(f_status, &temp, "f082f cancelled=.true."); check_count_f(f_status, &expected_count, "f082f count"); } ///////////////////////////////////////////////////////////////////////// static void test_f2f08(MPI_Fint *f_status, MPI_Fint f_tag, MPI_Fint expected_count) { MPI_Fint temp; MPI_F08_status f08_status; printf("Testing C MPI_Status_f2f08\n"); // NOTE: The f_status has "cancelled" set to true. MPI_Status_f2f08(f_status, &f08_status); check_int(f08_status.MPI_SOURCE, rank, "f2f08 source"); check_int(f08_status.MPI_TAG, f_tag, "f2f08 tag"); check_int(f08_status.MPI_ERROR, MPI_SUCCESS, "f2f08 success"); temp = 1; check_cancelled_f_wrapper(f_status, &temp, "f2f08 cancelled=.true."); check_count_f(f_status, &expected_count, "f2f08 count"); } ///////////////////////////////////////////////////////////////////////// static void generate_c_status(MPI_Status *status, int c_tag, int c_count) { MPI_Fint sendbuf, recvbuf; MPI_Request requests[2]; MPI_Status statuses[2]; // Create a status the "normal" way // // Use a non-blocking send/receive to ourselves so that we can use // an array WAIT function so that the MPI_ERROR element will be // set in the resulting status. sendbuf = 789; MPI_Irecv(&recvbuf, 1, MPI_INTEGER, rank, c_tag, MPI_COMM_WORLD, &requests[0]); MPI_Isend(&sendbuf, 1, MPI_INTEGER, rank, c_tag, MPI_COMM_WORLD, &requests[1]); MPI_Waitall(2, requests, statuses); // Copy the resulting receive status to our output status memcpy(status, &statuses[0], sizeof(MPI_Status)); // Now set some slightly different values in the status that // results in a very large count (larger than can be represented // by 32 bits) MPI_Status_set_cancelled(status, 0); MPI_Status_set_elements(status, MPI_INTEGER, c_count); } ///////////////////////////////////////////////////////////////////////// // This function is the entry point from Fortran void test_c_functions(MPI_F08_status *f08_status, MPI_Fint *f08_tag, MPI_Fint *f_status, MPI_Fint *f_tag, MPI_Fint *f_count, MPI_Fint *mpi_status_size, MPI_Fint *mpi_source, MPI_Fint *mpi_tag, MPI_Fint *mpi_error) { MPI_Status c_status; int c_tag; int c_count; MPI_Comm_rank(MPI_COMM_WORLD, &rank); // MPI (up to MPI-4, at least) specifically defines that // MPI_STATUS_SIZE is only available in Fortran. So we need to // pass it in from Fortran so that we can have it here in C. // Ditto for MPI_SOURCE, MPI_TAG, and MPI_ERROR. But note that // those values are indexes in to an array, and since Fortran // indexes on 1 and C indexes on 0, subtract 1 from those values // here in C. f_mpi_status_size = *mpi_status_size; f_mpi_source = *mpi_source - 1; f_mpi_tag = *mpi_tag - 1; f_mpi_error = *mpi_error - 1; printf("Testing C functions...\n"); // Make the C values slightly different than the Fortran values c_tag = 333; c_count = ((int) *f_count) + 99; generate_c_status(&c_status, c_tag, c_count); test_f082c(f08_status, *f08_tag, *f_count); test_c2f08(&c_status, c_tag, c_count); test_f2c(f_status, *f_tag, *f_count); test_c2f(&c_status, c_tag, c_count); test_f082f(f08_status, *f08_tag, *f_count); test_f2f08(f_status, *f_tag, *f_count); } <file_sep>/runtime/hello_world/run.sh #!/bin/bash -xe # Final return value FINAL_RTN=0 # Number of nodes - for accounting/verification purposes # Default: 1 NUM_NODES=${CI_NUM_NODES:-1} if [ "x" != "x${CI_HOSTFILE}" ] ; then ARG_HOSTFILE="--hostfile ${CI_HOSTFILE}" else ARG_HOSTFILE="" fi _shutdown() { # --------------------------------------- # Cleanup # --------------------------------------- exit $FINAL_RTN } # --------------------------------------- # Run the test - Hostname # --------------------------------------- echo "==========================" echo "Test: hostname" echo "==========================" mpirun ${ARG_HOSTFILE} --map-by ppr:5:node hostname 2>&1 | tee output-hn.txt # --------------------------------------- # Verify the results # --------------------------------------- ERRORS=`grep ERROR output-hn.txt | wc -l` if [[ $ERRORS -ne 0 ]] ; then echo "ERROR: Error string detected in the output" FINAL_RTN=1 _shutdown fi LINES=`wc -l output-hn.txt | awk '{print $1}'` if [[ $LINES -ne $(( 5 * $NUM_NODES )) ]] ; then echo "ERROR: Incorrect number of lines of output" FINAL_RTN=2 _shutdown fi if [ $FINAL_RTN == 0 ] ; then echo "Success - hostname" fi # --------------------------------------- # Run the test - Hello World # --------------------------------------- echo "==========================" echo "Test: Hello World" echo "==========================" mpirun ${ARG_HOSTFILE} --map-by ppr:5:node ./hello 2>&1 | tee output.txt # --------------------------------------- # Verify the results # --------------------------------------- ERRORS=`grep ERROR output.txt | wc -l` if [[ $ERRORS -ne 0 ]] ; then echo "ERROR: Error string detected in the output" FINAL_RTN=1 _shutdown fi LINES=`wc -l output.txt | awk '{print $1}'` if [[ $LINES -ne $(( 5 * $NUM_NODES )) ]] ; then echo "ERROR: Incorrect number of lines of output" FINAL_RTN=2 _shutdown fi if [ $FINAL_RTN == 0 ] ; then echo "Success - hello world" fi echo "==========================" echo "Success" echo "==========================" _shutdown <file_sep>/packaging/run_nmcheck.c /* * $HEADER$ * * Run nmcheck_prefix.pl on itself * only needs to be run with one rank */ #include <mpi.h> #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { char cmd[256]; int myrank; int rv; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); if (myrank == 0) { sprintf(cmd, "./nmcheck_prefix.pl \"%s\"", argv[0]); rv = system(cmd); if (rv) { MPI_Abort(MPI_COMM_WORLD, MPI_ERR_OTHER); } } MPI_Finalize(); return 0; } <file_sep>/events/events_callbacks.c /* * events_callbacks.c * * Test event callback registration and free * Test handle and callback get/set info * */ #include "events_common.h" char user_data_string[MAX_STRING] = "Test String"; // Test flags int event_cb_success = 0; int event_free_cb_success = 0; int event_free_cb_user_data_access = 1; int event_handle_get_info_success = 1; int event_handle_set_info_success = 1; int event_handle_set_info_updated = 0; int event_callback_get_info_success = 1; int event_callback_set_info_success = 1; int event_callback_set_info_updated = 0; int event_handle_alloc_event_index_exceed_handled = 1; int event_handle_alloc_event_index_negative_handled = 1; void print_results() { if ( 0 != rank ) return; print_pf_result("MPI_T_event_register_callback", "Event Callback Success", event_cb_success); print_pf_result("MPI_T_event_handle_free", "Event Free Callback Success", event_free_cb_success); print_pf_result("MPI_T_event_handle_free", "Event Free user_data access", event_free_cb_user_data_access); print_pf_result("MPI_T_event_handle_get_info", "Successful call", event_handle_get_info_success); print_pf_result("MPI_T_event_handle_set_info", "Successful call", event_handle_set_info_success); print_pf_result("MPI_T_event_handle_set_info", "Key added to Info object", event_handle_set_info_updated); print_pf_result("MPI_T_event_callback_get_info", "Successful call", event_callback_get_info_success); print_pf_result("MPI_T_event_callback_set_info", "Successful call", event_callback_set_info_success); print_pf_result("MPI_T_event_callback_set_info", "Key added to Info object", event_callback_set_info_updated); if ( do_failure_tests ) { print_pf_result("MPI_T_event_handle_alloc", "Handled event index too large", event_handle_alloc_event_index_exceed_handled); print_pf_result("MPI_T_event_handle_alloc", "Handled negative event index", event_handle_alloc_event_index_negative_handled); } fprintf(outstream, "%-*s - %-*s : %6d\n", func_width, "TOTAL ERROR COUNT", metric_width, "", error_count); } void test_event_cb_function(MPI_T_event_instance event, MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data) { print_debug("In cb_function : %s %s %d\n", __func__, __FILE__, __LINE__); //print_debug("user_data is :%s:\n", (char*)user_data); //print_debug("user_data_string is :%s:\n", (char*)user_data_string); event_cb_success = 1; if ( NULL == user_data || strcmp(user_data, user_data_string) ) print_error("test_event_cb_function could not access user_data", NO_MPI_ERROR_CODE, TEST_CONTINUE); } void test_free_event_cb_function(MPI_T_event_registration handle, MPI_T_cb_safety cb_safety, void *user_data) { print_debug("In cb_function : %s %s %d\n", __func__, __FILE__, __LINE__); print_debug("user_data is :%s:\n", (char*)user_data); event_free_cb_success = 1; if ( NULL == user_data || strcmp(user_data, user_data_string) ) { print_error("test_event_free_cb_function could not access user_data", NO_MPI_ERROR_CODE, TEST_CONTINUE); event_free_cb_user_data_access = 0; } } void test_handle_alloc_register_free() { int retval; MPI_T_event_registration event_registration; // TEST MPI_T_event_handle_alloc // print_debug("Testing expected success for index %d\n", event_index); retval = MPI_T_event_handle_alloc(event_index, MPI_COMM_WORLD, MPI_INFO_NULL, &event_registration) ; if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_handle_alloc did not return MPI_SUCCESS", retval, TEST_EXIT); // Test MPI_T_event_handle_alloc invalid arguments if ( do_failure_tests ) { int bad_event_index; MPI_T_event_registration bad_event_registration; bad_event_index = 11111111; print_debug("Testing expected failure for index %d\n", bad_event_index); retval = MPI_T_event_handle_alloc(bad_event_index, MPI_COMM_WORLD, MPI_INFO_NULL, &bad_event_registration) ; if ( retval == MPI_SUCCESS ) { print_error("MPI_T_event_handle_alloc returned MPI_SUCCESS with too large index", retval, TEST_EXIT); event_handle_alloc_event_index_exceed_handled = 0; } else print_debug("MPI_T_event_handle_alloc handled too large index\n", retval, TEST_EXIT); bad_event_index = -1; print_debug("Testing expected failure for index %d\n", bad_event_index); retval = MPI_T_event_handle_alloc(bad_event_index, MPI_COMM_WORLD, MPI_INFO_NULL, &bad_event_registration) ; if ( retval == MPI_SUCCESS ) { print_error("MPI_T_event_handle_alloc returned MPI_SUCCESS with negative index", retval, TEST_EXIT); event_handle_alloc_event_index_negative_handled = 0; } else print_debug("MPI_T_event_handle_alloc handled negative index\n", retval, TEST_EXIT); } // TEST MPI_T_event_register_callback // cb_user_data = (void*)user_data_string; print_debug("cb_user_data is %s\n", cb_user_data); print_debug("Testing expected MPI_T_event_register_callback success for index %d\n", event_index); retval = MPI_T_event_register_callback(event_registration, MPI_T_CB_REQUIRE_ASYNC_SIGNAL_SAFE, MPI_INFO_NULL, cb_user_data, test_event_cb_function); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_register_callback did not return MPI_SUCCESS", retval, TEST_EXIT); if ( do_failure_tests ) { } generate_callback_activity(); //} // TEST MPI_T_event_handle_free // retval = MPI_T_event_handle_free(event_registration, cb_user_data, test_free_event_cb_function); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_handle_free did not return MPI_SUCCESS", retval, TEST_EXIT); if ( do_failure_tests ) { } } void print_info_obj(MPI_Info info) { int i, retval, vallen = MPI_MAX_INFO_VAL, nkeys, flag; char key[MPI_MAX_INFO_KEY]; char value[MPI_MAX_INFO_VAL+1]; retval = MPI_Info_get_nkeys(info, &nkeys); if ( retval != MPI_SUCCESS ) print_error("MPI_Info_get_nkeys did not return MPI_SUCCESS", retval, TEST_CONTINUE); print_debug("MPI_Info_get_nkeys nkeys is %d\n", nkeys); for ( i = 0; i < nkeys; i++ ) { MPI_Info_get_nthkey( info, i, key ); retval = MPI_Info_get( info, key, vallen, value, &flag ); if ( retval != MPI_SUCCESS ) { print_error("MPI_Info_get did not return MPI_SUCCESS", retval, TEST_CONTINUE); } else print_debug("Info entry index %2d - %d:%s:%s:%d\n", i, flag, key, value); } } void test_info() { int retval, vallen = MPI_MAX_INFO_VAL, nkeys, flag, initial_nkeys = 0; MPI_T_event_registration event_registration; char key[MPI_MAX_INFO_KEY]; char value[MPI_MAX_INFO_VAL+1]; MPI_Info info; MPI_T_cb_safety cb_safety = MPI_T_CB_REQUIRE_ASYNC_SIGNAL_SAFE; // // Tests // // - Test for successful calls to all get/set info // - Check to see if set info calls add values for get calls // - Record initial nkeys count // - Add unique key // - get_info // - See if nkeys has increased // // Set Up Test // // Allocate a handle to use for testing retval = MPI_T_event_handle_alloc(event_index, MPI_COMM_WORLD, MPI_INFO_NULL, &event_registration) ; if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_handle_alloc did not return MPI_SUCCESS", retval, TEST_EXIT); // // Get Handle Info // retval = MPI_T_event_handle_get_info(event_registration, &info); if ( retval != MPI_SUCCESS ) { print_error("MPI_T_event_handle_get_info did not return MPI_SUCCESS", retval, TEST_CONTINUE); event_handle_get_info_success = 0; } // // Get And Store Handle Info Key Count // retval = MPI_Info_get_nkeys(info, &nkeys); if ( retval != MPI_SUCCESS ) print_error("MPI_Info_get_nkeys did not return MPI_SUCCESS", retval, TEST_CONTINUE); else initial_nkeys = nkeys; print_debug("MPI_Info_get_nkeys nkeys is %d\n", nkeys); // // Add Entry To Handle Info // retval = MPI_Info_set(info, "randomkey", "randomkeyvalue"); if ( retval != MPI_SUCCESS ) print_error("MPI_info_set did not return MPI_SUCCESS", retval, TEST_CONTINUE); print_info_obj(info); retval = MPI_Info_get_nkeys(info, &nkeys); if ( retval != MPI_SUCCESS ) print_error("MPI_Info_get_nkeys did not return MPI_SUCCESS", retval, TEST_CONTINUE); print_debug("After MPI_Info_set, MPI_Info_get_nkeys nkeys is %d\n", nkeys); // // Confirm Entry Has Been Added // MPI_Info_get_nthkey( info, 0, key ); retval = MPI_Info_get( info, key, vallen, value, &flag ); if ( retval != MPI_SUCCESS ) { print_error("MPI_Info_get did not return MPI_SUCCESS", retval, TEST_CONTINUE); } else print_debug("Verifying that info values are %d:%s:%s:%d\n", flag, key, value); // // Set Handle Info // retval = MPI_T_event_handle_set_info(event_registration, info); if ( retval != MPI_SUCCESS ) { print_error("MPI_T_event_handle_set_info did not return MPI_SUCCESS", retval, TEST_CONTINUE); event_handle_set_info_success = 0; } // // Get Event Handle Info // retval = MPI_T_event_handle_get_info(event_registration, &info); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_handle_get_info did not return MPI_SUCCESS", retval, TEST_CONTINUE); // // Test For Increase In Nkeys To Confirm Update // retval = MPI_Info_get_nkeys(info, &nkeys); if ( retval != MPI_SUCCESS ) print_error("MPI_Info_get_nkeys did not return MPI_SUCCESS", retval, TEST_CONTINUE); if ( nkeys > initial_nkeys ) event_handle_set_info_updated = 1; else print_error("MPI_T_event_handle_set_info did not update info object", NO_MPI_ERROR_CODE, TEST_CONTINUE); print_debug("MPI_T_event_handle_get_info nkeys is %d\n", nkeys); // Register Callback retval = MPI_T_event_register_callback(event_registration, cb_safety, MPI_INFO_NULL, cb_user_data, test_event_cb_function); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_register_callback did not return MPI_SUCCESS", retval, TEST_EXIT); // // Get Handle Info // retval = MPI_T_event_callback_get_info(event_registration, cb_safety, &info); if ( retval != MPI_SUCCESS ) { print_error("MPI_T_event_callback_get_info did not return MPI_SUCCESS", retval, TEST_CONTINUE); event_callback_get_info_success = 0; } // // Get And Store Callback Info Key Count // retval = MPI_Info_get_nkeys(info, &nkeys); if ( retval != MPI_SUCCESS ) print_error("MPI_Info_get_nkeys did not return MPI_SUCCESS", retval, TEST_CONTINUE); else initial_nkeys = nkeys; print_debug("MPI_Info_get_nkeys nkeys is %d\n", nkeys); // // Add Entry To Callback Info // retval = MPI_Info_set(info, "randomkey", "randomkeyvalue"); if ( retval != MPI_SUCCESS ) print_error("MPI_info_set did not return MPI_SUCCESS", retval, TEST_CONTINUE); print_info_obj(info); retval = MPI_Info_get_nkeys(info, &nkeys); if ( retval != MPI_SUCCESS ) print_error("MPI_Info_get_nkeys did not return MPI_SUCCESS", retval, TEST_CONTINUE); print_debug("After MPI_Info_set, MPI_Info_get_nkeys nkeys is %d\n", nkeys); // // Confirm Entry Has Been Added // MPI_Info_get_nthkey( info, 0, key ); retval = MPI_Info_get( info, key, vallen, value, &flag ); if ( retval != MPI_SUCCESS ) { print_error("MPI_Info_get did not return MPI_SUCCESS", retval, TEST_CONTINUE); } else print_debug("Verifying that info values are %d:%s:%s:%d\n", flag, key, value); // // Set Callback Info // retval = MPI_T_event_callback_set_info(event_registration, cb_safety, info); if ( retval != MPI_SUCCESS ) { print_error("MPI_T_event_callback_set_info did not return MPI_SUCCESS", retval, TEST_CONTINUE); event_callback_set_info_success = 0; } // // Get Event Callback Info // retval = MPI_T_event_callback_get_info(event_registration, cb_safety, &info); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_callback_get_info did not return MPI_SUCCESS", retval, TEST_CONTINUE); // // Test For Increase In Nkeys To Confirm Update // retval = MPI_Info_get_nkeys(info, &nkeys); if ( retval != MPI_SUCCESS ) print_error("MPI_Info_get_nkeys did not return MPI_SUCCESS", retval, TEST_CONTINUE); if ( nkeys > initial_nkeys ) event_callback_set_info_updated = 1; else print_error("MPI_T_event_callback_set_info did not update info object", NO_MPI_ERROR_CODE, TEST_CONTINUE); print_debug("MPI_T_event_callback_get_info nkeys is %d\n", nkeys); } int main (int argc, char** argv) { test_init("MPI_T Events Callback Tests", argc, argv); test_handle_alloc_register_free(); test_info(); print_results(); MPI_T_finalize(); MPI_Finalize(); return 0; } <file_sep>/runtime/bin/cleanup-scrub-local.sh #!/bin/bash PROGS="prte prted prun mpirun timeout" clean_files() { FILES=("pmix-*" "core*" "openmpi-sessions-*" "pmix_dstor_*" "ompi.*" "prrte.*" ) for fn in ${FILES[@]}; do find /tmp/ -maxdepth 1 \ -user $USER -a \ -name $fn \ -exec rm -rf {} \; if [ -n "$TMPDIR" ] ; then find $TMPDIR -maxdepth 1 \ -user $USER -a \ -name $fn \ -exec rm -rf {} \; fi done } killall -q ${PROGS} > /dev/null clean_files killall -q -9 ${PROGS} > /dev/null exit 0 <file_sep>/events/events_types.c /* * events_types.c * * Test events type functions for event count and info * */ #include "events_common.h" int event_count = 0; // Test flags int event_info_success = 0; int event_info_failed = 0; int event_info_displacements_start_at_0 = 1; int event_count_result = 0; int event_get_num_handle_null = 0; void print_results() { if ( 0 != rank ) return; fprintf(outstream, "%-*s - %-*s : %6d\n", func_width, "MPI_T_event_get_num", metric_width, "Event count", event_count); print_pf_result("MPI_T_event_get_num", "Successful return", event_count_result); print_pf_result("MPI_T_event_get_info", "Successful return", event_info_success); print_pf_result("MPI_T_event_get_info", "Displacements start at 0", event_info_displacements_start_at_0); fprintf(outstream, "%-*s - %-*s : %6d\n", func_width, "MPI_T_event_get_info", metric_width, "Successful event calls", event_info_success); fprintf(outstream, "%-*s - %-*s : %6d\n", func_width, "MPI_T_event_get_info", metric_width, "Unexpected Failed event calls", event_info_failed); if ( do_failure_tests ) { print_pf_result("MPI_T_event_get_num", "Handle NULL argument", event_get_num_handle_null); } fprintf(outstream, "%-*s - %-*s : %6d\n", func_width, "TOTAL ERROR COUNT", metric_width, "", error_count); } void test_get_num() { int retval; retval = MPI_T_event_get_num(&event_count); if ( retval != MPI_SUCCESS ) print_error("MPI_T_event_get_num did not return MPI_SUCCESS", retval, TEST_EXIT); else event_count_result = 1; if ( do_failure_tests ) { retval = MPI_T_event_get_num(NULL); if ( retval != MPI_ERR_ARG ) { fprintf(errout, "Expected value %d, got %d\n", MPI_ERR_ARG, retval); print_error("MPI_T_event_get_num did not return MPI_ERR_ARG", retval, TEST_CONTINUE); } else event_get_num_handle_null = 1; } } void test_get_info() { int i, d; char type_name[MPI_MAX_OBJECT_NAME]; int retval, resultlen; EVENT_INFO *infos; EVENT_INFO ci; infos = (EVENT_INFO*)malloc (event_count * sizeof(EVENT_INFO)); if ( NULL == infos ) print_error("Failed to allocate event info object!!!", -1, TEST_EXIT); /* * get_info requirements * * subsequent calls to this routine that query information about the same event type must return the same information * returns MPI_T_ERR_INVALID_INDEX if event_index does not match a valid event type index */ for ( i = 0; i < event_count; i++ ) { ci.event_index = i; // int MPI_T_event_get_info(int event_index, char *name, int *name_len, // int *verbosity, MPI_Datatype *array_of_datatypes, // MPI_Aint *array_of_displacements, int *num_elements, // MPI_T_enum *enumtype, MPI_Info* info, // char *desc, int *desc_len, int *bind) // /* Get lengths */ retval = MPI_T_event_get_info ( ci.event_index, NULL, &(ci.name_len), &(ci.verbosity), NULL, NULL, &(ci.num_elements), &(ci.enumtype), NULL, NULL, &(ci.desc_len), &(ci.bind) ); if (MPI_SUCCESS != retval && MPI_T_ERR_INVALID_INDEX != retval ) { if ( MPI_T_ERR_INVALID_INDEX != retval ) { fprintf(errout, "Expected value %d, got %d\n", MPI_T_ERR_INVALID_INDEX, retval); } print_error("MPI_T_event_get_info Invalid return value", -1, TEST_CONTINUE); } if (MPI_SUCCESS != retval ) { print_error("Failed to get event info", retval, TEST_CONTINUE); event_info_failed++; ci.name_len = 0; memcpy(&infos[i], &ci, sizeof(EVENT_INFO)); continue; } else { event_info_success++; } // allocate strings and arrays for datatypes and displacements ci.name = (char*)malloc(ci.name_len); ci.array_of_datatypes = (MPI_Datatype*)malloc(ci.num_elements*sizeof(MPI_Datatype)); ci.array_of_displacements = (MPI_Aint*)malloc(ci.num_elements*sizeof(MPI_Aint)); ci.desc = (char*)malloc(ci.desc_len); if ( !ci.name || ! ci.array_of_datatypes || !ci.array_of_displacements || !ci.desc ) print_error("Failed to allocate info name and description buffers", retval, TEST_EXIT); /* Get data */ retval = MPI_T_event_get_info( ci.event_index, ci.name, &(ci.name_len), &(ci.verbosity), ci.array_of_datatypes, ci.array_of_displacements, &(ci.num_elements), &(ci.enumtype), &(ci.info), ci.desc, &(ci.desc_len), &(ci.bind) ) ; if (MPI_SUCCESS != retval ) { print_error("Failed to get event info", retval, TEST_CONTINUE); event_info_failed++; } else { event_info_success++; } memcpy(&infos[i], &ci, sizeof(EVENT_INFO)); if ( 1 == event_info_displacements_start_at_0 && 0 != ci.array_of_displacements[0] ) { print_error("Event_info displacements do not start at 0", retval, TEST_CONTINUE); event_info_displacements_start_at_0 = 0; } } // Print event info and elements if ( print_events && !rank ) { for ( i = 0; i < event_count; i++ ) { if ( infos[i].name_len < 1 ) { print_debug("Event[%7d] : Unavailable\n", infos[i].event_index); continue; } fprintf(outstream, "Event[%7d] : %-40s : %-50.*s : %5d : %s\n", infos[i].event_index, infos[i].name, MAX_STRING-1, infos[i].desc, infos[i].num_elements, bind_str(infos[i].bind) ); for ( d = 0; d < infos[i].num_elements; d++ ) { if ( infos[i].array_of_datatypes[d] != 0 ) { MPI_Type_get_name( infos[i].array_of_datatypes[d], type_name, &resultlen); fprintf(outstream, " [%d] Datatype : %20s Displacement : %lu\n", d, type_name, (unsigned long)infos[i].array_of_displacements[d]); } } fprintf(outstream, "\n"); } } free(ci.name); free(ci.desc); free(infos); } int main (int argc, char** argv) { test_init("MPI_T Events Type Tests", argc, argv); test_get_num(); test_get_info(); print_results(); MPI_T_finalize(); MPI_Finalize(); return 0; } <file_sep>/runtime/bin/pretty-print-hwloc/src/include/autogen/hwloc_tools_config_bottom.h /* * */ #include <limits.h> #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif <file_sep>/events/Makefile EXES = events_types events_callbacks events_read_data events_meta_data events_source events_dropped events_example CC= mpicc CFLAGS= -O2 -g -Wall LIBS=events_common.o def: clean ${EXES} events_types : events_types.o events_common.o $(CC) $(CFLAGS) -o $@ $< ${LIBS} events_callbacks : events_callbacks.o events_common.o $(CC) $(CFLAGS) -o $@ $< ${LIBS} events_read_data : events_read_data.o events_common.o $(CC) $(CFLAGS) -o $@ $< ${LIBS} events_meta_data : events_meta_data.o events_common.o $(CC) $(CFLAGS) -o $@ $< ${LIBS} events_source : events_source.o events_common.o $(CC) $(CFLAGS) -o $@ $< ${LIBS} events_dropped : events_dropped.o events_common.o $(CC) $(CFLAGS) -o $@ $< ${LIBS} events_example : events_example.o $(CC) $(CFLAGS) -o $@ $< clean: rm -f ${EXES} core.* *.o
d5c17a98e78f10baaddf29dd8713e50eef56203c
[ "Markdown", "Makefile", "C", "M4Sugar", "Shell" ]
65
C
open-mpi/ompi-tests-public
dcc6ec78448000ee2519623134d2595d394feff0
36f57a5bd16d8d933a9b9f7d4aaaafc91e978d27
refs/heads/master
<repo_name>poojabhatia1997/Todo-api<file_sep>/server.js var express = require('express'); var bodyParser = require('body-parser'); var _ = require('underscore'); var db = require('./db.js'); var middleware = require('./middleware.js')(db); var app = express(); var bcrypt = require('bcrypt'); var PORT = process.env.PORT || 3000; // var todos = [{ // id: 1, // description: '<NAME>', // completed: false // }, // { // id: 2, // description: '<NAME>', // completed: false // }]; var todos = []; var nextTodoId = 1; app.use(bodyParser.json()); app.get('/', middleware.requireAuthentication, function (req, res) { res.send('Todo API Root'); }); app.get('/todos',middleware.requireAuthentication, function (req,res) { // var queryParams = req.query; // var filteredTodos = todos; // if (queryParams.hasOwnProperty('completed') && queryParams.completed === 'true'){ // filteredTodos = _.where(filteredTodos, {'completed': true}); // }else if (queryParams.hasOwnProperty('completed') && queryParams.completed === 'false'){ // filteredTodos = _.where(filteredTodos, {'completed': false}); // } // if (queryParams.hasOwnProperty('q') && queryParams.q.length > 0 ) { // filteredTodos = _.filter(filteredTodos, function(todo) { // return todo.description.toLowerCase().indexOf(queryParams.q.toLowerCase()) > -1; // }); // } // res.json(filteredTodos); var query = req.query; var where = {} if (query.hasOwnProperty('completed') && query.completed === 'true'){ where.completed = true } else if (query.hasOwnProperty('completed') && query.completed === 'false'){ where.completed = false } if (query.hasOwnProperty('q') && query.q.length > 0){ where.description = { $like: '%' + query.q + '%' } } db.todo.findAll({ where: where }).then(function (todos) { if (todos){ res.json(todos); } }, function (e) { res.status(500).send(); }); }); app.get('/todos/:id', middleware.requireAuthentication, function (req,res) { var todoid = parseInt( req.params.id, 10 ); var matchedTodo; // var matchedTodo = _.findWhere(todos, {id: todoid}); // todos.forEach(function (todo) { // //res.send('Outside loop ' + todoid + todo.id); // if (todoid === todo.id){ // matchedTodo = todo; // } // }); // if (matchedTodo){ // res.json(matchedTodo); // } // else{ // res.status(404).send(); // } db.todo.findById(todoid).then(function (todo){ if(!!todo){ res.json(todo.toJSON()); // using sequlite } else { res.status(404).send(); } },function (e) { res.status(500).send(); }); }); app.post('/todos', middleware.requireAuthentication, function (req, res) { //var body = req.body; var body = _.pick(req.body, 'description', 'completed'); db.todo.create(body).then(function (todo) { req.user.addTodo(todo).then(function(){ return todo.reload(); }).then( function (todo) { res.json(todo.toJSON()); }); }), function (e) { res.status(400).json(e); } // if (!(_isBoolean(body.completed)) || !(_isString(body.description))) { // return res.status(404).send(); // } // body.id = nextTodoId++; // todos.push(body); // res.json(body); }); app.post('/users', function (req, res) { var body = _.pick(req.body,'email', 'password'); db.user.create(body).then(function (data) { res.json(data.toPublicJSON()); },function (e) { res.status(400).json(e); }); }); app.post('/users/login', function (req, res) { var body = _.pick(req.body,'email', 'password'); //using class methods db.user.authenticate(body).then(function (user) { var token = user.generateToken('authentication'); return db.token.create({ token: token }).then(function (tokenInstance) { res.header('Auth', tokenInstance.get('token')).json(user.toPublicJSON()); }).catch(function () { res.status(401).send(); }); }); // if (typeof body.email !== 'string' && typeof body.password !== 'string'){ // res.status(404).send(); // } // db.user.findOne({ // where: { // email: body.email // } // }).then(function (user) { // if( !user || !bcrypt.compareSync(body.password,user.get('password_hash'))){ //match password entered by user in login and the stired hashed password // return res.status(401).send(); // } // res.json(user.toPublicJSON()); // }, function (e) { // res.status(500).send(); // }); }); app.delete('/users/login', middleware.requireAuthentication, function (req, res) { console.log("1"); req.token.destroy().then(function () { console.log("2"); res.status(204).send(); }).catch(function () { console.log("3"); res.status(500).send(); }); }); app.delete('/todos/:id',middleware.requireAuthentication ,function (req, res) { // var todoid = parseInt(req.params.id,10); // var matchedTodo = _.findWhere(todos, {id: todoid}); // if (!matchedTodo) { // res.status(404).json({"error": "No todo found with id"}); // } // else{ // todos = _.without(todos, matchedTodo); // res.json(matchedTodo); // } var todoid = parseInt(req.params.id,10); db.todo.destroy({ where: { id: todoid } }).then(function (rowDeleted) { if (rowDeleted === 0){ res.status(404).json("No todo found!"); }else{ res.status(204).send(); } },function () { res.status(500).send(); }); }); app.put('/todos/:id',middleware.requireAuthentication ,function (req, res) { // var todoid = parseInt(req.params.id,10); // var matchedTodo = _.findWhere(todos, {id: todoid}); // var body = _.pick(req.body, 'description', 'completed'); // var validAttributes = {} // if (body.hasOwnProperty('completed') && _.isBoolean(body.completed)){ // validAttributes.completed = body.completed; // }else if (body.hasOwnProperty('completed')) { // return res.status(400).send(); // } // if (body.hasOwnProperty('description') && _.isString(body.description) && body.description.trim().length > 0){ // validAttributes.description = body.description; // }else if (body.hasOwnProperty('description')){ // return res.status(400).send(); // } // _.extend(matchedTodo, validAttributes); // res.json(matchedTodo); var todoid = parseInt(req.params.id, 10); var body = _.pick(req.body,'description','completed'); var attributes = {} if(body.hasOwnProperty('description')){ attributes.description = body.description; } else if (body.hasOwnProperty('completed')){ attributes.completed = body.completed; } db.todo.findById(todoid).then(function (todo) { if (todo){ return todo.update(attributes); //todo.update is instance method }else{ res.status(404).send(); } },function () { res.status(500).send(); }).then(function (todo) { res.json(todo.toJSON()); }, function (e) { res.status(400).send(); }); }); db.sequelize.sync({force: true}).then(function () { //db.sequelize.sync({force: true}) for droping table and creating new app.listen(PORT, function () { console.log('Express listening on post ' + PORT + '!'); }); });
997d7e66c7b3093509919bbb386c497c78677bf3
[ "JavaScript" ]
1
JavaScript
poojabhatia1997/Todo-api
10c7466800be3ff09ee4f9cf11ec26fd8438ed65
240c4105638e293baa419d424a97ced222522cc0
refs/heads/master
<repo_name>phouse512/faucet<file_sep>/src/constants/auth.constants.js export const authConstants = { AUTH_STORAGE: 'faucet_app_user', }; <file_sep>/src/auth.js import { authConstants } from './constants'; const auth = { currentUser() { return true; if (localStorage.getItem(authConstants.AUTH_STORAGE)) { return JSON.parse(localStorage.getItem(authConstants.AUTH_STORAGE)); } return null; }, loggedIn() { const token = localStorage && localStorage.getItem(authConstants.AUTH_STORAGE); if (token) { return true; } return false; }, }; export default auth; <file_sep>/src/containers/BudgetPage.jsx import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import BudgetNavbar from '../components/budget/BudgetNavbar'; import { changeView } from '../actions/budget.actions'; export class BudgetPage extends React.Component { render () { return ( <div className="budget-page"> <BudgetNavbar viewChange={this.props.changeView} selectedView={this.props.selectedView} /> <h4>Test</h4> </div> ); } } BudgetPage.propTypes = { match: PropTypes.shape({ url: PropTypes.string, }).isRequired, }; export const mapStateToProps = state => ({ selectedView: state.budget.view, }); export const mapDispatchToProps = dispatch => ({ changeView: (view) => dispatch(changeView(view)), }); const BudgetPageContainer = connect( mapStateToProps, mapDispatchToProps, )(BudgetPage); export default BudgetPageContainer; <file_sep>/src/constants/budget.constants.js export const budgetConstants = { CHANGE_VIEW: 'B_CHANGE_VIEW', }; <file_sep>/src/components/Navbar.jsx import React from 'react'; import PropTypes from 'prop-types'; import { NavLink } from 'react-router-dom'; const Navbar = ({ match }) => ( <div className="flex-container flex-column navbar"> <h2 className="navbar__title"><i className="fas fa-tint"></i> faucet</h2> <div className="nav-menu"> <ul> <li className="nav-menu__item"> <NavLink to={`${match.url}/overview`} activeClassName="nav-menu__item--active"> <i className="fas fa-tachometer-alt"></i> overview </NavLink> </li> <li className="nav-menu__item"> <NavLink to={`${match.url}/finance`} activeClassName="nav-menu__item--active"> <i className="fas fa-dollar-sign"></i> finance </NavLink> </li> </ul> </div> </div> ); Navbar.defaultProps = {}; Navbar.propTypes = { match: PropTypes.shape({ url: PropTypes.string, }).isRequired, }; export default Navbar; <file_sep>/src/reducers/index.js import { combineReducers } from 'redux'; import budget from './budget'; import login from './login'; const appReducer = combineReducers({ budget, login, }); const faucetApp = (state, action) => { return appReducer(state, action); }; export default faucetApp; <file_sep>/src/reducers/budget.js import { budgetConstants } from '../constants'; const baseState = { isLoading: false, view: 'analysis', }; const budget = (state = baseState, action) => { switch (action.type) { case budgetConstants.CHANGE_VIEW: return Object.assign({}, state, { view: action.view, }); default: return state; } }; export default budget; <file_sep>/src/components/budget/BudgetNavbar.jsx import React from 'react'; import PropTypes from 'prop-types'; import { NavLink } from 'react-router-dom'; import SelectBar from '../common/SelectBar'; const BudgetNavbar = ({ viewChange, selectedView }) => ( <div className="budget-nav"> <SelectBar items={[ { name: 'Analysis', value: 'analysis' }, { name: 'Label Records', value: 'label' }, { name: 'Add Source', value: 'source' }, { name: 'Settings', value: 'settings' }, ]} onChange={viewChange} selected={selectedView} /> <div className="budget-nav-right"> 21 unlabeled </div> </div> ); BudgetNavbar.defaultProps = {}; BudgetNavbar.propTypes = { selectedView: PropTypes.string.isRequired, viewChange: PropTypes.func.isRequired, }; export default BudgetNavbar;
9910a5a078ffaf2875a4c42e9cd80763432b146a
[ "JavaScript" ]
8
JavaScript
phouse512/faucet
c08363cbc32ab475f730c112539c78259e11b096
b5ba1434beb01f934024913a70469d7c3ea1c91e
refs/heads/master
<file_sep>var $ = function (id) { return document.getElementById(id); }; var calculate_click = function () { var floatHwPts; floatHwPts = parseFloat($("hw_pts").value); floatMidPts= parseFloat($("mid_pts").value); floatFinPts= parseFloat($("fin_pts").value); floatTotalPts= parseFloat(floatHwPts+ floatMidPts+ floatFinPts); intGradeOption= parseInt($("grade_option").value); if (intGradeOption===1) { if(floatTotalPts >= 80) { stringMessage= "Pass"; } else { stringMessage= "Fail"; } } else { if (floatTotalPts>= 90) { stringMessage= "A"; } else { if (floatTotalPts>= 80 && floatTotalPts < 90) { stringMessage= "B"; } else { if (floatTotalPts>= 70 && floatTotalPts < 80) { stringMessage="C"; } else { if (floatTotalPts>= 60 && floatTotalPts < 70) { stringMessage="D"; } else { stringMessage="F"; } } } } } $("final_grade").value= stringMessage; }; window.onload = function () { $("final_grade").value = ""; //blanks the final grade text box upon page load $("calculate").onclick = calculate_click; //activates main method when the button is clicked $("hw_pts").focus(); //puts the cursor on the first DOM text input box };
6b5959eaca90030d79e7f60a7518f19b77cf044d
[ "JavaScript" ]
1
JavaScript
Howell1999/CIS-2013-programs
a887366cdb3d4b0df366490bf6295875c4dbc618
f3c02ab5904bcbb24dbb4e7f9b87d76694559770
refs/heads/master
<repo_name>cmxiv/ngjest<file_sep>/README.md # NgJest Create new Angular project with Jest as the testing framework of choice. ## How to use? ``` npx ngjest <project name> <ng new options> ``` ## Pending features - Add formatter - Add interactive way to configure the installation<file_sep>/index.js #!/usr/bin/env node import minimist from 'minimist' import shell from 'shelljs' import addJest from './jest.js' import removeKarma from './karma.js' const args = minimist(process.argv.slice(2)) const project = args._[0] delete args._ // Set some defaults if(!args['style']) { args['style'] = 'scss' } // Create new Angular project without installing let ngArgs = Object.keys(args).map(arg => `--${arg} ${args[arg]}`).join(' ') ngArgs = !!ngArgs.length ? ` ${ngArgs}` : '' shell.exec(`ng new ${project}${ngArgs}`) // Remove Karma removeKarma(project) // Add Jest addJest(project) <file_sep>/jest.js import shell from 'shelljs' import fs from "fs"; import {EOL} from 'os' function updateTestJs(project) { const newTestJs = [ "import 'jest-preset-angular/setup-jest';", "Object.defineProperty(window, 'CSS', {value: null});", "Object.defineProperty(document, 'doctype', {value: '<!DOCTYPE html>'});", "Object.defineProperty(document.body.style, 'transform', {value: () => {return {enumerable: true,configurable: true};}});", "Object.defineProperty(window, 'getComputedStyle', {value: () => {return {display: 'none', appearance: ['-webkit-appearance']};}});", EOL ].join(EOL) fs.writeFileSync(`./${project}/src/test.ts`, newTestJs) } function updateAngularJson(project) { const file = `./${project}/angular.json` const angularJson = JSON.parse(fs.readFileSync(file, 'utf-8')) const ngProject = angularJson.defaultProject delete angularJson.projects[ngProject].architect.test fs.writeFileSync(file, JSON.stringify(angularJson, null, ' ')) } function updatePackageJson(project) { const file = `./${project}/package.json` const packageJson = JSON.parse(fs.readFileSync(file, 'utf-8')) packageJson.scripts['test'] = 'jest' packageJson.scripts['test:watch'] = 'jest --watch' packageJson['jest'] = { "preset": "jest-preset-angular", "setupFilesAfterEnv": [ "<rootDir>/src/setupJest.ts" ] } fs.writeFileSync(file, JSON.stringify(packageJson, null, ' ')) } function addJestConfigJs(project) { const jestConfigJs = ` const { pathsToModuleNameMapper } = require('ts-jest/utils'); const { compilerOptions } = require('./tsconfig'); module.exports = { preset: 'jest-preset-angular', roots: ['<rootDir>/src/'], testMatch: ['**/+(*.)+(spec).+(ts)'], setupFilesAfterEnv: ['<rootDir>/src/test.ts'], collectCoverage: true, coverageReporters: ['html'], coverageDirectory: 'coverage/${project}', moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, { prefix: '<rootDir>/' }) }; ` fs.writeFileSync(`./${project}/jest.config.js`, jestConfigJs) } function addBlankSetupJestTs(project) { fs.writeFileSync(`./${project}/src/setupJest.ts`, EOL) } function updateTsconfig(project) { const tsconfigJson = fs.readFileSync(`./${project}/tsconfig.json`, 'utf-8').split(EOL).splice(1).join(EOL) fs.writeFileSync(`./${project}/tsconfig.json`, tsconfigJson) const tsconfigSpecText = fs.readFileSync(`./${project}/tsconfig.spec.json`, 'utf-8').split(EOL).splice(1).join(EOL) const tsconfigSpecJson = JSON.parse(tsconfigSpecText) tsconfigSpecJson.compilerOptions['types'] = ['jest', 'node'] tsconfigSpecJson.compilerOptions['esModuleInterop'] = true tsconfigSpecJson.compilerOptions['emitDecoratorMetadata'] = true fs.writeFileSync(`./${project}/tsconfig.spec.json`, JSON.stringify(tsconfigSpecJson, null, ' ')) } export default function addJest(project) { shell.exec(`cd ${project} && npm i jest jest-preset-angular @types/jest --save-dev`) updateTestJs(project) updateTsconfig(project) addJestConfigJs(project) updateAngularJson(project) updatePackageJson(project) addBlankSetupJestTs(project) }<file_sep>/karma.js import shell from "shelljs"; import fs from 'fs' export default function removeKarma(project) { // Remove Karma dependencies const packageJson = JSON.parse(fs.readFileSync(`./${project}/package.json`, 'utf-8')) const deps = [...Object.keys(packageJson.devDependencies), ...Object.keys(packageJson.dependencies)] const removableDeps = deps.filter(dep => dep.includes('karma') || dep.includes('jasmine')); shell.exec(`cd ${project} && npm uninstall ${removableDeps.join(' ')}`) // Remove Karma config file shell.rm(`./${project}/karma.conf.js`) }
48a7dc61811ae8105a1b980cdc0b918cbc4c8983
[ "Markdown", "JavaScript" ]
4
Markdown
cmxiv/ngjest
2e180668cbc0105787a6e8f130ff206cd25ebc4a
e097def5c1ad33e7080b6ad2a4dec753e195f037
refs/heads/master
<file_sep>// // Created by jinjun on 18-6-27. // #ifndef CPP_STUDY_SODIUM_STUDY_HPP #define CPP_STUDY_SODIUM_STUDY_HPP #include <iostream> #include <secp256k1.h> #include <boost/thread.hpp> #define SECP256K1_SK_BYTES 32 #define SECP256K1_MSG_BYTES 32 #define SECP256K1_PUB_KEY 33 class crypto_perf{ public: crypto_perf(); void run(); ~crypto_perf(); secp256k1_context *secp256k1_context1; private: void _test_sodium_signature(); // for secp void _test_secp256k1_sign_verify(); }; extern const size_t dataset_size; extern const size_t dataset_vector_size; extern const size_t iteration; extern uint8_t ** allocate_random_dataset(); extern void free_random_dataset(uint8_t ** dataset); extern boost::mutex a; #endif //CPP_STUDY_SODIUM_STUDY_HPP <file_sep>#pragma once #include <iostream> namespace display { using namespace std; template <class T> void displayNumbers(T data, int dataNumber) { // Display the numbers for (int i = 0; i < dataNumber; i++) { if (i == 0) { cout << "The numbers are: "; } cout<< data[i]; if (i == dataNumber - 1) { cout << endl; } else { cout << " "; } } return; } void displayTitle(string const& title); void printCharInHex(unsigned char*, size_t); } <file_sep>// // Created by jinjun on 18-6-29. // #ifndef CRYPTO_SELECTION_HASH_PERF_HPP #define CRYPTO_SELECTION_HASH_PERF_HPP extern "C" { #include "KangarooTwelve.h" #include "KeccakHash.h" }; #include <iostream> #include <boost/function.hpp> class hash_perf { public: hash_perf(); void run(); ~hash_perf(); private: uint8_t *_dataset; const size_t _dataset_size = 1024*1024; const size_t _k12_output_len = 256; const size_t _iteration = 1024; void _k12_perf(); // K12 Test void _sha256_perf(); void _sha3_perf(); std::map<std::string, boost::function<void(hash_perf*)>> _m; //function table //std::map<std::string, boost::function<void(hash_perf*)>> m; }; #endif //CRYPTO_SELECTION_HASH_PERF_HPP <file_sep>// // Created by jinjun on 18-6-27. // #include "crypto_perf.hpp" #include <iostream> #include <sodium.h> #include "display.hpp" #include <boost/shared_ptr.hpp> #include <vector> #include <chrono> #include <secp256k1.h> #include <openssl/conf.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include "ed25519_perf.hpp" using std::cout; using std::endl; using display::displayTitle; using display::printCharInHex; /* * The data set is 1000 random data, the data len is 32byte */ const size_t dataset_size = 1000; const size_t dataset_vector_size = 32; const size_t iteration = 1; boost::mutex a; // Test Sig performance // Generate the dataset, for avoiding the cache uint8_t ** allocate_random_dataset() { using namespace boost; auto **ret = new uint8_t* [dataset_size]; for (int i = 0; i < dataset_size; i++) { ret[i] = new uint8_t[dataset_vector_size]; // Generate the random data randombytes_buf(ret[i], dataset_vector_size); } return ret; } void free_random_dataset(uint8_t ** dataset) { for (int i = 0; i < dataset_size; i++) { delete(dataset[i]); } delete(dataset); } static uint8_t ** allocate_sig_msg_buf(size_t sign_bytes) { auto sig_ret = new uint8_t*[dataset_size]; for (int i= 0; i < dataset_size; i++) { sig_ret[i] = new uint8_t[sign_bytes + dataset_vector_size]; } return sig_ret; } /* * Try to understant libsodium lib. */ void crypto_perf::_test_sodium_signature() { const char *msg = "test"; u_int8_t sk[crypto_sign_SECRETKEYBYTES]; u_int8_t pk[crypto_sign_PUBLICKEYBYTES]; crypto_sign_keypair(pk, sk); u_int8_t sig[crypto_sign_BYTES + 4]; u_int64_t sig_msg_len = 0; crypto_sign(sig, (unsigned long long*)&sig_msg_len, (const unsigned char*)msg, 4, sk); u_int8_t unsig_msg[4]; u_int64_t unsig_msg_len= 0; if (crypto_sign_open(&unsig_msg[0], (unsigned long long*)&unsig_msg_len, sig, sig_msg_len, pk)) { cout<<"Msg mismatch"<<endl; } } static long perf_crypto_sign(uint8_t **dataset, uint8_t sk[crypto_sign_SECRETKEYBYTES], uint8_t** sig_ret) { //2. Prepare the pk and sk u_int64_t sig_msg_len = 0; // 4. Measure it auto start = std::chrono::steady_clock::now(); for(int i= 0; i < iteration; i++) { for(int data_vector_index = 0; data_vector_index < dataset_size; data_vector_index++) { auto dataset_vector = dataset[data_vector_index]; crypto_sign(sig_ret[data_vector_index], (unsigned long long*)&sig_msg_len, (const unsigned char*)dataset_vector, dataset_vector_size, sk); } } auto end = std::chrono::steady_clock::now(); auto duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); //x. free the data return duaration.count(); } static long perf_crypto_verify(uint8_t ** sig_msg, uint8_t pk[crypto_sign_PUBLICKEYBYTES]) { u_int8_t unsig_msg[dataset_vector_size]; u_int64_t unsig_msg_len= 0; auto start = std::chrono::steady_clock::now(); for(int i= 0; i < iteration; i++) { for (int data_vector_index = 0; data_vector_index < dataset_size; data_vector_index++) { if (crypto_sign_open(&unsig_msg[0], (unsigned long long *) &unsig_msg_len, sig_msg[data_vector_index], crypto_sign_BYTES + dataset_vector_size, pk)) { cout << "Msg mismatch" << endl; } } } auto end = std::chrono::steady_clock::now(); auto duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); return duaration.count(); } // Multithread sign and verification perf static void perf_sign_verify (int i) { auto dataset = allocate_random_dataset(); auto sig_ret = allocate_sig_msg_buf(crypto_sign_BYTES); u_int8_t sk[crypto_sign_SECRETKEYBYTES]; u_int8_t pk[crypto_sign_PUBLICKEYBYTES]; crypto_sign_keypair(pk, sk); auto sign_duration = perf_crypto_sign(dataset, sk, sig_ret); auto verify_duaration = perf_crypto_verify(sig_ret, pk); a.lock(); cout << "In thread "<< i<<endl; cout << "Signed " << iteration * dataset_size << " messages, used: " << sign_duration<< " milliseconds" << endl; cout << "Verified " << iteration * dataset_size << " messages, used: " << verify_duaration<< " milliseconds" << endl; a.unlock(); free_random_dataset(sig_ret); free_random_dataset(dataset); } static void multi_thread_sig_perf() { // Only 4 CPU in my CPU using boost::thread; std::vector<thread*> tv; for (int i = 0; i < boost::thread::hardware_concurrency(); i++) { tv.emplace_back(new thread(perf_sign_verify, i)); } for (auto t : tv) { t->join(); } } /* * Try to understand bitcoin's libsecp256k1 */ void crypto_perf::_test_secp256k1_sign_verify() { uint8_t sk[SECP256K1_SK_BYTES] = {1}; // you can set to any value secp256k1_ecdsa_signature sig; uint8_t msg_hash[SECP256K1_MSG_BYTES] = {0}; // Any value which the msg can generated uint8_t sig_out[SECP256K1_MSG_BYTES + 32 + 8]; size_t sig_out_len = sizeof(sig_out); secp256k1_pubkey pubkey; uint8_t pk[SECP256K1_PUB_KEY]; size_t pk_len = sizeof(pk); auto ret = secp256k1_ecdsa_sign(this->secp256k1_context1, &sig, &msg_hash[0], &sk[0], nullptr, nullptr ); assert(ret == 1); // Everything is at sig, get it from the sig ret = secp256k1_ecdsa_signature_serialize_der(this->secp256k1_context1, &sig_out[0], &sig_out_len, &sig); assert(ret == 1); // Generate pub key ret = secp256k1_ec_pubkey_create(this->secp256k1_context1, &pubkey, &sk[0]); assert(ret == 1); ret = secp256k1_ec_pubkey_serialize(this->secp256k1_context1, &pk[0], &pk_len, &pubkey, SECP256K1_EC_COMPRESSED); assert(ret == 1); // Parse the pubkey ret = secp256k1_ec_pubkey_parse(this->secp256k1_context1, &pubkey, &pk[0], pk_len); assert(ret == 1); ret = secp256k1_ecdsa_signature_parse_der(this->secp256k1_context1, &sig, &sig_out[0], sig_out_len); assert(ret == 1); ret = secp256k1_ecdsa_verify(this->secp256k1_context1, &sig, &msg_hash[0], &pubkey); assert(ret == 1); } // The secp256 part long perf_secp256k1_sign(crypto_perf* sec, uint8_t **dataset, uint8_t sk[SECP256K1_SK_BYTES], uint8_t** sig_ret) { secp256k1_ecdsa_signature sig; size_t sig_out_len = 72; auto start = std::chrono::steady_clock::now(); for(int i= 0; i < iteration; i++) { for (int data_vector_index = 0; data_vector_index < dataset_size; data_vector_index++) { secp256k1_ecdsa_signature sig; auto ret = secp256k1_ecdsa_sign(sec->secp256k1_context1, &sig, dataset[data_vector_index], &sk[0], nullptr, nullptr ); assert(ret == 1); // Everything is at sig, get it from the sig sig_out_len = 72; ret = secp256k1_ecdsa_signature_serialize_der(sec->secp256k1_context1, sig_ret[data_vector_index], &sig_out_len, &sig); sig_ret[data_vector_index][71] = (char)sig_out_len; assert(ret == 1); } } auto end = std::chrono::steady_clock::now(); auto duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); return duaration.count(); } long perf_secp256k1_verify(crypto_perf* sec, uint8_t **sig_msg, uint8_t **dataset, uint8_t *sk) { size_t sig_out_len = 72; secp256k1_pubkey pubkey; // Generate pub key auto ret = secp256k1_ec_pubkey_create(sec->secp256k1_context1, &pubkey, &sk[0]); assert(ret == 1); auto start = std::chrono::steady_clock::now(); for(int i= 0; i < iteration; i++) { for (int data_vector_index = 0; data_vector_index < dataset_size; data_vector_index++) { secp256k1_ecdsa_signature sig; sig_out_len = sig_msg[data_vector_index][71]; ret = secp256k1_ecdsa_signature_parse_der(sec->secp256k1_context1, &sig, sig_msg[data_vector_index], sig_out_len); assert(ret == 1); ret = secp256k1_ecdsa_verify(sec->secp256k1_context1, &sig, dataset[data_vector_index], &pubkey); assert(ret == 1); } } auto end = std::chrono::steady_clock::now(); auto duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); return duaration.count(); } void secp256k1_perf_sign_verify (crypto_perf* sec, int i) { auto dataset = allocate_random_dataset(); auto secp256k1_sig_out = allocate_sig_msg_buf(40); u_int8_t sk[SECP256K1_SK_BYTES] = {1}; auto sign_duration = perf_secp256k1_sign(sec, dataset, sk, secp256k1_sig_out); auto verify_duaration = perf_secp256k1_verify(sec, secp256k1_sig_out, dataset, sk); a.lock(); cout << "In thread "<< i<<endl; cout << "Signed " << iteration * dataset_size << " messages, used: " << sign_duration<< " milliseconds" << endl; cout << "Verified " << iteration * dataset_size << " messages, used: " << verify_duaration<< " milliseconds" << endl; a.unlock(); free_random_dataset(secp256k1_sig_out); free_random_dataset(dataset); } void multi_thread_secp256k1_perf(crypto_perf* sec) { // Only 4 CPU in my CPU using boost::thread; std::vector<thread*> tv; for (int i = 0; i < boost::thread::hardware_concurrency(); i++) { tv.emplace_back(new thread(secp256k1_perf_sign_verify, sec, i)); } for (auto t : tv) { t->join(); } } // RSA part static EVP_PKEY* rsa_generate_keypair() { EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr); assert(ctx != nullptr); auto ret = EVP_PKEY_keygen_init(ctx); assert(ret == 1); ret = EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048); assert(ret == 1); EVP_PKEY *ppkey = nullptr; ret = EVP_PKEY_keygen(ctx, &ppkey); assert(ret == 1); assert(ppkey != nullptr); return ppkey; } static void rsa_free_keypair(EVP_PKEY* ppkey) { EVP_PKEY_free(ppkey); } static void rsa_sign(const char*msg, size_t msglen, uint8_t *sig_ret, uint32_t *sig_ret_len, EVP_PKEY *ppkey) { EVP_MD_CTX *mctx = nullptr; size_t siglen = 0; mctx = EVP_MD_CTX_create(); assert(mctx != nullptr); auto ret = EVP_DigestSignInit(mctx, nullptr, EVP_sha256(), nullptr, ppkey); assert(ret == 1); ret = EVP_DigestSignUpdate(mctx, msg, msglen); assert(ret == 1); ret = EVP_DigestSignFinal(mctx, nullptr, &siglen); assert(ret == 1); assert(siglen <= *sig_ret_len); ret = EVP_DigestSignFinal(mctx, sig_ret, &siglen); assert(ret == 1); *sig_ret_len = (uint32_t)siglen; EVP_MD_CTX_destroy(mctx); } static void rsa_verify(const char*msg, size_t msglen, uint8_t *sig_ret, uint32_t sig_ret_len, EVP_PKEY *ppkey) { EVP_MD_CTX *mctx = nullptr; mctx = EVP_MD_CTX_create(); assert(mctx != nullptr); auto ret = EVP_DigestVerifyInit(mctx, nullptr, EVP_sha256(), nullptr, ppkey); assert(ret == 1); ret = EVP_DigestSignUpdate(mctx, msg, msglen); assert(ret == 1); ret = EVP_DigestVerifyFinal(mctx, sig_ret, sig_ret_len); assert(ret == 1); EVP_MD_CTX_destroy(mctx); } static void rsa_sign_verify() { // 1 generate a key EVP_PKEY *ppkey= rsa_generate_keypair(); const char *msg = "Hello, Infiniblock!"; uint8_t sig_ret[512] = {0}; uint32_t sig_len = sizeof(sig_ret); rsa_sign(msg, strlen(msg), &sig_ret[0], &sig_len, ppkey); rsa_verify(msg, strlen(msg), &sig_ret[0], sig_len, ppkey); rsa_free_keypair(ppkey); } // RSA Perf Test long perf_rsa_sign(uint8_t **sig, uint8_t **dataset, EVP_PKEY *ppkey) { size_t sig_out_len = 512; // It's a big problem auto start = std::chrono::steady_clock::now(); for(int i= 0; i < iteration; i++) { for (int data_vector_index = 0; data_vector_index < dataset_size; data_vector_index++) { rsa_sign((const char*)dataset[data_vector_index], 32, sig[data_vector_index], (uint32_t*)&sig_out_len, ppkey); // the sig out len , should be 256, fixed value } } auto end = std::chrono::steady_clock::now(); auto duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); return duaration.count(); } long perf_rsa_verify(uint8_t **sig, uint8_t **dataset, EVP_PKEY *ppkey) { auto start = std::chrono::steady_clock::now(); for(int i= 0; i < iteration; i++) { for (int data_vector_index = 0; data_vector_index < dataset_size; data_vector_index++) { rsa_verify((const char*)dataset[data_vector_index], 32, sig[data_vector_index], 256, ppkey); // the sig out len , should be 256, fixed value } } auto end = std::chrono::steady_clock::now(); auto duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); return duaration.count(); } static void rsa_perf_sign_verify (int i) { auto dataset = allocate_random_dataset(); auto rsa_sig_ret = allocate_sig_msg_buf(512-dataset_vector_size); EVP_PKEY *ppkey= rsa_generate_keypair(); auto sign_duaration = perf_rsa_sign(rsa_sig_ret, dataset, ppkey); auto verify_duaration = perf_rsa_verify(rsa_sig_ret, dataset, ppkey); a.lock(); cout << "In thread "<< i<<endl; cout << "Signed " << iteration * dataset_size << " messages, used: " << sign_duaration<< " milliseconds" << endl; cout << "Verified " << iteration * dataset_size << " messages, used: " << verify_duaration<< " milliseconds" << endl; a.unlock(); free_random_dataset(rsa_sig_ret); free_random_dataset(dataset); } void multi_thread_rsa_perf() { // Only 4 CPU in my CPU using boost::thread; std::vector<thread*> tv; for (int i = 0; i < boost::thread::hardware_concurrency(); i++) { tv.emplace_back(new thread(rsa_perf_sign_verify, i)); } for (auto t : tv) { t->join(); } } // amd-64-24k implementation perf void multi_thread_ed25519_perf() { // Only 4 CPU in my CPU using boost::thread; std::vector<thread*> tv; for (int i = 0; i < boost::thread::hardware_concurrency(); i++) { tv.emplace_back(new thread(ed25519_perf_thread, i)); } for (auto t : tv) { t->join(); } } void crypto_perf::run(){ u_int8_t sk[crypto_sign_SECRETKEYBYTES]; u_int8_t pk[crypto_sign_PUBLICKEYBYTES]; auto dataset = allocate_random_dataset(); displayTitle("Secp256K1(bitcoin) Basic Test"); this->_test_secp256k1_sign_verify(); cout<<"Success" << endl; displayTitle("secp256k1(bitcoin) Perf Test"); auto secp256k1_sig_out = allocate_sig_msg_buf(40); auto sign_duration = perf_secp256k1_sign(this, dataset, sk, secp256k1_sig_out); cout << "Signed " << iteration * dataset_size << " messages, used: " << sign_duration<< " milliseconds" << endl; sign_duration = perf_secp256k1_verify(this, secp256k1_sig_out, dataset, sk); cout << "Verified " << iteration * dataset_size << " messages, used: " << sign_duration<< " milliseconds" << endl; displayTitle("Multi Thread Perf for SECP256K1(bitcoin)"); multi_thread_secp256k1_perf(this); free_random_dataset(secp256k1_sig_out); displayTitle("RSA(openssl) Basic Test"); rsa_sign_verify(); cout<<"Success"<<endl; // If failed, the code will be coredumped due to assert displayTitle("RSA(openssl) Perf Test"); auto rsa_sig_ret = allocate_sig_msg_buf(512-dataset_vector_size); EVP_PKEY *ppkey= rsa_generate_keypair(); sign_duration = perf_rsa_sign(rsa_sig_ret, dataset, ppkey); cout << "Signed " << iteration * dataset_size << " messages, used: " << sign_duration<< " milliseconds" << endl; sign_duration = perf_rsa_verify(rsa_sig_ret, dataset, ppkey); cout << "Signed " << iteration * dataset_size << " messages, used: " << sign_duration<< " milliseconds" << endl; displayTitle("Multi Thread Perf for RSA(openssl)"); multi_thread_rsa_perf(); rsa_free_keypair(ppkey); free_random_dataset(rsa_sig_ret); displayTitle("ED25519(naci) Basic Test"); ed25519_basic_test(); displayTitle("ED25519(naci) Perf Test"); long sign_d = 0; long verify_d = 0; ed25519_perf_test(dataset, &sign_d, &verify_d); cout << "Signed " << iteration * dataset_size << " messages, used: " <<sign_d<< " milliseconds" << endl; cout << "Signed " << iteration * dataset_size << " messages, used: " <<verify_d<< " milliseconds" << endl; displayTitle("Multi Thread Perf for ED25519(naci)"); multi_thread_ed25519_perf(); displayTitle("ED22519(sodium) Perf Test"); //1. Generate the dataset auto sig_ret = allocate_sig_msg_buf(crypto_sign_BYTES); crypto_sign_keypair(pk, sk); sign_duration = perf_crypto_sign(dataset, sk, sig_ret); cout << "Signed " << iteration * dataset_size << " messages, used: " << sign_duration<< " milliseconds" << endl; auto verify_duaration = perf_crypto_verify(sig_ret, pk); cout << "Verified " << iteration * dataset_size << " messages, used: " << verify_duaration<< " milliseconds" << endl; free_random_dataset(sig_ret); displayTitle("Multi Thread Perf for ED25519(sodium)"); multi_thread_sig_perf(); free_random_dataset(dataset); } crypto_perf::crypto_perf() { auto ret = sodium_init(); assert(ret == 0); this->secp256k1_context1 = secp256k1_context_create(SECP256K1_CONTEXT_SIGN|SECP256K1_CONTEXT_VERIFY); assert(this->secp256k1_context1); // Rsa part ERR_load_crypto_strings(); OPENSSL_add_all_algorithms_conf(); OPENSSL_config(nullptr); } crypto_perf::~crypto_perf() { secp256k1_context_destroy(this->secp256k1_context1); //rsa part EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); ERR_free_strings(); }<file_sep>#include <iostream> #include "crypto_perf.hpp" #include "hash_perf.hpp" #include "compress_perf.hpp" #include <boost/program_options.hpp> int main(int argc, char ** argv) { boost::program_options::options_description desc("Crypto/Hash"); desc.add_options() ("crypto", "Do crypto benchmark") ("compress", "Do compress benchmark") ("hash", "Do hash benchmark"); boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); boost::program_options::notify(vm); if (vm.count("crypto")) { auto cp = crypto_perf(); cp.run(); } if (vm.count("hash")) { auto hp = hash_perf(); hp.run(); } if (vm.count("compress")) { compress_perf().run(); } return 0; }<file_sep>// // Created by jinjun on 18-5-30. // #include "display.hpp" #include <iostream> #include <cassert> #include <boost/format.hpp> namespace display { const int HeaderLength = 80; using namespace std; using boost::format; void displayTitle(string const& title) { // Calculate the total length assert(title.length() <= HeaderLength); long left_label_number = (HeaderLength - title.length()) / 2; long right_label_number = HeaderLength - title.length() - left_label_number; assert(right_label_number >= 0); string header; for (int i= 0; i < left_label_number; i ++) { header.append("="); } header.append(title); for (int i= 0; i < right_label_number; i ++) { header.append("="); } cout << header << endl; } void printCharInHex(unsigned char* data, size_t len) { cout<<"0x"; for (int i=0; i < len; i++ ) { cout<<format("%02x")%(unsigned int)data[len-i-1]; } return; } } <file_sep>// // Created by jinjun on 18-7-1. // #include "compress_perf.hpp" #include "lz4.h" #include "crypto_perf.hpp" #include <chrono> #include <ed25519/ed25519.h> #include "display.hpp" #include "snappy.h" compress_perf::compress_perf() { // Allocate the dataset _dataset = allocate_random_dataset(); _dataset_vector_size = dataset_vector_size; _dataset_size = dataset_size; _sig_array = new signature_t[dataset_size]; _iteration = 1; _dataset_size = 1; public_key_t pubkey; private_key_t prikey; // Create a keypair auto ret = ed25519_create_keypair(&prikey, &pubkey); // Generate the ED25519 hash for (int data_vector_index = 0; data_vector_index < _dataset_size; data_vector_index++) { ed25519_sign(&_sig_array[data_vector_index], _dataset[data_vector_index], 32, &pubkey, &prikey); //memcpy(&(_sig_array[data_vector_index].data)[0], "Hello, this is from infiniBlock, please leave your name here", ed25519_signature_SIZE); //memset(&(_sig_array[data_vector_index].data)[0], 0, ed25519_signature_SIZE); //auto s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; //memcpy(&(_sig_array[data_vector_index].data)[0], s, strlen(s)); } // Register the compress functions boost::function<int (compress_perf*)> lz4 = &compress_perf::_lz4_perf; boost::function<int (compress_perf*)> zstd = &compress_perf::_zstd_perf; boost::function<int (compress_perf*)> snappy = &compress_perf::_snappy_perf; _m["LZ4"] = lz4; _m["ZSTD"] = zstd; _m["SNAPPY"] = snappy; } compress_perf::~compress_perf() { free_random_dataset(_dataset); free(_sig_array); } void compress_perf::run() { uint64_t total = 0; for (auto const &func : _m) { total = 0; std::cout<<func.first<<": "; auto start = std::chrono::steady_clock::now(); for(int i= 0; i < _iteration; i++) { total += func.second(this); } auto end = std::chrono::steady_clock::now(); auto duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); std::cout<<"Ratio:" << ((double)total)/(_iteration * _dataset_size * sizeof(signature_t)) << std::endl; std::cout<<"Compress " << (_dataset_size * _iteration * sizeof(signature_t)) / (1024 * 1024) << "M bytes data, used:" << duaration.count() << " milliseconds" << std::endl; } } int compress_perf::_lz4_perf() { char dst[2 * ed25519_signature_SIZE] = {0}; int total = 0; int dst_size = LZ4_compressBound(ed25519_signature_SIZE); for (int data_vector_index = 0; data_vector_index < _dataset_size; data_vector_index++) { total += LZ4_compress_default((const char*)&(_sig_array[data_vector_index].data)[0], &dst[0], ed25519_signature_SIZE, 2*ed25519_signature_SIZE); } return total; } int compress_perf::_zstd_perf() { // ? return 0; } int compress_perf::_snappy_perf() { char dst[2 * ed25519_signature_SIZE] = {0}; int total = 0; size_t dst_size = 0; for (int data_vector_index = 0; data_vector_index < _dataset_size; data_vector_index++) { snappy::RawCompress((const char*)&(_sig_array[data_vector_index].data)[0], ed25519_signature_SIZE, &dst[0], &dst_size); total += dst_size; } return total; }<file_sep>// // Created by jinjun on 18-7-1. // #ifndef CRYPTO_SELECTION_COMPRESS_PERF_HPP #define CRYPTO_SELECTION_COMPRESS_PERF_HPP #include <iostream> #include <boost/function.hpp> #include <ed25519/ed25519.h> class compress_perf { public: compress_perf(); void run(); ~compress_perf(); private: uint8_t **_dataset; size_t _dataset_vector_size; size_t _dataset_size; size_t _iteration; signature_t *_sig_array; int _lz4_perf(); // K12 Test int _snappy_perf(); int _zstd_perf(); std::map<std::string, boost::function<int (compress_perf*)>> _m; }; #endif //CRYPTO_SELECTION_COMPRESS_PERF_HPP <file_sep>cmake_minimum_required(VERSION 3.10) project(crypto_selection) set(CMAKE_CXX_STANDARD 11) include_directories( ${CMAKE_SOURCE_DIR}/include /home/jinjun/opt/boost/include /home/jinjun/opt/SandyBridge/libkeccak.a.headers) # Please specify this part link_directories(/home/jinjun/opt/boost/lib) find_library(SODIUM libsodium.a) # Use the static link, instead of dynamic link find_library(SECP256K1 libsecp256k1.a) find_library(GMP libgmp.a) find_library(KECCAK NAME keccak HINTS /home/jinjun/opt/SandyBridge/) #add_library(keccak ${keccak_SRC}) #file(GLOB keccak_SRC "keccak/*.c" "keccak/*.h" "keccak/*.inc" "keccak/*.macros") add_library(display src/display.cpp include/display.hpp) add_library(crypto_perf src/crypto_perf.cpp src/ed25519_perf.cpp include/crypto_perf.hpp include/ed25519_perf.hpp) add_library(hash_perf src/hash_perf.cpp include/hash_perf.hpp) add_library(compress_perf src/compress_perf.cpp include/compress_perf.hpp) add_executable(crypto_selection main.cpp) target_link_libraries(crypto_selection crypto_perf display hash_perf compress_perf ${KECCAK} ${SODIUM} ${SECP256K1} ${GMP} ed25519 boost_system boost_thread pthread crypto boost_program_options lz4 snappy) <file_sep>// // Created by jinjun on 18-6-29. // #ifndef CRYPTO_SELECTION_ED25519_PERF_HPP #define CRYPTO_SELECTION_ED25519_PERF_HPP extern void ed25519_basic_test(); extern void ed25519_perf_test(uint8_t **dataset, long *sign_duaration, long* verify_duaration); extern void ed25519_perf_thread(int i); #endif //CRYPTO_SELECTION_ED25519_PERF_HPP <file_sep>// // Created by jinjun on 18-6-29. // #include <iostream> #include <cassert> #include <ed25519/ed25519.h> #include <chrono> #include "crypto_perf.hpp" #include <boost/shared_ptr.hpp> using namespace std; void ed25519_basic_test() { public_key_t pubkey; private_key_t prikey; signature_t sig; // Create a keypair auto ret = ed25519_create_keypair(&prikey, &pubkey); assert(ret != 0); uint8_t msg[32] = {0}; ed25519_sign(&sig, msg, 32, &pubkey, &prikey); ret = ed25519_verify(&sig, msg, 32, &pubkey); assert(ret == 1); } void ed25519_perf_test(uint8_t **dataset, long *sign_duaration, long* verify_duaration) { public_key_t pubkey; private_key_t prikey; signature_t sig; // Create a keypair auto ret = ed25519_create_keypair(&prikey, &pubkey); assert(ret != 0); // Create sig boost::shared_ptr<signature_t[]> sigarray(new signature_t[dataset_size]); auto start = std::chrono::steady_clock::now(); for(int i= 0; i < iteration; i++) { for (int data_vector_index = 0; data_vector_index < dataset_size; data_vector_index++) { ed25519_sign(&sigarray[data_vector_index], dataset[data_vector_index], 32, &pubkey, &prikey); } } auto end = std::chrono::steady_clock::now(); auto duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); *sign_duaration = duaration.count(); start = std::chrono::steady_clock::now(); for(int i= 0; i < iteration; i++) { for (int data_vector_index = 0; data_vector_index < dataset_size; data_vector_index++) { ret = ed25519_verify(&sigarray[data_vector_index], dataset[data_vector_index], 32, &pubkey); assert(ret == 1); } } end = std::chrono::steady_clock::now(); duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); *verify_duaration = duaration.count(); } void ed25519_perf_thread(int i) { auto dataset = allocate_random_dataset(); long sign_duaration = 0; long verify_duaration = 0; ed25519_perf_test(dataset, &sign_duaration, &verify_duaration); a.lock(); cout << "In thread "<< i<<endl; cout << "Signed " << iteration * dataset_size << " messages, used: " << sign_duaration<< " milliseconds" << endl; cout << "Verified " << iteration * dataset_size << " messages, used: " << verify_duaration<< " milliseconds" << endl; a.unlock(); free_random_dataset(dataset); } <file_sep># crypto_benchmark Crypto Benchmark for Signature and Hash # Test setup The following libs are evaluated: - [libsodium](https://github.com/jedisct1/libsodium) - [libsecp256k1](https://github.com/bitcoin-core/secp256k1) - [ed25519](https://github.com/hyperledger/iroha-ed25519) - [openssl](https://www.openssl.org/) - [KCP](https://keccak.team/) The reason we evaluate ed25519 is that, in theory ED25519 can be optimized to high perf implementation. Foe details, please see this [paper](https://ed25519.cr.yp.to/ed25519-20110926.pdf). KCP contains the latest HASH implementations, such as K12 and SHA3, They are candidates for Infiniblock. # Test Environment ```apple js jinjun@jinjun-virtual-machine:~/ws/crypto_benchmark/cmake-build-debug$ cat /proc/cpuinfo processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 94 model name : Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz stepping : 3 microcode : 0x33 cpu MHz : 2592.080 cache size : 6144 KB physical id : 0 siblings : 1 core id : 0 cpu cores : 1 apicid : 0 initial apicid : 0 fpu : yes fpu_exception : yes cpuid level : 22 wp : yes ``` # Test Results ```apple js =========================Secp256K1(bitcoin) Basic Test========================== Success ==========================secp256k1(bitcoin) Perf Test========================== Signed 1000 messages, used: 58 milliseconds Verified 1000 messages, used: 77 milliseconds ====================Multi Thread Perf for SECP256K1(bitcoin)==================== In thread 0 Signed 1000 messages, used: 52 milliseconds Verified 1000 messages, used: 74 milliseconds In thread 3 Signed 1000 messages, used: 53 milliseconds Verified 1000 messages, used: 72 milliseconds In thread 1 Signed 1000 messages, used: 66 milliseconds Verified 1000 messages, used: 84 milliseconds In thread 2 Signed 1000 messages, used: 78 milliseconds Verified 1000 messages, used: 89 milliseconds ============================RSA(openssl) Basic Test============================= Success =============================RSA(openssl) Perf Test============================= Signed 1000 messages, used: 676 milliseconds Signed 1000 messages, used: 22 milliseconds =======================Multi Thread Perf for RSA(openssl)======================= In thread 3 Signed 1000 messages, used: 765 milliseconds Verified 1000 messages, used: 21 milliseconds In thread 1 Signed 1000 messages, used: 759 milliseconds Verified 1000 messages, used: 25 milliseconds In thread 2 Signed 1000 messages, used: 728 milliseconds Verified 1000 messages, used: 23 milliseconds In thread 0 Signed 1000 messages, used: 734 milliseconds Verified 1000 messages, used: 21 milliseconds ============================ED25519(naci) Basic Test============================ ============================ED25519(naci) Perf Test============================= Signed 1000 messages, used: 21 milliseconds Signed 1000 messages, used: 60 milliseconds ======================Multi Thread Perf for ED25519(naci)======================= In thread 0 Signed 1000 messages, used: 22 milliseconds Verified 1000 messages, used: 60 milliseconds In thread 1 Signed 1000 messages, used: 20 milliseconds Verified 1000 messages, used: 67 milliseconds In thread 3 Signed 1000 messages, used: 23 milliseconds Verified 1000 messages, used: 77 milliseconds In thread 2 Signed 1000 messages, used: 21 milliseconds Verified 1000 messages, used: 89 milliseconds ===========================ED22519(sodium) Perf Test============================ Signed 1000 messages, used: 33 milliseconds Verified 1000 messages, used: 73 milliseconds =====================Multi Thread Perf for ED25519(sodium)====================== In thread 0 Signed 1000 messages, used: 27 milliseconds Verified 1000 messages, used: 81 milliseconds In thread 1 Signed 1000 messages, used: 36 milliseconds Verified 1000 messages, used: 76 milliseconds In thread 2 Signed 1000 messages, used: 35 milliseconds Verified 1000 messages, used: 78 milliseconds In thread 3 Signed 1000 messages, used: 41 milliseconds Verified 1000 messages, used: 76 milliseconds K12: Hash 1024M bytes data, used:955 milliseconds SHA256: Hash 1024M bytes data, used:2674 milliseconds SHA3: Hash 1024M bytes data, used:434 milliseconds LZ4: Ratio:1.03125 Compress 0M bytes data, used:0 milliseconds SNAPPY: Ratio:1.04688 Compress 0M bytes data, used:0 milliseconds ZSTD: Ratio:0 Compress 0M bytes data, used:0 milliseconds ``` # Conclusion As the results show, we will use the **ED25519** as Infiniblock sign/verify algorithm, use the **SHA3** as the hash algorithm. As to compress, since current compress algorithm are uesless to signature, which is the main part of the transaction, do we really need compress? The answer is NO!<file_sep>// // Created by jinjun on 18-6-29. // #include <cstdint> #include <hash_perf.hpp> #include <chrono> #include "openssl/sha.h" hash_perf::hash_perf() { _dataset = new uint8_t[_dataset_size]; boost::function<void (hash_perf*)> k12 = &hash_perf::_k12_perf; boost::function<void (hash_perf*)> sha256 = &hash_perf::_sha256_perf; boost::function<void (hash_perf*)> sha3 = &hash_perf::_sha3_perf; _m["K12"] = k12; _m["SHA256"] = sha256; _m["SHA3"] = sha3; } hash_perf::~hash_perf() { delete _dataset; } void hash_perf::run() { for (auto const &func : _m) { std::cout<<func.first<<": "; auto start = std::chrono::steady_clock::now(); for(int i= 0; i < _iteration; i++) { func.second(this); } auto end = std::chrono::steady_clock::now(); auto duaration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start); std::cout<<"Hash " << (_dataset_size * _iteration) / (1024 * 1024) << "M bytes data, used:" << duaration.count() << " milliseconds" << std::endl; } } void hash_perf::_k12_perf() { const char *customization = "InfiniBlock"; size_t cus_len = strlen(customization); uint8_t output[_k12_output_len] = {0}; auto ret = KangarooTwelve(_dataset, _dataset_size, &output[0], _k12_output_len, (const uint8_t*)customization, cus_len); assert(ret ==0 ); } void hash_perf::_sha256_perf() { uint8_t output[SHA256_DIGEST_LENGTH] = {0}; SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, _dataset, _dataset_size); SHA256_Final(output, &ctx); } void hash_perf::_sha3_perf() { Keccak_HashInstance sha3; uint8_t output[32] = {0}; Keccak_HashInitialize_SHA3_256(&sha3); Keccak_HashUpdate(&sha3, _dataset, _dataset_size); Keccak_HashFinal(&sha3, &output[0]); }
393f312831539164323c0b8ff654eef5207bf92a
[ "Markdown", "CMake", "C++" ]
13
C++
infiniblock/crypto_benchmark
941f7b396a419bf2b8bf92a7fcc3fd7d0444bc68
1bed42f29a6ab16edcd12a970af8dba1ff5bd24d
refs/heads/main
<repo_name>nehasharma19920/NoteTracker<file_sep>/src/main/java/com/entities/Note.java package com.entities; import java.util.Date; import java.util.Random; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "note") public class Note { @Id private Integer id; @Column(name = "content" ,length = 1500) private String content; @Column(name = "tittle") private String tittle; @Column(name = "date") private Date addedDate; public Note(String tittle, String content, Date addedDate) { super(); this.id = new Random().nextInt(10000); this.content = content; this.tittle = tittle; this.addedDate = addedDate; } public Note() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTittle() { return tittle; } public void setTittle(String tittle) { this.tittle = tittle; } public Date getAddedDate() { return addedDate; } public void setAddedDate(Date addedDate) { this.addedDate = addedDate; } @Override public String toString() { // TODO Auto-generated method stub return "id" +id + "tittle"+tittle +"content"+content; } } <file_sep>/src/main/java/com/servlets/SaveNotesServlet.java package com.servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import org.hibernate.Transaction; import com.entities.Note; import com.helper.FactoryProvider; public class SaveNotesServlet extends HttpServlet { private static final long serialVersionUID = 1L; public SaveNotesServlet() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String tittle = request.getParameter("tittle"); String content = request.getParameter("content"); Note note = new Note(tittle, content, new Date()); System.out.println(note); Session session = FactoryProvider.getFactory().openSession(); Transaction tx = session.beginTransaction(); session.save(note); tx.commit(); session.close(); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<h1 style = 'text-align:center;'>Note added successfully</h1>"); writer.println("<h1 style = 'text-align:center;'><a href='view_all_notes.jsp'>View all notes</a></h1>"); writer.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } }
130e536cdf2389ba572e1da663b0b575f79791cc
[ "Java" ]
2
Java
nehasharma19920/NoteTracker
0f5db9a4d49dca559e67a3b1d02268b4e1050ba3
1f1c9b810b2205816586ffd2a3103232ab39ab74
refs/heads/master
<file_sep>package com.jrsimo.daw; public class BinString { public BinString(){} public String convetir(String s){ return aBinario(sumar(s)); } public int sumar(String s) { String s1= s.substring(0); int sum= 0; while(!s1.equals("")) { sum = sum +(int)(s1.charAt(0)); s1= s1.substring(1); } return sum; } public String aBinario(int n){ String s=""; while (n > 0){ if(n%2==0) s = "0"+s; else s= "1"+s; n= n/2; } return s; } } <file_sep>package JUNIT; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class CalculadoraTest { Calculadora cal1; @Before public void antesDelTest() { cal1 = new Calculadora(); System.out.println("Reinicinando calculadora....."); } @Test public void sumartest(){ float resultado=cal1.sumar(2, 4); System.out.println("2 + 4 = "+ cal1.sumar(2,4)); assertEquals("Metodo sumarTest",6.0, resultado, 0); } @Test public void restatest(){ float resultado=cal1.restar(2, 4); System.out.println("2 + 4 = "+ cal1.restar(2,4)); assertEquals("Metodo restarTest",6.0, resultado, 0); } @Test public void multiplicartest(){ float resultado=cal1.multiplicar(2, 4); System.out.println("2 + 4 = "+ cal1.multiplicar(2,4)); assertEquals("Metodo restarTest",6.0, resultado, 0); } @Test public void dividirtest(){ float resultado=cal1.dividir(2, 4); System.out.println("2 + 4 = "+ cal1.dividir(2,4)); assertEquals("Metodo restarTest",6.0, resultado, 0); } } <file_sep>package JUNIT; public class CalculadoraDemo { public static void main(String[] args) { Calculadora cal = new Calculadora(); System.out.println("2 + 4 = "+ cal.sumar(2,4)); System.out.println("2 + 4 = "+ cal.restar(2,4)); System.out.println("2 + 4 = "+ cal.multiplicar(2,4)); System.out.println("2 + 4 = "+ cal.dividir(2,4)); System.out.println(); } } <file_sep># PracticasDaw Ejercicios de clase <file_sep>import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class LineTest { double delta = 0.001; Line theLine; double x0=1,x1=3,y0=2,y1=4; @Before public void setUp() { theLine= new Line(1,2,3,4); } // claculate de slo`pe of the line@Test public void testgetSlope(){ double valorReal =theLine.getSlope(); double valorEsperado = (4 - 2) / (3 - 1); assertEquals(valorEsperado, valorReal,delta); } @Test public void testgetDistance(){ double valorReal = theLine.getDistance(); double valorEsperado = Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)); assertEquals(valorEsperado, valorReal,delta); } @Test public void testparallelTo(){ Line theLine2; theLine2 = new Line(1,2,3,4); boolean valorReal = theLine.parallelTo(theLine2); assertTrue(valorReal); } }
049d38f4ab5d2f4f27779b0cd057533ef5e06b8b
[ "Markdown", "Java" ]
5
Java
dapaslan/PracticasDaw
ea4347696c29f26daaf117dab07e92bfd9244e25
f8a4717bf0b67a1e8cc523efff696142d11b178b
refs/heads/master
<file_sep>/** * */ package com.application.util.multithreading.example; /** * @author Administrator * */ public class testThread { /** * */ public testThread() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } } <file_sep>/** * */ package com.application.controller; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * @author Administrator * 注册登录 */ @Controller public class LoginController { @RequestMapping("/login" ) public String doLogin(Map<String,Object> model) { return "system/login"; } @RequestMapping("/dashboard" ) public String doSupervise(Map<String,Object> model) { return "system/dashboard_1"; } @RequestMapping(value="/doLogout") public String doLogout(@RequestParam("/login") Model model) { return "logout_success"; } } <file_sep>package com.application.dao; import org.springframework.stereotype.Repository; @Repository public class UserAuthorizationDao { //int deleteByPrimaryKey(String id); //int insert(UserAuthorization record); //UserAuthorization selectByPrimaryKey(String id); //List<UserAuthorization> selectAll(); //int updateByPrimaryKey(UserAuthorization record); }<file_sep>package com.application.dao; import org.springframework.stereotype.Repository; @Repository public class SettingsDao { //int deleteByPrimaryKey(String id); //int insert(Settings record); //List<Settings> selectAll(); }<file_sep>package com.application.model; public class UserGroupRelatedRole { private String id; private String usergroupid; private String roleid; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getUsergroupid() { return usergroupid; } public void setUsergroupid(String usergroupid) { this.usergroupid = usergroupid == null ? null : usergroupid.trim(); } public String getRoleid() { return roleid; } public void setRoleid(String roleid) { this.roleid = roleid == null ? null : roleid.trim(); } }<file_sep>/** * */ package com.application.controller; import org.springframework.stereotype.Controller; /** * @author Administrator * 资料管理 */ @Controller public class DatumController { } <file_sep>package com.application.dao; import org.springframework.stereotype.Repository; @Repository public class UserGroupDao { //int deleteByPrimaryKey(String id); //int insert(UserGroup record); //UserGroup selectByPrimaryKey(String id); //List<UserGroup> selectAll(); //int updateByPrimaryKey(UserGroup record); }<file_sep>package com.application.model; public class UserRelatedRole { private byte[] id; private byte[] userid; private byte[] roleid; public byte[] getId() { return id; } public void setId(byte[] id) { this.id = id; } public byte[] getUserid() { return userid; } public void setUserid(byte[] userid) { this.userid = userid; } public byte[] getRoleid() { return roleid; } public void setRoleid(byte[] roleid) { this.roleid = roleid; } }<file_sep>/** * */ package com.application.service; import org.springframework.stereotype.Service; /** * @author Administrator * 注册登录 */ @Service public interface ILoginService { } <file_sep>package com.application.model; public class User { private String id; private String roleid; private String username; private String phone; private String email; private String qusetion; private String anwser; private String usergroupid; private String registertime; private String registerip; private String logintime; private String loginip; private String status; private String isonline; private String isenabled; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getRoleid() { return roleid; } public void setRoleid(String roleid) { this.roleid = roleid == null ? null : roleid.trim(); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getQusetion() { return qusetion; } public void setQusetion(String qusetion) { this.qusetion = qusetion == null ? null : qusetion.trim(); } public String getAnwser() { return anwser; } public void setAnwser(String anwser) { this.anwser = anwser == null ? null : anwser.trim(); } public String getUsergroupid() { return usergroupid; } public void setUsergroupid(String usergroupid) { this.usergroupid = usergroupid == null ? null : usergroupid.trim(); } public String getRegistertime() { return registertime; } public void setRegistertime(String registertime) { this.registertime = registertime == null ? null : registertime.trim(); } public String getRegisterip() { return registerip; } public void setRegisterip(String registerip) { this.registerip = registerip == null ? null : registerip.trim(); } public String getLogintime() { return logintime; } public void setLogintime(String logintime) { this.logintime = logintime == null ? null : logintime.trim(); } public String getLoginip() { return loginip; } public void setLoginip(String loginip) { this.loginip = loginip == null ? null : loginip.trim(); } public String getStatus() { return status; } public void setStatus(String status) { this.status = status == null ? null : status.trim(); } public String getIsonline() { return isonline; } public void setIsonline(String isonline) { this.isonline = isonline == null ? null : isonline.trim(); } public String getIsenabled() { return isenabled; } public void setIsenabled(String isenabled) { this.isenabled = isenabled == null ? null : isenabled.trim(); } }
810806a3f95c847c553655559acc0ac45186e94b
[ "Java" ]
10
Java
sweethomemax/study
f4fe131e05c232b0f858da8c8384ce1652f4be4e
9575da60817178c9225ac2d1f93bacee18ce8ac2
refs/heads/master
<file_sep># Implementation of dual-number based automatic differentiation import numpy.matlib from numbers import Number class NDimensionalDual(object): def __init__(self, dim, vals): self.dim = dim self.vals = vals def matrix(self): matrix = numpy.matlib.zeros((dim, dim)) for pos, val in vals: row = 1 col = pos while pos < dim: matrix[row, col] = val row += 1 col += 1 return matrix def __add__(self, other): if isinstance(other, NDimensionalDual): length = max(len(self.vals), len(other.vals)) new_vals = [0] * length for vals in [self.vals, other.vals]: for pos, val in enumerate(vals): new_vals[pos] += val return NDimensionalDual(length, new_vals) elif isinstance(other, Number): new_vals = self.vals[:] new_vals[0] += other return NDimensionalDual(self.dim, new_vals) def __sub__(self, other): if isinstance(other, Number): return self + (-1 * other) elif isinstance(other, NDimensionalDual): new_vals = [0] * length for pos, val in self.vals: new_vals[pos] = val for pos, val in other.vals: new_vals[pos] = -val def __mul__(self, other): def __div__(self, other): pass def __pow__(self, other): pass def __radd__(self, other): self.__add__(other) def __rsub__(self, other): self.__sub__(other) def __rmul__(self, other): self.__mul__(other) def __rdiv__(self, other): self.__div__(other) def __rpow__(self, other): raise NotImplementedError def __abs__(self): pass<file_sep>numerical-analysis ================== Implementation of algorithms from the Numerical Analysis courses I've studied at university
a23ba0a249944504208d88408bca608da54c8b89
[ "Markdown", "Python" ]
2
Python
smllmn/numerical-analysis
e428b316551904a6bd6ac79ca0395f6bf0923705
b3a35e5a4d259c33fe311a4aaede74a8e688907d
refs/heads/master
<file_sep>package com.atguigu.gmall0919.logger.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.atguigu.gmall0919.common.constant.GmallConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @RestController //ResponseBody+Controller @Slf4j public class LoggerController { @Autowired KafkaTemplate kafkaTemplate; //@RequestMapping(value = "log" ,method = RequestMethod.POST) @PostMapping("/log") public String dolog(@RequestParam("logString") String logString ){ System.out.println(logString); //1 加时间戳 //456456456 //BBBBBBBBBBBBbbb JSONObject jsonObject = JSON.parseObject(logString); jsonObject.put("ts",System.currentTimeMillis()); String jsonString = jsonObject.toJSONString(); //落盘日志 log4j logback log4j2 loging -->> slf4j log.info(jsonString); // 发送kafka if(jsonObject.getString("type").equals("startup")){ kafkaTemplate.send(GmallConstant.KAFKA_TOPIC_STARTUP,jsonString); }else{ kafkaTemplate.send(GmallConstant.KAFKA_TOPIC_EVENT,jsonString); } return "success"; } } <file_sep>package com.atguigu.gmall0919.publisher.mapper; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; public interface DauMapper { public Long selectDauTotal(String date); public List<Map> selectDauHourCount(String date ); } <file_sep>package com.atguigu.gmall0919.publisher.service; import java.util.List; import java.util.Map; public interface PublisherService { public Long getDauTotal(String date); public Map getDauHourMap(String date); public Double getOrderAmountTotal(String date); public Map getOrderAmountHour(String date); public Map getSaleDetail(String date,String keyword,int startpage, int size); } <file_sep>package com.atguigu.gmall0919.publisher.controller; import com.alibaba.fastjson.JSON; import com.atguigu.gmall0919.publisher.bean.Option; import com.atguigu.gmall0919.publisher.bean.Stat; import com.atguigu.gmall0919.publisher.service.PublisherService; import org.apache.commons.lang.time.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import sun.java2d.pipe.SpanShapeRenderer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @RestController public class PublisherController { @Autowired PublisherService publisherService; @GetMapping("realtime-total") public String getTotal(@RequestParam("date") String date ){ Long dauTotal = publisherService.getDauTotal(date); List<Map> totalList= new ArrayList(); Map dauMap=new HashMap(); dauMap.put("id","dau"); dauMap.put("name","新增日活"); dauMap.put("value",dauTotal); totalList.add(dauMap); Map newMidMap=new HashMap(); newMidMap.put("id","new_mid"); newMidMap.put("name","新增设备"); newMidMap.put("value",233); totalList.add(newMidMap); Double orderAmountTotal = publisherService.getOrderAmountTotal(date); Map orderAmountMap=new HashMap(); orderAmountMap.put("id","order_amount"); orderAmountMap.put("name","新增交易额"); orderAmountMap.put("value",orderAmountTotal!=null?orderAmountTotal:0.0D); totalList.add(orderAmountMap); String jsonString = JSON.toJSONString(totalList); return jsonString; } @GetMapping("realtime-hour") public String getRealtimeHour(@RequestParam("id") String id ,@RequestParam("date")String date){ Map<String,Map> hourMap= new HashMap<>(); if("dau".equals(id)){ Map todayDauHourMap= publisherService.getDauHourMap(date); String yd = getYd(date); Map yesterdayDauHourMap= publisherService.getDauHourMap(yd); hourMap.put("today",todayDauHourMap); hourMap.put("yesterday",yesterdayDauHourMap); return JSON.toJSONString(hourMap); }else if ("order_amount".equals(id)){ Map todayOrderAmountHourMap= publisherService.getOrderAmountHour(date); String yd = getYd(date); Map yesterdayOrderAmountHourMap= publisherService.getOrderAmountHour(yd); hourMap.put("today",todayOrderAmountHourMap); hourMap.put("yesterday",yesterdayOrderAmountHourMap); return JSON.toJSONString(hourMap); } return null; } private String getYd(String td){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date tdDate = simpleDateFormat.parse(td); Date ydDate = DateUtils.addDays(tdDate, -1); String yd = simpleDateFormat.format(ydDate); return yd; } catch (ParseException e) { throw new RuntimeException("日期格式不正确"); } } @GetMapping("sale_detail") public String getSaleDetail(@RequestParam("date") String date ,@RequestParam("startpage") int startpage ,@RequestParam("size") int size ,@RequestParam("keyword") String keyword ){ Map saleDetailMap= publisherService.getSaleDetail(date,keyword,startpage,size); Long total =(Long)saleDetailMap.get("total"); List<Map> detailList =(List<Map>)saleDetailMap.get("detail"); Map ageAgg =(Map) saleDetailMap.get("ageAgg"); Long age20lt=0L; Long age20gte30lt=0L; Long age30gte=0L; for (Object o : ageAgg.entrySet()) { Map.Entry entry = (Map.Entry) o; String ageStr =(String) entry.getKey(); Long ageCount =(Long) entry.getValue(); Integer age = Integer.valueOf(ageStr); if (age<20){ age20lt+=ageCount; }else if(age>=20&&age<30){ age20gte30lt+=ageCount; }else{ age30gte+=ageCount; } } Double age20ltRatio= Math.round( age20lt*1000D/total)/10D; Double age20gte30ltRatio=Math.round( age20gte30lt*1000D/total)/10D;; Double age30gteRatio=Math.round( age30gte*1000D/total)/10D;; Map resultMap=new HashMap(); List ageOptions=new ArrayList(); ageOptions.add(new Option("20岁以下",age20ltRatio)); ageOptions.add(new Option("20岁到30岁",age20gte30ltRatio)); ageOptions.add(new Option("30岁及以上",age30gteRatio)); List genderOptions=new ArrayList(); genderOptions.add(new Option("男",27.5D)); genderOptions.add(new Option("女",72.5D)); List<Stat> statList=new ArrayList<>(); statList.add(new Stat("年龄占比",ageOptions)); statList.add(new Stat("性别占比",genderOptions)); resultMap.put("stat",statList); resultMap.put("total",total); resultMap.put("detail",detailList); return JSON.toJSONString(resultMap); } } <file_sep>package com.atguigu.gmall0919.common.constant; public class GmallConstant { public static final String KAFKA_TOPIC_STARTUP="GMALL_STARTUP"; public static final String KAFKA_TOPIC_EVENT="GMALL_EVENT"; public static final String KAFKA_TOPIC_ORDER="GMALL_ORDER"; public static final String KAFKA_TOPIC_ORDER_DETAIL="GMALL_ORDER_DETAIL"; public static final String KAFKA_TOPIC_USER="GMALL_USER"; public static final String ES_INDEX_ALERT="gmall0919_coupon_alert"; public static final String ES_INDEX_SALE="gmall0919_sale_detail"; }
c788bff63ada0665068bcbf3e1c8570bc3fa620b
[ "Java" ]
5
Java
qingjianmoxie/gmall0919-parent
8cfabf73f357922ba727991ef8793e4c3e59bd40
04b273f795d0660b79827fb9872c1e43e218c468
refs/heads/master
<repo_name>pkp95/Projects<file_sep>/urlread.py from __future__ import print_function from pylab import * import matplotlib.pyplot as plt import pandas as pd import xlwt import urllib2 import pylab from xlutils.copy import copy from xlrd import open_workbook wiki="http://stats.espncricinfo.com/ci/engine/stats/index.html?batting_hand=1;batting_hand=2;batting_hand=3;class=2;filter=advanced;floodlit=1;floodlit=2;home_or_away=1;home_or_away=2;home_or_away=3;innings_number=1;innings_number=2;keeper=0;orderby=batted_score;result=1;result=2;result=3;result=5;size=200;template=results;tournament_type=2;tournament_type=3;tournament_type=5;type=batting;view=innings" page=urllib2.urlopen(wiki) from bs4 import BeautifulSoup soup=BeautifulSoup(page) right_table=soup.findAll('table', class_='engineTable') a=[] b=[] c=[] d=[] for row in right_table[2].find_all('tr'): cells=row.findAll('td') if len(cells) in [13]: text=str(cells[0]) text1=text.split("</a> (")[1] text2=text1.split(")</td>")[0] a.append(cells[0].find(text=True)) b.append(cells[1].find(text=True)) c.append(cells[10].find(text=True)) d.append(text2) workbookwrite=xlwt.Workbook() sheet=workbookwrite.add_sheet('Sheet1') sheet.write(0,0,'Player') sheet.write(0,1,'Runs') sheet.write(0,2,'Ground') sheet.write(0,3,'Team') for i in range(1,201): sheet.write(i,0,a[i-1]) sheet.write(i,1,b[i-1]) sheet.write(i,2,c[i-1]) sheet.write(i,3,d[i-1]) workbookwrite.save('ans.xls') for i in range(2,379): book_ro = open_workbook("ans.xls") book = copy(book_ro) sheet1 = book.get_sheet(0) print (i) wiki="http://stats.espncricinfo.com/ci/engine/stats/index.html?batting_hand=1;batting_hand=2;batting_hand=3;class=2;filter=advanced;floodlit=1;floodlit=2;home_or_away=1;home_or_away=2;home_or_away=3;innings_number=1;innings_number=2;keeper=0;orderby=batted_score;page="+str(i)+";result=1;result=2;result=3;result=5;size=200;template=results;tournament_type=2;tournament_type=3;tournament_type=5;type=batting;view=innings" page=urllib2.urlopen(wiki) soup=BeautifulSoup(page) right_table=soup.findAll('table', class_='engineTable') a=[] b=[] c=[] d=[] for row in right_table[2].find_all('tr'): cells=row.findAll('td') if len(cells) in [13]: text=str(cells[0]) text1=text.split("</a> (")[1] text2=text1.split(")</td>")[0] a.append(cells[0].find(text=True)) b.append(cells[1].find(text=True)) c.append(cells[10].find(text=True)) d.append(text2) for j in range(1,201): sheet1.write(j+(200*(i-1)),0,a[j-1]) sheet1.write(j+(200*(i-1)),1,b[j-1]) sheet1.write(j+(200*(i-1)),2,c[j-1]) sheet1.write(j+(200*(i-1)),3,d[j-1]) book.save("ans.xls");
bccf6e145937c78876478f107355478ecbcbe559
[ "Python" ]
1
Python
pkp95/Projects
b6f9a51069884b8619e17facce0790526f9dfadf
2edb5f209a9d9346dd850232ff3e7fc72a286ceb
refs/heads/main
<file_sep>price = 1E6 good_credit = False if good_credit: down_payment = 0.1 * price else: down_payment = 0.2 * price print(f"Down payment: ${down_payment}") # formatted string. <file_sep>import random for i in range(3): # creating a range object three times. print(random.randint(10, 22)) # random module, then random method. letters = ['A', 'B', 'C', 'D', 'E'] picked = random.choice(letters) # picking a letter from the letters list. print(picked) # blank # blank class Dice: # always blank two lines above and below the class loop. def roll(self): first = random.randint(1, 6) second = random.randint(1, 6) return (first, second) # ending the class loop with tuple using (). # blank # blank dice = Dice() print(dice.roll()) <file_sep>secret_number = 5 guess_count = 1 guess_limit = 3 while guess_count <= guess_limit: guess = int(input('guess: ')) guess_count += 1 if guess == secret_number: print("You won!") break else: print("Game over!")<file_sep># tuples uses (). Not []. [] is for lists. # tuples are immutable meaning cannot be changed. numbers = (1, 2, 3) numbers[numbers[1]] # the 1st index. print(numbers[1]) <file_sep>course = 'Python for Beginners' print(len(course)) print(course.upper()) print(course) print(course.lower()) print(course.find('n')) print(course.title('B')) print(course.replace('Beginners', 'Absolute Beginners')) print('python' in course) len() course.upper() course.lower() course.title() course.find() course.replace() <file_sep>has_high_income = True has_good_credit = False has_criminal_record = False if has_high_income and not has_criminal_record: print("Eligible for loan") <file_sep>weight = input('Weight: ') unit = input("kg or lbs? ") if unit.lower() == "lbs": converted = weight * 0.45 print(f"You're {converted} kg.") else: converted = weight / 0.45 print(f"You're {converted} lbs.")<file_sep># collection = strings prices = [10, 20, 30] total = 0 for dollars in prices: # defining dollars to add up the values in prices. total += dollars # total = total + dollars (prices) print(f"Total: {total}") # formatted string. <file_sep># sorting the only unique numbers: numbers = [1,2,5,3,6,2,2,2,4] uniques = [] for duplicates in numbers: # adding non-duplicates in the uniques variable. if duplicates not in uniques: uniques.append(duplicates) print(uniques) <file_sep># hashtage = comments print('Sky is blue')<file_sep>house_price = 1E6 good_credit = False if good_credit: downpayment = 0.1 * house_price else: downpayment = 0.2 * house_price message = f"My downpayment is: ${downpayment}." print(message)<file_sep>x = (10 + 3) * 2 ** 2 print(x) x = (2+3)*10-3 print(x)<file_sep>course = "Python's Course for Beginners" another = course[:] print(another) name = 'Jennifer' print(name[1:4]) # first parameter is inclusive, second is exclusive. print(name[:-2]) # printing 0th <= name < -2nd. print(name[0:-2]) # same as right above. <file_sep># inputting your profile info: birth_year = input('Birth year: ') print(type(birth_year)) age = 2020 - int(birth_year) print(type(age)) print(age) body_weight_lbs = input('your current weight: ') body_weight_kg = 0.45 * int(body_weight_lbs) print(body_weight_kg) <file_sep># Python3_tutorial_mosh Python Tutorial for Beginners (full course) by Programming with Mosh. <file_sep># passing information to the functions. def greet_user(first_name, last_name): print(f'Hi {first_name}, {last_name}!') print('Welcome aboard') # now the actual output. print("Start") greet_user("Bruce", last_name= "Banner") print("Finish") <file_sep>import math print(math.floor(2.9)) # lower case. <file_sep>coordinates = (2,4,3) # assign integers to my variable. x,y,z=coordinates # assign xyz values to my variable. print(y) # now I'm printing only the y value. print(x) # x value. <file_sep>weight = int(input('Weight: ')) # what about the floating input? print() unit = input("Indicate 'lbs' or 'kg': ") # any input error for sth else? print() if unit.lower() == 'lbs': converted = weight * 0.45 print(f"You're {converted} kg.") else: converted = weight / 0.45 print(f"You're {converted} lbs.") <file_sep>names = ['Phil', 'Bob', 'Katie', 'John', 'Sam'] print(names[0:3]) # excluding John and Sam # Finding the largest number on the list: # If in for loops: numbers = [12, 24, 6, 2, 8, 4, 10] max = numbers[0] # defining a max varible from the numbers variable. # starting with 0th index in the for loop below, but it really # doesn't matter which index to start with. for number in numbers: if number > max: max = number # setting a new max. print(max) <file_sep># printing proper error messages by the human developer. # using TRY and EXCEPT constructions to handle errors. try: # defining a try block. age = int(input('Age: ')) income = 120592 # inserting an arbitrary variable to avoid Zero. risk = income / age # inserting an arbitrary variable to avoid Zero. print(age) except ZeroDivisionError: # now assigning the Zero age error message. print() print('ERROR: Age cannot be zero.') except ValueError: print() print('ERROR: Invalid value. Type a numerical value.') <file_sep>course = 'a learning python' print(course.title())<file_sep>i=2 # two asteroids '**' while i <= 10: # iterate until the index reaches less or equal to ten. print('*' * i) i = i+3 # incrementing by 2. # without addition, i will be an infinite loop. print("Done") <file_sep>print('Enter "menu" for help') command = "" started = False while True: command = input("> ").lower() if command == "start": if started: print("The car is already revving!") else: started = True print("The car is revving") elif command == "stop": if not started: print("The car is already stopped!") else: started = False print("The car is stopped") elif command == "menu": print(''' Enter "start" to start the car. Enter "stop" to stop the car. Enter "quit" to exit the game. ''') elif command == "quit": break else: print("I don't understand that.")<file_sep># performing math module. import math print(math.floor(2.9))<file_sep>from converters import kg_to_lbs print(kg_to_lbs(69)) from utils import find_max numbers = [10, 3, 6, 2] maximum = find_max(numbers) print(maximum)<file_sep># iterate characters bills = [10, 20, 30] total = 0 for grocery_list in bills: total += grocery_list print(f"Total bills: ${total}")<file_sep>first_name = 'Phil' last_name = 'Moon' message = first_name + ' [' + last_name + '] is a coder' msg = f'{first_name} [{last_name}] is a coder.' print(msg) subject = 'Python' platform = 'YouTube' message_2 = f"I'm learning {subject} on {platform}!" print(message_2)<file_sep># for loops are to iterate strings etc. # define with a 'loop variable'. # nested loops are loops within the loop. # generating quardinants. for x in range(4): # starting the quardinants from 0. for y in range(3): # inner loop is completed first before the outer loop. print(f"({x}, {y})") # multiplying 'x' with my loop variable. numbers = [1, 1, 1, 1, 5] for x_count in numbers: print('x' * x_count) # nested loop. numbers = [5, 2, 5, 2, 2] for x_count in numbers: output = '' # defining a variable with an empty string. for count in range(x_count): # using a range function to sequence x_count. output += 'x' print(output) <file_sep>userid = "sphilmoon" if len(userid) < 3: print("letter must be at lease 3 letters long.") elif len(userid) > 50: print("less than 50 letters long.") else: print('looks good!')<file_sep># loop in loop for x in range(4): for y in range(3): print(f'{x}, {y}') ###################################### numbers = [5, 2, 5, 2, 2] for star_count in numbers: print('*' * star_count) ###################################### for x in range(4): for y in range(3): print(f'{x}, {y}') numbers = [1, 1, 1, 1, 5] for star_count in numbers: output = "" for star_count in range(star_count): output += "*" print(output)<file_sep>temperature = 31 if temperature > 30: # greater than 30 degree print("It's a hot day") else: print("It's not a hot day") username = "sphilmoon" if len(username) <= 5: # first if condition # the length of index. print("your username must be at least 5 characters") elif len(username) > 50: # second if condition print("your username must be less than 50 characters") else: # aka otherwise, anything between 5-50 characters. print("your username looks good!")
7a4649fa35a0306b120c76e448944ff48539c9cc
[ "Markdown", "Python" ]
32
Python
sphilmoon/Python3_tutorial_mosh
bb70de5bff7b4d26f58fe1dcdfd4ec4957631bd5
58ec9a1abdf801ccb1d88f85de56baa5f6fb4a7f
refs/heads/master
<repo_name>pvytykac/WTZadanie<file_sep>/server/src/main/java/edu/tuke/transform/e2dto/RegistrationRequestE2DTO.java package edu.tuke.transform.e2dto; import edu.tuke.dto.employees.RegistrationRequestDTO; import edu.tuke.entity.RegistrationRequest; import edu.tuke.transform.generic.Transform; public class RegistrationRequestE2DTO extends Transform<RegistrationRequest, RegistrationRequestDTO> { @Override public Class<RegistrationRequestDTO> getClassTo() { return RegistrationRequestDTO.class; } @Override public void transform(RegistrationRequest e, RegistrationRequestDTO dto) { dto.setId(e.getId()); dto.setEmail(e.getEmail()); dto.setStatus(e.getStatus()); dto.setEmployeeGroup(e.getEmployeeGroup().getName()); dto.setIdEmployeeGroup(e.getEmployeeGroup().getId()); } } <file_sep>/server/src/main/java/edu/tuke/dto/dashboard/ConfirmationDTO.java package edu.tuke.dto.dashboard; import edu.tuke.dto.AbstractDTO; import edu.tuke.entity.enums.ConfirmationStatusEnum; import java.util.Date; public class ConfirmationDTO extends AbstractDTO<Long> { private String employeeName; private Long employeeId; private Date from; private Date to; private ConfirmationStatusEnum status; private Boolean notifiable; private Long exportId; private String invoiceId; public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public Date getFrom() { return from; } public void setFrom(Date from) { this.from = from; } public Date getTo() { return to; } public void setTo(Date to) { this.to = to; } public ConfirmationStatusEnum getStatus() { return status; } public void setStatus(ConfirmationStatusEnum status) { this.status = status; } public Boolean getNotifiable() { return notifiable; } public void setNotifiable(Boolean notifiable) { this.notifiable = notifiable; } public Long getExportId() { return exportId; } public void setExportId(Long exportId) { this.exportId = exportId; } public String getInvoiceId() { return invoiceId; } public void setInvoiceId(String invoiceId) { this.invoiceId = invoiceId; } } <file_sep>/server/src/main/java/edu/tuke/transform/dto2e/CompanyOwnerDTO2E.java package edu.tuke.transform.dto2e; import edu.tuke.dto.registration.CompanyOwnerDTO; import edu.tuke.entity.CompanyOwner; import edu.tuke.transform.generic.Transform; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; public class CompanyOwnerDTO2E extends Transform<CompanyOwnerDTO, CompanyOwner> { @Override public Class<CompanyOwner> getClassTo() { return CompanyOwner.class; } @Override public void transform(CompanyOwnerDTO dto, CompanyOwner e) { e.setId(dto.getId()); e.setPrefix(dto.getPrefix()); e.setFirstname(dto.getFirstname()); e.setLastname(dto.getLastname()); e.setEmail(dto.getEmail()); e.setPhonenumber(dto.getTelephone()); e.setPassHash(new ShaPasswordEncoder().encodePassword(dto.getPassword(), null)); } } <file_sep>/server/src/main/java/edu/tuke/transform/dto2e/WorkLogE2DTO.java package edu.tuke.transform.dto2e; import edu.tuke.dto.dashboard.WorkLogDTO; import edu.tuke.entity.WorkLog; import edu.tuke.transform.generic.Transform; public class WorkLogE2DTO extends Transform<WorkLog, WorkLogDTO> { @Override public Class<WorkLogDTO> getClassTo() { return WorkLogDTO.class; } @Override public void transform(WorkLog e, WorkLogDTO dto) { dto.setId(e.getId()); dto.setEmployeeName(e.getEmployee().getLastname() + " " + e.getEmployee().getFirstname()); dto.setDate(e.getDate()); dto.setTime(e.getTimeWorked()); dto.setIdEmployee(e.getEmployee().getId()); dto.setComment(e.getComment()); } } <file_sep>/server/src/main/java/edu/tuke/docs/DocumentTemplate.java package edu.tuke.docs; import edu.tuke.entity.enums.DocumentTypeEnum; import java.io.*; import java.util.HashMap; import java.util.Map; public abstract class DocumentTemplate { protected File bodyFile; protected Map<String, String> mapParam = new HashMap<String, String>(); public abstract DocumentTypeEnum getDocumentType(); protected abstract void initBodyFile(); public void addParam(String key, String value) { mapParam.put(key, value); } public String getHtml() { initBodyFile(); String body = null; BufferedReader reader; try { StringBuffer buffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(new FileInputStream(bodyFile), "UTF-8")); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } body = buffer.toString(); reader.close(); } catch (IOException e) { e.printStackTrace(); return null; } for (String key : mapParam.keySet()) { if (mapParam.get(key) != null) { body = body.replace("$" + key + "$", mapParam.get(key)); } } return body; } } <file_sep>/server/src/main/java/edu/tuke/transform/e2dto/ConfirmationE2DTO.java package edu.tuke.transform.e2dto; import edu.tuke.dto.dashboard.ConfirmationDTO; import edu.tuke.entity.ConfirmationRequest; import edu.tuke.entity.enums.ConfirmationStatusEnum; import edu.tuke.transform.generic.Transform; import java.util.Calendar; public class ConfirmationE2DTO extends Transform<ConfirmationRequest, ConfirmationDTO> { @Override public Class<ConfirmationDTO> getClassTo() { return ConfirmationDTO.class; } @Override public void transform(ConfirmationRequest e, ConfirmationDTO dto) { dto.setId(e.getId()); dto.setEmployeeName(e.getEmployee().getLastname() + " " + e.getEmployee().getFirstname()); dto.setEmployeeId(e.getEmployeeId()); dto.setFrom(e.getExport().getExportFrom()); dto.setTo(e.getExport().getExportTo()); dto.setExportId(e.getExport().getId()); Calendar toCompare = Calendar.getInstance(); toCompare.add(Calendar.DAY_OF_YEAR, -3); dto.setNotifiable(e.getExport().getTimestamp().before(toCompare.getTime()) && e.getStatus() == ConfirmationStatusEnum.PENDING); dto.setStatus(e.getStatus()); } } <file_sep>/server/src/main/java/edu/tuke/entity/WorkLogExport.java package edu.tuke.entity; import edu.tuke.entity.superclass.CompanySpecificEntity; import edu.tuke.entity.superclass.Persistent; import javax.persistence.*; import java.util.Date; import java.util.List; /** * Export odpracovaneho casu v konkretnom casovom intervale */ @Entity @Table( name = "work_log_export") public class WorkLogExport extends CompanySpecificEntity implements Persistent<Long> { @Id @GeneratedValue( strategy = GenerationType.IDENTITY) private Long id; @Temporal( TemporalType.TIMESTAMP) @Column private Date timestamp; @Temporal( TemporalType.DATE) @Column private Date exportFrom; @Temporal( TemporalType.DATE) @Column private Date exportTo; @OneToMany( fetch = FetchType.LAZY, mappedBy = "export") private List<ConfirmationRequest> liConfirmationRequest; @OneToMany( fetch = FetchType.LAZY, mappedBy = "export") private List<Document> liDocument; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Date getExportFrom() { return exportFrom; } public void setExportFrom(Date exportFrom) { this.exportFrom = exportFrom; } public Date getExportTo() { return exportTo; } public void setExportTo(Date exportTo) { this.exportTo = exportTo; } public List<ConfirmationRequest> getLiConfirmationRequest() { return liConfirmationRequest; } public void setLiConfirmationRequest(List<ConfirmationRequest> liConfirmationRequest) { this.liConfirmationRequest = liConfirmationRequest; } public List<Document> getLiDocument() { return liDocument; } public void setLiDocument(List<Document> liDocument) { this.liDocument = liDocument; } } <file_sep>/server/src/main/java/edu/tuke/transform/e2dto/ExportE2DetailDTO.java package edu.tuke.transform.e2dto; import edu.tuke.dto.dashboard.ConfirmationDTO; import edu.tuke.dto.export.DocumentDTO; import edu.tuke.dto.export.ExportDetailDTO; import edu.tuke.entity.ConfirmationRequest; import edu.tuke.entity.Document; import edu.tuke.entity.WorkLogExport; import edu.tuke.transform.TransformFacade; import edu.tuke.transform.generic.Transform; import java.util.ArrayList; public class ExportE2DetailDTO extends Transform<WorkLogExport, ExportDetailDTO> { @Override public Class<ExportDetailDTO> getClassTo() { return ExportDetailDTO.class; } @Override public void transform(WorkLogExport e, ExportDetailDTO dto) { dto.setId(e.getId()); dto.setFrom(e.getExportFrom()); dto.setTo(e.getExportTo()); dto.setLiConfirmation(new ArrayList<ConfirmationDTO>()); dto.setLiDocument(new ArrayList<DocumentDTO>()); for (Document d : e.getLiDocument()) dto.getLiDocument().add( TransformFacade.documentE2DTO.transform(d)); for (ConfirmationRequest c : e.getLiConfirmationRequest()) dto.getLiConfirmation().add( TransformFacade.confirmationE2DTO.transform(c)); } } <file_sep>/server/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>jar</packaging> <artifactId>server</artifactId> <parent> <artifactId>WTZadanie</artifactId> <groupId>edu.tuke</groupId> <version>1.0-SNAPSHOT</version> </parent> <dependencies> <!-- SPRING --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <!-- AOP dependency --> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.3</version> </dependency> <!-- JDBC datasource pooling --> <dependency> <groupId>com.jolbox</groupId> <artifactId>bonecp</artifactId> <version>0.7.1.RELEASE</version> </dependency> <!-- HIBeRNATE --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.2.1.Final</version> </dependency> <dependency> <artifactId>hibernate-core</artifactId> <groupId>org.hibernate</groupId> <type>jar</type> <version>4.2.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency> <!-- another --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.20</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.3</version> </dependency> <!-- String Template vs. 4 --> <dependency> <groupId>org.antlr</groupId> <artifactId>ST4</artifactId> <version>4.0.7</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.0</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.0</version> </dependency> <dependency> <groupId>org.apache.directory.studio</groupId> <artifactId>org.apache.commons.io</artifactId> <version>2.4</version> </dependency> <!-- TEEST --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.8.4</version> <scope>test</scope> </dependency> <!-- ASPECTJ --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.11</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.11</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>copy-resources-projectEnvironment</id> <phase>process-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${project.build.outputDirectory}</outputDirectory> <overwrite>true</overwrite> <resources> <resource> <directory>${projectEnvironment}</directory> <filtering>false</filtering> <includes> <include>**/*.properties</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/server/src/main/java/edu/tuke/dto/dashboard/EmployeeDTO.java package edu.tuke.dto.dashboard; import edu.tuke.dto.registration.UserDTO; public class EmployeeDTO extends UserDTO { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/server/src/main/java/edu/tuke/filter/dashboard/ConfirmationFilterDTO.java package edu.tuke.filter.dashboard; import edu.tuke.entity.enums.ConfirmationStatusEnum; import edu.tuke.filter.AbstractFilterDTO; import edu.tuke.security.SecurityHelper; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ConfirmationFilterDTO extends AbstractFilterDTO { private Date from; private Date to; private List<Long> employeeId; private ConfirmationStatusEnum status; public ConfirmationFilterDTO(Boolean currentUserOnly) { if (currentUserOnly) { employeeId = new ArrayList<Long>(1); employeeId.add(SecurityHelper.getIdEmployee()); } } public Date getFrom() { return from; } public void setFrom(Date from) { this.from = from; } public Date getTo() { return to; } public void setTo(Date to) { this.to = to; } public List<Long> getEmployeeId() { return employeeId; } public void setEmployeeId(List<Long> employeeId) { this.employeeId = employeeId; } public ConfirmationStatusEnum getStatus() { return status; } public void setStatus(ConfirmationStatusEnum status) { this.status = status; } } <file_sep>/server/src/main/java/edu/tuke/dto/employees/AddRegistrationRequestDTO.java package edu.tuke.dto.employees; import edu.tuke.validation.Email; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; public class AddRegistrationRequestDTO { @NotNull private Long idWorkGroup; @Email(optional = false) private List<EmailDTO> liEmail; public AddRegistrationRequestDTO() { liEmail = new ArrayList<EmailDTO>(); liEmail.add(new EmailDTO()); } public Long getIdWorkGroup() { return idWorkGroup; } public void setIdWorkGroup(Long idWorkGroup) { this.idWorkGroup = idWorkGroup; } public List<EmailDTO> getLiEmail() { return liEmail; } public void setLiEmail(List<EmailDTO> liEmail) { this.liEmail = liEmail; } } <file_sep>/web/src/main/java/edu/tuke/security/AjaxJSFRedirectStrategy.java package edu.tuke.security; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.web.session.InvalidSessionStrategy; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AjaxJSFRedirectStrategy implements InvalidSessionStrategy { private static final Log log = LogFactory.getLog(AjaxJSFRedirectStrategy.class); private String invalidSessionUrl; public AjaxJSFRedirectStrategy(String invalidSessionUrl) { this.invalidSessionUrl = invalidSessionUrl; } @Override public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("onInvalidSessionDetected()"); // if (request.getRequestedSessionId() == null || request.isRequestedSessionIdValid()) // return; String url = request.getContextPath() + invalidSessionUrl; if ("partial/ajax".equals(request.getHeader("Faces-Request"))) { log.debug("call JSF redirect to url: " + url); sendJsfRedirect(response, url); } else { log.debug("call standart response redirect to url: " + url); response.sendRedirect(url); } } public void sendJsfRedirect(HttpServletResponse response, String url) throws IOException { String ajaxRedirectXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<partial-response><redirect url=\""+url+"\"></redirect></partial-response>"; response.setContentType("text/xml"); response.getWriter().write(ajaxRedirectXml); } }<file_sep>/server/src/main/java/edu/tuke/dao/WorkLogExportDAO.java package edu.tuke.dao; import edu.tuke.dao.generic.CompanySpecificDAO; import edu.tuke.entity.Company; import edu.tuke.entity.Document; import edu.tuke.entity.WorkLogExport; import edu.tuke.filter.dashboard.WorkLogExportFilterDTO; import edu.tuke.security.SecurityHelper; import org.springframework.stereotype.Repository; import javax.persistence.NoResultException; import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @Repository public class WorkLogExportDAO extends CompanySpecificDAO<WorkLogExport, Long> { @Override public Class<WorkLogExport> getEntityClass() { return WorkLogExport.class; } public List<WorkLogExport> search(WorkLogExportFilterDTO filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<WorkLogExport> query = cb.createQuery(WorkLogExport.class); Root<WorkLogExport> root = query.from(WorkLogExport.class); Fetch<WorkLogExport, List<Document>> docFetch = root.fetch("liDocument", JoinType.LEFT); makePredicates(query, root, filter); // ByMJ. if (filter.getSortField() != null) { Path<?> sortPath = null; if (filter.getSortField().equalsIgnoreCase("from")) { sortPath = root.<WorkLogExport>get("export").<Date>get("exportFrom"); } else if (filter.getSortField().equalsIgnoreCase("to")) { sortPath = root.<WorkLogExport>get("export").<Date>get("exportTo"); } if (filter.getAscending()) { query.orderBy(cb.asc(sortPath)); } else { query.orderBy(cb.desc(sortPath)); } } query.distinct(true); query.select(root); return em.createQuery(query) .setFirstResult(filter.getFirst()) .setMaxResults(filter.getSize()) .getResultList(); } public Long searchCount(WorkLogExportFilterDTO filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> query = cb.createQuery(Long.class); Root<WorkLogExport> root = query.from(WorkLogExport.class); makePredicates(query, root, filter); // ByMJ. query.select(cb.countDistinct(root)); return em.createQuery(query) .getSingleResult(); } // ByMJ. private void makePredicates(CriteriaQuery<?> query, Root<WorkLogExport> root, WorkLogExportFilterDTO filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); List<Predicate> liPredicate = new ArrayList<Predicate>(); Expression<Long> cId = root.<Company>get("company").<Long>get("id"); liPredicate.add(cb.equal(cId, SecurityHelper.getIdCompany())); if (filter.getFrom() != null) { Expression<Date> p = root.<Date>get("exportFrom"); liPredicate.add(cb.greaterThanOrEqualTo(p, filter.getFrom())); } if (filter.getTo() != null) { Expression<Date> p = root.<Date>get("exportTo"); liPredicate.add(cb.lessThanOrEqualTo(p, filter.getTo())); } query.where(liPredicate.toArray(new Predicate[liPredicate.size()])); } public WorkLogExport getDetail(Long idExport) { String query = "SELECT DISTINCT e FROM WorkLogExport e " + "LEFT JOIN FETCH e.liConfirmationRequest " + "WHERE e.id = :idExport"; return em.createQuery(query, WorkLogExport.class) .setParameter("idExport", idExport) .getSingleResult(); } public List<Document> getDocuments(Long idExport) { String query = "SELECT DISTINCT doc FROM WorkLogExport e " + "JOIN e.liDocument doc " + "WHERE e.id = :idExport"; return em.createQuery(query, Document.class) .setParameter("idExport", idExport) .getResultList(); } public WorkLogExport getLastExport() { try { String query = "SELECT e FROM WorkLogExport e " + "WHERE e.company.id = :idCompany " + "ORDER BY e.exportTo DESC"; return em.createQuery(query, WorkLogExport.class) .setParameter("idCompany", SecurityHelper.getIdCompany()) .setMaxResults(1) .getSingleResult(); } catch (NoResultException e) { return null; } } public WorkLogExport findByDate(Date value) { try { String query = "SELECT e FROM WorkLogExport e " + "WHERE e.company.id = :idCompany " + "AND e.exportFrom <= :date " + "AND e.exportTo >= :date"; return em.createQuery(query, WorkLogExport.class) .setParameter("idCompany", SecurityHelper.getIdCompany()) .setParameter("date", value) .getSingleResult(); } catch (NoResultException e) { return null; } } }<file_sep>/server/src/main/java/edu/tuke/transform/dto2e/RegistrationRequestDTO2E.java package edu.tuke.transform.dto2e; import edu.tuke.dto.employees.RegistrationRequestDTO; import edu.tuke.entity.RegistrationRequest; import edu.tuke.transform.generic.Transform; public class RegistrationRequestDTO2E extends Transform<RegistrationRequestDTO, RegistrationRequest> { @Override public Class<RegistrationRequest> getClassTo() { return RegistrationRequest.class; } @Override public void transform(RegistrationRequestDTO dto, RegistrationRequest e) { e.setId(dto.getId()); e.setStatus(dto.getStatus()); e.setEmail(dto.getEmail()); } } <file_sep>/server/src/main/java/edu/tuke/entity/enums/ConstantEnum.java package edu.tuke.entity.enums; import edu.tuke.entity.superclass.Displayable; import org.apache.commons.lang3.StringUtils; public enum ConstantEnum implements Displayable { TAX_LOW, TAX_HIGH, TAX_HIGH_LIMIT; @Override public String getDisplayName() { return StringUtils.capitalize(this.toString().toLowerCase()).replace( "_", " "); } } <file_sep>/server/src/main/resources/enviroment.properties application.context=http://localhost:8080/ZadanieWT/ jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/zadwt jdbc.username=root jdbc.password=<PASSWORD> pdf.upload=D:/ZADWT_FILES/ pdf.wkhtmltopdf=C:/Program Files (x86)/wkhtmltopdf/wkhtmltopdf.exe <file_sep>/server/src/main/java/edu/tuke/services/IEmployeeGroupService.java package edu.tuke.services; import edu.tuke.dto.settings.EmployeeGroupDTO; import java.util.List; public interface IEmployeeGroupService { public List<EmployeeGroupDTO> listEmployeeGroups(); public void saveEmployeeGroup(EmployeeGroupDTO empGroup); } <file_sep>/server/src/main/java/edu/tuke/transform/dto2e/WorkLogDTO2E.java package edu.tuke.transform.dto2e; import edu.tuke.dto.dashboard.WorkLogDTO; import edu.tuke.entity.WorkLog; import edu.tuke.transform.generic.Transform; public class WorkLogDTO2E extends Transform<WorkLogDTO, WorkLog> { @Override public Class<WorkLog> getClassTo() { return WorkLog.class; } @Override public void transform(WorkLogDTO dto, WorkLog e) { e.setId(dto.getId()); e.setDate(dto.getDate()); e.setTimeWorked(dto.getTime()); e.setComment(dto.getComment()); } } <file_sep>/server/src/main/java/edu/tuke/validation/NonZeroTimeValidator.java package edu.tuke.validation; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.text.SimpleDateFormat; import java.util.Date; public class NonZeroTimeValidator implements ConstraintValidator<NonZeroTime, Date> { private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); @Override public void initialize(NonZeroTime constraintAnnotation) { } @Override public boolean isValid(Date value, ConstraintValidatorContext context) { String[] str = sdf.format(value).split(":"); Long h = Long.valueOf(str[0]); Long m = Long.valueOf(str[1]); return h != 0 || m != 0L; } } <file_sep>/server/src/main/java/edu/tuke/services/impl/PDFService.java package edu.tuke.services.impl; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.*; @Component public class PDFService { @Value(value = "${pdf.wkhtmltopdf}") private static String converter; @Value(value = "${pdf.uploadDir}") private static String uploadPath; /** * @param fileName Without extension. * @param htmlContent HTML text for converting to PDF * @return PDF file output stream */ public static ByteArrayOutputStream convertHtmlToPdf(String fileName, String htmlContent) { ByteArrayOutputStream os = new ByteArrayOutputStream(); // save HTML to disc String uploadDirPath = uploadPath + "html2pdf/"; try { FileUtils.forceMkdir(new File(uploadDirPath)); } catch (IOException e) { e.printStackTrace(); } File html = new File(uploadDirPath + fileName + ".html"); try { FileUtils.writeStringToFile(html, htmlContent, "UTF-8"); // create pdf from html ProcessBuilder pb = new ProcessBuilder(converter, uploadDirPath + fileName + ".html", uploadDirPath + fileName + ".pdf"); // For some odd reason, the output from wkhtmltopdf goes to stderr and NOT stdout! pb.redirectErrorStream(true); Process process = pb.start(); BufferedReader inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = inStreamReader.readLine(); while (line != null) { System.out.println(line); line = inStreamReader.readLine(); } try { int exitValue = process.waitFor(); System.out.println("\n\nExit Value is " + exitValue); } catch (InterruptedException e) { e.printStackTrace(); } // get PDF File pdf = new File(uploadDirPath + fileName + ".pdf"); FileInputStream pdfStream = new FileInputStream(pdf); IOUtils.copy(pdfStream, os); pdfStream.close(); FileUtils.forceDelete(html); FileUtils.forceDelete(pdf); } catch (IOException e) { e.printStackTrace(); } return os; } public void setConverter(String converter) { PDFService.converter = converter; } public void setUploadPath(String uploadPath) { PDFService.uploadPath = uploadPath; } } <file_sep>/server/src/main/java/edu/tuke/transform/dto2e/EmployeeGroupDTO2E.java package edu.tuke.transform.dto2e; import edu.tuke.dto.settings.EmployeeGroupDTO; import edu.tuke.entity.EmployeeGroup; import edu.tuke.transform.generic.Transform; public class EmployeeGroupDTO2E extends Transform<EmployeeGroupDTO, EmployeeGroup> { @Override public Class<EmployeeGroup> getClassTo() { return EmployeeGroup.class; } @Override public void transform(EmployeeGroupDTO dto, EmployeeGroup e) { e.setId(dto.getId()); e.setName(dto.getName()); e.setRate(dto.getRate()); } } <file_sep>/server/src/main/java/edu/tuke/validation/EmployeeValidator.java package edu.tuke.validation; import edu.tuke.dao.WorkLogDAO; import edu.tuke.dto.employees.EmployeeFullDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.support.SpringBeanAutowiringSupport; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.text.SimpleDateFormat; public class EmployeeValidator implements ConstraintValidator<EmployeeValidation, EmployeeFullDTO> { @Autowired private WorkLogDAO workLogDAO; private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); @Override public void initialize(EmployeeValidation constraintAnnotation) { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); } @Override public boolean isValid(EmployeeFullDTO value, ConstraintValidatorContext context) { boolean isValid = true; // if( value.getEmploymentType() == EmploymentTypeEnum.ZIVNOST){ // if(!isFilled( value.getIco())){ // context.buildConstraintViolationWithTemplate( "field is required" ) // .addNode( "ico" ).addConstraintViolation(); // isValid = false; // } // // if( !isFilled( value.getDic())){ // context.buildConstraintViolationWithTemplate( "field is required" ) // .addNode( "dic" ).addConstraintViolation(); // isValid = false; // } // // if( !isFilled( value.getObchodneMeno())){ // context.buildConstraintViolationWithTemplate( "field is required" ) // .addNode( "obchodneMeno" ).addConstraintViolation(); // isValid = false; // } // // if( !isFilled( value.getTradeItem())){ // context.buildConstraintViolationWithTemplate( "field is required" ) // .addNode( "tradeItem" ).addConstraintViolation(); // isValid = false; // } // } return isValid; } private boolean isFilled(String s) { return s != null && !s.isEmpty(); } } <file_sep>/server/src/main/java/edu/tuke/transform/e2dto/EmployeeFullE2DTO.java package edu.tuke.transform.e2dto; import edu.tuke.dto.employees.EmployeeFullDTO; import edu.tuke.entity.Employee; import edu.tuke.transform.generic.Transform; public class EmployeeFullE2DTO extends Transform<Employee, EmployeeFullDTO> { @Override public Class<EmployeeFullDTO> getClassTo() { return EmployeeFullDTO.class; } @Override public void transform(Employee e, EmployeeFullDTO dto) { dto.setId(e.getId()); dto.setEmployeeGroup(e.getGroup().getName()); dto.setIdEmployeeGroup(e.getGroup().getId()); dto.setName(e.getPrefix() + " " + e.getFirstname() + " " + e.getLastname()); dto.setAddress(e.getAddress().getStreet() + " " + e.getAddress().getNumber() + ", " + e.getAddress().getZip() + ", " + e.getAddress().getCity()); dto.setEmail(e.getEmail()); dto.setEmploymentType(e.getType()); dto.setEmployeeType(e.getEmployeeType()); } } <file_sep>/web/src/main/java/edu/tuke/Controller/DashboardController.java package edu.tuke.controller; import edu.tuke.Facade; import edu.tuke.FacesHelper; import edu.tuke.SelectItemConverter; import edu.tuke.WTLazyDataModel; import edu.tuke.dto.dashboard.ConfirmationDTO; import edu.tuke.dto.dashboard.EmployeeDTO; import edu.tuke.dto.dashboard.WorkLogDTO; import edu.tuke.dto.dashboard.WorkLogExportDTO; import edu.tuke.dto.export.DocumentDTO; import edu.tuke.dto.export.ExportDTO; import edu.tuke.entity.enums.ConfirmationStatusEnum; import edu.tuke.entity.enums.DocumentTypeEnum; import edu.tuke.entity.enums.RightEnum; import edu.tuke.filter.dashboard.ConfirmationFilterDTO; import edu.tuke.filter.dashboard.DocumentFilterDTO; import edu.tuke.filter.dashboard.WorkLogExportFilterDTO; import edu.tuke.filter.dashboard.WorkLogFilterDTO; import edu.tuke.security.SecurityHelper; import edu.tuke.services.*; import edu.tuke.services.impl.PDFService; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.component.UIComponent; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import javax.validation.ConstraintViolation; import javax.validation.Validation; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.List; import java.util.Set; @ManagedBean @ViewScoped public class DashboardController { private IConfirmationService confirmationService = Facade.getServiceByClass(IConfirmationService.class); private IEmployeeService emplService = Facade.getServiceByClass(IEmployeeService.class); private IDocumentService docService = Facade.getServiceByClass(IDocumentService.class); private IWorkLogService workLogService = Facade.getServiceByClass(IWorkLogService.class); private IWorkLogExportService workLogExportService = Facade.getServiceByClass(IWorkLogExportService.class); private IMailService mailService = Facade.getServiceByClass(IMailService.class); private List<SelectItem> liEmployee; private List<SelectItem> liConfirmationStatus; private List<SelectItem> liDocumentType; private WorkLogDTO workLog; private WorkLogExportDTO export; private ConfirmationDTO confirmation; private ExportDTO exportDTO; private DocumentDTO document; private Long countPendingConfirmations; private UIComponent wlDialogForm; @PostConstruct public void init() { liEmployee = SelectItemConverter.convertEntity(EmployeeDTO.class, emplService.list(), "name", false); liConfirmationStatus = SelectItemConverter.convertEnum(ConfirmationStatusEnum.values()); liDocumentType = SelectItemConverter.convertEnum(DocumentTypeEnum.values()); if (SecurityHelper.getIdEmployee() != null) countPendingConfirmations = confirmationService.getPendingCount(); } public void downloadDocument() { String fileName = document.getId().toString() + "_" + SecurityHelper.getPrincipal().getId().toString(); ByteArrayOutputStream out = PDFService.convertHtmlToPdf(fileName, document.getBody()); FacesContext fc = FacesContext.getCurrentInstance(); ExternalContext ec = fc.getExternalContext(); ec.responseReset(); ec.setResponseContentType("application/pdf"); ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); try { OutputStream output = ec.getResponseOutputStream(); output.write(out.toByteArray()); output.close(); } catch (Exception e) { e.printStackTrace(); } fc.responseComplete(); } public void createExport() { exportDTO = workLogExportService.createNewExport(); } public void saveExport() { workLogExportService.saveExport(exportDTO); } public void resetAllConfirmationFilter() { allConfirmationModel.setFilter(new ConfirmationFilterDTO(false)); } public void resetAllWorkLogFilter() { allWorkLogModel.setFilter(new WorkLogFilterDTO(false)); } public void resetAllDocumentFilter() { allDocumentsModel.setFilter(new DocumentFilterDTO(false)); } public void resetWorkLogExportFilter() { workLogExportModel.setFilter(new WorkLogExportFilterDTO()); } public void resetMyConfirmationFilter() { myConfirmationModel.setFilter(new ConfirmationFilterDTO(true)); } public void resetMyWorkLogFilter() { myWorkLogModel.setFilter(new WorkLogFilterDTO(true)); } public void resetMyDocumentFilter() { myDocumentsModel.setFilter(new DocumentFilterDTO(false)); } public void createWorkLog() { workLog = new WorkLogDTO(); } public void saveWorkLog() { Set<ConstraintViolation<WorkLogDTO>> setValidationError = Validation.buildDefaultValidatorFactory(). getValidator().validate(workLog); if (setValidationError.isEmpty()) { workLogService.saveWorkLog(workLog); } else { ConstraintViolation violation = setValidationError.toArray( new ConstraintViolation[setValidationError.size()])[0]; FacesHelper.setValidationError(wlDialogForm.getClientId(), violation); } } public Long getCountPendingConfirmations() { return countPendingConfirmations; } public void notifyConfirmation(ConfirmationDTO dto) { } public void redirectToExportDetail() { FacesHelper.redirectWithParam("/jsf/export/export.jsf?idExport=" + export.getId()); } public void redirectToConfirmation() { FacesHelper.redirectWithParam("/jsf/confirmation/confirmation.jsf?idConf=" + confirmation.getId()); } // ........................................................ RENDER CONDITIONS public boolean isRenderMyTab() { return SecurityHelper.hasRight(RightEnum.CAN_LOG_WORK); } public boolean isRenderAllTab() { return SecurityHelper.hasRight(RightEnum.CAN_VIEW_CONFIRMATION_ALL) || SecurityHelper.hasRight(RightEnum.CAN_VIEW_WORK_LOG_ALL) || SecurityHelper.hasRight(RightEnum.CAN_VIEW_EXPORT); } // ........................................................ GETTERS & SETTERS public WTLazyDataModel<WorkLogExportDTO, WorkLogExportFilterDTO> getWorkLogExportModel() { return workLogExportModel; } public WTLazyDataModel<WorkLogDTO, WorkLogFilterDTO> getMyWorkLogModel() { return myWorkLogModel; } public WTLazyDataModel<ConfirmationDTO, ConfirmationFilterDTO> getMyConfirmationModel() { return myConfirmationModel; } public WTLazyDataModel<WorkLogDTO, WorkLogFilterDTO> getAllWorkLogModel() { return allWorkLogModel; } public WTLazyDataModel<ConfirmationDTO, ConfirmationFilterDTO> getAllConfirmationModel() { return allConfirmationModel; } public WTLazyDataModel<DocumentDTO, DocumentFilterDTO> getAllDocumentsModel() { return allDocumentsModel; } public WTLazyDataModel<DocumentDTO, DocumentFilterDTO> getMyDocumentsModel() { return myDocumentsModel; } public List<SelectItem> getLiEmployee() { return liEmployee; } public void setLiEmployee(List<SelectItem> liEmployee) { this.liEmployee = liEmployee; } public List<SelectItem> getLiConfirmationStatus() { return liConfirmationStatus; } public List<SelectItem> getLiDocumentType() { return liDocumentType; } public void setLiConfirmationStatus(List<SelectItem> liConfirmationStatus) { this.liConfirmationStatus = liConfirmationStatus; } public WorkLogDTO getWorkLog() { return workLog; } public DocumentDTO getDocument() { return document; } public void setDocument(DocumentDTO document) { this.document = document; } public void setWorkLog(WorkLogDTO workLog) { this.workLog = workLog; } public WorkLogExportDTO getExport() { return export; } public void setExport(WorkLogExportDTO export) { this.export = export; } public ConfirmationDTO getConfirmation() { return confirmation; } public void setConfirmation(ConfirmationDTO confirmation) { this.confirmation = confirmation; } public UIComponent getWlDialogForm() { return wlDialogForm; } public void setWlDialogForm(UIComponent wlDialogForm) { this.wlDialogForm = wlDialogForm; } public ExportDTO getExportDTO() { return exportDTO; } private WTLazyDataModel<ConfirmationDTO, ConfirmationFilterDTO> allConfirmationModel = new WTLazyDataModel<ConfirmationDTO, ConfirmationFilterDTO>(new ConfirmationFilterDTO(false)) { @Override public List<ConfirmationDTO> getData(ConfirmationFilterDTO confirmationFilterDTO) { return confirmationService.search(confirmationFilterDTO); } @Override public Long getCount(ConfirmationFilterDTO confirmationFilterDTO) { return confirmationService.getSearchCount(confirmationFilterDTO); } }; private WTLazyDataModel<WorkLogDTO, WorkLogFilterDTO> allWorkLogModel = new WTLazyDataModel<WorkLogDTO, WorkLogFilterDTO>(new WorkLogFilterDTO(false)) { @Override public List<WorkLogDTO> getData(WorkLogFilterDTO filter) { return workLogService.search(filter); } @Override public Long getCount(WorkLogFilterDTO filter) { return workLogService.searchCount(filter); } }; private WTLazyDataModel<ConfirmationDTO, ConfirmationFilterDTO> myConfirmationModel = new WTLazyDataModel<ConfirmationDTO, ConfirmationFilterDTO>(new ConfirmationFilterDTO(true)) { @Override public List<ConfirmationDTO> getData(ConfirmationFilterDTO confirmationFilterDTO) { return confirmationService.search(confirmationFilterDTO); } @Override public Long getCount(ConfirmationFilterDTO confirmationFilterDTO) { return confirmationService.getSearchCount(confirmationFilterDTO); } }; private WTLazyDataModel<WorkLogDTO, WorkLogFilterDTO> myWorkLogModel = new WTLazyDataModel<WorkLogDTO, WorkLogFilterDTO>(new WorkLogFilterDTO(true)) { @Override public List<WorkLogDTO> getData(WorkLogFilterDTO filter) { return workLogService.search(filter); } @Override public Long getCount(WorkLogFilterDTO filter) { return workLogService.searchCount(filter); } }; private WTLazyDataModel<WorkLogExportDTO, WorkLogExportFilterDTO> workLogExportModel = new WTLazyDataModel<WorkLogExportDTO, WorkLogExportFilterDTO>(new WorkLogExportFilterDTO()) { @Override public List<WorkLogExportDTO> getData(WorkLogExportFilterDTO workLogExportFilterDTO) { return workLogExportService.search(workLogExportFilterDTO); } @Override public Long getCount(WorkLogExportFilterDTO workLogExportFilterDTO) { return workLogExportService.searchCount(workLogExportFilterDTO); } }; private WTLazyDataModel<DocumentDTO, DocumentFilterDTO> myDocumentsModel = new WTLazyDataModel<DocumentDTO, DocumentFilterDTO>(new DocumentFilterDTO(true)) { @Override public List<DocumentDTO> getData(DocumentFilterDTO filter) { return docService.search(filter); } @Override public Long getCount(DocumentFilterDTO filter) { return docService.searchCount(filter); } }; private WTLazyDataModel<DocumentDTO, DocumentFilterDTO> allDocumentsModel = new WTLazyDataModel<DocumentDTO, DocumentFilterDTO>(new DocumentFilterDTO(false)) { @Override public List<DocumentDTO> getData(DocumentFilterDTO filter) { return docService.search(filter); } @Override public Long getCount(DocumentFilterDTO filter) { return docService.searchCount(filter); } }; } <file_sep>/server/src/main/java/edu/tuke/transform/generic/Transform.java package edu.tuke.transform.generic; import edu.tuke.entity.superclass.Persistent; import java.util.ArrayList; import java.util.List; public abstract class Transform<FROM, TO> { public abstract Class<TO> getClassTo(); public abstract void transform( FROM from, TO to); public TO transform( FROM from){ TO to = getNewToInstance(); transform( from, to); return to; } public void transform( List<FROM> liFrom, List<TO> liTo){ if(liFrom == null || liTo == null || liFrom.isEmpty() || liTo.isEmpty() || liFrom.size() != liTo.size()) throw new IllegalStateException("one of lists is null / empty or their size doesn't match"); for( int i = 0; i < liFrom.size(); i++){ FROM from = liFrom.get( i); TO to = liTo.get( i); transform( from, to); } } public List<TO> transform( List<FROM> liFrom){ if( liFrom == null || liFrom.isEmpty()) return new ArrayList<TO>(); List<TO> liTo = new ArrayList<TO>( liFrom.size()); for( FROM from: liFrom){ liTo.add( transform( from)); } return liTo; } private TO getNewToInstance(){ try{ return getClassTo().newInstance(); }catch(Exception e){} return null; } } <file_sep>/server/src/main/java/edu/tuke/dto/confirmation/DocumentTemplateDTO.java package edu.tuke.dto.confirmation; import edu.tuke.dto.dashboard.WorkLogDTO; import java.util.List; public class DocumentTemplateDTO { private List<WorkLogDTO> liWorkLog; public DocumentTemplateDTO(List<WorkLogDTO> liWorkLog) { this.liWorkLog = liWorkLog; } public String getHtml() { return null; } } <file_sep>/web/src/main/java/edu/tuke/Controller/RegistrationController.java package edu.tuke.controller; import edu.tuke.Facade; import edu.tuke.SelectItemConverter; import edu.tuke.dto.employees.RegistrationRequestDTO; import edu.tuke.dto.registration.EmployeeRegDTO; import edu.tuke.entity.enums.EmployeeTypeEnum; import edu.tuke.entity.enums.EmploymentTypeEnum; import edu.tuke.services.IRegistrationService; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import java.util.List; @ManagedBean @ViewScoped public class RegistrationController { private String uid; private IRegistrationService regService = Facade.getServiceByClass(IRegistrationService.class); private RegistrationRequestDTO regRequest; private EmployeeRegDTO employee; private List<SelectItem> liEmployeeType; private List<SelectItem> liEmploymentType; @PostConstruct public void init() { uid = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("req"); regRequest = regService.findByUid(uid); employee = new EmployeeRegDTO(); employee.setEmail(regRequest.getEmail()); employee.setIdEmployeeGroup(regRequest.getIdEmployeeGroup()); employee.setIdRegistration(regRequest.getId()); liEmployeeType = SelectItemConverter.convertEnum(EmployeeTypeEnum.values()); liEmploymentType = SelectItemConverter.convertEnum(EmploymentTypeEnum.values()); } public String register() { regService.register(employee); return "/login.jsf"; } public RegistrationRequestDTO getRegRequest() { return regRequest; } public EmployeeRegDTO getEmployee() { return employee; } public List<SelectItem> getLiEmployeeType() { return liEmployeeType; } public List<SelectItem> getLiEmploymentType() { return liEmploymentType; } } <file_sep>/server/src/main/java/edu/tuke/dto/settings/RoleRightDTO.java package edu.tuke.dto.settings; import edu.tuke.dto.AbstractDTO; import edu.tuke.entity.enums.RightEnum; import java.util.List; public class RoleRightDTO extends AbstractDTO<Long> { private String name; private List<RightEnum> liRight; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<RightEnum> getLiRight() { return liRight; } public void setLiRight(List<RightEnum> liRight) { this.liRight = liRight; } } <file_sep>/server/src/main/java/edu/tuke/dto/settings/EmployeeGroupDTO.java package edu.tuke.dto.settings; import edu.tuke.dto.AbstractDTO; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class EmployeeGroupDTO extends AbstractDTO<Long> { @NotNull @Size(min = 4, message = "Name must be at least 4 letter long.") private String name; @NotNull private Long roleId; private String roleName; @Min(value = 3, message = "Rate must be higher then 3.") private Double rate = 3.0D; public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public Double getRate() { return rate; } public void setRate(Double rate) { this.rate = rate; } } <file_sep>/server/src/main/java/edu/tuke/entity/enums/EmploymentTypeEnum.java package edu.tuke.entity.enums; import edu.tuke.entity.superclass.Displayable; import org.apache.commons.lang3.StringUtils; public enum EmploymentTypeEnum implements Displayable { DOHODA, ZIVNOST, TPP; @Override public String getDisplayName() { return StringUtils.capitalize(this.toString().toLowerCase()); } } <file_sep>/server/src/main/java/edu/tuke/services/IRegistrationService.java package edu.tuke.services; import edu.tuke.dto.employees.RegistrationRequestDTO; import edu.tuke.dto.registration.EmployeeRegDTO; public interface IRegistrationService { public RegistrationRequestDTO findByUid(String uid); public void register(EmployeeRegDTO employee); } <file_sep>/server/src/main/java/edu/tuke/services/impl/ConstantService.java package edu.tuke.services.impl; import edu.tuke.services.IConstantService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class ConstantService implements IConstantService { } <file_sep>/server/src/main/java/edu/tuke/services/impl/CompanyService.java package edu.tuke.services.impl; import edu.tuke.dao.AddressDAO; import edu.tuke.dao.CompanyDAO; import edu.tuke.dao.CompanyOwnerDAO; import edu.tuke.dto.ICOJsonDTO; import edu.tuke.dto.registration.CompanyDTO; import edu.tuke.dto.registration.CompanyOwnerDTO; import edu.tuke.entity.Address; import edu.tuke.entity.Company; import edu.tuke.entity.CompanyOwner; import edu.tuke.services.ICompanyService; import edu.tuke.transform.TransformFacade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class CompanyService implements ICompanyService { @Autowired private AddressDAO addressDAO; @Autowired private CompanyDAO companyDAO; @Autowired private CompanyOwnerDAO ownerDAO; @Override public void registerCompany(CompanyDTO companyDTO, CompanyOwnerDTO ownerDTO) { CompanyOwner owner = TransformFacade.companyOwnerDTO2E.transform(ownerDTO); Address ownerAddress = TransformFacade.addressDTO2E.transform(ownerDTO.getAddress()); Company company = TransformFacade.companyDTO2E.transform(companyDTO); Address companyAddress = TransformFacade.addressDTO2E.transform(ownerDTO.getAddress()); addressDAO.persist(ownerAddress); addressDAO.persist(companyAddress); owner.setAddress(ownerAddress); company.setAddress(companyAddress); ownerDAO.persist(owner); company.setOwner(owner); companyDAO.persist(company); owner.setCompany(company); ownerDAO.merge(owner); } @Override public ICOJsonDTO findByICO(String ico) { Company c = companyDAO.findByICO(ico); if (c != null) return TransformFacade.companyE2JSON.transform(c); else return null; } } <file_sep>/server/src/main/java/edu/tuke/entity/EmployeeGroup.java package edu.tuke.entity; import edu.tuke.entity.superclass.CompanySpecificEntity; import edu.tuke.entity.superclass.Persistent; import javax.persistence.*; import javax.validation.constraints.Size; import java.util.List; /** * <NAME> / <NAME> */ @Entity @Table( name="employee_group") public class EmployeeGroup extends CompanySpecificEntity implements Persistent<Long> { @Id @GeneratedValue( strategy = GenerationType.IDENTITY) private Long id; @Column private String name; @ManyToOne( fetch = FetchType.LAZY, optional = false) private Role role; @Column private Double rate; @OneToMany( fetch = FetchType.LAZY, mappedBy = "group") private List<Employee> liEmployee; 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 Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public Double getRate() { return rate; } public void setRate(Double rate) { this.rate = rate; } public List<Employee> getLiEmployee() { return liEmployee; } public void setLiEmployee(List<Employee> liEmployee) { this.liEmployee = liEmployee; } } <file_sep>/server/src/main/java/edu/tuke/entity/superclass/CompanySpecificEntity.java package edu.tuke.entity.superclass; import edu.tuke.entity.Company; import javax.persistence.*; /** * Abstraktna trieda pre tabulky, ktore obsahuje udaje specificke pre jednotlive firmy */ @MappedSuperclass public abstract class CompanySpecificEntity { @Column( name="id_company", updatable = false, insertable = false) private Long companyId; @ManyToOne( fetch = FetchType.LAZY, optional = false) @JoinColumn( name="id_company", referencedColumnName = "id") private Company company; public Long getCompanyId() { return companyId; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } } <file_sep>/server/src/main/java/edu/tuke/dto/registration/CompanyOwnerDTO.java package edu.tuke.dto.registration; public class CompanyOwnerDTO extends UserDTO { } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>edu.tuke</groupId> <artifactId>WTZadanie</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>server</module> <module>web</module> </modules> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.6</maven.compiler.source> <maven.compiler.target>1.6</maven.compiler.target> <org.springframework.version>3.1.3.RELEASE</org.springframework.version> </properties> <profiles> <profile> <id>PV</id> <properties> <projectEnvironment>src/config/pv</projectEnvironment> </properties> </profile> <profile> <id>PS</id> <properties> <projectEnvironment>src/config/ps</projectEnvironment> </properties> </profile> <profile> <id>MJ</id> <properties> <projectEnvironment>src/config/mj</projectEnvironment> </properties> </profile> </profiles> <dependencies> <!-- SPRING --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${org.springframework.version}</version> <exclusions> <exclusion> <artifactId>spring-aop</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-expression</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <!-- Jackson JSON Mapper --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${org.springframework.version}</version> <exclusions> <exclusion> <artifactId>spring-aop</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <!-- Bean validation --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency> <!-- json --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.2</version> </dependency> <!-- common --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>net.sourceforge.jocache</groupId> <artifactId>shiftone-cache</artifactId> <version>2.0b</version> </dependency> </dependencies> <repositories> <repository> <id>sonatype-repo</id> <name>The sonatype repository</name> <url>https://oss.sonatype.org/content/groups/public/</url> </repository> <repository> <id>repository.jboss.org-public</id> <name>JBoss repository</name> <url>https://repository.jboss.org/nexus/content/groups/public</url> </repository> <repository> <id>ebi-repo</id> <name>The EBI internal repository</name> <url>http://www.ebi.ac.uk/~maven/m2repo</url> </repository> <repository> <id>org.springframework.security.taglibs.facelets</id> <name>Spring security facelets taglibs</name> <url>http://spring-security-facelets-taglib.googlecode.com/svn/repo/</url> </repository> <repository> <id>prime-repo</id> <name>PrimeFaces Maven Repository</name> <url>http://repository.primefaces.org</url> <layout>default</layout> </repository> </repositories> </project><file_sep>/server/src/main/java/edu/tuke/dto/employees/EmployeeFullDTO.java package edu.tuke.dto.employees; import edu.tuke.dto.AbstractDTO; import edu.tuke.entity.enums.EmployeeTypeEnum; import edu.tuke.entity.enums.EmploymentTypeEnum; public class EmployeeFullDTO extends AbstractDTO<Long> { private String name; private String address; private String email; private Long idEmployeeGroup; private String employeeGroup; private EmployeeTypeEnum employeeType; private EmploymentTypeEnum employmentType; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getIdEmployeeGroup() { return idEmployeeGroup; } public void setIdEmployeeGroup(Long idEmployeeGroup) { this.idEmployeeGroup = idEmployeeGroup; } public String getEmployeeGroup() { return employeeGroup; } public void setEmployeeGroup(String employeeGroup) { this.employeeGroup = employeeGroup; } public EmployeeTypeEnum getEmployeeType() { return employeeType; } public void setEmployeeType(EmployeeTypeEnum employeeType) { this.employeeType = employeeType; } public EmploymentTypeEnum getEmploymentType() { return employmentType; } public void setEmploymentType(EmploymentTypeEnum employmentType) { this.employmentType = employmentType; } } <file_sep>/server/src/main/java/edu/tuke/dao/RoleDAO.java package edu.tuke.dao; import edu.tuke.dao.generic.CompanySpecificDAO; import edu.tuke.entity.Role; import edu.tuke.security.SecurityHelper; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class RoleDAO extends CompanySpecificDAO<Role, Long> { @Override public Class<Role> getEntityClass() { return Role.class; } public List<Role> listWithRights() { String query = "SELECT ro FROM Role ro " + "JOIN FETCH ro.rights ri " + "WHERE ro.company.id = :idCompany "; return em.createQuery(query, Role.class) .setParameter("idCompany", SecurityHelper.getIdCompany()) .getResultList(); } } <file_sep>/server/src/main/java/edu/tuke/dto/settings/RoleDTO.java package edu.tuke.dto.settings; import edu.tuke.dto.AbstractDTO; public class RoleDTO extends AbstractDTO<Long> { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/server/src/main/java/edu/tuke/dto/dashboard/WorkLogDTO.java package edu.tuke.dto.dashboard; import edu.tuke.dto.AbstractDTO; import edu.tuke.validation.InNonConfirmedRange; import edu.tuke.validation.NonZeroTime; import edu.tuke.validation.WorkLogValidation; import javax.validation.constraints.Past; import java.util.Date; @WorkLogValidation public class WorkLogDTO extends AbstractDTO<Long> { @InNonConfirmedRange @Past(message = "You cant log work in the future.") private Date date; @NonZeroTime private Date time; private String comment; private Long idEmployee; private String employeeName; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public Long getIdEmployee() { return idEmployee; } public void setIdEmployee(Long idEmployee) { this.idEmployee = idEmployee; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } } <file_sep>/server/src/main/java/edu/tuke/validation/WorkLogValidator.java package edu.tuke.validation; import edu.tuke.dao.WorkLogDAO; import edu.tuke.dto.dashboard.WorkLogDTO; import edu.tuke.entity.WorkLog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.support.SpringBeanAutowiringSupport; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.text.SimpleDateFormat; import java.util.List; public class WorkLogValidator implements ConstraintValidator<WorkLogValidation, WorkLogDTO> { @Autowired private WorkLogDAO workLogDAO; private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); @Override public void initialize(WorkLogValidation constraintAnnotation) { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); } @Override public boolean isValid(WorkLogDTO value, ConstraintValidatorContext context) { List<WorkLog> liWorkLog = workLogDAO.listByDateForCurrentEmployee(value.getDate()); Long sum = 0L; for (WorkLog log : liWorkLog) { if (!log.getId().equals(value.getId())) { String[] str = sdf.format(log.getTimeWorked()).split(":"); sum += Long.valueOf(str[0]) * 60; sum += Long.valueOf(str[1]); } } String[] str = sdf.format(value.getTime()).split(":"); sum += Long.valueOf(str[0]) * 60; sum += Long.valueOf(str[1]); return sum <= 24 * 60; } } <file_sep>/server/src/main/java/edu/tuke/services/impl/EmployeeGroupService.java package edu.tuke.services.impl; import edu.tuke.dao.EmployeeGroupDAO; import edu.tuke.dao.RoleDAO; import edu.tuke.dto.settings.EmployeeGroupDTO; import edu.tuke.entity.EmployeeGroup; import edu.tuke.services.IEmployeeGroupService; import edu.tuke.transform.TransformFacade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class EmployeeGroupService implements IEmployeeGroupService { @Autowired private RoleDAO roleDAO; @Autowired private EmployeeGroupDAO employeeGroupDAO; @Override public List<EmployeeGroupDTO> listEmployeeGroups() { return TransformFacade.employeeGroupE2DTO .transform(employeeGroupDAO.list()); } @Override public void saveEmployeeGroup(EmployeeGroupDTO dto) { EmployeeGroup e; if (dto.getId() == null) e = new EmployeeGroup(); else e = employeeGroupDAO.find(dto.getId()); e.setRole(roleDAO.find(dto.getRoleId())); TransformFacade.employeeGroupDTO2E.transform(dto, e); employeeGroupDAO.saveOrUpdate(e); } } <file_sep>/server/src/main/java/edu/tuke/dao/DocumentDAO.java package edu.tuke.dao; import edu.tuke.dao.generic.EmployeeSpecificDAO; import edu.tuke.entity.Company; import edu.tuke.entity.Document; import edu.tuke.entity.Employee; import edu.tuke.entity.WorkLogExport; import edu.tuke.entity.enums.DocumentTypeEnum; import edu.tuke.filter.dashboard.DocumentFilterDTO; import edu.tuke.security.SecurityHelper; import org.springframework.stereotype.Repository; import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @Repository public class DocumentDAO extends EmployeeSpecificDAO<Document, Long> { @Override public Class<Document> getEntityClass() { return Document.class; } public List<Document> search(DocumentFilterDTO filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Document> query = cb.createQuery(Document.class); Root<Document> root = query.from(Document.class); makePredicates(query, root, filter); makeOrder(query, root, filter); query.distinct(true); query.select(root); return em.createQuery(query) .setFirstResult(filter.getFirst()) .setMaxResults(filter.getSize()) .getResultList(); } public Long searchCount(DocumentFilterDTO filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> query = cb.createQuery(Long.class); Root<Document> root = query.from(Document.class); makePredicates(query, root, filter); query.select(cb.countDistinct(root)); return em.createQuery(query) .getSingleResult(); } private void makePredicates(CriteriaQuery<?> query, Root<Document> root, DocumentFilterDTO filter) { List<Predicate> liPredicate = new ArrayList<Predicate>(); CriteriaBuilder cb = em.getCriteriaBuilder(); Expression<Long> cId = root.<Employee>get("employee").<Company>get("company").<Long>get("id"); liPredicate.add(cb.equal(cId, SecurityHelper.getIdCompany())); if (filter.getLiIdEmployee() != null && !filter.getLiIdEmployee().isEmpty()) { Expression<Long> exp = root.<Employee>get("employee").<Long>get("id"); liPredicate.add(exp.in(filter.getLiIdEmployee())); } if (filter.getFrom() != null) { Expression<Date> exp = root.<WorkLogExport>get("export").<Date>get("exportFrom"); liPredicate.add(cb.greaterThanOrEqualTo(exp, filter.getFrom())); } if (filter.getTo() != null) { Expression<Date> exp = root.<WorkLogExport>get("export").<Date>get("exportTo"); liPredicate.add(cb.lessThanOrEqualTo(exp, filter.getTo())); } if (filter.getType() != null) { Expression<DocumentTypeEnum> exp = root.<DocumentTypeEnum>get("type"); liPredicate.add(cb.equal(exp, filter.getType())); } query.where(liPredicate.toArray(new Predicate[liPredicate.size()])); } private void makeOrder(CriteriaQuery<?> query, Root<Document> root, DocumentFilterDTO filter) { } } <file_sep>/server/src/main/java/edu/tuke/validation/InNonConfirmedRange.java package edu.tuke.validation; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; @Constraint(validatedBy = {InNonConfirmedRangeValidator.class}) @Documented @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface InNonConfirmedRange { String message() default "Time range already exported."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } <file_sep>/server/src/main/java/edu/tuke/dto/export/ExportDetailDTO.java package edu.tuke.dto.export; import edu.tuke.dto.AbstractDTO; import edu.tuke.dto.dashboard.ConfirmationDTO; import java.util.Date; import java.util.List; public class ExportDetailDTO extends AbstractDTO<Long> { private Date from; private Date to; private List<ConfirmationDTO> liConfirmation; private List<DocumentDTO> liDocument; public Date getFrom() { return from; } public void setFrom(Date from) { this.from = from; } public Date getTo() { return to; } public void setTo(Date to) { this.to = to; } public List<ConfirmationDTO> getLiConfirmation() { return liConfirmation; } public void setLiConfirmation(List<ConfirmationDTO> liConfirmation) { this.liConfirmation = liConfirmation; } public List<DocumentDTO> getLiDocument() { return liDocument; } public void setLiDocument(List<DocumentDTO> liDocument) { this.liDocument = liDocument; } } <file_sep>/web/src/main/java/edu/tuke/security/LoginBean.java package edu.tuke.security; import edu.tuke.Facade; import edu.tuke.dto.registration.CompanyDTO; import edu.tuke.dto.registration.CompanyOwnerDTO; import edu.tuke.services.ICompanyService; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.IOException; import java.io.Serializable; @ManagedBean @ViewScoped public class LoginBean implements Serializable { private String userName; private String password; private ICompanyService companyService = Facade.getServiceByClass(ICompanyService.class); private CompanyDTO company = new CompanyDTO(); private CompanyOwnerDTO ownerDTO = new CompanyOwnerDTO(); public void registerCompany() { companyService.registerCompany(company, ownerDTO); } public String login() { try { ExternalContext context = FacesContext.getCurrentInstance() .getExternalContext(); ServletRequest request = ((ServletRequest) context.getRequest()); RequestDispatcher dispatcher = request .getRequestDispatcher("/j_spring_security_check"); dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse()); FacesContext.getCurrentInstance().responseComplete(); return "/jsf/dashboard.jsf"; } catch (Exception e) { e.printStackTrace(); } return ""; } public String logout() throws ServletException, IOException { ExternalContext context = FacesContext.getCurrentInstance() .getExternalContext(); ServletRequest request = (ServletRequest) context.getRequest(); String ip = request.getRemoteAddr(); FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); RequestDispatcher dispatcher = request .getRequestDispatcher("/j_spring_security_logout"); dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse()); FacesContext.getCurrentInstance().responseComplete(); return "/login.jsf"; } public String getPrincipal() { return SecurityHelper.getPrincipal().getUsername(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public CompanyDTO getCompany() { return company; } public void setCompany(CompanyDTO company) { this.company = company; } public CompanyOwnerDTO getOwnerDTO() { return ownerDTO; } public void setOwnerDTO(CompanyOwnerDTO ownerDTO) { this.ownerDTO = ownerDTO; } } <file_sep>/server/src/main/java/edu/tuke/security/SecurityHelper.java package edu.tuke.security; import edu.tuke.entity.enums.RightEnum; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; public class SecurityHelper { public static UserInfo getPrincipal(){ if (SecurityContextHolder.getContext().getAuthentication() ==null) return null; Object o = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if ( o != null && !(o instanceof UserInfo) ) throw new IllegalStateException("Principal must be instance of UserInfo, p = " + o); return (UserInfo) o; } public static Long getIdEmployee(){ return getPrincipal().getId(); } public static Boolean hasRight( RightEnum right){ for( GrantedAuthority auth: getPrincipal().getAuthorities()){ if( auth.getAuthority().equalsIgnoreCase( right.toString())) return true; } return false; } public static Long getIdCompany(){ return getPrincipal().getCompanyId(); } } <file_sep>/server/src/main/java/edu/tuke/dto/employees/RegistrationRequestDTO.java package edu.tuke.dto.employees; import edu.tuke.dto.AbstractDTO; import edu.tuke.entity.enums.RegistrationStatusEnum; public class RegistrationRequestDTO extends AbstractDTO<Long> { private String email; private RegistrationStatusEnum status; private Long idEmployeeGroup; private String employeeGroup; private Long idCompany; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public RegistrationStatusEnum getStatus() { return status; } public void setStatus(RegistrationStatusEnum status) { this.status = status; } public Long getIdEmployeeGroup() { return idEmployeeGroup; } public void setIdEmployeeGroup(Long idEmployeeGroup) { this.idEmployeeGroup = idEmployeeGroup; } public String getEmployeeGroup() { return employeeGroup; } public void setEmployeeGroup(String employeeGroup) { this.employeeGroup = employeeGroup; } } <file_sep>/server/src/main/java/edu/tuke/dao/EmployeeDAO.java package edu.tuke.dao; import edu.tuke.dao.generic.CompanySpecificDAO; import edu.tuke.entity.Address; import edu.tuke.entity.Company; import edu.tuke.entity.Employee; import edu.tuke.entity.EmployeeGroup; import edu.tuke.entity.enums.EmployeeTypeEnum; import edu.tuke.entity.enums.EmploymentTypeEnum; import edu.tuke.filter.employees.EmployeeFilterDTO; import edu.tuke.security.SecurityHelper; import org.springframework.stereotype.Repository; import javax.persistence.NoResultException; import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.List; @Repository public class EmployeeDAO extends CompanySpecificDAO<Employee, Long> { @Override public Class<Employee> getEntityClass() { return Employee.class; } public List<Employee> search(EmployeeFilterDTO employeeFilterDTO) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> query = cb.createQuery(Employee.class); Root<Employee> root = query.from(Employee.class); Fetch<Employee, Address> addrFetch = root.fetch("address"); Fetch<Employee, EmployeeGroup> emplGroupFetch = root.fetch("group"); makePredicates(query, root, employeeFilterDTO); makeSort(query, root, employeeFilterDTO); query.distinct(true); query.select(root); return em.createQuery(query) .setFirstResult(employeeFilterDTO.getFirst()) .setMaxResults(employeeFilterDTO.getSize()) .getResultList(); } public Long searchCount(EmployeeFilterDTO employeeFilterDTO) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> query = cb.createQuery(Long.class); Root<Employee> root = query.from(Employee.class); makePredicates(query, root, employeeFilterDTO); query.select(cb.countDistinct(root)); return em.createQuery(query) .getSingleResult(); } private void makePredicates(CriteriaQuery<?> query, Root<Employee> root, EmployeeFilterDTO filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); List<Predicate> liPredicate = new ArrayList<Predicate>(); liPredicate.add(cb.equal( root.<Company>get("company").<Long>get("id"), SecurityHelper.getIdCompany())); liPredicate.add(cb.equal( root.<Boolean>get("active"), true)); if (filter.getEmail() != null && !filter.getEmail().isEmpty()) { Expression<String> exp = root.<String>get("email"); liPredicate.add(cb.like(exp, "%" + filter.getEmail() + "%")); } if (filter.getName() != null && !filter.getName().isEmpty()) { for (String part : filter.getName().split(" ")) { Expression<String> exp1 = root.<String>get("prefix"); Expression<String> exp2 = root.<String>get("firstname"); Expression<String> exp3 = root.<String>get("lastname"); liPredicate.add(cb.or( cb.like(exp1, "%" + part + "%"), cb.like(exp2, "%" + part + "%"), cb.like(exp3, "%" + part + "%"))); } } if (filter.getEmploymentType() != null) { Expression<EmploymentTypeEnum> exp = root.<EmploymentTypeEnum>get("type"); liPredicate.add(cb.equal(exp, filter.getEmploymentType())); } if (filter.getEmployeeType() != null) { Expression<EmployeeTypeEnum> exp = root.<EmployeeTypeEnum>get("employeeType"); liPredicate.add(cb.equal(exp, filter.getEmployeeType())); } query.where(liPredicate.toArray(new Predicate[liPredicate.size()])); } private void makeSort(CriteriaQuery<?> query, Root<Employee> root, EmployeeFilterDTO filter) { if (filter.getSortField() != null && !filter.getSortField().isEmpty()) { Path<?> sortPath = null; CriteriaBuilder cb = em.getCriteriaBuilder(); String sortField = filter.getSortField(); if (sortField.equalsIgnoreCase("name")) { sortPath = root.<String>get("lastname"); } else if (sortField.equalsIgnoreCase("address")) { sortPath = root.<Address>get("address").<String>get("street"); } else if (sortField.equalsIgnoreCase("email")) { sortPath = root.<String>get("email"); } if (sortPath != null) { if (filter.getAscending()) { query.orderBy(cb.asc(sortPath)); } else { query.orderBy(cb.desc(sortPath)); } } } } public Employee findByICO(String ico) { String query = "SELECT e FROM Employee e " + "WHERE e.ico = :ico"; try { return em.createQuery(query, Employee.class) .setParameter("ico", ico) .getSingleResult(); } catch (NoResultException e) { return null; } } } <file_sep>/server/src/main/java/edu/tuke/dao/ConfirmationRequestDAO.java package edu.tuke.dao; import edu.tuke.dao.generic.EmployeeSpecificDAO; import edu.tuke.entity.Company; import edu.tuke.entity.ConfirmationRequest; import edu.tuke.entity.Employee; import edu.tuke.entity.WorkLogExport; import edu.tuke.entity.enums.ConfirmationStatusEnum; import edu.tuke.filter.dashboard.ConfirmationFilterDTO; import edu.tuke.security.SecurityHelper; import org.springframework.stereotype.Repository; import javax.persistence.NoResultException; import javax.persistence.criteria.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; @Repository public class ConfirmationRequestDAO extends EmployeeSpecificDAO<ConfirmationRequest, Long> { private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); @Override public Class<ConfirmationRequest> getEntityClass() { return ConfirmationRequest.class; } public List<ConfirmationRequest> search(ConfirmationFilterDTO filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ConfirmationRequest> query = cb.createQuery(ConfirmationRequest.class); Root<ConfirmationRequest> root = query.from(ConfirmationRequest.class); Fetch<ConfirmationRequest, Employee> empFetch = root.fetch("employee"); Fetch<ConfirmationRequest, WorkLogExport> expFetch = root.fetch("export"); makePredicates(query, root, filter); if (filter.getSortField() != null) { Path<?> sortPath = null; if (filter.getSortField().equalsIgnoreCase("employeeName")) { sortPath = root.<Employee>get("employee").<String>get("lastname"); } else if (filter.getSortField().equalsIgnoreCase("from")) { sortPath = root.<WorkLogExport>get("export").<Date>get("exportFrom"); } else if (filter.getSortField().equalsIgnoreCase("to")) { sortPath = root.<WorkLogExport>get("export").<Date>get("exportTo"); } else if (filter.getSortField().equalsIgnoreCase("status")) { sortPath = root.<ConfirmationStatusEnum>get("status"); } if (filter.getAscending()) { query.orderBy(cb.asc(sortPath)); } else { query.orderBy(cb.desc(sortPath)); } } query.distinct(true); query.select(root); return em.createQuery(query) .setFirstResult(filter.getFirst()) .setMaxResults(filter.getSize()) .getResultList(); } public Long searchCount(ConfirmationFilterDTO filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> query = cb.createQuery(Long.class); Root<ConfirmationRequest> root = query.from(ConfirmationRequest.class); makePredicates(query, root, filter); query.select(cb.countDistinct(root)); return em.createQuery(query) .getSingleResult(); } private void makePredicates(CriteriaQuery<?> query, Root<ConfirmationRequest> root, ConfirmationFilterDTO filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); List<Predicate> liPredicate = new ArrayList<Predicate>(); Expression<Long> cId = root.<Employee>get("employee").<Company>get("company").<Long>get("id"); liPredicate.add(cb.equal(cId, SecurityHelper.getIdCompany())); if (filter.getStatus() != null) { Expression<ConfirmationStatusEnum> p = root.<ConfirmationStatusEnum>get("status"); liPredicate.add(cb.equal(p, filter.getStatus())); } if (filter.getEmployeeId() != null && !filter.getEmployeeId().isEmpty()) { Expression<Long> p = root.<Employee>get("employee").<Long>get("id"); liPredicate.add(p.in(filter.getEmployeeId())); } if (filter.getFrom() != null) { Expression<Date> p = root.<WorkLogExport>get("export").<Date>get("exportFrom"); liPredicate.add(cb.greaterThanOrEqualTo(p, filter.getFrom())); } if (filter.getTo() != null) { Expression<Date> p = root.<WorkLogExport>get("export").<Date>get("exportTo"); liPredicate.add(cb.lessThanOrEqualTo(p, filter.getTo())); } query.where(liPredicate.toArray(new Predicate[liPredicate.size()])); } public ConfirmationRequest findByDateForCurrentUser(Date value) { try { String query = "SELECT c FROM ConfirmationRequest c " + "WHERE c.employee.id = :employeeId " + "AND c.export.exportFrom <= :date " + "AND c.export.exportTo >= :date"; return em.createQuery(query, ConfirmationRequest.class) .setParameter("employeeId", SecurityHelper.getIdEmployee()) .setParameter("date", value) .getSingleResult(); } catch (NoResultException e) { return null; } } public Long getTimeWorked(Date from, Date to, Long idEmployee) { String query = "SELECT w.timeWorked FROM WorkLog w " + "WHERE w.employee.id = :idEmployee " + "AND w.date BETWEEN :from AND :to"; List<Date> liDate = em.createQuery(query, Date.class) .setParameter("idEmployee", idEmployee) .setParameter("from", from) .setParameter("to", to) .getResultList(); Long sum = 0L; for (Date date : liDate) { String[] str = sdf.format(date).split(":"); sum += Long.valueOf(str[0]) * 60; sum += Long.valueOf(str[1]); } return sum; } public Long countByStatus(ConfirmationStatusEnum status) { String sql = "SELECT COUNT(c) FROM ConfirmationRequest c " + "WHERE c.status = :status AND c.employee.id = :idEmployee"; return em.createQuery(sql, Long.class) .setParameter("idEmployee", SecurityHelper.getIdEmployee()) .setParameter("status", status) .getSingleResult(); } } <file_sep>/README.md WTZadanie ========= <file_sep>/server/src/main/java/edu/tuke/transform/e2dto/WorkLogExportE2DTO.java package edu.tuke.transform.e2dto; import edu.tuke.dto.dashboard.WorkLogExportDTO; import edu.tuke.entity.ConfirmationRequest; import edu.tuke.entity.WorkLogExport; import edu.tuke.entity.enums.ConfirmationStatusEnum; import edu.tuke.transform.generic.Transform; public class WorkLogExportE2DTO extends Transform<WorkLogExport, WorkLogExportDTO> { @Override public Class<WorkLogExportDTO> getClassTo() { return WorkLogExportDTO.class; } @Override public void transform(WorkLogExport e, WorkLogExportDTO dto) { dto.setId(e.getId()); dto.setFrom(e.getExportFrom()); dto.setTo(e.getExportTo()); dto.setTimestamp(e.getTimestamp()); dto.setConfCount(e.getLiConfirmationRequest().size()); dto.setDocCount(e.getLiDocument().size()); // ByMJ. Integer pendingCount = 0; for (ConfirmationRequest confirmationRequest : e.getLiConfirmationRequest()) { if (confirmationRequest.getStatus() == ConfirmationStatusEnum.PENDING) { pendingCount++; } } dto.setPendingCount(pendingCount); } } <file_sep>/server/src/main/java/edu/tuke/services/ITestEntityService.java package edu.tuke.services; import edu.tuke.dto.TestDTO; import edu.tuke.entity.test.TestEntity; import java.util.List; @Deprecated public interface ITestEntityService { public Long saveEntity( TestDTO dto); public TestDTO getEntity( Long idEntity); public List<TestDTO> listEntity(); public void removeEntity( TestDTO dto); public Long getEntityCount(); } <file_sep>/server/src/main/java/edu/tuke/services/IConfirmationService.java package edu.tuke.services; import edu.tuke.docs.DocumentTemplate; import edu.tuke.dto.dashboard.ConfirmationDTO; import edu.tuke.filter.dashboard.ConfirmationFilterDTO; import java.util.List; public interface IConfirmationService { public List<ConfirmationDTO> search(ConfirmationFilterDTO filter); public Long getSearchCount(ConfirmationFilterDTO filter); public ConfirmationDTO findById(Long id); public void confirm(ConfirmationDTO confirmation, DocumentTemplate doc); public DocumentTemplate getDocument(ConfirmationDTO conf); public Long getPendingCount(); } <file_sep>/server/src/main/java/edu/tuke/dto/registration/UserDTO.java package edu.tuke.dto.registration; import edu.tuke.dto.AbstractDTO; import edu.tuke.validation.Email; import edu.tuke.validation.Telephone; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; public abstract class UserDTO extends AbstractDTO<Long> { private String prefix; @NotNull private String firstname; @NotNull private String lastname; @Email(optional = false) private String email; @Length(min = 6) private String password; @Telephone private String telephone; private AddressDTO address = new AddressDTO(); public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public AddressDTO getAddress() { return address; } public void setAddress(AddressDTO address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } } <file_sep>/server/src/main/java/edu/tuke/transform/e2dto/TestE2DTO.java package edu.tuke.transform.e2dto; import edu.tuke.dto.TestDTO; import edu.tuke.entity.test.TestEntity; import edu.tuke.transform.generic.Transform; public class TestE2DTO extends Transform<TestEntity, TestDTO> { @Override public Class<TestDTO> getClassTo() { return TestDTO.class; } @Override public void transform(TestEntity e, TestDTO dto) { dto.setId( e.getId()); dto.setName( e.getName()); dto.setEnumerated( e.getEnumerated()); dto.setDate( e.getDate()); } } <file_sep>/server/src/main/java/edu/tuke/entity/Employee.java package edu.tuke.entity; import edu.tuke.entity.enums.EmployeeTypeEnum; import edu.tuke.entity.enums.EmploymentTypeEnum; import javax.persistence.*; import java.util.List; /** * User zamestnanec */ @Entity @DiscriminatorValue(value = "EMPLOYEE") public class Employee extends User { @ManyToOne(fetch = FetchType.LAZY) private EmployeeGroup group; @Column(name = "bank_account") private String bankAccount; @Column private Boolean active; @Column private Boolean ztp; @Column(name = "obchodne_meno") private String obchodneMeno; @Column private String ico; @Column private String dic; @Column(name = "trade_item") String tradeItem; @Enumerated(EnumType.STRING) @Column private EmploymentTypeEnum type; @Enumerated(EnumType.STRING) @Column(name = "employee_type") private EmployeeTypeEnum employeeType; @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee") private List<Document> liDocument; public EmployeeGroup getGroup() { return group; } public void setGroup(EmployeeGroup group) { this.group = group; } public String getBankAccount() { return bankAccount; } public void setBankAccount(String bankAccount) { this.bankAccount = bankAccount; } public EmploymentTypeEnum getType() { return type; } public void setType(EmploymentTypeEnum type) { this.type = type; } public List<Document> getLiDocument() { return liDocument; } public void setLiDocument(List<Document> liDocument) { this.liDocument = liDocument; } public EmployeeTypeEnum getEmployeeType() { return employeeType; } public void setEmployeeType(EmployeeTypeEnum employeeType) { this.employeeType = employeeType; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public Boolean getZtp() { return ztp; } public void setZtp(Boolean ztp) { this.ztp = ztp; } public String getObchodneMeno() { return obchodneMeno; } public void setObchodneMeno(String obchodneMeno) { this.obchodneMeno = obchodneMeno; } public String getIco() { return ico; } public void setIco(String ico) { this.ico = ico; } public String getDic() { return dic; } public void setDic(String dic) { this.dic = dic; } public String getTradeItem() { return tradeItem; } public void setTradeItem(String tradeItem) { this.tradeItem = tradeItem; } } <file_sep>/server/src/main/java/edu/tuke/entity/test/TestEntity.java package edu.tuke.entity.test; import edu.tuke.entity.superclass.Persistent; import javax.persistence.*; import java.util.Date; @Entity @Table( name="test_entity") @Deprecated public class TestEntity implements Persistent<Long> { @Id @GeneratedValue( strategy = GenerationType.IDENTITY) private Long id; @Column( name = "name") private String name; @Column( name = "creation_date") @Temporal( TemporalType.DATE) private Date date; @Column( name = "enumerated") @Enumerated( EnumType.STRING) private TestEnum enumerated; public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public TestEnum getEnumerated() { return enumerated; } public void setEnumerated(TestEnum enumerated) { this.enumerated = enumerated; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } <file_sep>/server/src/main/java/edu/tuke/filter/employees/EmployeeFilterDTO.java package edu.tuke.filter.employees; import edu.tuke.entity.enums.EmployeeTypeEnum; import edu.tuke.entity.enums.EmploymentTypeEnum; import edu.tuke.filter.AbstractFilterDTO; public class EmployeeFilterDTO extends AbstractFilterDTO { private String name; private String email; private Long workGroupId; private EmployeeTypeEnum employeeType; private EmploymentTypeEnum employmentType; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getWorkGroupId() { return workGroupId; } public void setWorkGroupId(Long workGroupId) { this.workGroupId = workGroupId; } public EmployeeTypeEnum getEmployeeType() { return employeeType; } public void setEmployeeType(EmployeeTypeEnum employeeType) { this.employeeType = employeeType; } public EmploymentTypeEnum getEmploymentType() { return employmentType; } public void setEmploymentType(EmploymentTypeEnum employmentType) { this.employmentType = employmentType; } } <file_sep>/server/src/config/MJ/enviroment.properties application.context=http://localhost:8080/ZadanieWT/ jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/zadwt jdbc.username=root jdbc.password=<PASSWORD> <file_sep>/server/src/main/java/edu/tuke/dto/AbstractDTO.java package edu.tuke.dto; import edu.tuke.entity.superclass.Persistent; public abstract class AbstractDTO<ID> implements Persistent<ID> { private ID id; public ID getId() { return id; } public void setId(ID id) { this.id = id; } } <file_sep>/server/src/main/java/edu/tuke/dto/dashboard/WorkLogExportDTO.java package edu.tuke.dto.dashboard; import edu.tuke.dto.AbstractDTO; import edu.tuke.entity.enums.ConfirmationStatusEnum; import java.util.Date; public class WorkLogExportDTO extends AbstractDTO<Long> { private Date from; private Date to; private ConfirmationStatusEnum status; private Long id; private Date timestamp; private Integer docCount; private Integer confCount; private Integer pendingCount; // ByMJ. public Date getFrom() { return from; } public void setFrom(Date from) { this.from = from; } public Date getTo() { return to; } public void setTo(Date to) { this.to = to; } public ConfirmationStatusEnum getStatus() { return status; } public void setStatus(ConfirmationStatusEnum status) { this.status = status; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Integer getDocCount() { return docCount; } public void setDocCount(Integer docCount) { this.docCount = docCount; } public Integer getConfCount() { return confCount; } public void setConfCount(Integer confCount) { this.confCount = confCount; } // ByMJ. public Integer getPendingCount() { return pendingCount; } // ByMJ. public void setPendingCount(Integer pendingCount) { this.pendingCount = pendingCount; } } <file_sep>/server/src/main/java/edu/tuke/entity/enums/DocumentTypeEnum.java package edu.tuke.entity.enums; import edu.tuke.entity.superclass.Displayable; import org.apache.commons.lang3.StringUtils; public enum DocumentTypeEnum implements Displayable { INVOICE, PAYSLIP; @Override public String getDisplayName() { return StringUtils.capitalize(this.toString().toLowerCase()); } } <file_sep>/server/src/config/pv/data.sql -- 6.11.2013 Testovaci pouzivatel + jeho company, username: <EMAIL>, pass: <PASSWORD> alter table user modify group_id BIGINT(9) DEFAULT NULL; insert into address values( NULL, 'Test', '25 A', 'Testovacia', '000 00'); set @address = LAST_INSERT_ID(); insert into user values( 'OWNER', NULL, NULL, '<EMAIL>', 'Test', 'Testovsky', 1, '0908 000 999', 'Ing.', NULL, NULL, @address, NULL, 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'); set @owner = LAST_INSERT_ID(); insert into company values( NULL, NULL, NULL, NULL, 'Test company', @address, @owner); update user set id_company = LAST_INSERT_ID() where id = @owner;<file_sep>/server/src/main/java/edu/tuke/transform/dto2e/CompanyDTO2E.java package edu.tuke.transform.dto2e; import edu.tuke.dto.registration.CompanyDTO; import edu.tuke.entity.Company; import edu.tuke.transform.generic.Transform; public class CompanyDTO2E extends Transform<CompanyDTO, Company> { @Override public Class<Company> getClassTo() { return Company.class; } @Override public void transform(CompanyDTO companyDTO, Company company) { company.setId(companyDTO.getId()); company.setName(companyDTO.getName()); company.setIco(companyDTO.getRegNo()); company.setDic(companyDTO.getTaxNo()); } }
0f32308769b91f2b83e1bd158426ae17b56ead7b
[ "SQL", "Markdown", "Maven POM", "INI", "Java" ]
67
Java
pvytykac/WTZadanie
e660dfb8835a6accfd6e1a37364f4ac82fda52fa
4b748e421efdc8bb933861b55ffe527665b4c53a
refs/heads/main
<repo_name>ishika3/code-2<file_sep>/guideline7.py def fib(n): if n==0: return 0 elif n==1: return 1 else: return fib(n-1)+fib(n-2) def main(): n=int(input("enter number")) print("the series:",end='') for i in range(0,n+1): result=fib(i) print(result,end=',') #driver code if __name__=="__main__": main()
67b7444b5a0d09ccd0aebfea52c7d14fed17aa37
[ "Python" ]
1
Python
ishika3/code-2
0249c4274051822e673c4f6c4cdb2279cfd9e6fc
1b0c10ba142ce24bf8713d3777179785ccd53321
refs/heads/master
<repo_name>digpads/hunliji_projectMax<file_sep>/app/components/Main/Sider/index.jsx import React, {Component} from 'react' import {Link, IndexLink} from 'react-router' import {message, Icon, Menu} from 'antd' import styles from './style.css' const SubMenu = Menu.SubMenu; export default class extends Component { constructor(props) { super(props) this.state = { selected: this.props.pathname } } componentWillReceiveProps(nextProps) { let pathname=nextProps.pathname if(this.state.selected!==pathname){ this.setState({ selected: nextProps.pathname }) } } render() { let {selected} = this.state let ser = selected.split('/')[2]||'' let current = '/' + ser return ( <Menu className={styles.sider} style={{zIndex:1000}} defaultOpenKeys={[current]} selectedKeys={[current]} mode="inline" theme="dark" > <Menu.Item key="/"> <IndexLink to="/hunliji"><Icon type="home"/>首页</IndexLink> </Menu.Item> <SubMenu key="/FeedBack" title={<span><Icon type="solution" />产品运营</span>}> <Menu.Item key="/FeedBack"> <Link to="/hunliji/FeedBack">用户反馈</Link> </Menu.Item> </SubMenu> <SubMenu key="/MerchantTopic" title={<span><Icon type="team" />商家运营</span>}> <Menu.Item key="/MerchantTopic"> <Link to="/hunliji/MerchantTopic">商家活动/专题</Link> </Menu.Item> </SubMenu> <SubMenu key="/substance" title={<span><Icon type="appstore-o"/>内容运营</span>}> <Menu.Item key="/ThemeList"> <Link to="/hunliji/ThemeList">内容编辑</Link> </Menu.Item> <Menu.Item key="/substance"> <Link to="/hunliji/substance">专题页面</Link> </Menu.Item> </SubMenu> </Menu> ); } }<file_sep>/app/components/Substance/List/Tab/Chosen/index.js import React, {Component} from 'react' import styles from './style.css' import {Table, Button, message,Select,Modal} from 'antd' import {hashHistory} from 'react-router' import getColumns from './columns' import Api from '../../../../../api/zhi_shui/substanceApi' const Option=Select.Option const confirm=Modal.confirm export default class extends Component { state = { data: [], loading: false, type:'1', pagination: { showQuickJumper: true, showTotal: total => `共 ${total} 条`, // showSizeChanger: true, current: 1, pageSize:20,//后端固定的每页20条 total:0 } } search=async (current=1)=>{ this.setState({ loading:true }) let {data}=await Api.search_topic() this.setState({ loading:false, data }) } //删除记录 del = (id,isActivate)=> { if(isActivate){ return message.warning('请先取消激活再进行删除!',2) } confirm({ title: '您确认要删除这项内容吗?', onOk: ()=> { console.log(`删除id为${id}的记录`) } }) } //分页,排序,删选发生变化时的操作 handleTableChange = ({current})=> { this.search(current) } /* 点击新建专题或者编辑专题,跳转到专题路由界面 如果id存在表示是编辑专题,不存在就是新建专题 */ goToSpecialTopic=(id)=>{ hashHistory.push({ pathname:'/hunliji/substance/specialTopic/'+id, query:{ type:'edit' } }) } //选择分类 selectType = (type)=> { this.setState({type}, ()=> { this.search(this.state.pagination.current) }) } componentDidMount() { this.search() } render() { let { data, loading, pagination,type }=this.state return ( <div className={styles.container}> <div className={styles.tbar}> <div className={styles.action_type}> <Select showSearch placeholder="选择分类" style={{width:100}} onChange={this.selectType} value={type}> <Option value="1">结婚故事</Option> <Option value="2">创意婚礼</Option> <Option value="3">备婚干货</Option> <Option value="4">婚假话题</Option> </Select> </div> </div> <Table columns={getColumns(this)} dataSource={data} loading={loading} pagination={pagination} onChange={this.handleTableChange} rowKey={record => record.id} /> </div> ) } }<file_sep>/app/actions/types/substance.type.js //作为约定,为了区分,type常量前都加上_,并且都要写上注释(都为大写的话看起来不方便) //专题列表的action常量 export const _searchTopic='_searchTopic' export const _topicLoading='_topicLoading' export const _addToRefined='_addToRefined' export const _selectTopicCategory='_selectTopicCategory' export const _topicPaginationHandle='_topicPaginationHandle' //条件改变 export const _changeCondition='_changeCondition' export const _resetSearchParams='_resetSearchParams' //精选话题的action常量<file_sep>/app/actions/substance/index.js import * as types from '../types/substance.type' import Api from '../../api/zhi_shui/substanceApi' /* 专题列表actions */ //搜索专题列表 export const searchTopic=()=>async (dispatch,getState)=>{ //收集搜索条件 let params=getState().searchParams params.category=getState().topic.category params.page=getState().topic.pagination.current params.per_page=getState().topic.pagination.pageSize console.log('搜索条件为:',params) params=`page=${params.page}&per_page=${params.per_page}` dispatch({ type:types._topicLoading, loading:true }) let {data:{list=[],total_count}}=await Api.search_topicApi(params) dispatch({ type:types._topicLoading, loading:false }) dispatch({ type:types._searchTopic, data:list, total:total_count*1 }) } //专题列表分页处理 export const topicPaging=({current,pageSize})=>(dispatch,getState)=>{ dispatch({ type:types._topicPaginationHandle, current, pageSize }) searchTopic()(dispatch,getState) } //专题置顶或者取消置顶 export const stick=params=>async (dispatch,getState)=>{ await Api.stick_topicApi(params) //置顶或者取消置顶再搜索 searchTopic()(dispatch,getState) } //是否全局可见和是否激活 export const activeGlobalHandle=params=>async (dispatch,getState)=>{ await Api.set_activeGlobalApi(params) searchTopic()(dispatch,getState) } //点击专题列表最前面的复选框的处理,将选中的加入到精选话题队列等待被后续设置为精选话题 export const addToRefined=ids=>({ type:types._addToRefined, ids }) //批量设置为精选话题 export const setToChosen=params=>async (dispatch,getState)=>{ await Api.set_chosenApi(params) searchTopic()(dispatch,getState) } //专题列表的选择分类 export const selectTopicCategory=category=>({ type:types._selectTopicCategory, category }) //专题列表删除 export const delTopic=id=>async (dispatch,getState)=>{ await Api.del_topicApi(id) searchTopic()(dispatch,getState) } /* 最上面那一排搜索条件的表单actions */ //改变搜索条件,就是专题界面最上面那一排条件 export const changeCondition = changedValue => ({ type: types._changeCondition, changedValue, }) //搜索条件重置 export const resetSearchParams=()=>({ type:types._resetSearchParams }) /* 精选话题列表的actions */<file_sep>/app/components/Substance/List/ToolBar/citys.js export default [{ value: 'zhejiang', label: '浙江省', children: [{ value: 'hangzhou', label: '杭州市' },{ value: 'huzhou', label: '湖州市' },{ value: 'ningbo', label: '宁波市' }] }]<file_sep>/app/components/Substance/SpecialTopic/index.js import React, {Component} from 'react' import {Form, Select, Input,Tag, Button, Upload,Radio,Badge,message} from 'antd' import {hashHistory} from 'react-router' import TagsModal from './AllTagsModal' import Ueditor from '../../common/Ueditor' import ueditorConfig from './ueditorConfig' import Api from '../../../api/zhi_shui/substanceApi' const FormItem = Form.Item const Option = Select.Option const RadioGroup = Radio.Group @Form.create() export default class extends Component { state={ ueditorId:'editor_specialTopic', tagsModalShow:false, max:20,//添加的最大数 formData:{ MyMarkList:[], id:'', city_name:'', title:'',//短标题 good_title:'',//长标题 type:'',//专题种类 category:'',//分类, list_img:'',//列表图 img_share:'',//分享图 img_head:'',//首图 moduleId:'',//模块悬浮ID summary:'',//引导语, hidden:'1',//是否激活, content_html:''//富文本内容 } } //显示增加标签的modal界面 showTagsModal=()=>{ let {formData:{MyMarkList},max}=this.state if(MyMarkList.length>=max){ return message.warning(`最多添加${max}个标签`) } this.setState({ tagsModalShow:!this.state.tagsModalShow }) } //删除标签 delTag=id=>()=>{ let formData=Object.assign({},this.state.formData) let tags=formData.MyMarkList for(let i=0,len=tags.length;i<len;i++){ if(id===tags[i].id){ tags.splice(i) return this.setState({ formData }) } } } //增加标签 addTags=(selectedTags)=>{ let formData=Object.assign({},this.state.formData) formData.MyMarkList=formData.MyMarkList.concat(selectedTags) this.setState({ formData }) } //保存编辑或者新建之后的专题 save=async ()=>{ const {form}=this.props let formData=form.getFieldsValue() formData.MyMarkList=this.state.MyMarkList formData.content_html=UE.getEditor(this.state.ueditorId).getContent() if(formData.id){ await Api.editSubstanceApi(formData) }else{ await Api.addSubstanceApi(formData) } hashHistory.push('/hunliji/substance') } //取消保存后跳转到专题界面 cancelSave=()=>{ hashHistory.push('/hunliji/substance') } //获取对应id的专题详情 getInfo=async id=>{ let {data={}}=await Api.getSubstance_infoApi(id) this.setState({ formData:data }) } componentDidMount(){ const {routeParams:{id}}=this.props if(id){ //如果存在就表示是编辑页面,就需要发请求获取详情 this.getInfo(id) } } render() { //获取路由带过来的id,如果存在就是编辑专题,不存在就是新建专题 const {routeParams:{id}, form:{getFieldProps}}=this.props let {formData,ueditorId,tagsModalShow,max} = this.state //当前拥有的标签 let tags=formData.MyMarkList.map((tag,i)=>( <Tag closable color="red" onClose={this.delTag(tag.id)} key={i}>{tag.name}</Tag> )) let specialTopicId=null //是编辑专题的时候就显示专题ID if (id) { specialTopicId = ( <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 6 }} label="专题ID"> <Input disabled={true} {...getFieldProps('id',{initialValue:formData.id})}/> </FormItem> ) } return ( <div> <Form horizontal> {specialTopicId} <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 6 }} label="选择城市"> <Select showSearch {...getFieldProps('city_name',{initialValue:formData.city_name})}> <Option value="1">杭州</Option> <Option value="2">宁波</Option> </Select> </FormItem> <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 6 }} required label="短标题"> <Input {...getFieldProps('title',{initialValue:formData.title})}/> </FormItem> <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 6 }} required label="长标题"> <Input {...getFieldProps('good_title',{initialValue:formData.good_title})}/> </FormItem> <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 6 }} required label="专题种类"> <Select showSearch {...getFieldProps('type',{initialValue:formData.type})}> <Option value="1">百科</Option> <Option value="2">教育</Option> <Option value="3">促销</Option> <Option value="4">酒店</Option> </Select> </FormItem> <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 6 }} label="分类"> <Select showSearch {...getFieldProps('category',{initialValue:formData.category})}> <Option value="1">结婚故事</Option> <Option value="2">创意婚礼</Option> <Option value="3">备婚干货</Option> <Option value="4">婚假话题</Option> </Select> </FormItem> <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 10 }} label="标签"> {tags} <Button size="small" type="dashed" onClick={this.showTagsModal}>+ 添加标签</Button> <Badge count={tags.length} /> </FormItem> <FormItem label="列表图" help="尺寸1080*540" labelCol={{ span: 2 }} wrapperCol={{ span: 8 }}> <Upload name="list_img" action="http://up.qiniu.com/" withCredentials={true} listType="picture"> <Button type="primary" icon="upload"> 添加图片 </Button> </Upload> </FormItem> <FormItem label="分享图" help="尺寸200*200" labelCol={{ span: 2 }} wrapperCol={{ span: 8 }}> <Upload name="img_share" action="http://up.qiniu.com/" listType="picture"> <Button type="primary" icon="upload"> 添加图片 </Button> </Upload> </FormItem> <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 6 }} label="悬浮模块ID"> <Input {...getFieldProps('moduleId',{initialValue:formData.moduleId})}/> </FormItem> <FormItem label="首图" help="尺寸200*200" labelCol={{ span: 2 }} wrapperCol={{ span: 10 }}> <Upload name="img_head" action="http://up.qiniu.com/" listType="picture"> <Button type="primary" icon="upload"> 添加图片 </Button> </Upload> </FormItem> <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 12 }} label="引导语" help="哈哈哈你个大傻逼"> <Input type="textarea" {...getFieldProps('summary',{initialValue:formData.summary})} placeholder="请输入引导语"/> </FormItem> <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 8 }} label="是否激活"> <RadioGroup {...getFieldProps('hidden',{initialValue:formData.hidden})}> <Radio value="1">是</Radio> <Radio value="0">否</Radio> </RadioGroup> </FormItem> </Form> <Ueditor funs={ueditorConfig.funs} defaultContent={formData.content_html} toolbars={ueditorConfig.toolbars} ueditorId={ueditorId}> </Ueditor> <Button type="primary" icon="save" onClick={this.save} style={{marginRight:20}}> 保存 </Button> <Button type="primary" onClick={this.cancelSave} icon="cross-circle-o"> 取消 </Button> { tagsModalShow?( <TagsModal max={max} currTags={formData.MyMarkList} onCancle={this.showTagsModal} onOk={this.addTags} tagsModalShow={tagsModalShow}/> ):null } </div> ) } }<file_sep>/app/util/index.js /* 工具类,这里定义了很多工具方法 */ import React from 'react' import styles from './style.css' const devUrl='/' const prodUrl='/p/admin/Tpl/Home/default/richTextThread/' export default{ //获取一些url时,比如本地用假数据请求一个json文件的时候,去获取真正的url,这样获取的url,无论在本地还是线上都能正常工作 getRealUrl(url){ let prefix=__DEV__?devUrl:prodUrl if(url.startsWith('/')){ url=url.substring(1) } return prefix+url }, //在列表中有些列显示的是图的时候可以使用 imgHandle(src){ if(src===''||!src){ src='http://qnm.hunliji.com/o_1an6lmevq1fg3lqt18n6188hvh17.jpg' } if(src.indexOf('?')===-1){ src=src+'?imageView2/2/w/160/h/120/format/webp' } return( <div className={styles.tbox}> <img className={styles.tboxImg} src={src} /> </div> ) }, //请求登陆 reqLogin:(replace,target,loginAgain=true)=>{ if(localStorage.getItem('login_token')){ target&&replace(target) }else if(loginAgain){ replace('/login') } } } <file_sep>/app/reducers/zhi_shui/substance/searchParams.reducer.js import {_resetSearchParams,_changeCondition} from '../../../actions/types/substance.type' import update from 'react/lib/update' const initState={ //专题页面的搜索条件 type:'1',//专题类型 city:['zhejiang', 'hangzhou'],//城市 title:'1',//标题 hidden:'0',//是否激活 is_global:'0',//是否全局可见 label:'1',//标签 } export default (state=initState,action)=>{ switch (action.type){ case _changeCondition: return update(state, {$merge: action.changedValue}) case _resetSearchParams: return initState default: return state } }<file_sep>/app/components/Substance/List/Tab/Topic/columns.js import React from 'react' import util from '../../../../../util' import styles from './style.css' import {Switch,Checkbox} from 'antd' export default component=>( [{ title:'专题ID', dataIndex:'id', width:80, key:'id' },{ title: '标题', width:150, dataIndex: 'title', key:'title' }, { title:'列表图', width:180, dataIndex:'list_img', key:'list_img', render:src=>util.imgHandle(src) }, { title: '专题种类', dataIndex: 'type_name', width:100, key:'type_name' },{ title:'分类', width:80, dataIndex:'category', key:'category', render:(text)=>{ let category='结婚故事' switch (text){ case '2':category='创意婚礼'; break; case '3':category='备婚干货'; break; case '4':category='婚假话题' } return category; } },{ title:'城市', width:100, dataIndex:'city_name', key:'city_name' },{ title:'是否激活', width:100, dataIndex:'hidden', key:'hidden', render:(hidden, {id,is_refined})=>( <Switch checkedChildren="开" unCheckedChildren="关" onChange={(checked)=>component.activeGlobalHandle(id,'hidden',is_refined)} checked={hidden==='0'?false:true}/> ) },{ title:'是否全局可见', width:150, dataIndex:'is_global', key:'is_global', render:(text, {id,is_global})=>( <Switch checkedChildren="是" unCheckedChildren="否" onChange={(checked)=>component.activeGlobalHandle(id,'is_global')} checked={is_global==='0'?false:true}/> ) },{ title:'操作人', width:100, dataIndex:'operation_people', key:'operation_people' },{ title: '操作', key: 'operation', width:200, render: (text, {id,isActivate,weight}) => ( <span className={styles.operation}> <a onClick={()=>component.stick(id,weight)}> {/*weight为0表示这项专题没有被置顶,所以要显示置顶,1反之*/} {weight==='0'?'置顶':'取消置顶'} </a> <a onClick={()=>console.log('复制链接')}> 复制链接 </a> <a onClick={()=>component.goToSpecialTopic('edit',id)}> 编辑 </a> <a onClick={()=>component.del(id,isActivate)}> 删除 </a> </span> ) }] )<file_sep>/app/components/Substance/List/Tab/Chosen/columns.js import React from 'react' import styles from './style.css' export default component=>( [{ title:'专题ID', dataIndex:'id', key:'id' },{ title: '标题', dataIndex: 'name', key:'name' }, { title:'列表图', dataIndex:'img', key:'img' }, { title: '专题种类', dataIndex: 'type', key:'type' },{ title:'分类', dataIndex:'classify', key:'classify' },{ title:'城市', dataIndex:'city', key:'city' },{ title:'开始显示日期', dataIndex:'startDate', key:'startDate' },{ title:'全局可见', dataIndex:'visible', key:'visible' },{ title:'操作人', dataIndex:'operationPeople', key:'operationPeople' },{ title: '操作', width:200, key: 'operation', render: (text, {id}) => ( <span className={styles.operation}> <a onClick={()=>{console.log('复制链接')}}> 复制链接 </a> <a onClick={()=>component.goToSpecialTopic(id)}> 编辑 </a> <a onClick={()=>{console.log('删除')}}> 删除 </a> </span> ) }] )
1ba07fe420f7823efd3163b9fd64f79fd3cd50bb
[ "JavaScript" ]
10
JavaScript
digpads/hunliji_projectMax
55e6b030c7a07aa76af36476f865430cae2b2175
8df540fbf56e7c2a781ab64ef86890d999a0176d
refs/heads/main
<repo_name>Monsterup/Fazztrack<file_sep>/routes/products.js const express = require('express') const router = express.Router() const dbConn = require('../db') router.get('/', (req, res, next) => { dbConn.query('select * from produk', (err, result) => { if(err) { req.flash('error', err); res.render('index',{data:''}); } else { res.render('index',{data:result}); } }) }) router.get('/add', (req, res, next) => { res.render('create', { nama_produk: '', jumlah: 0, harga: 0, keterangan: '' }) }) router.post('/add', (req, res, next) => { let {nama, jumlah, harga, keterangan} = req.body; var form_data = { nama_produk: nama, jumlah: jumlah, harga: harga, keterangan: keterangan } try { dbConn.query('insert into produk set ?', form_data, (err, result) => { if(err) throw new Error else { req.flash('success', 'Produk berhasil ditambahkan') res.redirect('/') } }) } catch (error) { req.flash('error', error); } }) router.get('/edit/(:id)', (req, res, next) => { let {id} = req.params; try { dbConn.query('select * from produk where id = ' + id, (err, result) => { if(err) throw new Error else { res.render('update', { title: 'Edit Produk', id: result[0].id, nama: result[0].nama_produk, jumlah: result[0].jumlah, harga: result[0].harga, keterangan: result[0].keterangan }) } }) } catch (error) { req.flash('error', error); } }) router.post('/edit/(:id)', (req, res, next) => { let {id} = req.params; let {nama,jumlah,harga,keterangan} = req.body; var form_data = { nama_produk: nama, jumlah: jumlah, harga: harga, keterangan: keterangan } try { dbConn.query('update produk set ? where id = ' + id, form_data, (err, result) => { if(err) throw new Error else { req.flash('success', 'Produk berhasil diupdate') res.redirect('/') } }) } catch (error) { req.flash('error', error); } }) router.get('/delete/(:id)', (req, res, next) => { let {id} = req.params; try { dbConn.query('delete from produk where id = ' + id, (err, result) => { if(err) throw new Error else { req.flash('success', 'Produk berhasil dihapus') res.redirect('/') } }) } catch (error) { req.flash('error', error); } }) module.exports = router;<file_sep>/README.md # Fazztrack INDEX ![alt text](https://github.com/monsterup/Fazztrack/blob/main/index.png?raw=true) ADD ![alt text](https://github.com/monsterup/Fazztrack/blob/main/add.png?raw=true) UPDATE ![alt text](https://github.com/monsterup/Fazztrack/blob/main/edit.png?raw=true)
9dc1ee1f2ac0d1fa7e2eb8ada87e8f5317b349d7
[ "JavaScript", "Markdown" ]
2
JavaScript
Monsterup/Fazztrack
a882a3c952d677163d4d0bbe30ed5b581543b563
e9db3a85d5e63f85f4a6ea7a35e5696ebbb42228
refs/heads/master
<file_sep>import turtle wn = turtle.Screen() bob = turtle.Turtle() color = ("blue","black","red") colors = ("yellow","green") bob.setposition(0, 0) m = 0 for c in color: #CREATES THE FIRST ROW OF CIRCLES WHICH INCLUDE BLUE, BLACK AND RED CIRCLES bob.penup() bob.fd(m) m = 75 bob.pendown() bob.color(c) bob.circle(50) bob.penup() bob.setposition(37.5, -75) bob.pendown() m = 0 for c in colors: #CREATES THE SECOND ROW OF CIRCLES WHICH INCLUDE YELLOW AND GREEN CIRCLES bob.penup() bob.fd(m) m = 75 bob.pendown() bob.color(c) bob.circle(50) wn.exitonclick() <file_sep>import turtle wn = turtle.Screen() bob = turtle.Turtle() bob.pensize(8) bob.penup() #CREATES A BLUE CIRCLE AT THE APPROPRIATE POSITION bob.setposition(25,50) bob.color("blue") bob.pendown() bob.circle(50) bob.penup() #CREATES A BLACK CIRCLE AT THE APPROPRIATE POSITION bob.setposition(75,50) bob.color("black") bob.pendown() bob.circle(50) bob.penup() #CREATES A RED CIRCLE AT THE APPROPRIATE POSITION bob.setposition(125,50) bob.color("red") bob.pendown() bob.circle(50) bob.penup() #CREATES A YELLOW CIRCLE AT THE APPROPRIATE POSITION bob.setposition(50,-25) bob.color("yellow") bob.pendown() bob.circle(50) bob.penup() #CREATES A GREEN CIRCLE AT THE APPROPRIATE POSITION bob.setposition(100,-25) bob.color("green") bob.pendown() bob.circle(50) wn.exitonclick() '''import turtle bob = turtle.Turtle() wn = turtle.Screen() colours = ("blue","yellow","black","green","red") angle = (45,225,45,225,0) n = 0 bob.setposition(0,0) for c in colours: bob.color(c) bob.penup() bob.rt(angle[n]) n =+ 1 bob.fd(50) bob.pendown() bob.circle(50) wn.exitonclick() ''' <file_sep># Olympic Symbol OLYMPIC symbol created using turtle library. This Python code uses the Turtle Library and draws the Olympic symbol. You will find 2 attached Python codes- One is with FOR loops while the other one is a simple code without any loops for Beginners.
29119553b18d4aa36be709da2d782b4258c104c0
[ "Markdown", "Python" ]
3
Python
siddarth-arora/Olympic-Symbol
dfdaef45985a4a6c6cffcfa3a5714432d137ebfc
59808fbcf935feadc129b91c0bfa2d58c146d60a
refs/heads/main
<repo_name>alex90o/ejemploVEctorStruc<file_sep>/main.cpp #include <iostream> using namespace std; #include <vector> #include <algorithm> #include<string.h> struct palabrabuscada { char *palabra; int cantidad; }; //fuente //https://stackoverflow.com/questions/4892680/sorting-a-vector-of-structs // función de comparación: bool compareByLength(const palabrabuscada &a, const palabrabuscada &b) { return a.cantidad < b.cantidad; } //--------- class indice { public: vector <palabrabuscada> ind; int posicionActual; public: indice(); void cargar_indice(char *palabra,int cant); void leer_indice(); ~indice(); }; indice::indice() { this->posicionActual=0; } void indice::cargar_indice( char *palabra,int cant) { this->ind.push_back(palabrabuscada()); this->ind[posicionActual].palabra=palabra; this->ind[posicionActual].cantidad=cant; this->posicionActual++; //const char *palabra1="libros"; //this->ind[posicionActual]=palabra1; //-------- //this->ind->directorio= directorio; //this->ind->nombre_archivo= nombrearchivo; //this->ind->cantidad=cant; //indice.ind->palabra //this->ind.push_back(palabrabuscada()); //this->ind.push_back({palabra,directorio,nombrearchivo,cant}); } indice::~indice() { } int main() { indice indicArchivos; /* int num; char *palab; cout << "Introduce un numero entero: "; cin >> num; cout << "Introduce la palabra: "; cin>>palab; indicArchivos.cargar_indice(palab,num); int i=0; cout <<"Palabra"<<": "<<indicArchivos.ind[i].palabra; cout << endl; cout <<"Cantidad"<<": "<<indicArchivos.ind[i].cantidad; cout << endl; */ cout <<"con el for"<< endl; for (int i = 0; i < 5; i++){ char *palabaux=new char; int numaux; cout << "Introduce un numero entero: "; cin >> numaux; cout << "Introduce la palabra: "; cin>>palabaux; indicArchivos.cargar_indice(palabaux,numaux); } cout << endl; for (int i = 0; i < indicArchivos.ind.size(); i++){ cout <<"Palabra "<<indicArchivos.ind[i].palabra; cout << endl; cout <<"Cantidad de veces "<<indicArchivos.ind[i].cantidad; cout << endl<<endl; } //usar std::sorten el encabezado #include <algorithm>: std::sort(indicArchivos.ind.begin(), indicArchivos.ind.end(), compareByLength); cout<<"despues del sort"<<endl<<endl; for (int i = 0; i < indicArchivos.ind.size(); i++){ cout <<"Palabra "<<indicArchivos.ind[i].palabra; cout << endl; cout <<"Cantidad de veces "<<indicArchivos.ind[i].cantidad; cout << endl<<endl; } return 0; }
91445da18cb40c8826e1039a1905b48f4cf135bc
[ "C++" ]
1
C++
alex90o/ejemploVEctorStruc
4091713faf6cbe2ac8a4f573d21a4c926e653e14
a28a3b3c6df8df9a1000ecab1310522e121e9354
refs/heads/master
<repo_name>penelopezone/radars<file_sep>/src/scanner.rs use std::net::{IpAddr, SocketAddr}; use std::ops::Range; use std::thread::{self, JoinHandle}; use scan_group::{ScanGroup, PortNumber}; pub struct Scanner { target: IpAddr } fn ports() -> Range<PortNumber> { (1..65535) } fn n_threads() -> u32 { 1000 } fn await_results<T>(handles: Vec<JoinHandle<T>>) -> Vec<thread::Result<T>> { handles.into_iter().map(|h| h.join()).collect() } impl Scanner { pub fn new(target: IpAddr) -> Scanner { Scanner { target: target } } pub fn scan(self) { let handles = self.build_scan_groups(); self.print_handle_results(handles); } fn build_scan_groups(&self) -> Vec<JoinHandle<Vec<PortNumber>>> { let addrs = self.socket_addrs(); let chunks = addrs.chunks(addrs.len() / n_threads() as usize); chunks.into_iter().map(|chunk| { ScanGroup::new(chunk.to_vec()).dispatch() }).collect() } fn print_handle_results(&self, handles: Vec<JoinHandle<Vec<PortNumber>>>) { let results: Vec<_> = await_results(handles); for result in results { let open_ports = result; match open_ports { Ok(x) => for open_port in x { println!("{} is open", open_port); }, Err(_) => println!("Error: joining a thread failed"), } } } fn socket_addrs(&self) -> Vec<SocketAddr> { ports().into_iter().map(|port_number| { SocketAddr::new(self.target, port_number) }).collect() } } <file_sep>/src/main.rs use std::str::FromStr; use std::env::args; use std::process::exit; use std::net::IpAddr; mod scanner; mod scan_group; use scanner::Scanner; fn main() { if args().count() == 2 { let ip_string = args().nth(1).unwrap(); let ip_address = IpAddr::from_str(&ip_string); match ip_address { Ok(address) => scan_ports(address), Err(_) => show_error(ip_string), } } else { println!("Usage is: ./radars ip_address"); exit(1); } } fn scan_ports(address: IpAddr) { Scanner::new(address).scan(); } fn show_error(address: String) { println!("Couldn't parse `{}` as an IP address", address); exit(1); } <file_sep>/src/scan_group.rs use std::thread::{spawn, JoinHandle}; use std::io::{self, Write}; use std::net::{SocketAddr, TcpStream}; pub type PortNumber=u16; fn port_is_open(addr: &SocketAddr) -> bool { let conn = TcpStream::connect(addr); conn.is_ok() } pub struct ScanGroup { addrs: Vec<SocketAddr> } fn report_progress() { print!("."); io::stdout().flush().unwrap(); } impl ScanGroup { pub fn new(addrs: Vec<SocketAddr>) -> ScanGroup { ScanGroup { addrs: addrs } } pub fn dispatch(self) -> JoinHandle<Vec<PortNumber>> { spawn(move || self.perform_scan()) } fn perform_scan(self) -> Vec<PortNumber> { self.addrs.into_iter().filter(|addr| { report_progress(); port_is_open(addr) }).map(|addr| addr.port()).collect() } }
6ec8023d36f355e7d76e7cd38c9d844903406b52
[ "Rust" ]
3
Rust
penelopezone/radars
79e9a6a0415767e4f308780b2282f009b38ea0d7
ada1e0096bccfecb6019cdd8ef9a611d8d5122cd
refs/heads/master
<file_sep>import { useState } from "react"; import axios from "axios"; import "./App.css"; async function postSong({ song }) { const formData = new FormData(); formData.append("song", song); const result = await axios .post("https://monty-test-aws-s3.herokuapp.com/songs", formData, { headers: { "Content-Type": "multipart/form-data" }, }) .then((res) => { alert(`https://monty-test-aws-s3.herokuapp.com/songs/${res.data["success"]}`); }); return result.data; } function App() { const [file, setFile] = useState(); const [songs, setSongs] = useState([]); const submit = async (event) => { event.preventDefault(); const result = await postSong({ song: file }); setSongs([result.songs, ...songs]); }; const fileSelected = (event) => { const file = event.target.files[0]; setFile(file); }; return ( <div className="App"> <h1>test-aws-s3</h1> <br /> <br /> <form onSubmit={submit}> <input onChange={fileSelected} type="file" /> <button type="submit">Submit</button> </form> </div> ); } export default App;
85f93e000e81c30c820660b058b96b761080f1d7
[ "JavaScript" ]
1
JavaScript
manthankumbhar/test-aws-s3-front
232a9c696ab30eb1c217147df4f9b4e391a5066a
984b80a172f5c2832dfb0d62db0e222dae9c23b4
refs/heads/master
<file_sep>#include <stdio.h> #include <string.h> #include <iostream> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <event.h> using namespace std; // 事件base struct event_base* base; // 读事件回调函数 void onRead(int iCliFd, short iEvent, void *arg) { int iLen; char buf[1500]; iLen = recv(iCliFd, buf, 1500, 0); if (iLen <= 0) { cout << "Client Close" << endl; // 连接结束(=0)或连接错误(<0),将事件删除并释放内存空间 struct event *pEvRead = (struct event*)arg; event_del(pEvRead); delete pEvRead; close(iCliFd); return; } buf[iLen] = 0; cout << "Client Info:" << buf << endl; } // 连接请求事件回调函数 void onAccept(int iSvrFd, short iEvent, void *arg) { int iCliFd; struct sockaddr_in sCliAddr; socklen_t iSinSize = sizeof(sCliAddr); iCliFd = accept(iSvrFd, (struct sockaddr*)&sCliAddr, &iSinSize); // 连接注册为新事件 (EV_PERSIST为事件触发后不默认删除) struct event *pEvRead = new event; event_set(pEvRead, iCliFd, EV_READ|EV_PERSIST, onRead, pEvRead); event_base_set(base, pEvRead); event_add(pEvRead, NULL); } int main() { int iSvrFd; struct sockaddr_in sSvrAddr; memset(&sSvrAddr, 0, sizeof(sSvrAddr)); sSvrAddr.sin_family = AF_INET; sSvrAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); sSvrAddr.sin_port = htons(8888); // 创建tcpSocket(iSvrFd),监听本机8888端口 iSvrFd = socket(AF_INET, SOCK_STREAM, 0); bind(iSvrFd, (struct sockaddr*)&sSvrAddr, sizeof(sSvrAddr)); listen(iSvrFd, 10); // 初始化base base = event_base_new(); struct event evListen; // 设置事件 event_set(&evListen, iSvrFd, EV_READ|EV_PERSIST, onAccept, NULL); // 设置为base事件 event_base_set(base, &evListen); // 添加事件 event_add(&evListen, NULL); // 事件循环 event_base_dispatch(base); return 0; } <file_sep># libevent 测试例子 ## timer/timer.c 用来测试libevent的定时器的,添加一个定时器 ## timer/time2.c 测试libevent定时器,同时添加两个定时器 ## timer/time3.c 测试libevent定时器,两个定时器相互之间穿插添加 ## socket/socket.c 测试libevent网络,例子来源于网络 ## socket/socket2.c 测试libevent网络,例子来自于http://www.cnblogs.com/cnspace/archive/2011/07/19/2110891.html <file_sep>#include <stdio.h> #include <event.h> int main() { struct event_base *base ; base = event_init(); return 0 ; } <file_sep>#include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <linux/tcp.h> int main() { int sfd, fd; struct addrinfo *ai; struct addrinfo *next; struct addrinfo hints = { .ai_flags = AI_PASSIVE, .ai_family = AF_UNSPEC }; struct linger ling = {0, 0}; int error; int success = 0; char *interface = NULL ; int port = 22224 ; char port_buf[NI_MAXSERV]; struct sockaddr addr; socklen_t addrlen; int flags = 1 ; int fs; hints.ai_socktype = SOCK_STREAM ; snprintf(port_buf, sizeof(port_buf), "%d", port); error= getaddrinfo(interface, port_buf, &hints, &ai); if (error != 0) { if (error != EAI_SYSTEM) fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error)); else perror("getaddrinfo()"); return 1; } for (next= ai; next; next= next->ai_next) { if ((sfd = socket(next->ai_family, next->ai_socktype, next->ai_protocol)) == -1){ perror("server_socket") ; exit(1) ; } if ((fs = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, fs | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1){ if (errno != EADDRINUSE) { perror("bind()"); close(sfd); freeaddrinfo(ai); return 1; } close(sfd); continue; } listen(sfd,10); while (1){ addrlen = sizeof(addr); fd = accept(sfd,&addr,&addrlen) ; char * wstr = "this is test" ; write(fd,wstr,strlen(wstr)) ; close(fd) ; } } freeaddrinfo(ai); } <file_sep>#include <stdio.h> #include <event.h> #include <sys/time.h> #include <unistd.h> #include <stdbool.h> #include <stdint.h> #include <fcntl.h> #include <stdlib.h> #define rel_time_t unsigned int struct event_base *main_base; struct event clockevent,clockevent2; volatile unsigned int current_time; void clock_handler(const int fd, const short which, void *arg) ; static void set_current_time(void) { struct timeval timer; gettimeofday(&timer, NULL); current_time = (rel_time_t) (timer.tv_sec); } void clock_handler2(const int fd, const short which, void *arg) { printf("this is clock_handler2 function\n") ; } void clock_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 1, .tv_usec = 0 }; struct timeval t2 = {.tv_sec = 1, .tv_usec = 0 }; static bool initialized = false; if(initialized){ evtimer_del(&clockevent); evtimer_del(&clockevent2); }else{ initialized = true; } evtimer_set(&clockevent2, clock_handler2, 0); event_base_set(main_base, &clockevent2); evtimer_add(&clockevent2, &t2); evtimer_set(&clockevent, clock_handler, 0); event_base_set(main_base, &clockevent); evtimer_add(&clockevent, &t); set_current_time(); printf("current_time: %d\n", current_time); } int main(int argc, char *argv[]) { main_base = event_init() ; clock_handler(0,0,0) ; event_base_loop(main_base, 0); return 0 ; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include <sys/time.h>   typedef struct my_timer_s my_timer_t;   struct my_timer_s {     my_timer_t *prev, *next;     int diff_sec;     int diff_usec;     void (*func)(); };   my_timer_t  *timer_list = NULL;   void callback_timeout() {     my_timer_t *p, *q;     struct itimerval itimer;     sigset_t set, oldset;       p = timer_list;       sigemptyset(&set);     sigaddset(&set, SIGALRM);     sigprocmask(SIG_SETMASK, &set, &oldset);       for (q = timer_list->next; q; q = q->next) {         q->diff_sec -= p->diff_sec;         q->diff_usec -= p->diff_usec;     }       if (timer_list->next != NULL) {         timer_list = timer_list->next;           itimer.it_interval.tv_sec = 0;         itimer.it_interval.tv_usec = 0;         itimer.it_value.tv_sec = timer_list->diff_sec;         itimer.it_value.tv_usec = timer_list->diff_usec;           setitimer(ITIMER_REAL, &itimer, NULL);     }       sigprocmask(SIG_SETMASK,&oldset,NULL);       p->func();       free(p); }   int register_timer(int sec, int usec, void (*action)()) {     my_timer_t  *t, *p, *pre;     struct itimerval itimer;     struct sigaction sa;     sigset_t set, oldset;       t = (my_timer_t *) malloc(sizeof(my_timer_t));     t->next = t->prev = NULL;     t->diff_sec = sec;     t->diff_usec = usec;     t->func = action;       sigemptyset(&set);     sigaddset(&set, SIGALRM);     sigprocmask(SIG_SETMASK,&set,&oldset);       if (timer_list == NULL) {           timer_list = t;       } else {           for (pre = NULL, p = timer_list; p; pre = p, p = p->next) {             if (p->diff_sec > t->diff_sec ) {                 t->next = p;                 p->prev = t;                   if (p->prev) {                     p->prev->next = t;                     t->prev = p->prev;                 }                   break;             }         }           if (p == NULL) {             t->prev = pre;             pre->next = t;         }     }       t = timer_list;       itimer.it_interval.tv_sec = 0;     itimer.it_interval.tv_usec = 0;     itimer.it_value.tv_sec = t->diff_sec;     itimer.it_value.tv_usec = t->diff_usec;     setitimer(ITIMER_REAL, &itimer, NULL);       sigprocmask(SIG_SETMASK, &oldset, NULL);       return 0; }   void func1() {     printf("timer1\n"); }     void func2() {     printf("timer2\n"); }     void func3() {     printf("timer3\n"); }     void timer_handler (int signo) {     switch(signo) {     case SIGALRM:         callback_timeout();         break;     } }   int main () {     struct sigaction sa;     struct itimerval itimer;       /*     memset (&sa, 0, sizeof (sa));     sa.sa_handler = &timer_handler;     sa.sa_flags = 0;     sigemptyset(&sa.sa_mask);     sigaction(SIGALRM, &sa, NULL);     */     signal(SIGALRM, timer_handler);       register_timer(1, 0, &func1);     register_timer(4, 0, &func2);     register_timer(5, 0, &func3);       while (1);       return 0; } <file_sep>#define _GNU_SOUFCE #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <sched.h> #include <signal.h> #include <unistd.h> #define STACK_SIZE (1024*1024) static char container_stack[STACK_SIZE] ; char * const container_args[] = { "/bin/bash", NULL } ; int container_main(void * arg) { printf("Contaner- inserted the container\n") ; sethostname("container",10) ; execv(container_args[0],container_args) ; printf("wrong{!\n") ; return 1 ; } int main() { printf("Parent - start a container!\n") ; int container_pid = clone(container_main, container_stack+STACK_SIZE, CLONE_NEWUTS | SIGCHLD , NULL) ; waitpid(container_pid,NULL,0) ; printf("Parent -container stopped!\n") ; return 0 ; }
9586443c7555fd95fe4e594d7f2711c8b42c4677
[ "Markdown", "C" ]
7
C
yuehai1117/test-code
971002ba8a641bd22a780d859bd215ef3ca5bd52
4516971eb598a9b88a3a51d63f5def4b5021e790
refs/heads/master
<file_sep># RemoteConnection Socket Programming(Windows:C#/Ubuntu:Node.js-Windows:C#/Windows:Python) <br> <br> Hi everyone! <br> This project includes remote connection between C# in Windows and Node.js in Ubuntu, between C# in Windows and Python in Windows and finally SQL server.<br> It was done in Visual Studio.<br> Programming language is C#.<br> You can look remote connection stage from Create.cshtml. (This project includes client side. You can access server side from my page.)<br> Good luck!<br> Bu proje Windows taki C# ile Ubuntu daki Node.js arasında, Windows taki C# ile Windows taki Python arasında ve SQL server arasında uzaktan bağlantı içerir.<br> Visual Studio da gerçekleştirildi.<br> Programlama dili C# tır.<br> Create.cshtml dan uzaktan bağlantı aşamasına bakabilirsiniz. (Bu proje client bölümünü içerir. Server bölümüne sayfamdan erişebilirsiniz.)<br> Kolay gelsin. <file_sep>/* Author = <NAME> Create Date = 23.10.18 Purpose = This project's purpose is connect the other pc`s and do sharing data between pc`s in the same network Projenin amacı diğer bilgisayarlarla bağlantı kurmak ve diğer bilgisayarlar arasında veri paylaşımı yapmak. Done Operation = A Core Pc is connected the other pc's SQL Server, the other pc's SQLite and the other pc's Node.js of Ubuntu. It is connected remote with SQL Server and it is connected with socket programming Python for remote connection SQLite and with socket programming Node.js for remote connection Ubuntu. You can look this section from Create.cshtml.cs Bir ana bilgisayardan diğer bilgisayardaki SQL Server a, SQLite a ve Ubuntu daki Node.js e bağlantı kurulur. SQL Server ile uzaktan bağlantı sağlanır, SQLite a uzaktan bağlantı sağlamak için Python ile soket programlama yapılır ve Ubuntu ya uzaktan bağlantı sağlamak için Node.js ile soket programlama yapılır. Create.cshtml.cs bölümünden bakabilirsiniz. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ConnectApp { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } } <file_sep>using ConnectApp.Data; using Microsoft.EntityFrameworkCore; namespace ConnectApp { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions options) : base (options) { } public DbSet<Customer> Customers { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data.SQLite; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using ConnectApp.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace ConnectApp.Pages { public class CreateModel : PageModel { private readonly AppDbContext _db; public string IpAddres = null; public CreateModel(AppDbContext db) { _db = db; } [BindProperty] public Customer Customer { get; set; } public String sIp="", sDateTime = ""; public async Task<IActionResult> OnPostAsync() //Post form kullanıldığı zaman OnPostAsync kullanılır. When you used Post Form, you use OnPostAsync. { #region Take own ip address and date-time information as dynamic ~ Kendi ip adresimizi ve gün-zaman bilgilerimizi dinamik olarak almak. IPAddress[] addr = (Dns.GetHostEntry(Dns.GetHostName())).AddressList; sIp = addr[addr.Length - 1].ToString(); sDateTime = DateTime.Now.ToString(); #endregion #region Connect Python for SQLite ConnectPython(); #endregion #region Ubuntu NodeJsConnect(); #endregion #region SQLServer Connected //Firstly, you have to do change your settings in the SQL Server Configuration Manager. ~ Öncelikle SQL Server Configuration Manager daki ayarlarınızı değiştirmek zorundasınız. ConnectSQLServer(); #endregion if (!ModelState.IsValid) { return Page();//Hataları döndürmek için. ~ For send to back errors. } _db.Customers.Add(Customer); await _db.SaveChangesAsync(); return RedirectToPage("/Index"); } #region SQL Server private void ConnectSQLServer() { String connectString; SqlConnection cnn; String sql = ""; SqlCommand command; SqlDataAdapter adapter = new SqlDataAdapter(); connectString = @"Data Source=192.168.211.135; Initial Catalog=Connect_SEDA;User ID=sa; Password=<PASSWORD>; Timeout=45"; //@"Data Source=Your want connection's ip address; Initial Catalog=Your Database's Name; User ID=Your login's Name; Password=<PASSWORD>" //@"Data Source=Bağlanmak istediğiniz ip adresi; Initial Catalog=Veritabanınızın adı; User ID=Giriş adınız; Password=<PASSWORD>" cnn = new SqlConnection(connectString); try { cnn.Open(); sql = "insert into SEDA_Computer (Name,SurName,Information) values ('" + Customer.Name + "', ' " + Customer.SurName + "', '" + sIp + " " + sDateTime + "')"; command = new SqlCommand(sql, cnn); adapter.InsertCommand = new SqlCommand(sql, cnn); adapter.InsertCommand.ExecuteNonQuery(); command.Dispose(); cnn.Close(); } catch { Debug.WriteLine("Bağlanılmadı"); cnn.Close(); } Debug.WriteLine("Bağlanıldı."); } #endregion #region Python for SQLite private void ConnectPython() // C# has client code, Python has server code. ~ C# ta client kodu, Python da sever kodu var. { try { TcpClient tcpClient = new TcpClient(); tcpClient.Connect("192.168.211.139", 7000);//Your want connection ip address and socket number ~ bağlanmak istediğiniz ip adresi ve soket numarası String sMessage = Customer.Name + " " + Customer.SurName + " " + sIp + " " + sDateTime; ASCIIEncoding aSCIImessage = new ASCIIEncoding(); NetworkStream stm = tcpClient.GetStream(); byte[] bAsciiMessage = aSCIImessage.GetBytes(sMessage); stm.Write(bAsciiMessage, 0, bAsciiMessage.Length); tcpClient.Close(); } catch (Exception e) { Debug.WriteLine("Error: " + e.StackTrace); } } #endregion #region Ubuntu ~ Node.js private void NodeJsConnect()// C# has client code, Node.js has server code. ~ C# ta client kodu, Python da sever kodu var. { try { TcpClient tcpClient = new TcpClient(); tcpClient.Connect("192.168.211.130", 8000); //Your want connection ip address and socket number ~ bağlanmak istediğiniz ip adresi ve soket numarası String sMessage = Customer.Name + " " + Customer.SurName + " " + sIp + " " + sDateTime; ASCIIEncoding aSCIImessage = new ASCIIEncoding(); NetworkStream stm = tcpClient.GetStream(); byte[] bAsciiMessage = aSCIImessage.GetBytes(sMessage); stm.Write(bAsciiMessage, 0, bAsciiMessage.Length); tcpClient.Close(); } catch (Exception e) { Debug.WriteLine("Error: " + e.StackTrace); } } #endregion } }
8d0d05d6b5024e365153e95ee90ce88f946bf405
[ "Markdown", "C#" ]
4
Markdown
FatmaSedaOZYURT/RemoteConnection
ea8253bf4004442825a2dc4c8bfeed6864fdb3b9
369df24289956e536b44f256b8a5c007e2f80909
refs/heads/main
<file_sep>#include <bits/stdc++.h> using namespace std; //DP solution int findSolDP(int arr[], int n){ //Calculating Total Sum of are cures int sum=0; for(int i=0;i<n;i++){ sum+=arr[i]; } //Initialiazing 2D array DP //Here DP[i][j] represents value of cures in first half(A) upto i in arr having j equals sum+(A-B) -->(B o valure of cures in second half) //(A-B) should had lead to -ve index hence we add sum to it //Soo, answer is dp[n-1][sum] int dp[n][2*sum+1]; for(int i=0;i<n;i++){ for(int j=0;j<(2*sum+1);j++){ dp[i][j]=INT_MIN; } } //For every element, we have three choices dp[0][sum]=0;//No taking first element dp[0][sum+arr[0]]=arr[0];//Taking it in A dp[0][sum-arr[0]]=0;//Taking it in B for(int i=0;i<n-1;i++){ for(int j=0;j<(2*sum+1);j++){ if(dp[i][j]!=INT_MIN){ dp[i+1][j]=max(dp[i+1][j],dp[i][j]);//No taking (i+1)th element if((j+arr[i+1])<=(2*sum)) dp[i+1][j+arr[i+1]]=max(dp[i+1][j+arr[i+1]],(dp[i][j]+arr[i+1]));//Taking it in A if((j-arr[i+1])>=0) dp[i+1][j-arr[i+1]]=max(dp[i+1][j-arr[i+1]],dp[i][j]);//Taking it in B } } } return dp[n-1][sum]; } //Recursive solution int findSolRec(int arr[], int pos, int A, int B){ if(pos==-1){ if(A==B) return A; else return 0; } int temp=findSolRec(arr,pos-1,A+arr[pos],B); temp=max(temp,findSolRec(arr,pos-1,A,B+arr[pos])); temp=max(temp,findSolRec(arr,pos-1,A,B)); return temp; } int main(){ int t; cin>>t; for(int q=1;q<=t;q++){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } int A=0,B=0; cout<<findSolDP(arr,n)<<"\n"; // cout<<findSolRec(arr,n-1,A,B)<<"\n"; } return 0; }<file_sep>//Optimal Strategy for Game #include<iostream> using namespace std; // DP Solution // Time Complexity : O(n^2) //Space Complexity : O(n^2) long long maximumAmount(int arr[], int n) { //dp[i][j] represents solution for array starting from index i and ending at j long long dp[n][n]={}; for(int i=0;i<n;i++){ dp[i][i]=arr[i]; if(i!=(n-1)) dp[i][i+1]=max(arr[i],arr[i+1]); } for(int d=2;d<n;d++){ // Diagonal of the matrix for(int i=0;i<(n-d);i++){ // Row Number of matrix or starting index for sub array solution int j=i+d; // Coloumn Number of matrix or ending index for sub array solution // We had to take max out of two ways of picking at both the ends for Player // Now for each case we have two situations for opponent, but opponent will give minimum out of it to Player in its next turn dp[i][j]=max(arr[i]+min(dp[i+2][j],dp[i+1][j-1]),arr[j]+min(dp[i][j-2],dp[i+1][j-1])); } } // Answer will be dp[0][n-1] as we need solution for array starting from 0 and ending at (n-1) return dp[0][n-1]; } //Driver Code int main(){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } cout<<maximumAmount(arr,n)<<"\n"; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; void canTalk(int n, pair<int, int> arr[], int k, int goUpto[]){ sort(arr,arr+n); goUpto[arr[n-1].second]=arr[n-1].first; for(int i=(n-2);i>=0;i--){ if((arr[i+1].first-arr[i].first)<=k) goUpto[arr[i].second]=goUpto[arr[i+1].second]; else goUpto[arr[i].second]=arr[i].first; } } int main(){ int n,p,k; cin>>n>>k>>p; pair<int,int> arr[n]; int goUpto[n+1]; for(int i=1;i<=n;i++){ int temp; cin>>temp; arr[i-1].first=temp; arr[i-1].second=i; } canTalk(n,arr,k,goUpto); for(int q=1;q<=p;q++){ int a,b; cin>>a>>b; cout<<((goUpto[a]==goUpto[b])?"Yes":"No")<<"\n"; } return 0; }<file_sep>// Program to get next smallest number having same number of 1s in the binary representation as the give number #include<bits/stdc++.h> using namespace std; int nextSmallestNumber(int n){ int c0=0,temp=n,c1=0; //Counting the leftmost 0's before first 1 while(temp && !(temp&1)){ c0++; temp>>=1; } //Counting the 1's after that 0's while(temp && (temp&1)){ c1++; temp>>=1; } //Changing 0 after 1's to 1 int oneInc=1<<(c1+c0); n=n|oneInc; //Making leftmost 0's and 1's to 0 and rearrange it to make first (c1-1) bits to 1 n=n&oneInc; int ones=pow(2,c1-1)-1; n=n|ones; return n; } int main(){ int n; cin>>n; int ans=nextSmallestNumber(n); cout<<ans<<"\n"; return 0; }<file_sep>//Given two integers M and N (max 32 bit) and given two bit positions i and j, insert all bits of N into M such that bits oof N //start at index j and end at index i. #include<bits/stdc++.h> using namespace std; void binaryMix(int& m, int n, int i, int j){ //first check whether values of i and j are correct if(i<0 | j>31 | (j-i+1)!=((int)log2(n)+1)){ m=-1; return; } //creating a bitMask to make all required bits 0 int bitMask=pow(2,j-i+1)-1; bitMask=~(bitMask<<i); m=m&bitMask; //Inserting n into m n=n<<i; m|=n; } void printBinary32(int num){ for(unsigned i=1<<31;i>0;i=i>>1){ cout<<((num&i)?"1":"0"); } } int main(){ int m,n,i,j; cin>>m>>n>>i>>j; binaryMix(m,n,i,j); if(m==-1) cout<<m<<"\n"; else printBinary32(m); return 0; }<file_sep>#include<iostream> #include<limits.h> #include<vector> using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; void matrixMultiplication(int p, int arr[], vvi &m, vvi &s){ int n=p-1; for(int i=1;i<=n;i++){ m[i][i]=0; } for(int l=2;l<=n;l++){ for(int i=1;i<=n-l+1;i++){ int j=i+l-1; m[i][j]=INT_MAX; for(int k=i;k<j;k++){ int temp=m[i][k]+m[k+1][j]+arr[i-1]*arr[k]*arr[j]; if(temp<m[i][j]){ m[i][j]=temp; s[i][j]=k; } } } } } void print(vvi s, int i, int j){ if(i==j) cout<<" A"<<i<<" "; else{ cout<<"("; print(s,i,s[i][j]); print(s,s[i][j]+1,j); cout<<")"; } } int LookUp(int n, int arr[], vvi &m, vvi &s, int i, int j){ if(m[i][j]<INT_MAX) return m[i][j]; if(i==j){ m[i][j]=0; } else{ for(int k=i;k<j;k++){ int temp=LookUp(n,arr,m,s,i,k)+LookUp(n,arr,m,s,k+1,j)+arr[i-1]*arr[k]*arr[j]; if(temp<m[i][j]){ m[i][j]=temp; s[i][j]=k; } } } return m[i][j]; } void matrixMultiplicationMemoized(int p, int arr[], vvi &m, vvi &s){ int n=p-1; for(int i=1;i<=n;i++){ for(int j=i;j<=n;j++){ m[i][j]=INT_MAX; } } LookUp(n,arr,m,s,1,n); } int main(){ int n; cin>>n; vvi m(n,vi(n)),s(n,vi(n)); int dim[n]; for(int i=0;i<n;i++){ cin>>dim[i]; } // matrixMultiplication(n,dim,m,s); matrixMultiplicationMemoized(n,dim,m,s); cout<<"Minimum Cost : "<<m[1][n-1]<<"\n"; cout<<"Optimal Parenthesization : "; print(s,1,n-1); cout<<"\n"; return 0; }<file_sep>#include<iostream> #include<limits.h> #include<vector> int price[11]; using namespace std; int getMaxRecursive(int n){ if(n==0) return 0; int ans=INT_MIN; for(int i=0;i<n;i++){ ans=max(price[i],getMaxRecursive(n-i-1)); } return ans; } void getMaxBottomUp(int n, vector<int> &ans, vector<int> &way){ ans[0]=0; for(int i=1;i<=n;i++){ int temp=INT_MIN; for(int j=i;j>=1;j--){ if(temp<(price[j]+ans[i-j])){ temp=price[j]+ans[i-j]; way[i]=j; } } ans[i]=temp; } } int MemoizedCutRodAux(int n, vector<int> &ans){ if(ans[n]>=0){ return ans[n]; } int q; if(n==0) q=0; else{ q=INT_MIN; for(int i=1;i<=n;i++){ q=max(q,price[i]+MemoizedCutRodAux(n-i,ans)); } } ans[n]=q; return q; } int MemoizedCutRod(int n){ vector<int> ans(n+1); for(int i=0;i<=n;i++){ ans[i]=INT_MIN; } return MemoizedCutRodAux(n,ans); } int main(){ price[1]=1; price[2]=5; price[3]=8; price[4]=9; price[5]=10; price[6]=17; price[7]=17; price[8]=20; price[9]=24; price[10]=30; int n; cin>>n; // cout<<getMaxRecursive(n)<<"\n"; vector<int> ans(n+1),way(n+1); getMaxBottomUp(n,ans,way); cout<<"Length Cost Pieces\n"; for(int i=1;i<=n;i++){ printf("%6d%5d ",i,ans[i]); int j=i; while(j>0){ cout<<way[j]; j-=way[j]; if(j) cout<<"+"; } cout<<"\n"; } // cout<<MemoizedCutRod(n)<<"\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //Solution 1 via DP long long noOfWays1(int m, int n, int x) { long long dp[n+1][x+1]; //Initailizing 2d array with 0 for(int i=0;i<=n;i++){ for(int j=0;j<=x;j++){ dp[i][j]=0; } } //Making first row for(int i=1;i<=x && i<=m;i++){ dp[1][i]=1; } //Further for(int i=2;i<=n;i++){//i : No. of dice for(int j=i;j<=m*i && j<=x;j++){//j : Sum of dices for(int k=1;k<j && k<=m;k++){ dp[i][j]+=dp[i-1][j-k];//As assuming one dice to be taking values from 1 to m-1 and rest (i-1) dices having sum (j-k) } } } return dp[n][x]; } //Optimized Space DP version long long noOfWays2(int m, int n, int x) { long long dp[2][x+1]; //Initailizing array with 0 for(int i=1;i<=x;i++){ dp[0][i]=0; dp[1][i]=0; } //Making for only one dice for(int i=1;i<=x && i<=m;i++){ dp[0][i]=1; } //Further increasing number of dice for(int i=2;i<=n;i++){ // i: Number of dices for(int j=i;j<=m*i && j<=x;j++){ // j : Sum on dices for(int k=1;k<j && k<=m;k++){ dp[1][j]+=dp[0][j-k];//As assuming one dice to be taking values from 1 to m-1 and rest (i-1) dices having sum (j-k) } } for(int j=1;j<=x;j++){ dp[0][j]=dp[1][j]; dp[1][j]=0; } } return dp[0][x]; } int main(){ int m,n,x; cin>>m>>n>>x; // cout<<noOfWays1(m,n,x)<<"\n"; cout<<noOfWays2(m,n,x)<<"\n"; return 0; }<file_sep>//Egg dropping Puzzle Solution using DP #include<iostream> #include<limits.h> using namespace std; //DP Solution //Time Complexity : O(n*k^2) //Space Comlexity : O(n*k) int eggDrop1(int n, int k){ //dp[i][j] shows attemps with i eggs and k floors int dp[n+1][k+1]; //Initial values for(int i=0;i<=n;i++){ dp[i][0]=0;//As with 0 floors, we have 0 ways } for(int i=0;i<=k;i++){ dp[0][i]=0;//As with 0 eggs, we have 0 ways dp[1][i]=i;//As with 1 eggs, in worst case, we have to try with all floors one by one from down to top } //Further creating bottom-up Solution for(int i=2;i<=n;i++){ // i : Number of eggs for(int j=1;j<=k;j++){ // j : Number of floors dp[i][j]=INT_MAX; for(int m=1;m<=j;m++){ // m : trying with all floors to find floor with minimum tests in worst case // dp[i-1][m-1] : If egg broke at mth floor // dp[i][j-m] : If egg survive at mth floor // Take max out of above two(worst case) // 1 : for mth floor // Take minimum out of al floors dp[i][j]=min(dp[i][j],(1+max(dp[i-1][m-1],dp[i][j-m]))); } } } //Answer is dp[n][k] as we have to find attempts with n eggs and k floors return dp[n][k]; } //If u understand above solution, then this is just space optimized version of it //instead of using dp[n][k] space, we will use only dp[2][k] becoz we need only last second row to compute last row //Time Complexity : O(n*k^2) //Space Comlexity : O(k) int eggDrop2(int n, int k){ int dp[2][k+1]; for(int i=0;i<=k;i++){ dp[0][i]=i; } for(int i=2;i<=n;i++){ dp[1][0]=0; for(int j=1;j<=k;j++){ dp[1][j]=INT_MAX; for(int m=1;m<=j;m++){ dp[1][j]=min(dp[1][j],(1+max(dp[0][m-1],dp[1][j-m]))); } } for(int i=0;i<=k;i++){ dp[0][i]=dp[1][i]; } } return dp[0][k]; } //Driver Code int main(){ // n -> number of eggs // k -> number of floors int n,k; cin>>n>>k; // int ans=eggDrop1(n,k); int ans=eggDrop2(n,k); cout<<"Minimum Number of Trials = "<<ans<<"\n"; return 0; }<file_sep>//Program to find length of longest sequence of '1' in binary representation of a given number provided one flip of '0' to '1' is allowed #include<bits/stdc++.h> #include<math.h> using namespace std; //Simply taking each bit and making decision based on it and previous bit //Time Complexity : O(lg(n)) //Space Complexity : O(1) int findLongest1(int n){ int maxLen=0,tempLen=0,pre_last=0,pos=1,zeroPos=0; while(n){ int last_digit=n&1; if(last_digit==1){ tempLen++; } else if(last_digit==0 && pre_last==0){ zeroPos=pos; tempLen=1; } else{ tempLen=pos-zeroPos; zeroPos=pos; } if(tempLen>maxLen) maxLen=tempLen; n>>=1; pre_last=last_digit; pos++; } if(zeroPos==0) maxLen++; return maxLen; } //Storing count of 0 and 1 alternatively in another array and then finding best way to attach to 1 string //Time Complexity : O(lg(n)) //Space Complexity : O(lg(n)) int findLongest2(int n){ vector<int> count(1); count[0]=0; int i=0; while(n){ int last_digit=n&1; if(i%2==0){ if(last_digit==0){ count[i]++; } else{ i++; count.push_back(1); } } else{ if(last_digit==1){ count[i]++; } else{ i++; count.push_back(1); } } n=n>>1; } int ans=1; int s=count.size(); if(s==1) ans=1; else if(s==2) ans=count[1]+1; else{ if(count[0]==0) ans=count[1]; else ans=count[1]+1; for(i=2;i<s-1;i+=2){ if(count[i]==1) ans=max(count[i-1]+count[i+1]+1,ans); else ans=max(ans,max(count[i-1],count[i+1])+1); } } return ans; } void print(int n){ if(n>0){ print(n>>1); cout<<(n&1); } } int main(){ int n; cin>>n; cout<<"Binary Representation : \n"; print(n); cout<<"\n"; // int ans=findLongest1(n); int ans=findLongest2(n); cout<<ans<<"\n"; return 0; }<file_sep>//Program to find two repeating numbers in array containing (n+2) numbers in range 1...n #include<bits/stdc++.h> using namespace std; void findRepeating(int a[], int n, int& ans1, int& ans2){ int xor1=0,xor2=0; for(int i=1;i<=n;i++) xor1^=i; //XOR of 1...n for(int i=0;i<n+2;i++) xor2^=a[i]; //XOR of array int k=xor1^xor2; // k is ans1^ans2 xor1=0; xor2=0; int bitDiff=k&(~(k-1)); //Finding any set bit of k that will differ ans1 and ans2 (here we are taking first set bit) for(int i=1;i<=n;i++){ if(i&bitDiff) xor1^=i; //XORing in 1...n having bitDiff bit set else xor2^=i; // bitDiff not set } for(int i=0;i<n+2;i++){ if(a[i]&bitDiff) xor1^=a[i]; //XORing in array having bitDiff bit set else xor2^=a[i]; //bitDiff not set } ans1=xor1; //xor1 and xor2 will give ans1 and ans2 respectively as all other numbers cancel with each other ans2=xor2; } int main(){ int n,ans1,ans2; cin>>n; int a[n+2]; for(int i=0;i<n+2;i++) cin>>a[i]; findRepeating(a,n,ans1,ans2); cout<<ans1<<" "<<ans2<<"\n"; return 0; }<file_sep>//Program to turn off rightmost bit of a number #include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; //In (n+1), all right 1's before first 0 will become 0 and rightmost 1 will become 1 //After ORing n with (n+1) all number after rightmost 0 will not effected and before it, all are 1's will remain 1 and that 0 will become 1 n=n|(n+1); cout<<n<<"\n"; return 0; }<file_sep>#include<iostream> #include<limits.h> #include<vector> using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; void LCS(string x, string y, int m, int n, vvi &b, vvi &c){ for(int i=0;i<m+1;i++){ c[i][0]=0; } for(int i=0;i<n+1;i++){ c[0][i]=0; } for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ if(x[i-1]==y[j-1]){ b[i][j]=0; c[i][j]=c[i-1][j-1]+1; } else{ if(c[i-1][j]>c[i][j-1]){ b[i][j]=1; c[i][j]=c[i-1][j]; } else{ b[i][j]=2; c[i][j]=c[i][j-1]; } } } } } void print(string x, vvi b, int i, int j){ if(i==0 || j==0){ return; } if(b[i][j]==0){ print(x,b,i-1,j-1); cout<<x[i-1]; } else if(b[i][j]==1){ print(x,b,i-1,j); } else{ print(x,b,i,j-1); } } int main(){ string x,y; cin>>x>>y; int m=x.length(); int n=y.length(); vvi b(m+1,vi(n+1)),c(m+1,vi(n+1)); LCS(x,y,m,n,b,c); cout<<"Length of LCS : "<<c[m][n]<<"\n"; cout<<"LCS : "; print(x,b,m,n); return 0; }<file_sep>//Convert Little Endian to Big Endian and Vice Versa #include<bits/stdc++.h> using namespace std; int main(){ int num; scanf("%x",&num); //Any number taken in hexadecimal value printf("Intiatially :- 0x%x\n",num); //Take all 8 bits one by one by bit masking int first=num&(0x000000FF); int second=num&(0x0000FF00); int third=num&(0x00FF0000); int forth=num&(0xFF000000); //Rearrange it first<<=24; second<<=8; third>>=8; forth>>=24; //Combine it num=first|second|third|forth; printf("Finally :- 0x%x\n",num); return 0; }<file_sep>#include<iostream> #include<limits.h> using namespace std; int findAnswer(int n, int a[]){ int dp[n+1]; for(int i=1;i<=n;i++){ dp[i]=1; } for(int i=1;i<=n;i++){ for(int j=1;j<i;j++){ if(a[i]>a[j]){ dp[i]=max(dp[i],dp[j]+1); } } } int ans=dp[1]; for(int i=2;i<=n;i++){ if(dp[i]>ans) ans=dp[i]; } return ans; } int main(){ int t; cin>>t; for(int q=1;q<=t;q++){ int n; cin>>n; int a[n+1]; for(int i=1;i<=n;i++){ cin>>a[i]; } int ans=findAnswer(n,a); cout<<ans<<"\n"; } return 0; }<file_sep>//Program to find number in in array of unique (n-1) elements in range of 1...n #include<bits/stdc++.h> using namespace std; int findMissing(int a[], int n){ int xor1=0,xor2=0; for(int i=1;i<=n;i++){ xor1^=i; } for(int i=0;i<n-1;i++){ xor2^=a[i]; } return (xor1^xor2); } int main(){ int n; cin>>n; int a[n-1]; for(int i=0;i<n-1;i++) cin>>a[i]; int ans=findMissing(a,n); cout<<ans<<"\n"; return 0; }<file_sep>//Program for setting kth bit of a number #include<bits/stdc++.h> using namespace std; int settingKth(int &n, int k){ //(1<<(k-1)) will create a bit mask of form such that all bits are 0 other than kth bit // if kth bit is 1 in n, after ORing, it will remain 1 // else if kth bit is 0 in n, after ORing, it will become 1 return (n | (1<<(k-1))); } int main(){ int n,k; cin>>n; cin>>k; int ans=settingKth(n,k); cout<<ans<<endl; return 0; }<file_sep>//Program to clear kth bit of a number #include<bits/stdc++.h> using namespace std; int clearingKth(int &n, int k){ //(1<<(k-1)) will create a bit mask of form such that all bits are 0 other than kth bit // After negation, all bits of it will become 1 other than kth bit // if kth bit is 0 in n, after ANDing, it will remain 0 // else if kth bit is 1 in n, after ANDing, it will become 0 return (n & ~(1<<(k-1))); } int main(){ int n,k; cin>>n; cin>>k; int ans=clearingKth(n,k); cout<<ans<<endl; return 0; }<file_sep>//Program to turn off rightmost bit of a number #include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; //In (n-1), all right 0's before first 1 will become 1 and rightmost 1 will become 0 //After ANDing n with (n-1) all number after rightmost 1 will not effected and before it, all are 0's will remain 0 and that 1 will become 0 n=n&(n-1); cout<<n<<"\n"; return 0; }<file_sep>//Program to toggle kth bit of a number #include<bits/stdc++.h> using namespace std; int togglingKth(int &n, int k){ //(1<<(k-1)) will create a bit mask of form such that all bits are 0 other than kth bit // if kth bit is 1 in n, after XORing, it will become 0 // else if kth bit is 0 in n, after XORing, it will become 1 return (n ^ (1<<(k-1))); } int main(){ int n,k; cin>>n; cin>>k; int ans=togglingKth(n,k); cout<<ans<<endl; return 0; }<file_sep>//Program to compute A^n using bit manipulation #include<bits/stdc++.h> using namespace std; //Time Complexity : O(lg(n)) (In brute force, it is O(n)) //Space Complexity : O(1) int power(int a, int n){ int ans=1; while(n){ //(n&1) will give last bit if n (one by one we will explore all bits of n) int last_bit=n&1; if(last_bit==1) ans*=a; // if last bit is one, we need to take this value to a in consideration a=a*a;//at each time value becoming square n=n>>1;// to get next bit in next iteration } return ans; } int main(){ int a,n; cin>>a>>n; int ans=power(a,n); cout<<ans<<"\n"; return 0; }<file_sep>//Program to print nth term of a fibonacci series #include<iostream> using namespace std; int nthTerm(int n){ //First two values are 1 if(n==1 || n==2) return 1; else{ //Building Initial Value int lastT=1,lastST=1; for(int i=3;i<=n;i++){ int temp=lastST; lastST=lastT; lastT=temp+lastT;//By Definition } return lastT; } } int main(){ int n; cin>>n; int ans=nthTerm(n); cout<<ans<<"\n"; return 0; }<file_sep>//Program to check whether our machine is Little of Big Endian #include<bits/stdc++.h> using namespace std; int main(){ //num taken in hexadecimal value int num=0x12345678;//Takes 4 bytes char *p;//Takes 1 bytes(because we need to access byte by byte) p=(char *)&num;//Type casting //If the following print in same order, Big Endian //Else, if in reverse, Little Endian printf("%x",*p); p++; printf("%x",*p); p++; printf("%x",*p); p++; printf("%x",*p); return 0; }<file_sep>//Program to get minimum multipliction for a Matrix Chain Multiplication #include<iostream> #include<limits.h> using namespace std; int MCM(int n, int p[]){ //2D array storage for string optimized subsolutions int dp[n+1][n+1]; //Initializing diagonal elements to 0 as it represent multiplication of single matrix for(int i=1;i<=n;i++){ dp[i][i]=0; } //Taking chain length from 2 to n for(int l=2;l<=n;l++){ //Row index for(int i=1;i<=n-l+1;i++){ //Coloumn index int j=i+l-1; //Taking out minimum number of multiplication for chain A(i)*A(i+1)*----*A(j) int min=INT_MAX; for(int k=i;k<j;k++){ int temp=dp[i][k]+dp[k+1][j]+p[i-1]*p[k]*p[j]; if(temp<min){ min=temp; } } dp[i][j]=min; } } //Because we need answer for chain A(1)*A(2)*----*A(n) return dp[1][n]; } int main(){ int n; //Input the number of matrices cin>>n; int p[n+1]; //Size of matrices in continous order (n+1) entries for(int i=0;i<=n;i++){ cin>>p[i]; } int ans=MCM(n,p); cout<<ans<<"\n"; return 0; }<file_sep>//Program to print first n terms of a fibonacci series #include<iostream> using namespace std; void nthTerm(int n, int ans[]){ //First two values are 1 ans[1]=1; ans[2]=1; //Remaining for(int i=3;i<=n;i++){ ans[i]=ans[i-1]+ans[i-2];//Definition } } int main(){ int n; cin>>n; int ans[n+1]; nthTerm(n,ans); for(int i=1;i<=n;i++){ cout<<ans[i]<<" "; } return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int knapSackRecursiveUtil(int w, int wt[], int val[], int i, int tempW, int total){ if(tempW>w) return 0; //Sack overloaded if(tempW==w || i==-1) return total;//Capacity reached or items exhausted //There are two possibilies for each each:- //(i):Keep it in sack int temp=knapSackRecursiveUtil(w,wt,val,i-1,tempW+wt[i],total+val[i]); //(ii):Dont keep it in sack temp=max(temp,knapSackRecursiveUtil(w,wt,val,i-1,tempW,total)); return temp; } //Recursive Solution int knapSackRecursive(int w, int wt[], int val[], int n){ int tempW=0; int total=0; return knapSackRecursiveUtil(w,wt,val,n-1,tempW,total); } //DP Solution int knapSackDP(int w, int wt[], int val[], int n){ int dp[n+1][w+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=w;j++){ dp[i][j]=INT_MIN; } } //Initialization dp[0][0]=0; for(int i=0;i<n;i++){ for(int j=0;j<=w;j++){ if(dp[i][j]!=INT_MIN){ dp[i+1][j]=max(dp[i+1][j],dp[i][j]);//Not Taking (i+1)th value if((j+wt[i+1])<=w) dp[i+1][j+wt[i+1]]=max(dp[i+1][j+wt[i+1]],(dp[i][j]+val[i+1]));//Taking (i+1)th value } } } //Now, answer is max out of last row int ans=dp[n][0]; for(int i=1;i<=w;i++){ if(dp[n][i]>ans) ans=dp[n][i]; } return ans; } int main(){ //n:-Number of items //w:-Capacity of knap Sack int n,w; cin>>w>>n; //wt:-Array containing the weight of each item //val:-Array containing corresponding value int wt[n+1],val[n+1]; for(int i=1;i<=n;i++){ cin>>wt[i]>>val[i]; } // cout<<knapSackRecursive(w,wt,val,n)<<"\n"; cout<<knapSackDP(w,wt,val,n)<<"\n"; return 0; }<file_sep>//Maximum Product Cutting #include<iostream> using namespace std; // DP Solution // Time Complexity : O(n^2) // Space Complexity : O(n) int maxProduct(int n){ int dp[n+1]={}; dp[0]=dp[1]=0; for(int i=2;i<=n;i++){ // i : Rod Length for(int j=1;j<i;j++){ // j : Checking where to cut // (i*(i-j)) : We have just a cut a jth position, no other cut // j*dp[i-j] : Cut at jth position, and keep rod of length j and for remaining length of (i-j) using optimization dp[i]=max(dp[i],max((i*(i-j)),j*dp[i-j])); } } return dp[n]; } //Driver Code int main(){ int n; // n : length of rod cin>>n; int ans=maxProduct(n); cout<<ans<<"\n"; return 0; }
d576d45bdd7ee7c27a90bfcd97b4cd300187cbc5
[ "C++" ]
27
C++
GeekyCoder001/CP-Solutions
e10894e2392dbf58b17a40f7154d7f10203753bd
2df87097c41afa3e68d54da17c61c2146028e1be
refs/heads/master
<repo_name>arsenie96paul/Python<file_sep>/100369891/server.py # Server import socket import sys import random import array import re import select def within(guess, random, med): dif = abs(random - guess) if dif == 0: return 0 elif dif < med and dif > 0: return 1 else: return 2 #client client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.bind(("127.0.0.1", 4000)) client.listen(5) #admin admin = socket.socket(socket.AF_INET, socket.SOCK_STREAM) admin.bind(("127.0.0.1", 4001)) admin.listen(5) FIRST = 1 SECOND = 2 THIRD = 3 sockets = [] adresses = [] rnd = {} steps ={} sockets.append(client) sockets.append(admin) while True: ( r, w, e) = select.select(sockets, [], []) for variable in r: if ( variable == client): (conn,addr) = variable.accept() sockets.append(conn) adresses.append(addr) info = conn.recv(80).decode().strip() if ( info == "Hello"): conn.send("Greetings\r\n".encode()) info = conn.recv(80).decode().strip() if ( info == "Game"): conn.send("Ready\r\n".encode()) randomNumber = random.randrange(0,30) rnd[conn] = randomNumber elif (variable == admin): (conn,addr) = variable.accept() info = conn.recv(80).decode().strip() if ( info == "Hello"): conn.send("Admin-Greetings\r\n".encode()) info = conn.recv(80).decode().strip() if ( info == "Who"): adress = " " for elements in adresses: adress += str(elements[0]) + " " + str(elements[1]) + "\n" conn.send(adress.encode()) else : number = conn.recv(80).decode() number = int(number.split(":")[1]) final = within(number, rnd[conn],3) if (final == 0): conn.send("Correct\r\n".encode()) conn.close() break else: if ( final == 1) : conn.send("Close\r\n".encode()) elif ( final == 2): conn.send("Far\r\n".encode()) <file_sep>/100369891/pclient.py # Client import socket import sys host = "127.0.0.1" port = 4000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.send("Hello\r\n".encode()) recieved = s.recv(80).decode().strip() if recieved == "Greetings": s.send("Game\r\n".encode()) recieved = s.recv(80).decode().strip() if recieved == "Ready": print("Welcome to the guess the number game!") while True: try: InsertNumber = input("What is your guess? ") s.send(("My guess is:" + InsertNumber).encode()) recieved3 = s.recv(80).decode().strip() if recieved3 == "Far": print("You are way off.") elif recieved3 == "Close": print("You are close!") elif recieved3 == "Correct": print("You guessed correctly!") s.close() break except ConnectionResetError: pass <file_sep>/100369891/aclient.py #Admin import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", 4001)) s.send('Hello\r\n'.encode()) info = s.recv(80).decode() if ( info == "Admin-Greetings\r\n" ): s.send("Who\r\n".encode()) print ( "The players currently playing are:") info = s.recv(10000).decode() print(info) s.close()
a6196319e484c598a8e909c8b4f2d4e4b7c57f78
[ "Python" ]
3
Python
arsenie96paul/Python
b9fd212a72e4e9b6294a7d6c1a8ff5315681bca3
e6ac58022985d56c565986e640be52c485ff816e
refs/heads/master
<repo_name>Vyan4033/penjualan_tv<file_sep>/pages/index.js import User from "./user/HomeUser" export default function Home() { return ( <div> <User/> </div> ) } <file_sep>/components/props/Jumbotron.js import "bootstrap/dist/css/bootstrap.min.css" import Link from 'next/link' export default function jumbotron(props){ return( <div> <div className="position-relative overflow-hidden p-3 p-md-5 m-md-3 text-center bg-light"> <div className="col-md-5 p-lg-5 mx-auto my-5"> <h1 className="display-4 fw-normal">{props.judul}</h1> <p className="lead fw-normal">{props.isi}</p> </div> </div> </div> ) }<file_sep>/pages/admin/DataTV.js //@ts-check import DataTV from "../../components/admin/Data-TV" import Layout from "../../components/admin/LayoutAdmin" const Data = () => { return( <div> <Layout> <DataTV/> </Layout> </div> ) } export default Data<file_sep>/pages/admin/TambahDt.js //@ts-check import Tambahtv from '../../components/admin/TambahTV' import Layout from '../../components/admin/LayoutAdmin' const TambahDt = () => { return( <div> <Layout> <Tambahtv/> </Layout> </div> ) } export default TambahDt<file_sep>/components/user/DataTV.js //@ts-check import Link from "next/link" const DataTV = ({data}) => { return( <div className="container"> <h3 className="font-bold text-center">Data Paket</h3> <table className="table"> <thead> <tr> <th className="text-center">ID</th> <th className="text-center">Nama Televisi</th> <th className="text-center">Harga</th> <th className="text-center">Aksi</th> </tr> </thead> <tbody> { data.map((tv, idx) => ( <tr key={idx}> <td> {tv.id} </td> <td> {tv.nama} </td> <td className="text-center"> {tv.harga} </td> <td> <div className="d-flex justify-content-center"> <Link href="/Pemesanan"> <button className = "btn btn-primary">Pesan</button> </Link> </div> </td> </tr> )) } </tbody> </table> </div> ) } export default DataTV<file_sep>/components/user/Layout.js import Homepage from '../../../project/components/user/homepage'; const Layout = ({children}) => { return ( <div> <Homepage/> {children} </div> ); } export default Layout;<file_sep>/penjualantv.sql -- phpMyAdmin SQL Dump -- version 4.9.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 15, 2021 at 06:40 PM -- Server version: 10.4.8-MariaDB -- PHP Version: 7.1.33 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `penjualantv` -- -- -------------------------------------------------------- -- -- Table structure for table `televisi` -- CREATE TABLE `televisi` ( `id` varchar(250) NOT NULL, `nama` varchar(5000) NOT NULL, `harga` varchar(500) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `televisi` -- INSERT INTO `televisi` (`id`, `nama`, `harga`) VALUES ('01', 'Samsung LED Curved TV 49\"', 'Rp. 6.500.000'), ('02', 'Sony LED TV 32\"', 'Rp. 2.500.000'), ('03', 'Sony LED TV 48\"', 'Rp. 5.300.000'), ('04', 'LG LED TV 55\"', 'Rp. 8.250.000'), ('05', 'Panasonic LED TV 32\"', 'Rp. 1.700.000'), ('06', 'Sharp LED TV 32\"', 'Rp. 1.800.000'); -- -- Indexes for dumped tables -- -- -- Indexes for table `televisi` -- ALTER TABLE `televisi` ADD PRIMARY KEY (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/components/Pemesanan.js import 'bootstrap/dist/css/bootstrap.min.css' export default function pemesanan(){ return( <div> <div className="text-center"> <h2>Form Pemesanan</h2> </div> <div className="mb-3 container"> <input type="email" className="form-control" id="exampleFormControlInput1" placeholder="Alamat Email"/> <input type="password" className="form-control" id="exampleFormControlInput1" placeholder="<NAME>"/> <input type="email" className="form-control" id="exampleFormControlInput1" placeholder="Alamat"/> <select className="form-select" aria-label="Default select example"> <option selected>Pilihan TV</option> <option value="Samsung LED Curved TV 49 Inch">Samsung LED Curved TV 49 Inch</option> <option value="Sony LED TV 32 Inch">Sony LED TV 32 Inch</option> <option value="Sony LED TV 48 Inch">Sony LED TV 48 Inch</option> <option value="LG LED TV 55 Inch">LG LED TV 55 Inch</option> <option value="Panasonic LED TV 32 Inch">Panasonic LED TV 32 Inch</option> <option value="Sharp LED TV 32 Inch">Sharp LED TV 32 Inch</option> </select> </div> <div className="container"> <h4>Metode Pembayaran</h4> <select className="form-select" aria-label="Default select example"> <option selected>--Pilih Metode Pembayaran--</option> <option value="Indomaret">Indomaret</option> <option value="Alfamart">Alfamart</option> <option value="Gopay">Gopay</option> </select> </div> <div className="mb-3 container text-center"> <button type="button" className="btn btn-primary">Bayar</button> </div> </div> ) }<file_sep>/components/user/homepage.js import Link from 'next/link' export default function homePage(){ return( <div> <header className="blog-header py-3 bg-info"> <div className="row flex-nowrap justify-content-between align-items-center"> <div className="col-15 text-center pt-1"> <Link href="/admin/DataTV"> <h2 className="blog-header-logo text-dark">Mahkota TV</h2> </Link> </div> </div> </header> <div> <nav className="nav d-flex justify-content-center"> <Link href="/"><a className="p-2 link-secondary">Home</a></Link> <Link href="/user/DataUser"><a className="p-2 link-secondary">Data Televisi</a></Link> <Link href="/Pemesanan"><a className="p-2 link-secondary">Pemesanan</a></Link> </nav> </div> </div> ) }<file_sep>/components/admin/Data-TV.js //@ts-check import Link from 'next/link' import Router from 'next/router' import { mutate } from 'swr'; import { useData } from '../../lib/swr-fetch' const dataTV = () => { const {data, error} = useData(); if (error) { return <div>Error Loading</div> } if (!data) { return <div>Loading</div> } console.log(data) async function hapusTV(id){ let res = await fetch(`/api/hapusData?id=${id}`, {method : 'DELETE'}) let json = await res.json() if (!res.ok) throw Error(json.message) mutate('/api/hapusData') alert('Data dihapus') Router.push('/admin/DataTV') } return( <div className="container w-75 mx-auto py-4"> <h3 className="font-bold text-center">Data Televisi</h3> <table className="table"> <thead> <tr> <th className="text-center">ID</th> <th className="text-center">Nama Televisi</th> <th className="text-center">Harga Televisi</th> <th className="text-center">Aksi</th> </tr> </thead> <tbody> { data.map((tv, idx) => ( <tr key={idx}> <td className="text-center"> {tv.id} </td> <td className="text-center"> {tv.nama} </td> <td className="text-center"> {tv.harga} </td> <td className="text-center"> <div className="d-flex justify-content-between"> <Link href={`/admin/UpdateDt? &id=${tv.id} &nama=${tv.nama} &harga=${tv.harga}`} > <button className = "btn btn-primary">Edit</button> </Link> <button className = "btn btn-danger" value={tv.id} onClick={(e) => hapusTV(e.target.value)}> Delete </button> </div> </td> </tr> )) } </tbody> </table> <div className="text-center"> <Link href="/admin/TambahDt"> <a className="btn btn-primary">Tambahkan</a> </Link> </div> </div> ) } export default dataTV<file_sep>/pages/admin/UpdateDt.js //@ts-check import Layout from "../../components/admin/LayoutAdmin"; import Update from "../../components/admin/UpdateTV"; const UpdateTV = () => { return( <div> <Layout> <Update/> </Layout> </div> ) } export default UpdateTV<file_sep>/components/admin/UpdateTV.js //@ts-check import Router, { useRouter } from "next/router"; import { useEffect, useState } from "react"; const Update = () => { const [_id, setId] = useState(''); const [_nama, setNama] = useState(''); const [_harga, setHarga] = useState(''); const router = useRouter(); const { id, nama, harga } = router.query; useEffect(() => { if (typeof id == 'string') { setId(id); } if (typeof nama == 'string') { setNama(nama); } if (typeof harga == 'string') { setHarga(harga); } }, [id, nama, harga, id]) const submitHandler = async (e) => { e.preventDefault() try { const res = await fetch('/api/updateData', { method: 'PATCH', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ id: _id, nama: _nama, harga: _harga, }), }) const json = await res.json() if (!res.ok) throw Error(json.message) alert("Update Berhasil") Router.push('/admin/DataTV') } catch (e) { throw Error(e.message) } } return( <div> <div className="container mt-4"> <form className="w-50 mx-auto" onSubmit={submitHandler}> <h2 className="text-center">Update Data Televisi</h2> <div className="form-floating"> <input className="form-control mb-2" id = "id" type = "text" placeholder = "ID" value = {_id} onChange = {(e) => setId(e.target.value)} /> <label htmlFor="id">ID</label> </div> <div className="form-floating"> <input className="form-control mb-2" id = "nama" type = "text" placeholder = "Nama Televisi" value = {_nama} onChange = {(e) => setNama(e.target.value)} /> <label htmlFor="nama">Nama Televisi</label> </div> <div className="form-floating"> <input className="form-control mb-2" id = "harga" type = "text" placeholder = "Harga" value = {_harga} onChange = {(e) => setHarga(e.target.value)} /> <label htmlFor="harga">Harga</label> </div> <div className="text-center"> <button className="btn btn-primary" type="submit"> Update </button> </div> </form> </div> </div> ) } export default Update<file_sep>/pages/Pemesanan.js import Pembayaran from '../components/Pemesanan' import Layout from '../components/user/Layout' export default function Bayar(){ return( <div> <Layout> <Pembayaran/> </Layout> </div> ) }<file_sep>/pages/user/HomeUser.js import Jumbotron from "../../components/props/Jumbotron"; import Layout from "../../components/user/Layout"; const UserHome = () => { let jumbo = {judul : "Mahkota Televisi", isi : "Disini kami memiliki Televisi idaman yang nyaman dan aman untuk keluarga. Merupakan keinginan setiap orang. Oleh karena itu kami akan mewujudkan impian anda. Tersedia berbagai tipe dan harga yang bersahabat." } return( <div> <Layout> <Jumbotron judul = {jumbo.judul} isi = {jumbo.isi}/> </Layout> </div> ) } export default UserHome
737725e92799c657d313de7adec1fc36f87f248f
[ "JavaScript", "SQL" ]
14
JavaScript
Vyan4033/penjualan_tv
bab2acf28de14643807532b63b0835f39c255bf3
25a67052f9a0b6e6969314f1c17ffca46aba98ee
refs/heads/master
<file_sep>// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // This application uses the Azure IoT Hub device SDK for .NET // For samples see: https://github.com/Azure/azure-iot-sdk-csharp/tree/master/iothub/device/samples using System; using Microsoft.Azure.Devices.Client; using Newtonsoft.Json; using System.Text; using System.Threading.Tasks; using NLog; using System.Collections.Generic; using System.IO; using System.IO.Compression; using Microsoft.Extensions.Configuration; namespace simulated_device { class SimulatedDevice { private static DeviceClient s_deviceClient; private static DeviceModel[] s_devices; private static Logger _logger; // The device connection string to authenticate the device with your IoT hub. // Using the Azure CLI: // az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyDotnetDevice --output table private readonly static string s_connectionString = "XXX"; /// <summary> /// Number of different devices /// </summary> private const int NB_DEVICE = 10; /// <summary> /// Number of values sent by batch /// </summary> private const int NB_VALUES = 100; /// <summary> /// Delay between batch of value /// </summary> private const int DELAY = 5000; // Async method to send simulated telemetry private static async void SendDeviceToCloudMessagesAsync() { int loopDevice = 0; int countMessage = 1; while (true) { var telemetryDataPoints = new List<DeviceModel>(NB_VALUES); for (int loopValue = 0; loopValue < NB_VALUES; loopValue++) { var telemetryDataPoint = s_devices[loopDevice].NextValue(); telemetryDataPoints.Add(telemetryDataPoint); loopDevice++; if (loopDevice >= NB_DEVICE) loopDevice = 0; } var messageString = JsonConvert.SerializeObject(telemetryDataPoints); byte[] inputBytes = Encoding.UTF8.GetBytes(messageString); _logger.Info("Sending message. Uncompressed data is {0} bytes", inputBytes.Length); Message message; using (var outputStream = new MemoryStream()) { // Cf. http://gigi.nullneuron.net/gigilabs/compressing-strings-using-gzip-in-c/ using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress)) gZipStream.Write(inputBytes, 0, inputBytes.Length); var outputBytes = outputStream.ToArray(); _logger.Info("Sending message. Compressed data is {0} bytes", outputBytes.Length); message = new Message(outputBytes); } // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. //message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); // Send the telemetry message await s_deviceClient.SendEventAsync(message); _logger.Info("Message {0} sent", countMessage); _logger.Info("Waiting {0}ms", DELAY); await Task.Delay(DELAY); countMessage++; ; } } private static void initializeDevices() { s_devices = new DeviceModel[NB_DEVICE]; for (int i = 0; i < NB_DEVICE; ++i) { s_devices[i] = new DeviceModel(); } } private static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); _logger = LogManager.GetCurrentClassLogger(); _logger.Info("IoT Hub Quickstarts #1 - Simulated device. Ctrl-C to exit."); try { // Connect to the IoT hub using the MQTT protocol s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt); _logger.Info("Device Client initialized"); initializeDevices(); _logger.Info("Devices initialized"); SendDeviceToCloudMessagesAsync(); Console.ReadLine(); } catch (Exception ex) { // NLog: catch any exception and log it. _logger.Error(ex, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) LogManager.Shutdown(); } } } } <file_sep>using System; namespace simulated_device { public class DeviceModel { // CONST public const double MAX_HUMIDITY = 100; public const double MIN_HUMIDITY = 0; public const double MAX_TEMPERATURE = 100; public const double MIN_TEMPERATURE = -40; private static readonly Random rand = new Random(); // telemetry values public double Temperature { get; set; } public double Humidity { get; set; } public Guid DeviceId { get; set; } public DeviceModel() { Temperature = 20; Humidity = 60; this.DeviceId = Guid.NewGuid(); } public DeviceModel(double temperature, double humidity, Guid deviceId) { this.Temperature = temperature; this.Humidity = humidity; this.DeviceId = deviceId; } public DeviceModel NextValue() { Temperature = Temperature + rand.NextDouble() * 15 - 7.5; Temperature = Math.Max(MIN_TEMPERATURE, Temperature); Temperature = Math.Min(MAX_TEMPERATURE, Temperature); Humidity = Humidity + rand.NextDouble() * 20 - 10; Humidity = Math.Max(MIN_HUMIDITY, Humidity); Humidity = Math.Min(MAX_TEMPERATURE, Humidity); return new DeviceModel { DeviceId = DeviceId, Temperature = Temperature, Humidity = Humidity }; } } }
2f873baa7238ba59237966ec30220afd72ce9521
[ "C#" ]
2
C#
r3dlin3/AzureIoTQuickstarts
52034d1a67d6955564376c7c33f6df64624c7d0b
e5ec981d65fddad91ff9ebfe8769a984134e7ce5
refs/heads/master
<repo_name>m-alcu/dcf77-receivers<file_sep>/README.md # dcf77-receivers DCF receivers examples #### Simple_Clock_Lcd LCD IC2 connected to SCL & SCA of ARDUINO, take care of the addreess, LCD may have 0x27 or 0x3F address DCF77 receiver connected to A3 (non inverted signal), pull up 5K resistor conecting RF output to VCC <file_sep>/Simple_Clock_Json_Pings/Simple_Clock_Json_Pings.ino // // www.blinkenlight.net // // Copyright 2016 <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 detailSerial. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ #include <dcf77.h> #include <PriUint64.h> const uint8_t dcf77_analog_sample_pin = 3; const uint8_t dcf77_sample_pin = 17; // A5 == d19 const uint8_t dcf77_inverted_samples = 0; const uint8_t dcf77_analog_samples = 0; const uint8_t dcf77_pin_mode = INPUT; // disable internal pull up //const uint8_t dcf77_pin_mode = INPUT_PULLUP; // enable internal pull up const uint8_t dcf77_monitor_led = 13; // A4 == d18 uint8_t ledpin(const uint8_t led) { return led; } uint16_t countBits = 0; uint16_t ms_counter = 0; uint64_t messageBuffer = 0; uint64_t outputBuffer = 0; uint8_t sample_input_pin() { const uint8_t sampled_data = #if defined(__AVR__) dcf77_inverted_samples ^ (dcf77_analog_samples? (analogRead(dcf77_analog_sample_pin) > 200) : digitalRead(dcf77_sample_pin)); #else dcf77_inverted_samples ^ digitalRead(dcf77_sample_pin); #endif if (sampled_data == 1) { countBits++; } digitalWrite(ledpin(dcf77_monitor_led), sampled_data); return sampled_data; } void output_handler(const Clock::time_t &decoded_time) { ms_counter = countBits; countBits = 0; messageBuffer = messageBuffer << 1; if (ms_counter > 150) { messageBuffer = messageBuffer | 1; } int sec = BCD::bcd_to_int(decoded_time.second); if (sec == 0) { outputBuffer = messageBuffer; Serial.print("guardo output segundo: "); Serial.println(sec); } } int signalQual = 0; int clockState = 0; void setup() { using namespace Clock; Serial.begin(9600); pinMode(ledpin(dcf77_monitor_led), OUTPUT); pinMode(dcf77_sample_pin, dcf77_pin_mode); DCF77_Clock::setup(); DCF77_Clock::set_input_provider(sample_input_pin); DCF77_Clock::set_output_handler(output_handler); // Wait till clock is synced, depending on the signal quality this may take // rather long. About 5 minutes with a good signal, 30 minutes or longer // with a bad signal for (uint8_t state = Clock::useless; state == Clock::useless || state == Clock::dirty; state = DCF77_Clock::get_clock_state()) { // wait for next sec Clock::time_t now; DCF77_Clock::get_current_time(now); SendStatus(now); } } void loop() { Clock::time_t now; DCF77_Clock::get_current_time(now); if (now.month.val > 0) { SendStatus(now); } } void SendStatus(Clock::time_t now) { switch (DCF77_Clock::get_clock_state()) { case Clock::useless: clockState = 1; break; case Clock::dirty: clockState = 2; break; case Clock::synced: clockState = 3; break; case Clock::locked: clockState = 4; break; } Serial.print("{\"ClockState\":"); Serial.print(clockState); Serial.print(",\"SignalQual\":"); Serial.print(DCF77_Clock::get_prediction_match()); Serial.print(",\"Weekday\":"); Serial.print(BCD::bcd_to_int(now.weekday)); Serial.print(",\"Day\":"); Serial.print(BCD::bcd_to_int(now.day)); Serial.print(",\"Month\":"); Serial.print(BCD::bcd_to_int(now.month)); Serial.print(",\"Year\":"); Serial.print(2000+BCD::bcd_to_int(now.year)); Serial.print(",\"Summertime\":"); Serial.print(now.uses_summertime? 2: 1); Serial.print(",\"ChangeScheduled\":"); Serial.print(now.timezone_change_scheduled? 1: 0); Serial.print(",\"Hour\":"); Serial.print(BCD::bcd_to_int(now.hour)); Serial.print(",\"Minute\":"); Serial.print(BCD::bcd_to_int(now.minute)); Serial.print(",\"Second\":"); Serial.print(BCD::bcd_to_int(now.second)); Serial.print(",\"LeapSecond\":"); Serial.print(now.leap_second_scheduled? 1: 0); Serial.print(",\"MSCounter\":"); Serial.print(ms_counter); Serial.print(",\"Buffer\":"); Serial.print(Serial.print(PriUint64<BIN>(outputBuffer))); Serial.print("}"); Serial.println(""); } <file_sep>/Simple_Clock_Lcd/Simple_Clock_Lcd.ino // // www.blinkenlight.net // // Copyright 2016 <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/ #include <dcf77.h> #include <LiquidCrystal_I2C.h> const uint8_t dcf77_analog_sample_pin = 3; const uint8_t dcf77_sample_pin = 17; // A5 == d19 const uint8_t dcf77_inverted_samples = 0; const uint8_t dcf77_analog_samples = 0; const uint8_t dcf77_pin_mode = INPUT; // disable internal pull up //const uint8_t dcf77_pin_mode = INPUT_PULLUP; // enable internal pull up const uint8_t dcf77_monitor_led = 13; // A4 == d18 uint8_t ledpin(const uint8_t led) { return led; } uint16_t countBits = 0; uint8_t level = 0; uint16_t pulse = 0; uint8_t sample_input_pin() { const uint8_t sampled_data = #if defined(__AVR__) dcf77_inverted_samples ^ (dcf77_analog_samples? (analogRead(dcf77_analog_sample_pin) > 200) : digitalRead(dcf77_sample_pin)); #else dcf77_inverted_samples ^ digitalRead(dcf77_sample_pin); #endif if (level != sampled_data) { if (level == 0) countBits = 0; if (level == 1) pulse = countBits; } countBits++; level = sampled_data; digitalWrite(ledpin(dcf77_monitor_led), sampled_data); return sampled_data; } int signalQual = 0; //LiquidCrystal_I2C lcd(0x27,16,2); LiquidCrystal_I2C lcd(0x3F,16,2); void setup() { using namespace Clock; lcd.init(); lcd.backlight(); pinMode(ledpin(dcf77_monitor_led), OUTPUT); pinMode(dcf77_sample_pin, dcf77_pin_mode); DCF77_Clock::setup(); DCF77_Clock::set_input_provider(sample_input_pin); // Wait till clock is synced, depending on the signal quality this may take // rather long. About 5 minutes with a good signal, 30 minutes or longer // with a bad signal for (uint8_t state = Clock::useless; state == Clock::useless || state == Clock::dirty; state = DCF77_Clock::get_clock_state()) { // wait for next sec Clock::time_t now; DCF77_Clock::get_current_time(now); SendStatus(now); } } void loop() { Clock::time_t now; DCF77_Clock::get_current_time(now); if (now.month.val > 0) { SendStatus(now); } } void SendStatus(Clock::time_t now) { lcd.setCursor(0,0); switch (BCD::bcd_to_int(now.weekday)) { case 1: lcd.print("Mon"); break; case 2: lcd.print("Tue"); break; case 3: lcd.print("Wed"); break; case 4: lcd.print("Thu"); break; case 5: lcd.print("Fri"); break; case 6: lcd.print("Sat"); break; case 7: lcd.print("Sun"); break; } lcd.setCursor(4,0); printDigits(BCD::bcd_to_int(now.day)); lcd.print("/"); lcd.setCursor(7,0); printDigits(BCD::bcd_to_int(now.month)); lcd.setCursor(9,0); lcd.print("/"); lcd.setCursor(10,0); lcd.print(2000+BCD::bcd_to_int(now.year)); lcd.setCursor(14,0); lcd.print("+"); lcd.setCursor(15,0); lcd.print(now.uses_summertime? 2: 1); lcd.setCursor(0,1); if (pulse < 100) { lcd.print("0"); } lcd.print(pulse); lcd.setCursor(3,1); switch (DCF77_Clock::get_clock_state()) { case Clock::useless: lcd.print("U"); break; case Clock::dirty: lcd.print("D"); break; case Clock::synced: lcd.print("S"); break; case Clock::locked: lcd.print("L"); break; } lcd.setCursor(4,1); signalQual = DCF77_Clock::get_prediction_match(); if (signalQual == 255 || signalQual == 0 ) { lcd.print(" "); } else { if (signalQual < 10) { lcd.print("0"); } lcd.print(signalQual); } lcd.setCursor(6,1); lcd.print(now.timezone_change_scheduled? "H": " "); lcd.setCursor(7,1); printDigits(BCD::bcd_to_int(now.hour)); lcd.setCursor(9,1); lcd.print(":"); lcd.setCursor(10,1); printDigits(BCD::bcd_to_int(now.minute)); lcd.setCursor(12,1); lcd.print(":"); lcd.setCursor(13,1); printDigits(BCD::bcd_to_int(now.second)); lcd.setCursor(15,1); lcd.print(now.leap_second_scheduled? "S": " "); } void printDigits(int digits){ // utility function for digital clock display: prints preceding colon and leading 0 if(digits < 10) lcd.print('0'); lcd.print(digits); }
73dcc978275f660b4c635068829d18f95b40cea3
[ "Markdown", "C++" ]
3
Markdown
m-alcu/dcf77-receivers
91a2205e1061a5cd666640c6667ba79473c76f17
d9b41a068eccda14c37fae5be5b8e9a45d30ce7f
refs/heads/master
<file_sep>window.addEventListener("load", async function () { let innerHtmlButtons = window.localStorage.getItem("user") ? "<li><button class='custom-button' id='sair'>Sair</button>" : "<li><button class='custom-button' id='entrar'>Entrar</button></li><li><button class='custom-button' id='cadastrar'>Cadastrar</button></li>"; document.getElementById("buttons").innerHTML = innerHtmlButtons; var mySwiper = new Swiper(".swiper-container", { pagination: { el: ".swiper-pagination", clickable: true, }, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, slidesPerView: 1, breakpoints: { 768: { slidesPerView: 2, }, 1024: { slidesPerView: 3, }, }, }); document .getElementsByClassName("mask")[0] .addEventListener("click", toggleSidebar); document .getElementsByClassName("sm-only")[0] .addEventListener("click", toggleSidebar); let response; // Checking if api is online try { response = await fetch("https://rotten-potatos-api.herokuapp.com/ping"); let data = await response.text(); console.info(data); init(); } catch (error) { console.warn(error); console.info(response); } }); function init() { let stars = document.getElementsByClassName("star"); let thumbs = document.getElementsByClassName("thumbs"); let details = document.getElementsByClassName("see-more"); for (let i = 0; i < details.length; i++) { details[i].addEventListener("click", openDescription); } if (window.localStorage.getItem("user")) { for (var i = 0; i < thumbs.length; i++) { thumbs[i].addEventListener("click", like); stars[i].addEventListener("click", favorite); } } else { for (var i = 0; i < thumbs.length; i++) { stars[i].addEventListener("click", () => { Toast.show( "Você não está logado!", "Faça login para poder favoritar um filme!", "info", false ); }); thumbs[i].addEventListener("click", () => { Toast.show( "Você não está logado!", "Faça login para poder dar like em um filme!", "info", false ); }); } } let comments = document.getElementsByClassName("comment"); for (var i = 0; i < comments.length; i++) { comments[i].addEventListener("click", comment); } let buttonAddComment = document.getElementById("addComment"); buttonAddComment.addEventListener("click", addComment); } toggleSidebar = () => { document.getElementsByClassName("mask")[0].classList.toggle("hide"); document.getElementById("navbar").classList.toggle("sidebar"); }; animModal = (modal, animType) => { let modalElement = document.getElementById(modal); if (animType === "open") modalElement.classList.add("showModalAnim"); else modalElement.classList.remove("showModalAnim"); }; toggleModal = (modal) => { document.getElementById(modal).classList.toggle("hide"); }; addComment = async (e) => { e.preventDefault(); let id_filme = parseInt(window.sessionStorage.getItem("idForComment")); console.log("Filme id: ", id_filme); let json = { id_filme, id_usuario: JSON.parse(window.localStorage.getItem("user")).id, texto: document.getElementById("userComment").value, }; const options = { method: "POST", body: JSON.stringify(json), headers: { "Content-Type": "application/json", }, }; console.log(options); let response; try { response = await fetch( "https://rotten-potatos-api.herokuapp.com/comentar ", options ); let text = await response.text(); if (text == "Salvo!") { e.target.classList.toggle("star-selected"); Toast.show("Sucesso", "Comentário adicionado!", "success", false); } else { Toast.show( "Erro ao comentar!", "Houve algum problema ao comentar, tente novamente!", "error", true ); } } catch (error) { console.warn(error); console.info(response); } }; comment = async (e) => { if (window.localStorage.getItem("user")) { console.log(e.target.dataset); window.sessionStorage.setItem( "idForComment", parseInt(e.target.dataset.filmeid, 10) ); animModal("modalComments", "open"); toggleModal("modalComments"); } else { Toast.show( "Você não está logado!", "Faça login para poder adicionar um comentário!", "info", false ); } }; favorite = async (e) => { let id_filme = parseInt(e.target.dataset.filmeid, 10); console.log("Filme id: ", id_filme); let json = { id_filme, id_usuario: JSON.parse(window.localStorage.getItem("user")).id, }; const options = { method: "POST", body: JSON.stringify(json), headers: { "Content-Type": "application/json", }, }; let response; try { response = await fetch( "https://rotten-potatos-api.herokuapp.com/favoritar", options ); let text = await response.text(); if (text == "Favoritado!") { e.target.classList.toggle("star-selected"); Toast.show( "Sucesso", "Filme adicionado aos seus favoritos!", "success", false ); } else { Toast.show( "Erro ao favoritar!", "Houve algum problema ao favoritar, tente novamente!", "error", true ); } } catch (error) { console.warn(error); console.info(response); } }; like = async (e) => { let id_filme = parseInt(e.target.dataset.filmeid, 10); console.log("Filme id: ", id_filme); let json = { id_filme, id_usuario: JSON.parse(window.localStorage.getItem("user")).id, }; const options = { method: "POST", body: JSON.stringify(json), headers: { "Content-Type": "application/json", }, }; let response; try { response = await fetch( "https://rotten-potatos-api.herokuapp.com/like", options ); let text = await response.text(); if (text == "Liked!") { e.target.classList.toggle("thumbs-selected"); Toast.show( "Sucesso", "Você deu like em um filme!", "success", false ); history.go(0); } else { Toast.show( "Erro dar like!", "Houve algum problema ao dar Like, tente novamente!", "error", true ); } } catch (error) { console.warn(error); console.info(response); } }; openDescription = (e) => { document.getElementById("film" + e.target.dataset.filmeid).submit(); }; sleep = (ms) => { console.info("Sleep: ", ms); return new Promise((resolve) => setTimeout(resolve, ms)); }; <file_sep>class Toast { static show(title, text, type, showConfirmButton){ Swal.fire({ toast: true, position: "top", showConfirmButton, title, text, type, }); } }<file_sep>window.addEventListener("load", async function () { try { let response = await fetch( "https://rotten-potatos-api.herokuapp.com/filmes" ); let data = await response.json(); generateCards(data); init(); } catch (error) { console.warn(error); } function generateCards(data) { let cardsContainer = document.getElementById("cards"); let allCards = ""; for (const filme of data) { let cardHtml = ` <div class="card cursor-normal"> <div class="overlay"> <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-star star" style="margin: 20px;" data-filmeid="${filme.id}"> <polygon data-filmeid="${filme.id}" points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"> </polygon> </svg> <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-thumbs-up thumbs" style="margin: 20px;" data-filmeid="${filme.id}"> <path data-filmeid="${filme.id}" d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"> </path> </svg> <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-message-square comment" style="margin: 20px;" data-filmeid="${filme.id}"> <path data-filmeid="${filme.id}" d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path> </svg> <form action="description.html" method="GET" id="film${filme.id}"> <input type="text" name="filmeId" style="display:none;" value="${filme.id}" /> <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye see-more" style="margin: 20px;" data-filmeid="${filme.id}"> <path data-filmeid="${filme.id}" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path> <circle data-filmeid="${filme.id}" cx="12" cy="12" r="3"></circle> </svg> </form> </div> <img src="${filme.url_capa}" style="width: 100%;" /> <div class="card-content"> <h4><b>${filme.titulo}</b></h4> <p>${filme.sinopse}</p> </div> </div> `; allCards += cardHtml; } cardsContainer.innerHTML = allCards; } }); <file_sep>window.addEventListener("load", async function () { if (window.localStorage.getItem("user")) { document.getElementById("sair").addEventListener("click", async () => { console.log("Log out..."); window.localStorage.removeItem("user"); Toast.show( "Sucesso!", "LOGOUT realizado com sucesso, você será redirecionado automaticamente!", "success", false ); await sleep(1500); history.go(0); }); let buttonModalComments = document.getElementById( "closeModalCommentsButton" ); if (buttonModalComments) document .getElementById("closeModalCommentsButton") .addEventListener("click", () => { animModal("modalComments", "close"); toggleModal("modalComments"); }); } else { document.getElementById("entrar").addEventListener("click", () => { animModal("modalLogin", "open"); toggleModal("modalLogin"); }); document .getElementById("closeModalLoginButton") .addEventListener("click", () => { animModal("modalLogin", "close"); toggleModal("modalLogin"); }); document.getElementById("cadastrar").addEventListener("click", () => { animModal("modalSignup", "open"); toggleModal("modalSignup"); }); document .getElementById("closeModalSignupButton") .addEventListener("click", () => { animModal("modalSignup", "close"); toggleModal("modalSignup"); }); } document .getElementById("formLogin") .addEventListener("submit", async (event) => { event.preventDefault(); let object = {}; for (let index = 0; index < 2; index++) { object[event.target[index].id] = event.target[index].value; } let json = JSON.stringify(object); console.log(json); const options = { method: "POST", body: json, headers: { "Content-Type": "application/json", }, }; try { console.clear(); let response = await fetch( "https://rotten-potatos-api.herokuapp.com/login", options ); let json = await response.json(); window.localStorage.setItem("user", JSON.stringify(json)); Toast.show( "Sucesso!", "LOGIN realizado com sucesso, você será redirecionado automaticamente!", "success", false ); await sleep(1500); animModal("modalLogin", "close"); toggleModal("modalLogin"); history.go(0); } catch (error) { Toast.show( "Erro durante o login!", "Houve algum problema com seu login, verifique suas informações e tente novamente!", "error", false ); console.warn(error); } }); document .getElementById("formSignup") .addEventListener("submit", async (event) => { event.preventDefault(); let object = {}; for (let index = 0; index < 4; index++) { object[event.target[index].id] = event.target[index].value; } let json = JSON.stringify(object); console.log(json); const options = { method: "POST", body: json, headers: { "Content-Type": "application/json", }, }; try { console.clear(); let response = await fetch( "https://rotten-potatos-api.herokuapp.com/cadastro", options ); let text = await response.text(); if (text == "Salvo") { Toast.show( "Sucesso!", "Cadastro realizado com sucesso, faça seu login!", "success", false ); animModal("modalSignup", "close"); toggleModal("modalSignup"); } else { Toast.show( "Erro durante o cadastro!", "Houve algum problema com seu cadastro, verifique suas informações e tente novamente!", "error", false ); } } catch (error) { console.warn(error); } }); }); <file_sep>window.addEventListener("load", async function () { if (!window.localStorage.getItem("user")) { document.getElementById("addComment").disabled = true; document.getElementById("addComment").classList.add("disabled"); } let response; let responseComments; try { let url_string = window.location.href; //window.location.href let url = new URL(url_string); let filmeId = url.searchParams.get("filmeId"); window.sessionStorage.setItem("idForComment", filmeId); response = await fetch( "https://rotten-potatos-api.herokuapp.com/filme/" + filmeId ); let data = await response.json(); fillValues(data); responseComments = await fetch( "https://rotten-potatos-api.herokuapp.com/comentarios/" + filmeId ); let comments = await responseComments.json(); fillComments(comments); init(); } catch (error) { console.warn(error); console.info(response); console.info(responseComments); } function fillValues(film) { let descriptionContainer = document.getElementById("description"); let content = ` <div class="container"> <div class="film-panel cursor-normal"> <div class="banner-film"> <img src="${film.url_capa}" style="width: 100%;" /> </div> <div class="panel-content"> <h4><b>${film.titulo}</b></h4> <p>${film.sinopse}</p> <div class="panel-actions"> <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="stroke-black feather feather-star star" style="margin: 10px 10px 10px 0;" data-filmeid="${film.id}"> <polygon data-filmeid="${film.id}" points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"> </polygon> </svg> <div class="button-likes"> <span>${film.count_likes}</span> <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="stroke-black feather feather-thumbs-up thumbs" style="margin: 10px;" data-filmeid="${film.id}"> <path data-filmeid="${film.id}" d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"> </path> </svg> </div> </div> </div> </div> </div> `; descriptionContainer.innerHTML = content; } function fillComments(comments) { console.log(comments); let commentsContainer = document.getElementById("comments"); let allComments = ""; for (const comment of comments) { let content = ` <div class="comment"> <h4>Usuario ${comment.id_usuario} <span>${comment.data}</span></h4> <p> ~ ${comment.texto}</p> </div> `; allComments += content; } commentsContainer.innerHTML = allComments; } });
e6aa164ef027864c72234127d45e501bf88905d1
[ "JavaScript" ]
5
JavaScript
andrehgdias/rotten-potatos-website
b3af8ad9d8763a32e5e558a89fcbccb5b2a87e57
3aee430359fae561c65b40f2acb8044c0e9357cb
refs/heads/master
<repo_name>rallyfanru/motec<file_sep>/runme.sh #!/bin/bash D_FILENAME="dsdsADSADSaDSAD" if [ $# = 0 ] then echo "Для запуска скрипта используйте опции командной строки:" echo "-f Имя файла с логом абита (обязательный параметр)" exit fi while getopts ":f:" optname do case "$optname" in "f") if [ -e $OPTARG ] ; then echo -e "\033[1mУстановка параметров:\033[0m Используется abit - файл $OPTARG" D_FILENAME=$OPTARG else echo -en "\E[31;40m\033[4m\033[1mОшибка!\033[0m: " echo "Файл $OPTARG не найден!" fi ;; "?") echo -en "\E[31;40m\033[4m\033[1mОшибка!\033[0m: " echo "Неизвестный параметр $OPTARG" ;; ":") echo -en "\E[31;40m\033[4m\033[1mОшибка!\033[0m: " echo "Отсутствует параметр для $OPTARG" ;; *) # Соответствий не найдено echo -en "\E[31;40m\033[4m\033[1mОшибка!\033[0m: " echo "Unknown error while processing options" ;; esac # echo "OPTIND is now $OPTIND" done if [ ! -e $D_FILENAME ] ; then echo -en "\E[31;40m\033[4m\033[1mОшибка!\033[0m: " echo "Опущен обязательный параметр -f, указано неверное имя файла, или файл не существует" exit fi if [ ! -e ./result ] ; then mkdir ./result fi echo -e "\033[1mВыполняется:\033[0m" TMPFILE=`mktemp` echo "- Конвертирование в UTF-8, удаление лишнего..." head -1 $D_FILENAME|iconv -f cp1251 -t utf8|sed 's/\x0D$//' > $TMPFILE cat $D_FILENAME|iconv -f cp1251 -t utf8|grep -P '^\d'|sed -e 's/\,/\./g'|sed 's/\x0D$//' >> $TMPFILE echo "done" echo "- Используется временный файл $TMPFILE..." filename=$(basename $D_FILENAME) motecfile="./result/"${filename%.*}.ld echo "- Конвертирование в motec лог $motecfile..." ./ab2mot $TMPFILE $motecfile <file_sep>/README.md abit -> motec ============= Конвертер. Для сборки выполнить make. Запускается .sh скриптом с параметром -f и путем до csv файла. На выходе создает какой-то бинарник. <file_sep>/defin.h #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <errno.h> #include <math.h> #define MAXLINE 1000 /* максимальная длина строки */ #define STARTITEM 0x78601 // 0x3448 /*начало описания элементов*/ #define ITEMCOUNT 6 /*заглушка на время */ #define MAXITEM 18 //Максимальное количество элементов. typedef struct { int prevchain; int nextchain; int offsettodata; unsigned int samplecount; short f1; short f2; short databyte; short samplerate; short f5; short f6w; short f7w; short decimalplaces; char long_description[32]; char shortdecr[8]; char unitname[8]; int u1; unsigned int maxvalue; int minvalue; int u4[4]; int crc; int u5[2]; int u6; } itemhead; itemhead item_list[MAXITEM]; // struct items { // short enabled; // struct itemhead *link; // short datanum; // }; /* Номера жестко привязаны, добавлять только в конец! */ char *head_strings[] = { "время, мс", //0 "B0, мб/мрс (атмосферное давление)", //1 "DFP, bar (Давление топлива)", //2 "DOP, bar (Давление масла)", //3 "Fдр, % (положение дросселя)", //4 "GF_A, G (Ускорение поперечное)", //5 "GF_L, G (Ускорение продольное)", //6 "GPSALTITUDE, m (Высота над уровнем моря)", //7 "GPSDATE, ##.##.##", //8 "GPSLATITUDE, ggmm.m (Широта)", //9 "GPSLONGITUDE, ggmm.m (Долгота)", //10 "GPSSPEED, км/ч (Горизонтальная скорость)", //11 "GPSTIME, ##.##.##", //12 "GPSTRACK, ° (Направление)", //13 "N, 1/мин (обороты двигателя)", //14 "Uб, В (напряжение бортсети)", //15 "Твзд, °C (температура воздуха)", //16 "Тож, °C (температура ОЖ)" //17 }; #define iTIME 0 #define iATM 1 #define iDFP 2 #define iDOP 3 #define iDROS 4 #define iGF_A 5 #define iGF_L 6 #define iGPSALT 7 #define iGPSDATE 8 #define iGPSLAT 9 #define iGPSLONG 10 #define iGPSSPEED 11 #define iGPSTIME 12 #define iGPSTRACK 13 #define iN 14 #define iU 15 #define iAIR 16 #define iTEMP 17 char read_head[MAXITEM][200]; short key_item[MAXITEM]; int min[MAXITEM]; int max[MAXITEM]; char head_data[STARTITEM]; void init_itemlist(short samplecount, short samplerate) { int i; for(i=0; i< MAXITEM; i++){ //Значения общие для большинства элементов item_list[i].samplecount=samplecount; item_list[i].samplerate=samplerate; item_list[i].f5=0; item_list[i].f6w=1; item_list[i].f7w=1; item_list[i].u1=0; //item_list[i].u4=0; item_list[i].crc=0; //item_list[i].u5=0; item_list[i].u6=0; } /* Барометрической давление */ item_list[1].f1=2; item_list[1].f2=3; item_list[1].databyte=2; item_list[1].decimalplaces=0; strcpy(item_list[1].long_description,"Baro Pres"); strcpy(item_list[1].shortdecr,"BAP"); strcpy(item_list[1].unitname,"kPa"); /* Давление топлива */ item_list[2].f1=2; item_list[2].f2=3; item_list[2].databyte=2; item_list[2].decimalplaces=2; strcpy(item_list[2].long_description,"Fuel Pres"); strcpy(item_list[2].shortdecr,"FP"); strcpy(item_list[2].unitname,"bar"); /* Давление тормозов */ item_list[3].f1=2; item_list[3].f2=3; item_list[3].databyte=2; item_list[3].decimalplaces=2; strcpy(item_list[3].long_description,"Brake Pres"); strcpy(item_list[3].shortdecr,"BP"); strcpy(item_list[3].unitname,"bar"); /* Дроссель */ item_list[4].f1=2; item_list[4].f2=3; item_list[4].databyte=2; item_list[4].decimalplaces=1; strcpy(item_list[4].long_description,"Throttle Pos"); strcpy(item_list[4].shortdecr,"Throttle"); strcpy(item_list[4].unitname,"%"); /* Ускорение продольное */ item_list[5].f1=15; item_list[5].f2=3; item_list[5].databyte=2; item_list[5].decimalplaces=3; strcpy(item_list[5].long_description,"G Force Lat"); strcpy(item_list[5].shortdecr,"G Force"); strcpy(item_list[5].unitname,"G"); /* Ускорение поперечное */ item_list[6].f1=15; item_list[6].f2=3; item_list[6].databyte=2; item_list[6].decimalplaces=3; strcpy(item_list[6].long_description,"G Force Long"); strcpy(item_list[6].shortdecr,"G Force"); strcpy(item_list[6].unitname,"G"); // /* GPS высота */ item_list[7].f1=8099; item_list[7].f2=5; item_list[7].databyte=2; item_list[7].decimalplaces=1; strcpy(item_list[7].long_description,"GPS Altitude"); strcpy(item_list[7].shortdecr,"GPS Alt"); strcpy(item_list[7].unitname,"m"); // /* GPS LAT */ item_list[9].f1=8112; item_list[9].f2=5; item_list[9].databyte=4; item_list[9].decimalplaces=7; strcpy(item_list[9].long_description,"GPS Latitude"); strcpy(item_list[9].shortdecr,"GPSLat"); strcpy(item_list[9].unitname,"deg"); // /* GPS Long */ item_list[10].f1=8113; item_list[10].f2=5; item_list[10].databyte=4; item_list[10].decimalplaces=7; strcpy(item_list[10].long_description,"GPS Longitude"); strcpy(item_list[10].shortdecr,"GPSLong"); strcpy(item_list[10].unitname,"deg"); // /* GPS Speed */ item_list[11].f1=121; item_list[11].f2=3; item_list[11].databyte=2; item_list[11].decimalplaces=1; strcpy(item_list[11].long_description,"GPS Speed"); strcpy(item_list[11].shortdecr,"GPS Spd"); strcpy(item_list[11].unitname,"km/h"); /* RPM */ item_list[14].f1=1; item_list[14].f2=4; item_list[14].databyte=2; item_list[14].decimalplaces=0; strcpy(item_list[14].long_description,"Engine RPM"); strcpy(item_list[14].shortdecr,"Engine"); strcpy(item_list[14].unitname,"rpm"); /* U, В */ item_list[15].f1=26; item_list[15].f2=3; item_list[15].databyte=2; item_list[15].decimalplaces=1; strcpy(item_list[15].long_description,"Bat Volts ECU"); strcpy(item_list[15].shortdecr,"ECU BV"); strcpy(item_list[15].unitname,"V"); /* Температура воздуха */ item_list[16].f1=5; item_list[16].f2=3; item_list[16].databyte=2; item_list[16].decimalplaces=0; strcpy(item_list[16].long_description,"Air Temp Manifold"); strcpy(item_list[16].shortdecr,"AT M"); strcpy(item_list[16].unitname,"C"); /* Температура воды */ item_list[17].f1=5; item_list[17].f2=3; item_list[17].databyte=2; item_list[17].decimalplaces=0; strcpy(item_list[17].long_description,"Engine Temp"); strcpy(item_list[17].shortdecr,"Engine"); strcpy(item_list[17].unitname,"C"); }; double convert_gps(double gpsin) { int grad=0; gpsin = gpsin / 100.0; grad = (int) gpsin; //берет только целую часть, не округляя gpsin = (gpsin - grad)*100.0/60.0; gpsin += grad; return gpsin; };<file_sep>/Makefile # Makefile ab2mot: main.o gcc -o ab2mot main.o -lm main.o: main.c gcc -c main.c clean: rm -f *.o *.a *.so *.bin *.ld ab2mot good: rm -f *.o *.a *.so <file_sep>/main.c /* main.c */ #include "defin.h" int main (int argc, char ** argv) { FILE *fp, *motec, *head; char line[MAXLINE], *p; char *st, *endptr; int i, k, j; char *outname; char logdate[] = "01/01/2000"; char logtime[] = "12:00:00"; int datea, dateb, datec; short item_size=sizeof(itemhead); int data_start=STARTITEM; //реальное вычисление ниже. int data_size=0; int nextchain=STARTITEM; //реальное вычисление ниже. int prevchain=0; int lastchain=0; unsigned int samplecount; short samplerate; short not_first=0; //Флаг первой строки из файла, чтоб минимумы правильно считать int itemcount = sizeof(head_strings)/sizeof(head_strings[0]); //количество строк в массиве // double data[MAXLINES][MAXITEM]; double **data; data =(double **)calloc(1,sizeof(double *)); //data указатель на массив указателей //чтобы определить какие элементы есть в файле, изначально массив соответствия индексов //заполняется -1 (0 есть в индексах). Потом все что больше 0 - присутствует. for(i=0;i<itemcount;i++) key_item[i] = -1; outname=argv[2]; /******************************************************************************************************************** * * Обработка входа * ********************************************************************************************************************/ if ((fp = fopen(argv[1], "r")) == NULL){ printf("Ошибка открытия файла с входными данными. \n"); return 1; } //В первой строке заголовок p = fgets(line, MAXLINE, fp); st = strtok(p, ";"); k=0; strcpy(read_head[k],st); while(st) { st = strtok('\0', ";"); if(st !=NULL) { k++; strcpy(read_head[k],st); }; } //Из последнего символа надо удалить \n j=strlen(read_head[k]) - 1; if ( read_head[k][j-1] == 0x0D) read_head[k][j-1]='\0'; if ( read_head[k][j] == 0x0A) read_head[k][j]='\0'; //Магия. Определение по заголовку столбца, что за данные в нем //Номера элементов head_strings совпадают с номерами item_list //В результате в массиве key_item соответствие элементов for(j=0; j <= k; j++){ int a; for(a=0; a < itemcount; a++){ if( strcmp(read_head[j], head_strings[a]) == 0 ) { key_item[a] = j; break; } } } //Просто, чтоб увидеть чего оно там наделало // for(j=0; j < itemcount; j++){ // if(key_item[j] >= 0) printf("Индекс: %d Номер ст. в файле: %d Описание: %s \n",j,key_item[j],head_strings[j]); // } //Остальные строки с данными for (i = 0; (p = fgets(line, MAXLINE, fp)) != NULL; i++) { int ar=0; st = strtok(p, ";"); data = (double **)realloc(data, (i+1)*sizeof(*data)); if(data == NULL){ printf("Ошибка выделения памяти под массив data\n"); return 1; } data[i]=(double *)calloc(itemcount,sizeof(double)); data[i][ar]=strtod(st,&endptr); while(st) { st = strtok('\0', ";"); if(st !=NULL) { ar++; data[i][ar]=strtod(st,&endptr); }; } //Избавляемся от точки в дробном значении if(key_item[iDFP] > 0) data[i][key_item[iDFP]] = data[i][key_item[iDFP]] * 100.0; if(key_item[iDOP] > 0) { if(data[i][key_item[iDOP]] < 0) data[i][key_item[iDOP]]=0.0; data[i][key_item[iDOP]] = data[i][key_item[iDOP]] * 100.0; } if(key_item[iDROS] > 0) data[i][key_item[iDROS]] =data[i][key_item[iDROS]] * 10.0; // if(key_item[iTEMP] > 0) data[i][key_item[iTEMP]] =data[i][key_item[iTEMP]] * 10.0; // if(key_item[iAIR] > 0) data[i][key_item[iAIR]] =data[i][key_item[iAIR]] * 10.0; if(key_item[iU] > 0) data[i][key_item[iU]] =data[i][key_item[iU]] * 10.0; if(key_item[iGF_A] > 0) data[i][key_item[iGF_A]] =data[i][key_item[iGF_A]] * 1000.0; if(key_item[iGF_L] > 0) data[i][key_item[iGF_L]] =data[i][key_item[iGF_L]] * 1000.0; if(key_item[iGPSSPEED] > 0) data[i][key_item[iGPSSPEED]]=data[i][key_item[iGPSSPEED]] * 10.0; if(key_item[iGPSALT] > 0) data[i][key_item[iGPSALT]] =data[i][key_item[iGPSALT]] * 10.0; if(key_item[iGPSLAT] > 0) { data[i][key_item[iGPSLAT]] = convert_gps(data[i][key_item[iGPSLAT]]) * 10000000; }; if(key_item[iGPSLONG] > 0) { data[i][key_item[iGPSLONG]] = convert_gps(data[i][key_item[iGPSLONG]]) * 10000000; }; if(!not_first){ for(j=0; j <= ar; j++){ min[j]=(int) round(data[i][j]); max[j]=(int) round(data[i][j]); } not_first++; } for(j=0; j <= ar; j++){ if( (int) round(data[i][j]) > max[j] ) max[j] = (int) round(data[i][j]); if( (int) round(data[i][j]) < min[j] ) min[j] = (int) round(data[i][j]); } } fclose(fp); samplecount = i; samplerate=(int) round(i / data[i-1][0]); printf("Частота: %d Hz \nКоличество элементов: %d \n",samplerate, samplecount); init_itemlist(samplecount,samplerate); //Заполнение массива элементов заголовка i=0; for(j=0; j < itemcount; j++){ if(key_item[j] >= 0 && strlen(item_list[j].long_description) > 0) { data_start+=item_size; i++; } } printf("Старт данных: 0x%x \nРазмер секции данных: %d (0x%x) \nСекций: %d \n",data_start,data_size,data_size,i); printf("Размер элемента: %d (0x%x)\n",sizeof(itemhead),sizeof(itemhead)); //data[2][iGPSDATE] //data[2][iGPSTIME] datea = (int) data[2][iGPSTIME]/10000; dateb = (int) (data[2][iGPSTIME]/100 - datea * 100.0); datec = (int) (data[2][iGPSTIME] - datea * 10000.0 - dateb * 100.0); datea = datea + 4; //GMT + 4 sprintf(logtime,"%02d:%02d:%02d",datea,dateb,datec); datea = (int) data[2][iGPSDATE]/10000; dateb = (int) (data[2][iGPSDATE]/100 - datea * 100.0); datec = (int) (data[2][iGPSDATE] - datea * 10000.0 - dateb * 100.0); sprintf(logdate,"%02d/%02d/20%02d",datea,dateb,datec); printf("Дата %s \n",logdate); printf("Время %s \n",logtime); /*************************************************************************************************************** * * Запись мотека * ***************************************************************************************************************/ if ((head=fopen("data/head_noname.bin", "r")) == NULL){ printf("Ошибка открытия файла шаблона заголовка. \n"); return 1; } fread(&head_data, sizeof(head_data),1, head); fclose(head); printf("Заголовок: %d (0x%x) \n",sizeof(head_data),sizeof(head_data)); if ((motec=fopen(outname, "a+")) == NULL){ printf("Ошибка открытия motec-файла %s! \n",outname); return 1; } fwrite(&head_data, sizeof(head_data), 1, motec); /* запись заголовков */ i=0; for(j=0; j < itemcount; j++){ if(key_item[j] >= 0 && strlen(item_list[j].long_description) > 0) //есть ли элемент в файле и есть ли для него описание { if(i > 0) prevchain=nextchain - item_size; nextchain=STARTITEM+(i+1)*item_size; if (j+1 == itemcount) nextchain=lastchain; item_list[j].nextchain=nextchain; item_list[j].prevchain=prevchain; item_list[j].offsettodata=data_start; item_list[j].maxvalue=max[j]; item_list[j].minvalue=min[j]; data_start=data_start+samplecount*item_list[j].databyte; printf("%d %s N: %x P: %x D: %x dD: %x Min: %d Max: %d \n",j,item_list[j].long_description,nextchain,prevchain,item_list[j].offsettodata,samplecount*item_list[j].databyte,item_list[j].minvalue,item_list[j].maxvalue); fwrite(&item_list[j], sizeof(item_list[j]), 1, motec); i++; } } /* запись самих данных */ for(j=0; j < itemcount; j++){ if(key_item[j] >= 0 && strlen(item_list[j].long_description) > 0) //есть ли элемент в файле и есть ли для него описание { for(i=0; i < samplecount; i++){ if(item_list[j].databyte == 4){ // В зависимости от размера данных, 4 или 2 байта на значение int fbdata=data[i][key_item[j]]; fwrite(&fbdata, sizeof(fbdata), 1, motec); }else{ short tbdata=data[i][key_item[j]]; fwrite(&tbdata, sizeof(tbdata), 1, motec); }; //free(data[i]); } } } fclose(motec); //free(data); motec=fopen(outname, "r+"); fseek(motec, 0x0C, SEEK_SET); fwrite(&data_start, sizeof(data_start), 1, motec); fseek(motec, 0x05E, SEEK_SET); fwrite(&logdate, sizeof(logdate), 1, motec); fseek(motec, 0x07E, SEEK_SET); fwrite(&logtime, sizeof(logtime), 1, motec); fclose(motec); return 0; }
fd54fe45b6d501a3f64939f0862e0d2e28eb0a00
[ "Markdown", "C", "Makefile", "Shell" ]
5
Shell
rallyfanru/motec
6e42103eb0919a0244b04ca7b0cd06057abc456f
d8e3804f4e1119ea83bfb74afd55e9691cdcc5ec
refs/heads/master
<file_sep>#pragma once #include "Model.h" #include "ModelInstance.h" #include "RushHour.h" class Vehicle : public ModelInstance { public: // Constructors Vehicle() = delete; Vehicle(Model& m) : ModelInstance(m) {} Vehicle(Model& m, DirectX::XMMATRIX scale, DirectX::XMVECTOR alignment, bool rotate180, unsigned short length); Vehicle(const Vehicle&) = default; Vehicle(Vehicle&&) = default; Vehicle& operator= (const Vehicle&) = default; Vehicle& operator= (Vehicle&&) = default; ~Vehicle() {}; // Transformation methods void SetMovementStep(float s); DirectX::XMMATRIX GetTransformation() const; DirectX::XMMATRIX GetInitRotation() const; float GetMovementStep() const { return _movementStep; } bool IsRotated180() const { return _rotate180; } // Graphics settings methods float GetGlowLevel() const { return _glowLevel; } void SetGlowLevel(float glowLevel) { _glowLevel = glowLevel; } // Collision testing methods bool IsOccupyingPosition(Coords2i_t pos) const; unsigned short GetLength() const { return _length; } // Other methods void Hide() { _displayed = false; } // Do not display this vehicle void Show() { _displayed = true; } // Display this vehicle bool IsHidden() const { return !_displayed; } private: // Transformation matrices and vars bool _rotate180 = false; float _movementStep = 0.0f; // Auxiliary vars unsigned short _length = 1; // Graphics settings vars bool _displayed = false; float _glowLevel = 0.0f; }; <file_sep>#pragma once #include <DirectXMath.h> #include "Model.h" class Marker { public: // Constructors Marker() = delete; Marker(Model& m) : _model(m) {} Marker(Model& m, DirectX::XMMATRIX scale); Marker(const Marker&) = default; Marker(Marker&&) = default; Marker& operator= (const Marker&) = default; Marker& operator= (Marker&&) = default; ~Marker() {} // Transformation methods void SetPosition(Coords3f_t coords) { _position = coords; } void SetPosition(float x, float y, float z) { SetPosition({ x, y, z }); } DirectX::XMMATRIX GetTransformation() const; DirectX::XMMATRIX GetInitRotation() const { return _rotation; } Coords3f_t GetPosition() const { return _position; } DirectX::XMMATRIX GetScale() const { return _scale; } // Other methods Model& GetModel() const { return _model; } void Hide() { _displayed = false; } // Do not display this marker void Show() { _displayed = true; } // Display this marker bool IsHidden() const { return !_displayed; } private: // Reference to polygon model Model& _model; // Transformation matrices and vars DirectX::XMMATRIX _scale = DirectX::XMMatrixIdentity(); // scale instance size Coords3f_t _position = { 0.0f, 0.0f, 0.0f }; // positon instance DirectX::XMMATRIX _rotation = DirectX::XMMatrixIdentity(); // rotate the instance into the initial position // Graphics settings vars bool _displayed = true; }; <file_sep>#include "stdafx.h" #include "CommonException.h" <file_sep>#pragma once #include <vector> #include <DirectXMath.h> #include "RushHour.h" #include "D3DSupplementary.h" #include "assimp\Importer.hpp" #include "assimp\mesh.h" #include "assimp\types.h" #include "assimp\vector3.h" #include "assimp\postprocess.h" #include "assimp\scene.h" class Model { private: #define INVALID_MATERIAL 0xFFFFFFFF struct MeshEntry { MeshEntry() { _numIndices = 0; _baseVertex = 0; _baseIndex = 0; _materialIndex = INVALID_MATERIAL; _pTexture = nullptr; } unsigned int _numIndices; unsigned int _baseVertex; unsigned int _baseIndex; unsigned int _materialIndex; ID3D11ShaderResourceView* _pTexture; // texture buffer }; /* Common vertex and index buffer for all models */ static std::vector<VERTEX> _objectVertices; static std::vector<VVERTEX> _objectVVertices; static std::vector<UINT> _objectIndices; std::vector<MeshEntry> _entries; // metadata for model instance Assimp::Importer _imp; const aiScene* _pScene = nullptr; const aiMesh* _pMesh = nullptr; public: Model(const char* pFile, ID3D11Device* dev); Model(const Model&) = delete; Model(Model&&) = default; Model& operator= (const Model&) = delete; Model& operator= (Model&&) = default; ~Model(); const aiScene* GetScene() const { return _pScene; }; const std::vector<MeshEntry> GetMeshEntries() const { return _entries; } static const std::vector<VERTEX> GetModelVertices() { return _objectVertices; } static const std::vector<VVERTEX> GetModelVVertices() { return _objectVVertices; } static const std::vector<UINT> GetModelIndices() { return _objectIndices; }; }; <file_sep># RushHour RushHour 3D game (DirectX 11). You must help the red car to leave the parking lot! <file_sep>#include "stdafx.h" #include <d3dcompiler.h> #include "ShadowRenderer.h" #include "CommonException.h" void ShadowRenderer::LoadRenderTextureShaders() { // load and compile vertex and pixel shader ID3D10Blob *VS, *PS; D3DCompileFromFile(L"shadow.shader", NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "VShader", "vs_4_0", 0, 0, &VS, NULL); D3DCompileFromFile(L"shadow.shader", NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "PShader", "ps_4_0", 0, 0, &PS, NULL); if (FAILED(_d3d->GetDevice()->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &_rtvs))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D vertex shader!"); } if (FAILED(_d3d->GetDevice()->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &_rtps))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D pixel shader!"); } // create the input layout object D3D11_INPUT_ELEMENT_DESC ied[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (FAILED(_d3d->GetDevice()->CreateInputLayout(ied, 3, VS->GetBufferPointer(), VS->GetBufferSize(), &_rtlayout))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D input layout!"); } } void ShadowRenderer::ConfigureRendering() { _d3d->SetBuffers(); // Set default Vertex, Index and Constant buffer _d3d->SetViewport(); // select which primtive type we are using _d3d->GetDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // select Rasterizer and Sampler configuration _d3d->GetDeviceContext()->RSSetState(_d3d->GetRState()); _d3d->GetDeviceContext()->PSSetSamplers(0, 1, _d3d->GetSStateWrapAddr()); _d3d->GetDeviceContext()->PSSetSamplers(1, 1, _d3d->GetSStateClampAddr()); // set render texture as a render target SetRenderTargetRenderTexture(); SetRenderTextureShaders(); // clear the render texture to black FLOAT bgColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; _d3d->GetDeviceContext()->ClearRenderTargetView(GetRenderTexture(), bgColor); // clear depth buffer of render texture _d3d->GetDeviceContext()->ClearDepthStencilView(GetRTZBuffer(), D3D11_CLEAR_DEPTH, 1.0f, 0); } void ShadowRenderer::ConfigureRenderingDebug() { _d3d->SetBuffers(); // Set default Vertex, Index and Constant buffer _d3d->SetViewport(); // select which primtive type we are using _d3d->GetDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // select Rasterizer and Sampler configuration _d3d->GetDeviceContext()->RSSetState(_d3d->GetRState()); _d3d->GetDeviceContext()->PSSetSamplers(0, 1, _d3d->GetSStateWrapAddr()); _d3d->GetDeviceContext()->PSSetSamplers(1, 1, _d3d->GetSStateClampAddr()); // set backbuffer as a rendertarget _d3d->SetRenderTargetBackBuffer(); SetRenderTextureShaders(); // clear the render texture to deep blue FLOAT bgColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f }; _d3d->GetDeviceContext()->ClearRenderTargetView(_d3d->GetBackBuffer(), bgColor); // clear depth buffer of back buffer _d3d->GetDeviceContext()->ClearDepthStencilView(_d3d->GetZBuffer(), D3D11_CLEAR_DEPTH, 1.0f, 0); } <file_sep>#pragma once #include <DirectXMath.h> #include <DirectXCollision.h> #include <vector> #include <map> #include <memory> #include <string> #include "D3D.h" #include "Camera.h" #include "Vehicle.h" class VehiclePicker { public: VehiclePicker() = delete; VehiclePicker(D3D* d3d, Camera* camera, DirectX::XMMATRIX& worldOffset) : _d3d(d3d), _camera(camera), _worldOffset(worldOffset) { } ~VehiclePicker(); // Generate bounding boxes from all vehicles void InitBoundingBoxes(std::map<std::string, Vehicle>* pVehicles); void UpdateBoundingBox(std::string vehicleName); void SetPickingRay(LONG mouseX, LONG mouseY); // Test picking ray intersection with _vehicleBBs and return the closest one in bb if found bool GetHitVehicle(std::string& v) const; std::wstring GetDebugString() const { return _dbgString; } private: // DirectX objects D3D* _d3d = nullptr; Camera* _camera = nullptr; // World offset DirectX::XMMATRIX _worldOffset; // Picking ray DirectX::XMVECTOR _pickingRayOrigin, _pickingRayDirection; // Pointer to all Vehicles std::map<std::string, Vehicle>* _pVehicles; // Vector of vehicle bounding boxes std::map<std::string, DirectX::BoundingBox> _vehicleBBs; // Methods std::vector<DirectX::XMFLOAT3> GetXMFLOAT3VectorFromModelVertices(const std::vector<VERTEX>& modelVertices) const; // Debug stuff std::wstring _dbgString; void SetDebugString(std::wstring s) { _dbgString = s; } }; <file_sep>#pragma once #include <d3d11.h> #include <directxmath.h> #include <vector> #include "TextureRenderer.h" #include "RushHour.h" #include "D3DSupplementary.h" #include "D3D.h" class DepthRenderer : public TextureRenderer { public: DepthRenderer() = delete; DepthRenderer(D3D* d3d) : TextureRenderer(d3d) { LoadRenderTextureShaders(); }; ~DepthRenderer() {}; void LoadRenderTextureShaders() override; void ConfigureRendering() override; }; <file_sep>#pragma once class Timer { public: Timer(); ~Timer(); void StartTimer(); // Reset Timer double GetTime(); // Return num of seconds since last StartTimer() call double GetFrameTime(); // Return num of seconds sincse last GetFrameTime() call private: __int64 _counterStart = 0; double _countsPerSecond = 0.0; __int64 _frameTimeOld = 0; double _frameTime; }; <file_sep>#include "stdafx.h" #include "VehiclePicker.h" #include "RushHour.h" #include <limits> using namespace DirectX; using namespace std; VehiclePicker::~VehiclePicker() { } // Create picking ray from camera position and mouse click void VehiclePicker::SetPickingRay(LONG mouseX, LONG mouseY) { float pointX, pointY; // Transform mouse cursor from viewport coordinates into normalised device coordinates (into the -1 to +1 range) pointX = ((2.0f * static_cast<float>(mouseX)) / static_cast<float>(SCREEN_WIDTH)) - 1.0f; pointY = (((2.0f * static_cast<float>(mouseY)) / static_cast<float>(SCREEN_HEIGHT)) - 1.0f) * -1.0f; // Transform into homogeneous clip space XMFLOAT4 ray_clip = { pointX, pointY, 1.0, 1.0 }; XMVECTOR ray_clip_v = XMLoadFloat4(&ray_clip); // Transform into eye (camera) space XMMATRIX invProjMtrx = XMMatrixInverse(nullptr, _d3d->GetProjectionMatrix()); XMVECTOR ray_eye_v = XMVector4Transform(ray_clip_v, invProjMtrx); // Unproject x,y components, so set the z,w part to mean "forwards, and not a point". XMFLOAT4 ray_eye; XMStoreFloat4(&ray_eye, ray_eye_v); ray_eye = { ray_eye.x, ray_eye.y, 1.0, 0.0 }; ray_eye_v = XMLoadFloat4(&ray_eye); // Transform into world space XMMATRIX invViewMtrx = XMMatrixInverse(nullptr, _camera->GetViewMatrix()); XMFLOAT4 ray_wrld; XMStoreFloat4(&ray_wrld, XMVector4Transform(ray_eye_v, invViewMtrx)); // Cast the "picking" ray from camera position in the direction defined by normalized direction vector XMVECTOR ray_wrld_v = XMLoadFloat3(&XMFLOAT3(ray_wrld.x, ray_wrld.y, ray_wrld.z)); _pickingRayDirection = XMVector3Normalize(ray_wrld_v); _pickingRayOrigin = _camera->GetPosition(); } //#define TRIANGLETEST // if defined, use triangles hit detection after bounding box hit //#define INDICESTEST // if defined, detect hit triangles generated with use of indices bool VehiclePicker::GetHitVehicle(string& v) const { float minDistance = (numeric_limits<float>::max)(); bool found = false; for (auto vehicleBB : _vehicleBBs) { float distance; if (vehicleBB.second.Intersects(_pickingRayOrigin, _pickingRayDirection, distance)) { #ifdef TRIANGLETEST // Bounding box hit, now check all triangles float distance2; Vehicle vehicle = _pVehicles->at(vehicleBB.first); vector<UINT> indices = vehicle.GetModel().GetModelIndices(); auto vertices = vehicle.GetModel().GetModelVVertices(); XMMATRIX tm = vehicle.GetTransformation() * _worldOffset; #ifdef INDICESTEST auto i = indices.begin(); while (i != indices.end()) { XMVECTOR v1, v2, v3; v1 = vehicle.GetModel().GetModelVVertices().at(*(i++)).posv; v2 = vehicle.GetModel().GetModelVVertices().at(*(i++)).posv; v3 = vehicle.GetModel().GetModelVVertices().at(*(i++)).posv; #else auto i = vertices.begin(); while (i != vertices.end()) { XMVECTOR v1, v2, v3; v1 = (*(i++)).posv; if (i == vertices.end()) break; v2 = (*(i++)).posv; if (i == vertices.end()) break; v3 = (*(i++)).posv; #endif v1 = XMVector3Transform(v1, tm); v2 = XMVector3Transform(v2, tm); v3 = XMVector3Transform(v3, tm); if (DirectX::TriangleTests::Intersects(_pickingRayOrigin, _pickingRayDirection, v1, v2, v3, distance2)) { if (distance2 < minDistance) { minDistance = distance2; v = vehicleBB.first; found = true; } } } #else if (distance < minDistance) { minDistance = distance; v = vehicleBB.first; found = true; } #endif } } return found; } // Convert modelVertices into array of XMFLOAT3 vector<XMFLOAT3> VehiclePicker::GetXMFLOAT3VectorFromModelVertices(const std::vector<VERTEX>& modelVertices) const { vector<XMFLOAT3> xmfloatVector; xmfloatVector.reserve(modelVertices.size()); for (auto modelVertex : modelVertices) { xmfloatVector.push_back(modelVertex.pos); } return xmfloatVector; } // Create bounding box for each displayed vehicle void VehiclePicker::InitBoundingBoxes(std::map<std::string, Vehicle>* pVehicles) { _pVehicles = pVehicles; _vehicleBBs.clear(); // Create bounding boxes for all displayed vehicles for (auto vehicle : *_pVehicles) { if (!(vehicle.second.IsHidden())) { // Get bounding box of the model without transformation DirectX::BoundingBox bb; // BUS bounding boxes are for some reason created too big - it helps to divide number of vertices with a magic number ;) int modelVerticesDivisor = 1; // for normal object do not divide if (vehicle.first.substr(0,3) == "bus") { modelVerticesDivisor = 4; // for bus, divide by magic number } BoundingBox::CreateFromPoints(bb, vehicle.second.GetModel().GetModelVertices().size()/modelVerticesDivisor, GetXMFLOAT3VectorFromModelVertices(vehicle.second.GetModel().GetModelVertices()).data(), sizeof(XMFLOAT3)); bb.Transform(bb, vehicle.second.GetTransformation() * _worldOffset); _vehicleBBs.insert(make_pair(vehicle.first, bb)); } } } void VehiclePicker::UpdateBoundingBox(std::string vehicleName) { int modelVerticesDivisor = 1; // for normal object do not divide if (vehicleName.substr(0,3) == "bus") { modelVerticesDivisor = 4; // for bus, divide by magic number } DirectX::BoundingBox bb; BoundingBox::CreateFromPoints(bb, _pVehicles->at(vehicleName).GetModel().GetModelVertices().size()/modelVerticesDivisor, GetXMFLOAT3VectorFromModelVertices(_pVehicles->at(vehicleName).GetModel().GetModelVertices()).data(), sizeof(XMFLOAT3)); bb.Transform(bb, _pVehicles->at(vehicleName).GetTransformation() * _worldOffset); _vehicleBBs[vehicleName] = bb; } <file_sep>#include "stdafx.h" #include <d3d11.h> #include <directxmath.h> #include <numeric> #include "OrthoWindow.h" #include "CommonException.h" using namespace DirectX; // It creates a simple 2D rectangle object for 2D orthogonal rendering OrthoWindow::OrthoWindow(D3D* d3d, FLOAT windowWidth, FLOAT windowHeight) : _d3d(d3d), _windowWidth(windowWidth), _windowHeight(windowHeight) { CreateOrthoWindowModel(); CreateVertexBuffer(); CreateIndexBuffer(); CreateConstantBuffer(); // Get Orthomatrix for projection _orthoMatrix = XMMatrixOrthographicLH((float)_windowWidth, (float)_windowHeight, 0.1f, 1000.0f); } OrthoWindow::~OrthoWindow() { if (_vBuffer) _vBuffer->Release(); if (_iBuffer) _iBuffer->Release(); if (_cBuffer) _cBuffer->Release(); } DirectX::XMMATRIX OrthoWindow::GetViewMatrix() const { return XMMatrixLookAtLH( CAMINITPOSITION, XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f), // the look-at position XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f) // the up direction ); } void OrthoWindow::CreateOrthoWindowModel() { FLOAT left, right, top, bottom; // prepare coordinates left = (_windowWidth / 2) * -1; right = left + _windowWidth; top = _windowHeight / 2; bottom = top - _windowHeight; // Load the vertex vector with data. _objectVertices.reserve(6); VERTEX v; v.normal = { 0.0f, 0.0f, 0.0f }; // First triangle. v.pos = { left, top, 0.0f }; v.textCoord = { 0.0f, 0.0f }; _objectVertices.push_back(v); v.pos = { right, bottom, 0.0f }; v.textCoord = { 1.0f, 1.0f }; _objectVertices.push_back(v); v.pos = { left, bottom, 0.0f }; v.textCoord = { 0.0f, 1.0f }; _objectVertices.push_back(v); // Second triangle. // v.pos = { left, top, 0.0f }; // v.textCoord = { 0.0f, 0.0f }; // _objectVertices.push_back(v); v.pos = { right, top, 0.0f }; v.textCoord = { 1.0f, 0.0f }; _objectVertices.push_back(v); // v.pos = { right, bottom, 0.0f }; // v.textCoord = { 1.0f, 1.0f }; // _objectVertices.push_back(v); // Load the index vector with data _objectIndices.insert(_objectIndices.end(), { 2, 1, 0, 1, 3, 0 }); } void OrthoWindow::CreateConstantBuffer() { // constant buffer D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(OrthoWindow::CBUFFER); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; if (FAILED(_d3d->GetDevice()->CreateBuffer(&bd, NULL, &_cBuffer))) { throw CommonException((LPWSTR)L"Critical error: Unable to create OrthoWindow constant buffer!"); } } void OrthoWindow::CreateVertexBuffer() { D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(VERTEX) * _objectVertices.size(); bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA vertexData; vertexData.pSysMem = _objectVertices.data(); vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; if (FAILED(_d3d->GetDevice()->CreateBuffer(&bd, &vertexData, &_vBuffer))) { throw CommonException((LPWSTR)L"Critical error: Unable to create OrthoWindow vertex buffer!"); } } void OrthoWindow::CreateIndexBuffer() { D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(UINT) * _objectIndices.size(); bd.BindFlags = D3D11_BIND_INDEX_BUFFER; D3D11_SUBRESOURCE_DATA indexData; indexData.pSysMem = _objectIndices.data(); indexData.SysMemPitch = 0; indexData.SysMemSlicePitch = 0; if (FAILED(_d3d->GetDevice()->CreateBuffer(&bd, &indexData, &_iBuffer))) { throw CommonException((LPWSTR)L"Critical error: Unable to create OrthoWindow index buffer!"); } } void OrthoWindow::SetBuffers() { // select which vertex buffer to display UINT stride = sizeof(VERTEX); UINT offset = 0; _d3d->GetDeviceContext()->IASetVertexBuffers(0, 1, GetVBufferAddr(), &stride, &offset); _d3d->GetDeviceContext()->IASetIndexBuffer(GetIBuffer(), DXGI_FORMAT_R32_UINT, 0); _d3d->GetDeviceContext()->VSSetConstantBuffers(0, 1, &_cBuffer); _d3d->SetZBufferOff(); } void OrthoWindow::SetViewport() { // set the viewport D3D11_VIEWPORT viewport; ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT)); viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = _windowWidth; viewport.Height = _windowHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; _d3d->GetDeviceContext()->RSSetViewports(1, &viewport); } <file_sep>#pragma once #include <DirectXMath.h> #include "RushHour.h" class Camera { public: Camera(); ~Camera(); void SetNewPosition(DirectX::XMMATRIX rotation); DirectX::XMVECTOR GetPosition() const { return _camPosition; } DirectX::XMMATRIX GetViewMatrix() const; private: DirectX::XMVECTOR _camPosition; }; <file_sep>#pragma once #include "TextureRenderer.h" #include "OrthoWindow.h" class OrthoWindowRenderer : public TextureRenderer { public: OrthoWindowRenderer() = delete; OrthoWindowRenderer(D3D* d3d, OrthoWindow* orthoWindow); ~OrthoWindowRenderer() {}; void LoadRenderTextureShaders() override; void ConfigureRendering() override; void ConfigureRenderingDebug(); private: OrthoWindow* _orthoWindow; }; <file_sep>#pragma once #include <d3d11.h> #include <directxmath.h> #include <vector> #include "RushHour.h" #include "D3DSupplementary.h" #include "D3D.h" class TextureRenderer { public: TextureRenderer() = delete; TextureRenderer(D3D* d3d, FLOAT textureWidth, FLOAT textureHeight); TextureRenderer(D3D* d3d) : TextureRenderer(d3d, SCREEN_WIDTH, SCREEN_HEIGHT) {} ~TextureRenderer(); ID3D11RenderTargetView* GetRenderTexture() const { return _rTexture; } ID3D11ShaderResourceView** GetRenderTextureSRVAddr() { return &(_rTextureSRV); } ID3D11DepthStencilView* GetRTZBuffer() const { return _rtzBuffer; } void SetRenderTargetRenderTexture() { _d3d->SetRenderTarget(&(_rTexture), _rtzBuffer); } void SetRenderTextureShaders(); virtual void LoadRenderTextureShaders() = 0; virtual void ConfigureRendering() = 0; protected: D3D * _d3d; ID3D11RenderTargetView* _rTexture; // render texture ID3D11ShaderResourceView* _rTextureSRV; // render texture shader resource view ID3D11DepthStencilView* _rtzBuffer; // render texture depth buffer ID3D11VertexShader* _rtvs; // render texture vertex shader ID3D11PixelShader* _rtps; // render texture pixel shader ID3D11InputLayout* _rtlayout; // render texture layout FLOAT _textureWidth, _textureHeight; void CreateRenderTextureDepthBuffer(); void CreateRenderTexture(); }; <file_sep>#include "stdafx.h" #include "D2D.h" #include "CommonException.h" D2D::D2D(D3D* d3d) : _d3d(d3d) { CreateDevice(); CreateBitmapRenderTarget(); InitializeTextFormats(); } D2D::~D2D() { if (_dev) _dev->Release(); if (_devCon) _devCon->Release(); if (_factory) _factory->Release(); if (_yellowBrush) _yellowBrush->Release(); if (_whiteBrush) _whiteBrush->Release(); if (_blackBrush) _blackBrush->Release(); if (_textFormatFPS) _textFormatFPS->Release(); } void D2D::CreateDevice() { if (FAILED(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown**>(&_writeFactory)))) { throw CommonException((LPWSTR)L"Critical error: Unable to create the DirectWrite factory!"); } D2D1_FACTORY_OPTIONS options; ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS)); //options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION; if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, __uuidof(ID2D1Factory2), &options, reinterpret_cast<LPVOID*>(&_factory)))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct2D Factory!"); } if (FAILED(_factory->CreateDevice(_d3d->GetDXGIDevice(), &_dev))) { throw CommonException((LPWSTR)L"Critical error: Unable to create the Direct2D device!"); } if (FAILED(_dev->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_ENABLE_MULTITHREADED_OPTIMIZATIONS, &_devCon))) { throw CommonException((LPWSTR)L"Critical error: Unable to create the Direct2D device context!"); } } void D2D::CreateBitmapRenderTarget() { // specify the desired bitmap properties D2D1_BITMAP_PROPERTIES1 bp; ZeroMemory(&bp, sizeof(D2D1_BITMAP_PROPERTIES1)); bp.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM; bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE; bp.dpiX = 96.0f; bp.dpiY = 96.0f; bp.bitmapOptions = D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW; bp.colorContext = nullptr; // Direct2D needs the DXGI version of the back buffer IDXGISurface* dxgiBuffer; if (FAILED(_d3d->GetSwapChain()->GetBuffer(0, __uuidof(IDXGISurface), reinterpret_cast<LPVOID*>(&dxgiBuffer)))) { throw CommonException((LPWSTR)L"Critical error: Unable to retrieve the Direct2D back buffer!"); } // create the bitmap ID2D1Bitmap1* targetBitmap; if (FAILED(_devCon->CreateBitmapFromDxgiSurface(dxgiBuffer, &bp, &targetBitmap))) { throw CommonException((LPWSTR)L"Critical error: Unable to create the Direct2D bitmap from the DXGI surface!"); } // set the newly created bitmap as render target _devCon->SetTarget(targetBitmap); } void D2D::InitializeTextFormats() { // create standard brushes if (FAILED(_devCon->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow), &_yellowBrush))) throw CommonException((LPWSTR)L"Critical error: Unable to create the yellow brush!"); if (FAILED(_devCon->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &_blackBrush))) throw CommonException((LPWSTR)L"Critical error: Unable to create the black brush!"); if (FAILED(_devCon->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &_whiteBrush))) throw CommonException((LPWSTR)L"Critical error: Unable to create the white brush!"); // set up text formats // info text if (FAILED(_writeFactory->CreateTextFormat(L"Lucida Console", nullptr, DWRITE_FONT_WEIGHT_LIGHT, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 12.0f, L"en-GB", &_textFormatFPS))) throw CommonException((LPWSTR)L"Critical error: Unable to create text format for FPS information!"); if (FAILED(_textFormatFPS->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING))) throw CommonException((LPWSTR)L"Critical error: Unable to set text alignment!"); if (FAILED(_textFormatFPS->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR))) throw CommonException((LPWSTR)L"Critical error: Unable to set paragraph alignment!"); } void D2D::PrintInfo() { _devCon->BeginDraw(); _devCon->DrawTextLayout(D2D1::Point2F(INFOPOSITIONX, INFOPOSITIONY), _textLayoutFPS, _yellowBrush); if (FAILED(_devCon->EndDraw())) { throw CommonException((LPWSTR)L"Critical error: Unable to draw FPS information!"); } } <file_sep>#pragma once #include <d3d11.h> #include <DXGI.h> #include <D2D1.h> #include <D2D1_2.h> #include <dwrite_2.h> #include "D3D.h" class D2D { public: D2D() = delete; D2D(D3D* d3d); ~D2D(); void PrintInfo(); // prints info to the screen IDWriteTextFormat* GetTextFormatFPS() { return _textFormatFPS; } IDWriteTextLayout* GetTextLayoutFPS() { return _textLayoutFPS; } IDWriteTextLayout** GetTextLayoutFPSAddr() { return &(_textLayoutFPS); } IDWriteFactory2 * GetWriteFactory() { return _writeFactory; } private: // device, factory IDWriteFactory2 * _writeFactory; // pointer to the DirectWrite factory ID2D1Factory2* _factory; // pointer to the Direct2D factory ID2D1Device1* _dev; // pointer to the Direct2D device ID2D1DeviceContext1* _devCon; // pointer to the device context D3D* _d3d; // brushes ID2D1SolidColorBrush* _yellowBrush; ID2D1SolidColorBrush* _whiteBrush; ID2D1SolidColorBrush* _blackBrush; // text formats IDWriteTextFormat* _textFormatFPS; // text layouts IDWriteTextLayout* _textLayoutFPS; void CreateDevice(); // creates the device and its context void CreateBitmapRenderTarget(); // creates the bitmap render target, set to be the same as the backbuffer already in use for Direct3D void InitializeTextFormats(); // initializes the different formats, for now, only a format to print FPS information will be created }; <file_sep>#include "stdafx.h" #include "ModelInstance.h" using namespace std; using namespace DirectX; ModelInstance::ModelInstance(Model & m, DirectX::XMMATRIX scale, DirectX::XMVECTOR alignment, DirectX::XMMATRIX rotation) : ModelInstance(m) { _scale = scale; _alignment = alignment; _rotation = rotation; } void ModelInstance::SetPosition(Coords2i_t coords) { _position = coords; } void ModelInstance::SetColor(DirectX::XMUINT3 c) { _color = MakeColorVector(c); } void ModelInstance::SetColor(DirectX::XMVECTOR c) { _color = c; } XMVECTOR ModelInstance::MakeColorVector(XMUINT3 rgb) { const float k = 1.0f / 255.0f; XMVECTOR ret = { rgb.x*k, rgb.y*k, rgb.z*k }; return ret; } // Return rotation matrix reflecting initial orientation of instance based on IsRotated180() and GetOrientation() state. // It does not reflect world rotation. DirectX::XMMATRIX ModelInstance::GetInitRotation() const { XMMATRIX rMatrix = _rotation; if (GetOrientation() == ModelInstance::XAxis) { rMatrix *= XMMatrixRotationY(XMConvertToRadians(90)); } return rMatrix; } DirectX::XMMATRIX ModelInstance::GetTransformation() const { XMMATRIX r = _rotation; XMMATRIX p = XMMatrixTranslation(static_cast<float>(GetPosition().x), 0.0f, static_cast<float>(GetPosition().z)); if (GetOrientation() == ModelInstance::XAxis) { // rotate the instance 90degrees r *= XMMatrixRotationY(XMConvertToRadians(90.0f)); // rotate the alignment and movementStep 90degrees p *= XMMatrixTranslation(GetAlignment().m128_f32[0], GetAlignment().m128_f32[1], GetAlignment().m128_f32[2]); } else { // no rotation p *= XMMatrixTranslation(GetAlignment().m128_f32[2], GetAlignment().m128_f32[1], GetAlignment().m128_f32[0]); } return r * GetScale() * p; } <file_sep>#include "stdafx.h" #include "Model.h" #include <WICTextureLoader.h> #include <DDSTextureLoader.h> #include <memory> using namespace std; using namespace DirectX; std::vector<VERTEX> Model::_objectVertices; std::vector<VVERTEX> Model::_objectVVertices; std::vector<UINT> Model::_objectIndices; Model::Model(const char* pFile, ID3D11Device* dev) { const aiVector3D Zero3D(0.0f, 0.0f, 0.0f); _pScene = _imp.ReadFile(pFile, aiProcess_FlipUVs | aiProcess_FixInfacingNormals | aiProcess_MakeLeftHanded | aiProcess_GenSmoothNormals | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); if (!_pScene) { }else { if (_pScene->mNumMeshes < 1) { } else { // Process all meshes for (unsigned int m = 0; m < _pScene->mNumMeshes; m++) { _pMesh = _pScene->mMeshes[m]; MeshEntry me; me._baseVertex = Model::_objectVertices.size(); me._baseIndex = _objectIndices.size(); if (_pMesh) { // Load vertices Model::_objectVertices.reserve(Model::_objectVertices.size() + _pMesh->mNumVertices); for (unsigned int i = 0; i < _pMesh->mNumVertices; i++) { const aiVector3D* pPos = &(_pMesh->mVertices[i]); const aiVector3D* pNormal = (_pMesh->mNormals != nullptr) ? &(_pMesh->mNormals[i]) : &Zero3D; const aiVector3D* pTexCoord = (_pMesh->HasTextureCoords(0)) ? &(_pMesh->mTextureCoords[0][i]) : &Zero3D; VERTEX v; VVERTEX vv; v.pos.x = pPos->x; v.pos.y = pPos->y; v.pos.z = pPos->z; vv.posv = XMLoadFloat3(&v.pos); v.normal.x = pNormal->x; v.normal.y = pNormal->y; v.normal.z = pNormal->z; v.textCoord.x = pTexCoord->x; v.textCoord.y = pTexCoord->y; Model::_objectVertices.push_back(v); Model::_objectVVertices.push_back(vv); } // Load indices _objectIndices.reserve(_objectIndices.size() + (_pMesh->mNumFaces * 3)); for (unsigned int i = 0; i < _pMesh->mNumFaces; i++) { if (_pMesh->mFaces[i].mNumIndices == 3) { _objectIndices.push_back(_pMesh->mFaces[i].mIndices[0]); _objectIndices.push_back(_pMesh->mFaces[i].mIndices[1]); _objectIndices.push_back(_pMesh->mFaces[i].mIndices[2]); me._numIndices += 3; } } // Process material of the mesh if (_pScene->HasMaterials()) { aiMaterial* material = _pScene->mMaterials[_pMesh->mMaterialIndex]; aiString aiTextureFile; me._materialIndex = _pMesh->mMaterialIndex; // Load texture file if (material->GetTextureCount(aiTextureType_DIFFUSE) > 0) { material->GetTexture(aiTextureType_DIFFUSE, 0, &aiTextureFile); // Convert aiString to LPWSTR size_t size = strlen(aiTextureFile.C_Str()) + 1; // plus null auto wcTextureFile = std::make_unique<wchar_t[]>(size); size_t outSize; mbstowcs_s(&outSize, wcTextureFile.get(), size, aiTextureFile.C_Str(), size - 1); LPWSTR textureFile = wcTextureFile.get(); CreateWICTextureFromFile(dev, nullptr, textureFile, nullptr, &(me._pTexture), 0); if (me._pTexture == nullptr) { CreateDDSTextureFromFile(dev, nullptr, textureFile, nullptr, &(me._pTexture), 0); } } /* // Load property aiMaterialProperty* property; char* strp; float f; int i; for (unsigned int p = 0; p < material->mNumProperties; p++) { property = material->mProperties[p]; if (property->mType == aiPTI_String) { strp = (char*)(property->mData); strp += 4; } else if (property->mType == aiPTI_Float) { f = *(float*)(property->mData); } else if (property->mType == aiPTI_Integer) { i = *(int*)(property->mData); } } */ } // If no texture found, use the default one if (me._pTexture == nullptr) { CreateWICTextureFromFile(dev, nullptr, L"models/default.jpg", nullptr, &(me._pTexture), 0); } _entries.push_back(me); } } } } } Model::~Model() { for (auto i : _entries) { if (i._pTexture) { i._pTexture->Release(); } } } <file_sep>#pragma once #include <DirectXMath.h> #include "Model.h" class ModelInstance { public: enum Orientation_t { XAxis, ZAxis }; // Constructors ModelInstance() = delete; ModelInstance(Model& m) : _model(m) {} ModelInstance(Model& m, DirectX::XMMATRIX scale, DirectX::XMVECTOR alignment, DirectX::XMMATRIX rotation); ~ModelInstance() {} // Transformation methods void SetOrientation(ModelInstance::Orientation_t dir) { _orientation = dir; } void SetPosition(Coords2i_t coords); void SetPosition(int x, int z) { SetPosition({ x, z }); } void SetAlignment(DirectX::XMVECTOR alignment) { _alignment = alignment; } DirectX::XMMATRIX GetTransformation() const; DirectX::XMMATRIX GetInitRotation() const; ModelInstance::Orientation_t GetOrientation() const { return _orientation; } Coords2i_t GetPosition() const { return _position; } DirectX::XMVECTOR GetAlignment() const { return _alignment; } DirectX::XMMATRIX GetScale() const { return _scale; } // Graphics settings methods DirectX::XMVECTOR GetColor() const { return _color; } void SetColor(DirectX::XMUINT3 c); void SetColor(DirectX::XMVECTOR c); // Other methods Model& GetModel() const { return _model; } private: // Reference to polygon model Model& _model; // Transformation matrices and vars DirectX::XMMATRIX _scale = DirectX::XMMatrixIdentity(); // scale instance size Coords2i_t _position = { 0, 0 }; // positon instance DirectX::XMVECTOR _alignment = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); // align the instance to the grid field DirectX::XMMATRIX _rotation = DirectX::XMMatrixIdentity(); // rotate the instance into the initial position Orientation_t _orientation = Orientation_t::XAxis; // Graphics settings vars DirectX::XMVECTOR _color = DirectX::XMVectorSet(1.0f * CARLIGHTINTENSITY, 1.0f * CARLIGHTINTENSITY, 1.0f * CARLIGHTINTENSITY, 1.0f * CARLIGHTINTENSITY); // Auxiliary methods DirectX::XMVECTOR MakeColorVector(DirectX::XMUINT3 rgb); }; <file_sep>#pragma once // This class is used to perform orthographic rendering to 2D #include "D3D.h" #include "D3DSupplementary.h" class OrthoWindow { public: OrthoWindow() = delete; OrthoWindow(D3D* d3d, FLOAT windowWidth, FLOAT windowHeight); ~OrthoWindow(); void SetBuffers(); void SetViewport(); ID3D11Buffer* GetVBuffer() const { return _vBuffer; } ID3D11Buffer** GetVBufferAddr() { return &(_vBuffer); } ID3D11Buffer* GetIBuffer() const { return _iBuffer; } ID3D11Buffer* GetCBuffer() const { return _cBuffer; } FLOAT GetWindowWidth() const { return _windowWidth; } FLOAT GetWindowHeight() const { return _windowHeight; } DirectX::XMMATRIX GetOrthoMatrix() const { return _orthoMatrix; } DirectX::XMMATRIX GetViewMatrix() const; size_t GetNumOfIndices() const { return _objectIndices.size(); } struct CBUFFER { DirectX::XMMATRIX mvp; float screenWidth; float screenHeight; }; private: D3D* _d3d; FLOAT _windowWidth, _windowHeight; DirectX::XMMATRIX _orthoMatrix; std::vector<VERTEX> _objectVertices; std::vector<UINT> _objectIndices; ID3D11Buffer* _vBuffer; // vertex buffer ID3D11Buffer* _iBuffer; // index buffer ID3D11Buffer* _cBuffer; // constant buffer void CreateOrthoWindowModel(); void CreateVertexBuffer(); void CreateIndexBuffer(); void CreateConstantBuffer(); }; <file_sep>#include "stdafx.h" #include "Vehicle.h" using namespace std; using namespace DirectX; Vehicle::Vehicle(Model & m, DirectX::XMMATRIX scale, DirectX::XMVECTOR alignment, bool rotate180, unsigned short length) : ModelInstance(m, scale, alignment, XMMatrixIdentity()) { _length = length; _rotate180 = rotate180; } void Vehicle::SetMovementStep(float s) { _movementStep = s; } DirectX::XMMATRIX Vehicle::GetTransformation() const { XMMATRIX r; XMMATRIX p = XMMatrixTranslation(static_cast<float>(GetPosition().x), 0.0f, static_cast<float>(GetPosition().z)); if (GetOrientation() == Vehicle::XAxis) { // rotate the instance 90degrees r = XMMatrixRotationY(XMConvertToRadians(90.0f)); // rotate the alignment and movementStep 90degrees p *= XMMatrixTranslation(GetAlignment().m128_f32[0], GetAlignment().m128_f32[1], GetAlignment().m128_f32[2]); p *= XMMatrixTranslation(_movementStep, 0.0f, 0.0f); } else { // no rotation r = XMMatrixIdentity(); p *= XMMatrixTranslation(GetAlignment().m128_f32[2], GetAlignment().m128_f32[1], GetAlignment().m128_f32[0]); p *= XMMatrixTranslation(0.0f, 0.0f, _movementStep); } if (_rotate180) { r *= XMMatrixRotationY(XMConvertToRadians(180.0f)); } return r * GetScale() * p; } // Return rotation matrix reflecting initial orientation of instance based on IsRotated180() and GetOrientation() state. // It does not reflect world rotation. DirectX::XMMATRIX Vehicle::GetInitRotation() const { XMMATRIX rMatrix = ModelInstance::GetInitRotation(); if (IsRotated180()) { rMatrix *= XMMatrixRotationY(XMConvertToRadians(180)); } return rMatrix; } // Returns true if this instance is occupying position pos bool Vehicle::IsOccupyingPosition(Coords2i_t pos) const { if (IsHidden()) { return false; } Coords2i_t p = GetPosition(); for (unsigned short i = 0; i < _length; i++) { if ((p.x == pos.x) && (p.z == pos.z)) { return true; } if (GetOrientation() == Vehicle::XAxis) { p.x += 1; } else { p.z += 1; } } return false; } <file_sep>#ifndef __d3dsupplementary__ #define __d3dsupplementary__ #include <d3d11.h> #include <directxmath.h> struct VERTEX { DirectX::XMFLOAT3 pos; DirectX::XMFLOAT3 normal; DirectX::XMFLOAT2 textCoord; }; struct VVERTEX { DirectX::XMVECTOR posv; }; struct CBUFFER { DirectX::XMMATRIX world; DirectX::XMMATRIX mvp; DirectX::XMMATRIX lightmvp; DirectX::XMMATRIX invTrWorld; DirectX::XMVECTOR cameraPosition; DirectX::XMVECTOR lightPosition; DirectX::XMVECTOR diffuseColor; DirectX::XMVECTOR ambientColor; float specularPower; DirectX::XMVECTOR specularColor; }; #endif<file_sep>#pragma once #include <vector> #include <map> #include <string> #include <DirectXMath.h> #include "D3DSupplementary.h" #include "Model.h" #include "Vehicle.h" #include "D2D.h" #include "D3D.h" #include "Camera.h" #include "DepthRenderer.h" #include "ShadowRenderer.h" #include "OrthoWindow.h" #include "OrthoWindowRenderer.h" #include "VehiclePicker.h" #include "Marker.h" #define VEH(X) _vehicles.at(std::string(#X)) #define MI(X) _minstances.at(std::string(#X)) #define BUSLEN 3 #define CARLEN 2 #define BOARD_MAX_COORD 2 #define BOARD_MIN_COORD -3 class Game { public: Game() = delete; Game(HWND hWnd); ~Game(); enum Direction_t { Forward, Backward }; void Init(); void Update(double frameTime); void Render(); void Rotate(float direction); // Methods for operating active vehicle bool SetActiveVehicle(std::string idstr); bool UnsetActiveVehicle(); void SetNextActiveVehicle(); std::string GetActiveVehicle() const { return _activeVehicle; } bool MoveActiveVehicle(Game::Direction_t dir); // Methods for vehicles tests bool IsVehicleFreeForMove(std::string idstr) const; bool IsVehicleFreeForMoveForwardOrBackward(std::string idstr, Game::Direction_t dir) const; // Info text methods void PrintInfoString() const; void AddInfoString(std::wstring wstr); void SetDebugInfoString(std::wstring wstr); void ClearInfoString(); // Vehicle picker VehiclePicker* GetVehiclePicker() const { return _vehiclePicker; } private: // Timer vars double _frameTime = 0.0; // Info wstring std::wstring _infoString; std::wstring _debugInfoString; // DirectX objects D2D* _d2d = nullptr; D3D* _d3d = nullptr; Camera* _camera = nullptr; DepthRenderer* _depthRenderer = nullptr; ShadowRenderer* _shadowRenderer = nullptr; OrthoWindowRenderer* _dsOrthoWindowRenderer = nullptr; OrthoWindowRenderer* _fsOrthoWindowRenderer = nullptr; OrthoWindow* _downsampledWindow = nullptr; OrthoWindow* _fullsizedWindow = nullptr; // Models and objects containers std::map<std::string, Model> _models; std::map<std::string, ModelInstance> _minstances; std::map<std::string, Vehicle> _vehicles; std::map<std::string, Marker> _markers; // Active vehicle vars std::string _activeVehicle; bool _activeVehicleLock = false; // Vehicle picker VehiclePicker* _vehiclePicker = nullptr; // World position vars float _rotationAngle = 0; DirectX::XMMATRIX _rotation = DirectX::XMMatrixIdentity(); // as we index model position on grid in interval <-3, 2>, we need to move the board to be kept in the middle of the screen //DirectX::XMMATRIX _worldOffset = DirectX::XMMatrixTranslation(0.5f, 0.0f, 0.5f); DirectX::XMMATRIX _worldOffset = DirectX::XMMatrixTranslation(0.0f, 0.0f, 0.0f); // Color settings vars const float _ambientColorIntensity = AMBIENTCOLORINTENSITY; bool _glowLevelUp = true; // Rendering methods void RenderScene(CBUFFER* pcBuffer, DirectX::XMMATRIX matView, DirectX::XMMATRIX matPerspective, DirectX::XMMATRIX lightView, DirectX::XMMATRIX lightPerspective); void RenderOrthoWindow(OrthoWindow* orthoWindow, DirectX::XMMATRIX matView, DirectX::XMMATRIX matPerspective); // Active vehicle methods void UpdateMovementStep(); // If some movement activated, update movement step void UpdateGlowLevel(); // Makes the glow of active vehicle pulse bool IsActiveVehicleLocked() { return _activeVehicleLock; } bool LockActiveVehicle(); void UnlockActiveVehicle(); }; <file_sep>#include "stdafx.h" #include <d3dcompiler.h> #include <DirectXMath.h> #include "CommonException.h" #include "D3D.h" using namespace DirectX; // this method initializes and prepares Direct3D for use D3D::D3D(HWND hWnd) { CreateDevice(hWnd); // Create backbuffer and its zbuffer CreateDepthBuffer(); SetZBufferOn(); CreateRenderTarget(); SetViewport(); LoadBackBufferShaders(); CreateConstantBuffer(); InitRasterizer(); InitSampler(); _matPerspective = XMMatrixPerspectiveFovLH((FLOAT)XMConvertToRadians(45), (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, 1.0f, 100.0f); } D3D::~D3D() { // switch to windowed mode if (_swapChain) _swapChain->SetFullscreenState(FALSE, NULL); // release all the stuff if (_zBuffer) _zBuffer->Release(); if (_depthDisabledStencilState) _depthDisabledStencilState->Release(); if (_depthStencilState) _depthStencilState->Release(); if (_layout) _layout->Release(); if (_vs) _vs->Release(); if (_ps) _ps->Release(); if (_vBuffer) _vBuffer->Release(); if (_iBuffer) _iBuffer->Release(); if (_cBuffer) _cBuffer->Release(); if (_swapChain) _swapChain->Release(); if (_bBuffer) _bBuffer->Release(); if (_rs) _rs->Release(); if (_ssw) _ssw->Release(); if (_ssc) _ssc->Release(); if (_dev) _dev->Release(); if (_devCon) _devCon->Release(); } void D3D::CreateDevice(HWND hWnd) { DXGI_SWAP_CHAIN_DESC scd; ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC)); // fill the swap chain description struct scd.BufferDesc.Width = SCREEN_WIDTH; // set the back buffer width scd.BufferDesc.Height = SCREEN_HEIGHT; // set the back buffer height scd.BufferCount = 1; // one back buffer scd.BufferDesc.RefreshRate.Numerator = 0; // refresh rate: 0 -> do not care scd.BufferDesc.RefreshRate.Denominator = 1; scd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // use 32-bit color scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // how swap chain is to be used scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; // unspecified scan line ordering scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // unspecified scaling scd.OutputWindow = hWnd; // the window to be used scd.SampleDesc.Count = 4; // how many multisamples scd.SampleDesc.Quality = 0; scd.Windowed = RUNINWINDOW; // windowed/full-screen mode scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // allow full-screen switching by Alt-Enter D3D_FEATURE_LEVEL featureLevel; // create a device, device context and swap chain using the information in the scd struct if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT /* This flag is necessary for compatibility with Direct2D */, NULL, NULL, D3D11_SDK_VERSION, &scd, &_swapChain, &_dev, &featureLevel, &_devCon))) { throw CommonException((LPWSTR)L"Critical error: Unable to create the Direct3D device!"); } else if (featureLevel < D3D_FEATURE_LEVEL_11_0) { throw CommonException((LPWSTR)L"Critical error: You need DirectX 11.0 or higher to run this game!"); } if (FAILED(_dev->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<LPVOID*>(&_dxgiDevice)))) { throw CommonException((LPWSTR)L"Critical error: Unable to get Direct3D DXGI device!"); } } void D3D::CreateDepthBuffer() { // create the depth buffer texture D3D11_TEXTURE2D_DESC texd; ZeroMemory(&texd, sizeof(texd)); texd.Width = SCREEN_WIDTH; texd.Height = SCREEN_HEIGHT; texd.ArraySize = 1; texd.MipLevels = 1; texd.SampleDesc.Count = 4; texd.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; texd.Usage = D3D11_USAGE_DEFAULT; texd.BindFlags = D3D11_BIND_DEPTH_STENCIL; ID3D11Texture2D *pDepthBuffer; if (FAILED(_dev->CreateTexture2D(&texd, NULL, &pDepthBuffer))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D depth buffer texture!"); } // create the depth buffer D3D11_DEPTH_STENCIL_VIEW_DESC dsvd; ZeroMemory(&dsvd, sizeof(dsvd)); //dsvd.Format = DXGI_FORMAT_D32_FLOAT; dsvd.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS; if (FAILED(_dev->CreateDepthStencilView(pDepthBuffer, &dsvd, &(_zBuffer)))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D depth buffer!"); } pDepthBuffer->Release(); // create depth buffer states // Initialize the description of the stencil state. D3D11_DEPTH_STENCIL_DESC depthStencilDesc; ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); // Set up the description of the stencil state. depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Create the depth stencil state. if (FAILED(_dev->CreateDepthStencilState(&depthStencilDesc, &_depthStencilState))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D depth buffer state!"); } D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc; ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc)); // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. The only difference is // that DepthEnable is set to false, all other parameters are the same as the other depth stencil state. depthDisabledStencilDesc.DepthEnable = false; depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthDisabledStencilDesc.StencilEnable = false; depthDisabledStencilDesc.StencilReadMask = 0xFF; depthDisabledStencilDesc.StencilWriteMask = 0xFF; depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Create the state using the device. if (FAILED(_dev->CreateDepthStencilState(&depthDisabledStencilDesc, &_depthDisabledStencilState))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D depth buffer state!"); } } void D3D::CreateRenderTarget() { // create backbuffer and render target ID3D11Texture2D *pBackBuffer; if (FAILED(_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(&pBackBuffer)))) { throw CommonException((LPWSTR)L"Critical error: Unable to get Direct3D back buffer!"); } if (FAILED(_dev->CreateRenderTargetView(pBackBuffer, NULL, &_bBuffer))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D target view!"); } pBackBuffer->Release(); } void D3D::SetRenderTarget(ID3D11RenderTargetView** rtv, ID3D11DepthStencilView* dsv) { _devCon->OMSetRenderTargets(1, rtv, dsv); } void D3D::SetBuffers() { // select which vertex buffer to display UINT stride = sizeof(VERTEX); UINT offset = 0; _devCon->IASetVertexBuffers(0, 1, GetVBufferAddr(), &stride, &offset); _devCon->IASetIndexBuffer(GetIBuffer(), DXGI_FORMAT_R32_UINT, 0); _devCon->VSSetConstantBuffers(0, 1, &_cBuffer); _devCon->PSSetConstantBuffers(0, 1, &_cBuffer); SetZBufferOn(); } void D3D::ConfigureRenderering() { SetBuffers(); // Set default Vertex, Index and Constant buffer // select which primtive type we are using GetDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // select Rasterizer and Sampler configuration GetDeviceContext()->RSSetState(GetRState()); GetDeviceContext()->PSSetSamplers(0, 1, GetSStateWrapAddr()); GetDeviceContext()->PSSetSamplers(1, 1, GetSStateClampAddr()); // set backbuffer as a rendertarget SetRenderTargetBackBuffer(); SetBackBufferShaders(); // clear the render texture to deep blue FLOAT bgColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f }; GetDeviceContext()->ClearRenderTargetView(GetBackBuffer(), bgColor); // clear depth buffer of back buffer GetDeviceContext()->ClearDepthStencilView(GetZBuffer(), D3D11_CLEAR_DEPTH, 1.0f, 0); } void D3D::SetViewport() { // set the viewport D3D11_VIEWPORT viewport; ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT)); viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = SCREEN_WIDTH; viewport.Height = SCREEN_HEIGHT; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; _devCon->RSSetViewports(1, &viewport); } void D3D::LoadBackBufferShaders() { // load and compile vertex and pixel shader ID3D10Blob *VS, *PS; D3DCompileFromFile(L"shaders.shader", NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "VShader", "vs_4_0", 0, 0, &VS, NULL); D3DCompileFromFile(L"shaders.shader", NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "PShader", "ps_4_0", 0, 0, &PS, NULL); if (FAILED(_dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &_vs))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D vertex shader!"); } if (FAILED(_dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &_ps))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D pixel shader!"); } // create the input layout object D3D11_INPUT_ELEMENT_DESC ied[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (FAILED(_dev->CreateInputLayout(ied, 3, VS->GetBufferPointer(), VS->GetBufferSize(), &_layout))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D input layout!"); } } void D3D::SetBackBufferShaders() { _devCon->IASetInputLayout(_layout); _devCon->VSSetShader(_vs, 0, 0); _devCon->PSSetShader(_ps, 0, 0); } void D3D::SetZBufferOn() { _devCon->OMSetDepthStencilState(_depthStencilState, 1); } void D3D::SetZBufferOff() { _devCon->OMSetDepthStencilState(_depthDisabledStencilState, 1); } void D3D::CreateConstantBuffer() { // constant buffer D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(CBUFFER); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; if (FAILED(_dev->CreateBuffer(&bd, NULL, &_cBuffer))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D constant buffer!"); } } void D3D::CreateVertexBuffer(std::vector<VERTEX> OurVertices) { // create the vertex buffer D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DYNAMIC; bd.ByteWidth = sizeof(VERTEX) * OurVertices.size(); bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; if (FAILED(_dev->CreateBuffer(&bd, NULL, &_vBuffer))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D vertex buffer!"); } // copy the vertices into the buffer D3D11_MAPPED_SUBRESOURCE ms; if (FAILED(_devCon->Map(_vBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms))) { throw CommonException((LPWSTR)L"Critical error: Unable to map Direct3D vertex buffer!"); } memcpy(ms.pData, OurVertices.data(), sizeof(VERTEX) * OurVertices.size()); _devCon->Unmap(_vBuffer, NULL); } void D3D::CreateIndexBuffer(std::vector<UINT> OurIndices) { // create the index buffer D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DYNAMIC; bd.ByteWidth = sizeof(UINT) * OurIndices.size(); bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bd.MiscFlags = 0; if (FAILED(_dev->CreateBuffer(&bd, NULL, &_iBuffer))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D index buffer!"); } // copy the indices into the buffer D3D11_MAPPED_SUBRESOURCE ms; if (FAILED(_devCon->Map(_iBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms))) { throw CommonException((LPWSTR)L"Critical error: Unable to map Direct3D index buffer!"); } memcpy(ms.pData, OurIndices.data(), sizeof(UINT) * OurIndices.size()); _devCon->Unmap(_iBuffer, NULL); } void D3D::InitRasterizer() { D3D11_RASTERIZER_DESC rd; rd.FillMode = D3D11_FILL_SOLID; rd.CullMode = D3D11_CULL_BACK; rd.FrontCounterClockwise = TRUE; rd.DepthClipEnable = TRUE; rd.ScissorEnable = FALSE; rd.AntialiasedLineEnable = TRUE; rd.MultisampleEnable = FALSE; rd.DepthBias = 0; rd.DepthBiasClamp = 0.0f; rd.SlopeScaledDepthBias = 0.0f; if (FAILED(_dev->CreateRasterizerState(&rd, &_rs))) { throw CommonException((LPWSTR)L"Critical error: Unable to creat Direct3D rasterizer state!"); } } void D3D::InitSampler() { D3D11_SAMPLER_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sd.MaxAnisotropy = 16; sd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sd.BorderColor[0] = 0.0f; sd.BorderColor[1] = 0.0f; sd.BorderColor[2] = 0.0f; sd.BorderColor[3] = 0.0f; sd.ComparisonFunc = D3D11_COMPARISON_NEVER; sd.MinLOD = 0.0f; sd.MaxLOD = FLT_MAX; sd.MipLODBias = 0.0f; if (FAILED(_dev->CreateSamplerState(&sd, &_ssw))) { throw CommonException((LPWSTR)L"Critical error: Unable to creat Direct3D wrap sampler state!"); } sd.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; sd.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; sd.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; if (FAILED(_dev->CreateSamplerState(&sd, &_ssc))) { throw CommonException((LPWSTR)L"Critical error: Unable to creat Direct3D clamp sampler state!"); } } <file_sep>#include "stdafx.h" #include "Camera.h" using namespace DirectX; Camera::Camera() { _camPosition = CAMINITPOSITION; } Camera::~Camera() { } void Camera::SetNewPosition(XMMATRIX rotation) { _camPosition = CAMINITPOSITION; _camPosition = XMVector4Transform(_camPosition, rotation); } DirectX::XMMATRIX Camera::GetViewMatrix() const { return XMMatrixLookAtLH( _camPosition, // the camera position (rotating around the center of the board) XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f), // the look-at position XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f) // the up direction ); } <file_sep>#include "stdafx.h" #include <DirectXMath.h> #include "Game.h" #include "D3D.h" #include "CommonException.h" #include "Marker.h" using namespace DirectX; using namespace std; Game::Game(HWND hWnd) { _d3d = new D3D(hWnd); _d2d = new D2D(_d3d); _camera = new Camera(); _vehiclePicker = new VehiclePicker(_d3d, _camera, _worldOffset); _depthRenderer = new DepthRenderer(_d3d); _shadowRenderer = new ShadowRenderer(_d3d); _downsampledWindow = new OrthoWindow(_d3d, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2); _fullsizedWindow = new OrthoWindow(_d3d, SCREEN_WIDTH, SCREEN_HEIGHT); _dsOrthoWindowRenderer = new OrthoWindowRenderer(_d3d, _downsampledWindow); _fsOrthoWindowRenderer = new OrthoWindowRenderer(_d3d, _fullsizedWindow); } Game::~Game() { if (_d2d) delete _d2d; if (_d3d) delete _d3d; if (_camera) delete _camera; if (_vehiclePicker) delete _vehiclePicker; if (_depthRenderer) delete _depthRenderer; if (_shadowRenderer) delete _shadowRenderer; if (_dsOrthoWindowRenderer) delete _dsOrthoWindowRenderer; if (_fsOrthoWindowRenderer) delete _fsOrthoWindowRenderer; if (_downsampledWindow) delete _downsampledWindow; if (_fullsizedWindow) delete _fullsizedWindow; } // Called once per frame, rotates the cube and calculates the model and view matrices. void Game::Update(double frameTime) { _frameTime = frameTime; UpdateMovementStep(); UpdateGlowLevel(); } // Rotate the 3D scene a set amount of radians. void Game::Rotate(float direction) { _rotationAngle += static_cast<float>(ROTATESPEED * direction * _frameTime); // Prepare to pass the updated model matrix to the shader _rotation = XMMatrixRotationY(_rotationAngle); } // Set vehicle given by idstr as active and return true. Return false if such vehicle does not exist. bool Game::SetActiveVehicle(string idstr) { if (IsActiveVehicleLocked()) { return false; } if (_vehicles.find(idstr) == _vehicles.end()) { return false; } if (!_activeVehicle.empty()) { _vehicles.at(_activeVehicle).SetGlowLevel(0.0f); } _activeVehicle = idstr; return true; } bool Game::UnsetActiveVehicle() { if (IsActiveVehicleLocked()) { return false; } if (!_activeVehicle.empty()) { _vehicles.at(_activeVehicle).SetGlowLevel(0.0f); } _activeVehicle.clear(); return true; } // Find new shown vehicle the can be moved and set it as active void Game::SetNextActiveVehicle() { // get _vehicles iterator for activeInstace auto miItStart = (_activeVehicle.empty()) ? _vehicles.begin() : _vehicles.find(_activeVehicle); // and move iterator to next vehicle as a start position for searching miItStart++; for (auto it = miItStart; it != _vehicles.end(); it++) { // search behind the start position if (IsVehicleFreeForMove(it->first) && !it->second.IsHidden()) { SetActiveVehicle(it->first); return; } } for (auto it = _vehicles.begin(); it != miItStart; it++) { // search before the start position if (IsVehicleFreeForMove(it->first) && !it->second.IsHidden()) { SetActiveVehicle(it->first); return; } } } // Moves vehicle one field forward (dir > 0), or backward (dir < 0) // Return true if success. Return false if the vehicle can't be moved. bool Game::MoveActiveVehicle(Game::Direction_t dir) { string actVehicle = GetActiveVehicle(); if (actVehicle.empty() || !IsVehicleFreeForMoveForwardOrBackward(actVehicle, dir) || !LockActiveVehicle()) { return false; } int dirCoef = 1; // coeficient for movementStep direction if (dir == Game::Backward) { dirCoef = -1; } _vehicles.at(actVehicle).SetMovementStep(static_cast<float>(_frameTime * MOVE_SPEED * dirCoef)); return true; } // Return true if instace can move in either direction (forward or backward). bool Game::IsVehicleFreeForMove(std::string idstr) const { return IsVehicleFreeForMoveForwardOrBackward(idstr, Game::Backward) || IsVehicleFreeForMoveForwardOrBackward(idstr, Game::Forward); } // Return true if instace can move in specified direction. // Test whether position in required direction is occupyied by some vehicle or is blocked by grid limits. bool Game::IsVehicleFreeForMoveForwardOrBackward(std::string idstr, Game::Direction_t dir) const { const Vehicle& mi1 = _vehicles.at(idstr); for (auto it : _vehicles) { if (it.first == idstr) { // don't test itself continue; } const Vehicle& mi2 = it.second; Coords2i_t testCoords; int c = (dir == Game::Forward) ? mi1.GetLength() : -1; Coords2i_t p = mi1.GetPosition(); int newx, newz; if (mi1.GetOrientation() == Vehicle::XAxis) { newx = p.x + c; newz = p.z; } else { newx = p.x; newz = p.z + c; } if ((newx < BOARD_MIN_COORD) || (newx > BOARD_MAX_COORD) || (newz < BOARD_MIN_COORD) || (newz > BOARD_MAX_COORD)) { return false; } testCoords = { newx, newz }; if (mi2.IsOccupyingPosition(testCoords)) { return false; } } return true; } // Perform the movement started by MoveActiveVehicle() method step by step void Game::UpdateMovementStep() { if (GetActiveVehicle().empty()) { return; } Vehicle& mi = _vehicles.at(GetActiveVehicle()); Coords2i_t coords = mi.GetPosition(); float newMovementStep; int dirCoef; if (mi.GetMovementStep() == 0.0f) { // no movement requested return; } else if (mi.GetMovementStep() < 0.0f) { // moving backward newMovementStep = mi.GetMovementStep() - (static_cast<float>(_frameTime * MOVE_SPEED)); dirCoef = -1; } else { // moving forward newMovementStep = mi.GetMovementStep() + (static_cast<float>(_frameTime * MOVE_SPEED)); dirCoef = 1; } if (abs(newMovementStep) >= 1.0f) { // vehicle finished its move to new position, so replace movementStep with new vehicle position and update its BoundingBox if (mi.GetOrientation() == Vehicle::XAxis) { mi.SetPosition(coords.x + dirCoef, coords.z); } else { // (mi.GetOrientation() == Vehicle::ZAxis) mi.SetPosition(coords.x, coords.z + dirCoef); } newMovementStep = 0.0f; UnlockActiveVehicle(); } mi.SetMovementStep(newMovementStep); _vehiclePicker->UpdateBoundingBox(GetActiveVehicle()); } // Update glow level of active vehicle blinking void Game::UpdateGlowLevel() { const float maxGlowLevel = 2.0f; const float glowLevelStep = static_cast<float>(_frameTime * GLOWSPEED); if (GetActiveVehicle().empty()) { return; } Vehicle& ai = _vehicles.at(GetActiveVehicle()); float glowLevel = ai.GetGlowLevel(); if (glowLevel >= maxGlowLevel) { _glowLevelUp = false; } else if (glowLevel <= 0.0f) { _glowLevelUp = true; } int glowDirCoef = (_glowLevelUp) ? 1 : -1; float newGlowLevel = glowLevel + (glowLevelStep * glowDirCoef); if (newGlowLevel > maxGlowLevel) { newGlowLevel = maxGlowLevel; } else if (newGlowLevel < 0.0f) { newGlowLevel = 0.0f; } ai.SetGlowLevel(newGlowLevel); } bool Game::LockActiveVehicle() { if (_activeVehicleLock) { return false; } return _activeVehicleLock = true; } void Game::UnlockActiveVehicle() { _activeVehicleLock = false; } // Print info text void Game::PrintInfoString() const { wstring s = _infoString + _debugInfoString; if (FAILED(_d2d->GetWriteFactory()->CreateTextLayout(s.c_str(), (UINT32)s.size(), _d2d->GetTextFormatFPS(), (float)SCREEN_WIDTH, (float)SCREEN_HEIGHT, _d2d->GetTextLayoutFPSAddr()))) { throw CommonException((LPWSTR)L"Critical error: Failed to create the text layout for FPS information!"); } } void Game::ClearInfoString() { _infoString.clear(); } void Game::AddInfoString(wstring wstr) { _infoString += wstr; } void Game::SetDebugInfoString(std::wstring wstr) { _debugInfoString = wstr; } // Renders one frame using the vertex and pixel shaders. void Game::Render() { CBUFFER cBuffer; // *** CAMERA SECTION XMMATRIX matView; _camera->SetNewPosition(_rotation); matView = _camera->GetViewMatrix(); cBuffer.cameraPosition = _camera->GetPosition(); // Set projection matrix XMMATRIX matPerspective = _d3d->GetProjectionMatrix(); // *** LIGHTS SECTION XMMATRIX lightView, lightPerspective; XMVECTOR lightPosition = LIGHTPOSITION; // Set light view matrix lightView = XMMatrixLookAtLH( lightPosition, // the light position XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f), // the look-at position XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f) // the up direction ); cBuffer.lightPosition = lightPosition; // Set light projection matrix lightPerspective = XMMatrixPerspectiveFovLH((FLOAT)XMConvertToRadians(45), (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, 1.0f, 100.0f); #define USESOFTSHADOW // undefine to use basic shadows // *** RENDER SECTION // Render depth texture _depthRenderer->ConfigureRendering(); RenderScene(&cBuffer, matView, matPerspective, lightView, lightPerspective); // Render shadow into texture _shadowRenderer->ConfigureRendering(); //_shadowRenderer->ConfigureRenderingDebug(); _d3d->GetDeviceContext()->PSSetShaderResources(1, 1, _depthRenderer->GetRenderTextureSRVAddr()); // provide depth texture to shader RenderScene(&cBuffer, matView, matPerspective, lightView, lightPerspective); #ifdef USESOFTSHADOW // Downsample shadow texture into OrthoWindow _dsOrthoWindowRenderer->ConfigureRendering(); //_dsOrthoWindowRenderer->ConfigureRenderingDebug(); _d3d->GetDeviceContext()->PSSetShaderResources(0, 1, _shadowRenderer->GetRenderTextureSRVAddr()); // provide shadow texture to shader RenderOrthoWindow(_downsampledWindow, _downsampledWindow->GetViewMatrix(), _downsampledWindow->GetOrthoMatrix()); // Upsample shadow texture into OrthoWindow _fsOrthoWindowRenderer->ConfigureRendering(); //_fsOrthoWindowRenderer->ConfigureRenderingDebug(); _d3d->GetDeviceContext()->PSSetShaderResources(0, 1, _dsOrthoWindowRenderer->GetRenderTextureSRVAddr()); // provide downsampled texture to shader RenderOrthoWindow(_fullsizedWindow, _fullsizedWindow->GetViewMatrix(), _fullsizedWindow->GetOrthoMatrix()); #endif // Render final scene _d3d->ConfigureRenderering(); // Use the below line instead of the next when Ortographic projection of shadows is working properly: #ifdef USESOFTSHADOW _d3d->GetDeviceContext()->PSSetShaderResources(2, 1, _fsOrthoWindowRenderer->GetRenderTextureSRVAddr()); // use soft shadow (provide upsampled texture to shader) #else _d3d->GetDeviceContext()->PSSetShaderResources(2, 1, _shadowRenderer->GetRenderTextureSRVAddr()); // use basic shadow #endif RenderScene(&cBuffer, matView, matPerspective, lightView, lightPerspective); /* */ // print FPS info _d2d->PrintInfo(); // switch the back buffer and the front buffer _d3d->GetSwapChain()->Present(0, 0); } void Game::RenderOrthoWindow(OrthoWindow* orthoWindow, DirectX::XMMATRIX matView, DirectX::XMMATRIX matPerspective) { OrthoWindow::CBUFFER cBuffer; cBuffer.screenHeight = (float) orthoWindow->GetWindowHeight(); cBuffer.screenWidth = (float) orthoWindow->GetWindowWidth(); cBuffer.mvp = XMMatrixIdentity() * matView * matPerspective; // Send constant buffer _d3d->GetDeviceContext()->UpdateSubresource(orthoWindow->GetCBuffer(), 0, 0, &cBuffer, 0, 0); _d3d->GetDeviceContext()->DrawIndexed(orthoWindow->GetNumOfIndices(), 0, 0); } void Game::RenderScene(CBUFFER* pcBuffer, XMMATRIX matView, XMMATRIX matPerspective, XMMATRIX lightView, XMMATRIX lightPerspective) { // Set lights pcBuffer->diffuseColor = XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f); pcBuffer->ambientColor = XMVectorSet(_ambientColorIntensity, _ambientColorIntensity, _ambientColorIntensity, 1.0f); pcBuffer->specularColor = XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f); // Draw model instances for (auto it = _minstances.begin(); it != _minstances.end(); it++) { ModelInstance mi = it->second; // Store instance transformation into constant buffer XMMATRIX worldMatrix = mi.GetTransformation() * _worldOffset; XMMATRIX mvpMatrix = worldMatrix * matView * matPerspective; XMMATRIX lightMvpMatrix = worldMatrix * lightView * lightPerspective; XMMATRIX invTrWorld = XMMatrixInverse(nullptr, XMMatrixTranspose(worldMatrix)); pcBuffer->world = worldMatrix; pcBuffer->mvp = mvpMatrix; pcBuffer->lightmvp = lightMvpMatrix; pcBuffer->invTrWorld = invTrWorld; pcBuffer->specularPower = 100000.0f; // Send constant buffer _d3d->GetDeviceContext()->UpdateSubresource(_d3d->GetCBuffer(), 0, 0, pcBuffer, 0, 0); for (auto i : mi.GetModel().GetMeshEntries()) { // select texture _d3d->GetDeviceContext()->PSSetShaderResources(0, 1, &i._pTexture); _d3d->GetDeviceContext()->DrawIndexed(i._numIndices, i._baseIndex, i._baseVertex); } } // Draw vehicles for (auto it = _vehicles.begin(); it != _vehicles.end(); it++) { Vehicle mi = it->second; if (mi.IsHidden()) { continue; } // Store vehicle transformation into constant buffer XMMATRIX worldMatrix = mi.GetTransformation() * _worldOffset; XMMATRIX mvpMatrix = worldMatrix * matView * matPerspective; XMMATRIX lightMvpMatrix = worldMatrix * lightView * lightPerspective; XMMATRIX invTrWorld = XMMatrixInverse(nullptr, XMMatrixTranspose(worldMatrix)); pcBuffer->world = worldMatrix; pcBuffer->mvp = mvpMatrix; pcBuffer->lightmvp = lightMvpMatrix; pcBuffer->invTrWorld = invTrWorld; // Store vehicle color into constant buffer XMVECTOR vehicleColor = mi.GetColor(); pcBuffer->diffuseColor = vehicleColor; pcBuffer->specularColor = vehicleColor; float glowIntensity = _ambientColorIntensity + mi.GetGlowLevel(); pcBuffer->ambientColor = XMVectorSet(vehicleColor.m128_f32[0] * glowIntensity, vehicleColor.m128_f32[1] * glowIntensity, vehicleColor.m128_f32[2] * glowIntensity, vehicleColor.m128_f32[3] * glowIntensity); pcBuffer->specularPower = 20.0f; // Send constant buffer _d3d->GetDeviceContext()->UpdateSubresource(_d3d->GetCBuffer(), 0, 0, pcBuffer, 0, 0); for (auto i : mi.GetModel().GetMeshEntries()) { // select texture _d3d->GetDeviceContext()->PSSetShaderResources(0, 1, &i._pTexture); _d3d->GetDeviceContext()->DrawIndexed(i._numIndices, i._baseIndex, i._baseVertex); } } // Draw markers for (auto it = _markers.begin(); it != _markers.end(); it++) { Marker mi = it->second; if (mi.IsHidden()) { continue; } // Store marker transformation into constant buffer XMMATRIX worldMatrix = mi.GetTransformation(); XMMATRIX mvpMatrix = worldMatrix * matView * matPerspective; XMMATRIX lightMvpMatrix = worldMatrix * lightView * lightPerspective; XMMATRIX invTrWorld = XMMatrixInverse(nullptr, XMMatrixTranspose(worldMatrix)); pcBuffer->world = worldMatrix; pcBuffer->mvp = mvpMatrix; pcBuffer->lightmvp = lightMvpMatrix; pcBuffer->invTrWorld = invTrWorld; pcBuffer->specularPower = 100000.0f; // Send constant buffer _d3d->GetDeviceContext()->UpdateSubresource(_d3d->GetCBuffer(), 0, 0, pcBuffer, 0, 0); for (auto i : mi.GetModel().GetMeshEntries()) { // select texture _d3d->GetDeviceContext()->PSSetShaderResources(0, 1, &i._pTexture); _d3d->GetDeviceContext()->DrawIndexed(i._numIndices, i._baseIndex, i._baseVertex); } } } void Game::Init() { // Load all models _models.emplace(make_pair(string("bus"), Model("models/bus.obj", _d3d->GetDevice()))); _models.emplace(make_pair(string("car"), Model("models/taxi_cab.obj", _d3d->GetDevice()))); _models.emplace(make_pair(string("board"), Model("models/board.3DS", _d3d->GetDevice()))); _models.emplace(make_pair(string("wall"), Model("models/oldWall.obj", _d3d->GetDevice()))); _models.emplace(make_pair(string("ball"), Model("models/10536_soccerball_V1_iterations-2.obj", _d3d->GetDevice()))); // Create base model instances const float carScale = 0.0075f; const float busScale = 0.105f; const float boardScale1 = 1.0f; const float boardScale2 = 0.73f; const float wallScale = 0.1253f; const float ballScale = 0.01f; Vehicle miCar(_models.at("car"), XMMatrixScaling(carScale, carScale, carScale), XMVectorSet(0.5f, 0.0f, 0.0f, 0.0f), false, CARLEN); Vehicle miBus(_models.at("bus"), XMMatrixScaling(busScale, busScale, busScale), XMVectorSet(1.2f, 0.0f, 0.0f, 0.0f), true, BUSLEN); ModelInstance miBoard(_models.at("board"), XMMatrixScaling(boardScale1, boardScale1, boardScale2), XMVectorSet(-0.5f, -0.23f, -0.38f, 0.0f), XMMatrixRotationX(XMConvertToRadians(90.0f))); ModelInstance miWallZ(_models.at("wall"), XMMatrixScaling(wallScale, wallScale, wallScale), XMVectorSet(0.57f, -0.0f, 0.49f, 0.0f), XMMatrixIdentity()); ModelInstance miWallX(_models.at("wall"), XMMatrixScaling(wallScale, wallScale, wallScale), XMVectorSet(0.55f, -0.0f, 0.64f, 0.0f), XMMatrixIdentity()); Marker marker(_models.at("ball"), XMMatrixScaling(ballScale, ballScale, ballScale)); // Create base board as copy of base instance miBoard _minstances.insert(make_pair(string("board"), miBoard)); MI(board).SetPosition(0, 0); MI(board).SetOrientation(ModelInstance::XAxis); // Create markers //_markers.insert(make_pair(string("marker1"), marker)); // Create walls as copies of base instance miWall // Wall side 1 _minstances.insert(make_pair(string("wall1"), miWallZ)); _minstances.insert(make_pair(string("wall2"), miWallZ)); _minstances.insert(make_pair(string("wall3"), miWallZ)); _minstances.insert(make_pair(string("wall4"), miWallZ)); _minstances.insert(make_pair(string("wall5"), miWallZ)); _minstances.insert(make_pair(string("wall6"), miWallZ)); _minstances.insert(make_pair(string("wall7"), miWallZ)); MI(wall1).SetPosition(-4, -4); MI(wall1).SetOrientation(ModelInstance::ZAxis); MI(wall2).SetPosition(-3, -4); MI(wall2).SetOrientation(ModelInstance::ZAxis); MI(wall3).SetPosition(-2, -4); MI(wall3).SetOrientation(ModelInstance::ZAxis); MI(wall4).SetPosition(-1, -4); MI(wall4).SetOrientation(ModelInstance::ZAxis); MI(wall5).SetPosition(0, -4); MI(wall5).SetOrientation(ModelInstance::ZAxis); MI(wall6).SetPosition(1, -4); MI(wall6).SetOrientation(ModelInstance::ZAxis); MI(wall7).SetPosition(2, -4); MI(wall7).SetOrientation(ModelInstance::ZAxis); // Wall side 2 _minstances.insert(make_pair(string("wall8"), miWallX)); _minstances.insert(make_pair(string("wall9"), miWallX)); _minstances.insert(make_pair(string("wall10"), miWallX)); _minstances.insert(make_pair(string("wall11"), miWallX)); _minstances.insert(make_pair(string("wall12"), miWallX)); _minstances.insert(make_pair(string("wall13"), miWallX)); _minstances.insert(make_pair(string("wall14"), miWallX)); MI(wall8).SetPosition(-4, -4); MI(wall8).SetOrientation(ModelInstance::XAxis); MI(wall9).SetPosition(-4, -3); MI(wall9).SetOrientation(ModelInstance::XAxis); MI(wall10).SetPosition(-4, -2); MI(wall10).SetOrientation(ModelInstance::XAxis); MI(wall11).SetPosition(-4, -1); MI(wall11).SetOrientation(ModelInstance::XAxis); MI(wall12).SetPosition(-4, 0); MI(wall12).SetOrientation(ModelInstance::XAxis); MI(wall13).SetPosition(-4, 1); MI(wall13).SetOrientation(ModelInstance::XAxis); MI(wall14).SetPosition(-4, 2); MI(wall14).SetOrientation(ModelInstance::XAxis); // Wall side 3 _minstances.insert(make_pair(string("wall15"), miWallZ)); _minstances.insert(make_pair(string("wall16"), miWallZ)); _minstances.insert(make_pair(string("wall17"), miWallZ)); _minstances.insert(make_pair(string("wall18"), miWallZ)); _minstances.insert(make_pair(string("wall19"), miWallZ)); _minstances.insert(make_pair(string("wall20"), miWallZ)); _minstances.insert(make_pair(string("wall21"), miWallZ)); MI(wall15).SetPosition(-4, 2); MI(wall15).SetOrientation(ModelInstance::ZAxis); MI(wall16).SetPosition(-3, 2); MI(wall16).SetOrientation(ModelInstance::ZAxis); MI(wall17).SetPosition(-2, 2); MI(wall17).SetOrientation(ModelInstance::ZAxis); MI(wall18).SetPosition(-1, 2); MI(wall18).SetOrientation(ModelInstance::ZAxis); MI(wall19).SetPosition(0, 2); MI(wall19).SetOrientation(ModelInstance::ZAxis); MI(wall20).SetPosition(1, 2); MI(wall20).SetOrientation(ModelInstance::ZAxis); MI(wall21).SetPosition(2, 2); MI(wall21).SetOrientation(ModelInstance::ZAxis); // Wall side 4 _minstances.insert(make_pair(string("wall22"), miWallX)); _minstances.insert(make_pair(string("wall23"), miWallX)); _minstances.insert(make_pair(string("wall24"), miWallX)); _minstances.insert(make_pair(string("wall25"), miWallX)); _minstances.insert(make_pair(string("wall26"), miWallX)); MI(wall22).SetPosition(2, -4); MI(wall22).SetOrientation(ModelInstance::XAxis); MI(wall23).SetPosition(2, -3); MI(wall23).SetOrientation(ModelInstance::XAxis); MI(wall24).SetPosition(2, 0); MI(wall24).SetOrientation(ModelInstance::XAxis); MI(wall25).SetPosition(2, 1); MI(wall25).SetOrientation(ModelInstance::XAxis); MI(wall26).SetPosition(2, 2); MI(wall26).SetOrientation(ModelInstance::XAxis); // Create vehicles as copies of base instances miCar and miBus _vehicles.insert(make_pair(string("car1"), miCar)); _vehicles.insert(make_pair(string("car2"), miCar)); _vehicles.insert(make_pair(string("car3"), miCar)); _vehicles.insert(make_pair(string("car4"), miCar)); _vehicles.insert(make_pair(string("car5"), miCar)); _vehicles.insert(make_pair(string("car6"), miCar)); _vehicles.insert(make_pair(string("car7"), miCar)); _vehicles.insert(make_pair(string("car8"), miCar)); _vehicles.insert(make_pair(string("car9"), miCar)); _vehicles.insert(make_pair(string("car10"), miCar)); _vehicles.insert(make_pair(string("car11"), miCar)); _vehicles.insert(make_pair(string("car12"), miCar)); _vehicles.insert(make_pair(string("bus1"), miBus)); _vehicles.insert(make_pair(string("bus2"), miBus)); _vehicles.insert(make_pair(string("bus3"), miBus)); _vehicles.insert(make_pair(string("bus4"), miBus)); // Set color of each vehicle VEH(car1).SetColor(XMUINT3{ UINT(255 * CARLIGHTINTENSITY), 0, 0 }); // Player's car /* DEBUG - umistovani instanci bude resit trida Level */ // Positon vehicles into the grid // Available coordinates: <-3, 2> for x and z axis VEH(bus1).SetPosition(-3, -2); VEH(bus1).SetOrientation(Vehicle::ZAxis); VEH(bus1).Show(); VEH(bus2).SetPosition(0, -2); VEH(bus2).SetOrientation(Vehicle::ZAxis); VEH(bus2).Show(); VEH(bus3).SetPosition(2, -3); VEH(bus3).SetOrientation(Vehicle::ZAxis); VEH(bus3).Show(); VEH(bus4).SetPosition(-1, 2); VEH(bus4).SetOrientation(Vehicle::XAxis); VEH(bus4).Show(); VEH(car1).SetPosition(-2, -1); VEH(car1).SetOrientation(Vehicle::XAxis); VEH(car1).Show(); VEH(car2).SetPosition(-3, -3); VEH(car2).SetOrientation(Vehicle::XAxis); VEH(car2).Show(); VEH(car3).SetPosition(-3, 1); VEH(car3).SetOrientation(Vehicle::ZAxis); VEH(car3).Show(); VEH(car4).SetPosition(1, 1); VEH(car4).SetOrientation(Vehicle::XAxis); VEH(car4).Show(); /* DEBUG END */ // Select first active vehicle this->SetNextActiveVehicle(); // Fill Vertex and Index buffers with data from Models _d3d->CreateVertexBuffer(Model::GetModelVertices()); _d3d->CreateIndexBuffer(Model::GetModelIndices()); // Configure VehiclePicker _vehiclePicker->InitBoundingBoxes(&_vehicles); } <file_sep>#pragma once #include <stdexcept> class CommonException : public std::exception { public: CommonException() = default; CommonException(LPWSTR msg) : _msg(msg), exception() {} ~CommonException() = default; virtual LPWSTR What() { return _msg; } private: LPWSTR _msg; }; <file_sep>#include "stdafx.h" #include "TextureRenderer.h" #include "stdafx.h" #include <d3dcompiler.h> #include "TextureRenderer.h" #include "CommonException.h" TextureRenderer::TextureRenderer(D3D * d3d, FLOAT textureWidth, FLOAT textureHeight) : _d3d(d3d), _textureWidth(textureWidth), _textureHeight(textureHeight) { // Create shadow render texture and its zbuffer CreateRenderTextureDepthBuffer(); CreateRenderTexture(); } TextureRenderer::~TextureRenderer() { if (_rtzBuffer) _rtzBuffer->Release(); if (_rTextureSRV) _rTextureSRV->Release(); if (_rTexture) _rTexture->Release(); } void TextureRenderer::CreateRenderTextureDepthBuffer() { // create the depth buffer texture D3D11_TEXTURE2D_DESC texd; ZeroMemory(&texd, sizeof(texd)); texd.Width = static_cast<UINT>(_textureWidth); texd.Height = static_cast<UINT>(_textureHeight); texd.ArraySize = 1; texd.MipLevels = 1; texd.SampleDesc.Count = 1; texd.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; texd.Usage = D3D11_USAGE_DEFAULT; texd.BindFlags = D3D11_BIND_DEPTH_STENCIL; ID3D11Texture2D *pDepthBuffer; if (FAILED(_d3d->GetDevice()->CreateTexture2D(&texd, NULL, &pDepthBuffer))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D depth buffer texture!"); } // create the depth buffer D3D11_DEPTH_STENCIL_VIEW_DESC dsvd; ZeroMemory(&dsvd, sizeof(dsvd)); //dsvd.Format = DXGI_FORMAT_D32_FLOAT; dsvd.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS; if (FAILED(_d3d->GetDevice()->CreateDepthStencilView(pDepthBuffer, &dsvd, &(_rtzBuffer)))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D depth buffer!"); } pDepthBuffer->Release(); } void TextureRenderer::CreateRenderTexture() { ID3D11Texture2D* renderTexture; D3D11_TEXTURE2D_DESC textureDesc; // Initialize the render target texture description. ZeroMemory(&textureDesc, sizeof(textureDesc)); // Setup the render target texture description. textureDesc.Width = static_cast<UINT>(_textureWidth); textureDesc.Height = static_cast<UINT>(_textureHeight); textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; textureDesc.SampleDesc.Count = 1; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; // Create the render target texture. if (FAILED(_d3d->GetDevice()->CreateTexture2D(&textureDesc, NULL, &renderTexture))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D render texture!"); } // Setup the description of the render target view. D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; renderTargetViewDesc.Format = textureDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; // Create the render target view. if (FAILED(_d3d->GetDevice()->CreateRenderTargetView(renderTexture, &renderTargetViewDesc, &_rTexture))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D render texture target view!"); } // Setup the description of the shader resource view. D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc; shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; // Create the shader resource view. if (FAILED(_d3d->GetDevice()->CreateShaderResourceView(renderTexture, &shaderResourceViewDesc, &_rTextureSRV))) { throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D render texture shader resource view!"); } renderTexture->Release(); } void TextureRenderer::SetRenderTextureShaders() { _d3d->GetDeviceContext()->IASetInputLayout(_rtlayout); _d3d->GetDeviceContext()->VSSetShader(_rtvs, 0, 0); _d3d->GetDeviceContext()->PSSetShader(_rtps, 0, 0); } <file_sep>#include "stdafx.h" #include "Timer.h" Timer::Timer() { } Timer::~Timer() { } void Timer::StartTimer() { LARGE_INTEGER frequencyCount; QueryPerformanceFrequency(&frequencyCount); _countsPerSecond = double(frequencyCount.QuadPart); QueryPerformanceCounter(&frequencyCount); _counterStart = frequencyCount.QuadPart; } double Timer::GetTime() { LARGE_INTEGER currentTime; QueryPerformanceCounter(&currentTime); return double(currentTime.QuadPart - _counterStart) / _countsPerSecond; } double Timer::GetFrameTime() { LARGE_INTEGER currentTime; __int64 tickCount; QueryPerformanceCounter(&currentTime); tickCount = currentTime.QuadPart - _frameTimeOld; _frameTimeOld = currentTime.QuadPart; if (tickCount < 0) tickCount = 0; return float(tickCount) / _countsPerSecond; }<file_sep>#include "stdafx.h" #include "Marker.h" using namespace std; using namespace DirectX; Marker::Marker(Model & m, DirectX::XMMATRIX scale) : Marker(m) { _scale = scale; } DirectX::XMMATRIX Marker::GetTransformation() const { XMMATRIX r = _rotation; XMMATRIX p = XMMatrixTranslation(static_cast<float>(GetPosition().x), static_cast<float>(GetPosition().y), static_cast<float>(GetPosition().z)); return r * GetScale() * p; } <file_sep>#pragma once #include <d3d11.h> #include <directxmath.h> #include <vector> #include "RushHour.h" #include "D3DSupplementary.h" class D3D { public: D3D() = delete; D3D(HWND hWnd); D3D(D3D&&) = default; D3D& operator= (D3D&&) = default; ~D3D(); // D3D must not be copied, as it would release all elements after copy D3D(const D3D&) = delete; D3D& operator=(const D3D&) = delete; void CreateVertexBuffer(std::vector<VERTEX> OurVertices); void CreateIndexBuffer(std::vector<UINT> OurIndices); void SetRenderTargetBackBuffer() { SetRenderTarget(&(_bBuffer), _zBuffer); } void SetBackBufferShaders(); void SetRenderTarget(ID3D11RenderTargetView** rtv, ID3D11DepthStencilView* dsv); void SetZBufferOn(); void SetZBufferOff(); void SetBuffers(); void SetViewport(); void ConfigureRenderering(); IDXGISwapChain* GetSwapChain() const { return _swapChain; }; IDXGIDevice* GetDXGIDevice() const { return _dxgiDevice; } ID3D11Device* GetDevice() const { return _dev; } ID3D11DeviceContext* GetDeviceContext() const { return _devCon; } ID3D11RenderTargetView* GetBackBuffer() const { return _bBuffer; } ID3D11DepthStencilView* GetZBuffer() const { return _zBuffer; } ID3D11Buffer* GetCBuffer() const { return _cBuffer; } ID3D11Buffer* GetVBuffer() const { return _vBuffer; } ID3D11Buffer** GetVBufferAddr() { return &(_vBuffer); } ID3D11Buffer* GetIBuffer() const { return _iBuffer; } ID3D11InputLayout* GetLayout() const { return _layout; } ID3D11RasterizerState* GetRState() const { return _rs; } ID3D11SamplerState* GetSStateWrap() const { return _ssw; } ID3D11SamplerState** GetSStateWrapAddr() { return &(_ssw); } ID3D11SamplerState* GetSStateClamp() const { return _ssc; } ID3D11SamplerState** GetSStateClampAddr() { return &(_ssc); } DirectX::XMMATRIX GetProjectionMatrix() const { return _matPerspective; } private: IDXGISwapChain* _swapChain; // swap chain interface IDXGIDevice* _dxgiDevice; ID3D11Device* _dev; // device interface ID3D11DeviceContext* _devCon; // device context ID3D11VertexShader* _vs; // vertex shader ID3D11PixelShader* _ps; // pixel shader ID3D11InputLayout* _layout; // layout ID3D11RenderTargetView* _bBuffer; // backbuffer ID3D11DepthStencilView* _zBuffer; // depth buffer ID3D11Buffer* _cBuffer; // constant buffer ID3D11Buffer* _vBuffer; // vertex buffer ID3D11Buffer* _iBuffer; // index buffer // State objects ID3D11RasterizerState* _rs; // the default rasterizer state ID3D11SamplerState* _ssw; // sampler state wrap ID3D11SamplerState* _ssc; // sampler state clamp ID3D11DepthStencilState* _depthStencilState; // depth buffer state ID3D11DepthStencilState* _depthDisabledStencilState; // depth buffer disabled state // Matrices DirectX::XMMATRIX _matPerspective; void CreateDevice(HWND hWnd); void CreateDepthBuffer(); void CreateRenderTarget(); void LoadBackBufferShaders(); void CreateConstantBuffer(); void InitRasterizer(); void InitSampler(); };
441ca042202c550a95578ecaa12452a4c39c4378
[ "Markdown", "C", "C++" ]
31
C++
pazder82/RushHour
c5cc0ccaa175dc4b05a5c9babf46dbd01c3b3beb
867445a37e9f97789e3834dac9c1b5aec98af66d
refs/heads/master
<repo_name>Kennet28/Generic<file_sep>/Generic.Api/Seed.cs using System.Collections.Generic; using System.Linq; using Generic.Core.Models; using Microsoft.AspNetCore.Identity; using Newtonsoft.Json; namespace Generic.Api { public class Seed { public static void SeedUsers(RoleManager<Role> roleManager) { var roles = new List<Role> { new Role{Name = "Admin"} }; foreach (var role in roles) { roleManager.CreateAsync(role).Wait(); }; } } }<file_sep>/Generic.Api/Controllers/ClientController.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Generic.Api.Dtos; using Generic.Api.Validations; using Generic.Core.Models; using Generic.Core.Services; namespace Generic.Api.Controllers { [Route("api/[controller]")] [ApiController] public class ClientsController : ControllerBase { private readonly IClientService _clientService; private readonly IMapper _mapper; public ClientsController(IClientService clientService, IMapper mapper) { this._mapper = mapper; this._clientService = clientService; } [HttpGet("")] public async Task<ActionResult<IEnumerable<ClientCreate>>> GetAllClients() { var clients = await _clientService.GetAllClients(); var clientList = _mapper.Map<IEnumerable<Client>, IEnumerable<ClientReturn>>(clients); return Ok(clientList); } [HttpGet("{id}")] public async Task<ActionResult<ClientCreate>> GetClientById(int id) { var Client = await _clientService.GetClientById(id); var ClientCreate = _mapper.Map<Client, ClientCreate>(Client); return Ok(ClientCreate); } [HttpPost("")] public async Task<ActionResult<ClientCreate>> CreateClient([FromBody] ClientCreate clientCreate) { var validator = new ClientCreateValidator(); var validationResult = await validator.ValidateAsync(clientCreate); if (!validationResult.IsValid) return BadRequest(validationResult.Errors); // this needs refining, but for demo it is ok var ClientToCreate = _mapper.Map<ClientCreate, Client>(clientCreate); var newClient = await _clientService.CreateClient(ClientToCreate); var Client = await _clientService.GetClientById(newClient.Id); var ClientCreate = _mapper.Map<Client, ClientReturn>(Client); return Ok(ClientCreate); } [HttpPut("{id}")] public async Task<ActionResult<ClientCreate>> UpdateClient(int id, [FromBody] ClientCreate clientCreate) { var validator = new ClientCreateValidator(); var validationResult = await validator.ValidateAsync(clientCreate); var requestIsInvalid = id == 0 || !validationResult.IsValid; if (requestIsInvalid) return BadRequest(validationResult.Errors); // this needs refining, but for demo it is ok var ClientToBeUpdate = await _clientService.GetClientById(id); if (ClientToBeUpdate == null) return NotFound(); var Client = _mapper.Map<ClientCreate, Client>(clientCreate); await _clientService.UpdateClient(ClientToBeUpdate, Client); var updatedClient = await _clientService.GetClientById(id); var updatedClientCreate = _mapper.Map<Client, ClientReturn>(updatedClient); return Ok(updatedClientCreate); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteClient(int id) { if (id == 0) return BadRequest(); var Client = await _clientService.GetClientById(id); if (Client == null) return NotFound(); await _clientService.DeleteClient(Client); return NoContent(); } } }<file_sep>/Generic.Api/Startup.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Generic.Services; using Generic.Core.Repositories; using Generic.Core.Services; using Generic.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.Swagger; using Microsoft.AspNetCore.Identity; using Generic.Core.Models; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Authorization; namespace Generic.Api { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { IdentityBuilder builder = services.AddIdentityCore<User>(); builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services); builder.AddEntityFrameworkStores<DataContext>(); builder.AddDefaultTokenProviders(); builder.AddRoleManager<RoleManager<Role>>(); builder.AddSignInManager<SignInManager<User>>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII .GetBytes(Configuration.GetSection("AppSettings:Token").Value)), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; }); services.AddControllers(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default"))); services.AddScoped<IUnitOfWork, UnitOfWork>(); services.AddTransient<IClientService, ClientService>(); services.AddScoped<IUserService, UserService>(); services.AddScoped<IAuthenticationService, AuthenticationService>(); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] { } } }); }); services.AddAutoMapper(typeof(Startup)); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); // app.UseSignalR(routes => { // routes.MapHub<SignalHub>("/signalHub"); // }); app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.RoutePrefix = ""; c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Generic V1"); }); } } } <file_sep>/Generic.Core/Repositories/IAuthenticationRepository.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using Generic.Core.Models; using Microsoft.AspNetCore.Identity; namespace Generic.Core.Repositories { public interface IAuthenticationRepository { Task<SignInResult> CheckPasswordSignIn(User user, string password); } }<file_sep>/Generic.Api/DTOS/ClientReturn.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Generic.Api.Dtos { public class ClientReturn { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public string RFC { get; set; } } } <file_sep>/Generic.Data/Repositories/ClientRepository.cs using Generic.Core; using System; using System.Collections.Generic; using System.Text; using Generic.Core.Repositories; using Generic.Core.Models; namespace Generic.Data.Repositories { class ClientRepository : Repository<Client>, IClientRepository { public ClientRepository(DataContext context) : base(context) { } } } <file_sep>/Generic.Core/Services/IClientService.cs using Generic.Core.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Generic.Core.Services { public interface IClientService { Task<IEnumerable<Client>> GetAllClients(); Task<Client> GetClientById(int id); Task<Client> CreateClient(Client newClient); Task UpdateClient(Client ClientToBeUpdated, Client Client); Task DeleteClient(Client Client); } } <file_sep>/Generic.Data/UnitOfWork.cs using Generic.Core.Repositories; using Generic.Data.Repositories; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Generic.Core.Models; namespace Generic.Data { public class UnitOfWork : IUnitOfWork { private readonly DataContext _context; private ClientRepository _clientRepository; private readonly RoleManager<Role> _roleManager; private readonly UserManager<User> _userManager; private readonly SignInManager<User> _signInManager; private UserRepository _userRepository; private AuthenticationRepository _authenticationRepository; public UnitOfWork(DataContext context, RoleManager<Role> roleManager, UserManager<User> userManager, SignInManager<User> signInManager) { this._context = context; this._roleManager = roleManager; this._userManager = userManager; this._signInManager = signInManager; } public IClientRepository Clients => _clientRepository = _clientRepository ?? new ClientRepository(_context); public IUserRepository UserRepository => _userRepository = _userRepository ?? new UserRepository(_userManager, _context); public IAuthenticationRepository AuthenticationRepository => _authenticationRepository = _authenticationRepository ?? new AuthenticationRepository(_signInManager, _context); public async Task<int> CommitAsync() { return await _context.SaveChangesAsync(); } public void Dispose() { _context.Dispose(); } } } <file_sep>/Generic.Core/Repositories/IClientRepository.cs using Generic.Core.Models; using System; using System.Collections.Generic; using System.Text; namespace Generic.Core.Repositories { public interface IClientRepository : IRepository<Client> { } } <file_sep>/Generic.Data/Repositories/AuthenticationRepository.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Generic.Core.Models; using Generic.Core.Repositories; using Microsoft.Data.SqlClient; using System; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; namespace Generic.Data.Repositories { public class AuthenticationRepository : Repository<User>, IAuthenticationRepository { private readonly SignInManager<User> _signInManager; private readonly DataContext _context; public AuthenticationRepository(SignInManager<User> signInManager, DataContext context) : base(context) { _signInManager = signInManager; _context = context; } public async Task<SignInResult> CheckPasswordSignIn(User user, string password) { var result = await _signInManager.CheckPasswordSignInAsync(user, password, false); return result; } } } <file_sep>/Generic.Core/Models/Client.cs using System; namespace Generic.Core.Models { public class Client { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public string RFC { get; set; } } } <file_sep>/Generic.Core/Services/IAuthenticationService.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using Generic.Core.Models; namespace Generic.Core.Services { public interface IAuthenticationService { Task<BaseResponse<User>> Login(String userName, String password); } } <file_sep>/Generic.Api/Mapping/MappingProfile.cs using AutoMapper; using Generic.Api.Dtos; using Generic.Core.Models; namespace MyMusic.Api.Mapping { public class MappingProfile : Profile { public MappingProfile() { // Domain to Resource CreateMap<Client, ClientReturn>(); // Resource to Domain CreateMap<ClientCreate, Client>(); // Domain to Resource CreateMap<User, UserForReturnDto>(); // Resource to Domain CreateMap<UserForCreateDto, User>(); // Resource to Domain CreateMap<UserForUpdateDto, User>(); } } }<file_sep>/Generic.Services/ClientService.cs  using System.Collections.Generic; using System.Threading.Tasks; using Generic.Core.Models; using Generic.Core.Repositories; using Generic.Core.Services; namespace Generic.Services { public class ClientService : IClientService { private readonly IUnitOfWork _unitOfWork; public ClientService(IUnitOfWork unitOfWork) { this._unitOfWork = unitOfWork; } public async Task<Client> CreateClient(Client newClient) { await _unitOfWork.Clients.AddAsync(newClient); await _unitOfWork.CommitAsync(); return newClient; } public async Task DeleteClient(Client Client) { _unitOfWork.Clients.Remove(Client); await _unitOfWork.CommitAsync(); } public async Task<IEnumerable<Client>> GetAllClients() { return await _unitOfWork.Clients .GetAllAsync(); } public async Task<Client> GetClientById(int id) { return await _unitOfWork.Clients .GetByIdAsync(id); } public async Task UpdateClient(Client ClientToBeUpdated, Client Client) { ClientToBeUpdated.Name = Client.Name; ClientToBeUpdated.Address = Client.Address; await _unitOfWork.CommitAsync(); } } }<file_sep>/Generic.Api/DTOS/ClientCreate.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Generic.Api.Dtos { public class ClientCreate { public string Name { get; set; } public string Address { get; set; } public string RFC { get; set; } } } <file_sep>/Generic.Api/Validations/ClientCreateValidator.cs using FluentValidation; using Generic.Api.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Generic.Api.Validations { public class ClientCreateValidator : AbstractValidator<ClientCreate> { public ClientCreateValidator() { RuleFor(a => a.Name) .NotEmpty() .MaximumLength(50); } } }
5539039ae7f5378038b754149a9c91ad8b2d06cc
[ "C#" ]
16
C#
Kennet28/Generic
42d25d695acff2429671ae53a655b2eb0601677d
6c0a0c54d8d78c4094211b9c187d681b385e0a97
refs/heads/master
<repo_name>xkr47/eslint-plugin-react-props<file_sep>/docs/rules/jsx-no-invalid-props.md # JSX No invalid props (jsx-no-invalid-props) A quick check to see if a typo has been made on a PropType which at the minimum is annoying, but can also lead to debugging red herrings ## Rule Details This rule checks propTypes on a class and validates the PropTypes against a static list from the React docs ## Rule Options None yet ## Todo Make more intelligent when determining PropTypes i.e. could have been imported as "p" which would currently fail: ```js propTypes: { a: p.array }; ``` <file_sep>/tests/lib/rules/jsx-no-invalid-props.js 'use strict'; require('babel-eslint'); var rule = require('../../../lib/rules/jsx-no-invalid-props'); var RuleTester = require('eslint').RuleTester; var ruleTester = new RuleTester(); var ANY_ERROR_MESSAGE = 'Check your prop types'; ruleTester.run('jsx-no-invalid-props', rule, { valid: [ { code: [ 'import React, {PropTypes} from "react";', 'export default class TestComponent extends React.Component {', 'constructor(props) {', 'super(props);', 'this.state = {};', '}', 'render() {', 'return (', '<div></div>', ');', '}', '}', 'TestComponent.propTypes = {', 'a: PropTypes.array,', 'b: PropTypes.bool,', 'c: PropTypes.func,', 'd: PropTypes.number,', 'e: PropTypes.object,', 'f: PropTypes.string,', 'g: PropTypes.any,', 'h: PropTypes.arrayOf,', 'i: PropTypes.element,', 'j: PropTypes.instanceOf,', 'k: PropTypes.node,', 'l: PropTypes.objectOf,', 'm: PropTypes.oneOf,', 'n: PropTypes.oneOfType,', 'o: PropTypes.shape,', 'p: PropTypes.array,', 'q: PropTypes.bool,', 'r: PropTypes.func,', 's: PropTypes.number,', 't: PropTypes.object,', 'u: PropTypes.string,', 'v: PropTypes.any,', 'w: PropTypes.arrayOf,', 'x: PropTypes.element,', 'y: PropTypes.instanceOf,', 'z: PropTypes.node,', 'aa: PropTypes.objectOf,', 'ab: PropTypes.oneOf,', 'ac: PropTypes.oneOfType,', 'ad: PropTypes.shape', '};' ].join('\n'), ecmaFeatures: { jsx: true, modules: true, classes: true } } ], invalid: [ { code: [ 'import React, {PropTypes} from "react";', 'export default class TestComponent extends React.Component {', 'constructor(props) {', 'super(props);', 'this.state = {};', '}', 'render() {', 'return (', '<div></div>', ');', '}', '}', 'TestComponent.propTypes = {', 'a: PropTypes.arr,', '};' ].join('\n'), ecmaFeatures: { jsx: true, modules: true, classes: true }, errors: [{ message: 'arr is not a valid PropType', line: 14, column: 1, type: 'Property' }] }, { code: [ 'import React, {PropTypes} from "react";', 'export default class TestComponent extends React.Component {', 'constructor(props) {', 'super(props);', 'this.state = {};', '}', 'render() {', 'return (', '<div></div>', ');', '}', '}', 'TestComponent.propTypes = {', 'a: PropTypes,', '};' ].join('\n'), ecmaFeatures: { jsx: true, modules: true, classes: true }, errors: [{ message: 'unknown use of PropTypes', line: 14, column: 1, type: 'Property' }] } ] });
797b10b6ef8222f8ed519a71325dd754a2097a50
[ "Markdown", "JavaScript" ]
2
Markdown
xkr47/eslint-plugin-react-props
7048f936f76016186ab28826b25cf5bb31c1aff4
31be19859fcb61a1aeb67060e864f43d2fbd4f90
refs/heads/master
<file_sep># windowsapi A collection of Windows API source code <file_sep>#include <windows.h> const char g_class_name[] = "myHelloWorld2WindowClass"; // declare the WndProc function LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); /** * @brief Main Function - displays a resizable window * @note * @param hThisInstance: * @param hPrevInstance: * @param lpCmdLine: * @param nCmdShow: * @retval */ int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd; MSG Msg; //create a structure describing the window wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; // N.B. here we specify the name of our function wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hThisInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_class_name; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); // call RegisterClassEx. This is called "registering the window class". // this tells the operating system we are here and want a window if (!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } // the operating system says we can have a window. Now we create it using CreateWindowEx. // The parameters here define the appearance of the window: what the border looks like,the title, etc. hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, // what the border looks like g_class_name, "Hello World 2", // text appearing in top bar WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 840, 820, // window xpos, ypos, width, height NULL, NULL, hThisInstance, NULL); if (hwnd == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); /* the Message Loop. This while loop is perpetually going round and round at the "base" of the program, it constantly picks up messages from the keyboard, mouse and other devices, and calling the WndProc function */ while ( GetMessage(&Msg, NULL, 0, 0) > 0 ) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; } /** * @brief Display function - displays a string * @note * @param hwnd: * @param s: * @retval None */ void disp(HWND hwnd, char* s) { HFONT hfont, hOldfont; HDC hdc; hfont = (HFONT) GetStockObject(ANSI_VAR_FONT); // obtain a standard font hdc = GetDC(hwnd); // point to the "device context" for this window hOldfont = (HFONT) SelectObject(hdc, hfont); // select font into the device context if (hOldfont) // if succesful { TextOut(hdc, 10, 50, s, strlen(s)); SelectObject(hdc, hOldfont); // put the previous font back into dc } else MessageBox(hwnd, "could not select the font", "Error!", MB_ICONEXCLAMATION | MB_OK); ReleaseDC(hwnd, hdc); // tidy up } /** * @brief WindowsProcedure - call back function * @note * @param hwnd: * @param msg: * @param wParam: * @param lParam: * @retval */ LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_SIZE: disp(hwnd, "hello world 2"); return 0; case WM_LBUTTONDOWN: MessageBox(hwnd, "hello again", "Hello World 2", MB_OK); return 0; case WM_CLOSE: DestroyWindow(hwnd); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; default: return DefWindowProc(hwnd, msg, wParam, lParam); } } <file_sep>#include <windows.h> /** * @brief Main Function - displays a message box * @note * @param hThisInstance: * @param hPrevInstance: * @param lpCmdLine: * @param nCmdShow: * @retval */ int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MessageBox(NULL, "Yes, I am awesome", "A minimal Hello World Windows Program", MB_OK); return 0; }
5f8beb7f4dd2917b28b706746d383f04fe8eef5a
[ "Markdown", "C++" ]
3
Markdown
lismore/windowsapi
40d398e1e0bd207514d884b8227526f308694892
34127a2e023dd4e937783c88e77de5741240597e
refs/heads/master
<file_sep># Randomizador Un gestor de turnos aleatorios para juegos de azar. Agrega a los participantes, y en cada ronda el orden de participación de los jugadores será aleatorio. <file_sep>package randomizador; class Randomizador { public static void main(String[] args) { frmAgregarPersonas ventana = new frmAgregarPersonas(); ventana.setVisible(true); } }
fa735c9691249450d85ffeead3464a55a232905c
[ "Markdown", "Java" ]
2
Markdown
barreto-exe/randomizador
b485dafa44dcd2d01b97d564422ec15cc518fa95
1301a5017e13c3f78d58c4d58f4ab08e8c6656e8
refs/heads/master
<repo_name>stanimirovv/chalga-ili-rap<file_sep>/semtech/main.js // standard modules const https = require('https'); // dependencies const jsdom = require("jsdom"); const { JSDOM } = jsdom; // constants const mainContainerId = 'maintxt'; const maxParallelDownloads = 2; // Main functionality let allSongLyrics = []; /* Chalga */ // let urls = [ // 'https://textove.com/mariya-kaul-klavela-mariya-tekst', // 'https://textove.com/tsvetelina-yaneva-vsichko-tekst', // 'https://textove.com/aneliya-dah-tekst', // 'https://textove.com/emiliya-snezhanka-tekst', // 'https://textove.com/galena-habibi-tekst', // 'https://textove.com/emanuela-skapoto-se-plashta-tekst', // 'https://textove.com/azis-galin-na-egipet-faraona-tekst', // 'https://textove.com/galin-lidiya-nyama-da-mi-mine-tekst', // 'https://textove.com/alisiya-lidiya-ne-me-narichay-skapa-1-tekst', // 'https://textove.com/alisiya-lidiya-ne-me-narichay-skapa-tekst', // 'https://textove.com/desi-slava-lidiya-mnogo-lud-tekst', // 'https://textove.com/diona-dessita-lidiya-izlazhi-me-tekst', // 'https://textove.com/azis-motel-tekst', // 'https://textove.com/azis-napipay-go-tekst', // 'https://textove.com/azis-tseluvay-me-tekst', // 'https://textove.com/azis-tedi-aleksandrova-nasi-podgryavashti-zvezdichki-tekst', // 'https://textove.com/azis-mila-moya-angel-moy-tekst', // 'https://textove.com/azis-obicham-te-tekst', // 'https://textove.com/azis-salzi-tekst', // 'https://textove.com/azis-nyakoy-den-tekst', // 'https://textove.com/azis-mma-tekst', // 'https://textove.com/azis-bivshi-tekst', // 'https://textove.com/azis-boli-tekst', // 'https://textove.com/azis-vseki-pat-tekst', // 'https://textove.com/azis-evala-tekst', // 'https://textove.com/azis-kazhi-chestno-tekst', // 'https://textove.com/alisiya-na-ti-mi-govori-tekst', // 'https://textove.com/alisiya-iliyan-nito-duma-tekst', // 'https://textove.com/alisiya-konstantin-liubov-li-e-tekst', // 'https://textove.com/alisiya-toni-storaro-dobre-ti-beshe-tekst', // 'https://textove.com/alisiya-karamel-tekst', // 'https://textove.com/alisiya-ti-li-tekst', // 'https://textove.com/alisiya-iliyan-za-posledno-tekst', // 'https://textove.com/alisiya-imame-li-vrazka-tekst', // 'https://textove.com/alisiya-sablechi-me-tekst', // 'https://textove.com/alisiya-zapali-tekst', // 'https://textove.com/alisiya-vsichko-si-za-men-tekst', // 'https://textove.com/alisiya-dve-sartsa-tekst', // 'https://textove.com/alisiya-emrah-dusho-moya-tekst', // 'https://textove.com/alisiya-edva-li-te-boli-tekst', // 'https://textove.com/alisiya-toni-storaro-zlatoto-na-tati-tekst', // 'https://textove.com/alisiya-moy-tekst', // 'https://textove.com/galin-liubovta-tekst', // 'https://textove.com/galin-emanuela-5-6-7-8-tekst', // 'https://textove.com/galin-preslava-moga-tekst', // 'https://textove.com/konstantin-galin-kralete-tekst', // 'https://textove.com/yanitsa-galin-roklyata-ti-pada-tekst', // 'https://textove.com/azis-napipay-go-tekst', // 'https://textove.com/azis-tseluvay-me-tekst', // 'https://textove.com/azis-tedi-aleksandrova-nasi-podgryavashti-zvezdichki-tekst', // 'https://textove.com/azis-mila-moya-angel-moy-tekst', // 'https://textove.com/azis-obicham-te-tekst', // 'https://textove.com/azis-salzi-tekst', // 'https://textove.com/azis-nyakoy-den-tekst', // 'https://textove.com/azis-mma-tekst', // 'https://textove.com/azis-bivshi-tekst', // 'https://textove.com/azis-boli-tekst', // 'https://textove.com/azis-vseki-pat-tekst', // 'https://textove.com/azis-evala-tekst', // 'https://textove.com/azis-kazhi-chestno-tekst', // 'https://textove.com/alisiya-na-ti-mi-govori-tekst', // 'https://textove.com/alisiya-iliyan-nito-duma-tekst', // 'https://textove.com/alisiya-toni-storaro-dobre-ti-beshe-tekst', // 'https://textove.com/alisiya-karamel-tekst', // 'https://textove.com/alisiya-ti-li-tekst', // 'https://textove.com/alisiya-iliyan-za-posledno-tekst', // 'https://textove.com/alisiya-imame-li-vrazka-tekst', // 'https://textove.com/alisiya-sablechi-me-tekst', // 'https://textove.com/alisiya-zapali-tekst', // 'https://textove.com/alisiya-vsichko-si-za-men-tekst', // 'https://textove.com/alisiya-dve-sartsa-tekst', // 'https://textove.com/alisiya-emrah-dusho-moya-tekst', // 'https://textove.com/alisiya-edva-li-te-boli-tekst', // 'https://textove.com/alisiya-toni-storaro-zlatoto-na-tati-tekst', // 'https://textove.com/alisiya-konstantin-liubov-li-e-tekst', // 'https://textove.com/alisiya-moy-tekst', // 'https://textove.com/desi-slava-i-na-vsichki-kato-tebe-tekst', // 'https://textove.com/desi-slava-konstantin-az-byah-tuk-tekst', // 'https://textove.com/desi-slava-dzhordan-angelite-plachat-tekst', // 'https://textove.com/desi-slava-zabravi-za-men-tekst', // 'https://textove.com/desi-slava-lazha-tekst', // 'https://textove.com/desi-slava-edna-nosht-tekst', // 'https://textove.com/desi-slava-ezi-tura-tekst', // 'https://textove.com/desi-slava-dyavolska-magiya-tekst', // 'https://textove.com/desi-slava-zhadni-za-liubov-tekst', // 'https://textove.com/desi-slava-zabranen-tekst', // 'https://textove.com/desi-slava-zavinagi-tekst', // 'https://textove.com/desi-slava-dzhordan-zlatoto-mi-tekst', // 'https://textove.com/desi-slava-kazhi-mi-1-tekst', // 'https://textove.com/desi-slava-mrasni-porachki-tekst', // 'https://textove.com/desi-slava-galin-neka-da-e-tayno-tekst', // 'https://textove.com/yanitsa-az-li-da-te-ucha-tekst', // 'https://textove.com/yanitsa-bebcho-sabudi-se-tekst', // 'https://textove.com/yanitsa-v-pet-mi-zvanni-tekst', // 'https://textove.com/yanitsa-vinovna-tekst', // 'https://textove.com/yanitsa-vsichko-chuzhdo-pozhelavash-tekst', // 'https://textove.com/yanitsa-varnah-ti-go-tekst', // 'https://textove.com/yanitsa-vartelezhkata-tekst', // 'https://textove.com/yanitsa-kristiana-glavnata-tekst', // 'https://textove.com/yanitsa-dvoyno-vliuben-tekst', // 'https://textove.com/yanitsa-izkushenie-tekst', // 'https://textove.com/yanitsa-koy-si-ti-tekst', // 'https://textove.com/yanitsa-dj-zhivko-miks-natiskay-tekst', // 'https://textove.com/yanitsa-ne-moga-da-spra-tekst', // 'https://textove.com/yanitsa-dj-zhivko-miks-neshto-yako-tekst', // 'https://textove.com/yanitsa-galin-nyama-da-me-kupish-tekst', // 'https://textove.com/yanitsa-nyama-kak-tekst', // 'https://textove.com/yanitsa-otmastitelka-tekst', // 'https://textove.com/yanitsa-galin-roklyata-ti-pada-tekst', // 'https://textove.com/yanitsa-fuklata-tekst', // 'https://textove.com/yanitsa-shampionka-tekst', // 'https://textove.com/galena-habibi-tekst', // 'https://textove.com/tsvetelina-yaneva-vsichko-tekst', // 'https://textove.com/aneliya-dah-tekst', // 'https://textove.com/emiliya-snezhanka-tekst', // 'https://textove.com/mariya-kaul-klavela-mariya-tekst', // 'https://textove.com/konstantin-obadi-mi-se-tekst', // 'https://textove.com/konstantin-cherna-roza-tekst', // 'https://textove.com/konstantin-emanuela-oshte-te-obicham-tekst', // 'https://textove.com/konstantin-kato-san-tekst', // 'https://textove.com/konstantin-dzhuliya-shte-me-nauchish-li-tekst', // 'https://textove.com/konstantin-nespodelena-liubov-tekst', // 'https://textove.com/konstantin-ti-si-samo-8-mi-klas-tekst', // 'https://textove.com/konstantin-mr-king-tekst', // 'https://textove.com/kali-konstantin-v-raya-tekst', // 'https://textove.com/konstantin-vizhdam-te-tekst', // 'https://textove.com/konstantin-varni-se-tekst', // 'https://textove.com/konstantin-greshnik-tekst', // 'https://textove.com/konstantin-edvam-me-navi-tekst', // 'https://textove.com/konstantin-edna-zhena-edna-liubov-tekst', // 'https://textove.com/konstantin-izlishen-tekst', // 'https://textove.com/konstantin-toni-storaro-koma-tekst', // 'https://textove.com/preslava-gorchivi-spomeni-tekst', // 'https://textove.com/preslava-dyavolsko-zhelanie-tekst', // 'https://textove.com/preslava-bezrazlichna-tekst', // 'https://textove.com/preslava-obicham-te-tekst', // 'https://textove.com/preslava-zaklevam-te-tekst', // 'https://textove.com/preslava-zavinagi-tvoya-tekst', // 'https://textove.com/preslava-amatyorka-tekst', // 'https://textove.com/preslava-vsichko-svarshi-tekst', // 'https://textove.com/gloriya-stefan-mitrov-toni-dacheva-preslava-tsvetelina-yaneva-mariyana-dve-ochi-razplakani-tekst', // 'https://textove.com/preslava-zhenite-sled-men-tekst', // 'https://textove.com/galin-preslava-kapitana-kris-za-da-imam-teb-tekst', // 'https://textove.com/preslava-iztreznyavash-li-tekst', // 'https://textove.com/preslava-kak-ti-stoi-tekst', // 'https://textove.com/preslava-kogato-samne-tekst', // 'https://textove.com/preslava-kato-za-final-tekst', // 'https://textove.com/preslava-lazha-e-tekst', // 'https://textove.com/preslava-moeto-slabo-myasto-tekst', // 'https://textove.com/preslava-ne-se-iztrivash-tekst', // 'https://textove.com/preslava-novata-ti-tekst', // 'https://textove.com/preslava-obratno-v-igrata-tekst', // 'https://textove.com/preslava-pishi-go-neuspeshno-tekst', // 'https://textove.com/preslava-rezhim-neprilichna-tekst', // 'https://textove.com/emanuela-vinovna-tekst', // 'https://textove.com/emiliya-emanuela-vse-edno-mi-e-tekst', // 'https://textove.com/emanuela-notarialno-zaveren-tekst', // 'https://textove.com/emanuela-nishto-mazhko-tekst', // 'https://textove.com/emanuela-prazni-dumi-tekst', // 'https://textove.com/emanuela-gleday-me-na-snimka-tekst', // 'https://textove.com/emanuela-are-darpay-tekst', // 'https://textove.com/emanuela-bez-chuvstva-tekst', // 'https://textove.com/emanuela-vinovna-1-tekst', // 'https://textove.com/emanuela-da-si-plashtal-tekst', // 'https://textove.com/emanuela-krayna-myarka-tekst', // 'https://textove.com/dzhordan-emanuela-kupih-ti-sartse-tekst', // 'https://textove.com/konstantin-emanuela-ne-me-zasluzhavash-tekst', // 'https://textove.com/emanuela-otzad-mini-tekst', // 'https://textove.com/emanuela-pozhelavam-ti-tekst', // 'https://textove.com/emanuela-pochti-perfekten-tekst', // 'https://textove.com/emanuela-predatel-tekst', // 'https://textove.com/emanuela-skapoto-se-plashta-tekst', // 'https://textove.com/galin-emanuela-5-6-7-8-tekst', // 'https://textove.com/galin-megusta-tekst', // 'https://textove.com/galin-lidiya-nyama-da-mi-mine-tekst', // 'https://textove.com/galin-kak-si-kazhi-tekst', // 'https://textove.com/galin-preslava-tsarya-na-kupona-tekst', // 'https://textove.com/galin-112-tekst', // 'https://textove.com/galin-vse-napred-tekst', // 'https://textove.com/malina-galin-grehove-tekst', // 'https://textove.com/galin-edin-na-broy-tekst', // 'https://textove.com/galin-ani-hoang-kristiana-mezhdu-nas-tekst', // 'https://textove.com/galin-momche-bez-sartse-tekst', // 'https://textove.com/azis-galin-na-egipet-faraona-tekst', // 'https://textove.com/galin-dzhena-s-mene-da-varvish-tekst', // 'https://textove.com/preslava-dzhena-tuk-zhena-mu-pazi-tekst', // 'https://textove.com/dzhena-yako-mi-e-tekst', // 'https://textove.com/dzhena-koya-tekst', // 'https://textove.com/dzhena-huligan-tekst', // 'https://textove.com/dzhena-da-ti-bada-korona-tekst', // 'https://textove.com/dzhena-diagnoza-ti-tekst', // 'https://textove.com/dzhena-zhena-bez-ime-tekst', // 'https://textove.com/dzhena-gorkoto-momiche-tekst', // 'https://textove.com/dzhena-drazni-me-pak-tekst', // 'https://textove.com/andrea-dzhena-piy-edno-ot-mene-tekst', // 'https://textove.com/tsvetelina-yaneva-denis-teofikov-greshka-beshe-tekst', // 'https://textove.com/toni-storaro-tsvetelina-yaneva-bez-teb-liubov-tekst', // 'https://textove.com/galena-tsvetelina-yaneva-marakesh-tekst', // 'https://textove.com/tsvetelina-yaneva-chestito-tekst', // 'https://textove.com/tsvetelina-yaneva-bolka-moya-tekst', // 'https://textove.com/tsvetelina-yaneva-da-te-byah-zaryazala-tekst', // 'https://textove.com/tsvetelina-yaneva-fiki-ne-me-ostavyay-tekst', // 'https://textove.com/tsvetelina-yaneva-vsichko-tekst', // 'https://textove.com/tsvetelina-yaneva-angelat-tekst', // 'https://textove.com/tsvetelina-yaneva-bolka-moya-tekst', // 'https://textove.com/tsvetelina-yaneva-broy-me-tekst', // 'https://textove.com/tsvetelina-yaneva-vidimo-izneveril-tekst', // 'https://textove.com/tsvetelina-yaneva-kazhi-mi-alo-tekst', // 'https://textove.com/tsvetelina-yaneva-milionerche-tekst', // 'https://textove.com/galena-moro-mou-bebeto-mi-tekst', // 'https://textove.com/toni-storaro-galena-shefkata-tekst', // 'https://textove.com/galena-fenomenalen-tekst', // 'https://textove.com/galena-mamauragan-tekst', // 'https://textove.com/galena-100-pati-tekst', // 'https://textove.com/galena-dj-yat-me-izdade-tekst', // 'https://textove.com/galena-zhivko-miks-havana-tropicana-tekst', // 'https://textove.com/galena-fiki-bozhe-prosti-tekst', // 'https://textove.com/desi-slava-galena-v-tvoite-ochi-tekst', // 'https://textove.com/galena-za-pari-tekst', // 'https://textove.com/galena-za-posledno-tekst', // 'https://textove.com/galena-fiki-koy-tekst', // 'https://textove.com/galena-na-dve-golemi-tekst', // 'https://textove.com/galena-panika-tekst', // 'https://textove.com/azis-galena-tsvetelina-yaneva-pey-sartse-tekst', // 'https://textove.com/aneliya-zoopark-tekst', // 'https://textove.com/aneliya-dzhuliya-brammm-tekst', // 'https://textove.com/aneliya-vyarvay-tekst', // 'https://textove.com/aneliya-general-tekst', // 'https://textove.com/aneliya-da-ti-vikna-li-taksi-tekst', // 'https://textove.com/aneliya-day-mi-oshte-tekst', // 'https://textove.com/aneliya-vanya-za-patrona-tekst', // 'https://textove.com/aneliya-zoopark-tekst', // 'https://textove.com/aneliya-igri-za-naprednali-tekst', // 'https://textove.com/aneliya-milo-moe-tekst', // ]; /**/ /* rap */ let urls = [ 'https://textove.com/apsurt-oslushay-se-tekst', 'https://textove.com/apsurt-chuk-chuk-tekst', 'https://textove.com/apsurt-ppp-tekst', 'https://textove.com/apsurt-mama-tekst', 'https://textove.com/apsurt-piyani-tekst', 'https://textove.com/apsurt-moreto-tekst', 'https://textove.com/apsurt-kolega-1-tekst', 'https://textove.com/apsurt-satira-tekst', 'https://textove.com/apsurt-skit-1-tekst', 'https://textove.com/apsurt-gangsteri-tekst', 'https://textove.com/apsurt-psihopat-tekst', 'https://textove.com/apsurt-zvezdata-tekst', 'https://textove.com/apsurt-ako-tekst', 'https://textove.com/apsurt-bozdugan-tekst', 'https://textove.com/apsurt-freestyle-tekst', 'https://textove.com/apsurt-nescafe-3-v-1-tekst', 'https://textove.com/apsurt-kolega-tekst', 'https://textove.com/apsurt-ole-skit-tekst', 'https://textove.com/apsurt-free-style-tekst', 'https://textove.com/apsurt-bela-zhiga-tekst', 'https://textove.com/apsurt-chekay-malko-tekst', 'https://textove.com/apsurt-vtora-tsedka-tekst', 'https://textove.com/apsurt-stiga-fira-tekst', 'https://textove.com/apsurt-tsutska-skit-tekst', 'https://textove.com/apsurt-tozi-tants-tekst', 'https://textove.com/apsurt-bay-huy-tekst', 'https://textove.com/apsurt-tsvyat-zelen-tekst', 'https://textove.com/apsurt-pop-folk-tekst', 'https://textove.com/apsurt-non-stop-tekst', 'https://textove.com/apsurt-nedelya-sutrinta-tekst', 'https://textove.com/apsurt-kalchi-kalki-tekst', 'https://textove.com/apsurt-sveteshti-zhiletki-tekst', 'https://textove.com/degradatsiya-apsurt-go-otnasya-tekst', 'https://textove.com/apsurt-i-dicho-doping-test-tekst', 'https://textove.com/apsurt-ne-pitay-zashto-tekst', 'https://textove.com/apsurt-zhena-ot-shaolin-tekst', 'https://textove.com/apsurt-obicham-mayka-ti-tekst', 'https://textove.com/apsurt-bez-vazpitanie-tsenzurirana-tekst', 'https://textove.com/apsurt-bez-vazpitanie-original-tekst', 'https://textove.com/apsurt-iskam-tvoyto-tyalo-tekst', 'https://textove.com/apsurt-i-ball-face-punta-tekst', 'https://textove.com/apsurt-zhenata-na-shefa-tekst', 'https://textove.com/apsurt-i-beloslava-i-tvoyta-mayka-sashto-tekst', 'https://textove.com/apsurt-i-vasil-naydenov-chekay-malko-tekst', 'https://textove.com/apsurt-dicho-seks-belo-i-treva-tekst', 'https://textove.com/d2-apsurt-dicho-doping-test-tekst', 'https://textove.com/apsurt-zdravo-drazh-ili-pusni-tekst', 'https://textove.com/apsurt-hvani-me-za-trabata-tekst', 'https://textove.com/apsurt-tri-v-edno-neochakvano-dobra-kombinatsiya-tekst', 'https://textove.com/apsurt-chekay-malko-remiks-na-rst-tekst', 'https://textove.com/apsurt-vtora-tsedka-reklamata-na-nescafe-3in1-tekst', 'https://textove.com/apsurt-mran-mran-tekst', 'https://textove.com/so-called-crew-morfin-tekst', 'https://textove.com/so-called-crew-nedey-tekst', 'https://textove.com/so-called-crew-tova-e-tekst', 'https://textove.com/zhlach-trotoari-tekst', 'https://textove.com/zhlach-pechal-tekst', 'https://textove.com/zhlach-prenositelyat-tekst', 'https://textove.com/zhlach-dozhivotna-tekst', 'https://textove.com/zhlach-final-freestyle-tekst', 'https://textove.com/zhlach-egotrip-tova-e-tekst', 'https://textove.com/zhlach-balgarskata-presa-tekst', 'https://textove.com/zhlach-yavkata-dlg-vgz-tekst', 'https://textove.com/zhlach-i-utre-e-den-tekst', 'https://textove.com/zhlach-rusty-balakariya-tekst', 'https://textove.com/zhlach-gena-nikoynemozhedatespasiottovakoetoiskash-tekst', 'https://textove.com/zhlach-kragovrat-freestyle-tekst', 'https://textove.com/zhlach-chalgariya-freestyle-tekst', 'https://textove.com/zhlach-gena-nemilost-tekst', 'https://textove.com/zhlach-gena-ubiy-tekst', 'https://textove.com/zhlach-gena-oko-tekst', 'https://textove.com/zhlach-gena-prestizh-tekst', 'https://textove.com/zhlach-gena-grigovor-otgore-tekst', 'https://textove.com/zhlach-bate-douen-mnogotochie-tekst', 'https://textove.com/zhlach-gena-grigovor-kraya-tekst', 'https://textove.com/zhlach-gena-grigovor-128-tekst', 'https://textove.com/zhlach-gena-sofiysko-gradsko-tekst', 'https://textove.com/fo-zhlach-madmatic-glavnite-gotvachi-tekst', 'https://textove.com/zhlach-gena-kliuchov-reshavasht-tekst', 'https://textove.com/zhlach-gena-grigorov-nikadesiti-tekst', 'https://textove.com/zhlach-bryat-che-gena-doma-tekst', 'https://textove.com/zhlach-chetiri-i-dvayse-za-nachalo-tekst', 'https://textove.com/zhlach-gena-dj-skill-nas-tekst', 'https://textove.com/atila-zhlach-yavkata-dlg-tr1ckmusic-ot-a-do-ya-tekst', 'https://textove.com/zhlach-canal-creatures-of-sofia-freestyle-tekst', 'https://textove.com/zhlach-gena-oko-tekst', 'https://textove.com/gena-grigovor-logo5-zal-tekst', 'https://textove.com/zhlach-gena-grigovor-128-tekst', 'https://textove.com/zhlach-gena-grigovor-kraya-tekst', 'https://textove.com/zhlach-gena-grigovor-otgore-tekst', 'https://textove.com/grigovor-gena-tldr-tekst', 'https://textove.com/jay-tr1ckmusic-grigovor-neshto-kato-sci-fi-tekst', 'https://textove.com/rusty-grigovor-ok-ok-tekst', 'https://textove.com/bate-sasho-egn-tekst', 'https://textove.com/bate-sasho-satanas-bate-pesho-graka-karma-3-tekst', 'https://textove.com/bate-sasho-bate-pesho-camorata-bermudskiyat-triagalnik-tekst', 'https://textove.com/bate-sasho-bate-pesho-tsitata-proshtavam-vi-tekst', 'https://textove.com/bate-sasho-nogo-tekst', 'https://textove.com/bate-sasho-karma-4-tekst', 'https://textove.com/bate-sasho-tiho-tekst', 'https://textove.com/bate-pesho-salzite-tekst', 'https://textove.com/bate-pesho-someday-tekst', 'https://textove.com/bate-sasho-goreshto-tekst', 'https://textove.com/bate-sasho-tatuirana-tekst', 'https://textove.com/bate-sasho-lady-tekst', 'https://textove.com/bate-sasho-zashto-tekst', 'https://textove.com/bate-sasho-diafragma-tekst', 'https://textove.com/bate-pesho-byagam-tekst', 'https://textove.com/bate-sasho-medichi-tekst', 'https://textove.com/bate-douen-porno-tekst', 'https://textove.com/bate-sasho-tapi-pi-tekst', 'https://textove.com/hipodil-bate-goyko-tekst', 'https://textove.com/bate-sasho-pali-tekst', 'https://textove.com/bate-pesho-solo-tekst', 'https://textove.com/bate-sasho-galab-tekst', 'https://textove.com/bate-pesho-salzi-tekst', 'https://textove.com/bate-sasho-moeto-momiche-tekst', 'https://textove.com/bate-pesho-bebo-strast-tekst', 'https://textove.com/bate-sasho-bez-dusha-tekst', 'https://textove.com/bate-sasho-bmw-swag-tekst', 'https://textove.com/bate-sasho-za-teb-tekst', 'https://textove.com/bate-sasho-za-teb-tekst', 'https://textove.com/fars-flying-minds-tekst', 'https://textove.com/so-called-crew-vantka-fengi-vsichko-koeto-iskash-tekst', 'https://textove.com/rapara-kartela-vizhte-vsichki-tekst', 'https://textove.com/secta-mbt-bm-megz-tekst', 'https://textove.com/kapitana-iskah-samo-tebe-tekst', 'https://textove.com/krisko-2bona-gorilla-tekst', 'https://textove.com/angie-corine-kamikaze-tekst', 'https://textove.com/42-neka-zmayat-1-tekst', 'https://textove.com/vrgo-vrag-tekst', 'https://textove.com/dim4ou-mc-hammer-intro-tekst', 'https://textove.com/nadia-samo-teb-1-tekst', 'https://textove.com/kapitana-iskam-da-umra-tekst', 'https://textove.com/bobkata-sensei-grime-tekst', 'https://textove.com/secta-zona-na-komfort-tekst', 'https://textove.com/teodor-petrov-kontrol-tekst', 'https://textove.com/boro-parvi-mayko-mayko-tekst', 'https://textove.com/dax-my-last-words-tekst', 'https://textove.com/trf-bm-za-kvo-tekst', 'https://textove.com/mbt-bm-bb-pg-h5n1-tekst', 'https://textove.com/fyre-sofia-hills-tekst', 'https://textove.com/secta-prim-mamino-sinche-tekst', 'https://textove.com/choko-za-tebe-tekst', 'https://textove.com/deko-preplitam-tekst', 'https://textove.com/mishmash-izvini-me-tekst', 'https://textove.com/kapitana-mahlenetsa-pochvam-s-2-leva-tekst', 'https://textove.com/kapitana-fencheto-bozhidara-gaden-tekst', 'https://textove.com/vanya-g-yoana-star-sinya-krav-tekst', 'https://textove.com/vessou-sam-tekst', 'https://textove.com/fyre-vor-v-zakone-tekst', 'https://textove.com/dim4ou-trf-vrgo-prada-tekst', 'https://textove.com/sugar-djs-spik-deystvie-tekst', 'https://textove.com/marso-mbt-bm-chanel-tekst', 'https://textove.com/yorkaa-haosa-tekst', 'https://textove.com/yorkaa-op-ko-staa-tekst', 'https://textove.com/yorkaa-ot-men-tekst', 'https://textove.com/bobi-beattz-day-mi-tekst', 'https://textove.com/kapitana-bozhidara-obicham-te-tekst', 'https://textove.com/joker-flow-shtotoya-tekst', 'https://textove.com/lacho-skandau-vesi-boneva-netsafnali-rozi-tekst', 'https://textove.com/kapitana-bozhidara-ot-vreme-na-vreme-tekst', 'https://textove.com/kapitana-tragna-si-tekst', 'https://textove.com/bobi-beattz-boli-tekst', 'https://textove.com/zhlach-gena-grigorov-nikadesiti-tekst', 'https://textove.com/kapitana-nadezhda-nadezhda-za-deni-tekst', 'https://textove.com/kapitana-nadezhda-dueta-na-godinata-tekst', 'https://textove.com/kapitana-martvo-sazdanie-tekst', 'https://textove.com/bobi-beattz-neka-da-sa-pray-tekst', 'https://textove.com/bobi-beattz-karera-tekst', 'https://textove.com/skandau-rambo-tekst', 'https://textove.com/bobi-beattz-vlizam-arabskata-tekst', 'https://textove.com/100-kila-toxic-tekst', 'https://textove.com/100-kila-gaz-do-dupka-tekst', 'https://textove.com/wosh-mc-100-kila-kintite-v-sak-tekst', 'https://textove.com/rick-ross-100-kila-babuli-jabulah-tekst', 'https://textove.com/krisko-100-kila-mladi-bulki-tekst', 'https://textove.com/100-kila-100-gaydi-remix-tekst', 'https://textove.com/100-kila-3000-tekst', 'https://textove.com/rick-ross-100-kila-babuli-jabulah-tekst', 'https://textove.com/100-kila-balkan-funk-ne-legal-tekst', 'https://textove.com/100-kila-bom-bom-bom-tekst', 'https://textove.com/100-kila-freestyle-ii-tekst', 'https://textove.com/wosh-mc-vnimavay-tekst', 'https://textove.com/wosh-mc-moya-kur-tekst', 'https://textove.com/wosh-mc-spomeni-tekst', 'https://textove.com/wosh-mc-chovek-na-pokaz-tekst', 'https://textove.com/wosh-mc-raper-bate-tekst', 'https://textove.com/wosh-mc-100-kila-kintite-v-sak-tekst', 'https://textove.com/wosh-mc-momiche-tekst', 'https://textove.com/wosh-mc-fira-tekst', 'https://textove.com/wosh-mc-3-v-1-tekst', 'https://textove.com/wosh-mc-animal-tekst', 'https://textove.com/wosh-mc-better-than-you-tekst', 'https://textove.com/wosh-mc-blank-tekst', 'https://textove.com/wosh-mc-yoko-funkosmos-tekst', 'https://textove.com/wosh-mc-feel-i-got-the-benjamins-tekst', 'https://textove.com/wosh-mc-nice-apartment-tekst', 'https://textove.com/wosh-mc-yoko-nothing-tekst', 'https://textove.com/wosh-mc-on-fire-tekst', 'https://textove.com/wosh-mc-problems-tekst', 'https://textove.com/wosh-mc-we-smoke-tekst', 'https://textove.com/wosh-mc-vnimavay-tekst', 'https://textove.com/wosh-mc-vseki-den-tekst', 'https://textove.com/wosh-mc-gleday-pak-zvezdite-tekst', 'https://textove.com/wosh-mc-dve-taksita-tekst', 'https://textove.com/wosh-mc-zhalta-presa-tekst', 'https://textove.com/wosh-mc-za-moreto-e-taya-pesen-tekst', 'https://textove.com/wosh-mc-moya-kur-tekst', 'https://textove.com/wosh-mc-na-nebeto-tekst', 'https://textove.com/wosh-mc-obicham-ochite-ti-tekst', 'https://textove.com/wosh-mc-feel-yoko-pak-na-more-tekst', 'https://textove.com/wosh-mc-feel-prah-tekst', 'https://textove.com/wosh-mc-pri-loshiya-stil-tekst', 'https://textove.com/wosh-mc-tashatsi-tekst', 'https://textove.com/itso-hazarta-homelesz-imam-chovek-tekst', ]; async function test() { let promises = []; for (let i = 0; i < urls.length; i++) { promises.push(downloadMetaSomething(urls[i])); } await Promise.all(promises) .then( result => { let data = []; result.forEach( a => { data.push(a)}); console.log(JSON.stringify(data)); }); } test(); function downloadMetaSomething(url) { console.log(url); return new Promise( (resolve, reject) => { https.get(url, (resp) => { let data = ''; resp.on('data', (chunk) => { data += chunk; }); resp.on('end', () => { const dom = new JSDOM(data); const document = dom.window.document; let songName = document.getElementsByClassName('title_wrap')[0].children[2].innerHTML; // Get Authors const childNodes = document.getElementsByClassName('title_wrap')[0].children[1].children; let artists = []; for (let i = 0; i < childNodes.length; i++) { let artistId = childNodes[i].href; let artist = childNodes[i].children[0].innerHTML; artists.push( { artist, artistId } ); } let songId = url; resolve({ artists, songName, songId } ); }); }).on("error", (err) => { reject(err.message); }); }); } async function main() { for (let i = 0; i < urls.length; ) { let songRequestBuffer = []; for(let j = 0; j < maxParallelDownloads; j++) { if (i == urls.length) { continue; } songRequestBuffer.push(downloadAndParseSongLyrics(urls[i])); i++; } await Promise.all(songRequestBuffer) .then(result => { allSongLyrics.push(...result); if ( i == urls.length ) { console.log('Final result:', JSON.stringify(allSongLyrics)); } }) .catch(error => console.log(error)); } } // main(); // Private functions async function downloadAndParseSongLyrics(url) { return new Promise( (resolve, reject) => { // console.log('Donwloading: ' + url); https.get(url, (resp) => { let data = ''; resp.on('data', (chunk) => { data += chunk; }); resp.on('end', () => { const dom = new JSDOM(data); const document = dom.window.document; const childNodes = document.getElementById(mainContainerId).childNodes['1'].childNodes; const verses = cleanupSongVerses(childNodes); // Adds repeating lines addRepeatingVerses(verses); const chorus = extractChorus(verses); addRepeatingChorus(verses, chorus); // console.log('Song chorus: ', chorus); // console.log('Song lyrics: ', verses); resolve({ url: url, lyrics: verses.join('') }); }); }).on("error", (err) => { // console.log("Error: " + err.message); reject(err.message); }); }); } function cleanupSongVerses(elements) { let verses = []; elements.forEach( (obj, key) => { let line = obj.innerHTML.replace(/<br>/g, " "); line.trim(); verses.push(line); }); return verses; } function addRepeatingVerses(verses) { let versesToAdd = []; verses.forEach( verse => { if (verse.match(/припев/gi)) { return; } if (!verse.match(/\(x?х?Х?X?(\d)\)$/)) { return; } // Remove 1 since the number is the total times it is sang // not how many we need to add let repeatCount = verse.match(/\(x?х?Х?X?(\d)\)$/)[1] -1; for (let i = 0; i < repeatCount; i++) { versesToAdd.push(verse); } }); verses.push(...versesToAdd); return verses; } function extractChorus(verses) { const chorus = verses.filter( verse => { return verse.match(/припев/gi); }); // Theoretically, although unlikely the chorus may be both anotated and pasted multiple times return chorus[0]; } function addRepeatingChorus(verses, chorus) { re = /\([xхХX]\d\)$/g; let match; let chorusRepeatCount = 0; verses.forEach( verse => { if (verse.match(/припев:$/i)) { chorusRepeatCount++; } else { matches = re.exec(verse); if(!matches) { return; } matches.forEach( (match) => { if(!match) { return; } let timesRepeated = verse.match(/\([xхХX](\d)\)$/)[1]; chorusRepeatCount += parseInt(timesRepeated); }); } }); // console.log('REPEATING CHORUS COUNT: ', chorusRepeatCount); while( chorusRepeatCount > 0) { chorusRepeatCount--; verses.push(chorus); } return verses; } <file_sep>/machine_learning/bag_of_words.py import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression from sklearn import svm def load_and_parse_data(): chalga_lyrics = pd.read_json('a.json') rap_lyrics = pd.read_json('b.json') chalga_lyrics["type"] = 0 rap_lyrics["type"] = 1 data = pd.concat([chalga_lyrics, rap_lyrics]) data = data.sample(frac=1) print(data.head()) return data def train_and_test_model(data): vectorizer = CountVectorizer() data_bow = vectorizer.fit_transform(data["lyrics"]) print(vectorizer.get_feature_names()) return KK = [10, 100, 200, 300, 350] for K in KK: data_bow_train = data_bow[:K] data_target_train = data[:K] data_bow_test = data_bow[K:] data_target_test = data[K:] # Logistic print('Logistic regression') clf = LogisticRegression(random_state=0).fit(data_bow_train, data_target_train["type"]) print(clf.score(data_bow_test, data_target_test["type"])) #SVM print('Support Vector Machines') clf = svm.SVC() clf.fit(data_bow_train, data_target_train["type"]) print(clf.score(data_bow_test, data_target_test["type"])) data = load_and_parse_data() train_and_test_model(data) <file_sep>/machine_learning/__main__.py import gensim import json import pandas as pd import numpy as np from gensim.models.doc2vec import Doc2Vec, TaggedDocument import matplotlib.pyplot as plt from sklearn import manifold from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report from sklearn import svm def tagdocs(row): return TaggedDocument(row['lyrics'].split(" "), tags=[row['rownum']]) def docvecs(row): return model.infer_vector(row['lyrics'].split(" ")) data = pd.read_json('a.json') data['type'] = 0 data1 = pd.read_json('b.json') data1['type'] = 1 data = pd.concat([data, data1]) data["rownum"] = data.index data["taggeddoc"] = data.apply( tagdocs, axis=1) data = data.sample(frac=1) data_train = data[0:300] data_test = data[300:] # print(data) # print(data_train.head(3)) # print(data_train["taggeddoc"].tolist()) # model = Doc2Vec(data_train["taggeddoc"].tolist(), vector_size=100, window=2, min_count=1, workers=4) # model.save('chalga_ili_rap.model') model = Doc2Vec.load('chalga_ili_rap.model') #vector = model.infer_vector('любов ли е '.split(' ')) # print(vector) data_train["docvecs"] = data_train.apply( docvecs, axis=1) data_test["docvecs"] = data_test.apply( docvecs, axis=1) print(data_train["docvecs"].head(3)) # Logistic regression clf_logreg = LogisticRegression(random_state=0).fit(data_train["docvecs"].tolist(), data_train['type']) # SVM clf = svm.SVC() clf.fit(data_train["docvecs"].tolist(), data_train['type']) data_test['y_pred'] = clf.predict(data_test["docvecs"].tolist()) print('Support vectors') print(classification_report(data_test['type'], data_test['y_pred'])) print('Logistic regression') data_test['y_pred'] = clf_logreg.predict(data_test["docvecs"].tolist()) print(classification_report(data_test['type'], data_test['y_pred'])) # data_test.to_csv('result.csv') <file_sep>/semtech/main.py import json import urllib.request import urllib.parse import csv """ Note: the dataset should be present. If for some reason it isn't you can run download_dataset to recreate it. Since it will be piped to STDOUT you should pipe it to a file Note2: there is no error handling, good luck """ def download_dataset(): songs = [] for i in range(1, 8): url = 'https://api.discogs.com/labels/207112/releases?page=' + str(i) + '&per_page=100' f = urllib.request.urlopen(url) json_resp = f.read().decode('utf-8') data = json.loads(json_resp) for i in data["releases"]: # print(i["artist"]) songs.append(i) print(json.dumps(songs)) def parse_dataset(filename): parsed_songs = [] with open(filename) as json_file: data = json.load(json_file) print(len(data)) wr = csv.writer(open('final.csv', 'w', encoding="utf-8"), quoting=csv.QUOTE_ALL) wr.writerow(('artist', 'title', 'year', 'label', 'genre')) for i in data: # song = {"artist": i["artist"], "title": i["title"], "year": i["year"]} song = (i["artist"], i["title"], i["year"], 'planeta', 'pop-folk') wr.writerow(song) def download_album_dataset(): albums = [ { "url" : 'https://api.discogs.com/releases/12192823', "artist": "NDOE", "year": 2018, "album_name": "Хиляди Белези"}, { "url" : 'https://api.discogs.com/releases/12192668', "artist": "So Called Crew", "year": 2018, "album_name" : "Вода и Вино" }, { "url" : 'https://api.discogs.com/releases/7641358', "artist" : "100 Кила", "year" : 2013, "album_name" : "Zla10" }, { "url" : 'https://api.discogs.com/releases/7863031', "artist" : "Krisko", "year" : 2012, "album_name" : "Krisko Beats EP" }, # { "url" : 'https://api.discogs.com/releases/13733336', "artist" : "<NAME>", "year" : 2019, "album_name" : "Неправилен рап" } -- Needs aproval as of now, can't download ] album_songs = [] for album in albums: album_url = album["url"] f = urllib.request.urlopen(album_url) json_resp = f.read().decode('utf-8') data = json.loads(json_resp) for i in (data["videos"] + data["tracklist"]): i["artist"] = album["artist"] i["year"] = album["year"] i["album_name"] = album["album_name"] album_songs.append(i) print(json.dumps(album_songs)) def parse_album_dataset(filename): parsed_songs = [] with open(filename, encoding="utf-8") as json_file: data = json.load(json_file) print(len(data)) wr = csv.writer(open('final_album.csv', 'w'), quoting=csv.QUOTE_ALL) wr.writerow(('artist', 'album_name', 'title', 'year', 'uri', 'description', 'duration', 'label', 'genre')) for i in data: if not i.get('uri'): i['uri'] = '' if not i.get('description'): i['description'] = '' song = (i['artist'], i['album_name'], i['title'], i['year'], i['uri'], i['description'], i['duration'], 'facing the sun', 'hip-nop') wr.writerow(song) # parse_dataset('all_songs.json') parse_album_dataset('all_album_songs.json') # download_album_dataset()
fac138da3bb088708f1ef39c5b0fcaab40e453d9
[ "JavaScript", "Python" ]
4
JavaScript
stanimirovv/chalga-ili-rap
a18079f0c128185429770de48872645707ab0f05
3e8edb348021d3b033919bdda28b51944928a87f
refs/heads/master
<file_sep>all: g++ accessSim.cpp -o accessSim clean: rm accessSim <file_sep>#include <iostream> #include <cmath> #include <climits> using namespace std; typedef struct Cache_Data { bool empty; unsigned long long timeStamp; long long tag; Cache_Data() : empty(true), timeStamp(0), tag(0) {} } Cache_Data; class Cache_Template { private: int associativity; int indexBit; int blockBit; bool isLog; int hitCount; int missCount; unsigned long long currTime; Cache_Data** content; public: Cache_Template(int, int, int); ~Cache_Template(); bool Access(long long); void StartLog() {isLog = true;} void ShowStatistics(); }; int main(int argc, char *argv[]) { if (argc != 7) { cout << "./accessSim <Way> <Index bits> <Block bits> <Stride> <Size> <Iteration>" << endl; exit(1); } else { long iteration; long long currentAddress; int way, iBit, bBit, stride, size; way = atoi(argv[1]); iBit = atoi(argv[2]); bBit = atoi(argv[3]); Cache_Template cache(way, iBit, bBit); stride = atoi(argv[4]); size = atoi(argv[5]); iteration = atol(argv[6]); currentAddress = 0; // calculate address for (int i = 0 ; i < size ; i ++) { cache.Access(currentAddress); currentAddress += stride * 8; } currentAddress = 0; cache.StartLog(); for (long i = 0 ; i < iteration ; i ++) { cache.Access(currentAddress); currentAddress += stride * 8; if ((i % size) == (size - 1)) currentAddress = 0; } cache.ShowStatistics(); } } Cache_Template::Cache_Template(int ass, int iBit, int bBit) : isLog(false), hitCount(0), missCount(0), associativity(ass), indexBit(iBit), blockBit(bBit), currTime(0) { content = new Cache_Data*[associativity]; for (int i = 0 ; i < associativity ; i ++) { content[i] = new Cache_Data[1 << indexBit]; } } Cache_Template::~Cache_Template() { for (int i = 0 ; i < associativity ; i ++) { delete [] content[i]; } delete [] content; } // return TRUE for hit, FALSE for miss bool Cache_Template::Access(long long address) { int idx = (address >> blockBit) & ((1 << indexBit) - 1); long long tag = address >> (blockBit + indexBit); int targetWay; unsigned long long minTimeStamp = ULLONG_MAX; int minWay = -1; for (targetWay = 0 ; targetWay < associativity ; targetWay ++) { if ((!content[targetWay][idx].empty) && (content[targetWay][idx].tag == tag)) break; } // hit if (targetWay != associativity) { content[targetWay][idx].timeStamp = (currTime++); if (isLog) hitCount++; return true; } // miss for (targetWay = 0 ; targetWay < associativity ; targetWay ++) { if (content[targetWay][idx].empty) { content[targetWay][idx].empty = false; content[targetWay][idx].tag = tag; content[targetWay][idx].timeStamp = (currTime++); if (isLog) missCount++; return false; } else // find victim { if (content[targetWay][idx].timeStamp < minTimeStamp) { minTimeStamp = content[targetWay][idx].timeStamp; minWay = targetWay; } } } // TODO: write back? content[minWay][idx].tag = tag; content[minWay][idx].timeStamp = (currTime++); if (isLog) missCount++; return false; } void Cache_Template::ShowStatistics() { cout << "==========================================" << endl; cout << "\tTotal access: " << missCount + hitCount << endl; cout << "\t\thit: " << hitCount << endl; cout << "\t\tmiss: " << missCount << endl; cout << "\t\tmiss rate: " << (missCount / double(missCount + hitCount)) * 100 << " %" << endl; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <nvml.h> #include <sys/time.h> #define MAX_FILE_LEN 200 typedef struct GlobalCtrl { int intervalTime; int totalTime; int cudaDeviceNumber; char outputFile[MAX_FILE_LEN]; GlobalCtrl(): cudaDeviceNumber(0), intervalTime(200), totalTime(10) {sprintf(outputFile, "PowerUsageOutput.log");} } GlobalCtrl; bool CommandParser(int argc, char *argv[], GlobalCtrl *ctrl) { int cmd; while(1) { cmd = getopt(argc, argv, "t:o:T:D:"); if (cmd == -1) break; switch (cmd) { case 'D': ctrl->cudaDeviceNumber = atoi(optarg); break; case 't': ctrl->intervalTime = atoi(optarg); break; case 'T': ctrl->totalTime = atoi(optarg); break; case 'o': printf("Output file: %s\n", optarg); memset(ctrl->outputFile, 0, MAX_FILE_LEN); sprintf(ctrl->outputFile, "%s", optarg); break; default: printf("Error: Unknown argument: %s\n", optarg); return false; break; } } return true; } inline void CheckNVMLError(nvmlReturn_t error, char *msg) { if (NVML_SUCCESS != error) { printf("Error: %s: %s\n", msg, nvmlErrorString(error)); free(msg); exit(1); } free(msg); } int main(int argc, char *argv[]) { GlobalCtrl ctrl; if (!CommandParser(argc, argv, &ctrl)) exit(1); else { nvmlReturn_t error; nvmlDevice_t device; // Init { error = nvmlInit(); CheckNVMLError(error, strdup("Unable to initialize NVML")); } // Show all devices { unsigned int deviceNum, i; char name[NVML_DEVICE_NAME_BUFFER_SIZE]; nvmlDevice_t currDevice; error = nvmlDeviceGetCount(&deviceNum); CheckNVMLError(error, strdup("Unable to get device count")); printf("====== SUPPORT DEVICES ======\n"); for (i = 0 ; i < deviceNum ; i ++) { error = nvmlDeviceGetHandleByIndex(i, &currDevice); CheckNVMLError(error, strdup("Unable to get device handler")); error = nvmlDeviceGetName(currDevice, name, NVML_DEVICE_NAME_BUFFER_SIZE); CheckNVMLError(error, strdup("Unable to get device name")); printf("device %d: %s\n", i, name); } printf("=============================\n\n"); if (ctrl.cudaDeviceNumber >= deviceNum) { printf("Invalid device number\n"); exit(1); } printf("Select device %d\n", ctrl.cudaDeviceNumber); error = nvmlDeviceGetHandleByIndex(ctrl.cudaDeviceNumber, &device); } #if 0 // Check supported clock frequency { error = nvmlDeviceSetPersistenceMode(device, NVML_FEATURE_ENABLED); CheckNVMLError(error, strdup("Unable to change to persistence mode")); unsigned size = 10000; unsigned iterMemory, iterGraphic, memoryCount = size, graphicCount, memoryClock[size], graphicClock[size]; error = nvmlDeviceGetSupportedMemoryClocks(device, &memoryCount, memoryClock); CheckNVMLError(error, strdup("Unable to get supported memory clock")); for (iterMemory = 0 ; iterMemory < memoryCount ; iterMemory ++) { graphicCount = size; error = nvmlDeviceGetSupportedGraphicsClocks(device, memoryClock[iterMemory], &graphicCount, graphicClock); CheckNVMLError(error, strdup("Unable to get supported graphics clock")); for (iterGraphic = 0 ; iterGraphic < graphicCount ; iterGraphic ++) { printf("set memory clock: %5uMHz, graphics clock %5uMHz\n", memoryClock[iterMemory], graphicClock[iterGraphic]); error = nvmlDeviceSetApplicationsClocks(device, memoryClock[iterMemory], graphicClock[iterGraphic]); CheckNVMLError(error, strdup("Unable to set application clock")); usleep(1000); } } } #endif #if 1 // Power/Utilization polling { // Check power mode { nvmlEnableState_t powerMode = (nvmlEnableState_t)(0); error = nvmlDeviceGetPowerManagementMode(device, &powerMode); CheckNVMLError(error, strdup("Unable to get device power mode")); if (!powerMode) { printf("Error: Power management mode is not enable in current device.\n"); exit(1); } } // Start grab power/utilization info { int sampleInterval = ctrl.intervalTime * 1000; struct timeval startTime, curTime; unsigned long long start_utime, cur_utime; unsigned int curPower, curFreq, curTemp; nvmlPstates_t perfState; nvmlUtilization_t curUtil; FILE *fp = fopen(ctrl.outputFile, "w"); gettimeofday(&startTime, NULL); start_utime = startTime.tv_sec * 1000 + startTime.tv_usec / 1000; printf("start_time: %llu msec\n", start_utime); while (1) { gettimeofday(&curTime, NULL); cur_utime = curTime.tv_sec * 1000 + curTime.tv_usec / 1000; // Sample error = nvmlDeviceGetPowerUsage(device, &curPower); CheckNVMLError(error, strdup("Unable to read current power")); error = nvmlDeviceGetUtilizationRates(device, &curUtil); CheckNVMLError(error, strdup("Unable to read current utilization")); error = nvmlDeviceGetPerformanceState(device, &perfState); CheckNVMLError(error, strdup("Unable to get performance state")); error = nvmlDeviceGetClockInfo(device, NVML_CLOCK_SM, &curFreq); CheckNVMLError(error, strdup("Unable to get clock frequency")); error = nvmlDeviceGetTemperature(device, NVML_TEMPERATURE_GPU, &curTemp); CheckNVMLError(error, strdup("Unable to get GPU temperature")); fprintf(fp, "%llu %7u %3u %3u %3u %5u %3u\n", cur_utime, curPower, curUtil.gpu, curUtil.memory, perfState, curFreq, curTemp); // Grab end if ((cur_utime - start_utime) > (ctrl.totalTime * 1000)) break; usleep(sampleInterval); } printf("end_time: %llu msec\n", cur_utime); fclose(fp); } } #endif #if 0 // get the power information using nvmlDeviceGetSamples { nvmlValueType_t sampleType; unsigned int sampleCount; nvmlSample_t *sample; unsigned int idx; error = nvmlDeviceGetSamples(device, NVML_TOTAL_POWER_SAMPLES, start_utime * 1000, &sampleType, &sampleCount, NULL); //error = nvmlDeviceGetSamples(device, NVML_GPU_UTILIZATION_SAMPLES, start_utime * 1000, &sampleType, &sampleCount, NULL); //error = nvmlDeviceGetSamples(device, NVML_MEMORY_UTILIZATION_SAMPLES, start_utime * 1000, &sampleType, &sampleCount, NULL); CheckNVMLError(error, strdup("Unable to get maximum sample size")); printf("total sample count %u, type %d\n", sampleCount, sampleType); sample = (nvmlSample_t *) (malloc(sizeof(nvmlSample_t) * sampleCount)); error = nvmlDeviceGetSamples(device, NVML_TOTAL_POWER_SAMPLES, start_utime * 1000, &sampleType, &sampleCount, sample); //error = nvmlDeviceGetSamples(device, NVML_GPU_UTILIZATION_SAMPLES, start_utime * 1000, &sampleType, &sampleCount, sample); //error = nvmlDeviceGetSamples(device, NVML_MEMORY_UTILIZATION_SAMPLES, start_utime * 1000, &sampleType, &sampleCount, sample); CheckNVMLError(error, strdup("Unable to access sample buffer")); printf("total sample count %u, type %d\n", sampleCount, sampleType); for (idx = 0 ; idx < sampleCount ; idx ++) { printf("%llu (ns) %u\n", sample[idx].timeStamp, sample[idx].sampleValue.uiVal); } free (sample); } #endif } } <file_sep>include ../common/make.config all: g++ OpenCLInfo.cpp ${OPENCL_LIB} -o OpenCLInfo clean: rm OpenCLInfo <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include <sys/time.h> #include <time.h> #include <math.h> #include <limits.h> #include <float.h> #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif /* Macros */ #define CL_FILE_NAME "WorkGroupInterleavingTest.cl" #define PTX_FILE_NAME "WorkGroupInterleavingTest.ptx" #define COMPUTE_KERNEL_NAME "ComputeTask" #define MEMORY_KERNEL_NAME "MemoryTask" #define COMPUTE_DATA_SIZE 10 #define MEMORY_DATA_SIZE 128 #define INTERVAL 10 #define POWER_LOG_FILE_LEN 200 #define CHECK_CL_ERROR(error) \ do \ { \ if ((error)) \ { \ fprintf(stderr, "OpenCL API error %d, in %s:%d, function '%s'\n", (error), __FILE__, __LINE__, __FUNCTION__); \ exit(1); \ } \ } while(0) enum ExecutionMode { COMPUTE_ONLY = 0, MEMORY_ONLY, ALL }; /* Control struct */ struct OpenCL_Ctrl { int platform_id; int device_id; int global_size; int local_size; ExecutionMode executionMode; int computeIteration; int computeDataSize; int memoryDataSize; int memoryIteration; int interval; char powerFile[POWER_LOG_FILE_LEN]; OpenCL_Ctrl() : platform_id(0), device_id(0), global_size(1024), local_size(32), computeIteration(1000), memoryIteration(1000), executionMode(ALL), interval(INTERVAL) { sprintf(powerFile, "KernelExecution.log"); } } g_opencl_ctrl; void PrintTimingInfo(FILE* fptr) { struct timeval current; unsigned long long curr_time; gettimeofday(&current, NULL); curr_time = current.tv_sec * 1000 + current.tv_usec / 1000; fprintf(fptr, "%llu\n", curr_time); } void CommandParser(int argc, char *argv[]) { char* short_options = strdup("p:d:g:l:o:M:c:m:"); struct option long_options[] = { {"platformID", required_argument, NULL, 'p'}, {"deviceID", required_argument, NULL, 'd'}, {"globalSize", required_argument, NULL, 'g'}, {"localSize", required_argument, NULL, 'l'}, {"executeMode", required_argument, NULL, 'M'}, {"computeIteration", required_argument, NULL, 'c'}, {"memoryIteration", required_argument, NULL, 'm'}, {"powerLogFile", required_argument, NULL, 'o'}, /* option end */ {0, 0, 0, 0} }; int cmd; int optionIdx; while(1) { cmd = getopt_long(argc, argv, short_options, long_options, &optionIdx); /* finish parsing */ if (cmd == -1) break; switch (cmd) { case 'o': sprintf(g_opencl_ctrl.powerFile, "%s", optarg); break; case 'g': g_opencl_ctrl.global_size = atoi(optarg); break; case 'l': g_opencl_ctrl.local_size = atoi(optarg); break; case 'p': g_opencl_ctrl.platform_id = atoi(optarg); break; case 'd': g_opencl_ctrl.device_id = atoi(optarg); break; case 'M': g_opencl_ctrl.executionMode = (ExecutionMode)atoi(optarg); break; case 'c': g_opencl_ctrl.computeIteration = atoi(optarg); break; case 'm': g_opencl_ctrl.memoryIteration = atoi(optarg); break; case '?': fprintf(stderr, "Unknown option -%c\n", optopt); break; /* should not be here */ default: break; } } g_opencl_ctrl.computeDataSize = COMPUTE_DATA_SIZE * g_opencl_ctrl.global_size; g_opencl_ctrl.memoryDataSize = MEMORY_DATA_SIZE * g_opencl_ctrl.global_size; free (short_options); } void GetPlatformAndDevice(cl_platform_id & target_platform, cl_device_id & target_device) { cl_platform_id* platforms; cl_device_id* devices; cl_uint count; cl_int error; size_t length; char *queryString; /* Find platform */ error = clGetPlatformIDs(0, NULL, &count); CHECK_CL_ERROR(error); platforms = (cl_platform_id *)malloc(sizeof(cl_platform_id) * count); clGetPlatformIDs(count, platforms, NULL); if (g_opencl_ctrl.platform_id >= count) {fprintf(stderr, "Error: Cannot find selected platform\n"); exit(1);} target_platform = platforms[g_opencl_ctrl.platform_id]; /* Find device */ error = clGetDeviceIDs(target_platform, CL_DEVICE_TYPE_ALL, 0, NULL, &count); CHECK_CL_ERROR(error); devices = (cl_device_id *)malloc(sizeof(cl_device_id) * count); clGetDeviceIDs(target_platform, CL_DEVICE_TYPE_ALL, count, devices, NULL); if (g_opencl_ctrl.device_id >= count) {fprintf(stderr, "Error: Cannot find selected device\n"); exit(1);} target_device = devices[g_opencl_ctrl.device_id]; /* Get device name */ error = clGetDeviceInfo(target_device, CL_DEVICE_NAME, 0, NULL, &length); CHECK_CL_ERROR(error); queryString = (char *)malloc(sizeof(char) * length); clGetDeviceInfo(target_device, CL_DEVICE_NAME, length, queryString, NULL); fprintf(stderr, "Device selected: '%s'\n", queryString); { cl_uint vectorSize; error = clGetDeviceInfo(target_device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR, sizeof(vectorSize), &vectorSize, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "Preferred char vector width : %u\n", vectorSize); error = clGetDeviceInfo(target_device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, sizeof(vectorSize), &vectorSize, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "Preferred int vector width : %u\n", vectorSize); error = clGetDeviceInfo(target_device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, sizeof(vectorSize), &vectorSize, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "Preferred float vector width : %u\n", vectorSize); error = clGetDeviceInfo(target_device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE, sizeof(vectorSize), &vectorSize, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "Preferred double vector width : %u\n", vectorSize); } /* Free the space */ free(platforms); free(devices); free(queryString); } void CreateAndBuildProgram(cl_program &target_program, cl_context context, cl_device_id device, char *fileName) { FILE *fptr; size_t programSize; char *programSource; cl_int error, binaryError; fptr = fopen(fileName, "r"); if (fptr == NULL) { fprintf(stderr, "No such file: '%s'\n", fileName); exit(1); } /* Read program source */ fseek(fptr, 0, SEEK_END); programSize = ftell(fptr); rewind(fptr); programSource = (char *)malloc(sizeof(char) * (programSize + 1)); programSource[programSize] = '\0'; fread(programSource, sizeof(unsigned char), programSize, fptr); fclose(fptr); /* Create and build cl_program object */ target_program = clCreateProgramWithSource(context, 1, (const char **)(&programSource), &programSize, &error); CHECK_CL_ERROR(error); free(programSource); error = clBuildProgram(target_program, 1, &device, "-D COMPUTE_DATA_SIZE=10", NULL, NULL); if (error < 0) { size_t logSize; char *programBuildLog; error = clGetProgramBuildInfo(target_program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize); CHECK_CL_ERROR(error); programBuildLog = (char *)malloc(sizeof(char) * (logSize + 1)); error = clGetProgramBuildInfo(target_program, device, CL_PROGRAM_BUILD_LOG, logSize + 1, programBuildLog, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "%s\n", programBuildLog); free(programBuildLog); exit(1); } #if 0 { size_t binarySize; error = clGetProgramInfo(target_program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t), &binarySize, NULL); CHECK_CL_ERROR(error); unsigned char *binary = (unsigned char *) malloc(sizeof(unsigned char) * binarySize); error = clGetProgramInfo(target_program, CL_PROGRAM_BINARIES, binarySize, &binary, NULL); CHECK_CL_ERROR(error); FILE *fptr = fopen(PTX_FILE_NAME, "w"); fprintf(fptr, "%s", binary); fclose(fptr); } #endif free(fileName); } void ComputeDataCreation(void* &computeData) { computeData = malloc(g_opencl_ctrl.computeDataSize * sizeof(int)); { int *tmp; tmp = (int *)computeData; for (int i = 0 ; i < COMPUTE_DATA_SIZE * g_opencl_ctrl.global_size ; i ++) { tmp[i] = (rand() % INT_MAX); tmp[i] += (tmp[i] % 2) + 1; } } } void MemoryDataCreation(void* &memoryData, cl_mem kernelBuffer) { srand(time(NULL)); memoryData = malloc(g_opencl_ctrl.memoryDataSize * sizeof(cl_ulong)); { cl_ulong *tmp, *kernel; tmp = (cl_ulong *)memoryData; kernel = (cl_ulong *)kernelBuffer; for (int i = 0 ; i < g_opencl_ctrl.global_size ; i ++) { tmp[(MEMORY_DATA_SIZE - 1) * g_opencl_ctrl.global_size + i] = kernel[i]; } for (int i = MEMORY_DATA_SIZE - 2 ; i >= 0 ; i -- ) { for (int j = 0 ; j < g_opencl_ctrl.global_size ; j ++) { tmp[i * g_opencl_ctrl.global_size + j] = tmp[(i+1) * g_opencl_ctrl.global_size + j]; } } } } int main(int argc, char *argv[]) { cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue command_queue; cl_program program; cl_kernel memoryKernel, computeKernel; cl_mem memoryBuffer, computeBuffer; cl_int error; cl_event computeEvent, memoryEvent; cl_ulong queueTime, submitTime, startTime, endTime; size_t globalSize[1], localSize[1], warpSize; //FILE* fptr; void* memoryData = NULL; void* computeData = NULL; srand(time(NULL)); /* Parse options */ CommandParser(argc, argv); ComputeDataCreation(computeData); GetPlatformAndDevice(platform, device); //fptr = fopen(g_opencl_ctrl.powerFile, "w"); /* Create context */ context = clCreateContext(NULL, 1, &device, NULL, NULL, &error); CHECK_CL_ERROR(error); /* Create command queue */ command_queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE, &error); CHECK_CL_ERROR(error); /* Create program */ CreateAndBuildProgram(program, context, device, strdup(CL_FILE_NAME)); /* Create kernels */ computeKernel = clCreateKernel(program, COMPUTE_KERNEL_NAME, &error); CHECK_CL_ERROR(error); memoryKernel = clCreateKernel(program, MEMORY_KERNEL_NAME, &error); CHECK_CL_ERROR(error); /* Create buffers */ computeBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, g_opencl_ctrl.computeDataSize * sizeof(int), computeData, &error); CHECK_CL_ERROR(error); memoryBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, g_opencl_ctrl.memoryDataSize * sizeof(cl_ulong), NULL, &error); CHECK_CL_ERROR(error); //MemoryDataCreation(memoryData, memoryBuffer); /* Wrtie buffer */ //error = clEnqueueWriteBuffer(command_queue, memoryBuffer, CL_TRUE, 0, g_opencl_ctrl.memoryDataSize * sizeof(cl_ulong), memoryData, 0, NULL, NULL); //CHECK_CL_ERROR(error); /* Execute kernels */ error = clSetKernelArg(computeKernel, 0, sizeof(cl_mem), &computeBuffer); CHECK_CL_ERROR(error); error = clSetKernelArg(computeKernel, 1, sizeof(int), &g_opencl_ctrl.computeIteration); CHECK_CL_ERROR(error); error = clSetKernelArg(memoryKernel, 0, sizeof(cl_mem), &memoryBuffer); CHECK_CL_ERROR(error); error = clSetKernelArg(memoryKernel, 1, sizeof(int), &g_opencl_ctrl.memoryIteration); CHECK_CL_ERROR(error); //PrintTimingInfo(fptr); globalSize[0] = g_opencl_ctrl.global_size; localSize[0] = g_opencl_ctrl.local_size; if (g_opencl_ctrl.executionMode == ALL || g_opencl_ctrl.executionMode == COMPUTE_ONLY) { error = clEnqueueNDRangeKernel(command_queue, computeKernel, 1, NULL, globalSize, localSize, 0, NULL, &computeEvent); CHECK_CL_ERROR(error); } if (g_opencl_ctrl.executionMode == ALL || g_opencl_ctrl.executionMode == MEMORY_ONLY) { error = clEnqueueNDRangeKernel(command_queue, memoryKernel, 1, NULL, globalSize, localSize, 0, NULL, &memoryEvent); CHECK_CL_ERROR(error); } error = clFinish(command_queue); CHECK_CL_ERROR(error); //PrintTimingInfo(fptr); //fclose(fptr); /* Event profiling */ if (g_opencl_ctrl.executionMode == ALL || g_opencl_ctrl.executionMode == COMPUTE_ONLY) { error = clGetEventProfilingInfo(computeEvent, CL_PROFILING_COMMAND_QUEUED, sizeof(queueTime), &queueTime, NULL); CHECK_CL_ERROR(error); error = clGetEventProfilingInfo(computeEvent, CL_PROFILING_COMMAND_SUBMIT, sizeof(submitTime), &submitTime, NULL); CHECK_CL_ERROR(error); error = clGetEventProfilingInfo(computeEvent, CL_PROFILING_COMMAND_START, sizeof(startTime), &startTime, NULL); CHECK_CL_ERROR(error); error = clGetEventProfilingInfo(computeEvent, CL_PROFILING_COMMAND_END, sizeof(endTime), &endTime, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "compute queued @ %lu\n", queueTime); fprintf(stderr, "compute submit @ %lu\n", queueTime); fprintf(stderr, "compute start @ %lu\n", startTime); fprintf(stderr, "compute end @ %lu\n", endTime); fprintf(stderr, "compute duration %lu\n\n", endTime - startTime); clReleaseEvent(computeEvent); } if (g_opencl_ctrl.executionMode == ALL || g_opencl_ctrl.executionMode == MEMORY_ONLY) { error = clGetEventProfilingInfo(memoryEvent, CL_PROFILING_COMMAND_QUEUED, sizeof(queueTime), &queueTime, NULL); CHECK_CL_ERROR(error); error = clGetEventProfilingInfo(memoryEvent, CL_PROFILING_COMMAND_SUBMIT, sizeof(submitTime), &submitTime, NULL); CHECK_CL_ERROR(error); error = clGetEventProfilingInfo(memoryEvent, CL_PROFILING_COMMAND_START, sizeof(startTime), &startTime, NULL); CHECK_CL_ERROR(error); error = clGetEventProfilingInfo(memoryEvent, CL_PROFILING_COMMAND_END, sizeof(endTime), &endTime, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "memory queued @ %lu\n", queueTime); fprintf(stderr, "memory submit @ %lu\n", queueTime); fprintf(stderr, "memory start @ %lu\n", startTime); fprintf(stderr, "memory end @ %lu\n", endTime); fprintf(stderr, "memory duration %lu\n\n", endTime - startTime); clReleaseEvent(memoryEvent); } /* Read the output */ /* Release object */ clReleaseKernel(computeKernel); clReleaseKernel(memoryKernel); clReleaseMemObject(computeBuffer); clReleaseMemObject(memoryBuffer); clReleaseProgram(program); clReleaseCommandQueue(command_queue); clReleaseContext(context); free(computeData); free(memoryData); return 0; } <file_sep>CFLAGS=-g all: rapl_lib_shared rapl_lib_static PowerUsage_static #all: rapl_lib_shared PowerUsage rapl_lib_shared: gcc $(CFLAGS) -fpic -c msr.c cpuid.c rapl.c -lm gcc $(CFLAGS) -shared -o librapl.so msr.o cpuid.o rapl.o rapl_lib_static: gcc $(CFLAGS) -c msr.c cpuid.c rapl.c -lm ar rcs librapl.a msr.o cpuid.o rapl.o PowerUsage_static: gcc $(CFLAGS) PowerUsage.c -I. -L. -o PowerUsage ./librapl.a -lm PowerUsage: gcc $(CFLAGS) PowerUsage.c -I. -L. -lrapl -lm -o PowerUsage gprof: CFLAGS = -pg gprof: all ./PowerUsage -e 100 -d 60 >/dev/null 2>&1 gprof PowerUsage > PowerUsage.gprof rm -f gmon.out make clean clean: rm -f PowerUsage librapl.so librapl.a msr.o cpuid.o rapl.o <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include <sys/time.h> #include <time.h> #include <math.h> #include <limits.h> #include <float.h> #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif /* Macros */ #define DISPATCH_SIZE 32 //#define USE_CL_2_0_API #define CL_FILE_NAME "cacheHierarchyTest.cl" #define BINARY_FILE_NAME "cacheHierarchyTest.bin" #define KERNEL_1 "GeneratePattern" #define KERNEL_2 "Process" #define POWER_LOG_FILE_LEN 300 #define CHECK_CL_ERROR(error) \ do \ { \ if ((error)) \ { \ fprintf(stderr, "OpenCL API error %d, in %s:%d, function '%s'\n", (error), __FILE__, __LINE__, __FUNCTION__); \ exit(1); \ } \ } while(0) /* Control struct */ struct OpenCL_Ctrl { int platform_id; int device_id; long dataByte; long iteration; int size; int stride; int interval; long offset; int globalSize; int launcherSlice; int localSize; char powerFile[POWER_LOG_FILE_LEN]; OpenCL_Ctrl() : platform_id(0), device_id(0), size(1), stride(1), iteration(1), globalSize(1), localSize(1), offset(1), interval(1), launcherSlice(1) {sprintf(powerFile, "KernelExecution.log");} ~OpenCL_Ctrl() {} } g_opencl_ctrl; unsigned long long PrintTimingInfo(FILE* fptr) { struct timeval current; unsigned long long curr_time; gettimeofday(&current, NULL); curr_time = current.tv_sec * 1000 + current.tv_usec / 1000; fprintf(fptr, "%llu\n", curr_time); return (current.tv_sec * 1000000 + current.tv_usec); } void CommandParser(int argc, char *argv[]) { char* short_options = strdup("p:d:s:n:i:o:g:l:i:v:w:"); struct option long_options[] = { {"platformID", required_argument, NULL, 'p'}, {"deviceID", required_argument, NULL, 'd'}, {"iteration", required_argument, NULL, 'i'}, {"number", required_argument, NULL, 'n'}, {"stride", required_argument, NULL, 's'}, {"interval", required_argument, NULL, 'v'}, {"powerLogFile", required_argument, NULL, 'o'}, {"globalSize", required_argument, NULL, 'g'}, {"localSize", required_argument, NULL, 'l'}, {"launcherSlice", required_argument, NULL, 'w'}, /* option end */ {0, 0, 0, 0} }; int cmd; int optionIdx; while(1) { cmd = getopt_long(argc, argv, short_options, long_options, &optionIdx); /* finish parsing */ if (cmd == -1) break; switch (cmd) { case 'g': g_opencl_ctrl.globalSize = atoi(optarg); break; case 'l': g_opencl_ctrl.localSize = atoi(optarg); break; case 'o': sprintf(g_opencl_ctrl.powerFile, "%s", optarg); break; case 'w': g_opencl_ctrl.launcherSlice = atoi(optarg); break; case 'v': g_opencl_ctrl.interval = atoi(optarg); break; case 'n': g_opencl_ctrl.size = atoi(optarg); break; case 's': g_opencl_ctrl.stride = atoi(optarg); break; case 'i': g_opencl_ctrl.iteration = atol(optarg); break; case 'p': g_opencl_ctrl.platform_id = atoi(optarg); break; case 'd': g_opencl_ctrl.device_id = atoi(optarg); break; case '?': fprintf(stderr, "Unknown option -%c\n", optopt); break; /* should not be here */ default: break; } } g_opencl_ctrl.dataByte = sizeof(cl_ulong) * (long)(g_opencl_ctrl.stride) * (long)(g_opencl_ctrl.size) * (long)(g_opencl_ctrl.globalSize) / (long)(g_opencl_ctrl.localSize); g_opencl_ctrl.offset = (long)(g_opencl_ctrl.stride) * (long)(g_opencl_ctrl.size); fprintf(stderr, "Total buffer size: %ld\n", g_opencl_ctrl.dataByte); free (short_options); } void GetPlatformAndDevice(cl_platform_id & target_platform, cl_device_id & target_device) { cl_platform_id* platforms; cl_device_id* devices; cl_uint count; cl_int error; size_t length; char *queryString; /* Find platform */ error = clGetPlatformIDs(0, NULL, &count); CHECK_CL_ERROR(error); platforms = (cl_platform_id *)malloc(sizeof(cl_platform_id) * count); clGetPlatformIDs(count, platforms, NULL); if (g_opencl_ctrl.platform_id >= count) {fprintf(stderr, "Error: Cannot find selected platform\n"); exit(1);} target_platform = platforms[g_opencl_ctrl.platform_id]; /* Find device */ error = clGetDeviceIDs(target_platform, CL_DEVICE_TYPE_ALL, 0, NULL, &count); CHECK_CL_ERROR(error); devices = (cl_device_id *)malloc(sizeof(cl_device_id) * count); clGetDeviceIDs(target_platform, CL_DEVICE_TYPE_ALL, count, devices, NULL); if (g_opencl_ctrl.device_id >= count) {fprintf(stderr, "Error: Cannot find selected device\n"); exit(1);} target_device = devices[g_opencl_ctrl.device_id]; /* Get device name */ error = clGetDeviceInfo(target_device, CL_DEVICE_NAME, 0, NULL, &length); CHECK_CL_ERROR(error); queryString = (char *)malloc(sizeof(char) * length); error = clGetDeviceInfo(target_device, CL_DEVICE_NAME, length, queryString, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "Device selected: '%s'\n", queryString); #if 0 { cl_ulong global_cache_size; cl_device_mem_cache_type global_cache_type; cl_uint global_cache_line_size; cl_ulong global_memory_size; error = clGetDeviceInfo(target_device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(global_memory_size), &global_memory_size, NULL); CHECK_CL_ERROR(error); error = clGetDeviceInfo(target_device, CL_DEVICE_GLOBAL_MEM_CACHE_SIZE, sizeof(global_cache_size), &global_cache_size, NULL); CHECK_CL_ERROR(error); error = clGetDeviceInfo(target_device, CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE, sizeof(global_cache_line_size), &global_cache_line_size, NULL); CHECK_CL_ERROR(error); error = clGetDeviceInfo(target_device, CL_DEVICE_GLOBAL_MEM_CACHE_TYPE, sizeof(global_cache_type), &global_cache_type, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "Global memory size: %lu B\n", global_memory_size); fprintf(stderr, "Global memory cache size: %lu B\n", global_cache_size); fprintf(stderr, "Global memory cache line size: %u B\n", global_cache_line_size); fprintf(stderr, "Global memory cache type: "); if (global_cache_type == CL_READ_ONLY_CACHE) printf("Read Only\n"); else if (global_cache_type == CL_READ_WRITE_CACHE) printf("Read Write\n"); } #endif /* Free the space */ free(platforms); free(devices); free(queryString); } void CreateAndBuildProgram(cl_program &target_program, cl_context context, cl_device_id device, char *fileName) { FILE *fptr; size_t programSize; unsigned char *programSource; char option[150]; cl_int error, binaryError; fptr = fopen(fileName, "r"); if (fptr == NULL) { fprintf(stderr, "No such file: '%s'\n", fileName); exit(1); } /* Read program source */ fseek(fptr, 0, SEEK_END); programSize = ftell(fptr); rewind(fptr); programSource = (unsigned char *)malloc(sizeof(unsigned char) * (programSize + 1)); programSource[programSize] = '\0'; fread(programSource, sizeof(unsigned char), programSize, fptr); fclose(fptr); /* Create and build cl_program object */ target_program = clCreateProgramWithSource(context, 1, (const char **)(&programSource), &programSize, &error); CHECK_CL_ERROR(error); free(programSource); sprintf(option, "-cl-opt-disable -D DISPATCH_SIZE=%d -D SLICE=%d", DISPATCH_SIZE, g_opencl_ctrl.launcherSlice); error = clBuildProgram(target_program, 1, &device, option, NULL, NULL); if (error < 0) { size_t logSize; char *programBuildLog; error = clGetProgramBuildInfo(target_program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize); CHECK_CL_ERROR(error); programBuildLog = (char *)malloc(sizeof(char) * (logSize + 1)); error = clGetProgramBuildInfo(target_program, device, CL_PROGRAM_BUILD_LOG, logSize + 1, programBuildLog, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "%s\n", programBuildLog); free(programBuildLog); exit(1); } #if 0 { size_t binarySize; error = clGetProgramInfo(target_program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t), &binarySize, NULL); CHECK_CL_ERROR(error); unsigned char *binary = (unsigned char *) malloc(sizeof(unsigned char) * binarySize); error = clGetProgramInfo(target_program, CL_PROGRAM_BINARIES, binarySize, &binary, NULL); CHECK_CL_ERROR(error); FILE *fptr = fopen(BINARY_FILE_NAME, "w"); fprintf(fptr, "%s", binary); fclose(fptr); } #endif free(fileName); } void HostDataCreation(void* &data) { srand(time(NULL)); data = malloc(g_opencl_ctrl.dataByte); for (int i = 0 ; i < g_opencl_ctrl.size * g_opencl_ctrl.stride ; i ++) ((long *)(data))[i] = 0; } int main(int argc, char *argv[]) { cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue command_queue; cl_program program; cl_kernel kernel1, kernel2; cl_mem buffer; cl_int error; cl_event event; cl_ulong startTime, endTime; size_t globalSize[1], localSize[1], dispatchSize; unsigned long long start, end; FILE* fptr; void* hostData = NULL; /* Parse options */ CommandParser(argc, argv); HostDataCreation(hostData); GetPlatformAndDevice(platform, device); fptr = fopen(g_opencl_ctrl.powerFile, "a"); /* Create context */ context = clCreateContext(NULL, 1, &device, NULL, NULL, &error); CHECK_CL_ERROR(error); /* Create command queue */ #ifdef USE_CL_2_0_API { cl_queue_properties property[] = {CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0}; command_queue = clCreateCommandQueueWithProperties(context, device, property, &error); } #else { command_queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE, &error); } #endif CHECK_CL_ERROR(error); /* Create program */ CreateAndBuildProgram(program, context, device, strdup(CL_FILE_NAME)); /* Create kernels */ kernel1 = clCreateKernel(program, KERNEL_1, &error); CHECK_CL_ERROR(error); kernel2 = clCreateKernel(program, KERNEL_2, &error); CHECK_CL_ERROR(error); error = clGetKernelWorkGroupInfo(kernel1, device, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(size_t), &dispatchSize, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "Dispatch size = %lu\n", dispatchSize); /* Create buffers */ buffer = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, g_opencl_ctrl.dataByte, hostData, &error); CHECK_CL_ERROR(error); /* Execute kernels */ error = clSetKernelArg(kernel1, 0, sizeof(cl_mem), &buffer); CHECK_CL_ERROR(error); error = clSetKernelArg(kernel1, 1, sizeof(int), &g_opencl_ctrl.size); CHECK_CL_ERROR(error); error = clSetKernelArg(kernel1, 2, sizeof(int), &g_opencl_ctrl.stride); CHECK_CL_ERROR(error); error = clSetKernelArg(kernel1, 3, sizeof(int), &g_opencl_ctrl.interval); CHECK_CL_ERROR(error); error = clSetKernelArg(kernel2, 0, sizeof(cl_mem), &buffer); CHECK_CL_ERROR(error); error = clSetKernelArg(kernel2, 1, sizeof(long), &g_opencl_ctrl.iteration); CHECK_CL_ERROR(error); error = clSetKernelArg(kernel2, 2, sizeof(long), &g_opencl_ctrl.offset); CHECK_CL_ERROR(error); error = clSetKernelArg(kernel2, 3, sizeof(int), &g_opencl_ctrl.interval); CHECK_CL_ERROR(error); globalSize[0] = g_opencl_ctrl.globalSize; localSize[0] = g_opencl_ctrl.localSize; error = clEnqueueNDRangeKernel(command_queue, kernel1, 1, NULL, globalSize, localSize, 0, NULL, NULL); CHECK_CL_ERROR(error); error = clFinish(command_queue); CHECK_CL_ERROR(error); start = PrintTimingInfo(fptr); error = clEnqueueNDRangeKernel(command_queue, kernel2, 1, NULL, globalSize, localSize, 0, NULL, &event); CHECK_CL_ERROR(error); error = clFinish(command_queue); CHECK_CL_ERROR(error); end = PrintTimingInfo(fptr); fclose(fptr); error = clEnqueueReadBuffer(command_queue, buffer, CL_TRUE, 0, g_opencl_ctrl.dataByte, hostData, 0, NULL, NULL); CHECK_CL_ERROR(error); #if 0 long *currData; for (int i = 0 ; i < g_opencl_ctrl.globalSize/g_opencl_ctrl.localSize ; i ++) { currData = ((long *)(hostData)) + i * g_opencl_ctrl.stride * g_opencl_ctrl.size; for (int id = 0 ; id < g_opencl_ctrl.stride * g_opencl_ctrl.size ; id ++) printf("%lu ", ((long *)(currData))[id]); printf("\n\n"); } #endif /* Event profiling */ error = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(startTime), &startTime, NULL); CHECK_CL_ERROR(error); error = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(endTime), &endTime, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "\n['Process' execution time] %llu ns\n", (end - start) * 1000); fprintf(stdout, "%llu\n", (end - start) * 1000); /* Read the output */ /* Release object */ clReleaseKernel(kernel1); clReleaseKernel(kernel2); clReleaseMemObject(buffer); clReleaseEvent(event); clReleaseProgram(program); clReleaseCommandQueue(command_queue); clReleaseContext(context); free(hostData); return 0; } <file_sep>include ../../common/make.config all: g++ arith_utilization.cpp ${OPENCL_LIB} -o arith_utilization clean: rm arith_utilization <file_sep>include ../common/make.config all: gcc launch.cpp ${OPENCL_LIB} -o launch clean: rm launch <file_sep>#include <stdio.h> #include <stdlib.h> #include "kernelParser.h" extern int yyparse(); extern void initial(); extern FILE *yyin; extern PROGRAM* prog; int main(int argc, char *argv[]) { if(argc<2) { printf("Please select an input file\n"); exit(0); } FILE *fp=fopen(argv[1],"r"); if(!fp) { printf("couldn't open file for reading\n"); exit(0); } yyin=fp; initial(); yyparse(); fclose(fp); release(); //ReleaseParseResult(prog); } <file_sep>#include <iostream> using namespace std; int main(int argc, char* argv[]) { int blocks, line, stride, size; int currLoc; if (argc != 5) { cout << "./accessSim <Blocks> <Line size> <Stride> <Size>" << endl; } else { blocks = atoi(argv[1]); line = atoi(argv[2]); stride = atoi(argv[3]); size = atoi(argv[4]); } currLoc = 0; for (int i = 0 ; i < size ; i ++, currLoc += stride) { currLoc %= (blocks * line); for (int bIdx = 0; bIdx < (currLoc/line) ; bIdx ++) { for (int lIdx = 0; lIdx < line ; lIdx ++) cout << "_"; cout << " "; } for (int lIdx = 0; lIdx < (currLoc%line); lIdx ++) cout << "_"; cout << "o"; for (int lIdx = (currLoc%line)+1; lIdx < line; lIdx ++) cout << "_"; cout << " "; for (int bIdx = (currLoc/line) + 1; bIdx < blocks ; bIdx ++) { for (int lIdx = 0; lIdx < line ; lIdx ++) cout << "_"; cout << " "; } cout << endl; } } <file_sep>#ifndef __OPENCL_PARSER_H__ #define __OPENCL_PARSER_H__ /*========================================================================== DATA STRUCTURE DECLARATION ===============================================================*/ typedef struct DEP DEP; typedef struct Operation Operation; typedef struct STMT_List STMT_List; typedef struct FUNCTION FUNCTION; typedef struct PROGRAM PROGRAM; typedef struct Statement Statement; typedef struct OP_List OP_List; typedef struct Identifier Identifier; typedef struct ID_List ID_List; typedef struct Parameter Parameter; typedef struct Param_List Param_List; typedef struct Declarator Declarator; typedef struct Declaration Declaration; typedef enum OP_TYPE OP_TYPE; typedef enum OP_KIND OP_KIND; typedef enum STMT_TYPE STMT_TYPE; typedef enum DEP_TYPE DEP_TYPE; typedef struct SymbolTable SymbolTable; typedef struct SymbolTableEntry SymbolTableEntry; typedef struct SymbolTableLevel SymbolTableLevel; typedef struct TypeDescriptor TypeDescriptor; typedef struct StructMember StructMember; typedef struct StructDescriptor StructDescriptor; typedef struct StructDescriptorTable StructDescriptorTable; typedef enum SYMBOL_TYPE SYMBOL_TYPE; /*========================================================================== FUNCTION DECLARATION ===============================================================*/ void CreateSymbolTable(); void ReleaseSymbolTable(); void CreateSymbolTableLevel(); void ReleaseSymbolTableLevel(); void AddParamToSymbolTable(TypeDescriptor, char*, SYMBOL_TYPE); void AddIDListToSymbolTable(TypeDescriptor, ID_List*, SYMBOL_TYPE); TypeDescriptor FindSymbolInTable(char*, SYMBOL_TYPE); SymbolTableEntry* GetTableEntry(char*); void initial(); void MakeDependency(Operation*, Operation*, DEP_TYPE, unsigned long long int); PROGRAM* CreateProgram(FUNCTION*, FUNCTION*); void ReleaseOP(Operation*); Operation* CreateOP(OP_KIND); Operation* CreateOPWithDataHazard(OP_KIND, OP_List*, OP_List*); void GetStatementTypeName(Statement*, char*); void GetOperationDescriptor(Operation*, char*, char*); void ReleaseSTMTList(STMT_List*); void DebugSTMTList(STMT_List*, int); void DebugOPList(OP_List*); STMT_List* CreateSTMTList(Statement*); STMT_List* AddToSTMTList(STMT_List*, STMT_List*); void ReleaseSTMT(Statement*); Statement* CreateSTMT(void*, STMT_TYPE); void ReleaseOPList(OP_List*); OP_List* AddToOPList(OP_List*, OP_List*, Operation*); OP_List* CreateEmptyOPList(OP_List*, TypeDescriptor, SymbolTableEntry*); Declarator* CreateDeclarator(char*, Param_List*); Declarator* AddToDeclarator(Declarator*, Param_List*); char* GetNameInDeclarator(Declarator*); Declaration* AddDeclaration(Declaration*, Declaration*); Declaration* MakeDeclaration(ID_List*, OP_List*); Identifier* CreateIdentifier(char*, OP_List*); ID_List* CreateIDList(Identifier*); ID_List* AddToIDList(ID_List*, ID_List*); TypeDescriptor MixType(TypeDescriptor, TypeDescriptor); Parameter* CreateParameter(TypeDescriptor, char*); Param_List* CreateParamList(Parameter*); Param_List* AddToParamList(Param_List*, Param_List*); StructMember* CreateStructMember(TypeDescriptor, char*); StructDescriptor* AddToStructDescriptor(StructDescriptor*, StructMember*); void AddToStructDescriptorTable(StructDescriptor*, char*); StructDescriptor* FindInStructTable(char*); TypeDescriptor CreateTypeDescriptor(OP_TYPE, StructDescriptor*); StructDescriptor* CreateStructDescriptor(TypeDescriptor, ID_List*); StructDescriptor* MergeStructDescriptor(StructDescriptor*, StructDescriptor*); TypeDescriptor GetTypeInStructDescriptor(StructDescriptor*, char*); void ReleaseStructTable(); void ReleaseStructDescriptor(StructDescriptor*); SymbolTableEntry* CreateSymbolTableEntry(TypeDescriptor, char*, SYMBOL_TYPE, Operation*); SymbolTableEntry* GetStructMemberInSymbolEntry(SymbolTableEntry*, char*); /*========================================================================== GLOBAL VARIABLE DEFINITION ===============================================================*/ StructDescriptorTable* structTable; SymbolTable* symTable; PROGRAM* prog; /*========================================================================== DATA STRUCTURE DEFINITION ===============================================================*/ enum OP_TYPE { NONE_TYPE = 0, STRUCT_TYPE, UNION_TYPE, BOOL_TYPE = 0x1000, HALF_TYPE, VOID_TYPE, CHAR_TYPE, CHAR2_TYPE, CHAR4_TYPE, CHAR8_TYPE, CHAR16_TYPE, UCHAR_TYPE, UCHAR2_TYPE, UCHAR4_TYPE, UCHAR8_TYPE, UCHAR16_TYPE, SHORT_TYPE, SHORT2_TYPE, SHORT4_TYPE, SHORT8_TYPE, SHORT16_TYPE, USHORT_TYPE, USHORT2_TYPE, USHORT4_TYPE, USHORT8_TYPE, USHORT16_TYPE, INT_TYPE, INT2_TYPE, INT4_TYPE, INT8_TYPE, INT16_TYPE, UINT_TYPE, UINT2_TYPE, UINT4_TYPE, UINT8_TYPE, UINT16_TYPE, LONG_TYPE, LONG2_TYPE, LONG4_TYPE, LONG8_TYPE, LONG16_TYPE, ULONG_TYPE, ULONG2_TYPE, ULONG4_TYPE, ULONG8_TYPE, ULONG16_TYPE, FLOAT_TYPE = 0x10000, FLOAT2_TYPE, FLOAT4_TYPE, FLOAT8_TYPE, FLOAT16_TYPE, DOUBLE_TYPE, DOUBLE2_TYPE, DOUBLE4_TYPE, DOUBLE8_TYPE, DOUBLE16_TYPE, }; struct TypeDescriptor { OP_TYPE type; StructDescriptor* struct_desc; }; enum SYMBOL_TYPE { SYMBOL_IDENTIFIER = 0, SYMBOL_TYPENAME }; struct StructMember { TypeDescriptor type_desc; char* name; StructMember* next; }; struct StructDescriptor { char* name; StructMember* member_head; StructMember* member_tail; StructDescriptor* next; }; struct StructDescriptorTable { StructDescriptor* desc_head; StructDescriptor* desc_tail; }; struct SymbolTableEntry { TypeDescriptor type_desc; char* sym_name; SYMBOL_TYPE sym_type; SymbolTableEntry* next; Operation* op; /* for struct */ SymbolTableEntry* subEntry_head; SymbolTableEntry* subEntry_tail; }; struct SymbolTable { SymbolTableLevel* level_head; SymbolTableLevel* level_tail; }; struct SymbolTableLevel { SymbolTableLevel* prev; SymbolTableLevel* next; SymbolTableEntry* entry_head; SymbolTableEntry* entry_tail; }; enum DEP_TYPE { ISSUE_DEP = 0, STRUCTURAL_DEP, DATA_DEP_L, DATA_DEP_R }; enum STMT_TYPE { EXPRESSION_STMT = 0, SELECTION_STMT, ITERATION_STMT, IF_STMT, ELSE_STMT }; enum OP_KIND { NONE_OP = 0, ADDITION_OP, SUBTRACTION_OP, MULTIPLICATION_OP, DIVISION_OP, MODULAR_OP, INCREASE_OP, DECREASE_OP, SHIFT_LEFT_OP, SHIFT_RIGHT_OP, LESS_OP, LESS_EQUAL_OP, GREATER_OP, GREATER_EQUAL_OP, EQUAL_OP, NOT_EQUAL_OP, BITWISE_AND_OP, BITWISE_XOR_OP, BITWISE_OR_OP, LOGICAL_AND_OP, LOGICAL_OR_OP, MEMORY_OP }; struct DEP { Operation* op; unsigned long long int latency; }; struct Identifier { char* name; Operation* op; Identifier* next; }; struct ID_List { Identifier* id_head; Identifier* id_tail; }; struct Parameter { TypeDescriptor type_desc; char* name; Parameter* next; }; struct Param_List { Parameter* param_head; Parameter* param_tail; }; /* Add post-statement operation? */ struct OP_List { Operation* op_head; Operation* op_tail; OP_List* post_stmt_op_list; SymbolTableEntry* table_entry; TypeDescriptor curr_type_desc; }; // For declarator struct Declarator { char* name; Param_List* Params; }; // For declaration struct Declaration { ID_List* IDs; OP_List* OPs; }; /* Add pre-statement expression? */ struct Statement { OP_List* op_list; STMT_List* stmt_list; STMT_TYPE type; int opID; Statement* next; }; struct Operation { int id; // ID of current statement OP_KIND kind; OP_TYPE type; long long number; DEP* issue_dep; // pointer to the stmt that current stmt need to wait becuase of issue dependency DEP* structural_dep; // pointer to the stmt that current stmt need to wait becuase of structural dependency DEP* data_dep_l; // pointer to the stmt that current stmt need to wait becuase of data dependency DEP* data_dep_r; // pointer to the stmt that current stmt need to wait becuase of data dependency Operation *next; // pointer to next stmt with ID equals to (id+1) }; struct STMT_List { Statement* stmt_head; Statement* stmt_tail; }; #endif <file_sep>PAPI_SRC_DIR=/home/tony/GPGPU_MicroBenchmark_Suite/PAPI/papi-5.4.1/src PAPI_WRAPPER_DIR=/home/tony/GPGPU_MicroBenchmark_Suite/PAPI all: /usr/local/cuda-6.5/bin/nvcc cacheHierarchyTest.cu -I ${PAPI_SRC_DIR} -I ${PAPI_SRC_DIR}/testlib -I ${PAPI_WRAPPER_DIR} -I /usr/local/cuda-6.5/include -I /usr/local/cuda-6.5/extras/CUPTI/include -L ${PAPI_SRC_DIR}/testlib -lpapi -ltestlib -o cacheHierarchyTest /usr/local/cuda-6.5/bin/nvcc InFlightAccessTest.cu -I ${PAPI_SRC_DIR} -I ${PAPI_SRC_DIR}/testlib -I ${PAPI_WRAPPER_DIR} -I /usr/local/cuda-6.5/include -I /usr/local/cuda-6.5/extras/CUPTI/include -L ${PAPI_SRC_DIR}/testlib -lpapi -ltestlib -o InFlightAccessTest clean: rm cacheHierarchyTest InFlightAccessTest <file_sep>all: g++ PowerUsage.cpp -I AMDTPowerProfile/inc/ -L AMDTPowerProfile/bin/x86_64/ -lAMDTPowerProfileAPI -lAMDTBaseTools -lAMDTOSWrappers -o PowerUsage clean: rm PowerUsage <file_sep>all: lex kernelParser.l yacc -d kernelParser.y gcc kernelParser.c symbolTable.c lex.yy.c y.tab.c -o kernelParser -ll -ly rm lex.yy.c y.tab.c y.tab.h clean: rm kernelParser <file_sep>PAPI_SRC_DIR = /home/tony/papi-5.4.1/src all: /usr/local/cuda-6.5/bin/nvcc 2_Normal.cu -I ${PAPI_SRC_DIR} -I ${PAPI_SRC_DIR}/testlib -I /usr/local/cuda-6.5/include -I /usr/local/cuda-6.5/extras/CUPTI/include -L ${PAPI_SRC_DIR}/testlib -lpapi -ltestlib -o Normal clean: rm Normal <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/time.h> #include <AMDTDefinitions.h> #include <AMDTPowerProfileApi.h> #include <AMDTPowerProfileDataTypes.h> #define MAX_FILE_LEN 200 // counterIDs #define CPU_CU0_POWER 12 #define CPU_CU1_POWER 28 #define CPU_CORE0_FREQ 20 #define CPU_CORE1_FREQ 25 #define CPU_CORE2_FREQ 36 #define CPU_CORE3_FREQ 41 #define GPU_POWER 44 #define GPU_FREQ 47 typedef enum ProfileTarget { CPU = 0, GPU, All } ProfileTarget; typedef struct GlobalCtrl { int intervalTime; int totalTime; char outputFile[MAX_FILE_LEN]; int *profileCounter; int nProfileCounter; ProfileTarget targetDevice; GlobalCtrl(): intervalTime(200), totalTime(10), targetDevice(All) {sprintf(outputFile, "PowerUsageOutput.log");} ~GlobalCtrl() {delete [] profileCounter;} } GlobalCtrl; bool CommandParser(int argc, char *argv[], GlobalCtrl *ctrl) { int cmd; while(1) { cmd = getopt(argc, argv, "t:o:T:D:"); if (cmd == -1) break; switch (cmd) { case 't': ctrl->intervalTime = atoi(optarg); break; case 'T': ctrl->totalTime = atoi(optarg); break; case 'o': memset(ctrl->outputFile, 0, MAX_FILE_LEN); sprintf(ctrl->outputFile, "%s", optarg); break; case 'D': if (strcmp("CPU", optarg) == 0) ctrl->targetDevice = CPU; else if (strcmp("GPU", optarg) == 0) ctrl->targetDevice = GPU; else if (strcmp("All", optarg) == 0) ctrl->targetDevice = All; else fprintf(stderr, "Unsupported argument, use All as default\n"); break; default: printf("Error: Unknown argument: %s\n", optarg); return false; break; } } switch (ctrl->targetDevice) { case CPU: ctrl->nProfileCounter = 6; ctrl->profileCounter = new int[ctrl->nProfileCounter]; ctrl->profileCounter[0] = CPU_CU0_POWER; ctrl->profileCounter[1] = CPU_CU1_POWER; ctrl->profileCounter[2] = CPU_CORE0_FREQ; ctrl->profileCounter[3] = CPU_CORE1_FREQ; ctrl->profileCounter[4] = CPU_CORE2_FREQ; ctrl->profileCounter[5] = CPU_CORE3_FREQ; break; case GPU: ctrl->nProfileCounter = 2; ctrl->profileCounter = new int[ctrl->nProfileCounter]; ctrl->profileCounter[0] = GPU_POWER; ctrl->profileCounter[1] = GPU_FREQ; break; case All: ctrl->nProfileCounter = 8; ctrl->profileCounter = new int[ctrl->nProfileCounter]; ctrl->profileCounter[0] = CPU_CU0_POWER; ctrl->profileCounter[1] = CPU_CU1_POWER; ctrl->profileCounter[2] = CPU_CORE0_FREQ; ctrl->profileCounter[3] = CPU_CORE1_FREQ; ctrl->profileCounter[4] = CPU_CORE2_FREQ; ctrl->profileCounter[5] = CPU_CORE3_FREQ; ctrl->profileCounter[6] = GPU_POWER; ctrl->profileCounter[7] = GPU_FREQ; break; } return true; } inline void CheckAMDTError(AMDTResult error, char *msg) { if (AMDT_STATUS_OK != error) { printf("Error: %s: %u\n", msg, error); AMDTPwrProfileClose(); free(msg); exit(1); } free(msg); } int main(int argc, char *argv[]) { GlobalCtrl ctrl; if (!CommandParser(argc, argv, &ctrl)) exit(1); else { AMDTResult error; // Init { AMDTUInt32 nCounters; AMDTUInt32 minSampleTime; AMDTPwrCounterDesc *pCounters; AMDTPwrDeviceId deviceId = AMDT_PWR_ALL_DEVICES; error = AMDTPwrProfileInitialize(AMDT_PWR_PROFILE_MODE_ONLINE); CheckAMDTError(error, strdup("Unable to initialize AMDT driver")); //error = AMDTPwrSetSampleValueOption(AMDT_PWR_SAMPLE_VALUE_LIST); error = AMDTPwrSetSampleValueOption(AMDT_PWR_SAMPLE_VALUE_INSTANTANEOUS); CheckAMDTError(error, strdup("Unable to set sample value option")); for (int i = 0 ; i < ctrl.nProfileCounter ; i ++) { error = AMDTPwrEnableCounter(ctrl.profileCounter[i]); CheckAMDTError(error, strdup("Unable to enable AMDT counter")); } error = AMDTPwrGetMinimalTimerSamplingPeriod(&minSampleTime); CheckAMDTError(error, strdup("Unable to get minimal sampling period")); error = AMDTPwrSetTimerSamplingPeriod(minSampleTime * 5); CheckAMDTError(error, strdup("Unable to set sampling rate")); printf("minimal sampling period %d ms\n", minSampleTime); } // Power/Utilization polling { // Start grab power/utilization info { struct timeval startTime, curTime; unsigned long long start_utime, cur_utime; AMDTPwrSample* sampleResult; AMDTUInt32 nSamples; FILE *fp = fopen(ctrl.outputFile, "w"); error = AMDTPwrStartProfiling(); CheckAMDTError(error, strdup("Unable to start profiling")); gettimeofday(&startTime, NULL); start_utime = startTime.tv_sec * 1000 + startTime.tv_usec / 1000; printf("start_time: %llu msec\n", start_utime); while (1) { usleep(ctrl.intervalTime * 1000); gettimeofday(&curTime, NULL); cur_utime = curTime.tv_sec * 1000 + curTime.tv_usec / 1000; // Sample error = AMDTPwrReadAllEnabledCounters(&nSamples, &sampleResult); //CheckAMDTError(error, strdup("Unable to read counters")); if (error != AMDT_STATUS_OK) { printf("Error: Unable to read counters\n"); } else { //printf("nSample = %d\n", nSamples); //printf("nValue = %d\n", sampleResult->m_numOfValues); for (AMDTUInt32 idx = 0 ; idx < nSamples ; idx ++) { fprintf(fp, "%llu ", cur_utime); for (unsigned int i = 0; i < sampleResult->m_numOfValues; i++) { AMDTPwrCounterDesc counter; AMDTPwrGetCounterDesc(sampleResult->m_counterValues[i].m_counterID, &counter); //fprintf(fp, "%s %f\n", counter.m_name, sampleResult->m_counterValues[i].m_counterValue); if (counter.m_units == AMDT_PWR_UNIT_TYPE_WATT) fprintf(fp, "%f ", sampleResult->m_counterValues[i].m_counterValue * 1000); else fprintf(fp, "%f ", sampleResult->m_counterValues[i].m_counterValue); } fprintf(fp, "\n"); sampleResult ++; } } // Grab end if ((cur_utime - start_utime) > (ctrl.totalTime * 1000)) break; } printf("end_time: %llu msec\n", cur_utime); fclose(fp); AMDTPwrProfileClose(); CheckAMDTError(error, strdup("Unable to stop profiling")); } } } } <file_sep>include ../../../common/make.config all: g++ cacheHierarchyTest.cpp ${OPENCL_LIB} -o cacheHierarchyTest clean: rm cacheHierarchyTest <file_sep>/* * Copyright (c) 2011 Google, Inc * Contributed by <NAME> <<EMAIL>> * * 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. * * This file is part of libpfm, a performance monitoring support library for * applications on Linux. * * This file has been automatically generated. * * PMU: snb (Intel Sandy Bridge) */ static const intel_x86_umask_t snb_agu_bypass_cancel[]={ { .uname = "COUNT", .udesc = "This event counts executed load operations", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_arith[]={ { .uname = "FPU_DIV_ACTIVE", .udesc = "Cycles that the divider is active, includes integer and floating point", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "FPU_DIV", .udesc = "Number of cycles the divider is activated, includes integer and floating point", .uequiv = "FPU_DIV_ACTIVE:c=1:e=1", .ucode = 0x100 | INTEL_X86_MOD_EDGE | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_br_inst_exec[]={ { .uname = "NONTAKEN_COND", .udesc = "All macro conditional non-taken branch instructions", .ucode = 0x4100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_COND", .udesc = "All macro conditional taken branch instructions", .ucode = 0x8100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "NONTAKEN_DIRECT_JUMP", .udesc = "All macro unconditional non-taken branch instructions, excluding calls and indirects", .ucode = 0x4200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_DIRECT_JUMP", .udesc = "All macro unconditional taken branch instructions, excluding calls and indirects", .ucode = 0x8200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "NONTAKEN_INDIRECT_JUMP_NON_CALL_RET", .udesc = "All non-taken indirect branches that are not calls nor returns", .ucode = 0x4400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_INDIRECT_JUMP_NON_CALL_RET", .udesc = "All taken indirect branches that are not calls nor returns", .ucode = 0x8400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_RETURN_NEAR", .udesc = "All taken indirect branches that have a return mnemonic", .ucode = 0x8800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_DIRECT_NEAR_CALL", .udesc = "All taken non-indirect calls", .ucode = 0x9000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_INDIRECT_NEAR_CALL", .udesc = "All taken indirect calls, including both register and memory indirect", .ucode = 0xa000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_BRANCHES", .udesc = "All near executed branches instructions (not necessarily retired)", .ucode = 0xff00, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, { .uname = "ALL_CONDITIONAL", .udesc = "All macro conditional branch instructions", .ucode = 0xc100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ANY_COND", .udesc = "All macro conditional branch instructions", .ucode = 0xc100, .uequiv = "ALL_CONDITIONAL", .uflags= INTEL_X86_NCOMBO, }, { .uname = "ANY_INDIRECT_JUMP_NON_CALL_RET", .udesc = "All indirect branches that are not calls nor returns", .ucode = 0xc400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ANY_DIRECT_NEAR_CALL", .udesc = "All non-indirect calls", .ucode = 0xd000, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_br_inst_retired[]={ { .uname = "ALL_BRANCHES", .udesc = "All taken and not taken macro branches including far branches (Precise Event)", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS | INTEL_X86_DFL, }, { .uname = "CONDITIONAL", .udesc = "All taken and not taken macro conditional branch instructions (Precise Event)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "FAR_BRANCH", .udesc = "Number of far branch instructions retired (Precise Event)", .ucode = 0x4000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "NEAR_CALL", .udesc = "All macro direct and indirect near calls, does not count far calls (Precise Event)", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "NEAR_RETURN", .udesc = "Number of near ret instructions retired (Precise Event)", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "NEAR_TAKEN", .udesc = "Number of near branch taken instructions retired (Precise Event)", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "NOT_TAKEN", .udesc = "All not taken macro branch instructions retired (Precise Event)", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, }; static const intel_x86_umask_t snb_br_misp_exec[]={ { .uname = "NONTAKEN_COND", .udesc = "All non-taken mispredicted macro conditional branch instructions", .ucode = 0x4100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_COND", .udesc = "All taken mispredicted macro conditional branch instructions", .ucode = 0x8100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "NONTAKEN_INDIRECT_JUMP_NON_CALL_RET", .udesc = "All non-taken mispredicted indirect branches that are not calls nor returns", .ucode = 0x4400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_INDIRECT_JUMP_NON_CALL_RET", .udesc = "All taken mispredicted indirect branches that are not calls nor returns", .ucode = 0x8400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "NONTAKEN_RETURN_NEAR", .udesc = "All non-taken mispredicted indirect branches that have a return mnemonic", .ucode = 0x4800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_RETURN_NEAR", .udesc = "All taken mispredicted indirect branches that have a return mnemonic", .ucode = 0x8800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "NONTAKEN_DIRECT_NEAR_CALL", .udesc = "All non-taken mispredicted non-indirect calls", .ucode = 0x5000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_DIRECT_NEAR_CALL", .udesc = "All taken mispredicted non-indirect calls", .ucode = 0x9000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "NONTAKEN_INDIRECT_NEAR_CALL", .udesc = "All nontaken mispredicted indirect calls, including both register and memory indirect", .ucode = 0x6000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "TAKEN_INDIRECT_NEAR_CALL", .udesc = "All taken mispredicted indirect calls, including both register and memory indirect", .ucode = 0xa000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ANY_COND", .udesc = "All mispredicted macro conditional branch instructions", .ucode = 0xc100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ANY_RETURN_NEAR", .udesc = "All mispredicted indirect branches that have a return mnemonic", .ucode = 0xc800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ANY_DIRECT_NEAR_CALL", .udesc = "All mispredicted non-indirect calls", .ucode = 0xd000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ANY_INDIRECT_JUMP_NON_CALL_RET", .udesc = "All mispredicted indirect branches that are not calls nor returns", .ucode = 0xc400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_BRANCHES", .udesc = "All mispredicted branch instructions", .ucode = 0xff00, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_br_misp_retired[]={ { .uname = "ALL_BRANCHES", .udesc = "All mispredicted macro branches (Precise Event)", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS | INTEL_X86_DFL, }, { .uname = "CONDITIONAL", .udesc = "All mispredicted macro conditional branch instructions (Precise Event)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "NEAR_CALL", .udesc = "All macro direct and indirect near calls (Precise Event)", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "NOT_TAKEN", .udesc = "Number of branch instructions retired that were mispredicted and not-taken (Precise Event)", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "TAKEN", .udesc = "Number of branch instructions retired that were mispredicted and taken (Precise Event)", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, }; static const intel_x86_umask_t snb_lock_cycles[]={ { .uname = "SPLIT_LOCK_UC_LOCK_DURATION", .udesc = "Cycles in which the L1D and L2 are locked, due to a UC lock or split lock", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "CACHE_LOCK_DURATION", .udesc = "Cycles in which the L1D is locked", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_cpl_cycles[]={ { .uname = "RING0", .udesc = "Unhalted core cycles the thread was in ring 0", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "RING0_TRANS", .udesc = "Transitions from rings 1, 2, or 3 to ring 0", .uequiv = "RING0:c=1:e=1", .ucode = 0x100 | INTEL_X86_MOD_EDGE | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "RING123", .udesc = "Unhalted core cycles the thread was in rings 1, 2, or 3", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_cpu_clk_unhalted[]={ { .uname = "REF_P", .udesc = "Cycles when the core is unhalted (count at 100 Mhz)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "THREAD_P", .udesc = "Cycles when thread is not halted", .ucode = 0x0, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_dsb2mite_switches[]={ { .uname = "COUNT", .udesc = "Number of DSB to MITE switches", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, { .uname = "PENALTY_CYCLES", .udesc = "Cycles SB to MITE switches caused delay", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_dsb_fill[]={ { .uname = "ALL_CANCEL", .udesc = "Number of times a valid DSB fill has been cancelled for any reason", .ucode = 0xa00, .uflags= INTEL_X86_NCOMBO, }, { .uname = "EXCEED_DSB_LINES", .udesc = "DSB Fill encountered > 3 DSB lines", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "OTHER_CANCEL", .udesc = "Number of times a valid DSB fill has been cancelled not because of exceeding way limit", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_dtlb_load_misses[]={ { .uname = "MISS_CAUSES_A_WALK", .udesc = "Demand load miss in all TLB levels which causes an page walk of any page size", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "CAUSES_A_WALK", .udesc = "Demand load miss in all TLB levels which causes an page walk of any page size", .ucode = 0x100, .uequiv = "MISS_CAUSES_A_WALK", .uflags= INTEL_X86_NCOMBO, }, { .uname = "STLB_HIT", .udesc = "Number of DTLB lookups for loads which missed first level DTLB but hit second level DTLB (STLB); No page walk.", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "WALK_COMPLETED", .udesc = "Demand load miss in all TLB levels which causes a page walk that completes for any page size", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "WALK_DURATION", .udesc = "Cycles PMH is busy with a walk", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_dtlb_store_misses[]={ { .uname = "MISS_CAUSES_A_WALK", .udesc = "Miss in all TLB levels that causes a page walk of any page size (4K/2M/4M/1G)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "CAUSES_A_WALK", .udesc = "Miss in all TLB levels that causes a page walk of any page size (4K/2M/4M/1G)", .ucode = 0x100, .uequiv = "MISS_CAUSES_A_WALK", .uflags= INTEL_X86_NCOMBO, }, { .uname = "STLB_HIT", .udesc = "First level miss but second level hit; no page walk. Only relevant if multiple levels", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "WALK_COMPLETED", .udesc = "Miss in all TLB levels that causes a page walk that completes of any page size (4K/2M/4M/1G)", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "WALK_DURATION", .udesc = "Cycles PMH is busy with this walk", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_fp_assist[]={ { .uname = "ANY", .udesc = "Cycles with any input/output SSE or FP assists", .ucode = 0x1e00, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, { .uname = "SIMD_INPUT", .udesc = "Number of SIMD FP assists due to input values", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "SIMD_OUTPUT", .udesc = "Number of SIMD FP assists due to output values", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "X87_INPUT", .udesc = "Number of X87 assists due to input value", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "X87_OUTPUT", .udesc = "Number of X87 assists due to output value", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_fp_comp_ops_exe[]={ { .uname = "X87", .udesc = "Number of X87 uops executed", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "SSE_FP_PACKED_DOUBLE", .udesc = "Number of SSE double precision FP packed uops executed", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "SSE_FP_SCALAR_SINGLE", .udesc = "Number of SSE single precision FP scalar uops executed", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "SSE_PACKED_SINGLE", .udesc = "Number of SSE single precision FP packed uops executed", .ucode = 0x4000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "SSE_SCALAR_DOUBLE", .udesc = "Number of SSE double precision FP scalar uops executed", .ucode = 0x8000, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_hw_interrupts[]={ { .uname = "RECEIVED", .udesc = "Number of hardware interrupts received by the processor", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_hw_pre_req[]={ { .uname = "L1D_MISS", .udesc = "Hardware prefetch requests that misses the L1D cache. A request is counted each time it accesses the cache and misses it, including if a block is applicable or if it hits the full buffer, for example. This accounts for both L1 streamer and IP-based Hw prefetchers", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_icache[]={ { .uname = "MISSES", .udesc = "Number of Instruction Cache, Streaming Buffer and Victim Cache Misses. Includes UC accesses", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "IFETCH_STALL", .udesc = "Number of cycles wher a code-fetch stalled due to L1 instruction cache miss or iTLB miss", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_idq[]={ { .uname = "EMPTY", .udesc = "Cycles IDQ is empty", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "MITE_UOPS", .udesc = "Number of uops delivered to IDQ from MITE path", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DSB_UOPS", .udesc = "Number of uops delivered to IDQ from DSB path", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "MS_DSB_UOPS", .udesc = "Number of uops delivered to IDQ when MS busy by DSB", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "MS_MITE_UOPS", .udesc = "Number of uops delivered to IDQ when MS busy by MITE", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "MS_UOPS", .udesc = "Number of uops were delivered to IDQ from MS by either DSB or MITE", .ucode = 0x3000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "MITE_UOPS_CYCLES", .udesc = "Cycles where uops are delivered to IDQ from MITE (MITE active)", .uequiv = "MITE_UOPS:c=1", .ucode = 0x400 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "DSB_UOPS_CYCLES", .udesc = "Cycles where uops are delivered to IDQ from DSB (DSB active)", .ucode = 0x800 | (0x1 << INTEL_X86_CMASK_BIT), .modhw = _INTEL_X86_ATTR_C, .uflags= INTEL_X86_NCOMBO, }, { .uname = "MS_DSB_UOPS_CYCLES", .udesc = "Cycles where uops delivered to IDQ when MS busy by DSB", .uequiv = "MS_DSB_UOPS:c=1", .ucode = 0x1000 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "MS_MITE_UOPS_CYCLES", .udesc = "Cycles where uops delivered to IDQ when MS busy by MITE", .uequiv = "MS_MITE_UOPS:c=1", .ucode = 0x2000 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "MS_UOPS_CYCLES", .udesc = "Cycles where uops delivered to IDQ from MS by either BSD or MITE", .uequiv = "MS_UOPS:c=1", .ucode = 0x3000 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_DSB_UOPS", .udesc = "Number of uops deliver from either DSB paths", .ucode = 0x1800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_DSB_CYCLES", .udesc = "Cycles MITE/MS deliver anything", .ucode = 0x1800 | (0x1 << INTEL_X86_CMASK_BIT), .modhw = _INTEL_X86_ATTR_C, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_MITE_UOPS", .udesc = "Number of uops delivered from either MITE paths", .ucode = 0x2400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_MITE_CYCLES", .udesc = "Cycles DSB/MS deliver anything", .ucode = 0x2400 | (0x1 << INTEL_X86_CMASK_BIT), .modhw = _INTEL_X86_ATTR_C, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ANY_UOPS", .udesc = "Number of uops delivered to IDQ from any path", .ucode = 0x3c00, .uflags= INTEL_X86_NCOMBO, }, { .uname = "MS_DSB_UOPS_OCCUR", .udesc = "Occurrences of DSB MS going active", .uequiv = "MS_DSB_UOPS:c=1:e=1", .ucode = 0x1000 | INTEL_X86_MOD_EDGE | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_idq_uops_not_delivered[]={ { .uname = "CORE", .udesc = "Number of non-delivered uops to RAT (use cmask to qualify further)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_ild_stall[]={ { .uname = "LCP", .udesc = "Stall caused by changing prefix length of the instruction", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "IQ_FULL", .udesc = "Stall cycles due to IQ full", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_insts_written_to_iq[]={ { .uname = "INSTS", .udesc = "Number of instructions written to IQ every cycle", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_inst_retired[]={ { .uname = "ANY_P", .udesc = "Number of instructions retired", .ucode = 0x0, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, { .uname = "PREC_DIST", .udesc = "Precise instruction retired event to reduce effect of PEBS shadow IP distribution (Precise Event)", .ucntmsk = 0x2, .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, }; static const intel_x86_umask_t snb_int_misc[]={ { .uname = "RAT_STALL_CYCLES", .udesc = "Cycles RAT external stall is sent to IDQ for this thread", .ucode = 0x4000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "RECOVERY_CYCLES", .udesc = "Cycles waiting to be recovered after Machine Clears due to all other cases except JEClear", .ucode = 0x300 | (0x1 << INTEL_X86_CMASK_BIT), .modhw = _INTEL_X86_ATTR_C, .uflags= INTEL_X86_NCOMBO, }, { .uname = "RECOVERY_STALLS_COUNT", .udesc = "Number of times need to wait after Machine Clears due to all other cases except JEClear", .ucode = 0x300 | INTEL_X86_MOD_EDGE | (0x1 << INTEL_X86_CMASK_BIT), .modhw = _INTEL_X86_ATTR_E | _INTEL_X86_ATTR_C, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_itlb[]={ { .uname = "ITLB_FLUSH", .udesc = "Number of ITLB flushes, includes 4k/2M/4M pages", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, { .uname = "FLUSH", .udesc = "Number of ITLB flushes, includes 4k/2M/4M pages", .ucode = 0x100, .uequiv = "ITLB_FLUSH", .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_l1d[]={ { .uname = "ALLOCATED_IN_M", .udesc = "Number of allocations of L1D cache lines in modified (M) state", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_M_REPLACEMENT", .udesc = "Number of cache lines in M-state evicted of L1D due to snoop HITM or dirty line replacement", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "M_EVICT", .udesc = "Number of modified lines evicted from L1D due to replacement", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "REPLACEMENT", .udesc = "Number of cache lines brought into the L1D cache", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_l1d_blocks[]={ { .uname = "BANK_CONFLICT", .udesc = "Number of dispatched loads cancelled due to L1D bank conflicts with other load ports", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "BANK_CONFLICT_CYCLES", .udesc = "Cycles with l1d blocks due to bank conflicts", .ucode = 0x500, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_l1d_pend_miss[]={ { .uname = "OCCURRENCES", .udesc = "Occurrences of L1D_PEND_MISS going active", .uequiv = "PENDING:e=1:c=1", .ucode = 0x100 | INTEL_X86_MOD_EDGE | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "EDGE", .udesc = "Occurrences of L1D_PEND_MISS going active", .uequiv = "OCCURRENCES", .ucode = 0x100 | INTEL_X86_MOD_EDGE | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "PENDING", .udesc = "Number of L1D load misses outstanding every cycle", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PENDING_CYCLES", .udesc = "Cycles with L1D load misses outstanding", .uequiv = "PENDING:c=1", .ucode = 0x100 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_l2_l1d_wb_rqsts[]={ { .uname = "HIT_E", .udesc = "Non rejected writebacks from L1D to L2 cache lines in E state", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "HIT_M", .udesc = "Non rejected writebacks from L1D to L2 cache lines in M state", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_l2_lines_in[]={ { .uname = "ANY", .udesc = "L2 cache lines filling (counting does not cover rejects)", .ucode = 0x700, .uflags= INTEL_X86_NCOMBO, }, { .uname = "E", .udesc = "L2 cache lines in E state (counting does not cover rejects)", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "I", .udesc = "L2 cache lines in I state (counting does not cover rejects)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "S", .udesc = "L2 cache lines in S state (counting does not cover rejects)", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_l2_lines_out[]={ { .uname = "DEMAND_CLEAN", .udesc = "L2 clean line evicted by a demand", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_DIRTY", .udesc = "L2 dirty line evicted by a demand", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PREFETCH_CLEAN", .udesc = "L2 clean line evicted by a prefetch", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PREFETCH_DIRTY", .udesc = "L2 dirty line evicted by an MLC Prefetch", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DIRTY_ANY", .udesc = "Any L2 dirty line evicted (does not cover rejects)", .ucode = 0xa00, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_l2_rqsts[]={ { .uname = "ALL_CODE_RD", .udesc = "Any ifetch request to L2 cache", .ucode = 0x3000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "CODE_RD_HIT", .udesc = "L2 cache hits when fetching instructions", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "CODE_RD_MISS", .udesc = "L2 cache misses when fetching instructions", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_DEMAND_DATA_RD", .udesc = "Demand data read requests to L2 cache", .ucode = 0x300, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_DEMAND_RD_HIT", .udesc = "Demand data read requests that hit L2", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_PF", .udesc = "Any L2 HW prefetch request to L2 cache", .ucode = 0xc000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PF_HIT", .udesc = "Requests from the L2 hardware prefetchers that hit L2 cache", .ucode = 0x4000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PF_MISS", .udesc = "Requests from the L2 hardware prefetchers that miss L2 cache", .ucode = 0x8000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "RFO_ANY", .udesc = "Any RFO requests to L2 cache", .ucode = 0xc00, .uflags= INTEL_X86_NCOMBO, }, { .uname = "RFO_HITS", .udesc = "RFO requests that hit L2 cache", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "RFO_MISS", .udesc = "RFO requests that miss L2 cache", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_l2_store_lock_rqsts[]={ { .uname = "HIT_E", .udesc = "RFOs that hit cache lines in E state", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "MISS", .udesc = "RFOs that miss cache (I state)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "HIT_M", .udesc = "RFOs that hit cache lines in M state", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL", .udesc = "RFOs that access cache lines in any state", .ucode = 0xf00, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_l2_trans[]={ { .uname = "ALL", .udesc = "Transactions accessing MLC pipe", .ucode = 0x8000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "CODE_RD", .udesc = "L2 cache accesses when fetching instructions", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "L1D_WB", .udesc = "L1D writebacks that access L2 cache", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "LOAD", .udesc = "Demand Data Read* requests that access L2 cache", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "L2_FILL", .udesc = "L2 fill requests that access L2 cache", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "L2_WB", .udesc = "L2 writebacks that access L2 cache", .ucode = 0x4000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_PREFETCH", .udesc = "L2 or L3 HW prefetches that access L2 cache (including rejects)", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "RFO", .udesc = "RFO requests that access L2 cache", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_ld_blocks[]={ { .uname = "DATA_UNKNOWN", .udesc = "Blocked loads due to store buffer blocks with unknown data", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "STORE_FORWARD", .udesc = "Loads blocked by overlapping with store buffer that cannot be forwarded", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "NO_SR", .udesc = "Number of split loads blocked due to resource not available", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_BLOCK", .udesc = "Number of cases where any load is blocked but has not DCU miss", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_ld_blocks_partial[]={ { .uname = "ADDRESS_ALIAS", .udesc = "False dependencies in MOB due to partial compare on address", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_STA_BLOCK", .udesc = "Number of times that load operations are temporarily blocked because of older stores, with addresses that are not yet known. A load operation may incur more than one block of this type", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_load_hit_pre[]={ { .uname = "HW_PF", .udesc = "Non sw-prefetch load dispatches that hit the fill buffer allocated for HW prefetch", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "SW_PF", .udesc = "Non sw-prefetch load dispatches that hit the fill buffer allocated for SW prefetch", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_l3_lat_cache[]={ { .uname = "MISS", .udesc = "Core-originated cacheable demand requests missed L3", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "REFERENCE", .udesc = "Core-originated cacheable demand requests that refer to L3", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_machine_clears[]={ { .uname = "MASKMOV", .udesc = "The number of executed Intel AVX masked load operations that refer to an illegal address range with the mask bits set to 0", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "MEMORY_ORDERING", .udesc = "Number of Memory Ordering Machine Clears detected", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "SMC", .udesc = "Self-Modifying Code detected", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_mem_load_uops_llc_hit_retired[]={ { .uname = "XSNP_HIT", .udesc = "Load LLC Hit and a cross-core Snoop hits in on-pkg core cache (Precise Event)", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "XSNP_HITM", .udesc = "Load had HitM Response from a core on same socket (shared LLC) (Precise Event)", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "XSNP_MISS", .udesc = "Load LLC Hit and a cross-core Snoop missed in on-pkg core cache (Precise Event)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "XSNP_NONE", .udesc = "Load hit in last-level (L3) cache with no snoop needed (Precise Event)", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, }; static const intel_x86_umask_t snb_mem_load_uops_misc_retired[]={ { .uname = "LLC_MISS", .udesc = "Counts load driven L3 misses and some non simd split loads (Precise Event)", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_mem_load_uops_retired[]={ { .uname = "HIT_LFB", .udesc = "A load missed L1D but hit the Fill Buffer (Precise Event)", .ucode = 0x4000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "L1_HIT", .udesc = "Load hit in nearest-level (L1D) cache (Precise Event)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "L2_HIT", .udesc = "Load hit in mid-level (L2) cache (Precise Event)", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "L3_HIT", .udesc = "Load hit in last-level (L3) cache with no snoop needed (Precise Event)", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "L3_MISS", .udesc = "Retired load uops which data sources were data missed LLC (excluding unknown data source)", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, }; static const intel_x86_umask_t snb_mem_trans_retired[]={ { .uname = "LATENCY_ABOVE_THRESHOLD", .udesc = "Memory load instructions retired above programmed clocks, minimum threshold value is 3 (Precise Event and ldlat required)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS | INTEL_X86_LDLAT, }, { .uname = "PRECISE_STORE", .udesc = "Capture where stores occur, must use with PEBS (Precise Event required)", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, }; static const intel_x86_umask_t snb_mem_uops_retired[]={ { .uname = "ALL_LOADS", .udesc = "Any retired loads (Precise Event)", .ucode = 0x8100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "ANY_LOADS", .udesc = "Any retired loads (Precise Event)", .ucode = 0x8100, .uequiv = "ALL_LOADS", .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "ALL_STORES", .udesc = "Any retired stores (Precise Event)", .ucode = 0x8200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "ANY_STORES", .udesc = "Any retired stores (Precise Event)", .ucode = 0x8200, .uequiv = "ALL_STORES", .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "LOCK_LOADS", .udesc = "Locked retired loads (Precise Event)", .ucode = 0x2100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "LOCK_STORES", .udesc = "Locked retired stores (Precise Event)", .ucode = 0x2200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "SPLIT_LOADS", .udesc = "Retired loads causing cacheline splits (Precise Event)", .ucode = 0x4100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "SPLIT_STORES", .udesc = "Retired stores causing cacheline splits (Precise Event)", .ucode = 0x4200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "STLB_MISS_LOADS", .udesc = "STLB misses dues to retired loads (Precise Event)", .ucode = 0x1100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "STLB_MISS_STORES", .udesc = "STLB misses dues to retired stores (Precise Event)", .ucode = 0x1200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, }; static const intel_x86_umask_t snb_misalign_mem_ref[]={ { .uname = "LOADS", .udesc = "Speculative cache-line split load uops dispatched to the L1D", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "STORES", .udesc = "Speculative cache-line split Store-address uops dispatched to L1D", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_offcore_requests[]={ { .uname = "ALL_DATA_RD", .udesc = "Demand and prefetch read requests sent to uncore", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_DATA_READ", .udesc = "Demand and prefetch read requests sent to uncore", .uequiv = "ALL_DATA_RD", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_CODE_RD", .udesc = "Offcore code read requests, including cacheable and un-cacheables", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_DATA_RD", .udesc = "Demand Data Read requests sent to uncore", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_RFO", .udesc = "Offcore Demand RFOs, includes regular RFO, Locks, ItoM", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_offcore_requests_buffer[]={ { .uname = "SQ_FULL", .udesc = "Offcore requests buffer cannot take more entries for this thread core", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_offcore_requests_outstanding[]={ { .uname = "ALL_DATA_RD_CYCLES", .udesc = "Cycles with cacheable data read transactions in the superQ", .uequiv = "ALL_DATA_RD:c=1", .ucode = 0x800 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_CODE_RD_CYCLES", .udesc = "Cycles with demand code reads transactions in the superQ", .uequiv = "DEMAND_CODE_RD:c=1", .ucode = 0x200 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_DATA_RD_CYCLES", .udesc = "Cycles with demand data read transactions in the superQ", .uequiv = "DEMAND_DATA_RD:c=1", .ucode = 0x100 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "ALL_DATA_RD", .udesc = "Cacheable data read transactions in the superQ every cycle", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_CODE_RD", .udesc = "Code read transactions in the superQ every cycle", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_DATA_RD", .udesc = "Demand data read transactions in the superQ every cycle", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_RFO", .udesc = "Outstanding RFO (store) transactions in the superQ every cycle", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "DEMAND_RFO_CYCLES", .udesc = "Cycles with outstanding RFO (store) transactions in the superQ", .uequiv = "DEMAND_RFO:c=1", .ucode = 0x400 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_other_assists[]={ { .uname = "ITLB_MISS_RETIRED", .udesc = "Number of instructions that experienced an ITLB miss", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "AVX_TO_SSE", .udesc = "Number of transitions from AVX-256 to legacy SSE when penalty applicable", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "SSE_TO_AVX", .udesc = "Number of transitions from legacy SSE to AVX-256 when penalty applicable", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_partial_rat_stalls[]={ { .uname = "FLAGS_MERGE_UOP", .udesc = "Number of flags-merge uops in flight in each cycle", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "CYCLES_FLAGS_MERGE_UOP", .udesc = "Cycles in which flags-merge uops in flight", .uequiv = "FLAGS_MERGE_UOP:c=1", .ucode = 0x2000 | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "MUL_SINGLE_UOP", .udesc = "Number of Multiply packed/scalar single precision uops allocated", .ucode = 0x8000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "SLOW_LEA_WINDOW", .udesc = "Number of cycles with at least one slow LEA uop allocated", .ucode = 0x4000, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_resource_stalls[]={ { .uname = "ANY", .udesc = "Cycles stalled due to Resource Related reason", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, { .uname = "LB", .udesc = "Cycles stalled due to lack of load buffers", .ucode = 0x200, }, { .uname = "RS", .udesc = "Cycles stalled due to no eligible RS entry available", .ucode = 0x400, }, { .uname = "SB", .udesc = "Cycles stalled due to no store buffers available (not including draining from sync)", .ucode = 0x800, }, { .uname = "ROB", .udesc = "Cycles stalled due to re-order buffer full", .ucode = 0x1000, }, { .uname = "FCSW", .udesc = "Cycles stalled due to writing the FPU control word", .ucode = 0x2000, }, { .uname = "MXCSR", .udesc = "Cycles stalled due to the MXCSR register ranme occurring too close to a previous MXCSR rename", .ucode = 0x4000, }, { .uname = "MEM_RS", .udesc = "Cycles stalled due to LB, SB or RS being completely in use", .ucode = 0xe00, .uequiv = "LB:SB:RS", }, }; static const intel_x86_umask_t snb_resource_stalls2[]={ { .uname = "ALL_FL_EMPTY", .udesc = "Cycles stalled due to free list empty", .ucode = 0xc00, }, { .uname = "ALL_PRF_CONTROL", .udesc = "Cycles stalls due to control structures full for physical registers", .ucode = 0xf00, }, { .uname = "ANY_PRF_CONTROL", .udesc = "Cycles stalls due to control structures full for physical registers", .ucode = 0xf00, .uequiv = "ALL_PRF_CONTROL", }, { .uname = "BOB_FULL", .udesc = "Cycles Allocator is stalled due Branch Order Buffer", .ucode = 0x4000, }, { .uname = "OOO_RSRC", .udesc = "Cycles stalled due to out of order resources full", .ucode = 0x4f00, }, }; static const intel_x86_umask_t snb_rob_misc_events[]={ { .uname = "LBR_INSERTS", .udesc = "Count each time an new LBR record is saved by HW", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_rs_events[]={ { .uname = "EMPTY_CYCLES", .udesc = "Cycles the RS is empty for this thread", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_simd_fp_256[]={ { .uname = "PACKED_SINGLE", .udesc = "Counts 256-bit packed single-precision", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PACKED_DOUBLE", .udesc = "Counts 256-bit packed double-precision", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_sq_misc[]={ { .uname = "SPLIT_LOCK", .udesc = "Split locks in SQ", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_tlb_flush[]={ { .uname = "DTLB_THREAD", .udesc = "Number of DTLB flushes of thread-specific entries", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "STLB_ANY", .udesc = "Number of STLB flushes", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_uops_dispatched[]={ { .uname = "CORE", .udesc = "Counts total number of uops dispatched from any thread", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "STALL_CYCLES", .udesc = "Counts number of cycles no uops were dispatched on this thread", .uequiv = "THREAD:c=1:i=1", .ucode = 0x100 | INTEL_X86_MOD_INV | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "THREAD", .udesc = "Counts total number of uops to be dispatched per-thread each cycle", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_uops_dispatched_port[]={ { .uname = "PORT_0", .udesc = "Cycles which a Uop is dispatched on port 0", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PORT_1", .udesc = "Cycles which a Uop is dispatched on port 1", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PORT_2_LD", .udesc = "Cycles in which a load uop is dispatched on port 2", .ucode = 0x400, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PORT_2_STA", .udesc = "Cycles in which a store uop is dispatched on port 2", .ucode = 0x800, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PORT_2", .udesc = "Cycles in which a uop is dispatched on port 2", .ucode = 0xc00, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PORT_3_LD", .udesc = "Cycles in which a load uop is dispatched on port 3", .ucode = 0x1000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PORT_3_STA", .udesc = "Cycles in which a store uop is dispatched on port 3", .ucode = 0x2000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PORT_3", .udesc = "Cycles in which a uop is dispatched on port 3", .ucode = 0x3000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PORT_4", .udesc = "Cycles which a uop is dispatched on port 4", .ucode = 0x4000, .uflags= INTEL_X86_NCOMBO, }, { .uname = "PORT_5", .udesc = "Cycles which a Uop is dispatched on port 5", .ucode = 0x8000, .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_uops_issued[]={ { .uname = "ANY", .udesc = "Number of uops issued by the RAT to the Reservation Station (RS)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, { .uname = "CORE_STALL_CYCLES", .udesc = "Cycles no uops issued on this core (by any thread)", .uequiv = "ANY:c=1:i=1:t=1", .ucode = 0x100 | INTEL_X86_MOD_ANY | INTEL_X86_MOD_INV | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, { .uname = "STALL_CYCLES", .udesc = "Cycles no uops issued by this thread", .uequiv = "ANY:c=1:i=1", .ucode = 0x100 | INTEL_X86_MOD_INV | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO, }, }; static const intel_x86_umask_t snb_uops_retired[]={ { .uname = "ALL", .udesc = "All uops that actually retired (Precise Event)", .ucode = 0x100, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS | INTEL_X86_DFL, }, { .uname = "ANY", .udesc = "All uops that actually retired (Precise Event)", .ucode = 0x100, .uequiv= "ALL", .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "RETIRE_SLOTS", .udesc = "Number of retirement slots used (Precise Event)", .ucode = 0x200, .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "STALL_CYCLES", .udesc = "Cycles no executable uop retired (Precise Event)", .uequiv = "ALL:c=1:i=1", .ucode = 0x100 | INTEL_X86_MOD_INV | (0x1 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, { .uname = "TOTAL_CYCLES", .udesc = "Total cycles using precise uop retired event (Precise Event)", .uequiv = "ALL:c=16", .ucode = 0x100 | (0x10 << INTEL_X86_CMASK_BIT), .uflags= INTEL_X86_NCOMBO | INTEL_X86_PEBS, }, }; static const intel_x86_umask_t snb_offcore_response[]={ { .uname = "DMND_DATA_RD", .udesc = "Request: number of demand and DCU prefetch data reads of full and partial cachelines as well as demand data page table entry cacheline reads. Does not count L2 data read prefetches or instruction fetches", .ucode = 1ULL << (0 + 8), .grpid = 0, }, { .uname = "DMND_RFO", .udesc = "Request: number of demand and DCU prefetch reads for ownership (RFO) requests generated by a write to data cacheline. Does not count L2 RFO prefetches", .ucode = 1ULL << (1 + 8), .grpid = 0, }, { .uname = "DMND_IFETCH", .udesc = "Request: number of demand and DCU prefetch instruction cacheline reads. Does not count L2 code read prefetches", .ucode = 1ULL << (2 + 8), .grpid = 0, }, { .uname = "WB", .udesc = "Request: number of writebacks (modified to exclusive) transactions", .ucode = 1ULL << (3 + 8), .grpid = 0, }, { .uname = "PF_DATA_RD", .udesc = "Request: number of data cacheline reads generated by L2 prefetchers", .ucode = 1ULL << (4 + 8), .grpid = 0, }, { .uname = "PF_RFO", .udesc = "Request: number of RFO requests generated by L2 prefetchers", .ucode = 1ULL << (5 + 8), .grpid = 0, }, { .uname = "PF_IFETCH", .udesc = "Request: number of code reads generated by L2 prefetchers", .ucode = 1ULL << (6 + 8), .grpid = 0, }, { .uname = "PF_LLC_DATA_RD", .udesc = "Request: number of L3 prefetcher requests to L2 for loads", .ucode = 1ULL << (7 + 8), .grpid = 0, }, { .uname = "PF_LLC_RFO", .udesc = "Request: number of RFO requests generated by L2 prefetcher", .ucode = 1ULL << (8 + 8), .grpid = 0, }, { .uname = "PF_LLC_IFETCH", .udesc = "Request: number of L2 prefetcher requests to L3 for instruction fetches", .ucode = 1ULL << (9 + 8), .grpid = 0, }, { .uname = "BUS_LOCKS", .udesc = "Request: number bus lock and split lock requests", .ucode = 1ULL << (10 + 8), .grpid = 0, }, { .uname = "STRM_ST", .udesc = "Request: number of streaming store requests", .ucode = 1ULL << (11 + 8), .grpid = 0, }, { .uname = "OTHER", .udesc = "Request: counts one of the following transaction types, including L3 invalidate, I/O, full or partial writes, WC or non-temporal stores, CLFLUSH, Fences, lock, unlock, split lock", .ucode = 1ULL << (15+8), .grpid = 0, }, { .uname = "ANY_IFETCH", .udesc = "Request: combination of PF_IFETCH | DMND_IFETCH | PF_LLC_IFETCH", .uequiv = "PF_IFETCH:DMND_IFETCH:PF_LLC_IFETCH", .ucode = 0x24400, .grpid = 0, }, { .uname = "ANY_REQUEST", .udesc = "Request: combination of all request umasks", .uequiv = "DMND_DATA_RD:DMND_RFO:DMND_IFETCH:WB:PF_DATA_RD:PF_RFO:PF_IFETCH:PF_LLC_DATA_RD:PF_LLC_RFO:PF_LLC_IFETCH:BUS_LOCKS:STRM_ST:OTHER", .ucode = 0x8fff00, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, .grpid = 0, }, { .uname = "ANY_DATA", .udesc = "Request: combination of DMND_DATA | PF_DATA_RD | PF_LLC_DATA_RD", .uequiv = "DMND_DATA_RD:PF_DATA_RD:PF_LLC_DATA_RD", .ucode = 0x9100, .grpid = 0, }, { .uname = "ANY_RFO", .udesc = "Request: combination of DMND_RFO | PF_RFO | PF_LLC_RFO", .uequiv = "DMND_RFO:PF_RFO:PF_LLC_RFO", .ucode = 0x12200, .grpid = 0, }, { .uname = "ANY_RESPONSE", .udesc = "Response: count any response type", .ucode = 1ULL << (16+8), .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL | INTEL_X86_EXCL_GRP_GT, .grpid = 1, }, { .uname = "NO_SUPP", .udesc = "Supplier: counts number of times supplier information is not available", .ucode = 1ULL << (17+8), .grpid = 1, }, { .uname = "LLC_HITM", .udesc = "Supplier: counts L3 hits in M-state (initial lookup)", .ucode = 1ULL << (18+8), .grpid = 1, }, { .uname = "LLC_HITE", .udesc = "Supplier: counts L3 hits in E-state", .ucode = 1ULL << (19+8), .grpid = 1, }, { .uname = "LLC_HITS", .udesc = "Supplier: counts L3 hits in S-state", .ucode = 1ULL << (20+8), .grpid = 1, }, { .uname = "LLC_HITF", .udesc = "Supplier: counts L3 hits in F-state", .ucode = 1ULL << (21+8), .grpid = 1, }, { .uname = "LLC_MISS_LOCAL_DRAM", .udesc = "Supplier: counts L3 misses to local DRAM", .ucode = 1ULL << (22+8), .uequiv = "MISS_DRAM", .grpid = 1, }, { .uname = "LLC_MISS_LOCAL", .udesc = "Supplier: counts L3 misses to local DRAM", .ucode = 1ULL << (22+8), .uequiv = "MISS_DRAM", .grpid = 1, }, { .uname = "MISS_DRAM", .udesc = "Supplier: counts L3 misses to local DRAM", .ucode = 1ULL << (22+8), .grpid = 1, }, { .uname = "LLC_HITMESF", .udesc = "Supplier: counts L3 hits in any state (M, E, S, F)", .ucode = 0xfULL << (18+8), .uequiv = "LLC_HITM:LLC_HITE:LLC_HITS:LLC_HITF", .grpid = 1, }, { .uname = "SNP_NONE", .udesc = "Snoop: counts number of times no snoop-related information is available", .ucode = 1ULL << (31+8), .grpid = 2, }, { .uname = "SNP_NOT_NEEDED", .udesc = "Snoop: counts the number of times no snoop was needed to satisfy the request", .ucode = 1ULL << (32+8), .grpid = 2, }, { .uname = "NO_SNP_NEEDED", .udesc = "Snoop: counts the number of times no snoop was needed to satisfy the request", .ucode = 1ULL << (32+8), .uequiv = "SNP_NOT_NEEDED", .grpid = 2, }, { .uname = "SNP_MISS", .udesc = "Snoop: counts number of times a snoop was needed and it missed all snooped caches", .ucode = 1ULL << (33+8), .grpid = 2, }, { .uname = "SNP_NO_FWD", .udesc = "Snoop: counts number of times a snoop was needed and it hit in at leas one snooped cache", .ucode = 1ULL << (34+8), .grpid = 2, }, { .uname = "SNP_FWD", .udesc = "Snoop: counts number of times a snoop was needed and data was forwarded from a remote socket", .ucode = 1ULL << (35+8), .grpid = 2, }, { .uname = "HITM", .udesc = "Snoop: counts number of times a snoop was needed and it hitM-ed in local or remote cache", .ucode = 1ULL << (36+8), .grpid = 2, }, { .uname = "NON_DRAM", .udesc = "Snoop: counts number of times target was a non-DRAM system address. This includes MMIO transactions", .ucode = 1ULL << (37+8), .grpid = 2, }, { .uname = "SNP_ANY", .udesc = "Snoop: any snoop reason", .ucode = 0x7fULL << (31+8), .uequiv = "SNP_NONE:SNP_NOT_NEEDED:SNP_MISS:SNP_NO_FWD:SNP_FWD:HITM:NON_DRAM", .uflags= INTEL_X86_DFL, .grpid = 2, }, }; static const intel_x86_umask_t snb_baclears[]={ { .uname = "ANY", .udesc = "Counts the number of times the front end is re-steered, mainly when the BPU cannot provide a correct prediction and this is corrected by other branch handling mechanisms at the front end", .ucode = 0x1f00, .uflags= INTEL_X86_NCOMBO | INTEL_X86_DFL, }, }; static const intel_x86_umask_t snb_cycle_activity[]={ { .uname = "CYCLES_L2_PENDING", .udesc = "Cycles with pending L2 miss loads", .ucode = 0x0100 | (0x1 << INTEL_X86_CMASK_BIT), .uflags = INTEL_X86_NCOMBO, .ucntmsk= 0xf, }, { .uname = "CYCLES_L1D_PENDING", .udesc = "Cycles with pending L1D load cache misses", .ucode = 0x0200 | (0x2 << INTEL_X86_CMASK_BIT), .ucntmsk= 0x4, .uflags = INTEL_X86_NCOMBO, }, { .uname = "CYCLES_NO_DISPATCH", .udesc = "Cycles of dispatch stalls", .ucode = 0x0400 | (0x4 << INTEL_X86_CMASK_BIT), .ucntmsk= 0xf, .uflags = INTEL_X86_NCOMBO, }, { .uname = "STALLS_L2_PENDING", .udesc = "Execution stalls due to L2 pending loads", .ucode = 0x0500 | (0x5 << INTEL_X86_CMASK_BIT), .ucntmsk= 0xf, .uflags = INTEL_X86_NCOMBO, }, { .uname = "STALLS_L1D_PENDING", .udesc = "Execution stalls due to L1D pending loads", .ucode = 0x0600 | (0x6 << INTEL_X86_CMASK_BIT), .ucntmsk= 0x4, .uflags = INTEL_X86_NCOMBO, }, }; static const intel_x86_entry_t intel_snb_pe[]={ { .name = "AGU_BYPASS_CANCEL", .desc = "Number of executed load operations with all the following traits: 1. addressing of the format [base + offset], 2. the offset is between 1 and 2047, 3. the address specified in the base register is in one page and the address [base+offset] is in another page", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xb6, .numasks = LIBPFM_ARRAY_SIZE(snb_agu_bypass_cancel), .ngrp = 1, .umasks = snb_agu_bypass_cancel, }, { .name = "ARITH", .desc = "Counts arithmetic multiply operations", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x14, .numasks = LIBPFM_ARRAY_SIZE(snb_arith), .ngrp = 1, .umasks = snb_arith, }, { .name = "BACLEARS", .desc = "Branch re-steered", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xe6, .numasks = LIBPFM_ARRAY_SIZE(snb_baclears), .ngrp = 1, .umasks = snb_baclears, }, { .name = "BR_INST_EXEC", .desc = "Branch instructions executed", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x88, .numasks = LIBPFM_ARRAY_SIZE(snb_br_inst_exec), .ngrp = 1, .umasks = snb_br_inst_exec, }, { .name = "BR_INST_RETIRED", .desc = "Retired branch instructions", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xc4, .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_br_inst_retired), .ngrp = 1, .umasks = snb_br_inst_retired, }, { .name = "BR_MISP_EXEC", .desc = "Mispredicted branches executed", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x89, .numasks = LIBPFM_ARRAY_SIZE(snb_br_misp_exec), .ngrp = 1, .umasks = snb_br_misp_exec, }, { .name = "BR_MISP_RETIRED", .desc = "Mispredicted retired branches", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xc5, .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_br_misp_retired), .ngrp = 1, .umasks = snb_br_misp_retired, }, { .name = "BRANCH_INSTRUCTIONS_RETIRED", .desc = "Count branch instructions at retirement. Specifically, this event counts the retirement of the last micro-op of a branch instruction", .modmsk = INTEL_V3_ATTRS, .equiv = "BR_INST_RETIRED:ALL_BRANCHES", .cntmsk = 0xff, .code = 0xc4, }, { .name = "MISPREDICTED_BRANCH_RETIRED", .desc = "Count mispredicted branch instructions at retirement. Specifically, this event counts at retirement of the last micro-op of a branch instruction in the architectural path of the execution and experienced misprediction in the branch prediction hardware", .modmsk = INTEL_V3_ATTRS, .equiv = "BR_MISP_RETIRED:ALL_BRANCHES", .cntmsk = 0xff, .code = 0xc5, }, { .name = "LOCK_CYCLES", .desc = "Locked cycles in L1D and L2", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x63, .numasks = LIBPFM_ARRAY_SIZE(snb_lock_cycles), .ngrp = 1, .umasks = snb_lock_cycles, }, { .name = "CPL_CYCLES", .desc = "Unhalted core cycles at a specific ring level", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x5c, .numasks = LIBPFM_ARRAY_SIZE(snb_cpl_cycles), .ngrp = 1, .umasks = snb_cpl_cycles, }, { .name = "CPU_CLK_UNHALTED", .desc = "Cycles when processor is not in halted state", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x3c, .numasks = LIBPFM_ARRAY_SIZE(snb_cpu_clk_unhalted), .ngrp = 1, .umasks = snb_cpu_clk_unhalted, }, { .name = "DSB2MITE_SWITCHES", .desc = "Number of DSB to MITE switches", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xab, .numasks = LIBPFM_ARRAY_SIZE(snb_dsb2mite_switches), .ngrp = 1, .umasks = snb_dsb2mite_switches, }, { .name = "DSB_FILL", .desc = "DSB fills", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xac, .numasks = LIBPFM_ARRAY_SIZE(snb_dsb_fill), .ngrp = 1, .umasks = snb_dsb_fill, }, { .name = "DTLB_LOAD_MISSES", .desc = "Data TLB load misses", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x8, .numasks = LIBPFM_ARRAY_SIZE(snb_dtlb_load_misses), .ngrp = 1, .umasks = snb_dtlb_load_misses, }, { .name = "DTLB_STORE_MISSES", .desc = "Data TLB store misses", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x49, .numasks = LIBPFM_ARRAY_SIZE(snb_dtlb_store_misses), .ngrp = 1, .umasks = snb_dtlb_store_misses, }, { .name = "FP_ASSIST", .desc = "X87 Floating point assists", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xca, .numasks = LIBPFM_ARRAY_SIZE(snb_fp_assist), .ngrp = 1, .umasks = snb_fp_assist, }, { .name = "FP_COMP_OPS_EXE", .desc = "Counts number of floating point events", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x10, .numasks = LIBPFM_ARRAY_SIZE(snb_fp_comp_ops_exe), .ngrp = 1, .umasks = snb_fp_comp_ops_exe, }, { .name = "HW_INTERRUPTS", .desc = "Number of hardware interrupts received by the processor", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xcb, .numasks = LIBPFM_ARRAY_SIZE(snb_hw_interrupts), .ngrp = 1, .umasks = snb_hw_interrupts, }, { .name = "HW_PRE_REQ", .desc = "Hardware prefetch requests", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x4e, .numasks = LIBPFM_ARRAY_SIZE(snb_hw_pre_req), .ngrp = 1, .umasks = snb_hw_pre_req, }, { .name = "ICACHE", .desc = "Instruction Cache accesses", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x80, .numasks = LIBPFM_ARRAY_SIZE(snb_icache), .ngrp = 1, .umasks = snb_icache, }, { .name = "IDQ", .desc = "IDQ operations", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x79, .numasks = LIBPFM_ARRAY_SIZE(snb_idq), .ngrp = 1, .umasks = snb_idq, }, { .name = "IDQ_UOPS_NOT_DELIVERED", .desc = "Uops not delivered", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x9c, .numasks = LIBPFM_ARRAY_SIZE(snb_idq_uops_not_delivered), .ngrp = 1, .umasks = snb_idq_uops_not_delivered, }, { .name = "ILD_STALL", .desc = "Instruction Length Decoder stalls", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x87, .numasks = LIBPFM_ARRAY_SIZE(snb_ild_stall), .ngrp = 1, .umasks = snb_ild_stall, }, { .name = "INSTS_WRITTEN_TO_IQ", .desc = "Instructions written to IQ", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x17, .numasks = LIBPFM_ARRAY_SIZE(snb_insts_written_to_iq), .ngrp = 1, .umasks = snb_insts_written_to_iq, }, { .name = "INST_RETIRED", .desc = "Instructions retired", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xc0, .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_inst_retired), .ngrp = 1, .umasks = snb_inst_retired, }, { .name = "INSTRUCTION_RETIRED", .desc = "Number of instructions at retirement", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0x10000000full, .code = 0xc0, }, { .name = "INSTRUCTIONS_RETIRED", .desc = "This is an alias for INSTRUCTION_RETIRED", .modmsk = INTEL_V3_ATTRS, .equiv = "INSTRUCTION_RETIRED", .cntmsk = 0x10000000full, .code = 0xc0, }, { .name = "INT_MISC", .desc = "Miscellaneous internals", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xd, .numasks = LIBPFM_ARRAY_SIZE(snb_int_misc), .ngrp = 1, .umasks = snb_int_misc, }, { .name = "ITLB", .desc = "Instruction TLB", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xae, .numasks = LIBPFM_ARRAY_SIZE(snb_itlb), .ngrp = 1, .umasks = snb_itlb, }, { .name = "ITLB_MISSES", .desc = "Instruction TLB misses", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x85, .numasks = LIBPFM_ARRAY_SIZE(snb_dtlb_store_misses), .ngrp = 1, .umasks = snb_dtlb_store_misses, /* identical to actual umasks list for this event */ }, { .name = "L1D", .desc = "L1D cache", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x51, .numasks = LIBPFM_ARRAY_SIZE(snb_l1d), .ngrp = 1, .umasks = snb_l1d, }, { .name = "L1D_BLOCKS", .desc = "L1D is blocking", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xbf, .numasks = LIBPFM_ARRAY_SIZE(snb_l1d_blocks), .ngrp = 1, .umasks = snb_l1d_blocks, }, { .name = "L1D_PEND_MISS", .desc = "L1D pending misses", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0x4, .code = 0x48, .numasks = LIBPFM_ARRAY_SIZE(snb_l1d_pend_miss), .ngrp = 1, .umasks = snb_l1d_pend_miss, }, { .name = "L2_L1D_WB_RQSTS", .desc = "Writeback requests from L1D to L2", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x28, .numasks = LIBPFM_ARRAY_SIZE(snb_l2_l1d_wb_rqsts), .ngrp = 1, .umasks = snb_l2_l1d_wb_rqsts, }, { .name = "L2_LINES_IN", .desc = "L2 lines allocated", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xf1, .numasks = LIBPFM_ARRAY_SIZE(snb_l2_lines_in), .ngrp = 1, .umasks = snb_l2_lines_in, }, { .name = "L2_LINES_OUT", .desc = "L2 lines evicted", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xf2, .numasks = LIBPFM_ARRAY_SIZE(snb_l2_lines_out), .ngrp = 1, .umasks = snb_l2_lines_out, }, { .name = "L2_RQSTS", .desc = "L2 requests", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x24, .numasks = LIBPFM_ARRAY_SIZE(snb_l2_rqsts), .ngrp = 1, .umasks = snb_l2_rqsts, }, { .name = "L2_STORE_LOCK_RQSTS", .desc = "L2 store lock requests", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x27, .numasks = LIBPFM_ARRAY_SIZE(snb_l2_store_lock_rqsts), .ngrp = 1, .umasks = snb_l2_store_lock_rqsts, }, { .name = "L2_TRANS", .desc = "L2 transactions", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xf0, .numasks = LIBPFM_ARRAY_SIZE(snb_l2_trans), .ngrp = 1, .umasks = snb_l2_trans, }, { .name = "LAST_LEVEL_CACHE_MISSES", .desc = "This is an alias for L3_LAT_CACHE:MISS", .modmsk = INTEL_V3_ATTRS, .equiv = "L3_LAT_CACHE:MISS", .cntmsk = 0xff, .code = 0x412e, }, { .name = "LLC_MISSES", .desc = "Alias for LAST_LEVEL_CACHE_MISSES", .modmsk = INTEL_V3_ATTRS, .equiv = "LAST_LEVEL_CACHE_MISSES", .cntmsk = 0xff, .code = 0x412e, }, { .name = "LAST_LEVEL_CACHE_REFERENCES", .desc = "This is an alias for L3_LAT_CACHE:REFERENCE", .modmsk = INTEL_V3_ATTRS, .equiv = "L3_LAT_CACHE:REFERENCE", .cntmsk = 0xff, .code = 0x4f2e, }, { .name = "LLC_REFERENCES", .desc = "Alias for LAST_LEVEL_CACHE_REFERENCES", .modmsk = INTEL_V3_ATTRS, .equiv = "LAST_LEVEL_CACHE_REFERENCES", .cntmsk = 0xff, .code = 0x4f2e, }, { .name = "LD_BLOCKS", .desc = "Blocking loads", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x3, .numasks = LIBPFM_ARRAY_SIZE(snb_ld_blocks), .ngrp = 1, .umasks = snb_ld_blocks, }, { .name = "LD_BLOCKS_PARTIAL", .desc = "Partial load blocks", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x7, .numasks = LIBPFM_ARRAY_SIZE(snb_ld_blocks_partial), .ngrp = 1, .umasks = snb_ld_blocks_partial, }, { .name = "LOAD_HIT_PRE", .desc = "Load dispatches that hit fill buffer", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x4c, .numasks = LIBPFM_ARRAY_SIZE(snb_load_hit_pre), .ngrp = 1, .umasks = snb_load_hit_pre, }, { .name = "L3_LAT_CACHE", .desc = "Core-originated cacheable demand requests to L3", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x2e, .numasks = LIBPFM_ARRAY_SIZE(snb_l3_lat_cache), .ngrp = 1, .umasks = snb_l3_lat_cache, }, { .name = "MACHINE_CLEARS", .desc = "Machine clear asserted", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xc3, .numasks = LIBPFM_ARRAY_SIZE(snb_machine_clears), .ngrp = 1, .umasks = snb_machine_clears, }, { .name = "MEM_LOAD_UOPS_LLC_HIT_RETIRED", .desc = "L3 hit loads uops retired", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xd2, .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_mem_load_uops_llc_hit_retired), .ngrp = 1, .umasks = snb_mem_load_uops_llc_hit_retired, }, { .name = "MEM_LOAD_LLC_HIT_RETIRED", .desc = "L3 hit loads uops retired (deprecated use MEM_LOAD_UOPS_LLC_HIT_RETIRED)", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xd2, .equiv = "MEM_LOAD_UOPS_LLC_HIT_RETIRED", .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_mem_load_uops_llc_hit_retired), .ngrp = 1, .umasks = snb_mem_load_uops_llc_hit_retired, }, { .name = "MEM_LOAD_UOPS_MISC_RETIRED", .desc = "Loads and some non simd split loads uops retired", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xd4, .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_mem_load_uops_misc_retired), .ngrp = 1, .umasks = snb_mem_load_uops_misc_retired, }, { .name = "MEM_LOAD_MISC_RETIRED", .desc = "Loads and some non simd split loads uops retired (deprecated use MEM_LOAD_UOPS_MISC_RETIRED)", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xd4, .equiv = "MEM_LOAD_UOPS_MISC_RETIRED", .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_mem_load_uops_misc_retired), .ngrp = 1, .umasks = snb_mem_load_uops_misc_retired, }, { .name = "MEM_LOAD_UOPS_RETIRED", .desc = "Memory loads uops retired", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xd1, .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_mem_load_uops_retired), .ngrp = 1, .umasks = snb_mem_load_uops_retired, }, { .name = "MEM_LOAD_RETIRED", .desc = "Memory loads uops retired (deprecated use MEM_LOAD_UOPS_RETIRED)", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xd1, .equiv = "MEM_LOAD_UOPS_RETIRED", .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_mem_load_uops_retired), .ngrp = 1, .umasks = snb_mem_load_uops_retired, }, { .name = "MEM_TRANS_RETIRED", .desc = "Memory transactions retired", .modmsk = INTEL_V3_ATTRS | _INTEL_X86_ATTR_LDLAT, .cntmsk = 0x8, .code = 0xcd, .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_mem_trans_retired), .ngrp = 1, .umasks = snb_mem_trans_retired, }, { .name = "MEM_UOPS_RETIRED", .desc = "Memory uops retired", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xd0, .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_mem_uops_retired), .ngrp = 1, .umasks = snb_mem_uops_retired, }, { .name = "MEM_UOP_RETIRED", .desc = "Memory uops retired (deprecated use MEM_UOPS_RETIRED)", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xd0, .equiv = "MEM_UOPS_RETIRED", .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_mem_uops_retired), .ngrp = 1, .umasks = snb_mem_uops_retired, }, { .name = "MISALIGN_MEM_REF", .desc = "Misaligned memory references", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x5, .numasks = LIBPFM_ARRAY_SIZE(snb_misalign_mem_ref), .ngrp = 1, .umasks = snb_misalign_mem_ref, }, { .name = "OFFCORE_REQUESTS", .desc = "Offcore requests", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xb0, .numasks = LIBPFM_ARRAY_SIZE(snb_offcore_requests), .ngrp = 1, .umasks = snb_offcore_requests, }, { .name = "OFFCORE_REQUESTS_BUFFER", .desc = "Offcore requests buffer", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xb2, .numasks = LIBPFM_ARRAY_SIZE(snb_offcore_requests_buffer), .ngrp = 1, .umasks = snb_offcore_requests_buffer, }, { .name = "OFFCORE_REQUESTS_OUTSTANDING", .desc = "Outstanding offcore requests", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x60, .numasks = LIBPFM_ARRAY_SIZE(snb_offcore_requests_outstanding), .ngrp = 1, .umasks = snb_offcore_requests_outstanding, }, { .name = "OTHER_ASSISTS", .desc = "Count hardware assists", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xc1, .numasks = LIBPFM_ARRAY_SIZE(snb_other_assists), .ngrp = 1, .umasks = snb_other_assists, }, { .name = "PARTIAL_RAT_STALLS", .desc = "Partial Register Allocation Table stalls", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x59, .numasks = LIBPFM_ARRAY_SIZE(snb_partial_rat_stalls), .ngrp = 1, .umasks = snb_partial_rat_stalls, }, { .name = "RESOURCE_STALLS", .desc = "Resource related stall cycles", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xa2, .numasks = LIBPFM_ARRAY_SIZE(snb_resource_stalls), .ngrp = 1, .umasks = snb_resource_stalls, }, { .name = "RESOURCE_STALLS2", .desc = "Resource related stall cycles", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x5b, .numasks = LIBPFM_ARRAY_SIZE(snb_resource_stalls2), .ngrp = 1, .umasks = snb_resource_stalls2, }, { .name = "ROB_MISC_EVENTS", .desc = "Reorder buffer events", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xcc, .numasks = LIBPFM_ARRAY_SIZE(snb_rob_misc_events), .ngrp = 1, .umasks = snb_rob_misc_events, }, { .name = "RS_EVENTS", .desc = "Reservation station events", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x5e, .numasks = LIBPFM_ARRAY_SIZE(snb_rs_events), .ngrp = 1, .umasks = snb_rs_events, }, { .name = "SIMD_FP_256", .desc = "Counts 256-bit packed floating point instructions", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0x11, .numasks = LIBPFM_ARRAY_SIZE(snb_simd_fp_256), .ngrp = 1, .umasks = snb_simd_fp_256, }, { .name = "SQ_MISC", .desc = "SuperQ events", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xf4, .numasks = LIBPFM_ARRAY_SIZE(snb_sq_misc), .ngrp = 1, .umasks = snb_sq_misc, }, { .name = "TLB_FLUSH", .desc = "TLB flushes", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xbd, .numasks = LIBPFM_ARRAY_SIZE(snb_tlb_flush), .ngrp = 1, .umasks = snb_tlb_flush, }, { .name = "UNHALTED_CORE_CYCLES", .desc = "Count core clock cycles whenever the clock signal on the specific core is running (not halted)", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0x20000000full, .code = 0x3c, }, { .name = "UNHALTED_REFERENCE_CYCLES", .desc = "Unhalted reference cycles", .modmsk = INTEL_FIXED3_ATTRS, .cntmsk = 0x400000000ull, .code = 0x0300, /* pseudo encoding */ .flags = INTEL_X86_FIXED, }, { .name = "UOPS_DISPATCHED", .desc = "Uops dispatched", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xb1, .numasks = LIBPFM_ARRAY_SIZE(snb_uops_dispatched), .ngrp = 1, .umasks = snb_uops_dispatched, }, { .name = "UOPS_DISPATCHED_PORT", .desc = "Uops dispatch to specific ports", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xa1, .numasks = LIBPFM_ARRAY_SIZE(snb_uops_dispatched_port), .ngrp = 1, .umasks = snb_uops_dispatched_port, }, { .name = "UOPS_ISSUED", .desc = "Uops issued", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xe, .numasks = LIBPFM_ARRAY_SIZE(snb_uops_issued), .ngrp = 1, .umasks = snb_uops_issued, }, { .name = "UOPS_RETIRED", .desc = "Uops retired", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xff, .code = 0xc2, .flags= INTEL_X86_PEBS, .numasks = LIBPFM_ARRAY_SIZE(snb_uops_retired), .ngrp = 1, .umasks = snb_uops_retired, }, { .name = "CYCLE_ACTIVITY", .desc = "Stalled cycles", .modmsk = INTEL_V3_ATTRS & ~_INTEL_X86_ATTR_C, .cntmsk = 0xff, .code = 0xa3, .numasks = LIBPFM_ARRAY_SIZE(snb_cycle_activity), .ngrp = 1, .umasks = snb_cycle_activity, }, { .name = "OFFCORE_RESPONSE_0", .desc = "Offcore response event (must provide at least one request type and either any_response or any combination of supplier + snoop)", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xf, .code = 0x1b7, .flags= INTEL_X86_NHM_OFFCORE, .numasks = LIBPFM_ARRAY_SIZE(snb_offcore_response), .ngrp = 3, .umasks = snb_offcore_response, }, { .name = "OFFCORE_RESPONSE_1", .desc = "Offcore response event (must provide at least one request type and either any_response or any combination of supplier + snoop)", .modmsk = INTEL_V3_ATTRS, .cntmsk = 0xf, .code = 0x1bb, .flags= INTEL_X86_NHM_OFFCORE, .numasks = LIBPFM_ARRAY_SIZE(snb_offcore_response), .ngrp = 3, .umasks = snb_offcore_response, /* identical to actual umasks list for this event */ }, }; <file_sep>include ../../../common/make.config all: g++ buffer_address.cpp ${OPENCL_LIB} -o buffer_address clean: rm buffer_address <file_sep>all: g++ -I /usr/src/gdk/nvml/include -I /usr/include/nvidia/gdk -c -o PowerUsage.o PowerUsage.cpp g++ PowerUsage.o -lnvidia-ml -L /usr/src/gdk/nvml/lib/ -o PowerUsage rm PowerUsage.o clean: rm PowerUsage <file_sep>include ../../common/make.config all: gcc matrix.cpp ${OPENCL_LIB} -o matrix clean: rm matrix <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <time.h> #include <math.h> #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif /* Macros */ #define WORK_GROUP_SIZE 16 #define CL_FILE_NAME "launch.cl" #define BINARY_FILE_NAME "launch.bin" #define KERNEL_NAME "LaunchOrderTest" #define POWER_LOG_FILE_LEN 300 #define CHECK_CL_ERROR(error) \ do \ { \ if ((error)) \ { \ fprintf(stderr, "OpenCL API error %d, in %s:%d, function '%s'\n", (error), __FILE__, __LINE__, __FUNCTION__); \ exit(1); \ } \ } while(0) /* Control struct */ struct OpenCL_Ctrl { int platform_id; int device_id; bool timing; int localSize_1, localSize_2; int dataSizeW, dataSizeH, inputByte, outputByte; char powerFile[POWER_LOG_FILE_LEN]; OpenCL_Ctrl() : platform_id(0), device_id(0), timing(false), dataSizeH(32), dataSizeW(32) {sprintf(powerFile, "KernelExecution.log");} } g_opencl_ctrl; void PrintTimingInfo(FILE* fptr) { struct timeval current; unsigned long long curr_time; gettimeofday(&current, NULL); curr_time = current.tv_sec * 1000 + current.tv_usec / 1000; fprintf(fptr, "%llu\n", curr_time); } void CommandParser(int argc, char *argv[]) { int cmd; while(1) { cmd = getopt(argc, argv, "P:D:TW:H:O:L:l:"); /* finish parsing */ if (cmd == -1) break; switch (cmd) { case 'O': sprintf(g_opencl_ctrl.powerFile, "%s", optarg); break; case 'P': g_opencl_ctrl.platform_id = atoi(optarg); break; case 'D': g_opencl_ctrl.device_id = atoi(optarg); break; case 'T': g_opencl_ctrl.timing = true; break; case 'H': { int size = atoi(optarg); g_opencl_ctrl.dataSizeH = size; } break; case 'W': { int size = atoi(optarg); g_opencl_ctrl.dataSizeW = size; } break; case 'L': { int size = atoi(optarg); g_opencl_ctrl.localSize_1 = size; } break; case 'l': { int size = atoi(optarg); g_opencl_ctrl.localSize_2 = size; } break; case '?': fprintf(stderr, "Unknown option -%c\n", optopt); break; /* should not be here */ default: break; } } /* Print the setting */ g_opencl_ctrl.inputByte = sizeof(int); g_opencl_ctrl.outputByte = g_opencl_ctrl.dataSizeH * g_opencl_ctrl.dataSizeW * sizeof(int) / (g_opencl_ctrl.localSize_1 * g_opencl_ctrl.localSize_2); } void GetPlatformAndDevice(cl_platform_id & target_platform, cl_device_id & target_device) { cl_platform_id* platforms; cl_device_id* devices; cl_uint count; cl_int error; size_t length; char *queryString; /* Find platform */ error = clGetPlatformIDs(0, NULL, &count); CHECK_CL_ERROR(error); platforms = (cl_platform_id *)malloc(sizeof(cl_platform_id) * count); clGetPlatformIDs(count, platforms, NULL); if (g_opencl_ctrl.platform_id >= count) {fprintf(stderr, "Error: Cannot find selected platform\n"); exit(1);} target_platform = platforms[g_opencl_ctrl.platform_id]; /* Find device */ error = clGetDeviceIDs(target_platform, CL_DEVICE_TYPE_ALL, 0, NULL, &count); CHECK_CL_ERROR(error); devices = (cl_device_id *)malloc(sizeof(cl_device_id) * count); clGetDeviceIDs(target_platform, CL_DEVICE_TYPE_ALL, count, devices, NULL); if (g_opencl_ctrl.device_id >= count) {fprintf(stderr, "Error: Cannot find selected device\n"); exit(1);} target_device = devices[g_opencl_ctrl.device_id]; /* Get device name */ error = clGetDeviceInfo(target_device, CL_DEVICE_NAME, 0, NULL, &length); CHECK_CL_ERROR(error); queryString = (char *)malloc(sizeof(char) * length); clGetDeviceInfo(target_device, CL_DEVICE_NAME, length, queryString, NULL); fprintf(stderr, "Device selected: '%s'\n", queryString); /* Free the space */ free(platforms); free(devices); free(queryString); } void CreateAndBuildProgram(cl_program &target_program, cl_context context, cl_device_id device, char *fileName) { FILE *fptr; size_t programSize; char *programSource; cl_int error; fptr = fopen(fileName, "r"); if (fptr == NULL) { fprintf(stderr, "No such file: '%s'\n", fileName); exit(1); } /* Read program source */ fseek(fptr, 0, SEEK_END); programSize = ftell(fptr); rewind(fptr); programSource = (char *)malloc(sizeof(char) * (programSize + 1)); programSource[programSize] = '\0'; fread(programSource, sizeof(char), programSize, fptr); fclose(fptr); /* Create and build cl_program object */ target_program = clCreateProgramWithSource(context, 1, (const char **)(&programSource), &programSize, &error); CHECK_CL_ERROR(error); free(programSource); error = clBuildProgram(target_program, 1, &device, "-cl-opt-disable", NULL, NULL); //error = clBuildProgram(target_program, 1, &device, NULL, NULL, NULL); if (error < 0) { size_t logSize; char *programBuildLog; error = clGetProgramBuildInfo(target_program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize); CHECK_CL_ERROR(error); programBuildLog = (char *)malloc(sizeof(char) * (logSize + 1)); error = clGetProgramBuildInfo(target_program, device, CL_PROGRAM_BUILD_LOG, logSize + 1, programBuildLog, NULL); CHECK_CL_ERROR(error); fprintf(stderr, "%s\n", programBuildLog); free(programBuildLog); exit(1); } #if 0 { size_t binarySize; error = clGetProgramInfo(target_program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t), &binarySize, NULL); CHECK_CL_ERROR(error); unsigned char *binary = (unsigned char *) malloc(sizeof(unsigned char) * binarySize); error = clGetProgramInfo(target_program, CL_PROGRAM_BINARIES, binarySize, &binary, NULL); CHECK_CL_ERROR(error); FILE *fptr = fopen(BINARY_FILE_NAME, "w"); fprintf(fptr, "%s", binary); fclose(fptr); } #endif free(fileName); } void HostDataCreation(void* &input, void* &output) { srand(time(NULL)); input = malloc(g_opencl_ctrl.inputByte); output = malloc(g_opencl_ctrl.outputByte); ((int *)input)[0] = 0; } int main(int argc, char *argv[]) { FILE* g_fptr; cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue command_queue; cl_program program; cl_kernel kernel; cl_mem inputBuffer, outputBuffer; cl_int error; int inputSize; size_t globalSize[2], localSize[2]; struct timeval startTime, endTime; void* inputArray = NULL; void* outputArray = NULL; /* Parse options */ CommandParser(argc, argv); g_fptr = fopen(g_opencl_ctrl.powerFile, "a"); if (!g_fptr) exit(1); HostDataCreation(inputArray, outputArray); GetPlatformAndDevice(platform, device); /* Create context */ context = clCreateContext(NULL, 1, &device, NULL, NULL, &error); CHECK_CL_ERROR(error); /* Create command queue */ command_queue = clCreateCommandQueue(context, device, 0, &error); CHECK_CL_ERROR(error); /* Create program */ CreateAndBuildProgram(program, context, device, strdup(CL_FILE_NAME)); /* Create kernels */ kernel = clCreateKernel(program, KERNEL_NAME, &error); CHECK_CL_ERROR(error); /* Create buffers */ inputBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, g_opencl_ctrl.inputByte, inputArray, &error); CHECK_CL_ERROR(error); outputBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, g_opencl_ctrl.outputByte, NULL, &error); CHECK_CL_ERROR(error); /* Execute kernels */ error = clSetKernelArg(kernel, 0, sizeof(cl_mem), &inputBuffer); CHECK_CL_ERROR(error); error = clSetKernelArg(kernel, 1, sizeof(cl_mem), &outputBuffer); CHECK_CL_ERROR(error); error = clSetKernelArg(kernel, 2, sizeof(int), &g_opencl_ctrl.dataSizeW); CHECK_CL_ERROR(error); if (g_opencl_ctrl.timing) gettimeofday(&startTime, NULL); globalSize[0] = g_opencl_ctrl.dataSizeW; globalSize[1] = g_opencl_ctrl.dataSizeH; localSize[0] = g_opencl_ctrl.localSize_1; localSize[1] = g_opencl_ctrl.localSize_2; PrintTimingInfo(g_fptr); error = clEnqueueNDRangeKernel(command_queue, kernel, 2, NULL, globalSize, localSize, 0, NULL, NULL); CHECK_CL_ERROR(error); error = clFinish(command_queue); CHECK_CL_ERROR(error); PrintTimingInfo(g_fptr); if (g_opencl_ctrl.timing) gettimeofday(&endTime, NULL); fclose(g_fptr); /* Read the output */ error = clEnqueueReadBuffer(command_queue, outputBuffer, CL_TRUE, 0, g_opencl_ctrl.outputByte, outputArray, 0, NULL, NULL); CHECK_CL_ERROR(error); { fprintf(stdout, "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t -----> dim 0\n"); int* result = (int*) outputArray; for (int i = 0 ; i < g_opencl_ctrl.dataSizeH / g_opencl_ctrl.localSize_2 ; i ++ ) { for (int j = 0 ; j < g_opencl_ctrl.dataSizeW / g_opencl_ctrl.localSize_1 ; j ++ ) fprintf(stdout, "%6d\t", result[i * g_opencl_ctrl.dataSizeW / g_opencl_ctrl.localSize_1 + j]); fprintf(stdout, "\n"); } fprintf(stdout, "\n"); } /* Release object */ clReleaseKernel(kernel); clReleaseMemObject(inputBuffer); clReleaseMemObject(outputBuffer); clReleaseProgram(program); clReleaseCommandQueue(command_queue); clReleaseContext(context); free(inputArray); free(outputArray); if (g_opencl_ctrl.timing) { unsigned long long start, end; start = startTime.tv_sec * 1000000 + startTime.tv_usec; end = endTime.tv_sec * 1000000 + endTime.tv_usec; fprintf(stderr, "Kernel execution time: %llu ms\n", (end - start) / 1000); fprintf(stdout, "%llu\n", (end - start) * 1000); } fprintf(stderr, "DONE.\n"); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif using namespace std; template <typename T> void ShowCLDeviceNumberInfo(cl_device_id device, cl_device_info param, const char *name) { T *result; size_t num; cl_int err; err = clGetDeviceInfo(device, param, 0, NULL, &num); if (err < 0) { printf("Couldn't get platform info : %d\n", err); exit(1); } result = new T[ num/sizeof(T) ]; err = clGetDeviceInfo(device, param, num, result, NULL); printf("\t%s: ", name); for (int i = 0 ; i < num / sizeof(T) ; i ++) printf("%llu ", (unsigned long long int)(result[i])); printf("\n"); delete [] result; } void ShowCLDeviceStringInfo(cl_device_id device, cl_device_info param, const char *name) { char *result; size_t len; cl_int err; err = clGetDeviceInfo(device, param, 0, NULL, &len); if (err < 0) { printf("Couldn't get platform info : %d\n", err); exit(1); } result = new char [len]; clGetDeviceInfo(device, param, len, result, NULL); printf("\t%s : %s\n", name, result); delete [] result; } void ShowCLPlatformInfo(cl_platform_id platform, cl_platform_info param, const char *name) { char *result; size_t len; cl_int err; err = clGetPlatformInfo(platform, param, 0, NULL, &len); if (err < 0) { printf("Couldn't get platform info : %d\n", err); exit(1); } result = new char [len]; clGetPlatformInfo(platform, param, len, result, NULL); printf("%s : %s\n", name, result); delete [] result; } void GetCLDeviceInfo(cl_device_id device, int index) { cl_device_type deviceType; printf("\n\tDevice %d\n", index); clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(deviceType), &deviceType, NULL); printf("\tType : "); if (deviceType & CL_DEVICE_TYPE_DEFAULT) printf("Default "); if (deviceType & CL_DEVICE_TYPE_CPU) printf("CPU "); if (deviceType & CL_DEVICE_TYPE_GPU) printf("GPU "); if (deviceType & CL_DEVICE_TYPE_ACCELERATOR) printf("Accelerator "); printf("\n"); ShowCLDeviceStringInfo(device, CL_DEVICE_NAME, "Name"); ShowCLDeviceNumberInfo <cl_uint> (device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, "Work item dim"); ShowCLDeviceNumberInfo <size_t> (device, CL_DEVICE_MAX_WORK_ITEM_SIZES, "Work item size"); ShowCLDeviceNumberInfo <size_t> (device, CL_DEVICE_MAX_WORK_GROUP_SIZE, "Work group size"); ShowCLDeviceNumberInfo <cl_uint> (device, CL_DEVICE_MAX_COMPUTE_UNITS, "Compute units"); ShowCLDeviceStringInfo(device, CL_DEVICE_VENDOR, "Vendor"); ShowCLDeviceStringInfo(device, CL_DEVICE_VERSION, "Device Version"); ShowCLDeviceStringInfo(device, CL_DRIVER_VERSION, "Driver Version"); ShowCLDeviceStringInfo(device, CL_DEVICE_EXTENSIONS, "Extensions"); } void GetCLPlatformInfo(cl_platform_id platform, int index) { cl_device_id *devices; cl_uint deviceNum; cl_int err; printf("\n================= Platform %d ==========================\n", index); ShowCLPlatformInfo(platform, CL_PLATFORM_NAME, "Name"); ShowCLPlatformInfo(platform, CL_PLATFORM_VENDOR, "Vendor"); ShowCLPlatformInfo(platform, CL_PLATFORM_VERSION, "Version"); ShowCLPlatformInfo(platform, CL_PLATFORM_EXTENSIONS, "Extensions"); err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 0, NULL, &deviceNum); if(err < 0) { printf("Couldn't identify a device : %d\n", err); exit(1); } devices = new cl_device_id [deviceNum]; clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, deviceNum, devices, NULL); for (int index = 0 ; index < deviceNum ; index ++) GetCLDeviceInfo(devices[index], index); delete [] devices; printf("\n"); } int main() { cl_platform_id *platforms; cl_uint platformNum; cl_int err; err = clGetPlatformIDs(0, NULL, &platformNum); if(err < 0) { printf("Couldn't identify a platform : %d\n", err); exit(1); } platforms = new cl_platform_id [platformNum]; clGetPlatformIDs(platformNum, platforms, NULL); for (int index = 0 ; index < platformNum ; index ++) GetCLPlatformInfo(platforms[index], index); delete [] platforms; } <file_sep>#include <stdio.h> #include <stdlib.h> #include "kernelParser.h" // use to maintain the RAW data hazard of specific identifier (store the latest operation) void UpdateSymbolTable(OP_List* source, OP_List* update) { SymbolTableEntry* tmp = source->table_entry; if (tmp != NULL) { tmp->op = update->op_tail; } } // use to find the dependency due to RAW data hazard of specific identifier SymbolTableEntry* GetTableEntry(char* name) { if (name != NULL) { SymbolTableLevel* currLevel = symTable->level_tail; int cmpResult; while (currLevel) { SymbolTableEntry* currEntry = currLevel->entry_head; while (currEntry) { cmpResult = strcmp(currEntry->sym_name, name); if (cmpResult == 0) { return currEntry; } else if (cmpResult > 0) { break; } currEntry = currEntry->next; } currLevel = currLevel->prev; } } return NULL; } TypeDescriptor FindSymbolInTable(char* name, SYMBOL_TYPE type) { SymbolTableLevel* currLevel = symTable->level_tail; int cmpResult; while (currLevel) { SymbolTableEntry* currEntry = currLevel->entry_head; while (currEntry) { cmpResult = strcmp(currEntry->sym_name, name); if (cmpResult == 0) { if (currEntry->sym_type == type) { return currEntry->type_desc; } else { if (type == SYMBOL_IDENTIFIER) fprintf(stderr, "[Error] Symbol \'%s\' not found in symbolTable\n", name); return CreateTypeDescriptor(NONE_TYPE, NULL); } } else if (cmpResult > 0) { break; } currEntry = currEntry->next; } currLevel = currLevel->prev; } if (type == SYMBOL_IDENTIFIER) fprintf(stderr, "[Error] Symbol \'%s\' not found in symbolTable\n", name); return CreateTypeDescriptor(NONE_TYPE, NULL); } void AddParamToSymbolTable(TypeDescriptor type_desc, char* name, SYMBOL_TYPE sym_type) { SymbolTableLevel* currLevel = symTable->level_tail; SymbolTableEntry* tmp = CreateSymbolTableEntry(type_desc, name, sym_type, NULL); if (currLevel->entry_head == NULL) { currLevel->entry_head = tmp; currLevel->entry_tail = tmp; } else { int cmp_result; SymbolTableEntry *prev = NULL; SymbolTableEntry *iterEntry = currLevel->entry_head; while(1) { if (!iterEntry) // to the end { prev->next = tmp; currLevel->entry_tail = tmp; break; } cmp_result = strcmp(iterEntry->sym_name, tmp->sym_name); if (cmp_result > 0) { if (prev) prev->next = tmp; tmp->next = iterEntry; if (currLevel->entry_head == iterEntry) currLevel->entry_head = tmp; return; } else if (cmp_result == 0) { fprintf(stderr, "[Error] Redefine symbol \'%s\'. \n", tmp->sym_name); return; } else { prev = iterEntry; iterEntry = iterEntry->next; } } } } SymbolTableEntry* CreateSymbolTableEntry(TypeDescriptor type_desc, char* name, SYMBOL_TYPE sym_type, Operation* op) { SymbolTableEntry* tmp = (SymbolTableEntry*) malloc(sizeof(SymbolTableEntry)); tmp->type_desc = type_desc; tmp->sym_name = name; tmp->sym_type = sym_type; tmp->next = NULL; tmp->op = op; tmp->subEntry_head = NULL; tmp->subEntry_tail = NULL; if (type_desc.type == STRUCT_TYPE && type_desc.struct_desc) { StructMember* iter = type_desc.struct_desc->member_head; SymbolTableEntry* subEntry; while (iter) { // TODO struct initialization subEntry = CreateSymbolTableEntry(iter->type_desc, iter->name, sym_type, op); if (tmp->subEntry_head == NULL) { tmp->subEntry_head = subEntry; tmp->subEntry_tail = subEntry; } else { tmp->subEntry_tail->next = subEntry; tmp->subEntry_tail = subEntry; } iter = iter->next; } } return tmp; } // Add to the last level in symTable void AddIDListToSymbolTable(TypeDescriptor type_desc, ID_List* IDs, SYMBOL_TYPE sym_type) { Identifier* iter = IDs->id_head; SymbolTableLevel* currLevel = symTable->level_tail; while (iter) { SymbolTableEntry* tmp = CreateSymbolTableEntry(type_desc, iter->name, sym_type, iter->op); if (currLevel->entry_head == NULL) { currLevel->entry_head = tmp; currLevel->entry_tail = tmp; } else { int cmp_result; SymbolTableEntry *prev = NULL; SymbolTableEntry *iterEntry = currLevel->entry_head; while(1) { if (!iterEntry) // to the end { prev->next = tmp; currLevel->entry_tail = prev; break; } cmp_result = strcmp(iterEntry->sym_name, tmp->sym_name); if (cmp_result > 0) { if (prev) prev->next = tmp; tmp->next = iterEntry; if (currLevel->entry_head == iterEntry) currLevel->entry_head = tmp; break; } else if (cmp_result == 0) { fprintf(stderr, "[Error] Redefine symbol \'%s\'. \n", tmp->sym_name); break; } else { prev = iterEntry; iterEntry = iterEntry->next; } } } iter = iter->next; } } void CreateSymbolTable() { if (symTable != NULL) { fprintf(stderr, "[Error] Symbol Table has already been created\n"); return; } symTable = (SymbolTable*) malloc(sizeof(SymbolTable)); symTable->level_head = NULL; symTable->level_tail = NULL; } void ReleaseSymbolTable() { if (symTable->level_head != NULL) { fprintf(stderr, "[Error] Need to release all the levels first\n"); return; } free (symTable); } void ReleaseSymbolTableLevel() { if (!symTable) fprintf(stderr, "[Error] Need to create symbol table first\n"); else { SymbolTableLevel *tmp = symTable->level_tail; SymbolTableEntry *iter = tmp->entry_head; SymbolTableEntry *next; symTable->level_tail = symTable->level_tail->prev; if (symTable->level_tail == NULL) symTable->level_head = NULL; while (iter) { next = iter->next; free(iter->sym_name); free(iter); iter = next; } free (tmp); } } void CreateSymbolTableLevel() { if (!symTable) fprintf(stderr, "[Error] Need to create symbol table first\n"); else { SymbolTableLevel *tmp = (SymbolTableLevel *)malloc(sizeof(SymbolTableLevel)); tmp->prev = NULL; tmp->next = NULL; tmp->entry_head = NULL; tmp->entry_tail = NULL; if (!symTable->level_head) { symTable->level_head = tmp; symTable->level_tail = tmp; } else { tmp->prev = symTable->level_tail; symTable->level_tail->next = tmp; symTable->level_tail = tmp; } } } <file_sep>include ../common/make.config all: g++ WorkGroupInterleavingTest.cpp ${OPENCL_LIB} -o WorkGroupInterleavingTest clean: rm WorkGroupInterleavingTest <file_sep>#ifndef _PAPI_WRAPPER_HPP_ #define _PAPI_WRAPPER_HPP_ #include "papi_test.h" #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #define CHECK_PAPI_ERROR(error, name) \ do \ { \ if (error != PAPI_OK) \ { \ fprintf(stderr, "PAPI API '%s' error at line %d: %s (%d)\n", name, __LINE__, PAPI_strerror(error), error); \ exit(1); \ } \ } while(0) class PAPIWrapper { private: int eventCount; int eventSet; int *eventCode; char **eventName; long long *eventValue; void initialize() { int ret; ret = PAPI_library_init(PAPI_VER_CURRENT); if (ret != PAPI_VER_CURRENT) { fprintf(stderr, "PAPI API 'PAPU_library_init' error !\n"); exit(1); } fprintf(stdout, "PAPI_VERSION: %d.%d.%d\n", PAPI_VERSION_MAJOR( PAPI_VERSION ), PAPI_VERSION_MINOR( PAPI_VERSION ), PAPI_VERSION_REVISION( PAPI_VERSION ) ); ret = PAPI_create_eventset(&eventSet); CHECK_PAPI_ERROR(ret, "PAPI_create_eventset"); } void destroy() { int ret; ret = PAPI_cleanup_eventset(eventSet); CHECK_PAPI_ERROR(ret, "PAPI_cleanup_eventset"); ret = PAPI_destroy_eventset(&eventSet); CHECK_PAPI_ERROR(ret, "PAPI_destroy_eventset"); PAPI_shutdown(); } public: PAPIWrapper(): eventCount(0), eventSet(PAPI_NULL), eventCode(NULL), eventName(NULL), eventValue(NULL) { initialize(); } ~PAPIWrapper() { if (eventCode) free(eventCode); if (eventName) { for (int i = 0 ; i < eventCount ; i ++) free(eventName[i]); free(eventName); } if (eventValue) free(eventValue); } void Start() { int ret; ret = PAPI_start(eventSet); CHECK_PAPI_ERROR(ret, "PAPI_start"); } void Stop() { int ret; ret = PAPI_stop(eventSet, eventValue); CHECK_PAPI_ERROR(ret, "PAPI_stop"); destroy(); for (int i = 0 ; i < eventCount ; i ++) printf("%-40s --> %lld\n", eventName[i], eventValue[i]); } void PrintResult(char *fileName) { FILE *fptr = fopen(fileName, "w"); for (int i = 0 ; i < eventCount ; i ++) fprintf(fptr, "%-40s %lld\n", eventName[i], eventValue[i]); fclose(fptr); free(fileName); } void AddEvent(int count, ...) { if (eventCount != 0) { fprintf(stderr, "PAPIWrapper::AddEvent() can only be called once\n"); exit(1); } int ret; va_list argList; eventCount = count; eventName = (char **) malloc(sizeof(char *) * eventCount); eventCode = (int *) malloc(sizeof(int) * eventCount); eventValue = (long long *) malloc(sizeof(long long) * eventCount); va_start(argList, count); for (int i = 0; i < eventCount ; i ++) { eventName[i] = va_arg(argList, char*); ret = PAPI_event_name_to_code(eventName[i], &eventCode[i]); CHECK_PAPI_ERROR(ret, "PAPI_event_name_to_code"); fprintf(stdout, "[papi_wrapper] Name %s --- Code %#x\n", eventName[i], eventCode[i]); } ret = PAPI_add_events(eventSet, eventCode, eventCount); CHECK_PAPI_ERROR(ret, "PAPI_add_events"); va_end(argList); } }; #endif <file_sep>all: g++ CacheSim.cpp -o CacheSim clean: rm CacheSim
85f77b64792c1b067c44bef67c020f2cb445a5cb
[ "C", "Makefile", "C++" ]
28
Makefile
tony1223yu/GPGPU_MicroBenchmark_Suite
16d778b741322cbd4994dc3a9a99a43bc4d4ecc2
2387fd30c52c66c274584498d52b804fbb01afa1
refs/heads/master
<file_sep># trigram-story-generator<file_sep>/* * TCSS 435 - Autumn 2019 * Programming Assignment 3 - Random Story */ package model; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Random; /** * Model for a Unigram * A unigram is a string, and contains a list of bigrams. * @author <NAME> * @version 12/1/19 */ public class Unigram { /**The string representation of a unigram.*/ private String unigramString; /**The list of bigrams*/ private List<Bigram> bigramList; /** * Constructor * @param str */ public Unigram(String str) { this.unigramString = str; bigramList = new ArrayList<Bigram>(); } /** * Returns the unigram string. * @return */ public String getString() { return unigramString; } /** * Returns the bigram list. * @return */ public List<Bigram> getList() { return bigramList; } /** * Adds a bigram to the bigram list * @param b */ public void addToList(Bigram b) { bigramList.add(b); } /** * Checks if a bigram exists in the bigram list. * @param str * @return */ public boolean containsBigram(String str) { return bigramList.stream().anyMatch(bigram -> bigram.getString().equals(str)); } /** * Returns a bigram in the bigram list matching the conditions. * @param b * @return */ public Bigram findInList(Bigram b) { if(b == null) { System.out.println("Bigram Token is null"); } for(Bigram bigramInList : bigramList) { if(bigramInList.equals(b)) { return bigramInList; } } return null; } /** * Chooses a ranodm bigram from the list. * @return */ public Bigram chooseRandomBigram() { Random rand = new Random(); int randomIndex = rand.nextInt(bigramList.size()); return bigramList.get(randomIndex); } /** * Returns an integer representing the hashcode of this Unigram. */ @Override public int hashCode() { return Objects.hash(unigramString, bigramList); } /** * Checks if two Unigrams are equal. */ @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj == null || this.getClass() != obj.getClass()) { return false; } Unigram otherUnigram = (Unigram) obj; if(otherUnigram.getString() == null || !this.getString().equals(otherUnigram.getString())) { return false; } if(otherUnigram.getList().size() != this.bigramList.size()) { return false; } List<Bigram> otherBigramList = otherUnigram.getList(); for(int i = 0; i < bigramList.size(); i++) { if(!bigramList.get(i).getString().equals(otherBigramList.get(i).getString())) { return false; } } return true; } } <file_sep>/* * TCSS 435 - Autumn 2019 * Programming Assignment 3 - Random Story */ package model; import java.util.Objects; /** * Model for a trigram. * A trigram consists of a string, and frequency. * @author <NAME> * */ public class Trigram { /**String representation of a trigram.*/ private String trigramString; /**Frequency that this trigram appears given the parent bigram and unigram.*/ private int frequency; /** * Constructor * @param str */ public Trigram(String str) { trigramString = str; frequency = 1; } /** * Returns the string representation of a Trigram. * @return */ public String getString() { return trigramString; } /** * Increases the frequency of the trigram by one. */ public void incrementFrequency() { frequency++; } /** * Returns the frequency. * @return */ public int getFrequency() { return frequency; } /** * Returns an integer representing the hashcode of this Trigram. */ @Override public int hashCode() { return Objects.hash(trigramString, frequency); } /** * Checks if two Trigrams are equal. */ @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj == null || this.getClass() != obj.getClass()) { return false; } Trigram otherTrigram = (Trigram) obj; if(otherTrigram.getString() == null || !this.getString().equals(otherTrigram.getString())) { return false; } return true; } } <file_sep>/* * TCSS 435 - Autumn 2019 * Programming Assignment 3 - Random Story */ package model; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Random; /** * Model for a bigram. * Consists of a string, and a list of trigrams. * @author <NAME> * @version 12/1/19 */ public class Bigram { /**String representation of a trigram.*/ private String bigramString; /**List of trigrams*/ private List<Trigram> trigramList; /** * Constructor * @param str */ public Bigram(String str) { bigramString = str; trigramList = new ArrayList<Trigram>(); } /** * Returns trigram string. * @return */ public String getString() { return bigramString; } /** * Returns list of trigrams. * @return */ public List<Trigram> getTrigramList() { return trigramList; } /** * Adds a trigram to the trigram list. * @param t */ public void addToList(Trigram t) { trigramList.add(t); } /** * Checks if a trigram exists in the trigram list. * @param str * @return */ public boolean containsTrigram(String str) { return trigramList.stream().anyMatch(trigram -> trigram.getString().equals(str)); } /** * Returns a trigram from the trigram list matching the conditions. * @param t * @return */ public Trigram findInList(Trigram t) { if(t == null) { System.out.println("Trigram Token is Null"); return null; } for(Trigram trigramInList : trigramList) { if(trigramInList.equals(t)) { return trigramInList; } } return null; } /** * Chooses a trigram based on probability given the unigram, and bigram. * @return */ public Trigram chooseProbabilisticTrigram() { Random rand = new Random(); int totalTrigramCount = 0; for(Trigram t : trigramList) { totalTrigramCount += t.getFrequency(); } int randomWeight = (int) Math.ceil(rand.nextDouble() * totalTrigramCount); int sumWeight = 0; for(Trigram t : trigramList) { sumWeight += t.getFrequency(); if(sumWeight >= randomWeight) { return t; } } return null; } /** * Returns an integer representing the hashcode of this bigram. */ @Override public int hashCode() { return Objects.hash(bigramString, trigramList); } /** * Checks if two bigrams are equal. */ @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj == null || this.getClass() != obj.getClass()) { return false; } Bigram otherBigram = (Bigram) obj; if(otherBigram.getString() == null || !this.getString().equals(otherBigram.getString())) { return false; } return true; } }
1a6c634dbfd4742dfcfdf9102baf2dc7ab0d3929
[ "Markdown", "Java" ]
4
Markdown
Verex000/trigram-story-generator
e4710cf9158352c3eed0b3748bd6013b50793588
dc09754fda8c5038baed0f82af000a7f819d9892
refs/heads/master
<repo_name>PrameshKarki/Note-App<file_sep>/index.js let myNoteTitle = document.getElementById('title'); let myNoteContent = document.getElementById('note'); let addNoteBtn = document.getElementById('addNote'); let noteObject; showNotes(); addNoteBtn.addEventListener('click', function (e) { let notes = localStorage.getItem('notes'); if (notes == null) { noteObject = []; } else { noteObject = JSON.parse(notes); } //Define Object let tempObject = { content: "", title: '', date: '' } tempObject.content = myNoteContent.value; if (tempObject.content.length != 0) { tempObject.title = myNoteTitle.value; tempObject.date = currentDate(); noteObject.push(tempObject); localStorage.setItem('notes', JSON.stringify(noteObject)); myNoteTitle.value = ''; myNoteContent.value = ''; showNotes(); } else { alert('You must write something to add'); } }) //Function that returs current date function currentDate() { let today = new Date(); let dd = today.getDate(); let mm = today.getMonth() + 1; let yy = today.getFullYear(); if (dd < 10) dd = '0' + dd; if (mm < 10) mm = '0' + mm; today = dd + '/' + mm + '/' + yy; return today; } //Function to show Notes function showNotes() { let notes = localStorage.getItem('notes'); if (notes == null) { noteObject = []; } else { noteObject = JSON.parse(notes); } let gridContainer = document.getElementById('gridContainer'); let html = ''; noteObject.forEach(function (element, index) { html += `<div class="noteCard"> <div class="heading"> <p>Note No:${index + 1}</p> <p>Title:${element.title}</p> <p>Date:${element.date}</p> </div> <div class="content"> <p>${element.content}</p> </div> <button id=${index} onclick=deleteNote(this.id) class="deleteBtn">Delete Note</button> </div>` }); if (noteObject.length != 0) { gridContainer.innerHTML = html; } else { gridContainer.innerHTML = `Container is Empty!`; } } function deleteNote(index) { let notes = localStorage.getItem('notes'); if (notes == null) { noteObject = []; } else { noteObject = JSON.parse(notes); } noteObject.splice(index, 1); localStorage.setItem('notes', JSON.stringify(noteObject)); showNotes(); } let search = document.getElementById('search'); search.addEventListener('input', function (e) { let noteCard = document.getElementsByClassName('noteCard'); console.log(noteCard); Array.from(noteCard).forEach(function (element) { let noteText = element.getElementsByTagName('p')[3].innerText; if (noteText.includes(search.value)) { element.style.display = 'block'; } else { element.style.display = "none"; } }) })
5e7b57dbb30852f84ae653824d3bb2acc099e5f5
[ "JavaScript" ]
1
JavaScript
PrameshKarki/Note-App
e3798d300b72c0f4908b736f6aa45a06c2db63b9
b0cad8a59c9405960652a073f2c99dc2b9f5862b
refs/heads/master
<repo_name>ryanstantz/lambda_check_images_process_zip<file_sep>/unzip.py from __future__ import print_function import urllib import boto3 import zipfile import json #-------- aws variables ----------- s3_client= boto3.client('s3') lambda_client = boto3.client('lambda') #-------- functions begin--------- def lambda_handler(event, context): # Get the object from the event and show its content type zipped_bucket_name = event['Records'][0]['s3']['bucket']['name'] zipped_file_key = event['Records'][0]['s3']['object']['key'] try: # Download and save the zip to tmp storage s3_client.download_file(zipped_bucket_name, zipped_file_key, '/tmp/file.zip') # Unzip the file unzipped = zipfile.ZipFile('/tmp/file.zip') # Iterate all file names and push front image files into the list of # files to be converted from .tif to .png and saved to our s3 check # images bucket front_image_files = [] image_files = unzipped.namelist() for file in image_files: if file.endswith('f.tif'): front_image_files.insert(0, file) # Divide our list of images into smaller arrays of size n images # [1,2,3,4,5,6,7,8,9,10] -> [[1,2,3], [4,5,6], [7,8,9], [10]] n = 3 split_front_images = [front_image_files[i * n:(i + 1) * n] for i in range((len(front_image_files) + n - 1) // n )] for front_images_chunk in split_front_images: payload3={ "key": zipped_file_key, "bucket": zipped_bucket_name, "image_list": front_images_chunk } response = lambda_client.invoke( FunctionName="uploadImages", InvocationType='Event', Payload=json.dumps(payload3) ) print("REPSPONSE") print(response) except Exception as e: print(e) print('Error unzipping {} from bucket {}.'.format(zipped_file_key, zipped_bucket_name)) raise e
4b6dd6b13f1091c12b6e50e1f28f18eca78961ed
[ "Python" ]
1
Python
ryanstantz/lambda_check_images_process_zip
3282d34f3670a6e6524d669dc9521de69c1d2a88
2bc1010077fb08ca1bae9792d7b1172702e686ae
refs/heads/master
<repo_name>endreferencz/chess-html5<file_sep>/src/hu/mygame/shared/pieces/Rook.java package hu.mygame.shared.pieces; import hu.mygame.shared.Position; import java.util.ArrayList; public class Rook extends Piece { private static final String blackImage = "black_rook.png"; public static ArrayList<ArrayList<Position>> deltas = null; private static final long serialVersionUID = 1L; private static final String whiteImage = "white_rook.png"; public Rook() { } public Rook(Position position, boolean white) { super(position, white); } @Override public ArrayList<ArrayList<Position>> getDeltas() { if (deltas == null) { deltas = new ArrayList<ArrayList<Position>>(); for (int i = 0; i < 4; i++) { deltas.add(new ArrayList<Position>()); } for (int i = 1; i <= 7; i++) { deltas.get(0).add(new Position(i, 0)); deltas.get(1).add(new Position(0, i)); deltas.get(2).add(new Position(-i, 0)); deltas.get(3).add(new Position(0, -i)); } } return deltas; } @Override public String getImageName() { return white ? whiteImage : blackImage; } @Override public boolean isRookAndNotMoved() { return (moved == 0); } } <file_sep>/src/hu/mygame/shared/moves/Move.java package hu.mygame.shared.moves; import java.io.Serializable; import hu.mygame.shared.Board; import hu.mygame.shared.Position; import hu.mygame.shared.PromotionPiece; import hu.mygame.shared.exceptions.IllegalOperationException; import hu.mygame.shared.pieces.Piece; public abstract class Move implements Serializable { private static final long serialVersionUID = 1L; private int lastMoved = -1; private int lastMovedStep = -1; public abstract Position getHighlitePosition(); public abstract void makeMove(Board board); public abstract void setPromotionPiece(PromotionPiece promotionPiece) throws IllegalOperationException; public abstract boolean isPromotion(); public abstract Position getFrom(); public abstract void undoMove(Board board); protected void makeMoved(Piece piece, Board board) { lastMoved = piece.getMoved(); lastMovedStep = piece.getMovedStep(); piece.makeMoved(board.getStep()); } protected void undoMakeMoved(Piece piece) { piece.setMoved(lastMoved); piece.setMovedStep(lastMovedStep); } } <file_sep>/src/hu/mygame/shared/pieces/Bishop.java package hu.mygame.shared.pieces; import hu.mygame.shared.Position; import java.util.ArrayList; public class Bishop extends Piece { private static final String blackImage = "black_bishop.png"; public static ArrayList<ArrayList<Position>> deltas = null; private static final long serialVersionUID = 1L; private static final String whiteImage = "white_bishop.png"; public Bishop() { } public Bishop(Position position, boolean white) { super(position, white); } @Override public ArrayList<ArrayList<Position>> getDeltas() { if (deltas == null) { deltas = new ArrayList<ArrayList<Position>>(); for (int i = 0; i < 4; i++) { deltas.add(new ArrayList<Position>()); } for (int i = 1; i <= 7; i++) { deltas.get(0).add(new Position(i, i)); deltas.get(1).add(new Position(-i, i)); deltas.get(2).add(new Position(i, -i)); deltas.get(3).add(new Position(-i, -i)); } } return deltas; } @Override public String getImageName() { return white ? whiteImage : blackImage; } @Override public boolean isBishop() { return true; } } <file_sep>/src/hu/mygame/shared/pieces/Queen.java package hu.mygame.shared.pieces; import hu.mygame.shared.Position; import java.util.ArrayList; public class Queen extends Piece { private static final String blackImage = "black_queen.png"; public static ArrayList<ArrayList<Position>> deltas = null; private static final long serialVersionUID = 1L; private static final String whiteImage = "white_queen.png"; public Queen() { } public Queen(Position position, boolean white) { super(position, white); } @Override public ArrayList<ArrayList<Position>> getDeltas() { if (deltas == null) { deltas = new ArrayList<ArrayList<Position>>(); for (int i = 0; i < 8; i++) { deltas.add(new ArrayList<Position>()); } for (int i = 1; i <= 7; i++) { deltas.get(0).add(new Position(i, i)); deltas.get(1).add(new Position(-i, i)); deltas.get(2).add(new Position(i, -i)); deltas.get(3).add(new Position(-i, -i)); deltas.get(4).add(new Position(i, 0)); deltas.get(5).add(new Position(0, i)); deltas.get(6).add(new Position(-i, 0)); deltas.get(7).add(new Position(0, -i)); } } return deltas; } @Override public String getImageName() { return white ? whiteImage : blackImage; } } <file_sep>/src/hu/mygame/client/rpc/ChessGameService.java package hu.mygame.client.rpc; import hu.mygame.shared.Board; import hu.mygame.shared.SharedInvitation; import hu.mygame.shared.Player; import hu.mygame.shared.moves.Move; import java.util.List; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("chessGame") public interface ChessGameService extends RemoteService { public static String INVITATION = "1:"; public static String REFRESH_BOARD = "2:"; public static String PLAYER_WENT_ONLINE = "3:"; public static String PLAYER_WENT_OFFLINE = "4:"; public void changeName(String name); /** * At startup for channel connection. * * @return ID for channel */ public String connect(); public void declineInvitation(Long invitationId); public Board getBoard(Long boardId); /** * At startup for invitations. * * @return List of invitations */ public List<SharedInvitation> getMyInvitations(); /** * Get all players. * * @return List of players. First player is the current player. */ public List<Player> getPlayers(); public List<String> getWaitingPlayers(); public void invite(String userId); public boolean move(Long gameId, Move move); public void undo(Long gameId); public void requestUndo(Long gameId); public void startGame(); public void startGame(Long invitationId); void refuseUndo(Long gameId); void refuseDraw(Long gameId); void resign(Long gameId); void requestDraw(Long gameId); void draw(Long gameId); } <file_sep>/src/hu/mygame/client/MyGame.java package hu.mygame.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootLayoutPanel; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class MyGame implements EntryPoint { public static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network " + "connection and try again."; @Override public void onModuleLoad() { RootLayoutPanel.get().add(new Main()); } }<file_sep>/src/hu/mygame/client/rpc/ChessGameServiceAsync.java package hu.mygame.client.rpc; import hu.mygame.shared.Board; import hu.mygame.shared.SharedInvitation; import hu.mygame.shared.Player; import hu.mygame.shared.moves.Move; import java.util.List; import com.google.gwt.user.client.rpc.AsyncCallback; public interface ChessGameServiceAsync { void connect(AsyncCallback<String> callback); void declineInvitation(Long invitationId, AsyncCallback<Void> callback); void getBoard(Long boardId, AsyncCallback<Board> callback); void getMyInvitations(AsyncCallback<List<SharedInvitation>> callback); void getPlayers(AsyncCallback<List<Player>> callback); void getWaitingPlayers(AsyncCallback<List<String>> callback); void invite(String userId, AsyncCallback<Void> callback); void move(Long gameId, Move move, AsyncCallback<Boolean> callback); void startGame(AsyncCallback<Void> callback); void startGame(Long invitationId, AsyncCallback<Void> callback); void changeName(String name, AsyncCallback<Void> callback); void undo(Long gameId, AsyncCallback<Void> callback); void requestUndo(Long gameId, AsyncCallback<Void> callback); void refuseUndo(Long gameId, AsyncCallback<Void> callback); void resign(Long gameId, AsyncCallback<Void> callback); void requestDraw(Long gameId, AsyncCallback<Void> callback); void refuseDraw(Long gameId, AsyncCallback<Void> callback); void draw(Long gameId, AsyncCallback<Void> callback); } <file_sep>/src/hu/mygame/shared/Board.java package hu.mygame.shared; import hu.mygame.shared.moves.Move; import hu.mygame.shared.pieces.Bishop; import hu.mygame.shared.pieces.King; import hu.mygame.shared.pieces.Knight; import hu.mygame.shared.pieces.Pawn; import hu.mygame.shared.pieces.Piece; import hu.mygame.shared.pieces.Queen; import hu.mygame.shared.pieces.Rook; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Board implements Serializable { private static final long serialVersionUID = 1L; private String whitePlayer = null; private String blackPlayer = null; private ArrayList<Piece> pieces = new ArrayList<Piece>(); private Piece redoPiece = null; private Position redoPosition = new Position(); private Piece savedPiece = null; private Side side = Side.WHITE; private State state = State.WHITE_TURN; private int step = 0; private LinkedList<Move> moveHistory = new LinkedList<Move>(); private LinkedList<State> stateHistory = new LinkedList<State>(); public LinkedList<Move> getMoveHistory() { return moveHistory; } public Board() { } public Board(boolean init) { if (init) { pieces.add(new Rook(new Position(0, 0), true)); pieces.add(new Knight(new Position(0, 1), true)); pieces.add(new Bishop(new Position(0, 2), true)); pieces.add(new Queen(new Position(0, 3), true)); pieces.add(new King(new Position(0, 4), true)); pieces.add(new Bishop(new Position(0, 5), true)); pieces.add(new Knight(new Position(0, 6), true)); pieces.add(new Rook(new Position(0, 7), true)); for (int i = 0; i < 8; i++) { pieces.add(new Pawn(new Position(1, i), true)); } for (int i = 0; i < 8; i++) { pieces.add(new Pawn(new Position(6, i), false)); } pieces.add(new Rook(new Position(7, 0), false)); pieces.add(new Knight(new Position(7, 1), false)); pieces.add(new Bishop(new Position(7, 2), false)); pieces.add(new Queen(new Position(7, 3), false)); pieces.add(new King(new Position(7, 4), false)); pieces.add(new Bishop(new Position(7, 5), false)); pieces.add(new Knight(new Position(7, 6), false)); pieces.add(new Rook(new Position(7, 7), false)); } } public void add(Piece piece) { if (piece != null) { pieces.add(piece); } } public boolean free(int row, int column) { // TODO optimize Position position = new Position(row, column); return free(position); } public boolean free(Position position) { return (getPiece(position) == null); } public ArrayList<Move> getAvailableMoves(Piece piece) { if (piece == null) { return null; } else { return piece.getAvailableMoves(this); } } public ArrayList<Move> getAvailableMoves(Position position) { Piece piece = getPiece(position); if (piece != null) { if ((piece.isWhite() && side == Side.WHITE) || (piece.isBlack() && side == Side.BLACK)) { return getAvailableMoves(piece); } } return null; } public King getKing(boolean white) { for (Piece p : pieces) { if (p.isKing() && (p.isWhite() == white)) { return (King) p; } } return null; } public Piece getPiece(Position position) { for (Piece p : pieces) { if (p.getPosition().equals(position)) { return p; } } return null; } public ArrayList<Piece> getPieces() { return pieces; } public Piece getRedoPiece() { return redoPiece; } public Position getRedoPosition() { return redoPosition; } public Piece getSavedPiece() { return savedPiece; } public Side getSide() { return side; } public State getState() { return state; } public void setState(State state) { this.state = state; } public int getStep() { return step; } public boolean isMyTurn() { if (side == Side.WHITE && state == State.WHITE_TURN) return true; if (side == Side.WHITE && state == State.WHITE_TURN_CHESS) return true; if (side == Side.BLACK && state == State.BLACK_TURN) return true; if (side == Side.BLACK && state == State.BLACK_TURN_CHESS) return true; return false; } public boolean isPositionAttackedBy(Position position, boolean white) { Position temp = new Position(); temp.copy(position); Piece piece = null; for (ArrayList<Position> array : Piece.getAllDeltas(white)) { for (Position delta : array) { temp.copy(position); temp.add(delta); if (temp.isValid()) { if ((piece = getPiece(temp)) != null) { if (piece.isWhite() != white) { break; } for (ArrayList<Position> array2 : piece.getAttackDeltas()) { if (array2.contains(delta.getInvert())) { return true; } } break; } } else { break; } } } return false; } boolean isStaleMate(King king) { List<Move> available = king.getAvailableMoves(this); if (available != null) return false; List<Piece> copy = new ArrayList<Piece>(); for (Piece p : pieces) { copy.add(p); } for (Piece p : copy) { if (p.isWhite() == king.isWhite()) { available = p.getAvailableMoves(this); if (available != null) return false; } } return true; } public void undoLastMove() { if (state == State.WHITE_REQUESTED_UNDO || state == State.BLACK_REQUESTED_UNDO) { stateHistory.removeLast(); if (!moveHistory.isEmpty()) { moveHistory.getLast().undoMove(this); moveHistory.removeLast(); state = stateHistory.getLast(); stateHistory.removeLast(); step--; } } } public void movePiece(Move move) { // TODO ELLENORZES Piece piece = getPiece(move.getFrom()); if (piece.isWhite()) { if (state == State.WHITE_TURN || state == State.WHITE_TURN_CHESS) { stateHistory.add(state); state = State.BLACK_TURN; } else { return; } } else { if (state == State.BLACK_TURN || state == State.BLACK_TURN_CHESS) { stateHistory.add(state); state = State.WHITE_TURN; } else { return; } } move.makeMove(this); moveHistory.add(move); step++; Boolean white; if (state == State.BLACK_TURN) { white = false; } else { white = true; } King king = getKing(white); if (isPositionAttackedBy(king.getPosition(), !white)) { if (white) { if (isStaleMate(king)) { state = State.BLACK_WIN; return; } else { state = State.WHITE_TURN_CHESS; return; } } else { if (isStaleMate(king)) { state = State.WHITE_WIN; return; } else { state = State.BLACK_TURN_CHESS; return; } } } if ((pieces.size() == 2) || isStaleMate(king)) { state = State.DRAW; return; } if (pieces.size() == 3) { for (Piece p : pieces) { if (p.isBishop() || p.isKnight()) { state = State.DRAW; return; } } } if (pieces.size() == 4) { Position pos1 = null; Position pos2 = null; for (Piece p : pieces) { if (!(p.isBishop() || p.isKing())) { return; } else if (p.isBishop()) { if (pos1 != null) { pos2 = p.getPosition(); } else { pos1 = p.getPosition(); } } } if (((pos1.getColumn() + pos1.getRow()) % 2) == ((pos2.getColumn() + pos2.getRow()) % 2)) { state = State.DRAW; return; } } return; } public void moveWithUndo(Piece piece, Position target) { redoPiece = piece; Piece targetPiece = getPiece(target); if (targetPiece != null) { savedPiece = targetPiece; remove(targetPiece); } redoPosition.copy(piece.getPosition()); piece.getPosition().setColumn(target.getColumn()); piece.getPosition().setRow(target.getRow()); } protected void promote(Position selected, Position target) { // ERROR } public void remove(Piece piece) { if (piece != null) { pieces.remove(piece); } } public void setSide(Side side) { this.side = side; } public void undo() { if (redoPiece != null) { redoPiece.getPosition().copy(redoPosition); if (savedPiece != null) { add(savedPiece); } redoPiece = null; savedPiece = null; } } public void setWhitePlayer(String whitePlayer) { this.whitePlayer = whitePlayer; } public String getWhitePlayer() { return whitePlayer; } public void setBlackPlayer(String blackPlayer) { this.blackPlayer = blackPlayer; } public String getBlackPlayer() { return blackPlayer; } public void requestUndo(Side side) { if (step > 0 && state != State.WHITE_REQUESTED_UNDO && state != State.BLACK_REQUESTED_UNDO) { if (side == Side.WHITE) { stateHistory.add(state); state = State.WHITE_REQUESTED_UNDO; } else { stateHistory.add(state); state = State.BLACK_REQUESTED_UNDO; } } } public void refuseUndo() { if (state == State.WHITE_REQUESTED_UNDO || state == State.BLACK_REQUESTED_UNDO) { state = stateHistory.getLast(); stateHistory.removeLast(); } } public void requestDraw(Side side) { if (state != State.WHITE_REQUESTED_DRAW && state != State.BLACK_REQUESTED_DRAW) { if (side == Side.WHITE) { stateHistory.add(state); state = State.WHITE_REQUESTED_DRAW; } else { stateHistory.add(state); state = State.BLACK_REQUESTED_DRAW; } } } public void refuseDraw() { if (state == State.WHITE_REQUESTED_DRAW || state == State.BLACK_REQUESTED_DRAW) { state = stateHistory.getLast(); stateHistory.removeLast(); } } public void draw() { if (state == State.WHITE_REQUESTED_DRAW || state == State.BLACK_REQUESTED_DRAW) { state = State.DRAW; } } } <file_sep>/src/hu/mygame/client/chessboard/BoardDrawer.java package hu.mygame.client.chessboard; import hu.mygame.shared.Board; import hu.mygame.shared.Position; import hu.mygame.shared.Side; import hu.mygame.shared.State; import hu.mygame.shared.moves.Move; import hu.mygame.shared.pieces.Piece; import java.util.ArrayList; import com.google.gwt.canvas.dom.client.Context2d; import com.google.gwt.canvas.dom.client.CssColor; import com.google.gwt.dom.client.ImageElement; public class BoardDrawer { private static CssColor blackColor = CssColor.make("rgba(100,100,100,1)"); public static int height = 45; private static CssColor highlite = CssColor.make("rgba(255,0,0,0.2)"); private static CssColor whiteColor = CssColor.make("rgba(250,250,250,1)"); private static CssColor greyColor = CssColor.make("rgba(0,0,0,0.5)"); private static CssColor greenColor = CssColor.make("rgba(0,255,0,0.2)"); public static int width = 45; private Context2d context = null; private ImageLoader imageLoader = null; private Position lastHighlite = new Position(-1, -1); public BoardDrawer(Context2d context, ImageLoader imageLoader) { this.context = context; this.imageLoader = imageLoader; } public void clear() { context.save(); context.setFillStyle(whiteColor); context.fillRect(0, 0, context.getCanvas().getWidth(), context.getCanvas().getHeight()); context.restore(); } public void drawPieces(Board board) { context.save(); for (Piece p : board.getPieces()) { ImageElement image = imageLoader.getImage(p.getImageName()); if (image != null) { if (board.getSide() == Side.WHITE) context.drawImage(image, p.getPosition().getColumn() * width, 7 * height - p.getPosition().getRow() * height); else context.drawImage(image, 7 * width - p.getPosition().getColumn() * width, p.getPosition().getRow() * height); } } context.restore(); } public void drawGrid() { context.save(); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (((i + j) % 2) == 0) { context.setFillStyle(whiteColor); } else { context.setFillStyle(blackColor); } context.fillRect(i * width, j * height, width, height); } } context.restore(); } public void highLiteLastMove(Board board) { context.save(); if (!board.getMoveHistory().isEmpty()) { Position p = board.getMoveHistory().getLast().getHighlitePosition(); context.setFillStyle(greenColor); if (board.getSide() == Side.WHITE) context.fillRect(p.getColumn() * width, (7 - p.getRow()) * height, width, height); else context.fillRect((7 - p.getColumn()) * width, (p.getRow()) * height, width, height); } context.restore(); } public void hideIfUndo(Board board) { context.save(); if (board.getState() == State.WHITE_REQUESTED_UNDO || board.getState() == State.BLACK_REQUESTED_UNDO || board.getState() == State.WHITE_REQUESTED_DRAW || board.getState() == State.BLACK_REQUESTED_DRAW) { context.setFillStyle(greyColor); context.fillRect(0, 0, context.getCanvas().getWidth(), context.getCanvas().getHeight()); } context.restore(); } public void drawTable(Board board) { clear(); drawGrid(); highLiteLastMove(board); drawPieces(board); hideIfUndo(board); } public void highlite(ArrayList<Move> positions, Board board) { if (!lastHighlite.equals(positions)) { clear(); drawGrid(); highLiteLastMove(board); context.save(); context.setFillStyle(highlite); for (Move m : positions) { Position p = m.getHighlitePosition(); if (board.getSide() == Side.WHITE) context.fillRect(p.getColumn() * width, (7 - p.getRow()) * height, width, height); else context.fillRect((7 - p.getColumn()) * width, (p.getRow()) * height, width, height); } context.restore(); drawPieces(board); } } public void refresh() { } } <file_sep>/src/hu/mygame/shared/State.java package hu.mygame.shared; public enum State { BLACK_TURN, BLACK_TURN_CHESS, BLACK_WIN, DRAW, WHITE_TURN, WHITE_TURN_CHESS, WHITE_WIN, WHITE_REQUESTED_UNDO, BLACK_REQUESTED_UNDO, WHITE_REQUESTED_DRAW, BLACK_REQUESTED_DRAW }<file_sep>/src/hu/mygame/server/jdo/GameJDO.java package hu.mygame.server.jdo; import hu.mygame.client.rpc.ChessGameService; import hu.mygame.shared.Board; import java.io.Serializable; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; import com.google.appengine.api.channel.ChannelMessage; import com.google.appengine.api.channel.ChannelService; @PersistenceCapable public class GameJDO implements Serializable { private static final long serialVersionUID = 1L; @Persistent String blackUser; @Persistent(serialized = "true") Board board; @Persistent Boolean finished; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent String whiteUser; public GameJDO(String whiteUser, String blackUser, Board board) { super(); this.whiteUser = whiteUser; this.blackUser = blackUser; this.board = board; this.finished = false; } public String getBlackUser() { return blackUser; } public Board getBoard() { return board; } public Boolean getFinished() { return finished; } public Long getId() { return id; } public String getWhiteUser() { return whiteUser; } public void notifyPlayers(ChannelService channelService) { ChannelMessage message = new ChannelMessage(whiteUser, ChessGameService.REFRESH_BOARD + id); channelService.sendMessage(message); message = new ChannelMessage(blackUser, ChessGameService.REFRESH_BOARD + id); channelService.sendMessage(message); } public void setBlackUser(String blackUser) { this.blackUser = blackUser; } public void setBoard(Board board) { this.board = board; } public void setFinished(Boolean finished) { this.finished = finished; } public void setId(Long id) { this.id = id; } public void setWhiteUser(String whiteUser) { this.whiteUser = whiteUser; } public void notifyComingPlayer(ChannelService channelService) { } } <file_sep>/src/hu/mygame/server/servlet/ChannelConnectedServlet.java package hu.mygame.server.servlet; import hu.mygame.client.rpc.ChessGameService; import hu.mygame.server.PMF; import hu.mygame.server.jdo.GameJDO; import hu.mygame.server.jdo.PlayerJDO; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.channel.ChannelMessage; import com.google.appengine.api.channel.ChannelPresence; import com.google.appengine.api.channel.ChannelService; import com.google.appengine.api.channel.ChannelServiceFactory; public class ChannelConnectedServlet extends HttpServlet { private static final Logger log = Logger.getLogger(ChannelConnectedServlet.class.getName()); private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") @Override // Handler for _ah/channel/connected/ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { ChannelService channelService = ChannelServiceFactory.getChannelService(); ChannelPresence presence = channelService.parsePresence(req); String clientId = presence.clientId(); log.info("Channel connected: " + clientId); System.out.println("Channel connected: " + clientId); PersistenceManager pm = PMF.get().getPersistenceManager(); try { PlayerJDO player = pm.getObjectById(PlayerJDO.class, clientId); player.setOnline(true); } finally { pm.close(); } pm = PMF.get().getPersistenceManager(); try { Query query = pm.newQuery(GameJDO.class); query.setFilter("(whiteUser == userParam) && (finished == false)"); query.declareParameters("String userParam"); List<GameJDO> games = (List<GameJDO>) query.execute(clientId); for (GameJDO g : games) { ChannelMessage message = new ChannelMessage(clientId, ChessGameService.REFRESH_BOARD + g.getId()); channelService.sendMessage(message); } query = pm.newQuery(GameJDO.class); query.setFilter("(blackUser == userParam) && (finished == false)"); query.declareParameters("String userParam"); games = (List<GameJDO>) query.execute(clientId); for (GameJDO g : games) { ChannelMessage message = new ChannelMessage(clientId, ChessGameService.REFRESH_BOARD + g.getId()); channelService.sendMessage(message); } query = pm.newQuery(PlayerJDO.class); query.setFilter("online == true"); List<PlayerJDO> players = (List<PlayerJDO>) query.execute(); for (PlayerJDO p : players) { ChannelMessage message = new ChannelMessage(p.getUser(), ChessGameService.PLAYER_WENT_ONLINE + clientId); channelService.sendMessage(message); } } finally { pm.close(); } } } <file_sep>/src/hu/mygame/shared/moves/SimpleMove.java package hu.mygame.shared.moves; import hu.mygame.shared.Board; import hu.mygame.shared.Position; import hu.mygame.shared.PromotionPiece; import hu.mygame.shared.exceptions.IllegalOperationException; import hu.mygame.shared.pieces.Piece; public class SimpleMove extends Move { private static final long serialVersionUID = 1L; protected Position from = null; protected Position to = null; public SimpleMove() { } public SimpleMove(Position from, Position to) { this.from = from; this.to = to; } @Override public Position getHighlitePosition() { return to; } @Override public void makeMove(Board board) { Piece piece = board.getPiece(from); makeMoved(piece, board); piece.setPosition(to); } @Override public void undoMove(Board board) { Piece piece = board.getPiece(to); undoMakeMoved(piece); piece.setPosition(from); } @Override public void setPromotionPiece(PromotionPiece promotionPiece) throws IllegalOperationException { throw new IllegalOperationException("SimpleMove >> No promotionpiece."); } @Override public boolean isPromotion() { return false; } @Override public Position getFrom() { return from; } } <file_sep>/src/hu/mygame/shared/pieces/King.java package hu.mygame.shared.pieces; import hu.mygame.shared.Position; import java.util.ArrayList; public class King extends Piece { private static final String blackImage = "black_king.png"; public static ArrayList<ArrayList<Position>> deltas = null; private static final long serialVersionUID = 1L; private static final String whiteImage = "white_king.png"; public King() { } public King(Position position, boolean white) { super(position, white); } @Override public ArrayList<ArrayList<Position>> getDeltas() { if (deltas == null) { deltas = new ArrayList<ArrayList<Position>>(); deltas.add(new ArrayList<Position>()); deltas.get(0).add(new Position(-1, -1)); deltas.add(new ArrayList<Position>()); deltas.get(1).add(new Position(0, -1)); deltas.add(new ArrayList<Position>()); deltas.get(2).add(new Position(1, -1)); deltas.add(new ArrayList<Position>()); deltas.get(3).add(new Position(-1, 0)); deltas.add(new ArrayList<Position>()); deltas.get(4).add(new Position(1, 0)); deltas.add(new ArrayList<Position>()); deltas.get(5).add(new Position(-1, 1)); deltas.add(new ArrayList<Position>()); deltas.get(6).add(new Position(0, 1)); deltas.add(new ArrayList<Position>()); deltas.get(7).add(new Position(1, 1)); } return deltas; } @Override public String getImageName() { return white ? whiteImage : blackImage; } @Override public boolean isKing() { return true; } } <file_sep>/src/hu/mygame/client/dialog/PromotionDialog.java package hu.mygame.client.dialog; import hu.mygame.client.chessboard.ActionHandler; import hu.mygame.shared.PromotionPiece; import hu.mygame.shared.exceptions.IllegalOperationException; import hu.mygame.shared.moves.Move; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PushButton; import com.google.gwt.user.client.ui.Widget; public class PromotionDialog extends DialogBox { interface PromotionDialogUiBinder extends UiBinder<Widget, PromotionDialog> { } private static final PromotionDialogUiBinder uiBinder = GWT.create(PromotionDialogUiBinder.class); private ActionHandler actionHandler = null; @UiField PushButton button_bishop; @UiField PushButton button_knight; @UiField PushButton button_queen; @UiField PushButton button_rook; @UiField DialogBox dialog; @UiField Label label; private Move move = null; public PromotionDialog(Move move, ActionHandler actionHandler) { setWidget(uiBinder.createAndBindUi(this)); this.move = move; this.actionHandler = actionHandler; dialog.setPopupPositionAndShow(new PositionCallback() { @Override public void setPosition(int offsetWidth, int offsetHeight) { dialog.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, (Window.getClientHeight() - offsetHeight) / 2); } }); } @UiHandler("button_bishop") void onBishop(ClickEvent e) { dialog.hide(); try { move.setPromotionPiece(PromotionPiece.BISHOP); actionHandler.makeMove(move); } catch (IllegalOperationException e1) { // TODO } } @UiHandler("button_knight") void onKnight(ClickEvent e) { dialog.hide(); try { move.setPromotionPiece(PromotionPiece.KNIGHT); actionHandler.makeMove(move); } catch (IllegalOperationException e1) { // TODO } } @UiHandler("button_queen") void onQueen(ClickEvent e) { dialog.hide(); try { move.setPromotionPiece(PromotionPiece.QUEEN); actionHandler.makeMove(move); } catch (IllegalOperationException e1) { // TODO } } @UiHandler("button_rook") void onRook(ClickEvent e) { dialog.hide(); try { move.setPromotionPiece(PromotionPiece.ROOK); actionHandler.makeMove(move); } catch (IllegalOperationException e1) { // TODO } } } <file_sep>/src/hu/mygame/client/chessboard/ImageLoader.java package hu.mygame.client.chessboard; import java.util.HashMap; import com.google.gwt.dom.client.ImageElement; import com.google.gwt.event.dom.client.LoadEvent; import com.google.gwt.event.dom.client.LoadHandler; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.RootPanel; public class ImageLoader { private static String[] images = {"black_bishop.png", "black_king.png", "black_knight.png", "black_pawn.png", "black_queen.png", "black_rook.png", "white_bishop.png", "white_king.png", "white_knight.png", "white_pawn.png", "white_queen.png", "white_rook.png"}; private static HashMap<String, ImageElement> map = new HashMap<String, ImageElement>(); private int loaded = 0; public ImageLoader(final ChessBoard chessBoard) { loaded = 0; for (final String imageName : images) { if (map.get(imageName) == null) { final Image image = new Image(imageName); image.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { map.put(imageName, (ImageElement) image.getElement().cast()); loaded++; if (loaded == 12) { chessBoard.refresh(); } } }); image.setVisible(false); RootPanel.get().add(image); } } } public ImageElement getImage(String imageName) { return map.get(imageName); } } <file_sep>/src/hu/mygame/client/Main.java package hu.mygame.client; import hu.mygame.client.chessboard.ChessBoard; import hu.mygame.client.dialog.IncomingInvitationDialog; import hu.mygame.client.players.PlayersPanel; import hu.mygame.client.rpc.ChessGameService; import hu.mygame.client.rpc.ChessGameServiceAsync; import hu.mygame.shared.Board; import hu.mygame.shared.SharedInvitation; import hu.mygame.shared.Side; import hu.mygame.shared.Player; import java.util.HashMap; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.TabLayoutPanel; import com.google.gwt.user.client.ui.Widget; public class Main extends Composite implements AsyncCallback<List<SharedInvitation>> { interface MainUiBinder extends UiBinder<Widget, Main> { } private static MainUiBinder uiBinder = GWT.create(MainUiBinder.class); private HashMap<String, ChessBoard> boards = new HashMap<String, ChessBoard>(); private ChessGameServiceAsync chessGameService = GWT.create(ChessGameService.class); @UiField PlayersPanel playersPanel; @UiField TabLayoutPanel tabLayoutPanel; public Main() { initWidget(uiBinder.createAndBindUi(this)); new MyChannel(this); chessGameService.getMyInvitations(this); } @Override public void onFailure(Throwable caught) { // TODO } @Override public void onSuccess(List<SharedInvitation> result) { for (SharedInvitation s : result) { new IncomingInvitationDialog(s.getInvitationId(), s.getPlayer()); } } public void processMessage(String message) { if (message.startsWith(ChessGameService.REFRESH_BOARD)) { String gameId = message.substring(ChessGameService.REFRESH_BOARD.length()); refreshBoard(gameId.trim()); } else if (message.startsWith(ChessGameService.INVITATION)) { chessGameService.getMyInvitations(this); } else if (message.startsWith(ChessGameService.PLAYER_WENT_ONLINE)) { String playerId = message.substring(ChessGameService.PLAYER_WENT_ONLINE.length()); playersPanel.playerOnline(playerId.trim()); } else if (message.startsWith(ChessGameService.PLAYER_WENT_OFFLINE)) { String playerId = message.substring(ChessGameService.PLAYER_WENT_OFFLINE.length()); playersPanel.playerOffline(playerId.trim()); } } private void refreshBoard(final String gameId) { chessGameService.getBoard(Long.valueOf(gameId), new AsyncCallback<Board>() { @Override public void onFailure(Throwable caught) { } @Override public void onSuccess(Board result) { if (boards.containsKey(gameId)) { ChessBoard chessBoard = boards.get(gameId); chessBoard.setBoard(result); } else { ChessBoard chessBoard = new ChessBoard(Long.valueOf(gameId), result); String title = ""; if (result.getSide() == Side.WHITE) { title = getName(result.getBlackPlayer()); } else { title = getName(result.getWhitePlayer()); } tabLayoutPanel.add(chessBoard, title); tabLayoutPanel.selectTab(chessBoard); boards.put(gameId, chessBoard); } } }); } public String getName(String userId) { List<Player> players = playersPanel.getPlayers(); if (players == null) return null; for (Player p : players) { if (p.getUser().equals(userId)) { return p.getDisplayName(); } } return null; } } <file_sep>/src/hu/mygame/client/resources/Resources.java package hu.mygame.client.resources; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.ImageResource; public interface Resources extends ClientBundle { @Source("top_image.png") ImageResource top_image(); @Source("white_bishop.png") ImageResource white_bishop(); @Source("white_knight.png") ImageResource white_knight(); @Source("white_queen.png") ImageResource white_queen(); @Source("white_rook.png") ImageResource white_rook(); } <file_sep>/src/hu/mygame/server/rpc/ChessGameServiceImpl.java package hu.mygame.server.rpc; import hu.mygame.client.rpc.ChessGameService; import hu.mygame.server.PMF; import hu.mygame.server.jdo.GameJDO; import hu.mygame.server.jdo.InvitationJDO; import hu.mygame.server.jdo.PlayerJDO; import hu.mygame.shared.Board; import hu.mygame.shared.Player; import hu.mygame.shared.SharedInvitation; import hu.mygame.shared.Side; import hu.mygame.shared.State; import hu.mygame.shared.moves.Move; import java.util.ArrayList; import java.util.List; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.Query; import com.google.appengine.api.channel.ChannelMessage; import com.google.appengine.api.channel.ChannelService; import com.google.appengine.api.channel.ChannelServiceFactory; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class ChessGameServiceImpl extends RemoteServiceServlet implements ChessGameService { private static final long serialVersionUID = 1L; ChannelService channelService = ChannelServiceFactory.getChannelService(); UserService userService = UserServiceFactory.getUserService(); void notifyRefreshPlayers(PersistenceManager pm) { } @Override public String connect() { PersistenceManager pm = PMF.get().getPersistenceManager(); String userId = null; try { PlayerJDO currentPlayer = getCurrentPlayer(pm); userId = currentPlayer.getUser(); } finally { pm.close(); } if (userId == null) { return null; } else { return channelService.createChannel(userId); } } @Override public void declineInvitation(Long invitationId) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { InvitationJDO invitation = pm.getObjectById(InvitationJDO.class, invitationId); pm.deletePersistent(invitation); } finally { pm.close(); } } @Override public Board getBoard(Long gameId) { PersistenceManager pm = PMF.get().getPersistenceManager(); Board board = null; GameJDO game = null; try { game = pm.getObjectById(GameJDO.class, gameId); board = game.getBoard(); } finally { pm.close(); } if (board == null) return null; if (userService.getCurrentUser().getUserId().equals(game.getWhiteUser())) { return board; } else { board.setSide(Side.BLACK); return board; } } private PlayerJDO getCurrentPlayer(PersistenceManager pm) { PlayerJDO player = null; User user = userService.getCurrentUser(); try { player = pm.getObjectById(PlayerJDO.class, user.getUserId()); } catch (Exception e) { } if (player == null) { player = new PlayerJDO(0L, user.getEmail(), 0L, null, user.getUserId(), false, false, 0L); pm.makePersistent(player); } return player; } @Override @SuppressWarnings("unchecked") public List<SharedInvitation> getMyInvitations() { List<SharedInvitation> ret = new ArrayList<SharedInvitation>(); PersistenceManager pm = PMF.get().getPersistenceManager(); try { Query invitationQuery = pm.newQuery(InvitationJDO.class); invitationQuery.setFilter("target == targetParam"); invitationQuery.declareParameters("java.lang.String targetParam"); List<InvitationJDO> invitations = (List<InvitationJDO>) invitationQuery.execute(userService .getCurrentUser().getUserId()); for (InvitationJDO i : invitations) { PlayerJDO player = pm.getObjectById(PlayerJDO.class, i.getInitiator()); ret.add(new SharedInvitation(i.getId(), player.toPlayer())); } } finally { pm.close(); } return ret; } @Override @SuppressWarnings("unchecked") public List<Player> getPlayers() { List<Player> ret = new ArrayList<Player>(); PersistenceManager pm = PMF.get().getPersistenceManager(); try { PlayerJDO currentPlayer = getCurrentPlayer(pm); Query query = pm.newQuery(PlayerJDO.class); List<PlayerJDO> players = (List<PlayerJDO>) query.execute(); ret.add(currentPlayer.toPlayer()); for (PlayerJDO p : players) { if (!p.equals(currentPlayer)) { ret.add(p.toPlayer()); } } } finally { pm.close(); } return ret; } private PlayerJDO getWaitingPlayer(PersistenceManager pm) { Query query = pm.newQuery(PlayerJDO.class, "waiting == true"); @SuppressWarnings("unchecked") List<PlayerJDO> players = (List<PlayerJDO>) query.execute(); if (players.size() > 0) { return players.get(0); } else { return null; } } @Override public List<String> getWaitingPlayers() { ArrayList<String> ret = new ArrayList<String>(); PersistenceManager pm = PMF.get().getPersistenceManager(); try { Query query = pm.newQuery(PlayerJDO.class, "waiting == true"); @SuppressWarnings("unchecked") List<PlayerJDO> players = (List<PlayerJDO>) query.execute(); for (PlayerJDO p : players) { ret.add(p.getUser()); } } finally { pm.close(); } return ret; } @Override public void invite(String userId) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { PlayerJDO initiator = getCurrentPlayer(pm); PlayerJDO target = pm.getObjectById(PlayerJDO.class, userId); InvitationJDO invitation = new InvitationJDO(initiator.getUser(), target.getUser()); pm.makePersistent(invitation); ChannelMessage message = new ChannelMessage(userId, ChessGameService.INVITATION); channelService.sendMessage(message); } finally { pm.close(); } } @Override public boolean move(Long gameId, Move move) { PersistenceManager pm = PMF.get().getPersistenceManager(); Boolean ret = false; GameJDO game = null; try { game = pm.getObjectById(GameJDO.class, gameId); game.getBoard().movePiece(move); manageScore(game, pm); JDOHelper.makeDirty(game, "board"); ret = true; } finally { pm.close(); } User user = userService.getCurrentUser(); ChannelMessage message; if (user.getUserId().equals(game.getWhiteUser())) { message = new ChannelMessage(game.getBlackUser(), ChessGameService.REFRESH_BOARD + game.getId()); } else { message = new ChannelMessage(game.getWhiteUser(), ChessGameService.REFRESH_BOARD + game.getId()); } channelService.sendMessage(message); return ret; } private void manageScore(GameJDO game, PersistenceManager pm) { if (game.getBoard().getState() == State.WHITE_WIN) { PlayerJDO player1 = pm.getObjectById(PlayerJDO.class, game.getWhiteUser()); player1.setWin(player1.getWin() + 1); PlayerJDO player2 = pm.getObjectById(PlayerJDO.class, game.getBlackUser()); player2.setLost(player2.getLost() + 1); game.setFinished(true); } if (game.getBoard().getState() == State.BLACK_WIN) { PlayerJDO player1 = pm.getObjectById(PlayerJDO.class, game.getBlackUser()); player1.setWin(player1.getWin() + 1); PlayerJDO player2 = pm.getObjectById(PlayerJDO.class, game.getWhiteUser()); player2.setLost(player2.getLost() + 1); game.setFinished(true); } if (game.getBoard().getState() == State.DRAW) { PlayerJDO player1 = pm.getObjectById(PlayerJDO.class, game.getWhiteUser()); player1.setDraw(player1.getDraw() + 1); PlayerJDO player2 = pm.getObjectById(PlayerJDO.class, game.getBlackUser()); player2.setDraw(player2.getDraw() + 1); game.setFinished(true); } } @Override public void startGame() { PersistenceManager pm = PMF.get().getPersistenceManager(); try { PlayerJDO waitingPlayer = getWaitingPlayer(pm); PlayerJDO currentPlayer = getCurrentPlayer(pm); if (waitingPlayer != null && waitingPlayer != currentPlayer) { waitingPlayer.setWaiting(false); Board board = new Board(true); board.setWhitePlayer(waitingPlayer.getUser()); board.setBlackPlayer(currentPlayer.getUser()); GameJDO game = new GameJDO(waitingPlayer.getUser(), currentPlayer.getUser(), board); pm.makePersistent(game); game.notifyPlayers(channelService); } else { currentPlayer.setWaiting(true); } } finally { pm.close(); } } @Override public void startGame(Long invitationId) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { InvitationJDO invitation = pm.getObjectById(InvitationJDO.class, invitationId); PlayerJDO otherPlayer = pm.getObjectById(PlayerJDO.class, invitation.getTarget()); PlayerJDO currentPlayer = pm.getObjectById(PlayerJDO.class, invitation.getInitiator()); if (!otherPlayer.getUser().equals(currentPlayer.getUser())) { Board board = new Board(true); board.setWhitePlayer(otherPlayer.getUser()); board.setBlackPlayer(currentPlayer.getUser()); GameJDO game = new GameJDO(otherPlayer.getUser(), currentPlayer.getUser(), board); pm.makePersistent(game); game.notifyPlayers(channelService); } pm.deletePersistent(invitation); } finally { pm.close(); } } @Override public void changeName(String name) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { PlayerJDO currentPlayer = getCurrentPlayer(pm); currentPlayer.setName(name); } finally { pm.close(); } } @Override public void undo(Long gameId) { PersistenceManager pm = PMF.get().getPersistenceManager(); GameJDO game = null; try { game = pm.getObjectById(GameJDO.class, gameId); game.getBoard().undoLastMove(); JDOHelper.makeDirty(game, "board"); } finally { pm.close(); } ChannelMessage message; message = new ChannelMessage(game.getBlackUser(), ChessGameService.REFRESH_BOARD + game.getId()); channelService.sendMessage(message); message = new ChannelMessage(game.getWhiteUser(), ChessGameService.REFRESH_BOARD + game.getId()); channelService.sendMessage(message); } @Override public void requestUndo(Long gameId) { User user = userService.getCurrentUser(); PersistenceManager pm = PMF.get().getPersistenceManager(); GameJDO game = null; try { game = pm.getObjectById(GameJDO.class, gameId); if (user.getUserId().equals(game.getWhiteUser())) { game.getBoard().requestUndo(Side.WHITE); } else { game.getBoard().requestUndo(Side.BLACK); } JDOHelper.makeDirty(game, "board"); } finally { pm.close(); } game.notifyPlayers(channelService); } @Override public void refuseUndo(Long gameId) { PersistenceManager pm = PMF.get().getPersistenceManager(); GameJDO game = null; try { game = pm.getObjectById(GameJDO.class, gameId); game.getBoard().refuseUndo(); JDOHelper.makeDirty(game, "board"); } finally { pm.close(); } game.notifyPlayers(channelService); } @Override public void resign(Long gameId) { PersistenceManager pm = PMF.get().getPersistenceManager(); User user = userService.getCurrentUser(); GameJDO game = null; try { game = pm.getObjectById(GameJDO.class, gameId); if (user.getUserId().equals(game.getWhiteUser())) { game.getBoard().setState(State.BLACK_WIN); } else { game.getBoard().setState(State.WHITE_WIN); } manageScore(game, pm); JDOHelper.makeDirty(game, "board"); } finally { pm.close(); } game.notifyPlayers(channelService); } @Override public void requestDraw(Long gameId) { User user = userService.getCurrentUser(); PersistenceManager pm = PMF.get().getPersistenceManager(); GameJDO game = null; try { game = pm.getObjectById(GameJDO.class, gameId); if (user.getUserId().equals(game.getWhiteUser())) { game.getBoard().requestDraw(Side.WHITE); } else { game.getBoard().requestDraw(Side.BLACK); } JDOHelper.makeDirty(game, "board"); } finally { pm.close(); } game.notifyPlayers(channelService); } @Override public void refuseDraw(Long gameId) { PersistenceManager pm = PMF.get().getPersistenceManager(); GameJDO game = null; try { game = pm.getObjectById(GameJDO.class, gameId); game.getBoard().refuseDraw(); JDOHelper.makeDirty(game, "board"); } finally { pm.close(); } game.notifyPlayers(channelService); } @Override public void draw(Long gameId) { PersistenceManager pm = PMF.get().getPersistenceManager(); GameJDO game = null; try { game = pm.getObjectById(GameJDO.class, gameId); game.getBoard().draw(); manageScore(game, pm); JDOHelper.makeDirty(game, "board"); } finally { pm.close(); } game.notifyPlayers(channelService); } } <file_sep>/src/hu/mygame/shared/pieces/Piece.java package hu.mygame.shared.pieces; import hu.mygame.shared.Board; import hu.mygame.shared.Position; import hu.mygame.shared.moves.AttackMove; import hu.mygame.shared.moves.AttackMoveWithPromotion; import hu.mygame.shared.moves.CastleMove; import hu.mygame.shared.moves.Move; import hu.mygame.shared.moves.SimpleMove; import hu.mygame.shared.moves.SimpleMoveWithPromotion; import java.io.Serializable; import java.util.ArrayList; public abstract class Piece implements Serializable { private static ArrayList<ArrayList<Position>> allDeltasBlack = null; private static ArrayList<ArrayList<Position>> allDeltasWhite = null; private static final long serialVersionUID = 1L; public static ArrayList<ArrayList<Position>> getAllDeltas(boolean white) { if (white) { if (allDeltasWhite == null) { Queen queen = new Queen(); Knight knight = new Knight(); Pawn pawn = new Pawn(); pawn.setWhite(white); allDeltasWhite = new ArrayList<ArrayList<Position>>(); allDeltasWhite.addAll(queen.getAttackDeltas()); allDeltasWhite.addAll(knight.getAttackDeltas()); allDeltasWhite.addAll(pawn.getAttackDeltas()); } return allDeltasWhite; } else { if (allDeltasBlack == null) { Queen queen = new Queen(); Knight knight = new Knight(); Pawn pawn = new Pawn(); pawn.setWhite(white); allDeltasBlack = new ArrayList<ArrayList<Position>>(); allDeltasBlack.addAll(queen.getAttackDeltas()); allDeltasBlack.addAll(knight.getAttackDeltas()); allDeltasBlack.addAll(pawn.getAttackDeltas()); } return allDeltasBlack; } } protected int moved = 0; protected int movedStep = -1; protected Position position; protected boolean white; public Piece() { } public Piece(Position position, boolean white) { this.position = position; this.white = white; } public boolean enPassant(int step) { return false; } public ArrayList<ArrayList<Position>> getAttackDeltas() { return getDeltas(); } public ArrayList<Move> getAvailableMoves(Board board) { ArrayList<Move> ret = new ArrayList<Move>(); Position temp = new Position(); King king = board.getKing(isWhite()); for (ArrayList<Position> array : getDeltas()) { for (Position d : array) { temp.copy(position); temp.add(d); if (temp.isValid()) { Piece piece = board.getPiece(temp); if (piece == null) { board.moveWithUndo(this, temp); if (!board.isPositionAttackedBy(king.getPosition(), !isWhite())) { Move move; if (isPawn() && (temp.getRow() == 0 || temp.getRow() == 7)) { move = new SimpleMoveWithPromotion(this.getPosition(), new Position(temp.getRow(), temp.getColumn()), null); } else { move = new SimpleMove(this.getPosition(), new Position(temp.getRow(), temp.getColumn())); } ret.add(move); } board.undo(); } if (piece != null) { break; } } } } for (ArrayList<Position> array : getAttackDeltas()) { for (Position d : array) { temp.copy(position); temp.add(d); if (temp.isValid()) { Piece piece = board.getPiece(temp); if ((piece != null) && (piece.isWhite() != isWhite())) { board.moveWithUndo(this, temp); if (!board.isPositionAttackedBy(king.getPosition(), !isWhite())) { Move move; if (isPawn() && (temp.getRow() == 0 || temp.getRow() == 7)) { move = new AttackMoveWithPromotion(this.getPosition(), new Position(temp.getRow(), temp.getColumn()), null); } else { Position to = new Position(temp.getRow(), temp.getColumn()); move = new AttackMove(this.getPosition(), to, to); } ret.add(move); } board.undo(); } if (piece != null) { break; } } } } // Castling if (isKing() && (moved == 0)) { if (white) { Piece piece = board.getPiece(new Position(0, 7)); if (piece != null && piece.isRookAndNotMoved() && board.free(0, 5) && board.free(0, 6) && !board.isPositionAttackedBy(new Position(0, 5), !white) && !board.isPositionAttackedBy(new Position(0, 6), !white)) { Move move = new CastleMove(this.getPosition(), new Position(0, 6), piece.getPosition(), new Position(0, 5)); ret.add(move); } piece = board.getPiece(new Position(0, 0)); if (piece != null && piece.isRookAndNotMoved() && board.free(0, 1) && board.free(0, 2) && board.free(0, 3) && !board.isPositionAttackedBy(new Position(0, 2), !white) && !board.isPositionAttackedBy(new Position(0, 3), !white)) { Move move = new CastleMove(this.getPosition(), new Position(0, 2), piece.getPosition(), new Position(0, 3)); ret.add(move); } } else { Piece piece = board.getPiece(new Position(7, 7)); if (piece != null && piece.isRookAndNotMoved() && board.free(7, 5) && board.free(7, 6) && !board.isPositionAttackedBy(new Position(7, 5), !white) && !board.isPositionAttackedBy(new Position(7, 6), !white)) { Move move = new CastleMove(this.getPosition(), new Position(7, 6), piece.getPosition(), new Position(7, 5)); ret.add(move); } piece = board.getPiece(new Position(7, 0)); if (piece != null && piece.isRookAndNotMoved() && board.free(7, 1) && board.free(7, 2) && board.free(7, 3) && !board.isPositionAttackedBy(new Position(7, 2), !white) && !board.isPositionAttackedBy(new Position(7, 3), !white)) { Move move = new CastleMove(this.getPosition(), new Position(7, 2), piece.getPosition(), new Position(7, 3)); ret.add(move); } } } // en passant // TODO nem kerul sakkba a kiraly?! if (isPawn()) { Piece piece = board.getPiece(new Position(position.getRow(), position.getColumn() - 1)); if ((piece != null) && (piece.isWhite() != isWhite()) && piece.enPassant(board.getStep())) { if (isWhite()) { Move move = new AttackMove(this.getPosition(), new Position(position.getRow() + 1, position.getColumn() - 1), new Position(position.getRow(), position.getColumn() - 1)); ret.add(move); } else { Move move = new AttackMove(this.getPosition(), new Position(position.getRow() - 1, position.getColumn() - 1), new Position(position.getRow(), position.getColumn() - 1)); ret.add(move); } } piece = board.getPiece(new Position(position.getRow(), position.getColumn() + 1)); if ((piece != null) && (piece.isWhite() != isWhite()) && piece.enPassant(board.getStep())) { if (isWhite()) { Move move = new AttackMove(this.getPosition(), new Position(position.getRow() + 1, position.getColumn() + 1), new Position(position.getRow(), position.getColumn() + 1)); ret.add(move); } else { Move move = new AttackMove(this.getPosition(), new Position(position.getRow() - 1, position.getColumn() + 1), new Position(position.getRow(), position.getColumn() + 1)); ret.add(move); } } } if (ret.isEmpty()) return null; else return ret; } public abstract ArrayList<ArrayList<Position>> getDeltas(); public String getImageName() { return ""; } public Position getPosition() { return position; } public boolean isBishop() { return false; } public boolean isBlack() { return !white; } public boolean isKing() { return false; } public boolean isKnight() { return false; } public boolean isPawn() { return false; } public boolean isRookAndNotMoved() { return false; } public boolean isWhite() { return white; } public void makeMoved(int step) { moved++; this.movedStep = step; } public int getMovedStep() { return movedStep; } public void setMovedStep(int movedStep) { this.movedStep = movedStep; } public int getMoved() { return moved; } public void setMoved(int moved) { this.moved = moved; } public void setPosition(Position position) { this.position = position; } public void setWhite(boolean white) { this.white = white; } }
ca4dbdf49d7c77c000736e5d974e515d04cffcc2
[ "Java" ]
20
Java
endreferencz/chess-html5
9017498d6b5df6cd1574f3ec4a83167ea6561cba
eb436de79c768f7f04cff2af4bed0cf8a32df9e9
refs/heads/master
<file_sep>const app = require('./src/config/launcher') app.listen(3000,() => console.log('Server full power on port 3000')); <file_sep>const AtendimentosRotas = require('./atendmentos-rotas') module.exports = (app) =>{ AtendimentosRotas(app); }<file_sep># alura-Node_API_Rest Application Node API Rest
00ee3de411708f43baaff15e94d3b8d109566e22
[ "JavaScript", "Markdown" ]
3
JavaScript
ArkbraveNunes/alura-Node_API_Rest
ed82dec0d1978884b0c7a166609686430f4032d4
c6902105f2703264a0d0a3467e14fb0d73b5ba35
refs/heads/master
<file_sep>package com.yuting.qiche.controller; import com.yuting.qiche.service.TestService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/test") public class TestController { @Resource private TestService testService; @ResponseBody @RequestMapping(value="/do",method = RequestMethod.GET) public Map<String,String> test(@RequestParam(required = false) String name, @RequestParam(required = false) String age) { Map<String,String> map = new HashMap<String, String>(); map.put("name",testService.get()); map.put("age",age); return map; } }<file_sep>qiche ===== 标准web应用模板
f313977c89c5964fb614bf6b5e6fd968701204dc
[ "Markdown", "Java" ]
2
Java
juqiukai/qiche
d2dd5c6c0b718b550a00026627050ef5370c129b
31d03320c976e57a172dfea0bda598326d5cb587
refs/heads/master
<repo_name>annadzuienko/Git_test<file_sep>/sellerFeedback/readme.md https://annadzuienko.github.io/Git_test/sellerFeedback/index.html <file_sep>/budCapTest/readme.md https://annadzuienko.github.io/Git_test/budCapTest/dist/index.html <file_sep>/sellerFeedback/script.js let replay = document.getElementById('replay'); let blockReplay = document.getElementById('feedback__user-replay'); replay.onclick = function() { blockReplay.setAttribute('class', 'visible'); };
032dac56d9799199dbc048cf4f8c095d6722e2eb
[ "Markdown", "JavaScript" ]
3
Markdown
annadzuienko/Git_test
68f5dcb921b923b1e6f9c42ea7851230a2bb1a0c
838d636424fb59d9e4601143235ec24c5051d589
refs/heads/master
<repo_name>02gaurav/M.Tech-Thesis<file_sep>/README.md # There are various part of this thesis. I have uploaded modified cuckoo code for interval based memory dump. There is other code that describes analysis part. <file_sep>/create_result.sh for file in /home/gaurav/Malicious/*; do echo "$file" cuckoo submit $file > '/home/gaurav/fifile.txt' sleep 300s python /home/gaurav/delete.py mv /home/gaurav/.cuckoo/storage/analyses/* /media/gaurav/a7140a67-7b58-48f7-8c59-9b0154e5f001/Malware_dump done
5a6ba995df399730b9d1228a569c3b080c9e71ad
[ "Markdown", "Shell" ]
2
Markdown
02gaurav/M.Tech-Thesis
63a4337099083ad2c7caacb695726fb53dbb7c67
db1c0a15ea6b609304f380eb78c625b444de04cf
refs/heads/master
<repo_name>thurdai/vala-tests<file_sep>/build/src/25a6634@@com.github.thurdai.jarvis@exe/widgets/window.c /* window.c generated by valac 0.40.23, the Vala compiler * generated from window.vala, do not modify */ #include <glib.h> #include <glib-object.h> #include <gtk/gtk.h> #include <gio/gio.h> #include <gdk/gdk.h> #define JARVIS_TYPE_WINDOW (jarvis_window_get_type ()) #define JARVIS_WINDOW(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), JARVIS_TYPE_WINDOW, JarvisWindow)) #define JARVIS_WINDOW_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), JARVIS_TYPE_WINDOW, JarvisWindowClass)) #define JARVIS_IS_WINDOW(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), JARVIS_TYPE_WINDOW)) #define JARVIS_IS_WINDOW_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), JARVIS_TYPE_WINDOW)) #define JARVIS_WINDOW_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), JARVIS_TYPE_WINDOW, JarvisWindowClass)) typedef struct _JarvisWindow JarvisWindow; typedef struct _JarvisWindowClass JarvisWindowClass; typedef struct _JarvisWindowPrivate JarvisWindowPrivate; enum { JARVIS_WINDOW_0_PROPERTY, JARVIS_WINDOW_NUM_PROPERTIES }; static GParamSpec* jarvis_window_properties[JARVIS_WINDOW_NUM_PROPERTIES]; #define _g_object_unref0(var) ((var == NULL) ? NULL : (var = (g_object_unref (var), NULL))) #define TYPE_APPLICATION (application_get_type ()) #define APPLICATION(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), TYPE_APPLICATION, Application)) #define APPLICATION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), TYPE_APPLICATION, ApplicationClass)) #define IS_APPLICATION(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), TYPE_APPLICATION)) #define IS_APPLICATION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), TYPE_APPLICATION)) #define APPLICATION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), TYPE_APPLICATION, ApplicationClass)) typedef struct _Application Application; typedef struct _ApplicationClass ApplicationClass; struct _JarvisWindow { GtkApplicationWindow parent_instance; JarvisWindowPrivate * priv; GSettings* settings; }; struct _JarvisWindowClass { GtkApplicationWindowClass parent_class; }; static gpointer jarvis_window_parent_class = NULL; GType jarvis_window_get_type (void) G_GNUC_CONST; GType application_get_type (void) G_GNUC_CONST; JarvisWindow* jarvis_window_new (Application* app); JarvisWindow* jarvis_window_construct (GType object_type, Application* app); gboolean jarvis_window_before_destroy (JarvisWindow* self); static GObject * jarvis_window_constructor (GType type, guint n_construct_properties, GObjectConstructParam * construct_properties); static gboolean _jarvis_window___lambda4_ (JarvisWindow* self, GdkEventAny* e); static gboolean __jarvis_window___lambda4__gtk_widget_delete_event (GtkWidget* _sender, GdkEventAny* event, gpointer self); static void jarvis_window_finalize (GObject * obj); JarvisWindow* jarvis_window_construct (GType object_type, Application* app) { JarvisWindow * self = NULL; #line 5 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" g_return_val_if_fail (app != NULL, NULL); #line 6 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" self = (JarvisWindow*) g_object_new (object_type, "application", app, NULL); #line 5 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" return self; #line 82 "window.c" } JarvisWindow* jarvis_window_new (Application* app) { #line 5 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" return jarvis_window_construct (JARVIS_TYPE_WINDOW, app); #line 91 "window.c" } gboolean jarvis_window_before_destroy (JarvisWindow* self) { gboolean result = FALSE; gint width = 0; gint height = 0; gint x = 0; gint y = 0; gint _tmp0_ = 0; gint _tmp1_ = 0; gint _tmp2_ = 0; gint _tmp3_ = 0; GSettings* _tmp4_; GSettings* _tmp5_; GSettings* _tmp6_; GSettings* _tmp7_; #line 27 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" g_return_val_if_fail (self != NULL, FALSE); #line 29 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" gtk_window_get_size ((GtkWindow*) self, &_tmp0_, &_tmp1_); #line 29 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" width = _tmp0_; #line 29 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" height = _tmp1_; #line 30 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" gtk_window_get_position ((GtkWindow*) self, &_tmp2_, &_tmp3_); #line 30 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" x = _tmp2_; #line 30 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" y = _tmp3_; #line 32 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _tmp4_ = self->settings; #line 32 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" g_settings_set_int (_tmp4_, "pos-x", x); #line 33 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _tmp5_ = self->settings; #line 33 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" g_settings_set_int (_tmp5_, "pos-y", y); #line 34 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _tmp6_ = self->settings; #line 34 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" g_settings_set_int (_tmp6_, "window-width", width); #line 35 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _tmp7_ = self->settings; #line 35 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" g_settings_set_int (_tmp7_, "window-height", height); #line 37 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" result = FALSE; #line 37 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" return result; #line 145 "window.c" } static gboolean _jarvis_window___lambda4_ (JarvisWindow* self, GdkEventAny* e) { gboolean result = FALSE; #line 20 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" g_return_val_if_fail (e != NULL, FALSE); #line 21 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" result = jarvis_window_before_destroy (self); #line 21 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" return result; #line 160 "window.c" } static gboolean __jarvis_window___lambda4__gtk_widget_delete_event (GtkWidget* _sender, GdkEventAny* event, gpointer self) { gboolean result; result = _jarvis_window___lambda4_ ((JarvisWindow*) self, event); #line 20 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" return result; #line 173 "window.c" } static GObject * jarvis_window_constructor (GType type, guint n_construct_properties, GObjectConstructParam * construct_properties) { GObject * obj; GObjectClass * parent_class; JarvisWindow * self; GSettings* _tmp0_; GSettings* _tmp1_; GSettings* _tmp2_; GSettings* _tmp3_; GSettings* _tmp4_; #line 11 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" parent_class = G_OBJECT_CLASS (jarvis_window_parent_class); #line 11 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" obj = parent_class->constructor (type, n_construct_properties, construct_properties); #line 11 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" self = G_TYPE_CHECK_INSTANCE_CAST (obj, JARVIS_TYPE_WINDOW, JarvisWindow); #line 12 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" gtk_window_set_title ((GtkWindow*) self, "First Vala App"); #line 13 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" g_object_set ((GtkWindow*) self, "window-position", GTK_WIN_POS_CENTER, NULL); #line 14 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" gtk_window_set_default_size ((GtkWindow*) self, 400, 400); #line 16 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _tmp0_ = g_settings_new ("com.github.thurdai.jarvis"); #line 16 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _g_object_unref0 (self->settings); #line 16 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" self->settings = _tmp0_; #line 17 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _tmp1_ = self->settings; #line 17 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _tmp2_ = self->settings; #line 17 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" gtk_window_move ((GtkWindow*) self, g_settings_get_int (_tmp1_, "pos-x"), g_settings_get_int (_tmp2_, "pos-y")); #line 18 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _tmp3_ = self->settings; #line 18 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _tmp4_ = self->settings; #line 18 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" gtk_window_resize ((GtkWindow*) self, g_settings_get_int (_tmp3_, "window-width"), g_settings_get_int (_tmp4_, "window-height")); #line 20 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" g_signal_connect_object ((GtkWidget*) self, "delete-event", (GCallback) __jarvis_window___lambda4__gtk_widget_delete_event, self, 0); #line 24 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" gtk_widget_show_all ((GtkWidget*) self); #line 11 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" return obj; #line 226 "window.c" } static void jarvis_window_class_init (JarvisWindowClass * klass) { #line 1 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" jarvis_window_parent_class = g_type_class_peek_parent (klass); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" G_OBJECT_CLASS (klass)->constructor = jarvis_window_constructor; #line 1 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" G_OBJECT_CLASS (klass)->finalize = jarvis_window_finalize; #line 239 "window.c" } static void jarvis_window_instance_init (JarvisWindow * self) { } static void jarvis_window_finalize (GObject * obj) { JarvisWindow * self; #line 1 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" self = G_TYPE_CHECK_INSTANCE_CAST (obj, JARVIS_TYPE_WINDOW, JarvisWindow); #line 3 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" _g_object_unref0 (self->settings); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/widgets/window.vala" G_OBJECT_CLASS (jarvis_window_parent_class)->finalize (obj); #line 259 "window.c" } GType jarvis_window_get_type (void) { static volatile gsize jarvis_window_type_id__volatile = 0; if (g_once_init_enter (&jarvis_window_type_id__volatile)) { static const GTypeInfo g_define_type_info = { sizeof (JarvisWindowClass), (GBaseInitFunc) NULL, (GBaseFinalizeFunc) NULL, (GClassInitFunc) jarvis_window_class_init, (GClassFinalizeFunc) NULL, NULL, sizeof (JarvisWindow), 0, (GInstanceInitFunc) jarvis_window_instance_init, NULL }; GType jarvis_window_type_id; jarvis_window_type_id = g_type_register_static (gtk_application_window_get_type (), "JarvisWindow", &g_define_type_info, 0); g_once_init_leave (&jarvis_window_type_id__volatile, jarvis_window_type_id); } return jarvis_window_type_id__volatile; } <file_sep>/README.md # vala-tests Learning Vala for app development ( Tests ) <file_sep>/build/src/25a6634@@com.github.thurdai.jarvis@exe/Widgets/HeaderBar.c /* HeaderBar.c generated by valac 0.40.23, the Vala compiler * generated from HeaderBar.vala, do not modify */ #include <glib.h> #include <glib-object.h> #include <gtk/gtk.h> #define JARVIS_TYPE_HEADER_BAR (jarvis_header_bar_get_type ()) #define JARVIS_HEADER_BAR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), JARVIS_TYPE_HEADER_BAR, JarvisHeaderBar)) #define JARVIS_HEADER_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), JARVIS_TYPE_HEADER_BAR, JarvisHeaderBarClass)) #define JARVIS_IS_HEADER_BAR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), JARVIS_TYPE_HEADER_BAR)) #define JARVIS_IS_HEADER_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), JARVIS_TYPE_HEADER_BAR)) #define JARVIS_HEADER_BAR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), JARVIS_TYPE_HEADER_BAR, JarvisHeaderBarClass)) typedef struct _JarvisHeaderBar JarvisHeaderBar; typedef struct _JarvisHeaderBarClass JarvisHeaderBarClass; typedef struct _JarvisHeaderBarPrivate JarvisHeaderBarPrivate; #define JARVIS_TYPE_WINDOW (jarvis_window_get_type ()) #define JARVIS_WINDOW(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), JARVIS_TYPE_WINDOW, JarvisWindow)) #define JARVIS_WINDOW_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), JARVIS_TYPE_WINDOW, JarvisWindowClass)) #define JARVIS_IS_WINDOW(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), JARVIS_TYPE_WINDOW)) #define JARVIS_IS_WINDOW_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), JARVIS_TYPE_WINDOW)) #define JARVIS_WINDOW_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), JARVIS_TYPE_WINDOW, JarvisWindowClass)) typedef struct _JarvisWindow JarvisWindow; typedef struct _JarvisWindowClass JarvisWindowClass; enum { JARVIS_HEADER_BAR_0_PROPERTY, JARVIS_HEADER_BAR_MAIN_WINDOW_PROPERTY, JARVIS_HEADER_BAR_NUM_PROPERTIES }; static GParamSpec* jarvis_header_bar_properties[JARVIS_HEADER_BAR_NUM_PROPERTIES]; #define _g_object_unref0(var) ((var == NULL) ? NULL : (var = (g_object_unref (var), NULL))) struct _JarvisHeaderBar { GtkHeaderBar parent_instance; JarvisHeaderBarPrivate * priv; }; struct _JarvisHeaderBarClass { GtkHeaderBarClass parent_class; }; struct _JarvisHeaderBarPrivate { JarvisWindow* _main_window; }; static gpointer jarvis_header_bar_parent_class = NULL; GType jarvis_header_bar_get_type (void) G_GNUC_CONST; GType jarvis_window_get_type (void) G_GNUC_CONST; #define JARVIS_HEADER_BAR_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), JARVIS_TYPE_HEADER_BAR, JarvisHeaderBarPrivate)) JarvisHeaderBar* jarvis_header_bar_new (JarvisWindow* window); JarvisHeaderBar* jarvis_header_bar_construct (GType object_type, JarvisWindow* window); void jarvis_header_bar_open_dialog (JarvisHeaderBar* self); JarvisWindow* jarvis_header_bar_get_main_window (JarvisHeaderBar* self); static void jarvis_header_bar_set_main_window (JarvisHeaderBar* self, JarvisWindow* value); static GObject * jarvis_header_bar_constructor (GType type, guint n_construct_properties, GObjectConstructParam * construct_properties); static void _jarvis_header_bar_open_dialog_gtk_button_clicked (GtkButton* _sender, gpointer self); GtkStack* jarvis_window_get_stack (JarvisWindow* self); static void jarvis_header_bar_finalize (GObject * obj); static void _vala_jarvis_header_bar_get_property (GObject * object, guint property_id, GValue * value, GParamSpec * pspec); static void _vala_jarvis_header_bar_set_property (GObject * object, guint property_id, const GValue * value, GParamSpec * pspec); JarvisHeaderBar* jarvis_header_bar_construct (GType object_type, JarvisWindow* window) { JarvisHeaderBar * self = NULL; #line 5 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_return_val_if_fail (window != NULL, NULL); #line 6 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" self = (JarvisHeaderBar*) g_object_new (object_type, "main-window", window, NULL); #line 5 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" return self; #line 94 "HeaderBar.c" } JarvisHeaderBar* jarvis_header_bar_new (JarvisWindow* window) { #line 5 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" return jarvis_header_bar_construct (JARVIS_TYPE_HEADER_BAR, window); #line 103 "HeaderBar.c" } static gpointer _g_object_ref0 (gpointer self) { #line 47 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" return self ? g_object_ref (self) : NULL; #line 112 "HeaderBar.c" } void jarvis_header_bar_open_dialog (JarvisHeaderBar* self) { GtkDialog* dialog = NULL; JarvisWindow* _tmp0_; GtkDialog* _tmp1_; GtkLabel* label = NULL; GtkLabel* _tmp2_; GtkBox* content_area = NULL; GtkBox* _tmp3_; GtkBox* _tmp4_; #line 35 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_return_if_fail (self != NULL); #line 37 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp0_ = self->priv->_main_window; #line 37 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp1_ = (GtkDialog*) gtk_dialog_new_with_buttons ("Add a note", (GtkWindow*) _tmp0_, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, "Button 1", 1, "Button 2", 2, NULL, NULL); #line 37 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_object_ref_sink (_tmp1_); #line 37 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" dialog = _tmp1_; #line 46 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp2_ = (GtkLabel*) gtk_label_new ("This is content"); #line 46 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_object_ref_sink (_tmp2_); #line 46 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" label = _tmp2_; #line 47 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp3_ = gtk_dialog_get_content_area (dialog); #line 47 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp4_ = _g_object_ref0 (_tmp3_); #line 47 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" content_area = _tmp4_; #line 48 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_container_add ((GtkContainer*) content_area, (GtkWidget*) label); #line 50 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_widget_show_all ((GtkWidget*) dialog); #line 51 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_window_present ((GtkWindow*) dialog); #line 35 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _g_object_unref0 (content_area); #line 35 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _g_object_unref0 (label); #line 35 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _g_object_unref0 (dialog); #line 161 "HeaderBar.c" } JarvisWindow* jarvis_header_bar_get_main_window (JarvisHeaderBar* self) { JarvisWindow* result; JarvisWindow* _tmp0_; #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_return_val_if_fail (self != NULL, NULL); #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp0_ = self->priv->_main_window; #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" result = _tmp0_; #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" return result; #line 178 "HeaderBar.c" } static void jarvis_header_bar_set_main_window (JarvisHeaderBar* self, JarvisWindow* value) { #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_return_if_fail (self != NULL); #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" if (jarvis_header_bar_get_main_window (self) != value) { #line 190 "HeaderBar.c" JarvisWindow* _tmp0_; #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp0_ = _g_object_ref0 (value); #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _g_object_unref0 (self->priv->_main_window); #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" self->priv->_main_window = _tmp0_; #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_object_notify_by_pspec ((GObject *) self, jarvis_header_bar_properties[JARVIS_HEADER_BAR_MAIN_WINDOW_PROPERTY]); #line 200 "HeaderBar.c" } } static void _jarvis_header_bar_open_dialog_gtk_button_clicked (GtkButton* _sender, gpointer self) { #line 26 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" jarvis_header_bar_open_dialog ((JarvisHeaderBar*) self); #line 211 "HeaderBar.c" } static GObject * jarvis_header_bar_constructor (GType type, guint n_construct_properties, GObjectConstructParam * construct_properties) { GObject * obj; GObjectClass * parent_class; JarvisHeaderBar * self; GtkButton* menu_button = NULL; GtkButton* _tmp0_; GtkButton* _tmp1_; GtkButton* _tmp2_; GtkButton* add_button = NULL; GtkButton* _tmp3_; GtkButton* _tmp4_; GtkStyleContext* _tmp5_; GtkButton* _tmp6_; GtkButton* _tmp7_; GtkButton* _tmp8_; GtkStackSwitcher* stack_switcher = NULL; GtkStackSwitcher* _tmp9_; GtkStackSwitcher* _tmp10_; JarvisWindow* _tmp11_; GtkStack* _tmp12_; GtkStack* _tmp13_; GtkStackSwitcher* _tmp14_; #line 11 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" parent_class = G_OBJECT_CLASS (jarvis_header_bar_parent_class); #line 11 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" obj = parent_class->constructor (type, n_construct_properties, construct_properties); #line 11 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" self = G_TYPE_CHECK_INSTANCE_CAST (obj, JARVIS_TYPE_HEADER_BAR, JarvisHeaderBar); #line 15 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_header_bar_set_show_close_button ((GtkHeaderBar*) self, TRUE); #line 17 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp0_ = (GtkButton*) gtk_button_new_from_icon_name ("applications-system-symbolic", (GtkIconSize) GTK_ICON_SIZE_BUTTON); #line 17 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_object_ref_sink (_tmp0_); #line 17 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" menu_button = _tmp0_; #line 18 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp1_ = menu_button; #line 18 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_widget_set_valign ((GtkWidget*) _tmp1_, GTK_ALIGN_CENTER); #line 19 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp2_ = menu_button; #line 19 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_header_bar_pack_start ((GtkHeaderBar*) self, (GtkWidget*) _tmp2_); #line 21 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp3_ = (GtkButton*) gtk_button_new_with_label ("Add"); #line 21 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_object_ref_sink (_tmp3_); #line 21 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" add_button = _tmp3_; #line 22 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp4_ = add_button; #line 22 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp5_ = gtk_widget_get_style_context ((GtkWidget*) _tmp4_); #line 22 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_style_context_add_class (_tmp5_, "suggested-action"); #line 23 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp6_ = add_button; #line 23 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_widget_set_valign ((GtkWidget*) _tmp6_, GTK_ALIGN_CENTER); #line 24 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp7_ = add_button; #line 24 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_header_bar_pack_start ((GtkHeaderBar*) self, (GtkWidget*) _tmp7_); #line 26 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp8_ = add_button; #line 26 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_signal_connect_object (_tmp8_, "clicked", (GCallback) _jarvis_header_bar_open_dialog_gtk_button_clicked, self, 0); #line 28 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp9_ = (GtkStackSwitcher*) gtk_stack_switcher_new (); #line 28 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_object_ref_sink (_tmp9_); #line 28 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" stack_switcher = _tmp9_; #line 30 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp10_ = stack_switcher; #line 30 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp11_ = self->priv->_main_window; #line 30 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp12_ = jarvis_window_get_stack (_tmp11_); #line 30 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp13_ = _tmp12_; #line 30 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_stack_switcher_set_stack (_tmp10_, _tmp13_); #line 32 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _tmp14_ = stack_switcher; #line 32 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" gtk_header_bar_set_custom_title ((GtkHeaderBar*) self, (GtkWidget*) _tmp14_); #line 11 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _g_object_unref0 (stack_switcher); #line 11 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _g_object_unref0 (add_button); #line 11 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _g_object_unref0 (menu_button); #line 11 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" return obj; #line 315 "HeaderBar.c" } static void jarvis_header_bar_class_init (JarvisHeaderBarClass * klass) { #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" jarvis_header_bar_parent_class = g_type_class_peek_parent (klass); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_type_class_add_private (klass, sizeof (JarvisHeaderBarPrivate)); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" G_OBJECT_CLASS (klass)->get_property = _vala_jarvis_header_bar_get_property; #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" G_OBJECT_CLASS (klass)->set_property = _vala_jarvis_header_bar_set_property; #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" G_OBJECT_CLASS (klass)->constructor = jarvis_header_bar_constructor; #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" G_OBJECT_CLASS (klass)->finalize = jarvis_header_bar_finalize; #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_object_class_install_property (G_OBJECT_CLASS (klass), JARVIS_HEADER_BAR_MAIN_WINDOW_PROPERTY, jarvis_header_bar_properties[JARVIS_HEADER_BAR_MAIN_WINDOW_PROPERTY] = g_param_spec_object ("main-window", "main-window", "main-window", JARVIS_TYPE_WINDOW, G_PARAM_STATIC_STRINGS | G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY)); #line 336 "HeaderBar.c" } static void jarvis_header_bar_instance_init (JarvisHeaderBar * self) { #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" self->priv = JARVIS_HEADER_BAR_GET_PRIVATE (self); #line 345 "HeaderBar.c" } static void jarvis_header_bar_finalize (GObject * obj) { JarvisHeaderBar * self; #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" self = G_TYPE_CHECK_INSTANCE_CAST (obj, JARVIS_TYPE_HEADER_BAR, JarvisHeaderBar); #line 3 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" _g_object_unref0 (self->priv->_main_window); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" G_OBJECT_CLASS (jarvis_header_bar_parent_class)->finalize (obj); #line 359 "HeaderBar.c" } GType jarvis_header_bar_get_type (void) { static volatile gsize jarvis_header_bar_type_id__volatile = 0; if (g_once_init_enter (&jarvis_header_bar_type_id__volatile)) { static const GTypeInfo g_define_type_info = { sizeof (JarvisHeaderBarClass), (GBaseInitFunc) NULL, (GBaseFinalizeFunc) NULL, (GClassInitFunc) jarvis_header_bar_class_init, (GClassFinalizeFunc) NULL, NULL, sizeof (JarvisHeaderBar), 0, (GInstanceInitFunc) jarvis_header_bar_instance_init, NULL }; GType jarvis_header_bar_type_id; jarvis_header_bar_type_id = g_type_register_static (gtk_header_bar_get_type (), "JarvisHeaderBar", &g_define_type_info, 0); g_once_init_leave (&jarvis_header_bar_type_id__volatile, jarvis_header_bar_type_id); } return jarvis_header_bar_type_id__volatile; } static void _vala_jarvis_header_bar_get_property (GObject * object, guint property_id, GValue * value, GParamSpec * pspec) { JarvisHeaderBar * self; self = G_TYPE_CHECK_INSTANCE_CAST (object, JARVIS_TYPE_HEADER_BAR, JarvisHeaderBar); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" switch (property_id) { #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" case JARVIS_HEADER_BAR_MAIN_WINDOW_PROPERTY: #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" g_value_set_object (value, jarvis_header_bar_get_main_window (self)); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" break; #line 393 "HeaderBar.c" default: #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" break; #line 399 "HeaderBar.c" } } static void _vala_jarvis_header_bar_set_property (GObject * object, guint property_id, const GValue * value, GParamSpec * pspec) { JarvisHeaderBar * self; self = G_TYPE_CHECK_INSTANCE_CAST (object, JARVIS_TYPE_HEADER_BAR, JarvisHeaderBar); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" switch (property_id) { #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" case JARVIS_HEADER_BAR_MAIN_WINDOW_PROPERTY: #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" jarvis_header_bar_set_main_window (self, g_value_get_object (value)); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" break; #line 420 "HeaderBar.c" default: #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); #line 1 "/home/thurdai/Documents/apps/vala-tests/src/Widgets/HeaderBar.vala" break; #line 426 "HeaderBar.c" } }
22712a8d80dc857b1be684a8f27fd9ba2487aae3
[ "Markdown", "C" ]
3
C
thurdai/vala-tests
c9aa686d52e578e0e859d3d216449a816277d3e9
ab23680a6ec603d81722bfe9b76d6e001ad90aea
refs/heads/master
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Example * * This is an example of a few basic user interaction methods you could use * all done with a hardcoded array. * * @package CodeIgniter * @subpackage Rest Server * @category Controller * @author <NAME> * @link http://philsturgeon.co.uk/code/ */ // This can be removed if you use __autoload() in config.php OR use Modular Extensions require APPPATH.'/libraries/REST_Controller.php'; class Authanticate extends CI_Controller { function index() { var_dump($_POST); echo $this->input->post('username'); } function getlogo() { list($sitetitle,$sitelink,$sitelogo)=getMultiValue("settings",array("site_name","site_link","logo"),"id",1); echo $sitelogo; } function test_get(){ $id = $this->session->userdata('id'); $id = $this->session->userdata('apikey'); var_dump($id); echo $id == false; // echo 'Total Results: ' . $query->num_rows(); } function get_get(){ echo 123; } function getid(){ $apikey=$_REQUEST['id']; $q = $this->db->query("select user_id from apikeys where keyval='{$apikey}' and date_created >= now() - INTERVAL 1 DAY "); if($q->num_rows>0) { $r=$q->result(); $date_created=intval($r[0]->user_id); header("HTTP/1.1 200 OK"); echo json_encode(array('status' => $date_created)); return; } else { header("HTTP/1.1 200 OK"); echo json_encode(array('error' => 'failed')); return; } return; } function checkjcr(){ echo $this->session->userdata('jcr'); return; } function chkwork(){ echo $this->session->userdata('work order'); return; } function chkusers(){ echo $this->session->userdata('users'); return; } function login() { // $rawpostdata = file_get_contents("php://input"); // $post = json_decode($rawpostdata, true); // $username = $post['username']; // $password = $post['password']; if (!isset($_POST['username']) || !isset($_POST['password'])) { header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'invalid parameters')); return; } $username = $_POST['username']; $password = $_POST['<PASSWORD>']; if (empty($username) || empty($password) || !preg_match('/^[a-zA-Z0-9_]*$/', $username)) { header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'fail', 'error' => 'invalid input')); return; } $username = addslashes($username); $password = addslashes($password); $password = md5($password); $query = $this->db->query("SELECT id, username, password, avatar, roles, email FROM user WHERE username='{$username}' and password='{$<PASSWORD>}' and status=1 "); //jcr_modules, users_modules, work_modules, tickets_modules,jobs_modules, ivc_modules,timecard_modules, if($query->num_rows > 0){ $result = $query->result(); $id = $result[0]->id; $username = $result[0]->username; $avatar = $result[0]->avatar; $roles = $result[0]->roles; $email = $result[0]->email; /*$jcr_modules = $result[0]->jcr_modules; $users_modules = $result[0]->users_modules; $work_modules = $result[0]->work_modules; $tickets_modules = $result[0]->tickets_modules; $jobs_modules = $result[0]->jobs_modules; $ivc_modules = $result[0]->ivc_modules; $timecard_modules = $result[0]->timecard_modules;*/ $roles = $result[0]->roles; /*if($modules!='') { $modules=explode(',',$modules); foreach($modules as $k=>$v) { $this->session->set_userdata($v, 1); } }*/ $this->db->select("u.id, u.employee_id, e.first_name"); $this->db->from("user u"); $this->db->join('employees e', 'u.employee_id=e.id', 'left'); $this->db->where('u.id',$id); $name_query = $this->db->get(); $name_arr = $name_query->result_array(); $this->session->set_userdata('user_display_name', $name_arr[0]['first_name']); if($name_arr[0]['employee_id']<=0) { $this->session->set_userdata('user_display_name', $username); } $this->db->where('id', $id); $this->db->update('user',array('last_login'=>date('Y-m-d h:i:s'))); $this->session->set_userdata('id', $id); $this->session->set_userdata('username', $username); $this->session->set_userdata('avatar', $avatar); $apikey = md5($id . $username . time()); $this->session->set_userdata('apikey', $apikey); $this->load->config('aws_sdk'); $this->session->set_userdata('avatar', $this->config->item('hallen_bucket').'/'.$this->config->item('environment_path').'/'.$this->config->item('users_module').'/'.$avatar); /*$this->session->set_userdata('jcr_modules', $jcr_modules); $this->session->set_userdata('users_modules', $users_modules); $this->session->set_userdata('work_modules', $work_modules); $this->session->set_userdata('tickets_modules', $tickets_modules); $this->session->set_userdata('jobs_modules', $jobs_modules); $this->session->set_userdata('ivc_modules', $ivc_modules); $this->session->set_userdata('timecard_modules', $timecard_modules);*/ $this->session->set_userdata('roles', $roles); $this->session->set_userdata('email', $email); $data = array( 'keyval' => $apikey, 'user_id' => $id ); $this->db->query("DELETE from apikeys where user_id='{$id}'"); $this->db->insert('apikeys', $data); header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'successs', 'apikey' => $apikey)); // $this->response(array('status' => 'successs'), 200); }else{ header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'fail')); // $this->response(array('status' => 'fail'), 200); } // echo 'Total Results: ' . $query->num_rows(); } function passupdate(){ $guid = $this->input->post('id'); $password = $this->input->post('password'); $q1 = $this->db->query("select user_id from apikeys where keyval='{$guid}' and date_created >= now() - INTERVAL 1 DAY "); if($q1->num_rows>0) { $rdata = $q1->result(); $id = $rdata[0]->user_id; $sql = "DELETE from `apikeys` where `user_id`='{$id}'"; //Delete apikey $this->db->query($sql = "DELETE from `apikeys` where `user_id`='{$id}'"); $q = $this->db->query("select * from user where id='".$id."' "); if($q->num_rows>0) { $r = $q->result(); $email=$r[0]->email; $this->db->where('id', $id); $this->db->update('user',array('password'=>MD5($password))); $this->load->helper('url'); $burl=base_url(); $baseurl=$burl; $this->load->library('email'); $this->email->set_mailtype("html"); $this->email->from('<EMAIL>', 'Hallen Construction'); $this->email->to($email); $this->email->subject('(PLEASE IGNORE - FOR TESTING PURPOSES ONLY) Your new password reset successfully'); $body='Your password successfully reset, You should login now with new password: <a href="'.$baseurl.'">Login</a>.'; $this->email->message($body); $this->email->send(); $data = "Password successfullt reset please login with new password"; header("HTTP/1.1 200 OK"); echo json_encode(array('status' => $data)); return; } header("HTTP/1.1 200 OK"); echo json_encode(array('error' => 'duplicate')); return; //header("HTTP/1.1 200 OK"); //echo json_encode(array('error' => 'notmatched')); //return; } } function resetpass(){ $username= $_POST['username']; if (empty($username)) { //$this->response(array('status' => 'false', 'error' => 'Enter valid email address.'), 403); header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'Enter valid username.')); return; } $q = $this->db->query("select * from user where username='".$username."' "); if ($q->num_rows > 0) { $r = $q->result(); //print_r($r); $id=$r[0]->id; $email=$r[0]->email; $qq = $this->db->query("select * from apikeys where user_id='".$id."' "); if($qq->num_rows>0) { $rr=$qq->result(); $date_created=$rr[0]->date_created; if(time()-strtotime($date_created) > 60*60*24) { $this->db->query("DELETE from `apikeys` where `user_id`='{$id}'"); $apikey = md5($id . $username . time()); $data = array( 'keyval' => $apikey, 'user_id' => $id, 'date_created' => date('Y-m-d h:i:s') ); $this->db->insert('apikeys', $data); $this->resetpassword($apikey,$email); $data = "Reset password link again send to: ". $email; header("HTTP/1.1 200 OK"); echo json_encode(array('status' => $data)); return; } else { header("HTTP/1.1 200 OK"); echo json_encode(array('error' => 'failed')); return; } } else { $apikey = md5($id . $username . time()); $data = array( 'keyval' => $apikey, 'user_id' => $id, 'date_created' => date('Y-m-d h:i:s') ); $this->db->insert('apikeys', $data); $this->resetpassword($apikey,$email); $data = "Reset password link send to: ". $email; header("HTTP/1.1 200 OK"); echo json_encode(array('status' => $data)); return; } } header("HTTP/1.1 200 OK"); //echo json_encode(array('error' => 'Your email address not registered.')); echo json_encode(array('error' => 'duplicate')); //$this->response(array('status' => 'false', 'error' => 'Your email address not registered.'), 403); } private function resetpassword($apikey,$email) { $this->load->helper('string'); //$password= random_string('alnum', 16); //$this->db->where('id', $user->id); //$this->db->update('user',array('password'=>MD5($password))); $this->load->helper('url'); $burl=base_url(); //echo $email; $baseurl=$burl.'#/reset/'.$apikey; //$baseurl= $this->config->base_url().'reset/'.$user->id; //$link=base64_encode($user); $this->load->library('email'); $this->email->set_mailtype("html"); $this->email->from('<EMAIL>', 'Hallen Construction'); $this->email->to($email); $this->email->subject('(PLEASE IGNORE - FOR TESTING PURPOSES ONLY) Your Password Reset Link'); //$this->email->message('You have requested the new password, Here is you new password: '); $body='Please <a href="'.$baseurl.'">click here</a> to reset your password. <br /><br /> You should reset new password within 24 hours using this link otherwise you need to again reset that.'; $this->email->message($body); $this->email->send(); } function signup(){ // $rawpostdata = file_get_contents("php://input"); // $post = json_decode($rawpostdata, true); // $username = $post['username']; // $password = $post['password']; if (!isset($_POST['username']) || !isset($_POST['password'])) { header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'invalid parameters')); return; } $username = $_POST['username']; $password = $_POST['password']; if (empty($username) || empty($password) || strlen($username) > 20 || strlen($password) > 20 || !preg_match('/^[a-zA-Z0-9_]*$/', $username)) { header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'invalid parameters')); return; } $username = addslashes($username); $password = <PASSWORD>($<PASSWORD>); $password = md5($<PASSWORD>); $query = $this->db->query("SELECT username, password FROM user WHERE username='{$username}'"); if ($query->num_rows > 0) { // $this->response(array('error' => 'duplicate user'), 200); header("HTTP/1.1 200 OK"); echo json_encode(array('error' => 'duplicate')); } else { $data = array( 'username' => $username, 'password' => $<PASSWORD>, ); $this->db->insert('user', $data); $query = $this->db->query("SELECT id FROM user WHERE username='{$username}'"); //set session after user signup successfully if ($query->num_rows == 1) { $result = $query->result(); $id = $result[0]->id; $this->session->set_userdata('id', $id); $apikey = md5($id . $username . time()); $this->session->set_userdata('apikey', $apikey); $data = array( 'keyval' => $apikey, 'user_id' => $id ); $this->db->insert('apikeys', $data); // $this->response(array('status' => 'success', 'id' => $id), 200); header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'success', 'id' => $id, 'apikey' => $apikey)); } } // echo 'Total Results: ' . $query->num_rows(); } function logout(){ $apikey = $this->session->userdata('apikey'); $this->session->sess_destroy(); if (!empty($apikey)) { $this->db->query("DELETE from `apikeys` where `keyval`='{$apikey}'"); } // return $this->response(array('status' => 'success'), 200); header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'successs')); // echo 'Total Results: ' . $query->num_rows(); } function login_get(){ $id = $this->session->userdata('id'); return $id !== FALSE? $this->response(array('status' => 'true'), 200): $this->response(array('status' => 'false'), 200); // echo 'Total Results: ' . $query->num_rows(); } function user_get() { if(!$this->get('id')) { $this->response(NULL, 400); } // $user = $this->some_model->getSomething( $this->get('id') ); $users = array( 1 => array('id' => 1, 'name' => '<NAME>', 'email' => '<EMAIL>', 'fact' => 'Loves swimming'), 2 => array('id' => 2, 'name' => 'Person Face', 'email' => '<EMAIL>', 'fact' => 'Has a huge face'), 3 => array('id' => 3, 'name' => 'Scotty', 'email' => '<EMAIL>', 'fact' => 'Is a Scott!', array('hobbies' => array('fartings', 'bikes'))), ); $user = @$users[$this->get('id')]; if($user) { $this->response($user, 200); // 200 being the HTTP response code } else { $this->response(array('error' => 'User could not be found'), 404); } } function user_post() { //$this->some_model->updateUser( $this->get('id') ); $message = array('id' => $this->get('id'), 'name' => $this->post('name'), 'email' => $this->post('email'), 'message' => 'ADDED!'); $this->response($message, 200); // 200 being the HTTP response code } function user_delete() { //$this->some_model->deletesomething( $this->get('id') ); $message = array('id' => $this->get('id'), 'message' => 'DELETED!'); $this->response($message, 200); // 200 being the HTTP response code } function users_get() { //$users = $this->some_model->getSomething( $this->get('limit') ); $users = array( array('id' => 1, 'name' => '<NAME>', 'email' => '<EMAIL>'), array('id' => 2, 'name' => '<NAME>', 'email' => '<EMAIL>'), 3 => array('id' => 3, 'name' => 'Scotty', 'email' => '<EMAIL>', 'fact' => array('hobbies' => array('fartings', 'bikes'))), ); if($users) { $this->response($users, 200); // 200 being the HTTP response code } else { $this->response(array('error' => 'Couldn\'t find any users!'), 404); } } public function send_post() { var_dump($this->request->body); } public function send_put() { var_dump($this->put('foo')); } /*Get all data from database*/ function roleslist() { $query = $this->db->query("SELECT * FROM user_roles WHERE 1=1 order by role asc "); $result = $query->result(); $data = array(); foreach($result as $item){ // $data->title = $item.title; // $data->desc = $item.desc; // $data->id = $item.id; // $data->amount = $item.amount; // $item->comments = $this->getComments($item->id); } print_r(json_encode($result)); //header("HTTP/1.1 200 OK"); //echo json_encode(array('data' => $result)); //return; } /*Get all data from database*/ /*Get all data from database*/ function getlist() { $query = $this->db->query("SELECT u.*, if(u.status=1,'Active','Blocked') as status, r.role FROM user u left join user_roles r ON r.id=u.roles WHERE 1=1 order by u.id desc "); $result = $query->result(); $data = array(); foreach($result as $item){ // $data->title = $item.title; // $data->desc = $item.desc; // $data->id = $item.id; // $data->amount = $item.amount; // $item->comments = $this->getComments($item->id); } print_r(json_encode($result)); //header("HTTP/1.1 200 OK"); //echo json_encode(array('data' => $result)); //return; } /*Get all data from database*/ /*Get all data from database*/ function getlist1() { $id=intval($_REQUEST['id']); $query = $this->db->query("SELECT u.*, r.role FROM user u left join user_roles r ON r.id=u.roles WHERE u.id={$id} order by u.id desc "); //if(u.status=1,'Active','Blocked') as status, $result = $query->result(); $data = array(); foreach($result as $item){ // $data->title = $item.title; // $data->desc = $item.desc; // $data->id = $item.id; // $data->amount = $item.amount; // $item->comments = $this->getComments($item->id); } //print_r(json_encode($result)); header("HTTP/1.1 200 OK"); echo json_encode(array('data' => $result)); return; } /*Get all data from database*/ function allDelete() { $ids = implode(",",array_filter($_REQUEST['user_ids'])); $this->db->query("DELETE FROM user WHERE id IN (".$ids.")"); //$this->getlist(); return; } /*Delete single record.*/ function deletesingle() { $id = $_REQUEST['id']; $query = $this->db->query("SELECT * from user WHERE id='{$id}' "); if ($query->num_rows === 0) { //nothing to delete in the DB header("HTTP/1.1 200 OK"); echo json_encode(array('data' => 'not exists')); return; } else { $this->db->query("DELETE from user where id='{$id}' "); header("HTTP/1.1 200 OK"); echo json_encode(array('status' => 'success')); return; } } /*Add single record*/ function add() { $username=stripslashes($_REQUEST['username']); $email=stripslashes($_REQUEST['email']); $projects=implode(",",array_filter($_REQUEST['projects'])); $data = array( 'username' => stripslashes($_REQUEST['username']), 'password' => md5($_REQUEST['password']), 'email' => stripslashes($_REQUEST['email']), 'status' => intval($_REQUEST['status']), 'roles' => intval($_REQUEST['roles']), 'projects' => $projects ); $query = $this->db->query("SELECT id FROM user WHERE username='{$username}'"); if ($query->num_rows == 1) { header("HTTP/1.1 200 OK"); echo json_encode(array('error' => 'duplicate')); return; } $query = $this->db->query("SELECT id FROM user WHERE email='{$email}'"); if ($query->num_rows == 1) { header("HTTP/1.1 200 OK"); echo json_encode(array('error' => 'duplicate email')); return; } $this->db->insert('user', $data); $id = $this->db->insert_id(); if($id>0) { header("HTTP/1.1 200 OK"); echo json_encode(array('data' => 'success')); return; } } /*Add single record*/ /*Update single record*/ function update(){ $id=intval($_REQUEST['id']); $username=stripslashes($_REQUEST['username']); $email=stripslashes($_REQUEST['email']); $projects=implode(",",$_REQUEST['projects']); $modules=implode(",",$_REQUEST['modules']); if($_REQUEST['password']!=''){ $password = md5($_REQUEST['password']); } else { $password=$_REQUEST['oldpassword']; } $data = array( 'username' => stripslashes($_REQUEST['username']), 'password' => <PASSWORD>, 'email' => stripslashes($_REQUEST['email']), 'status' => intval($_REQUEST['status']), 'roles' => intval($_REQUEST['roles']), 'projects' => $projects, 'modules' => $modules, ); $query = $this->db->query("SELECT id FROM user WHERE username='{$username}' and id!='{$id}' "); if ($query->num_rows == 1) { header("HTTP/1.1 200 OK"); echo json_encode(array('error' => 'duplicate')); return; } $query = $this->db->query("SELECT id FROM user WHERE email='{$email}' and id!='{$id}' "); if ($query->num_rows == 1) { header("HTTP/1.1 200 OK"); echo json_encode(array('error' => 'duplicate email')); return; } $this->db->where('id', $id); $this->db->update('user', $data); header("HTTP/1.1 200 OK"); echo json_encode(array('data' => 'success')); return; } /*Update single record*/ } <file_sep>// var qs = document.querySelectorAll; angular.module('project', ['ngRoute']) .constant('VALID_USERNAME', /^[a-zA-Z0-9_]*$/) .factory('List', function($http) { var service = { list: [ {name:'gee', age: 25}, {name:'yury', age:25} ] }; return service; }) .factory('User', function($http, $q) { console.log(123); var service = { islogin: window.islogin, apikey: window.apikey, username: '', signup: function(username, password, callback){ $http({ method: 'post', data: $.param({username: username, password: <PASSWORD>}), url: siteUrl + 'REST/authanticate/signup', headers: {'Content-Type': 'application/x-www-form-urlencoded'} }) .success(callback) .error(function(){}); }, resetpass: function(username, callback){ $http({ method: 'post', data: $.param({username: username}), url: siteUrl + 'REST/authanticate/resetpass', headers: {'Content-Type': 'application/x-www-form-urlencoded'} }) .success(callback) .error(function(){}); }, login: function(username, password, callback){ $http({ method: 'post', data: $.param({username: username, password: <PASSWORD>}), url: siteUrl + 'REST/authanticate/login', headers: {'Content-Type': 'application/x-www-form-urlencoded'} }) .success(callback) .error(function(){}); // .post(siteUrl + '/REST/user/login', {username: username, password: <PASSWORD>}) }, logout: function(callback){ $http.get(siteUrl + 'REST/authanticate/logout') .success(function(){ service.islogin = false; callback(); }) .error(function(){ }); }, passupdate: function(password, id, callback){ /*var data = { id: password.id, name: password.password };*/ $http({ method: 'post', data: $.param({id: id, password: <PASSWORD>}), url: siteUrl + 'REST/authanticate/passupdate', headers: {'Content-Type': 'application/x-www-form-urlencoded'} }) .success(callback) .error(function(){}); }, get: function(callback,id){ if(service.initialized){ callback(); return; } $http({ method: 'POST', url: siteUrl + 'REST/authanticate/getid', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: $.param({id: id}), }) .success(callback) .error(function(){}); }, checkAuth: function(callback){ var d = $q.defer(); $http.get(siteUrl + 'REST/authanticate/login') .success(function(data){ if(data.status === 'true'){ service.islogin = true; callback(); d.resolve(); }else{ service.islogin = false; } }) .error(function(){ d.reject(); }); } }; return service; }) .config(function($routeProvider){ $routeProvider .when('/', { controller: 'indexController', templateUrl: 'application/views/login.html' }) .when('/reset-password', { controller: 'resetController', templateUrl: 'application/views/reset-password.html' }) .when('/reset/:id', { controller: 'resetPassController', templateUrl: 'application/views/resetpass.html' }) /*.when('/signup', { controller: 'signupController', templateUrl: 'asset/signup.html' }) .when('/reset-password', { controller: 'resetController', templateUrl: 'asset/reset-password.html' }) .when('/reset/:id', { controller: 'resetPassController', templateUrl: 'asset/resetpass.html' }) .when('/dashboard',{ controller: 'dashboardController', templateUrl: 'asset/dashboard.php' }) .when('/users',{ controller: 'usersController', templateUrl: 'asset/users/users.php' }) .when('/add',{ controller: 'usersController', templateUrl: 'asset/users/add.php' }) .when('/edit/:id',{ controller: 'usersEditController', templateUrl: 'asset/users/edit.php' }) .when('/jcr',{ controller: 'jcrController', templateUrl: 'asset/jcr/list.php' }) .when('/workflow',{ controller: 'workflowController', templateUrl: 'asset/workflow/list.php' }) //Not Used .when('/timezone',{ controller: 'timezoneController', templateUrl: 'asset/timezone/timezone.html' })*/ /*.when('/add',{ controller: 'timezoneController', templateUrl: 'asset/timezone/add.html' }) .when('/edit/:id',{ controller: 'timezoneEditController', templateUrl: 'asset/timezone/edit.html' })*/ .otherwise({ redirectTo: '/' }); }) .controller('indexController', function($scope, List, $location, User, VALID_USERNAME){ /*setTimeout(function(){ $(".off-canvas-submenu").hide(); $(".off-canvas-submenu-call").click(function() { $(this).parent().next(".off-canvas-submenu").slideToggle('fast'); }); $(document).foundation(); }, 500);*/ $scope.errors = []; //$scope.inputName = ''; $scope.list = List.list; if(User.islogin){ //$location.path('dashboard'); window.location = 'dashboard'; } $scope.goToSignUp = function() { $location.path('/signup'); }; $scope.goToResetPass = function() { $location.path('/reset-password'); }; $scope.goToEdit = function(id){ $location.path('/reset/' + id); }; $scope.login = function() { this.errors = []; if(_validate.apply(this, null)){ User.login(this.username, this.password, _loginCallback); } }; $scope.inputFocus = function(){ this.errors = []; }; var _validate = function(){ var username = $('#username').val(), error, valid = false, password = $('#<PASSWORD>').val(); if (!username || !password) { this.errors.push('Invalid username or password!'); } if (username.length > 20 || password.length > 20) { this.errors.push('Username or password should not exceed 20 character'); } this.username = username; this.password = <PASSWORD>; return !this.errors.length; }; var _loginCallback = function(data){ if(data.status == 'fail') { $scope.errors.push('Wrong username or password!'); } else { User.islogin = true; User.apikey = data.apikey; console.log('apikey is', data.apikey); User.username = this.username; $location.path('/expense'); } }; $scope.addPerson = function(){ console.log(this === $scope); console.log($scope); this.list.push({name: this.inputName, age: 25}); } }) .controller('resetPassController', function($scope, User, $location, $http, $routeParams, VALID_USERNAME){ $scope.errors = []; $scope.passupdate = function(){ $location.path('/reset/' + id); }; $scope.goToResetPass = function() { $location.path('/reset-password'); }; /*var _getCallback = function(data){ if(data.error === 'failed') { $scope.errors.push('Your reset password link expired, Please reset again.'); $('#hidethis').hide(); $('#hidebtn').hide(); } else { $('#hidethis').show(); $('#hidebtn').show(); $scope.errors.push('Please enter new password.'); $scope.id = data.status; } };*/ //var pathname = window.location.pathname.split("#"); //var filename = pathname[pathname.length-1]; var type = window.location.hash.substr(1); var pathname = type.split("/"); var uID = pathname[pathname.length-1]; $scope.id = uID; //User.get(_getCallback,uID); //$scope.username = ''; $scope.password = ''; $scope.passupdate = function(id){ this.errors = []; if(_validate.apply(this, null)){ //User.passupdate(this.password, _signupCallback); User.passupdate(this.password, this.id, _loginCallback); /*User.passupdate(this.password,id).success(function(data) { alert(data); }).error(function(data){ //TBC alert(data.error) });*/ } }; $scope.addPerson = function(){ console.log(this === $scope); console.log($scope); this.list.push({password: this.inputName, age: 25}); }; $scope.inputFocus = function(){ this.errors = []; }; var _signupCallback = function(data){ console.log(data); if(data.error === 'duplicate') { $scope.errors.push('Username exists, please choose another username'); } else { //User.password = <PASSWORD>; //User.apikey = data.apikey; //console.log('apikey is', User.apikey); $location.path('/'); } }; //sign up form validation var _validate = function(){ var password = $('#password').val().trim(), error, valid = false, password2 = $('#password2').val().trim(); if (!password || !password2) { this.errors.push('Required fields not empty.'); } else if (password !== <PASSWORD>2) { this.errors.push('Confirm password not match.'); } /*else if (password.length > 20) { this.errors.push('Username or password should not exceed 20 chars.'); }*/ this.password = <PASSWORD>; return !this.errors.length; }; var _loginCallback = function(data){ if(data.status == 'fail') { $scope.errors.push('Something wrong please try again!'); } else { /*User.islogin = true; User.apikey = data.apikey; console.log('apikey is', data.apikey); User.username = this.username;*/ $location.path('/'); } }; $scope.addPerson = function(){ console.log(this === $scope); console.log($scope); this.list.push({name: this.inputName, age: 25}); } }) .controller('resetController', function($scope, User, $location, $http, VALID_USERNAME){ $scope.errors = []; $scope.username = ''; $scope.resetpass = function(){ this.errors = []; if(_validate.apply(this, null)){ User.resetpass(this.username, _resetCallback); } }; $scope.inputFocus = function(){ this.errors = []; }; var _resetCallback = function(data){ console.log(data); if(data.error === 'failed') { $scope.errors.push('Reset password link already send to your email address.'); } else if(data.error === 'duplicate') { $scope.errors.push('Username is invalid, please try again.'); } else { //User.islogin = true; //User.username = this.username; //User.apikey = data.apikey; //console.log('apikey is', User.apikey); //$location.path('/'); //$scope.errors.push('Please check your email address for reset new password.'); $scope.errors.push(data.status); } }; //sign up form validation var _validate = function(){ var username = $('#username').val().trim(), error, valid = false; /*var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; if(emailPattern.test(document.getElementById('email').value)==false) { this.errors.push('Please enter valid email address.'); }*/ if (!username) { this.errors.push('Please enter valid username.'); } this.username = username; return !this.errors.length; }; }) .controller('signupController', function($scope, User, $location, $http, VALID_USERNAME){ $scope.errors = []; $scope.signup = function(){ $location.path('/detail/1'); }; $scope.goToSignIn = function() { $location.path('/'); }; $scope.username = ''; $scope.password = ''; $scope.signup = function(){ this.errors = []; if(_validate.apply(this, null)){ User.signup(this.username, this.password, _signupCallback); } }; $scope.addPerson = function(){ console.log(this === $scope); console.log($scope); this.list.push({name: this.inputName, age: 25}); }; $scope.inputFocus = function(){ this.errors = []; }; var _signupCallback = function(data){ console.log(data); if(data.error === 'duplicate') { $scope.errors.push('Username exists, please choose another username'); } else { User.islogin = true; User.username = this.username; User.apikey = data.apikey; console.log('apikey is', User.apikey); $location.path('/'); } }; //sign up form validation var _validate = function(){ var username = $('#username').val().trim(), error, valid = false, password = $('#<PASSWORD>').val().trim(), password2 = $('#<PASSWORD>').val().trim(); if (!username || !password || !<PASSWORD>2) { this.errors.push('Required fields not empty.'); } else if (password !== <PASSWORD>) { this.errors.push('Confirm password not match.'); } else if (username.length > 20 || password.length > 20) { this.errors.push('Username or password should not exceed 20 chars.'); } else if (!VALID_USERNAME.test(username)) { this.errors.push('Username should be only consists of letters, numbers or "_"'); } this.username = username; this.password = <PASSWORD>; return !this.errors.length; }; }) .controller('listController', function($scope, List){ console.log('list is'); console.log(List); $scope.myname = 'gee'; $scope.age = '25'; //$scope.inputName = ''; $scope.list = List.list; $scope.getCount = function(){ console.log('in getting count'); return this.list.length; }; $scope.getName = function(){ console.log('in getting name'); return '123'; } $scope.addPerson = function(){ console.log(this === $scope); console.log($scope); this.list.push({name: this.inputName, age: 25}); } }) .controller('testController', function($scope, $routeParams){ $scope.name = 'test controller'; $scope.getCount = function(){ return $scope.name.length; } });
83983cf953b6b8c6da272c2d04e21facc2a90486
[ "JavaScript", "PHP" ]
2
PHP
sujeetgupta5/hoss
7dab0e328a73cbdacaac68508d24de3f9f6d0ad2
3aff93ab9b9c9f921d446b189f0e0c03d02f171d
refs/heads/master
<file_sep>import React, { Component } from 'react' import Tier3 from './Tier3' export default class Tier2 extends Component { render() { return ( <div onClick={this.props.clickOnTier} className="tier2" style={{backgroundColor: this.props.childColor, color: this.props.childColor}}> <Tier3 handleChildClick={this.props.clickOnTier} color={this.props.grandChildColor} /> <Tier3 handleChildClick={this.props.clickOnTier} color={this.props.grandChildColor} /> </div> ) } }
1663b4eaf7a1bee9882e7d196f94d6e7e28b46fb
[ "JavaScript" ]
1
JavaScript
lawrend/react-information-flow-v-000
785c28e45371393995264dba7ea94ab2b721aab9
12f7a318bb6e1cb5142d105e7ab5eda1e47f0a5c
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace question1 { public class Program { static void Main(string[] args) { double res1 = SqrtTriangle(3, 4, 5); double res2 = SqrtRightTriangle(3, 4, 5); } public static double SqrtRightTriangle(float side1, float side2, float hypotenuse) { if (side1.IsNegativeNumber() || side2.IsNegativeNumber() || hypotenuse.IsNegativeNumber()) // IsNegativeNumber - Extension method { throw new Exception("Invalid Parameters"); } if (Math.Pow(side1, 2) + Math.Pow(side2, 2) != Math.Pow(hypotenuse, 2)) { throw new Exception("Is not Right Triangle"); } return (side1 * side2) / 2; } public static double SqrtTriangle(float a, float b, float c) { if (a.IsNegativeNumber() || b.IsNegativeNumber() || c.IsNegativeNumber()) //Extension method { throw new Exception("Invalid Parameters"); } float p = (a + b + c) / 2; return Math.Sqrt(p * (p - a) * (p - b) * (p - c)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace question1 { public static class floatExtensions { public static bool IsNegativeNumber(this float f) { return f <= 0.0f; } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace question1 { [TestClass] public class UnitTest1 { [TestMethod] public void Test_SqrtRightTriangle_Exceptions() { try { Program.SqrtRightTriangle(3, 4, 5); } catch (Exception ex) { Assert.Fail(ex.Message); } } [TestMethod] public void Test_SqrtRightTriangle_Result() { float hypotenuse = 5; float s1 = 3; float s2 = 4; double res = (s1 * s2) / 2; Assert.AreEqual(Program.SqrtRightTriangle(s1, s2, hypotenuse), res); } [TestMethod] public void Test_SqrtTriangle_Result() { float hypotenuse = 5; float s1 = 3; float s2 = 4; double res = (s1 * s2) / 2; Assert.AreEqual(Program.SqrtTriangle(s1, s2, hypotenuse), res); } [TestMethod] public void Test_SqrtTriangle_Exceptions() { try { Program.SqrtTriangle(3, 4, 5); } catch (Exception ex) { Assert.Fail(ex.Message); } } } }
3f2eac784286b40aeaab8b5b4c23d8535ec068be
[ "C#" ]
3
C#
WinoGarcia/MindboxTest
98ecd5e98339830f0a87caa938b232c2b84befb9
f66c9044f4ed617b17f017892eadbc5f0d6e814c
refs/heads/main
<file_sep>from enum import Flag import re class hangman: def __init__(self): self.list1 = ["Vehical", "Body Part", "Laptop", "Flower", "Pakistan"] self.list2 = ["truck", "brain", "lenovo", "orchid", "islamabad"] self.allowError = None self.guesses = [] self.guess = None self.size = 5 self.flag1 = None self.flag = None def displayFunc(self, word): for letter in word: if(letter.lower() in self.guesses): print(letter , end = " ") else: print("_", end = " ") def inputChar(self): done = False while not done: self.guess = input(f"{self.allowError} allow errors are left, Enter charactor: ") if not len(self.guess) == 1: print("Only one charactor allowed! Try Again") done = False elif not re.match("^[a-z]*$", self.guess): print("Error! Only letters a-z allowed! Try Again") done = False else: done = True self.guesses.append(self.guess.lower()) def errorCalculation(self, word): if (self.guess.lower() not in word.lower()): self.allowError -= 1 if(self.allowError == 0): loop = False return loop def result(self, word): if self.flag : print(f"You Win. The word is {word}") print("") else: print(f"You Lose. The word is {word}") print("") def playAgain(self): key = input("Do you want to play agian? if yes the press 'y': ") if(key == 'y'): self.flag1 = True return self.flag1 else: self.flag1 = False return self.flag1 def hangmanFunc(self): self.flag1 = True i = 0 while (i < self.size and self.flag1 == True): print(self.list1[i]) word = self.list2[i] self.flag = False self.allowError = 7 while not self.flag: self.displayFunc(word) print("") self.inputChar() if(self.errorCalculation(word) == False): break self.flag = True for letter in word: if letter.lower() not in self.guesses: self.flag = False self.result(word) self.guesses = [] self.playAgain() i += 1 if __name__ == "__main__": obj = hangman() obj.hangmanFunc()
5a66c551be921ada782df7171a2c00d39ef1fe66
[ "Python" ]
1
Python
ToheedAhmadNaveed/HangManProject
2b4c8fe427d1ab12fd2bde2bbf161a9deda3dfd4
46ef5e5747c2b840df123641ef1bfe49cc357e92
refs/heads/main
<file_sep>import React, { useState } from "react"; import NewTask from "./components/NewTask.js"; import TasksList from "./components/TasksList.js"; function App() { const data = JSON.parse(localStorage.getItem("tasks")); const [tasks, setTasks] = useState(data || []); const addTaskHandler = function (task) { setTasks((prevTasks) => { return [task, ...prevTasks]; }); }; localStorage.setItem("tasks", JSON.stringify(tasks)); const deleteItemHandler = function (taskId) { setTasks((prevTasks) => { const updatedTasks = prevTasks.filter((task) => task.id !== taskId); return updatedTasks; }); }; return ( <div> <h1>To Do List</h1> <NewTask onAddTask={addTaskHandler} /> {tasks && <TasksList items={tasks} onDeleteItem={deleteItemHandler} />} </div> ); } export default App; <file_sep>import React, { useState } from "react"; import Form from "./Form.js"; function NewTask(props) { const [isEditing, setIsEditing] = useState(false); const clickHandler = function () { setIsEditing(true); }; const stopEditingHandler = function () { setIsEditing(false); }; const saveTaskDataHandler = function (enteredTaskData) { const taskData = { ...enteredTaskData, id: Math.random().toString(), }; props.onAddTask(taskData); }; return ( <div className="container"> {!isEditing && ( <div className="center"> <button onClick={clickHandler} className="btn"> Add New Task </button> </div> )} {isEditing && ( <Form onSaveTaskData={saveTaskDataHandler} onCancel={stopEditingHandler} onCreate={stopEditingHandler} /> )} </div> ); } export default NewTask; <file_sep>import React, { useState } from "react"; function Form(props) { const [enteredTask, setEnteredTask] = useState(""); const [enteredImportance, setEnteredImportance] = useState(""); const [enteredUrgency, setEnteredUrgency] = useState(""); const taskChangeHandler = function (event) { setEnteredTask(event.target.value); }; const importanceChangeHandler = function (event) { setEnteredImportance(event.target.value); }; const urgencyChangeHandler = function (event) { setEnteredUrgency(event.target.value); }; const submitHandler = function (e) { e.preventDefault(); const taskData = { task: enteredTask, value: +enteredImportance + +enteredUrgency, }; setEnteredImportance(""); setEnteredTask(""); setEnteredUrgency(""); props.onSaveTaskData(taskData); props.onCreate(); }; return ( <form onSubmit={submitHandler} className="form"> <div> <label className="label">Task</label> <textarea className="input1" name="" id="" cols="30" rows="3" onChange={taskChangeHandler} value={enteredTask} required ></textarea> </div> <div> <label className="label"> How important is it in a scale of 0 to 10? </label> <input onChange={importanceChangeHandler} className="input2" type="number" min="0" max="10" value={enteredImportance} /> </div> <div> <label className="label">How urgent is it in a scale of 0 to 10?</label> <input onChange={urgencyChangeHandler} className="input3" type="number" min="0" max="10" value={enteredUrgency} /> </div> <div className="margin"> <button type="submit" className="btn"> Create task </button> <button className="btn-cancel" onClick={props.onCancel}> Cancel </button> </div> </form> ); } export default Form; <file_sep>import React from 'react'; import TaskItem from './TaskItem'; function Tasks(props) { // Order tasks by value props.items.sort((a, b) => parseFloat(b.value) - parseFloat(a.value)); const deleteHandler = function (id) { props.onDeleteItem(id); }; return ( <ol> {props.items.map((task) => ( <TaskItem key={task.id} title={task.task} value={task.value} onDelete={deleteHandler} id={task.id} /> ))} </ol> ); } export default Tasks;
ac4a5cfda9393f34169dcd88d075cfe71fc5417e
[ "JavaScript" ]
4
JavaScript
AlbertoRoldanUX-code/to-do-list-v2
8ee985832c9415e2d8060f77bc011b0fe32c71a7
e20bdb7d7804dd2501b3b3d74b85ddde6d8eb4d8
refs/heads/master
<repo_name>JCHappytime/python-csv-mongoDB<file_sep>/store_csv.py __author__ = 'Administrator' #encoding:utf-8 from pymongo import MongoClient import csv client = MongoClient('localhost',27017) db = client.local def saveToMongo(filename,collection,flag): csvfile = file(filename,'rb') reader = csv.reader(csvfile) if flag == 0: for line in reader: print is_chinese(line[0].decode("GBK")) if flag == 1: for line in reader: collection.insert({'Date':line[0],'Time':line[1],'DIF':line[2],'DEA':line[3],'MACD':line[4]}) csvfile.close() def is_chinese(uchar): if uchar >= u'\u4e00' and uchar<=u'\u9fa5': return True else: return False if __name__=="__main__": saveToMongo("KLinefile.csv",db.KLinefile,0) # saveToMongo("Calcfile.csv",db.Calcfile,1)
fc0758853788de3443ab4805b960bc7d7fa67b18
[ "Python" ]
1
Python
JCHappytime/python-csv-mongoDB
87d9e06e1c2764587819687babd7dc52ab1995c2
fb235e708a45ca65415c05ab89f95a1c7d19a015
refs/heads/master
<repo_name>aryalgaurav/CriminalIntent12<file_sep>/app/src/main/java/android/nku/edu/criminalintent/TimePickerFragment.java package android.nku.edu.criminalintent; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.TimePicker; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Created by Gaurav on 8/26/2016. */ public class TimePickerFragment extends DialogFragment { public static final String EXTRA_DATE = "android.nku.edu.criminalintent.date"; private static final String ARG_DATE = "date"; private TimePicker mTimePicker; protected Calendar mCalendar; @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Date date = (Date) getArguments().getSerializable(ARG_DATE); mCalendar = Calendar.getInstance(); mCalendar.setTime(date); View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_time, null); mTimePicker = (TimePicker) view.findViewById(R.id.dialog_time_time_picker); mTimePicker.setIs24HourView(false); mTimePicker.setCurrentHour(mCalendar.get(Calendar.HOUR_OF_DAY)); mTimePicker.setCurrentMinute(mCalendar.get(Calendar.MINUTE)); return new AlertDialog.Builder(getActivity()).setView(view) .setTitle(R.string.time_picker_title) .setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int year = mCalendar.get(Calendar.YEAR); int month = mCalendar.get(Calendar.MONTH); int day = mCalendar.get(Calendar.DAY_OF_MONTH); int hour = mTimePicker.getCurrentHour(); int minute = mTimePicker.getCurrentMinute(); Date date = new GregorianCalendar(year, month, day, hour, minute).getTime(); sendResultTime(Activity.RESULT_OK, date); } }).create(); } public static TimePickerFragment newInstance(Date date) { Bundle args = new Bundle(); args.putSerializable(ARG_DATE, date); TimePickerFragment fragment = new TimePickerFragment(); fragment.setArguments(args); return fragment; } /** * Creates an intent, puts the date on it as an extra, and then calls * CrimeFragment.onActivityResult(...) * */ private void sendResultTime(int resultCode, Date date) { if (getTargetFragment() == null) { return; } else { Intent intent = new Intent(); intent.putExtra(EXTRA_DATE, date); getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent); } } }
cd8eb352af6188e9588193b81294236d8b887789
[ "Java" ]
1
Java
aryalgaurav/CriminalIntent12
d85d32c5017582f585e40969d6e485559decfe00
880a7c47a10ca33bd4f0886c8889b5a5343db261
refs/heads/main
<file_sep># A multiple clients dictionary <file_sep> import java.awt.EventQueue; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.net.ServerSocket; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.JScrollPane; public class ServerGUI { private JTextArea textArea; private JFrame frame; public ServerGUI(ServerSocket server) { initialize(server); } public void initialize(ServerSocket server) { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(18, 6, 414, 255); frame.getContentPane().add(scrollPane); setTextArea(new JTextArea()); scrollPane.setViewportView(getTextArea()); getTextArea().setLineWrap(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { try { server.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.exit(0); } }); frame.setVisible(true); } public JTextArea getTextArea() { return textArea; } public void setTextArea(JTextArea textArea) { this.textArea = textArea; } } <file_sep> import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class HandleAClient implements Runnable { private Socket socket; private DataInputStream dis; private DataOutputStream dos; private MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); private String path; private ServerGUI ui; public HandleAClient(Socket socket, String path, ServerGUI ui) { this.socket = socket; this.path = path; this.ui = ui; } @Override public void run() { // TODO Auto-generated method stub try { DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); while (true) { String input = dis.readUTF(); control(input, dos, path); } } catch (EOFException e3) { try { socket.close(); Server.clientNum -= 1; ui.getTextArea().append("There are " + Server.clientNum + " client(s)." + "\n"); ui.getTextArea().append(socket.getInetAddress() + " has leaved" + "\n" + "\n"); System.out.println("There are " + Server.clientNum + " client(s)."); System.out.println(socket.getInetAddress() + " has leaved" + "\n"); } catch (IOException e) { e.printStackTrace(); } } catch (IOException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (dis != null) dis.close(); if (dos != null) dos.close(); if (socket != null) { socket.close(); socket = null; } } catch (IOException io) { io.printStackTrace(); } } } public void control(String input, DataOutputStream dos, String path) { Set<String> keySet = map.keySet(); StringTokenizer st = new StringTokenizer(input, ","); String command = st.nextToken(); if (command.equals("addMean")) { read(path); if (!st.hasMoreElements()) { try { dos.writeUTF("Please input a word or an explaination"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { String word = st.nextToken(); if (!st.hasMoreElements()) { try { dos.writeUTF("Please input a word or an explaination"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { String mean = st.nextToken(); ui.getTextArea().append(command + ": " + word + "\n"); ui.getTextArea().append("mean: " + mean + "\n" + "\n"); System.out.println(command + ": " + word); System.out.println("mean: " + mean); addMean(word, mean, dos); write(map, keySet, path); } } } else if (command.equals("find")) { read(path); if (!st.hasMoreElements()) { try { dos.writeUTF("Please input a word"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { String word = st.nextToken(); ui.getTextArea().append(command + ": " + word + "\n"); System.out.println(command + ": " + word); find(word, dos); } } else if (command.equals("delete")) { read(path); if (!st.hasMoreElements()) { try { dos.writeUTF("Please input a word"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { String word = st.nextToken(); ui.getTextArea().append(command + " " + word + "\n" + "\n"); System.out.println(command + " " + word); delete(word, dos); write(map, keySet, path); } } else if (command.equals("addWord")) { read(path); if (!st.hasMoreElements()) { try { dos.writeUTF("Please input a word or an explaination"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { String word = st.nextToken(); if (!st.hasMoreElements()) { try { dos.writeUTF("Please input a word or an explaination"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { String mean = st.nextToken(); ui.getTextArea().append(command + " " + word + "\n"); ui.getTextArea().append("mean: " + mean + "\n" + "\n"); System.out.println(command + ": " + word); System.out.println("mean: " + mean); addWord(word, mean, dos); write(map, keySet, path); } } } } public void addWord(String word, String mean, DataOutputStream dos) { if (map.containsKey(word)) { try { dos.writeUTF("The word already exist"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { map.add(word, mean); List<String> values = map.getValues(word); String meaning = String.join(",", values); try { dos.writeUTF("Add word Successful"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void addMean(String word, String mean, DataOutputStream dos) { if (!map.containsKey(word)) { try { dos.writeUTF("The word does not exist"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { map.add(word, mean); List<String> values = map.getValues(word); String meaning = String.join(",", values); try { dos.writeUTF("Add mean Successful"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void find(String word, DataOutputStream dos) { if (map.isEmpty()) { try { dos.writeUTF("The dictionary is empty"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { if (map.containsKey(word)) { List<String> values = map.getValues(word); String meaning = String.join(",", values); ui.getTextArea().append("mean: " + meaning + "\n" + "\n"); System.out.println(meaning); try { dos.writeUTF(meaning); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { dos.writeUTF("This word is not in the dictionary"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void delete(String word, DataOutputStream dos) { if (map.isEmpty()) { try { dos.writeUTF("The dictionary is empty"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { if (map.containsKey(word)) { map.remove(word); Set<String> keySet = map.keySet(); for (String key : keySet) { List<String> values = map.getValues(key); for (String value : values) { System.out.println(key + ": " + value); } } try { dos.writeUTF("Delete \"" + word + "\" Successful"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { dos.writeUTF("This word is not in the dictionary"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public synchronized void read(String path) { try { File file = new File(path); if (!file.exists()) { file.createNewFile(); } else { map.clear(); BufferedReader br = new BufferedReader(new FileReader(path)); String temp = br.readLine(); if (temp != null) { int index = Integer.parseInt(temp); for (int read = 0; read < index; read++) { String temp2 = br.readLine(); StringTokenizer st = new StringTokenizer(temp2, ":"); String words = st.nextToken(); String means = st.nextToken(); map.add(words, means); } } br.close(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { } } public synchronized void write(MultiValueMap<String, String> map, Set<String> keySet, String path) { PrintWriter pw = null; try { pw = new PrintWriter(new FileOutputStream(path), true); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int number = 0; for (String key : keySet) { List<String> value3 = map.getValues(key); for (int i = 0; i < value3.size(); i++) { number += 1; } } pw.println(number); System.out.println(number); for (String key : keySet) { List<String> value3 = map.getValues(key); for (String value : value3) { pw.println(key + ":" + value); } } pw.close(); } }
fe6ca3f2a4fdf2d26715ff074d329967b2637d91
[ "Markdown", "Java" ]
3
Markdown
forrest-lin-cellist/Dictionary-application
471b7a7ffbd06d95bc4f5abf2526770c63fc3d82
fdf59819d88ed9a1b8d437f0db26b6aac9f0d4bb
refs/heads/master
<file_sep>using System.Linq.Expressions; namespace MockAsyncAction { public class TestExpressionVisitor : ExpressionVisitor { } }
d84fbf6b0d7f245da2f07401b48f7c346e7b96aa
[ "C#" ]
1
C#
KeenOnCoding/MockAsyncAction
82143d3ad69f1d04bf27ffa8e8b5839299c3697b
4c1b85ef5fc64b87f2a084a322a5013610671acf
refs/heads/master
<file_sep>import {Routes, RouterModule} from '@angular/router'; import {HomePageComponent} from "./homePageComponent/home-page.component"; import {AdminLoginComponent} from "./adminLoginComponent/admin-login.component"; import {SignUpComponent} from "./signUpComponent/sign-up.component"; import {BlogerSignInComponent} from "./bloger-sign-in/bloger-sign-in.component"; import {ProfileComponent} from "./profile/profile.component"; import {CanActivateViaAuthGuard} from "./shared/guards/can-activate-via-auth.guard"; import {NewBlogPostComponent} from "./new-blog-post/new-blog-post.component"; const appRoutes: Routes = [ { path: '', component: HomePageComponent }, { path: 'admin', component: AdminLoginComponent }, { path: 'sign-up', component: SignUpComponent }, { path: 'bloger-sign-in', component: BlogerSignInComponent }, { path: 'profile', component: ProfileComponent, canActivate: [ CanActivateViaAuthGuard ] }, { path: 'new-blog-post', component: NewBlogPostComponent, // canActivate: [ // CanActivateViaAuthGuard // ] }, { path: '**', redirectTo: '/', pathMatch: 'full' } ]; export const routing = RouterModule.forRoot(appRoutes); <file_sep>/** * AuthController * * @description :: Server-side logic for managing auths * @help :: See http://links.sailsjs.org/docs/controllers */ module.exports = { index: function (req, res) { var login = req.param('login'); var password = req.param('password'); if(!login || !password){ res.json(401, {err: "Login and password required"}); } User.findOne({login: login}, function (err, user) { if(!user){ res.json(401, {err: "Invalid login or password"}); } console.log(user); if(password === <PASSWORD>){ res.json({ user: user, token: jwToken.issue({id : user.id }) }); } else{ return res.json(401, {err: 'invalid login or password'}); } }) } } <file_sep>/** * BlogPostController * * @description :: Server-side logic for managing blogposts * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { create: function (req, res, next) { BlogPost.create(req.params.all(), function BlogPostCreated(err, blogPost) { if(err) return next(err); if(blogPost){ res.json(200, {post: blogPost}); } }); } }; <file_sep># strapcms A quick description of strapcms. <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import {routing} from "./app.routing"; import {HomePageComponent} from "./homePageComponent/home-page.component"; import {AdminLoginComponent} from "./adminLoginComponent/admin-login.component"; import {SignUpComponent} from "./signUpComponent/sign-up.component"; import { BlogerSignInComponent } from './bloger-sign-in/bloger-sign-in.component'; import {BlogerService} from "./shared/bloger.service"; import { ProfileComponent } from './profile/profile.component'; import { ArticlesListComponent } from './articles-list/articles-list.component'; import {PostService} from "./shared/post.service"; import {CanActivateViaAuthGuard} from "./shared/guards/can-activate-via-auth.guard"; import { NewBlogPostComponent } from './new-blog-post/new-blog-post.component'; /* import {CKEditorModule} from "ng2-ckeditor"; */ @NgModule({ declarations: [ AppComponent, HomePageComponent, AdminLoginComponent, SignUpComponent, BlogerSignInComponent, ProfileComponent, ArticlesListComponent, NewBlogPostComponent ], imports: [ BrowserModule, FormsModule, HttpModule, routing, /* CKEditorModule */ ], providers: [Window, BlogerService, PostService, CanActivateViaAuthGuard], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>export const serverApi = "http://localhost:1337/"; <file_sep>export interface BlogPost { _id: number; name: string; content: string; points: number; // imageUrl: string; // publishDate: Date; } <file_sep>module.exports={ tableName:"users", atributes:{ first_name:{type:"string",required:true}, last_name:{ type:"string",required:true}, posts:{collection:'post', via:'user'} } };<file_sep>import {Component} from '@angular/core'; @Component({ selector: 'admin-login', templateUrl: './admin-login.component.html', styleUrls: ['./admin-login.component.scss'] }) export class AdminLoginComponent{ } <file_sep>import {Injectable} from '@angular/core'; import {Http, Headers, RequestOptions, Response} from "@angular/http"; import {Observable} from "rxjs/Observable"; import {BlogPost} from "./structures/blog-post"; @Injectable() export class PostService{ constructor(private http: Http){ } private extractData(res: Response) { let body = res.json(); return body.data || { }; } private handleError (error: any) { let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; console.error(errMsg); return Observable.throw(errMsg); } addPost(article: BlogPost): Observable<BlogPost>{ let articleJson = JSON.stringify(article); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post('/article/addOne', articleJson, options) .map(this.extractData) .catch(this.handleError); } getPartOfPosts(num: number, lastIndex: number): Observable<BlogPost[]>{ console.log(num + ', ' + lastIndex); return this.http.get('/article/getPart?num=' + num + '&lastIndex=' + lastIndex) .map(function (res: Response) { let body = res.json(); return body || { }; }) .catch(this.handleError); } getLastArticleId(): Observable<BlogPost>{ return this.http.get('/article/getLastArticleId') .map(function (res: Response) { let body = res.json(); return body || { }; }) .catch(this.handleError); } getArticle(id: number) { return this.http.get('/article/getArticle?article='+ id) .toPromise() .then(function (res: Response) { let body = res.json(); return body || { }; }) .catch(this.handleError); } } <file_sep>import { Component, OnInit } from '@angular/core'; import {Http} from "@angular/http"; import {PostService} from "../shared/post.service"; import {Router} from "@angular/router"; import {BlogPost} from "../shared/structures/blog-post"; @Component({ selector: 'app-articles-list', templateUrl: './articles-list.component.html', styleUrls: ['./articles-list.component.scss'] }) export class ArticlesListComponent implements OnInit { ngOnInit(): void { this.articles = []; this.postService.getLastArticleId().subscribe( lastArticleId => { console.log(lastArticleId); this.lastIndex = lastArticleId._id; console.log(this.lastIndex); this.getFourAricles(); }); } constructor(private http: Http, private postService: PostService, private router: Router){ } articles: BlogPost[]; lastIndex: number; getFourAricles(){ this.postService.getPartOfPosts(4, this.lastIndex).subscribe( articles => { console.log(articles); this.articles = this.articles.concat(articles); console.log(articles.length); this.lastIndex -= articles.length; console.log(this.lastIndex); function compareDesc(a,b) { if (a._id > b._id) return -1; if (a._id < b._id) return 1; return 0; } this.articles.sort(compareDesc); console.log(this.articles); } ); } loadMore(){ this.getFourAricles(); } onSelect(article: BlogPost){ // this.router.navigate(['/blog/article',article._id]); } } <file_sep>export interface Bloger { id: string; login: string; photoUrl: string; points: number; } <file_sep>/** Generated by sails-inverse-model Date:Sun Aug 27 2017 04:56:47 GMT+0300 (Türkiye Standart Saati) */ module.exports = { attributes: { name: { type: 'string', required: true, unique: true }, owner: { type: 'string', } } };<file_sep>module.exports = { /** * It will create a new user . */ create: function (req, res) { let firstName = req.param('first_name'), lastName = req.param('last_name'), age = req.param('age'); if(!firstName){ return res.badRequest({err:'Invalid first_name'}); } if(!lastName){ return res.badRequest({err:'Invlaid last_name'}); } User.create({ first_name : firstName, last_name : lastName, age:age }) .then(_user => { if(!_user) return res.serverError({err:'Unable to create user'}); return res.ok(_user); //to learn more about responses check api/responses folder }) .catch(err => res.serverError(err.message)); } };<file_sep>import { Component, OnInit } from '@angular/core'; import {Bloger} from "../shared/bloger"; import {BlogerService} from "../shared/bloger.service"; import {Router} from "@angular/router"; @Component({ selector: 'sign-up', templateUrl: './sign-up.component.html', styleUrls: ['./sign-up.component.scss'] }) export class SignUpComponent implements OnInit { constructor(private blogerService: BlogerService, private router: Router) { } ngOnInit() { } bloger = { login: "", photoUrl: "", password: "" } registerBloger(){ this.blogerService.registerBloger(this.bloger).subscribe(data => { this.blogerService.saveBloger(data); this.router.navigate(['profile']); }); } } <file_sep>module.exports = { tableName:"posts", attributes: { title : { type: 'string', required:true }, content : { type: 'longtext' ,required:true }, //Associations category : { model :'category', columnName:'category_id', required:true}, user : { model :'user', columnName:'user_id', required:true}, } };<file_sep>import {Injectable} from "@angular/core"; import {Bloger} from "./bloger"; import {Http, RequestOptions, Headers} from "@angular/http"; import {serverApi} from "../constants"; import {Observable} from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import {Router} from "@angular/router"; @Injectable() export class BlogerService { authToken: string; bloger: Bloger = { id: "", login: "", photoUrl: "", points: 0 }; constructor(private http: Http, private router: Router){ } registerBloger(bloger){ console.log(bloger); let body = JSON.stringify({login: bloger.login, password: <PASSWORD>, photoUrl: bloger.photoUrl}); let headers = new Headers({ 'Content-Type': 'application/json'}); let options = new RequestOptions({ headers: headers }); return this.http.post(serverApi + "user/create", body, options).map(res => { return res.json(); }); } signIn(login, password){ let body = JSON.stringify({login: login, password: <PASSWORD>}); let headers = new Headers({ 'Content-Type': 'application/json'}); let options = new RequestOptions({ headers: headers }); console.log(1234567890); return this.http.post(serverApi + "auth", body, options).map(res => { return res.json(); }); } saveBloger(data){ console.log(data); this.bloger.id = data['user']['id']; this.bloger.login = data['user']['login']; this.bloger.photoUrl = data['user']['photoUrl']; this.bloger.points = data['user']['points']; this.authToken = data['token']; localStorage.setItem('Authorization', this.authToken); localStorage.setItem('blogerId', this.bloger.id); } retrieveBloger(){ let token = localStorage.getItem('Authorization'); let blogerId = localStorage.getItem('blogerId'); if(token && blogerId){ this.authToken = token; let headers = new Headers({ 'Authorization': 'Bearer ' + token}); let options = new RequestOptions({ headers: headers }); this.http.get(serverApi + 'user/' + blogerId, options).map(res => { return res.json(); }).subscribe(data => { this.bloger.id = data.id; this.bloger.login = data.login; this.bloger.photoUrl = data.photoUrl; this.bloger.points = data.points; }); } } logOut(){ this.authToken = null; this.bloger = { id: "", login: "", photoUrl: "", points: 0 }; localStorage.removeItem("Authorization"); localStorage.removeItem("blogerId"); this.router.navigate(['home']); } isLoggedIn(){ if(this.authToken && this.bloger.id != ""){ return true; }else{ return false; } } } <file_sep>import { Component, OnInit } from '@angular/core'; import {BlogerService} from "../shared/bloger.service"; import {Router} from "@angular/router"; @Component({ selector: 'app-bloger-sign-in', templateUrl: './bloger-sign-in.component.html', styleUrls: ['./bloger-sign-in.component.scss'] }) export class BlogerSignInComponent implements OnInit { constructor(private blogerService: BlogerService, private router: Router) { } ngOnInit() { } login: string; password: string; signIn(){ this.blogerService.signIn(this.login, this.password).subscribe(data => { if(data){ this.blogerService.saveBloger(data); this.router.navigate(['profile']); }else{ console.log("wrong"); } }); } } <file_sep># news-page-server Sport news server using [Sails](http://sailsjs.org) <file_sep># NodeFrameworks Node en uygun Frameworks denemeleri kaşılaştırma <file_sep>import { Injectable } from '@angular/core'; import {CanActivate, Router} from '@angular/router'; import {BlogerService} from "../bloger.service"; @Injectable() export class CanActivateViaAuthGuard implements CanActivate { constructor(private blogerService: BlogerService, private router: Router) {} canActivate() { let bool = this.blogerService.isLoggedIn(); if(!bool){ this.router.navigate(['bloger-sign-in']); } return bool; } } <file_sep># blog-api +kullanımı kolay +mvc mimarisi<file_sep>import { Component, OnInit } from '@angular/core'; import {Router} from "@angular/router"; import {PostService} from "../shared/post.service"; import {BlogPost} from "../shared/structures/blog-post"; @Component({ selector: 'app-new-blog-post', templateUrl: './new-blog-post.component.html', styleUrls: ['./new-blog-post.component.scss'] }) export class NewBlogPostComponent implements OnInit { ngOnInit(): void { } // tslint:disable-next-line:member-ordering article: BlogPost = { _id: 0, name: '', content: "", points: 0 }; // tslint:disable-next-line:no-inferrable-types lastArticleId: number = 0; constructor(private postService: PostService, private router: Router){ } onSubmit(){ this.article._id = this.lastArticleId + 1; console.log(JSON.stringify(this.article)); this.postService.addPost(this.article).subscribe( article => { console.log(article); this.router.navigate(['/home']); }, error => console.log(error) ); } } <file_sep>import { Component, OnInit } from '@angular/core'; import {BlogerService} from "../shared/bloger.service"; import {Bloger} from "../shared/bloger"; import {Router} from "@angular/router"; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.scss'] }) export class ProfileComponent implements OnInit { bloger: Bloger; constructor(private blogerService: BlogerService, private router: Router) { this.bloger = blogerService.bloger; } ngOnInit() { } onSelect(article){ } newPost(){ this.router.navigate(['new-blog-post']); } } <file_sep>/** * PostController * * @description :: Server-side logic for managing Posts * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { /** * This method will create a new post for user */ create: function (req, res) { let title = req.param('title'), content = req.param('content'), userId = req.param('user_id'), categoryName = req.param('category_name'); if (!title) return res.badRequest({ err: 'Invalid post title field' }); if (!content) return res.badRequest({ err: 'Invalid post content field' }); if (!userId) return res.badRequest({ err: 'Invalid user_id field' }); if (!categoryName) return res.badRequest({ err: 'Invalid category_name field' }); Category.findOrCreate({ name: categoryName }) .then(_category => { if (!_category) throw new Error('Unable to create category record'); return _category; }) .then(_category => { return Post.create({ title, content, user: userId, category: _category.id }); }) .then(_post => { if (!_post) throw new Error('Unable to create new post'); return res.ok(_post); }) .catch(err => res.serverError(err.message)); }, /** * This method will update the post */ update: function (req, res) { let title = req.param('title'), content = req.param('content'), userId = req.param('user_id'), categoryId = req.param('category_id'), postId = req.params.id; if (!postId) return res.badRequest({ err: 'post id is missing' }); let post = {}; if (title) { post.title = title; } if (content) { post.content = content; } if (userId) { post.user = userId; } if (categoryId) { post.category = categoryId } Post.update({ id: postId }, post) .then(_post => { if (!_post[0] || _post[0].length === 0) return res.notFound({ err: 'No post found' }); return res.ok(_post[0]); }).catch(err => res.serverError(err)); }, /** * This method will delete the post */ delete: function (req, res) { let postId = req.params.id; if (!postId) return res.badRequest({ err: 'missing post_id field' }); Post.destroy({ id: postId }) .then(_post => { if (!_post || _post.length === 0) return res.notFound({ err: 'No post found in our record' }); return res.ok({msg:`Post is deleted with id ${postId}`}); }) .catch(err => res.serverError(err)); }, /** * Find all the posts with category and user */ findAll: function (req, res) { Post.find() .populate('user') .populate('category') .then(_posts => { if (!_posts || _posts.length === 0) { throw new Error('No post found'); } return res.ok(_posts); }) .catch(err => res.serverError(err)); }, /** * find single post based on id */ findOne: function (req, res) { let postId = req.params.id; if (!postId) return res.badRequest({ err: 'missing post_id field' }); Post.findOne({ id: postId }) .populate('category') .populate('user') .then(_post => { if (!_post) return res.notFound({ err: 'No post found' }); return res.ok(_post); }) .catch(err => res.serverError(err)); } }; <file_sep>module.exports = { tableName:"categories", attributes: { name : { type: 'string', unique: true, required: true }, posts: { collection:'post', via:'category' } } };<file_sep>/** * User.js * * @description :: User model * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { attributes: { schema: true, login: { type: 'string', required: true, unique: true }, photoUrl: { type: 'string', required: true }, encryptedPassword: { type: 'string' }, points: { type: 'integer', defaultsTo: function () { return 0; } }, toJSON: function () { var obj = this.toObject(); delete obj.password; delete obj.confirmation; delete obj.encriptedPassword; delete obj._csrf; return obj; } } }; <file_sep>/** * jwToken * * @description :: JSON Webtoken Service for sails * @help :: See https://github.com/auth0/node-jsonwebtoken & http://sailsjs.org/#!/documentation/concepts/Services */ var jwt = require('jsonwebtoken'); var tokenSecret = "thebestsecret"; module.exports.issue = function(payload) { return jwt.sign( payload, tokenSecret, { // expiresInMinutes: 180 } ); }; module.exports.verify = function (token, callback) { return jwt.verify( token, tokenSecret, {}, callback ); }
fd3a1641985e0e200e0e5e55d5f5ed32d34a01d6
[ "JavaScript", "TypeScript", "Markdown" ]
28
TypeScript
zinderud/NodeFrameworks
e7bd7330aa9233c57022a8fe1f48eec78c78fbc6
f22bef59f76c0ec79535640a7a12474c9e0fe566
refs/heads/main
<repo_name>MindScape00/ChatHistory<file_sep>/README.md # ChatHistory Chat History (Persistent Chat) This addon keeps a local history of your chat and then restores it every time you login, so you don't miss out on the last thing said, and don't have to fumble thru another addon menu to find it. It will store the last 500 messages received. The report is printed upon login, so you can scroll up and see what you missed, or what was said. ## Installation Drag the "ChatHistory" folder to your Epsilon/\_retail_/Interface/Addons/ folder. Launch the game, and login. In bottom left of Character Select, click "Addons" and then ensure Chat History is enabled. There is no config or commands, it runs automatically. ## Credits This addon is originally created by Vladinator from WoW Interface and all credits go to them for the original addon; this is merely a fork to update it to 8.3 and gear it towards Epsilon players. Original Addon: https://www.wowinterface.com/downloads/info20287-ChatHistory.html <file_sep>/ChatHistory/ChatHistory.lua -- maximum messages to log local LOG_MAX = 500 -- the chat frame to print messages at login local CHAT_FRAME = ChatFrame1 -- -- EDIT THESE ARE YOUR OWN RISK -- local EVENTS = { -- "CHAT_MSG_BATTLEGROUND", -- "CHAT_MSG_BATTLEGROUND_LEADER", -- "CHAT_MSG_BN_WHISPER", -- battle.net whispers will show wrong names between sessions -- "CHAT_MSG_BN_WHISPER_INFORM", -- battle.net whispers will show wrong names between sessions "CHAT_MSG_CHANNEL", -- all channel related talk (general, trade, defense, custom channels, e.g.) "CHAT_MSG_EMOTE", -- only "/me text" messages, not /dance, /lol and such "CHAT_MSG_GUILD", --"CHAT_MSG_GUILD_ACHIEVEMENT", "CHAT_MSG_OFFICER", "CHAT_MSG_PARTY", "CHAT_MSG_PARTY_LEADER", "CHAT_MSG_RAID", "CHAT_MSG_RAID_LEADER", "CHAT_MSG_RAID_WARNING", "CHAT_MSG_SAY", "CHAT_MSG_WHISPER", "CHAT_MSG_WHISPER_INFORM", "CHAT_MSG_YELL", "CHAT_MSG_SYSTEM", } -- -- DO NOT EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING -- local _G = _G local date = date local table = table local time = time local type = type local unpack = unpack local ADDON_NAME = ... local PLAYER_FLAG = "CHAT_HISTORY_PLAYER_ENTRY" local PLAYER_TEXT = "|TInterface\\GossipFrame\\WorkOrderGossipIcon.blp:0:0:1:-2:0:0:0:0:0:0:0:0:0|t " local ENTRY_FLAG = 6 local ENTRY_GUID = 12 local ENTRY_EVENT = 30 local ENTRY_TIME = 31 ChatHistoryDB2 = {} local addon = CreateFrame("Frame") local Print, Save, Init, OnEvent function Print() local temp addon.IsPrinting = true for i = #ChatHistoryDB2, 1, -1 do temp = ChatHistoryDB2[i] ChatFrame_MessageEventHandler(CHAT_FRAME, temp[ENTRY_EVENT], unpack(temp)) end addon.IsPrinting = false addon.HasPrinted = true if temp then CHAT_FRAME:AddMessage("---- Last message received " .. date("%x at %X", temp[ENTRY_TIME]) .. " ----") end end function Save(event, ...) local temp = {...} if temp[1] then temp[ENTRY_EVENT] = event temp[ENTRY_TIME] = time() if event == "CHAT_MSG_SYSTEM" then temp[1] = tostring(PLAYER_TEXT..temp[1]) end temp[ENTRY_FLAG] = PLAYER_FLAG table.insert(ChatHistoryDB2, 1, temp) for i = LOG_MAX, #ChatHistoryDB2 do table.remove(ChatHistoryDB2, LOG_MAX) end end end function Init() ChatHistoryDB2 = type(ChatHistoryDB2) == "table" and ChatHistoryDB2 or {} -- table.wipe(ChatHistoryDB2) -- DEBUG _G["CHAT_FLAG_" .. PLAYER_FLAG] = PLAYER_TEXT local oChatEdit_SetLastTellTarget = ChatEdit_SetLastTellTarget function ChatEdit_SetLastTellTarget(...) if addon.IsPrinting then return end return oChatEdit_SetLastTellTarget(...) end for i = 1, #EVENTS do addon:RegisterEvent(EVENTS[i]) end if IsLoggedIn() then OnEvent(addon, "PLAYER_LOGIN") else addon:RegisterEvent("PLAYER_LOGIN") end end function OnEvent(addon, event, ...) if event == "ADDON_LOADED" then if ADDON_NAME == ... then addon:UnregisterEvent(event) Init() end elseif event == "PLAYER_LOGIN" then addon:UnregisterEvent(event) addon.PlayerGUID = UnitGUID("player") Print() elseif addon.HasPrinted then Save(event, ...) end end addon:RegisterEvent("ADDON_LOADED") addon:SetScript("OnEvent", OnEvent)
92d1fcf75bc02418bba7cecb9505ee6fa28c3962
[ "Markdown", "Lua" ]
2
Markdown
MindScape00/ChatHistory
0d7fad1dde54e15c5f6d25890e7c2eac72b9e1e4
cc3ee3279093ce23b9a5cff0ca8b016ab961a068
refs/heads/master
<repo_name>Dashadower/git_console_test<file_sep>/3.py print("Hello this 3.py!!") <file_sep>/1.py print("Hello from 1.py!") <file_sep>/README.md Hello. This is a repo to test out git in console mode from ubuntu. <file_sep>/6.py print("Hello from 6.py!") <file_sep>/5.py print("Hello from 5.py!") <file_sep>/2.py print("Hello this is 2.py!")
a9781f32d8cc3291d3b653e7f39a4a08dc3d70a9
[ "Markdown", "Python" ]
6
Python
Dashadower/git_console_test
01d8fbb4d019e9ca21352e6d898e6bfacf1ba9cc
2dfc44b59aad97ac7a8d3258b295628c22331aaf
refs/heads/master
<repo_name>kentozuka/103api<file_sep>/app/ClassCat.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class ClassCat extends Model { public $timestamps = false; public function class() { return $this->belongsTo('App\Jugyou'); } public function first() { return $this->belongsTo('App\First'); } public function second() { return $this->belongsTo('App\Second'); } public function third() { return $this->belongsTo('App\Third'); } public function type() { return $this->belongsTo('App\Type'); } public function level() { return $this->belongsTo('App\Level'); } } <file_sep>/database/migrations/2020_04_04_120213_create_classes_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateClassesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('classes', function (Blueprint $table) { $table->id(); $table->year('year'); $table->integer('dept_id'); $table->text('title_jp'); $table->text('title_en'); $table->tinyInteger('credit'); $table->string('eligible', 5); $table->string('url', 50); // ここ大丈夫か再確認する $table->string('category_jp', 255); $table->string('category_en', 255); // category ne // $table->integer('level_id'); $table->integer('language_id'); $table->integer('term_id'); $table->integer('campus_id'); $table->boolean('is_open'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('classes'); } } <file_sep>/database/migrations/2020_03_31_054014_create_details_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateDetailsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('details', function (Blueprint $table) { $table->id(); $table->integer('class_id'); $table->text('subtitle'); $table->text('outline'); $table->text('objective'); // $table->text('goal'); $table->text('beforeafter'); $table->text('schedule'); $table->text('textbook'); $table->text('reference'); $table->integer('grading_id'); $table->text('note'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('details'); } } <file_sep>/app/Review.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Review extends Model { public function class() { return $this->belongsTo('App\Jugyou'); } public function like() { return $this->hasMany('App\Like'); } public function dislike() { return $this->hasMany('App\Dislike'); } } <file_sep>/app/Http/Controllers/Auth/RegisterController.php <?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\User; class RegisterController extends Controller { public function __invoke(Request $request) { $validatedData = $request->validate([ 'name' => 'required', 'email' => 'required|email|unique:users,email', 'password' => '<PASSWORD>', ]); $user = new User(); $user->fill($validatedData); $user->password = <PASSWORD>($request->password); $user->save(); $name = $request->name; if (!$token = auth()->attempt($request->only('email', 'password'))) { return response(null, 401); } return response()->json(compact('token', 'name')); } }<file_sep>/database/migrations/2020_04_04_163742_create_class_cats_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateClassCatsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('class_cats', function (Blueprint $table) { $table->id(); $table->integer('class_id'); $table->integer('first_id'); $table->integer('second_id'); $table->integer('third_id'); $table->integer('level_id'); $table->string('course_number', 10); $table->integer('type_id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('class_cats'); } } <file_sep>/app/Http/Controllers/ClassController.php <?php namespace App\Http\Controllers; use App\Jugyou; use App\Saved; use App\Detail; use App\View; use App\Period; use App\ClassCat; use Illuminate\Http\Request; use Illuminate\Support\Arr; use Illuminate\Pagination\LengthAwarePaginator; class ClassController extends Controller { public function search(Request $request) { // manual search functionality create april 27, 2020 // first step parameter validation $lng = $request->get('lng'); $dsp = $request->get('dsp'); if (!$lng || !$dsp) return response(null, 400); // narrowing the search scope by searching the base information first $base = []; array_push($base, ['year', now()->year]); if ($sch = $request->get('school')) array_push($base, ['dept_id', $sch]); if ($cre = $request->get('credit')) array_push($base, ['credit', $cre]); if ($eli = $request->get('eligible')) array_push($base, ['eligible', $eli]); if ($ter = $request->get('term')) array_push($base, ['term_id', $ter]); $lan = $request->get('language') ? json_decode($request->get('language')) : null; $can = $request->get('campus') ? json_decode($request->get('campus')) : null; if ($lan && $base) { $base = $can ? Jugyou::where($base)->whereIn('language_id', $lan)->whereIn('campus_id', $can)->pluck('id') : Jugyou::where($base)->whereIn('language_id', $lan)->pluck('id'); } else if ($base) { $base = $can ? Jugyou::where($base)->whereIn('campus_id', $can)->pluck('id') : Jugyou::where($base)->pluck('id'); } // futher narrowing the search scope by day and period $date = []; $day = $request->get('days') ? json_decode($request->get('days')) : []; $per = $request->get('periods') ? json_decode($request->get('periods')) : []; if ($base) { $date = Period::whereIn('class_id', $base)->get(); if ($day && $per) { $date = $date->whereIn('day', $day)->whereIn('period', $per)->pluck('class_id'); } else if ($day || $per) { $date = $day ? $date->whereIn('day', $day)->pluck('class_id') : $date->whereIn('period', $per)->pluck('id'); } else { $date = $date->pluck('class_id'); } } else { if ($day && $per) { $date = Period::whereIn('day', $day)->whereIn('period', $per)->pluck('class_id'); } else if ($day || $per) { $date = $day ? Period::whereIn('day', $day)->pluck('class_id') : Period::whereIn('period', $per)->pluck('id'); } } // further narrowing the search scope by academic desciplines $academic = []; $firsts = $request->get('firsts') ? json_decode($request->get('firsts')) : null; $seconds = $request->get('seconds') ? json_decode($request->get('seconds')) : null; $thirds = $request->get('thirds') ? json_decode($request->get('thirds')) : null; if ($date) { $academic = ClassCat::whereIn('class_id', $date)->get(); if ($thirds) { $academic = $academic->whereIn('first_id', $firsts)->whereIn('second_id', $seconds)->whereIn('third_id', $thirds)->pluck('class_id'); } else if ($seconds) { $academic = $academic->whereIn('first_id', $firsts)->whereIn('second_id', $seconds)->pluck('class_id'); }else if ($firsts) { $academic = $academic->whereIn('first_id', $firsts)->pluck('class_id'); } else { $academic = $academic->pluck('class_id'); } } else { if ($thirds) { $academic = ClassCat::whereIn('first_id', $firsts)->whereIn('second_id', $seconds)->whereIn('third_id', $thirds)->pluck('class_id'); } else if ($seconds) { $academic = ClassCat::whereIn('first_id', $firsts)->whereIn('second_id', $seconds)->pluck('class_id'); }else if ($firsts) { $academic = ClassCat::whereIn('first_id', $firsts)->pluck('class_id'); } } // create a ranking based on the search keyword relavance $key = $request->get('keyword'); $holder = []; if ($key) { if ($academic) { $en = Jugyou::whereIn('id', $academic)->where('title_en', 'like', "%$key%")->pluck('id')->toArray(); // 12pt $jp = Jugyou::whereIn('id', $academic)->where('title_jp', 'like', "%$key%")->pluck('id')->toArray(); // 12pt $sub = Detail::whereIn('class_id', $academic)->where('subtitle', 'like', "%$key%")->pluck('class_id')->toArray(); // 8pt $out = Detail::whereIn('class_id', $academic)->where('outline', 'like', "%$key%")->limit(80)->pluck('class_id')->toArray(); // 6pt $obj = Detail::whereIn('class_id', $academic)->where('objective', 'like', "%$key%")->limit(80)->pluck('class_id')->toArray(); // 2pt } else { $en = Jugyou::where('title_en', 'like', "%$key%")->pluck('id')->toArray(); // 12pt $jp = Jugyou::where('title_jp', 'like', "%$key%")->pluck('id')->toArray(); // 12pt $sub = Detail::where('subtitle', 'like', "%$key%")->pluck('class_id')->toArray(); // 8pt $out = Detail::where('outline', 'like', "%$key%")->limit(80)->pluck('class_id')->toArray(); // 6pt $obj = Detail::where('objective', 'like', "%$key%")->limit(80)->pluck('class_id')->toArray(); // 2pt } foreach ($en as $e) { array_key_exists($e, $holder) ? $holder[$e] += 10 : $holder[$e] = 12;} foreach ($jp as $j) {array_key_exists($j, $holder) ? $holder[$j] += 10 : $holder[$j] = 12;} foreach ($sub as $s) {array_key_exists($s, $holder) ? $holder[$s] += 6 : $holder[$s] = 8;} foreach ($out as $o) {array_key_exists($o, $holder) ? $holder[$o] += 4 : $holder[$o] = 6;} foreach ($obj as $b) {array_key_exists($b, $holder) ? $holder[$b] += 2: $holder[$b] = 2;} $holder = array_keys(collect($holder)->sort()->reverse()->toArray()); } else { $holder = $academic->toArray(); } // eliminating the result $trimmed = count($holder) > 25 ? count($holder) : false; // create result object $user_saved = $request->user()->saved_jugyous->pluck('class_id'); $bs = Jugyou::whereIn('id', $holder)->get('id'); if ($dsp === 'compact') { foreach ($bs as $ie) { $al = Jugyou::find($ie->id); $ie->title = $al['title_'.$lng]; $ie->professors = $al->profs->pluck('name_'.$lng); $ie->dept = $al->dept->$lng; $ie->term = $al->term->$lng; $ie->campus = $al->campus->$lng; $ie->rooms = $al->rooms; $ie->periods = $al->period; $ie->saved = Saved::where('class_id', $ie->id)->count(); $ie->view = View::where('class_id', $ie->id)->count(); $ie->user_saved = in_array($ie->id, $user_saved->toArray()); $ie->index = array_search($ie->id, $holder, true); } } else if ($dsp === 'detail') { foreach ($bs as $ie) { $al = Jugyou::find($ie->id); $ie->title = $al['title_'.$lng]; $ie->category = $al['category_'.$lng]; $ie->professors = $al->profs->pluck('name_'.$lng); $ie->dept = $al->dept->$lng; $ie->term = $al->term->$lng; $ie->campus = $al->campus->$lng; $ie->rooms = $al->rooms; $ie->periods = $al->period; $cats = ClassCat::where('class_id', $ie->id)->first(); $ie->level = $cats->level->$lng; $ie->type = $cats->type->$lng; $ie->detail = Detail::where('class_id', $ie->id)->select('outline')->first(); $ie->saved = Saved::where('class_id', $ie->id)->count(); $ie->view = View::where('class_id', $ie->id)->count(); $ie->user_saved = in_array($ie->id, $user_saved->toArray()); $ie->index = array_search($ie->id, $holder, true); } } $result = $bs->toArray(); usort($result, function ($a, $b) { return $a['index'] <=> $b['index']; }); return response()->json(['trimmed' => $trimmed, 'classes' => $result]); } public function index(Request $request) { $url = $request->url; $base = Jugyou::where('url', $url)->first(); $user_data = $request->user()->saved_jugyous->pluck('class_id'); if (!$base || !$language = $request->input('lng')) return response(null, 400); $basic = $base->only('year', 'title_' . $language, 'credit', 'eligible', 'url', 'category_' . $language, 'is_open'); $profs = $base->profs->pluck('name_' . $language); $dept = $base->dept->$language; $term = $base->term->$language; $campus = $base->campus->$language; $rooms = $base->rooms; $periods = $base->period; $level = $base->class_cat->first()->level->$language; $type = $base->class_cat->first()->type->$language; $detail = $base->detail; $base->detail->grading; $view = View::where('class_id', $base['id'])->count(); $saved = Saved::where('class_id', $base['id'])->count(); $is_saved = $user_data->contains($base['id']); $result = array('dept' => $dept, 'term' => $term, 'campus' => $campus, 'profs' => $profs, 'rooms' => $rooms, 'periods' => $periods, 'level' => $level, 'type' => $type, 'saved' => $saved, 'viwe' => $view, 'user_saved' => $is_saved, 'detail' => $detail); return response()->json(array_merge($basic, $result), 200); } public function saved(Request $request) { function class_data($data, $lng) { foreach ($data as $cl) { $base = Jugyou::find($cl->class_id); $cl->title = $base->only('title_' . $lng)['title_' . $lng]; $cl->profs = $base->profs->pluck('name_' . $lng); $cl->term = $base->term->$lng; $cl->languge = $base->language->$lng; $cl->department = $base->dept->$lng; $cl->saved = Saved::where('class_id', $cl->class_id)->count(); $cl->view = View::where('class_id', $cl->class_id)->count(); } } if (!$language = $request->input('lng')) return response(null, 400); $jugyous = $request->user()->saved_jugyous()->select('class_id')->paginate(25); if ($language === 'en') { class_data($jugyous, 'en'); } else if ($language === 'jp') { class_data($jugyous, 'jp'); } return response($jugyous, 200); } } <file_sep>/app/Http/Controllers/Auth/RefreshController.php <?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; class RefreshController extends Controller { public function __construct() { return $this->middleware(['auth:api']); } public function __invoke() { $token = auth()->refresh(); return response()->json(compact('token')); } } <file_sep>/app/ClassProf.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Pivot; class ClassProf extends Model { public $timestamps = false; public function class() { return $this->belongsTo('App\Jugyou'); } public function prof() { return $this->belongsTo('App\Prof'); } } <file_sep>/app/Grading.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Grading extends Model { public $timestamps = false; public function class() { return $this->belongsTo('App\Jugyou'); } public function detail() { return $this->hasOne('App\Detail'); } } <file_sep>/database/seeds/base-information.sql # ************************************************************ # Sequel Pro SQL dump # Version 4541 # # http://www.sequelpro.com/ # https://github.com/sequelpro/sequelpro # # Host: 127.0.0.1 (MySQL 5.7.28) # Database: 103 # Generation Time: 2020-04-07 16:25:14 +0000 # ************************************************************ /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Dump of table campuses # ------------------------------------------------------------ DROP TABLE IF EXISTS `campuses`; CREATE TABLE `campuses` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `jp` varchar(35) COLLATE utf8mb4_unicode_ci NOT NULL, `en` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL, `lati` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `long` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `campuses` WRITE; /*!40000 ALTER TABLE `campuses` DISABLE KEYS */; INSERT INTO `campuses` (`id`, `jp`, `en`, `lati`, `long`, `created_at`, `updated_at`) VALUES (1,'早稲田','Waseda','https://www.waseda.jp/top/access/waseda-campus',NULL,NULL,NULL), (2,'戸山','Toyama','https://www.waseda.jp/top/access/toyama-campus',NULL,NULL,NULL), (3,'所沢','Tokorozawa','https://www.waseda.jp/top/access/tokorozawa-campus',NULL,NULL,NULL), (4,'東伏見','Higashifushimi','https://www.waseda.jp/top/access/higashifushimi-campus',NULL,NULL,NULL), (5,'西早稲田','Nishiwaseda','https://www.waseda.jp/top/access/nishiwaseda-campus',NULL,NULL,NULL), (6,'その他','other','https://www.waseda.jp/top/access/',NULL,NULL,NULL); /*!40000 ALTER TABLE `campuses` ENABLE KEYS */; UNLOCK TABLES; # Dump of table depts # ------------------------------------------------------------ DROP TABLE IF EXISTS `depts`; CREATE TABLE `depts` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `jp` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL, `en` varchar(5) COLLATE utf8mb4_unicode_ci NOT NULL, `jp_long` varchar(25) COLLATE utf8mb4_unicode_ci NOT NULL, `en_long` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `code` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `depts` WRITE; /*!40000 ALTER TABLE `depts` DISABLE KEYS */; INSERT INTO `depts` (`id`, `jp`, `en`, `jp_long`, `en_long`, `code`, `created_at`, `updated_at`) VALUES (1,'政経','PSE','政治経済学部','School of Political Science and Economics','PSE',NULL,NULL), (2,'法学','LAW','法学部','School of Law','LAW',NULL,NULL), (3,'教育','EDU','教育学部','School of Education','EDU',NULL,NULL), (4,'商学','SOC','商学部','School of Commerce','SOC',NULL,NULL), (5,'社学','SSS','社会科学部','School of Social Sciences','SSS',NULL,NULL), (6,'人科','HUM','人間科学部','School of Human Sciences','HUM',NULL,NULL), (7,'スポーツ','SPS','スポーツ科学部','School of Sport Sciences','SPS',NULL,NULL), (8,'国際教養','SILS','国際教養学部','School of International Liberal Studies','SILS',NULL,NULL), (9,'文構','CMS','文化構想学部','School of Culture, Media and Society','CMS',NULL,NULL), (10,'文','HSS','文学部','School of Humanities and Social Sciences','HSS',NULL,NULL), (11,'先進','ASE','先進理工学部','School of Advanced Science and Engineering','ASE',NULL,NULL), (12,'基幹','FSE','基幹理工学部','School of Fundamental Science and Engineering','FSE',NULL,NULL), (13,'創造','CSE','創造理工学部','School of Creative Science and Engineering','CSE',NULL,NULL), (14,'グローバル','GEC','グローバルエデュケーションセンター','Global Education Center','GEC',NULL,NULL), (15,'その他','NRY','未登録','Not registered yet','NRY',NULL,NULL); /*!40000 ALTER TABLE `depts` ENABLE KEYS */; UNLOCK TABLES; # Dump of table firsts # ------------------------------------------------------------ DROP TABLE IF EXISTS `firsts`; CREATE TABLE `firsts` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `jp` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `en` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `code` varchar(5) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `firsts` WRITE; /*!40000 ALTER TABLE `firsts` DISABLE KEYS */; INSERT INTO `firsts` (`id`, `jp`, `en`, `code`, `created_at`, `updated_at`) VALUES (1,'情報学','Informatics','INF',NULL,NULL), (2,'図書館学/司書課程','Library Science/Librarian Course','LIB',NULL,NULL), (3,'学芸員共通科目','Curator-Training Program','CTP',NULL,NULL), (4,'文化財科学/博物館学','Scientific Studies of Material Culture','MUS',NULL,NULL), (5,'メディア研究','Media Studies','MDA',NULL,NULL), (6,'ジャーナリズム','Journalism','JOU',NULL,NULL), (7,'哲学','Philosophy','PHL',NULL,NULL), (8,'心理学','Psychology','PSY',NULL,NULL), (9,'考古学','Archaeology','ARC',NULL,NULL), (10,'歴史学','History','HIS',NULL,NULL), (11,'地域研究','Area Studies','ARS',NULL,NULL), (12,'地理学','Geography','GEO',NULL,NULL), (13,'政治学','Political Science','POL',NULL,NULL), (14,'国際関係論','International Relations','INT',NULL,NULL), (15,'法学','Law','LAW',NULL,NULL), (16,'経済学','Economics','ECN',NULL,NULL), (17,'商学','Commerce','CMM',NULL,NULL), (18,'経営学','Management','MAN',NULL,NULL), (19,'会計学','Accounting','ACC',NULL,NULL), (20,'統計学','Statistics','STA',NULL,NULL), (21,'社会学','Sociology','SOC',NULL,NULL), (22,'社会・安全システム科学','Social systems Engineering/Safety system','SSS',NULL,NULL), (23,'ジェンダー','Gender','GDR',NULL,NULL), (24,'教育学','Education','EDU',NULL,NULL), (25,'子ども学','Childhood science','CLD',NULL,NULL), (26,'人類学','Anthropology','ANT',NULL,NULL), (27,'数学','Mathematics','MAT',NULL,NULL), (28,'計算科学','Computational science','COM',NULL,NULL), (29,'物理学','Physics','PHY',NULL,NULL), (30,'化学','Chemistry','CHM',NULL,NULL), (31,'天文学','Astronomy','ASR',NULL,NULL), (32,'地球惑星科学','Earth and Planetary Science','PLN',NULL,NULL), (33,'生物学','Biology','BIO',NULL,NULL), (34,'ゲノム科学','Genome Science','GNM',NULL,NULL), (35,'医学','Medicine','MED',NULL,NULL), (36,'脳科学','Brain Sciences','BRN',NULL,NULL), (37,'看護学','Nursing','NRS',NULL,NULL), (38,'薬学','Pharmacy','PHA',NULL,NULL), (39,'ナノ・マイクロ科学','Nano/Micro Science','NAN',NULL,NULL), (40,'土木工学','Civil Engineering','CST',NULL,NULL), (41,'環境学','Environmental Science','ENV',NULL,NULL), (42,'建築学','Architecural Design &amp; Engineering','ADE',NULL,NULL), (43,'科学技術論','Science and Technology Studies','STS',NULL,NULL), (44,'機械工学','Mechanical Engineering','MEC',NULL,NULL), (45,'電気電子工学','Electrical and Electronic Engineering','ELC',NULL,NULL), (46,'制御・システム工学','Control Engineering/System Engineering','SYS',NULL,NULL), (47,'材料工学','Materials Engineering','MTL',NULL,NULL), (48,'プロセス・化学工学','Process/Chemical Engineering','PCS',NULL,NULL), (49,'経営工学','Industrial Engineering','MGT',NULL,NULL), (50,'総合工学','Integrated Engineering','IEN',NULL,NULL), (51,'人間科学','Human Sciences','HUM',NULL,NULL), (52,'家政学','Home Economics','LIF',NULL,NULL), (53,'農学','Agricultural Sciences','AGC',NULL,NULL), (54,'観光学','Tourism and Hospitality','TRS',NULL,NULL), (55,'芸術/美術','Art Studies','ART',NULL,NULL), (56,'デザイン学','Design Science','DES',NULL,NULL), (57,'健康/スポーツ科学','Health/Sports Science','HSS',NULL,NULL), (58,'言語学','Linguistics','LNG',NULL,NULL), (59,'語学','Languages','LAN',NULL,NULL), (60,'文学','Literature','LIT',NULL,NULL), (61,'総合社会科学','General Social Science','GSS',NULL,NULL), (62,'複合領域','Composite Fields Studies','CMF',NULL,NULL), (63,'基礎演習','Basic Study Practice','BSP',NULL,NULL), (64,'保健体育','Health and Physical Education','HPE',NULL,NULL), (65,'教職科目','Teacher-training Course Program','TCP',NULL,NULL), (66,'留学','Global Study Program','GSP',NULL,NULL), (67,'総合/学際','General Studies','GEN',NULL,NULL), (68,'指定なし','N/A','ZZZ',NULL,NULL); /*!40000 ALTER TABLE `firsts` ENABLE KEYS */; UNLOCK TABLES; # Dump of table languages # ------------------------------------------------------------ DROP TABLE IF EXISTS `languages`; CREATE TABLE `languages` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `jp` varchar(25) COLLATE utf8mb4_unicode_ci NOT NULL, `en` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL, `mixed` tinyint(1) NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `languages` WRITE; /*!40000 ALTER TABLE `languages` DISABLE KEYS */; INSERT INTO `languages` (`id`, `jp`, `en`, `mixed`, `created_at`, `updated_at`) VALUES (1,'指定なし','N/A',0,NULL,NULL), (2,'日本語','Japanese',0,NULL,NULL), (3,'英語','English',0,NULL,NULL), (4,'日・英併用','Japanese/English',1,NULL,NULL), (5,'ドイツ語','German',0,NULL,NULL), (6,'フランス語','French',0,NULL,NULL), (7,'中国語','Chinese',0,NULL,NULL), (8,'スペイン語','Spanish',0,NULL,NULL), (9,'朝鮮語','Korean',0,NULL,NULL), (10,'ロシア語','Russian',0,NULL,NULL), (11,'イタリア語','Italian',0,NULL,NULL), (12,'英・西併用','English/Spanish',1,NULL,NULL), (13,'英・中併用','English/Chinese',1,NULL,NULL), (14,'英・仏併用','English/French',1,NULL,NULL), (15,'英・朝併用','English/Korean',1,NULL,NULL), (16,'その他','other',0,NULL,NULL), (17,'日・仏併用','Japanese/French',1,NULL,NULL), (18,'英・独併用','English/German',1,NULL,NULL), (19,'','',0,NULL,NULL); /*!40000 ALTER TABLE `languages` ENABLE KEYS */; UNLOCK TABLES; # Dump of table levels # ------------------------------------------------------------ DROP TABLE IF EXISTS `levels`; CREATE TABLE `levels` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `jp` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `jp_desc` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `en` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `en_desc` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `levels` WRITE; /*!40000 ALTER TABLE `levels` DISABLE KEYS */; INSERT INTO `levels` (`id`, `jp`, `jp_desc`, `en`, `en_desc`, `created_at`, `updated_at`) VALUES (1,'初級レベル','入門的・導入的位置づけの科目','Level of Freshman','Beginner, initial or introductory',NULL,NULL), (2,'中級レベル','発展的・応用的内容を扱う科目','Level of Sophomore','Intermediate, developmental and applicative',NULL,NULL), (3,'上級レベル','実践的・専門的に高度な内容を扱う科目','Level of Junior','Advanced, practical and specialized',NULL,NULL), (4,'総仕上げ','学士課程で学習する最終段階の水準の科目','Level of Senior','Final stage advanced-level undergraduate',NULL,NULL), (5,'-','-','-','-',NULL,NULL), (6,'修士レベル','-','Level of Master','-',NULL,NULL), (7,'博士レベル','-','Level of Doctor','-',NULL,NULL), (8,'指定なし','-','Null','-',NULL,NULL); /*!40000 ALTER TABLE `levels` ENABLE KEYS */; UNLOCK TABLES; # Dump of table rooms # ------------------------------------------------------------ DROP TABLE IF EXISTS `rooms`; CREATE TABLE `rooms` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `campus_id` tinyint(4) NOT NULL, `building` int(11) NOT NULL, `room` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `rooms` WRITE; /*!40000 ALTER TABLE `rooms` DISABLE KEYS */; INSERT INTO `rooms` (`id`, `campus_id`, `building`, `room`, `created_at`, `updated_at`) VALUES (1,1,11,'605',NULL,NULL), (2,1,11,'912',NULL,NULL), (3,1,11,'812',NULL,NULL), (4,1,11,'817',NULL,NULL), (5,1,11,'915',NULL,NULL), (6,1,11,'809',NULL,NULL), (7,1,11,'707',NULL,NULL), (8,1,10,'106',NULL,NULL), (9,1,11,'801',NULL,NULL), (10,1,11,'805',NULL,NULL), (11,1,11,'504',NULL,NULL), (12,1,11,'604',NULL,NULL), (13,1,11,'815',NULL,NULL), (14,1,11,'610',NULL,NULL), (15,1,11,'609',NULL,NULL), (16,1,3,'404',NULL,NULL), (17,1,14,'501',NULL,NULL), (18,1,11,'503',NULL,NULL), (19,1,14,'607',NULL,NULL), (20,1,11,'508',NULL,NULL), (21,1,11,'507',NULL,NULL), (22,1,7,'311',NULL,NULL), (23,1,11,'702',NULL,NULL), (24,1,11,'906',NULL,NULL), (25,1,11,'813',NULL,NULL), (26,1,11,'816',NULL,NULL), (27,1,11,'803',NULL,NULL), (28,1,11,'603',NULL,NULL), (29,1,11,'820',NULL,NULL), (30,1,10,'102',NULL,NULL), (31,1,11,'818',NULL,NULL), (32,1,7,'209',NULL,NULL), (33,1,11,'902',NULL,NULL), (34,1,3,'305',NULL,NULL), (35,1,11,'704',NULL,NULL), (36,1,22,'201',NULL,NULL), (37,1,11,'711',NULL,NULL), (38,1,7,'206',NULL,NULL), (39,1,11,'502',NULL,NULL), (40,1,7,'207',NULL,NULL), (41,1,7,'306',NULL,NULL), (42,1,3,'607',NULL,NULL), (43,1,11,'709',NULL,NULL), (44,1,11,'811',NULL,NULL), (45,1,8,'B102',NULL,NULL), (46,1,14,'403',NULL,NULL), (47,1,11,'819',NULL,NULL), (48,1,11,'506',NULL,NULL), (49,1,11,'703',NULL,NULL), (50,1,8,'308',NULL,NULL), (51,1,3,'405',NULL,NULL), (52,1,11,'910',NULL,NULL), (53,1,3,'202(Center for Teaching,Learning, and Technology Active Learning)',NULL,NULL), (54,1,3,'502',NULL,NULL), (55,1,11,'901',NULL,NULL), (56,1,3,'401',NULL,NULL), (57,1,11,'807',NULL,NULL), (58,1,11,'606',NULL,NULL), (59,1,11,'701',NULL,NULL), (60,1,3,'801',NULL,NULL), (61,1,11,'505',NULL,NULL), (62,1,10,'104',NULL,NULL), (63,1,3,'306',NULL,NULL), (64,1,7,'419',NULL,NULL), (65,1,14,'604',NULL,NULL), (66,1,7,'205',NULL,NULL), (67,1,16,'702',NULL,NULL), (68,1,11,'710',NULL,NULL), (69,1,7,'312',NULL,NULL), (70,1,11,'814',NULL,NULL), (71,1,11,'911',NULL,NULL), (72,1,11,'804',NULL,NULL), (73,1,11,'705',NULL,NULL), (74,1,11,'802',NULL,NULL), (75,1,10,'201',NULL,NULL), (76,1,11,'708',NULL,NULL), (77,1,15,'101',NULL,NULL), (78,1,11,'808',NULL,NULL), (79,1,22,'619',NULL,NULL), (80,1,11,'806',NULL,NULL), (81,1,11,'909',NULL,NULL), (82,1,3,'701',NULL,NULL), (83,1,11,'914',NULL,NULL), (84,1,14,'610',NULL,NULL), (85,1,3,'802',NULL,NULL), (86,1,10,'208',NULL,NULL), (87,1,7,'308',NULL,NULL), (88,1,8,'307',NULL,NULL), (89,1,10,'306',NULL,NULL), (90,1,11,'905',NULL,NULL), (91,1,22,'601',NULL,NULL), (92,1,14,'402',NULL,NULL), (93,1,10,'301',NULL,NULL), (94,1,3,'301',NULL,NULL), (95,1,11,'706',NULL,NULL), (96,1,10,'204',NULL,NULL), (97,1,14,'502',NULL,NULL), (98,2,31,'202',NULL,NULL), (99,2,33,'432',NULL,NULL), (100,2,31,'203',NULL,NULL), (101,2,31,'204',NULL,NULL), (102,2,33,'440',NULL,NULL), (103,2,33,'232',NULL,NULL), (104,2,31,'307',NULL,NULL), (105,2,32,'322',NULL,NULL), (106,2,33,'231',NULL,NULL), (107,2,31,'03',NULL,NULL), (108,2,33,'433',NULL,NULL), (109,2,33,'333',NULL,NULL), (110,2,33,'732',NULL,NULL), (111,2,33,'441',NULL,NULL), (112,2,32,'224',NULL,NULL), (113,2,31,'02',NULL,NULL), (114,2,32,'226',NULL,NULL), (115,2,32,'321',NULL,NULL), (116,2,33,'435',NULL,NULL), (117,2,33,'531',NULL,NULL), (118,2,33,'436',NULL,NULL), (119,2,32,'225',NULL,NULL), (120,2,31,'201',NULL,NULL), (121,2,32,'228',NULL,NULL), (122,2,32,'227',NULL,NULL), (123,2,32,'324',NULL,NULL), (124,2,32,'323',NULL,NULL), (125,2,31,'205',NULL,NULL), (126,2,31,'103',NULL,NULL), (127,2,36,'582',NULL,NULL), (128,2,33,'438',NULL,NULL), (129,2,32,'229',NULL,NULL), (130,2,31,'105',NULL,NULL), (131,2,31,'104',NULL,NULL), (132,2,31,'106',NULL,NULL), (133,2,33,'731',NULL,NULL), (134,2,31,'310',NULL,NULL), (135,2,33,'439',NULL,NULL), (136,2,31,'01',NULL,NULL), (137,2,33,'431',NULL,NULL), (138,2,31,'301',NULL,NULL), (139,2,33,'437',NULL,NULL), (140,2,36,'482',NULL,NULL), (141,2,34,'451',NULL,NULL), (142,2,36,'682',NULL,NULL), (143,2,34,'357',NULL,NULL), (144,2,32,'325',NULL,NULL), (145,2,33,'332',NULL,NULL), (146,2,36,'481',NULL,NULL), (147,2,33,'331',NULL,NULL), (148,2,34,'356',NULL,NULL), (149,2,33,'434',NULL,NULL), (150,2,34,'452',NULL,NULL), (151,2,32,'127',NULL,NULL), (152,2,33,'613',NULL,NULL), (153,2,34,'355',NULL,NULL), (154,2,31,'208',NULL,NULL), (155,2,36,'382',NULL,NULL), (156,2,36,'681',NULL,NULL), (157,2,34,'453',NULL,NULL), (158,2,34,'151',NULL,NULL), (159,2,36,'581',NULL,NULL), (160,2,38,'AV',NULL,NULL), (161,2,32,'128',NULL,NULL), (162,2,31,'102',NULL,NULL), (163,2,39,'2105',NULL,NULL), (164,2,36,'283',NULL,NULL); /*!40000 ALTER TABLE `rooms` ENABLE KEYS */; UNLOCK TABLES; # Dump of table seconds # ------------------------------------------------------------ DROP TABLE IF EXISTS `seconds`; CREATE TABLE `seconds` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `first_id` int(11) NOT NULL, `jp` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `en` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `code` varchar(5) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `seconds` WRITE; /*!40000 ALTER TABLE `seconds` DISABLE KEYS */; INSERT INTO `seconds` (`id`, `first_id`, `jp`, `en`, `code`, `created_at`, `updated_at`) VALUES (1,1,'アルゴリズムと複雑性','Algorithms and Complexity','A',NULL,NULL), (2,1,'アーキテクチャと計算機構成','Architecture and Organization','B',NULL,NULL), (3,1,'計算科学','Computational Science','C',NULL,NULL), (4,1,'離散構造','Discrete Structures','D',NULL,NULL), (5,1,'グラフィクスと可視化','Graphics and Visualization','E',NULL,NULL), (6,1,'ヒューマンコンピュータインタラクション','Human-Computer Interaction','F',NULL,NULL), (7,1,'情報保全とセキュリティ','Information Assurance and Security','G',NULL,NULL), (8,1,'情報管理','Information Management','H',NULL,NULL), (9,1,'知的システム','Intelligent Systems','I',NULL,NULL), (10,1,'ネットワークと通信','Networking and Communications','J',NULL,NULL), (11,1,'オペレーティングシステム','Operating Systems','K',NULL,NULL), (12,1,'プラットフォームベース開発','Platform-based Development','L',NULL,NULL), (13,1,'並列分散処理','Parallel and Distributed Computing','M',NULL,NULL), (14,1,'プログラミング言語','Programming Languages','N',NULL,NULL), (15,1,'ソフトウェア開発の基礎','Software Development Fundamentals','O',NULL,NULL), (16,1,'ソフトウェア工学','Software Engineering','P',NULL,NULL), (17,1,'情報システムの基礎','Systems Fundamentals','Q',NULL,NULL), (18,1,'社会問題と実践','Social Issues and Professional Practice','R',NULL,NULL), (19,1,'その他','Others','V',NULL,NULL), (20,1,'総合','General','Y',NULL,NULL), (21,2,'図書館学/司書課程','Library Science/Librarian Course','X',NULL,NULL), (22,3,'学芸員共通科目','Curator-Training Program','X',NULL,NULL), (23,4,'文化財科学/博物館学','Scientific Studies of Material Culture','X',NULL,NULL), (24,5,'メディア研究','Media Studies','X',NULL,NULL), (25,6,'ジャーナリズム','Journalism','X',NULL,NULL), (26,7,'東洋哲学','Eastern Philosophy','E',NULL,NULL), (27,7,'論理学','Logic','L',NULL,NULL), (28,7,'倫理学','Ethics','M',NULL,NULL), (29,7,'宗教学','Religious Studies','R',NULL,NULL), (30,7,'科学哲学','Philosophy of Socience','S',NULL,NULL), (31,7,'思想史','History of Thought','T',NULL,NULL), (32,7,'その他 哲学','Philosophy','V',NULL,NULL), (33,7,'西洋哲学','Western Philosophy','W',NULL,NULL), (34,8,'心理学','Psychology','X',NULL,NULL), (35,9,'考古学','Archaeology','X',NULL,NULL), (36,10,'日本史','Japanese History','A',NULL,NULL), (37,10,'アジア史','History of Asia','B',NULL,NULL), (38,10,'北アメリカ史','History of North America','C',NULL,NULL), (39,10,'中南アメリカ史','History of Central &amp; South America','D',NULL,NULL), (40,10,'ヨーロッパ史','History of Europe','E',NULL,NULL), (41,10,'オセアニア史','History of Pacific-rim','F',NULL,NULL), (42,10,'アフリカ史','History of Africa','G',NULL,NULL), (43,10,'その他 歴史学','Historical Studies in General','V',NULL,NULL), (44,11,'日本研究','Japanese Studies','A',NULL,NULL), (45,11,'中国研究','Chinese Studies','B',NULL,NULL), (46,11,'台湾研究','Taiwanese Studies','C',NULL,NULL), (47,11,'コリア研究','Korean Studies','D',NULL,NULL), (48,11,'東南アジア研究','Southeast Asian studies','E',NULL,NULL), (49,11,'北アメリカ研究','North American Studies','F',NULL,NULL), (50,11,'中南アメリカ研究','Central &amp; South American Studies','G',NULL,NULL), (51,11,'ヨーロッパ研究','European Studies','H',NULL,NULL), (52,11,'イスラーム地域研究','Islamic Area Studies','I',NULL,NULL), (53,11,'オセアニア研究','Pacific-rim Studies','J',NULL,NULL), (54,11,'アフリカ研究','African Studies','K',NULL,NULL), (55,11,'その他 地域研究','Area Studies','V',NULL,NULL), (56,12,'地理学','Geography','X',NULL,NULL), (57,13,'政治学','Political Science','X',NULL,NULL), (58,14,'国際関係学','International Studies','A',NULL,NULL), (59,14,'国際公共政策','International Public Policy','B',NULL,NULL), (60,15,'公法','Public Law','A',NULL,NULL), (61,15,'民事法','Civil Law and Procedure','B',NULL,NULL), (62,15,'刑事法','Laws on Criminal Matters','C',NULL,NULL), (63,15,'基礎法','Basic Legal Sciences','D',NULL,NULL), (64,15,'国際法','International Law','E',NULL,NULL), (65,15,'社会法','Social Law','F',NULL,NULL), (66,15,'新領域法学','New Fields of Law','G',NULL,NULL), (67,15,'その他法学','Other Legal Sciences','H',NULL,NULL), (68,16,'応用経済学','Applied Economics','A',NULL,NULL), (69,16,'経済学一般','Economics in General','E',NULL,NULL), (70,16,'経済史','Economic History','H',NULL,NULL), (71,16,'理論・計量経済学','Theoretical Economics / Econometrics','T',NULL,NULL), (72,17,'企業財務','Corporate Finance','C',NULL,NULL), (73,17,'国際ビジネス・貿易','International Business and Trade','I',NULL,NULL), (74,17,'マーケティング','Marketing','M',NULL,NULL), (75,17,'リスクマネジメント・保険','Risk Management and Insurance','R',NULL,NULL), (76,18,'経営学','Management','X',NULL,NULL), (77,19,'会計学','Accounting','X',NULL,NULL), (78,20,'統計学','Statistics','X',NULL,NULL), (79,21,'社会学','Sociology','X',NULL,NULL), (80,22,'社会・安全システム科学','Social Systems Engineering/Safety System','X',NULL,NULL), (81,23,'ジェンダー','Gender','X',NULL,NULL), (82,24,'教育学','Education','X',NULL,NULL), (83,25,'子ども学','Childhood science','X',NULL,NULL), (84,26,'応用人類学','Applied Anthropology','A',NULL,NULL), (85,26,'文化人類学','Cultural Anthropology','C',NULL,NULL), (86,26,'自然人類学','Physical Anthropology','P',NULL,NULL), (87,26,'その他 人類学','Anthropology','V',NULL,NULL), (88,27,'数学','Mathematics','X',NULL,NULL), (89,28,'計算科学','Computational Science','X',NULL,NULL), (90,29,'応用物理学','Applied Physics','A',NULL,NULL), (91,29,'基礎物理学','Basic Physics','B',NULL,NULL), (92,29,'物理学','Physics','P',NULL,NULL), (93,30,'応用化学','Applied Chemistry','A',NULL,NULL), (94,30,'化学共通','Chemistry','C',NULL,NULL), (95,30,'材料化学','Materials Chemistry','M',NULL,NULL), (96,31,'天文学','Astronomy','X',NULL,NULL), (97,32,'地球惑星科学','Earth and Planetary Science','X',NULL,NULL), (98,33,'生物学','Biology','X',NULL,NULL), (99,34,'ゲノム科学','Genome Science','X',NULL,NULL), (100,35,'社会医学','Social Medicine','A',NULL,NULL), (101,35,'細菌学(含真菌学)','Bacteriology(including Mycology)','B',NULL,NULL), (102,35,'臨床医学','Clinical Medicine','C',NULL,NULL), (103,35,'精神神経科学','Psychiatric Science','D',NULL,NULL), (104,35,'環境生理学(含体力医学・栄養生理学)','Evnvironmental Physiology(including Physical Medicine and Nutritional Physiology)','E',NULL,NULL), (105,35,'免疫学','Immunology','F',NULL,NULL), (106,35,'医学一般','General Medicine','G',NULL,NULL), (107,35,'人類遺伝学','Human Genetics','H',NULL,NULL), (108,35,'内科学','Internal Medicine','I',NULL,NULL), (109,35,'病態医化学','Pathological Medical Chemistry','J',NULL,NULL), (110,35,'応用薬理学','Applied Pharmacology','K',NULL,NULL), (111,35,'病態検査学','Laboratory Medicine','L',NULL,NULL), (112,35,'医学物理学・放射線技術学','Medical Physics and Radiation Technology','M',NULL,NULL), (113,35,'疼痛学','Pain Science','N',NULL,NULL), (114,35,'腫瘍学','Oncology','O',NULL,NULL), (115,35,'病理学','Pathology','P',NULL,NULL), (116,35,'代謝学','Metabolomics','Q',NULL,NULL), (117,35,'放射線科学','Radiation Science','R',NULL,NULL), (118,35,'外科学','Surgery','S',NULL,NULL), (119,35,'疫学・予防医学','Epidemiology and Preventive Medicine','T',NULL,NULL), (120,35,'内分泌学','Endocrinology','U',NULL,NULL), (121,35,'ウイルス学','Virology','V',NULL,NULL), (122,35,'胎児・新生児医学','Embryonic/Neonatal Medicine','W',NULL,NULL), (123,35,'寄生虫学(含衛生動物学)','Parasitology(including Sanitary Zoology)','Y',NULL,NULL), (124,36,'脳科学','Brain Sciences','X',NULL,NULL), (125,37,'看護学','Nursing','X',NULL,NULL), (126,38,'薬学','Pharmacy','X',NULL,NULL), (127,39,'ナノ・マイクロ科学','Nano/Micro Science','X',NULL,NULL), (128,40,'土木工学','Civil Engineering','X',NULL,NULL), (129,41,'環境学および持続可能性','Environmental Science and Sustainability','E',NULL,NULL), (130,41,'その他 環境学','Environmental Science','V',NULL,NULL), (131,42,'建築学','Architecural Design &amp; Engineering','X',NULL,NULL), (132,43,'科学技術論','Science and Technology Studies','X',NULL,NULL), (133,44,'機械工学','Mechanical Engineering','X',NULL,NULL), (134,45,'電気電子工学','Electrical and Electronic Engineering','X',NULL,NULL), (135,46,'経営システム工学・制御システム工学','Industrial and Management System Engineering/Control Engineering','M',NULL,NULL), (136,46,'その他制御・システム工学','Control Engineering/System Engineering','V',NULL,NULL), (137,47,'材料工学','Materials Engineering','X',NULL,NULL), (138,48,'プロセス・化学工学','Process/Chemical Engineering','X',NULL,NULL), (139,49,'経営工学','Industrial Engineering','X',NULL,NULL), (140,50,'実体情報学','Embodiment Informatics','E',NULL,NULL), (141,50,'総合工学','Integrated Engineering','I',NULL,NULL), (142,51,'人間科学基幹','Core of Human Sciences','A',NULL,NULL), (143,51,'環境科学','Environmental Sciences','B',NULL,NULL), (144,51,'社会環境','Social Environment','C',NULL,NULL), (145,51,'人類文化・歴史','Culture and History of Humankind','D',NULL,NULL), (146,51,'環境デザイン・行動心理','Environmental Design and Psychology of Behavior','E',NULL,NULL), (147,51,'健康・生命医科学','Health and Biomedical Sciences','F',NULL,NULL), (148,51,'医工人間学','Medicine, Engineering and Humanity','G',NULL,NULL), (149,51,'保健福祉学','Health and Social Welfare','H',NULL,NULL), (150,51,'臨床心理行動科学','Clinical Psychology and Behavioral Science','I',NULL,NULL), (151,51,'人間情報工学','Human Informatics and Ergonomics','J',NULL,NULL), (152,51,'教育コミュニケーション','Education and Communication','K',NULL,NULL), (153,52,'家政学','Home Economics','X',NULL,NULL), (154,53,'水圏','Aquatic','A',NULL,NULL), (155,53,'応用生物学','Applied Biology','B',NULL,NULL), (156,53,'環境農学','Environmental Agricultura','E',NULL,NULL), (157,53,'植物','Plant','P',NULL,NULL), (158,53,'社会・経済','Society and Economy','S',NULL,NULL), (159,53,'その他農学','Agricultural Sciences','V',NULL,NULL), (160,54,'観光学','Tourism and Hospitality','X',NULL,NULL), (161,55,'舞踊','Dance Studies','D',NULL,NULL), (162,55,'映像','Film Studies','F',NULL,NULL), (163,55,'美術史','Art History','H',NULL,NULL), (164,55,'音楽','Music','M',NULL,NULL), (165,55,'絵画/写真/平面','Picture','P',NULL,NULL), (166,55,'彫刻/立体','Sculpture','S',NULL,NULL), (167,55,'演劇','Theatre','T',NULL,NULL), (168,55,'その他 芸術/美術','Art Studies','V',NULL,NULL), (169,56,'デザイン学','Design Science','X',NULL,NULL), (170,57,'トレーナー','Athletic Training and Conditioning','A',NULL,NULL), (171,57,'スポーツビジネス','Sport Business','B',NULL,NULL), (172,57,'スポーツ文化','Culture of Sport','C',NULL,NULL), (173,57,'身体運動科学','Exercise Sciences','E',NULL,NULL), (174,57,'健康スポーツ','Sports and Health Promotion','H',NULL,NULL), (175,57,'スポーツ医科学','Sport Medicine and Science','M',NULL,NULL), (176,57,'スポーツ教育','Sport/Physical Education','P',NULL,NULL), (177,57,'スポーツ科学','Sport Sciences','S',NULL,NULL), (178,57,'スポーツコーチング','Sports Coaching','T',NULL,NULL), (179,58,'応用言語学','Applied Linguistics','A',NULL,NULL), (180,58,'外国語教育学','Foreign Language Education','F',NULL,NULL), (181,58,'歴史言語学','Historical Linguistics','H',NULL,NULL), (182,58,'言語情報学','Linguistic Informatics','I',NULL,NULL), (183,58,'日本語教育学','Japanese Language Education','J',NULL,NULL), (184,58,'理論言語学','Theoretical Linguistics','T',NULL,NULL), (185,59,'中国語','Chinese','C',NULL,NULL), (186,59,'英語','English','E',NULL,NULL), (187,59,'フランス語','French','F',NULL,NULL), (188,59,'ドイツ語','German','G',NULL,NULL), (189,59,'イタリア語','Italian','I',NULL,NULL), (190,59,'日本語','Japanese','J',NULL,NULL), (191,59,'朝鮮語','Korean','K',NULL,NULL), (192,59,'ロシア語','Russian','R',NULL,NULL), (193,59,'スペイン語','Spanish','S',NULL,NULL), (194,59,'その他言語','World Languages','V',NULL,NULL), (195,60,'中国文学','Chinese Literature','C',NULL,NULL), (196,60,'英語圏文学','Literature in English','E',NULL,NULL), (197,60,'フランス文学','French Literature','F',NULL,NULL), (198,60,'ドイツ文学','German Literature','G',NULL,NULL), (199,60,'イタリア文学','Italian Literature','I',NULL,NULL), (200,60,'日本文学','Japanese Literature','J',NULL,NULL), (201,60,'比較文学','Comparative Literature','O',NULL,NULL), (202,60,'ロシア文学','Russian Literature','R',NULL,NULL), (203,60,'スペイン語圏文学','Literature in Spanish','S',NULL,NULL), (204,60,'その他 文学','Literature','V',NULL,NULL), (205,61,'総合社会科学','General Social Science','A',NULL,NULL), (206,61,'シチズンシップ・政府','Citizenship/Government','B',NULL,NULL), (207,61,'産業・企業・労働','Industry/Company/Labor','C',NULL,NULL), (208,61,'グローバル社会','Global Society','D',NULL,NULL), (209,61,'人権・福祉','Human Rights/Welfare','E',NULL,NULL), (210,61,'環境・計画','Environment/Planning','F',NULL,NULL), (211,61,'思想・文化','Thought/Culture','G',NULL,NULL), (212,61,'都市','Urban Studies','H',NULL,NULL), (213,62,'文化(比較文化・ジェンダー論・カルチュラルスタディーズ)','Culture','C',NULL,NULL), (214,62,'表現(美術/映像/演劇/音楽/芸能/文学/メディア論)','Expression','E',NULL,NULL), (215,62,'人間医工学','Human Medical Engineering','H',NULL,NULL), (216,62,'人間(心理学/哲学/身体論/健康/セラピー)','Human','M',NULL,NULL), (217,63,'基礎演習','Basic Study Practice','X',NULL,NULL), (218,64,'保健体育','Health and Physical Education','X',NULL,NULL), (219,65,'教職科目','Teacher-Training Course Program','X',NULL,NULL), (220,66,'留学','Global Study Program','X',NULL,NULL), (221,67,'総合/学際','General Studies','X',NULL,NULL), (222,68,'指定なし','N/A','Z',NULL,NULL); /*!40000 ALTER TABLE `seconds` ENABLE KEYS */; UNLOCK TABLES; # Dump of table terms # ------------------------------------------------------------ DROP TABLE IF EXISTS `terms`; CREATE TABLE `terms` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `jp` varchar(25) COLLATE utf8mb4_unicode_ci NOT NULL, `en` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `code` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `terms` WRITE; /*!40000 ALTER TABLE `terms` DISABLE KEYS */; INSERT INTO `terms` (`id`, `jp`, `en`, `code`, `created_at`, `updated_at`) VALUES (1,'春学期','Spring semester',NULL,NULL,NULL), (2,'春クォーター','Spring quarter ',NULL,NULL,NULL), (3,'夏クォーター','Summer quarter',NULL,NULL,NULL), (4,'夏期集中','Summer',NULL,NULL,NULL), (5,'秋学期','Fall semester',NULL,NULL,NULL), (6,'秋クォーター','Fall quarter',NULL,NULL,NULL), (7,'冬クォーター','Winter quarter',NULL,NULL,NULL), (8,'冬季集中','Winter',NULL,NULL,NULL), (9,'通年','Full year',NULL,NULL,NULL), (10,'その他','Others',NULL,NULL,NULL); /*!40000 ALTER TABLE `terms` ENABLE KEYS */; UNLOCK TABLES; # Dump of table thirds # ------------------------------------------------------------ DROP TABLE IF EXISTS `thirds`; CREATE TABLE `thirds` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `first_id` int(11) NOT NULL, `second_id` int(11) NOT NULL, `jp` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `en` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `code` varchar(5) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `thirds` WRITE; /*!40000 ALTER TABLE `thirds` DISABLE KEYS */; INSERT INTO `thirds` (`id`, `first_id`, `second_id`, `jp`, `en`, `code`, `created_at`, `updated_at`) VALUES (1,1,1,'概論','Introduction','0',NULL,NULL), (2,1,1,'一般','Algorithms and Complexity','1',NULL,NULL), (3,1,1,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (4,1,2,'概論','Introduction','0',NULL,NULL), (5,1,2,'一般','Architecture and Organization','1',NULL,NULL), (6,1,2,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (7,1,3,'概論','Introduction','0',NULL,NULL), (8,1,3,'一般','Computational Science','1',NULL,NULL), (9,1,3,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (10,1,4,'概論','Introduction','0',NULL,NULL), (11,1,4,'一般','Discrete Structures','1',NULL,NULL), (12,1,4,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (13,1,5,'概論','Introduction','0',NULL,NULL), (14,1,5,'一般','Graphics and Visualization','1',NULL,NULL), (15,1,5,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (16,1,6,'概論','Introduction','0',NULL,NULL), (17,1,6,'一般','Human-Computer Interaction','1',NULL,NULL), (18,1,6,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (19,1,7,'概論','Introduction','0',NULL,NULL), (20,1,7,'一般','Information Assurance and Security','1',NULL,NULL), (21,1,7,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (22,1,8,'概論','Introduction','0',NULL,NULL), (23,1,8,'一般','Information Management','1',NULL,NULL), (24,1,8,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (25,1,9,'概論','Introduction','0',NULL,NULL), (26,1,9,'一般','Intelligent Systems','1',NULL,NULL), (27,1,9,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (28,1,10,'概論','Introduction','0',NULL,NULL), (29,1,10,'一般','Networking and Communications','1',NULL,NULL), (30,1,10,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (31,1,11,'概論','Introduction','0',NULL,NULL), (32,1,11,'一般','Operating Systems','1',NULL,NULL), (33,1,11,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (34,1,12,'概論','Introduction','0',NULL,NULL), (35,1,12,'一般','Platform-based Development','1',NULL,NULL), (36,1,12,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (37,1,13,'概論','Introduction','0',NULL,NULL), (38,1,13,'一般','Parallel and Distributed Computing','1',NULL,NULL), (39,1,13,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (40,1,14,'概論','Introduction','0',NULL,NULL), (41,1,14,'一般','Programming Languages','1',NULL,NULL), (42,1,14,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (43,1,15,'概論','Introduction','0',NULL,NULL), (44,1,15,'一般','Software Development Fundamentals','1',NULL,NULL), (45,1,15,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (46,1,16,'概論','Introduction','0',NULL,NULL), (47,1,16,'一般','Software Engineering','1',NULL,NULL), (48,1,16,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (49,1,17,'概論','Introduction','0',NULL,NULL), (50,1,17,'一般','Systems Fundamentals','1',NULL,NULL), (51,1,17,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (52,1,18,'概論','Introduction','0',NULL,NULL), (53,1,18,'一般','Social Issues and Professional Practice','1',NULL,NULL), (54,1,18,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (55,1,19,'概論','Introduction','0',NULL,NULL), (56,1,19,'一般','Others','1',NULL,NULL), (57,1,19,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (58,1,20,'概論','Introduction','0',NULL,NULL), (59,1,20,'一般','General','1',NULL,NULL), (60,1,20,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (61,2,21,'図書館学/司書課程','Library Science/Librarian Course','0',NULL,NULL), (62,2,21,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (63,3,22,'学芸員共通科目','Curator-Training Program','0',NULL,NULL), (64,3,22,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (65,4,23,'概論','Introduction','0',NULL,NULL), (66,4,23,'その他','Others','8',NULL,NULL), (67,4,23,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (68,5,24,'メディア研究','Media Studies','0',NULL,NULL), (69,5,24,'理論','Theory','1',NULL,NULL), (70,5,24,'歴史','History','2',NULL,NULL), (71,5,24,'産業','Industries','3',NULL,NULL), (72,5,24,'制度','Institutions','4',NULL,NULL), (73,5,24,'広報・宣伝','Public Relations and Advertising','5',NULL,NULL), (74,5,24,'運動・文化','Social Activities and Culture','6',NULL,NULL), (75,5,24,'その他','Others','8',NULL,NULL), (76,5,24,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (77,6,25,'ジャーナリズム','Journalism','0',NULL,NULL), (78,6,25,'思想・倫理','Philosophy and Ethics','1',NULL,NULL), (79,6,25,'歴史','History','2',NULL,NULL), (80,6,25,'現代','Contemporary Journalism','3',NULL,NULL), (81,6,25,'国際・比較','International and Comparative Journalism','4',NULL,NULL), (82,6,25,'教育','Education','5',NULL,NULL), (83,6,25,'表現・技術','Representation and Technology','6',NULL,NULL), (84,6,25,'その他','Others','8',NULL,NULL), (85,6,25,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (86,7,26,'概論','Introduction','0',NULL,NULL), (87,7,26,'インド仏教','Indian Buddhism','1',NULL,NULL), (88,7,26,'インド哲学','Indian Philosophy','2',NULL,NULL), (89,7,26,'中国思想','Chinese Thought','3',NULL,NULL), (90,7,26,'道教','Taoism','4',NULL,NULL), (91,7,26,'儒教','Confucianism','5',NULL,NULL), (92,7,26,'日本仏教/中国仏教','Japanese Buddhism/Chinese Buddhism','6',NULL,NULL), (93,7,26,'日本思想','Japanese Thought','7',NULL,NULL), (94,7,26,'その他','Others','8',NULL,NULL), (95,7,26,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (96,7,27,'概論','Introduction','0',NULL,NULL), (97,7,27,'古典論理学','Classical Logic','1',NULL,NULL), (98,7,27,'数理論理学','Mathematical Logic','2',NULL,NULL), (99,7,27,'その他','Others','8',NULL,NULL), (100,7,27,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (101,7,28,'概論','Introduction','0',NULL,NULL), (102,7,28,'倫理学史','History of Ethics','1',NULL,NULL), (103,7,28,'応用倫理学','Applied Ethics','2',NULL,NULL), (104,7,28,'メタ倫理学','Metaethics','3',NULL,NULL), (105,7,28,'その他','Others','8',NULL,NULL), (106,7,28,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (107,7,29,'概論','Introduction','0',NULL,NULL), (108,7,29,'宗教哲学','Philosophy of Religion','1',NULL,NULL), (109,7,29,'宗教史学','History of Religions','2',NULL,NULL), (110,7,29,'宗教民俗学','Religious Folklore','3',NULL,NULL), (111,7,29,'その他','Others','8',NULL,NULL), (112,7,29,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (113,7,30,'概論','Introduction','0',NULL,NULL), (114,7,30,'その他','Others','1',NULL,NULL), (115,7,30,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (116,7,31,'概論','Introduction','0',NULL,NULL), (117,7,31,'古代思想史','Ancient Thought','1',NULL,NULL), (118,7,31,'中世思想史','Medieval Thought','2',NULL,NULL), (119,7,31,'近代思想史','Modern Thought','3',NULL,NULL), (120,7,31,'現代思想史','Contemporary Thought','4',NULL,NULL), (121,7,31,'その他','Others','8',NULL,NULL), (122,7,31,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (123,7,32,'概論','Introduction','0',NULL,NULL), (124,7,32,'総論','General','1',NULL,NULL), (125,7,32,'その他','Others','8',NULL,NULL), (126,7,32,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (127,7,33,'概論','Introduction','0',NULL,NULL), (128,7,33,'古代哲学','Ancient Philosophy','1',NULL,NULL), (129,7,33,'中世哲学','Medieval Philosophy','2',NULL,NULL), (130,7,33,'近代哲学','Modern Philosophy','3',NULL,NULL), (131,7,33,'現代哲学','Contemporary Philosophy','4',NULL,NULL), (132,7,33,'美学','Aesthetics','5',NULL,NULL), (133,7,33,'キリスト教思想','Christian Thought','6',NULL,NULL), (134,7,33,'その他','Others','8',NULL,NULL), (135,7,33,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (136,8,34,'概論','Introduction','0',NULL,NULL), (137,8,34,'心理学研究法','Psychological Research Methods','1',NULL,NULL), (138,8,34,'心理学実験実習','Psychological Laboratory Training','2',NULL,NULL), (139,8,34,'知覚心理学・学習心理学','Psychology of Perception / Learning and behavior','3',NULL,NULL), (140,8,34,'生理心理学・比較心理学','Physiological / Comparative Psychology','4',NULL,NULL), (141,8,34,'教育心理学・発達心理学','Educational / Developmental Psychology','5',NULL,NULL), (142,8,34,'臨床心理学・人格心理学・精神分析学','Clinical / Personality Psychology / Psychoanalysis','6',NULL,NULL), (143,8,34,'社会心理学・産業心理学','Social / Industrial Psychology','7',NULL,NULL), (144,8,34,'その他','Others','8',NULL,NULL), (145,8,34,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (146,9,35,'概論','Introduction','0',NULL,NULL), (147,9,35,'考古学史','A History of Archaeology','1',NULL,NULL), (148,9,35,'考古学の方法と理論','Method and Theory in Archaeology','2',NULL,NULL), (149,9,35,'日本考古学','Archaeology in Japan','3',NULL,NULL), (150,9,35,'外国考古学','Archaeology in Foreign Countries','4',NULL,NULL), (151,9,35,'文化遺産論・文化財行政学','Heritage Management','5',NULL,NULL), (152,9,35,'考古学と関連科学','Archaeometry','6',NULL,NULL), (153,9,35,'考古学実習','Field &amp; Laboratory Work in Archaeology','7',NULL,NULL), (154,9,35,'その他','Others','8',NULL,NULL), (155,9,35,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (156,10,36,'概論','Introduction','0',NULL,NULL), (157,10,36,'古代史','Ancient History','1',NULL,NULL), (158,10,36,'中世史','Medieval History','2',NULL,NULL), (159,10,36,'近世史','Early-modern History','3',NULL,NULL), (160,10,36,'近現代史','Modern History','4',NULL,NULL), (161,10,36,'その他','Others','8',NULL,NULL), (162,10,36,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (163,10,37,'概論','Introduction','0',NULL,NULL), (164,10,37,'東アジア','East Asia','1',NULL,NULL), (165,10,37,'東南アジア','Southeast Asia','2',NULL,NULL), (166,10,37,'南アジア','South Asia','3',NULL,NULL), (167,10,37,'内陸アジア','Inner Asia','4',NULL,NULL), (168,10,37,'西アジア','West Asia','5',NULL,NULL), (169,10,37,'その他','Others','8',NULL,NULL), (170,10,37,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (171,10,38,'概論','Introduction','0',NULL,NULL), (172,10,38,'近代史','Modern History','1',NULL,NULL), (173,10,38,'現代史','Contemporary History','2',NULL,NULL), (174,10,38,'その他','Others','8',NULL,NULL), (175,10,38,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (176,10,39,'概論','Introduction','0',NULL,NULL), (177,10,39,'近代史','Modern History','1',NULL,NULL), (178,10,39,'現代史','Contemporary History','2',NULL,NULL), (179,10,39,'その他','Others','8',NULL,NULL), (180,10,39,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (181,10,40,'概論','Introduction','0',NULL,NULL), (182,10,40,'古代史','Ancient History','1',NULL,NULL), (183,10,40,'中世史','Medieval History','2',NULL,NULL), (184,10,40,'近代史','Modern History','3',NULL,NULL), (185,10,40,'現代史','Contemporary History','4',NULL,NULL), (186,10,40,'その他','Others','8',NULL,NULL), (187,10,40,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (188,10,41,'概論','Introduction','0',NULL,NULL), (189,10,41,'近代史','Modern History','1',NULL,NULL), (190,10,41,'現代史','Contemporary History','2',NULL,NULL), (191,10,41,'その他','Others','8',NULL,NULL), (192,10,41,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (193,10,42,'概論','Introduction','0',NULL,NULL), (194,10,42,'近代史','Modern History','1',NULL,NULL), (195,10,42,'現代史','Contemporary History','2',NULL,NULL), (196,10,42,'その他','Others','8',NULL,NULL), (197,10,42,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (198,10,43,'概論','Introduction','0',NULL,NULL), (199,10,43,'その他','Others','8',NULL,NULL), (200,10,43,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (201,11,44,'概論','Introduction','0',NULL,NULL), (202,11,44,'その他','Others','8',NULL,NULL), (203,11,44,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (204,11,45,'概論','Introduction','0',NULL,NULL), (205,11,45,'その他','Others','8',NULL,NULL), (206,11,45,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (207,11,46,'概論','Introduction','0',NULL,NULL), (208,11,46,'その他','Others','8',NULL,NULL), (209,11,46,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (210,11,47,'概論','Introduction','0',NULL,NULL), (211,11,47,'その他','Others','8',NULL,NULL), (212,11,47,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (213,11,48,'概論','Introduction','0',NULL,NULL), (214,11,48,'その他','Others','8',NULL,NULL), (215,11,48,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (216,11,49,'概論','Introduction','0',NULL,NULL), (217,11,49,'その他','Others','8',NULL,NULL), (218,11,49,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (219,11,50,'概論','Introduction','0',NULL,NULL), (220,11,50,'その他','Others','8',NULL,NULL), (221,11,50,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (222,11,51,'概論','Introduction','0',NULL,NULL), (223,11,51,'その他','Others','8',NULL,NULL), (224,11,51,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (225,11,52,'概論','Introduction','0',NULL,NULL), (226,11,52,'その他','Others','8',NULL,NULL), (227,11,52,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (228,11,53,'概論','Introduction','0',NULL,NULL), (229,11,53,'その他','Others','8',NULL,NULL), (230,11,53,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (231,11,54,'概論','Introduction','0',NULL,NULL), (232,11,54,'その他','Others','8',NULL,NULL), (233,11,54,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (234,11,55,'概論','Introduction','0',NULL,NULL), (235,11,55,'その他','Others','8',NULL,NULL), (236,11,55,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (237,12,56,'地理学','Geography','0',NULL,NULL), (238,12,56,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (239,13,57,'政治学','Political Science','0',NULL,NULL), (240,13,57,'現代政治/政治過程','Contemporary Politics/Political Process','1',NULL,NULL), (241,13,57,'政治思想','Political Thoughts','2',NULL,NULL), (242,13,57,'比較政治','Comparative Politics','3',NULL,NULL), (243,13,57,'国際政治','International Politics','4',NULL,NULL), (244,13,57,'公共政策/行政学','Public Policy/Public Administration','5',NULL,NULL), (245,13,57,'歴史','Political History','6',NULL,NULL), (246,13,57,'制度/システム','Poitical Institutions/Political System','7',NULL,NULL), (247,13,57,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (248,14,58,'概論','Introduction','0',NULL,NULL), (249,14,58,'国際関係史','International History','1',NULL,NULL), (250,14,58,'国際安全保障','International Security','2',NULL,NULL), (251,14,58,'国際政治経済学','International Political Economy','3',NULL,NULL), (252,14,58,'国際機構論','International Organizations','4',NULL,NULL), (253,14,58,'国際社会学','Global Sociology','5',NULL,NULL), (254,14,58,'トランスナショナル研究','Transnational Studies','6',NULL,NULL), (255,14,58,'外交政策論','Foreign Policy Studies','7',NULL,NULL), (256,14,58,'その他','Others','8',NULL,NULL), (257,14,58,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (258,14,59,'概論','Introduction','0',NULL,NULL), (259,14,59,'地域統合研究','Regional Integration Studies','1',NULL,NULL), (260,14,59,'平和研究','Peace Studies','2',NULL,NULL), (261,14,59,'開発研究','Development Studies','3',NULL,NULL), (262,14,59,'国際人権論','International Human Rights','4',NULL,NULL), (263,14,59,'人間の安全保障','Human Security','5',NULL,NULL), (264,14,59,'グローバル・ガバナンス','Global Governance','6',NULL,NULL), (265,14,59,'国際コミュニケーション研究','International Communications Studies','7',NULL,NULL), (266,14,59,'その他','Others','8',NULL,NULL), (267,14,59,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (268,15,60,'公法概論','Introduction to Public Law','0',NULL,NULL), (269,15,60,'憲法','Constitutional Law','1',NULL,NULL), (270,15,60,'行政法','Administrative Law','2',NULL,NULL), (271,15,60,'その他','Others','8',NULL,NULL), (272,15,60,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (273,15,61,'民事法概論','Introduction to Civil Law and Procedure','0',NULL,NULL), (274,15,61,'民法','Civil Law','1',NULL,NULL), (275,15,61,'商法','Commercial Law','2',NULL,NULL), (276,15,61,'民事手続法','Law of Civil Procedure','3',NULL,NULL), (277,15,61,'その他','Others','8',NULL,NULL), (278,15,61,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (279,15,62,'刑事法概論','Introduction to Laws on Criminal Matters','0',NULL,NULL), (280,15,62,'刑法','Criminal Law','1',NULL,NULL), (281,15,62,'刑事政策','Criminal Policy','2',NULL,NULL), (282,15,62,'刑事訴訟法','Law of Criminal Procedure','3',NULL,NULL), (283,15,62,'その他','Others','8',NULL,NULL), (284,15,62,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (285,15,63,'基礎法概論','Introduction to Basic Legal Sciences','0',NULL,NULL), (286,15,63,'外国法','Foreign Law','1',NULL,NULL), (287,15,63,'法制史','Legal History','2',NULL,NULL), (288,15,63,'法哲学','Philosophy of Law','3',NULL,NULL), (289,15,63,'法社会学','Sociology of Law','4',NULL,NULL), (290,15,63,'その他','Others','8',NULL,NULL), (291,15,63,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (292,15,64,'国際法概論','Introduction to International Law','0',NULL,NULL), (293,15,64,'国際公法','Public International Law','1',NULL,NULL), (294,15,64,'国際私法','Private International Law','2',NULL,NULL), (295,15,64,'その他','Others','8',NULL,NULL), (296,15,64,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (297,15,65,'社会法概論','Introduction to Social Law','0',NULL,NULL), (298,15,65,'労働法','Labor and Employment Law','1',NULL,NULL), (299,15,65,'社会保障法','Social Security Law','2',NULL,NULL), (300,15,65,'ジェンダー法','Gender and Law','3',NULL,NULL), (301,15,65,'その他','Others','8',NULL,NULL), (302,15,65,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (303,15,66,'新領域法学概論','Introduction to New Fields of Law','0',NULL,NULL), (304,15,66,'環境法','Environmental Law','1',NULL,NULL), (305,15,66,'知的財産法','Intellectual Property Law','2',NULL,NULL), (306,15,66,'経済法','Economic Law','3',NULL,NULL), (307,15,66,'租税法','Tax Law','4',NULL,NULL), (308,15,66,'医事法','Health Law/Medical Law','5',NULL,NULL), (309,15,66,'その他','Others','8',NULL,NULL), (310,15,66,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (311,15,67,'概論','Introduction to Law','0',NULL,NULL), (312,15,67,'その他','Others','8',NULL,NULL), (313,15,67,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (314,16,68,'応用経済学','Applied Economics','0',NULL,NULL), (315,16,68,'国際経済学・開発経済学','International Economics / Development Economics','1',NULL,NULL), (316,16,68,'金融論・ファイナンス','Money and Banking / Finance','2',NULL,NULL), (317,16,68,'財政学・公共経済学・経済政策','Public Finance / Public Economics / Economic Policy','3',NULL,NULL), (318,16,68,'労働経済学・医療経済学・教育経済学','Labor Economics / Health Economics / Education Economics','4',NULL,NULL), (319,16,68,'産業組織論・法と経済学','Industrial Organization / Law and Economics','5',NULL,NULL), (320,16,68,'農業経済学・環境経済学・資源経済学','Agricultural Economics / Environment Economics/Resource Economics','6',NULL,NULL), (321,16,68,'都市経済学・地域経済学','Urban Economics / Regional Economics','7',NULL,NULL), (322,16,68,'政治経済学','Political Economy','8',NULL,NULL), (323,16,68,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (324,16,69,'経済学一般','Economics in General','0',NULL,NULL), (325,16,69,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (326,16,70,'経済史','Economic History','0',NULL,NULL), (327,16,70,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (328,16,71,'理論・計量経済学','Theoretical Economics / Econometrics','0',NULL,NULL), (329,16,71,'理論経済学・経済思想','Theoretical Economics / Economic Thought','1',NULL,NULL), (330,16,71,'経済統計','Economic Statistics','2',NULL,NULL), (331,16,71,'実験経済学 / 行動経済学','Experimental Economics / Behavioral Economics','3',NULL,NULL), (332,16,71,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (333,17,72,'企業財務','Corporate Finance','0',NULL,NULL), (334,17,72,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (335,17,73,'国際ビジネス・貿易','International Business and Trade','0',NULL,NULL), (336,17,73,'国際マーケティングマネジメント','International Marketing Management','1',NULL,NULL), (337,17,73,'ダイバシティマネジメント','Diversity Management','2',NULL,NULL), (338,17,73,'国際商務/貿易商務','International Commercial/Trade Transactions','3',NULL,NULL), (339,17,73,'貿易慣習','International Trade Usages','4',NULL,NULL), (340,17,73,'貿易論','International Trade','5',NULL,NULL), (341,17,73,'貿易政策','International Trade Policy','6',NULL,NULL), (342,17,73,'多国籍企業','Multinational Corporation','7',NULL,NULL), (343,17,73,'その他','Others','8',NULL,NULL), (344,17,73,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (345,17,74,'マーケティング','Marketing','0',NULL,NULL), (346,17,74,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (347,17,75,'概論','Introduction','0',NULL,NULL), (348,17,75,'保険論','Insurance','1',NULL,NULL), (349,17,75,'リスクマネジメント','Risk Management','2',NULL,NULL), (350,17,75,'保険制度','Insurance System','3',NULL,NULL), (351,17,75,'社会保険','Social Insurance','4',NULL,NULL), (352,17,75,'その他','Others','8',NULL,NULL), (353,17,75,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (354,18,76,'概論','Introducion to management','0',NULL,NULL), (355,18,76,'経営組織','Organization Theory','1',NULL,NULL), (356,18,76,'人的資源管理','Human Resource Management','2',NULL,NULL), (357,18,76,'経営戦略','Strategic Management','3',NULL,NULL), (358,18,76,'国際経営','International Management','4',NULL,NULL), (359,18,76,'アントレプレナーシップ','Entrepreneurship','5',NULL,NULL), (360,18,76,'技術経営','Management of Technology','6',NULL,NULL), (361,18,76,'その他','Others','8',NULL,NULL), (362,18,76,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (363,19,77,'会計学','Introduction to Accounting','0',NULL,NULL), (364,19,77,'財務会計','Financial Accounting','1',NULL,NULL), (365,19,77,'管理会計','Management Accounting','2',NULL,NULL), (366,19,77,'監査','Auditing','3',NULL,NULL), (367,19,77,'会計情報','Accounting Information','4',NULL,NULL), (368,19,77,'その他','Others','8',NULL,NULL), (369,19,77,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (370,20,78,'統計学','Statistics','0',NULL,NULL), (371,20,78,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (372,21,79,'概論','Introduction','0',NULL,NULL), (373,21,79,'社会学理論・社会学史・社会学方法論','Sociological Theory/History of Sociology/Methodology of Sociology','1',NULL,NULL), (374,21,79,'社会調査法','Social Research','2',NULL,NULL), (375,21,79,'家族・人口','Family/Population','3',NULL,NULL), (376,21,79,'地域社会・村落・都市','Regional Society/Rural Society/Urban Society','4',NULL,NULL), (377,21,79,'産業・労働','Industry/Labor','5',NULL,NULL), (378,21,79,'文化・宗教・社会意識','Culture/Religion/Social Consciousness','6',NULL,NULL), (379,21,79,'社会問題・社会運動','Social Problem/Social Movement','7',NULL,NULL), (380,21,79,'その他','Others','8',NULL,NULL), (381,21,79,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (382,22,80,'社会・安全システム科学','Social Systems Engineering/Safety System','0',NULL,NULL), (383,22,80,'自然災害科学・防災学','Natural Disaster Prevention Science','1',NULL,NULL), (384,22,80,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (385,23,81,'ジェンダー','Gender','0',NULL,NULL), (386,23,81,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (387,24,82,'教育学','Education','0',NULL,NULL), (388,24,82,'教科教育学','Education on School Subjects and Activities','1',NULL,NULL), (389,24,82,'その他','Others','8',NULL,NULL), (390,24,82,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (391,25,83,'子ども学','Childhood Science','0',NULL,NULL), (392,25,83,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (393,26,84,'概論','Introduction','0',NULL,NULL), (394,26,84,'その他','Others','8',NULL,NULL), (395,26,84,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (396,26,85,'概論','Introduction','0',NULL,NULL), (397,26,85,'その他','Others','8',NULL,NULL), (398,26,85,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (399,26,86,'概論','Introduction','0',NULL,NULL), (400,26,86,'その他','Others','8',NULL,NULL), (401,26,86,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (402,26,87,'概論','Introduction','0',NULL,NULL), (403,26,87,'その他','Others','8',NULL,NULL), (404,26,87,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (405,27,88,'数学','Mathematics','0',NULL,NULL), (406,27,88,'代数学','Algebra','1',NULL,NULL), (407,27,88,'幾何学','Geometry','2',NULL,NULL), (408,27,88,'解析学','Analysis','3',NULL,NULL), (409,27,88,'確率論・統計学','Probability Theory/ Statistics','4',NULL,NULL), (410,27,88,'応用数学','Applied Mathematics','5',NULL,NULL), (411,27,88,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (412,28,89,'計算科学','Computational Science','0',NULL,NULL), (413,28,89,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (414,29,90,'応用物理学','Applied Physics','0',NULL,NULL), (415,29,90,'光学','Optics','1',NULL,NULL), (416,29,90,'物理工学','Engineering Physics','2',NULL,NULL), (417,29,90,'情報工学','Information Engineering','3',NULL,NULL), (418,29,90,'計測工学','Instrumentation Engineering','4',NULL,NULL), (419,29,90,'原子力工学','Nuclear Engineering','5',NULL,NULL), (420,29,90,'量子ビーム科学','Quantum beam science','6',NULL,NULL), (421,29,90,'プラズマ科学','Plasma science','7',NULL,NULL), (422,29,90,'地球物理学','Geophysics','8',NULL,NULL), (423,29,90,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (424,29,91,'基礎物理学','Basic Physics','0',NULL,NULL), (425,29,91,'力学','Mechanics','1',NULL,NULL), (426,29,91,'電磁気学','Electromagnetism','2',NULL,NULL), (427,29,91,'熱・統計力学','Thermodynamics and Statistical Mechanics','3',NULL,NULL), (428,29,91,'量子力学','Quantum Mechanics','4',NULL,NULL), (429,29,91,'物理数学','Mathematics for Physics','5',NULL,NULL), (430,29,91,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (431,29,92,'物理学','Physics','0',NULL,NULL), (432,29,92,'量子物理学','Quantum Physics','1',NULL,NULL), (433,29,92,'数理物理学','Mathematical Physics','2',NULL,NULL), (434,29,92,'宇宙物理学','Astrophysics &amp; Cosmology','3',NULL,NULL), (435,29,92,'統計物理学','Statistical Physics','4',NULL,NULL), (436,29,92,'原子核・素粒子物理学','Nuclear and Particle Physics','5',NULL,NULL), (437,29,92,'原子分子物理学','Atomic and Molecular Physics','6',NULL,NULL), (438,29,92,'凝縮系物理学','Condensed Matter Physics','7',NULL,NULL), (439,29,92,'生物物理学','Biophysics','8',NULL,NULL), (440,29,92,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (441,30,93,'応用化学','Applied Chemistry','0',NULL,NULL), (442,30,93,'分析化学','Analytical Chemistry','1',NULL,NULL), (443,30,93,'生体関連化学','Bio-Related Chemistry','2',NULL,NULL), (444,30,93,'エネルギー関連化学','Energy-Related Chemistry','3',NULL,NULL), (445,30,93,'機能物性化学','Functional Solid State Chemistry','4',NULL,NULL), (446,30,93,'グリーン・環境化学','Green/Environmental Chemistry','5',NULL,NULL), (447,30,93,'高分子化学','Polymer Chemistry','6',NULL,NULL), (448,30,93,'合成化学','Synthetic Chemistry','7',NULL,NULL), (449,30,93,'生体分子化学','Biomolecular Chemistry','8',NULL,NULL), (450,30,93,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (451,30,94,'化学共通','Chemistry','0',NULL,NULL), (452,30,94,'無機化学','Inorganic Chemistry','1',NULL,NULL), (453,30,94,'有機化学','Organic Chemistry','2',NULL,NULL), (454,30,94,'物理化学','Physical Chemistry','3',NULL,NULL), (455,30,94,'ケミカルバイオロジー','Chemical Biology','4',NULL,NULL), (456,30,94,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (457,30,95,'材料化学','Materials Chemistry','0',NULL,NULL), (458,30,95,'デバイス関連化学','Device Related Chemistry','1',NULL,NULL), (459,30,95,'無機工業材料','Inorganic Industrial Materials','2',NULL,NULL), (460,30,95,'有機・ハイブリッド材料','Organic and Hybrid Materials','3',NULL,NULL), (461,30,95,'高分子・繊維材料','Polymer/Textile Materials','4',NULL,NULL), (462,30,95,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (463,31,96,'天文学','Astronomy','0',NULL,NULL), (464,31,96,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (465,32,97,'地球惑星科学','Earth and Planetary Science','0',NULL,NULL), (466,32,97,'地球宇宙化学','Geochemistry/Cosmochemistry','1',NULL,NULL), (467,32,97,'地質学','Geology','2',NULL,NULL), (468,32,97,'気象・海洋物理・陸水学','Meteorology/Physical Oceanography/Hydrology','3',NULL,NULL), (469,32,97,'岩石・鉱物・鉱床学','Petrology/Mineralogy/Economic Geology','4',NULL,NULL), (470,32,97,'固体地球惑星物理学','Solid Earth and Planetary Physics','5',NULL,NULL), (471,32,97,'超高層物理学','Speace and Upper Atmospheric Physics','6',NULL,NULL), (472,32,97,'層位・古生物学','Stratigraphy/Paleontology','7',NULL,NULL), (473,32,97,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (474,33,98,'生物学','Biology','0',NULL,NULL), (475,33,98,'進化生物学','Evolutionary Biology','1',NULL,NULL), (476,33,98,'分子生物学','Molecular biology','2',NULL,NULL), (477,33,98,'生化学','Biochemistry','3',NULL,NULL), (478,33,98,'細胞生物学','Cell biology','4',NULL,NULL), (479,33,98,'動物生理学','Animal physiology','5',NULL,NULL), (480,33,98,'植物生理学','Plant physiology','6',NULL,NULL), (481,33,98,'発生生物学','Developmental biolgy','7',NULL,NULL), (482,33,98,'生態学','Ecology','8',NULL,NULL), (483,33,98,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (484,34,99,'ゲノム科学','Genome Science','0',NULL,NULL), (485,34,99,'ゲノム生物学','Genome Biology','1',NULL,NULL), (486,34,99,'ゲノム医科学','Medical Genome Science','2',NULL,NULL), (487,34,99,'システムゲノム科学','System Genome Science','3',NULL,NULL), (488,34,99,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (489,35,100,'社会医学','Social Medicine','0',NULL,NULL), (490,35,100,'医療社会学','Medical Sociology','1',NULL,NULL), (491,35,100,'衛生学・公衆衛生学','Hygiene and public health','2',NULL,NULL), (492,35,100,'法医学','Legal Medicine','3',NULL,NULL), (493,35,100,'病院・医療管理学','Medical and Hospital Managemen','4',NULL,NULL), (494,35,100,'健康人口学','Health Demography','5',NULL,NULL), (495,35,100,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (496,35,101,'細菌学(含真菌学)','Bacteriology(including Mycology)','0',NULL,NULL), (497,35,101,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (498,35,102,'臨床医学','Clinical Medicine','0',NULL,NULL), (499,35,102,'麻酔科学','Anesthesiology','1',NULL,NULL), (500,35,102,'救急医学','Emergency Medicine','2',NULL,NULL), (501,35,102,'産婦人科学','Obstetrics and Gynecology','3',NULL,NULL), (502,35,102,'眼科学','Ophthalmology','4',NULL,NULL), (503,35,102,'耳鼻咽喉科学','Otorhinolaryngology','5',NULL,NULL), (504,35,102,'泌尿器科学','Urology','6',NULL,NULL), (505,35,102,'皮膚科学','Dermatology','7',NULL,NULL), (506,35,102,'小児科学','Pediatrics','8',NULL,NULL), (507,35,102,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (508,35,103,'精神神経科学','Psychiatric Science','0',NULL,NULL), (509,35,103,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (510,35,104,'環境生理学(含体力医学・栄養生理学)','Evnvironmental Physiology(including Physical Medicine and Nutritional Physiology)','0',NULL,NULL), (511,35,104,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (512,35,105,'免疫学','Immunology','0',NULL,NULL), (513,35,105,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (514,35,106,'医学一般','General Medicine','0',NULL,NULL), (515,35,106,'解剖学一般(含組織学・発生学)','General Anatomy (including Histology/Embryology)','1',NULL,NULL), (516,35,106,'医化学一般','General Medical Chemistry','2',NULL,NULL), (517,35,106,'薬理学一般','General Pharmacology','3',NULL,NULL), (518,35,106,'生理学一般','General Physiology','4',NULL,NULL), (519,35,106,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (520,35,107,'人類遺伝学','Human Genetics','0',NULL,NULL), (521,35,107,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (522,35,108,'内科学','Internal Medicine','0',NULL,NULL), (523,35,108,'循環器内科学','Cardiovascular Medicine','1',NULL,NULL), (524,35,108,'膠原病・アレルギー内科学','Collagenous Pathology/Allergology','2',NULL,NULL), (525,35,108,'消化器内科学','Gastroenterology','3',NULL,NULL), (526,35,108,'血液内科学','Hematology','4',NULL,NULL), (527,35,108,'感染症内科学','Infectious Disease Medicine','5',NULL,NULL), (528,35,108,'腎臓内科学','Kidney Internal Medicine','6',NULL,NULL), (529,35,108,'神経内科学','Neurology','7',NULL,NULL), (530,35,108,'呼吸器内科学','Respiratory Organ Intermal Medicine','8',NULL,NULL), (531,35,108,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (532,35,109,'病態医化学','Pathological Medical Chemistry','0',NULL,NULL), (533,35,109,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (534,35,110,'応用薬理学','Applied Pharmacology','0',NULL,NULL), (535,35,110,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (536,35,111,'病態検査学','Laboratory Medicine','0',NULL,NULL), (537,35,111,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (538,35,112,'医学物理学・放射線技術学','Medical Physics and Radiation Technology','0',NULL,NULL), (539,35,112,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (540,35,113,'疼痛学','Pain Science','0',NULL,NULL), (541,35,113,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (542,35,114,'腫瘍学','Oncology','0',NULL,NULL), (543,35,114,'腫瘍生物学','Tumor Biology','1',NULL,NULL), (544,35,114,'腫瘍診断学','Tumor Diagnostics','2',NULL,NULL), (545,35,114,'腫瘍治療学','Tumor Therapeutics','3',NULL,NULL), (546,35,114,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (547,35,115,'病理学','Pathology','0',NULL,NULL), (548,35,115,'実験病理学','Experimental Pathology','1',NULL,NULL), (549,35,115,'人体病理学','Human Pathology','2',NULL,NULL), (550,35,115,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (551,35,116,'代謝学','Metabolomics','0',NULL,NULL), (552,35,116,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (553,35,117,'放射線科学','Radiation Science','0',NULL,NULL), (554,35,117,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (555,35,118,'外科学','Surgery','0',NULL,NULL), (556,35,118,'心臓血管外科学','Cardiovascular Surgery','1',NULL,NULL), (557,35,118,'消化器外科学','Digestive Surgery','2',NULL,NULL), (558,35,118,'脳神経外科学','Neurosurgery','3',NULL,NULL), (559,35,118,'整形外科学','Orthopaedic Surgery','4',NULL,NULL), (560,35,118,'小児外科学','Pediatric Surgery','5',NULL,NULL), (561,35,118,'形成外科学','Plastic Surgery','6',NULL,NULL), (562,35,118,'呼吸器外科学','Respiratory Surgery','7',NULL,NULL), (563,35,118,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (564,35,119,'疫学・予防医学','Epidemiology and Preventive Medicine','0',NULL,NULL), (565,35,119,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (566,35,120,'内分泌学','Endocrinology','0',NULL,NULL), (567,35,120,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (568,35,121,'ウイルス学','Virology','0',NULL,NULL), (569,35,121,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (570,35,122,'胎児・新生児医学','Embryonic/Neonatal Medicine','0',NULL,NULL), (571,35,122,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (572,35,123,'寄生虫学(含衛生動物学)','Parasitology(including Sanitary Zoology)','0',NULL,NULL), (573,35,123,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (574,36,124,'脳科学','Brain Sciences','0',NULL,NULL), (575,36,124,'基盤・社会脳科学','Basic/Social Brain Science','1',NULL,NULL), (576,36,124,'脳計測科学','Brain Biometrics','2',NULL,NULL), (577,36,124,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (578,37,125,'看護学','Nursing','0',NULL,NULL), (579,37,125,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (580,38,126,'薬学','Pharmacy','0',NULL,NULL), (581,38,126,'生物系薬学','Biological Pharmacy','1',NULL,NULL), (582,38,126,'化学系薬学','Chemical Pharmacy','2',NULL,NULL), (583,38,126,'創薬化学','Drug Development Chemistry','3',NULL,NULL), (584,38,126,'環境・衛生系薬学','Environmental and Hygienic Pharmacy','4',NULL,NULL), (585,38,126,'医療系薬学','Medical Pharmacy','5',NULL,NULL), (586,38,126,'天然資源系薬学','Natural Medicines','6',NULL,NULL), (587,38,126,'薬理系薬学','Pharmacology in Pharmacy','7',NULL,NULL), (588,38,126,'物理系薬学','Physical Pharmacy','8',NULL,NULL), (589,38,126,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (590,39,127,'ナノ・マイクロ科学','Nano/Micro Science','0',NULL,NULL), (591,39,127,'ナノマイクロシステム','Nano/Microsystems','1',NULL,NULL), (592,39,127,'ナノバイオサイエンス','Nanobioscience','2',NULL,NULL), (593,39,127,'ナノ材料化学','Nanomaterials Chemistry','3',NULL,NULL), (594,39,127,'ナノ材料工学','Nanomaterials Engineering','4',NULL,NULL), (595,39,127,'ナノ構造化学','Nanostructural Chemistry','5',NULL,NULL), (596,39,127,'ナノ構造物理','Nanostructural Physics','6',NULL,NULL), (597,39,127,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (598,40,128,'土木工学','Civil Engineering','0',NULL,NULL), (599,40,128,'土木環境システム','Civi and Environmental Engineering','1',NULL,NULL), (600,40,128,'土木材料・施工・建設マネジメント','Civi engineering Materials/Construction/Construction Management','2',NULL,NULL), (601,40,128,'土木計画学・交通工学','Civil Engineering Project/Traffic Engineering','3',NULL,NULL), (602,40,128,'地盤工学','Geotechnical Engineering','4',NULL,NULL), (603,40,128,'水工学','Hydaulic Engineering','5',NULL,NULL), (604,40,128,'構造工学・地震工学・維持管理工学','Structural Engineering/Earthquake Engineering/Maintenance Management Engineering','6',NULL,NULL), (605,40,128,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (606,41,129,'環境学および持続可能性','Environmental Science and Sustainability','0',NULL,NULL), (607,41,129,'持続可能システム','Design and Evaluation of Sustainable and Environmental Conscious Ayatem','1',NULL,NULL), (608,41,129,'自然共生システム','Environmental and Ecological Symbiosis','2',NULL,NULL), (609,41,129,'環境材料・リサイクル','Environmental Cinscious Material and Recycle','3',NULL,NULL), (610,41,129,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (611,41,130,'その他 環境学','Environmental Science','0',NULL,NULL), (612,41,130,'環境リスク制御・評価','Enviromental Risk Control and Evaluation','1',NULL,NULL), (613,41,130,'環境動態解析','Environmental Dynamic Analysis','2',NULL,NULL), (614,41,130,'環境技術・環境負荷低減','Environmental Engineering and Reduction of Environmental Burden','3',NULL,NULL), (615,41,130,'環境影響評価','Environmental Impact Assessment','4',NULL,NULL), (616,41,130,'環境政策・環境社会システム','Environmental Policy and Social Systems','5',NULL,NULL), (617,41,130,'環境モデリング・保全修復技術','Modeling and Technoligies for Environmental Conservation and Remediation','6',NULL,NULL), (618,41,130,'放射線・化学物質影響科学','Risk Sciences of Radiation and Chemicals','7',NULL,NULL), (619,41,130,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (620,42,131,'建築学','Architecural Design &amp; Engineering','0',NULL,NULL), (621,42,131,'建築芸術','Architectural Art and Design','1',NULL,NULL), (622,42,131,'建築工学','Architectural Engineering','2',NULL,NULL), (623,42,131,'建築史','History of Architecture','3',NULL,NULL), (624,42,131,'建築計画','Architectural Design and Planning','4',NULL,NULL), (625,42,131,'都市計画','Urban Design','5',NULL,NULL), (626,42,131,'建築構造','Structural Design and Mechanics','6',NULL,NULL), (627,42,131,'建築環境設備','Architectural Environment Engineering','7',NULL,NULL), (628,42,131,'建築生産','Building Engineering','8',NULL,NULL), (629,42,131,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (630,43,132,'科学技術論','Science and Technology Studies','0',NULL,NULL), (631,43,132,'科学哲学・科学基礎論','Philosophy of Science/Theory of Science','1',NULL,NULL), (632,43,132,'科学史・技術史','History of Science/Technology','2',NULL,NULL), (633,43,132,'科学社会学','Sociology of Science','3',NULL,NULL), (634,43,132,'科学技術倫理','Science and Engineering Ethics','4',NULL,NULL), (635,43,132,'科学技術政策','Science and Technology Policy','5',NULL,NULL), (636,43,132,'科学技術社会論','Science, Technology and Society','6',NULL,NULL), (637,43,132,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (638,44,133,'機械工学','Mechanical Engineering','0',NULL,NULL), (639,44,133,'設計工学・機械機能要素・トライボロジー','Design Engineering/Machine Functional Elements/Tribology','1',NULL,NULL), (640,44,133,'機械力学','Dynamics','2',NULL,NULL), (641,44,133,'流体工学','Fluid Engineering','3',NULL,NULL), (642,44,133,'機械材料・材料力学','Materials/Mechanics of Mmaterials','4',NULL,NULL), (643,44,133,'知能機械学・機械システム','Mechanical Systems','5',NULL,NULL), (644,44,133,'生産工学・加工学','Production studies','6',NULL,NULL), (645,44,133,'熱工学','Thermal Engineering','7',NULL,NULL), (646,44,133,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (647,45,134,'電気電子工学','Electrical and Electronic Engineering','0',NULL,NULL), (648,45,134,'通信・ネットワーク工学','Commumication/Network Engineering','1',NULL,NULL), (649,45,134,'電子デバイス・電子機器','Electron device/Electronic Equipment','2',NULL,NULL), (650,45,134,'電子・電気材料工学','Electronic Materials/Electric Materials/Electric Materials','3',NULL,NULL), (651,45,134,'計測工学','Measurement Engineering','4',NULL,NULL), (652,45,134,'電力工学・電力変換・電気機器','Power Engineering/Power Conversion/Electric Machinery','5',NULL,NULL), (653,45,134,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (654,46,135,'経営システム工学・制御システム工学','Industrial and Management System Engineering/Control engineering','0',NULL,NULL), (655,46,135,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (656,46,136,'制御・システム工学','Control Engineering/System Engineering','0',NULL,NULL), (657,46,136,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (658,47,137,'材料工学','Materials Engineering','0',NULL,NULL), (659,47,137,'複合材料・表界面工学','Composite Materials/Surface and Interface Engineering','1',NULL,NULL), (660,47,137,'無機材料・物性','Inorganic Materials/Physical Propertoes','2',NULL,NULL), (661,47,137,'材料加工・組織制御工学','Material Processing/Misrostructural Control Engineering','3',NULL,NULL), (662,47,137,'金属・資源生産工学','Metal Making/Resorce Production Engineering','4',NULL,NULL), (663,47,137,'金属物性・材料','Physical Properties of Metals/Metal-Base Materials','5',NULL,NULL), (664,47,137,'構造・機能材料','Structural/Functional Materials','6',NULL,NULL), (665,47,137,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (666,48,138,'プロセス・化学工学','Process/Chemical Engineering','0',NULL,NULL), (667,48,138,'生物機能・バイオプロセス','Biofunction/Bioprocess','1',NULL,NULL), (668,48,138,'触媒・資源化学プロセス','Catalyst/Resource Chemical Process','2',NULL,NULL), (669,48,138,'加工物・移動操作・単位操作','Properties in Chemical Engineering Process/Transfer Operation/Unit Operation','3',NULL,NULL), (670,48,138,'反応工学・プロセスシステム','Reaction Engineering/Process System','4',NULL,NULL), (671,48,138,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (672,49,139,'経営工学','General Industrial Engineering','0',NULL,NULL), (673,49,139,'生産・物流システム工学','Manufacturing and Logistics Systems Engineering','1',NULL,NULL), (674,49,139,'施設・設備管理','Facility Management','2',NULL,NULL), (675,49,139,'マーケティング工学・製品サービス開発工学','Marketing Engineering, Product/Service Development','3',NULL,NULL), (676,49,139,'品質管理','Quality Management','4',NULL,NULL), (677,49,139,'経営情報システム','Management Information Systems','5',NULL,NULL), (678,49,139,'数理工学(含OR,確率・統計)','Mathematical Engineering: Operations Research, Statistics','6',NULL,NULL), (679,49,139,'人間工学・組織/人材マネジメント','Human Factors Engineering, Organization and Human Resource Management','7',NULL,NULL), (680,49,139,'事業経営(含技術経営,経済性工学)','Business Management: Technology Management, Engineering Economy','8',NULL,NULL), (681,49,139,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (682,50,140,'実体情報学','Embodiment Informatics','0',NULL,NULL), (683,50,140,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (684,50,141,'総合工学','Integrated Engineering','0',NULL,NULL), (685,50,141,'エネルギー学','Energy Engineering','1',NULL,NULL), (686,50,141,'地球・資源システム工学','Earth System and Resources Engineering','2',NULL,NULL), (687,50,141,'航空宇宙工学','Aerospace Engineering','3',NULL,NULL), (688,50,141,'船舶海洋工学','Naval and Maritime Engineering','4',NULL,NULL), (689,50,141,'原子力工学','Nuclear Engineering','5',NULL,NULL), (690,50,141,'核融合学','Nuclear Fusion Studies','6',NULL,NULL), (691,50,141,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (692,51,142,'人間科学基幹','Core of Human Sciences','0',NULL,NULL), (693,51,142,'人間科学基礎','Basics of Human Sciences','1',NULL,NULL), (694,51,142,'人間科学教養','Liberal Arts in Human Sciences','2',NULL,NULL), (695,51,142,'人間科学データリテラシー','Data Literacy of Human Sciences','3',NULL,NULL), (696,51,142,'実験調査研究法','Experimental and Survey Research Methods','4',NULL,NULL), (697,51,142,'その他','Others','8',NULL,NULL), (698,51,142,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (699,51,143,'環境科学','Environmental Sciences','0',NULL,NULL), (700,51,143,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (701,51,144,'社会環境','Social Environment','0',NULL,NULL), (702,51,144,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (703,51,145,'人類文化・歴史','Culture and History of Humankind','0',NULL,NULL), (704,51,145,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (705,51,146,'環境デザイン・行動心理','Environmental Design and Psychology of Behavior','0',NULL,NULL), (706,51,146,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (707,51,147,'健康・生命医科学','Health and Biomedical Sciences','0',NULL,NULL), (708,51,147,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (709,51,148,'医工人間学','Medicine, Engineering and Humanity','0',NULL,NULL), (710,51,148,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (711,51,149,'保健福祉学','Health and Social Welfare','0',NULL,NULL), (712,51,149,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (713,51,150,'臨床心理行動科学','Clinical Psychology and Behavioral Science','0',NULL,NULL), (714,51,150,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (715,51,151,'人間情報工学','Human Informatics and Ergonomics','0',NULL,NULL), (716,51,151,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (717,51,152,'教育コミュニケーション','Education and Communication','0',NULL,NULL), (718,51,152,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (719,52,153,'家政学','Home Economics','0',NULL,NULL), (720,52,153,'衣・住生活学','Clothing Life/Dwelling Life','1',NULL,NULL), (721,52,153,'生活科学','Life Science','2',NULL,NULL), (722,52,153,'食生活学','Eating Habits','3',NULL,NULL), (723,52,153,'育児','Child Care','4',NULL,NULL), (724,52,153,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (725,53,154,'水圏','Aquatic','0',NULL,NULL), (726,53,154,'水圏生産科学','Aquatic Bioproduction Science','1',NULL,NULL), (727,53,154,'水圏生命科学','Aquatic Life Science','2',NULL,NULL), (728,53,154,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (729,53,155,'応用生物学','Applied Biology','0',NULL,NULL), (730,53,155,'遺伝育種科学','Science in Genetics and Breeding','1',NULL,NULL), (731,53,155,'応用生物化学','Applied Biochemistry','2',NULL,NULL), (732,53,155,'応用微生物学','Applied Microbiology','3',NULL,NULL), (733,53,155,'応用分子細胞生物学','Applied Molecular and cellular biology','4',NULL,NULL), (734,53,155,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (735,53,156,'環境農学','Environmental Agricultura','0',NULL,NULL), (736,53,156,'環境農学(含ランドスケープ科学)','Environmental Agricultura(including Landscape Science)','1',NULL,NULL), (737,53,156,'農業環境・情報工学','Agricultural Environmental Engineering/Agriculturalinfomation Engineering','2',NULL,NULL), (738,53,156,'地域環境工学・計画学','Rural Environmental Engineering/Planning','3',NULL,NULL), (739,53,156,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (740,53,157,'植物','Plant','0',NULL,NULL), (741,53,157,'作物生産科学','Crop Production Science','1',NULL,NULL), (742,53,157,'園芸科学','Horticultural Science','2',NULL,NULL), (743,53,157,'植物保護科学','Plant Protection Science','3',NULL,NULL), (744,53,157,'植物栄養学・土壌学','Plant Nutrition/Soil Science','4',NULL,NULL), (745,53,157,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (746,53,158,'社会・経済','Society and Economy','0',NULL,NULL), (747,53,158,'経営・経済農学','Agricultural Science in Management and Economy','1',NULL,NULL), (748,53,158,'社会・開発農学','Agricultural Science in Nural Society and Development','2',NULL,NULL), (749,53,158,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (750,53,159,'農学','Agricultural Sciences','0',NULL,NULL), (751,53,159,'昆虫科学','Insect Science','1',NULL,NULL), (752,53,159,'森林科学','Forest Science','2',NULL,NULL), (753,53,159,'木質科学','Wood Science','3',NULL,NULL), (754,53,159,'動物生産科学','Animal Production Science','4',NULL,NULL), (755,53,159,'統合動物科学','Integrarive Animal Science','5',NULL,NULL), (756,53,159,'獣医学','Veterinary Medical Science','6',NULL,NULL), (757,53,159,'生物有機化学','Bioorganic Chemistry','7',NULL,NULL), (758,53,159,'食品科学','Food Science','8',NULL,NULL), (759,53,159,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (760,54,160,'概論','Introduction to Tourism and Hospitaliy','0',NULL,NULL), (761,54,160,'ツーリズム','Travel and Tourism Management','1',NULL,NULL), (762,54,160,'ホスピタリティ','Hospitality Management','2',NULL,NULL), (763,54,160,'レジャー/リゾート','Leisure and Resort Management','3',NULL,NULL), (764,54,160,'その他','Others','8',NULL,NULL), (765,54,160,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (766,55,161,'概論','Introduction','0',NULL,NULL), (767,55,161,'歴史','History','1',NULL,NULL), (768,55,161,'理論','Theory','2',NULL,NULL), (769,55,161,'表現分析','Expression Analysis','3',NULL,NULL), (770,55,161,'その他','Others','8',NULL,NULL), (771,55,161,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (772,55,162,'概論','Introduction','0',NULL,NULL), (773,55,162,'歴史','History','1',NULL,NULL), (774,55,162,'理論','Theory','2',NULL,NULL), (775,55,162,'表現分析','Expression Analysis','3',NULL,NULL), (776,55,162,'その他','Others','8',NULL,NULL), (777,55,162,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (778,55,163,'概論','Introduction','0',NULL,NULL), (779,55,163,'日本美術史','History of Japanese Art','1',NULL,NULL), (780,55,163,'東洋美術史','History of Oriental Art','2',NULL,NULL), (781,55,163,'西洋美術史','History of Western Art','3',NULL,NULL), (782,55,163,'その他','Others','8',NULL,NULL), (783,55,163,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (784,55,164,'概論','Introduction','0',NULL,NULL), (785,55,164,'芸術/芸能論','Art / Performing Art','1',NULL,NULL), (786,55,164,'思想論','Thought','2',NULL,NULL), (787,55,164,'歴史','History','3',NULL,NULL), (788,55,164,'人類学/民俗学','Anthropology / Folklore','4',NULL,NULL), (789,55,164,'社会学','Sociology','5',NULL,NULL), (790,55,164,'文学','Literature','6',NULL,NULL), (791,55,164,'音楽情報科学','Intermedia Music','7',NULL,NULL), (792,55,164,'その他','Others','8',NULL,NULL), (793,55,164,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (794,55,165,'概論','Introduction','0',NULL,NULL), (795,55,165,'絵画(日本)','Japanese picture','1',NULL,NULL), (796,55,165,'絵画(東洋)','Oriental Picture','2',NULL,NULL), (797,55,165,'絵画(西洋)','Western Picture','3',NULL,NULL), (798,55,165,'絵画(現代)','Contemporary Picture','4',NULL,NULL), (799,55,165,'写真','Photography','5',NULL,NULL), (800,55,165,'版画','Printing','6',NULL,NULL), (801,55,165,'その他','Others','8',NULL,NULL), (802,55,165,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (803,55,166,'概論','Introduction','0',NULL,NULL), (804,55,166,'彫刻(日本)','Japanese Sculpture','1',NULL,NULL), (805,55,166,'彫刻(東洋)','Oriental Sculpture','2',NULL,NULL), (806,55,166,'彫刻(西洋)','Western Sculpture','3',NULL,NULL), (807,55,166,'彫刻/立体(現代)','Contemporary Sculpture','4',NULL,NULL), (808,55,166,'その他','Others','8',NULL,NULL), (809,55,166,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (810,55,167,'概論','Introduction','0',NULL,NULL), (811,55,167,'歴史','History','1',NULL,NULL), (812,55,167,'理論','Theory','2',NULL,NULL), (813,55,167,'表現分析','Expression Analysis','3',NULL,NULL), (814,55,167,'その他','Others','8',NULL,NULL), (815,55,167,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (816,55,168,'概論','Introduction','0',NULL,NULL), (817,55,168,'その他','Others','8',NULL,NULL), (818,55,168,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (819,56,169,'デザイン学','Design Science','0',NULL,NULL), (820,56,169,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (821,57,170,'トレーナー','Athletic Training and Conditioning','0',NULL,NULL), (822,57,170,'アスレティックトレーニング','Athletic Training','1',NULL,NULL), (823,57,170,'コンディショニング','Athletic Conditioning','2',NULL,NULL), (824,57,170,'救急処置','First Aid and CPR','3',NULL,NULL), (825,57,170,'解剖学','Human Anatomy','4',NULL,NULL), (826,57,170,'スポーツ傷害評価','Evaluation of Sports Injury','5',NULL,NULL), (827,57,170,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (828,57,171,'スポーツビジネス','Sport Business','0',NULL,NULL), (829,57,171,'スポーツ経済学','Sport Economics','1',NULL,NULL), (830,57,171,'スポーツ経営学','Sport Management','2',NULL,NULL), (831,57,171,'アドミニストレーション','Sport Administration','3',NULL,NULL), (832,57,171,'スポーツビジネスマネジメント','Sport Business Management','4',NULL,NULL), (833,57,171,'スポーツマーケティング','Sports Marketing','5',NULL,NULL), (834,57,171,'トップスポーツマネジメント','Top Sports Management','6',NULL,NULL), (835,57,171,'スポーツクラブマネジメント','Sport Club Management','7',NULL,NULL), (836,57,171,'スポーツ組織','Sport Organization','8',NULL,NULL), (837,57,171,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (838,57,172,'スポーツ文化','Culture of Sport','0',NULL,NULL), (839,57,172,'スポーツ人類学','Sport Anthropology','1',NULL,NULL), (840,57,172,'スポーツ史','Sports History','2',NULL,NULL), (841,57,172,'武道','Martial Arts','3',NULL,NULL), (842,57,172,'舞踊','Dancing','4',NULL,NULL), (843,57,172,'スポーツ社会学','Sports Sociology','5',NULL,NULL), (844,57,172,'スポーツメディア','Sports Media','6',NULL,NULL), (845,57,172,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (846,57,173,'身体運動科学','Exercise Sciences','0',NULL,NULL), (847,57,173,'運動生理学','Exercise Physiology','1',NULL,NULL), (848,57,173,'生体ダイナミクス','Biodynamics','2',NULL,NULL), (849,57,173,'バイオメカニクス','Biomechanics','3',NULL,NULL), (850,57,173,'スポーツ神経科学','Sports Neuroscience','4',NULL,NULL), (851,57,173,'スポーツ神経生理学','Sports Neurophysiology','5',NULL,NULL), (852,57,173,'スポーツ心理学','Sport Psychology','6',NULL,NULL), (853,57,173,'運動生化学','Exercise Biochemistry','7',NULL,NULL), (854,57,173,'スポーツ栄養学','Sports Nutrition','8',NULL,NULL), (855,57,173,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (856,57,174,'健康スポーツ','Sports and Health Promotion','0',NULL,NULL), (857,57,174,'健康運動疫学','Exercise Epidemiology','1',NULL,NULL), (858,57,174,'健康行動科学','Health and Behavioral Sciences','2',NULL,NULL), (859,57,174,'健康スポーツマネジメント','Management of Health and Fitness Promotion','3',NULL,NULL), (860,57,174,'介護予防','Long-tem Care Prevention','4',NULL,NULL), (861,57,174,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (862,57,175,'スポーツ医科学','Sport Medicine and Science','0',NULL,NULL), (863,57,175,'スポーツ内科学','Sport Internal Medicine','1',NULL,NULL), (864,57,175,'運動免疫学','Exercise Immunology','2',NULL,NULL), (865,57,175,'スポーツ外科学','Sport Surgery','3',NULL,NULL), (866,57,175,'スポーツ整形外科学','Sport Orthopedics','4',NULL,NULL), (867,57,175,'スポーツ精神医科学','Sport Psychiatry','5',NULL,NULL), (868,57,175,'衛生学','Hygiene','6',NULL,NULL), (869,57,175,'予防医学','Preventive Medicine','7',NULL,NULL), (870,57,175,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (871,57,176,'スポーツ教育','Sport/Physical Education','0',NULL,NULL), (872,57,176,'スポーツ教育学','Sport Pedagogy','1',NULL,NULL), (873,57,176,'スポーツ教授学','Sport Didactics','2',NULL,NULL), (874,57,176,'体育科教育学','Pedagogy of Physical Education','3',NULL,NULL), (875,57,176,'保健','Health Education','4',NULL,NULL), (876,57,176,'スポーツ倫理学','Sport Ethics','5',NULL,NULL), (877,57,176,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (878,57,177,'スポーツ科学','Sport Sciences','0',NULL,NULL), (879,57,177,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (880,57,178,'スポーツコーチング','Sports Coaching','0',NULL,NULL), (881,57,178,'スポーツ方法学','Sports Methodology','1',NULL,NULL), (882,57,178,'スポーツ運動学','Qualitative Analysis of Human Movement','2',NULL,NULL), (883,57,178,'チームスポーツコーチング','Team Sports Coaching','3',NULL,NULL), (884,57,178,'トップスポーツコーチング','Top Sports Coaching','4',NULL,NULL), (885,57,178,'エリートコーチング','Elite Coaching','5',NULL,NULL), (886,57,178,'スポーツ技術・戦術','Sports Technique and Stragegy','6',NULL,NULL), (887,57,178,'トレーニング','Sport Training','7',NULL,NULL), (888,57,178,'コーチング心理学','Sport Psychology for Coaching','8',NULL,NULL), (889,57,178,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (890,58,179,'概論','Introduction','0',NULL,NULL), (891,58,179,'その他','Others','8',NULL,NULL), (892,58,179,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (893,58,180,'概論','Introduction','0',NULL,NULL), (894,58,180,'中国語教育','Chinese Education','1',NULL,NULL), (895,58,180,'英語教育','English Education','2',NULL,NULL), (896,58,180,'ドイツ語教育','German Education','3',NULL,NULL), (897,58,180,'フランス語教育','French Education','4',NULL,NULL), (898,58,180,'スペイン語教育','Spanish Education','5',NULL,NULL), (899,58,180,'ロシア語教育','Russian Education','6',NULL,NULL), (900,58,180,'その他','Others','8',NULL,NULL), (901,58,180,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (902,58,181,'概論','Introduction','0',NULL,NULL), (903,58,181,'その他','Others','8',NULL,NULL), (904,58,181,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (905,58,182,'概論','Introduction','0',NULL,NULL), (906,58,182,'その他','Others','8',NULL,NULL), (907,58,182,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (908,58,183,'概論','Introduction','0',NULL,NULL), (909,58,183,'日本語と教育','Japanese and Education','1',NULL,NULL), (910,58,183,'日本語と学習','Japanese and Learning','2',NULL,NULL), (911,58,183,'日本語と社会','Japanese and Society','3',NULL,NULL), (912,58,183,'日本語教育実習','Japanese Educational Practice','4',NULL,NULL), (913,58,183,'その他','Others','8',NULL,NULL), (914,58,183,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (915,58,184,'概論','Introduction','0',NULL,NULL), (916,58,184,'その他','Others','8',NULL,NULL), (917,58,184,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (918,59,185,'中国語','Chinese','0',NULL,NULL), (919,59,185,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (920,59,186,'英語','English','0',NULL,NULL), (921,59,186,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (922,59,187,'フランス語','French','0',NULL,NULL), (923,59,187,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (924,59,188,'ドイツ語','German','0',NULL,NULL), (925,59,188,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (926,59,189,'イタリア語','Italian','0',NULL,NULL), (927,59,189,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (928,59,190,'日本語','Japanese','0',NULL,NULL), (929,59,190,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (930,59,191,'朝鮮語','Korean','0',NULL,NULL), (931,59,191,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (932,59,192,'ロシア語','Russian','0',NULL,NULL), (933,59,192,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (934,59,193,'スペイン語','Spanish','0',NULL,NULL), (935,59,193,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (936,59,194,'その他言語','World Languages','0',NULL,NULL), (937,59,194,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (938,60,195,'概論','Introduction','0',NULL,NULL), (939,60,195,'中国古典文学','Ancient Chinese Classics','1',NULL,NULL), (940,60,195,'中国近世文学','Early Modern Chinese Literature','2',NULL,NULL), (941,60,195,'中国近現代文学','Modern Chinese Literature','3',NULL,NULL), (942,60,195,'中国語学','Chinese Linguistics','4',NULL,NULL), (943,60,195,'その他','Others','8',NULL,NULL), (944,60,195,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (945,60,196,'概論','Introduction','0',NULL,NULL), (946,60,196,'小説','Novel','1',NULL,NULL), (947,60,196,'詩','Poetry','2',NULL,NULL), (948,60,196,'戯曲','Drama','3',NULL,NULL), (949,60,196,'文学史','History of Literature','4',NULL,NULL), (950,60,196,'英語学','English Linguistics/ English Language Teaching','5',NULL,NULL), (951,60,196,'文学批評理論','Literary Theory','6',NULL,NULL), (952,60,196,'その他','Others','8',NULL,NULL), (953,60,196,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (954,60,197,'概論','Introduction','0',NULL,NULL), (955,60,197,'フランス語史','Language History','1',NULL,NULL), (956,60,197,'フランス文学史','French Literary History','2',NULL,NULL), (957,60,197,'フランス小説・詩','Poesy and Romance','3',NULL,NULL), (958,60,197,'フランス文学批評','Literary Criticism','4',NULL,NULL), (959,60,197,'フランス語文献学','Philology','5',NULL,NULL), (960,60,197,'その他','Others','8',NULL,NULL), (961,60,197,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (962,60,198,'概論','Introduction','0',NULL,NULL), (963,60,198,'中世ドイツ文学','Medieval German Literature','1',NULL,NULL), (964,60,198,'近世ドイツ文学','Early Modern German Literature','2',NULL,NULL), (965,60,198,'18・19世紀ドイツ文学','18th- and 19th-Century German Literature','3',NULL,NULL), (966,60,198,'20世紀ドイツ文学','20th-Century German Literature','4',NULL,NULL), (967,60,198,'現代ドイツ文学','Contemporary German Literature','5',NULL,NULL), (968,60,198,'その他','Others','8',NULL,NULL), (969,60,198,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (970,60,199,'概論','Introduction','0',NULL,NULL), (971,60,199,'その他','Others','8',NULL,NULL), (972,60,199,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (973,60,200,'概論','Introduction','0',NULL,NULL), (974,60,200,'日本上代文学(韻文・散文)','Japanese Ancient Literature','1',NULL,NULL), (975,60,200,'日本中古文学(韻文・散文)','Japanese Premedieval Literature','2',NULL,NULL), (976,60,200,'日本中世文学(韻文・散文)','Japanese Medieval Literature','3',NULL,NULL), (977,60,200,'日本近世文学(韻文・散文)','Japanese PreModern Literature','4',NULL,NULL), (978,60,200,'和漢比較文学','Wakan Comparative Literature','5',NULL,NULL), (979,60,200,'日本近現代文学','Japanese Modern and Contemporary Literature','6',NULL,NULL), (980,60,200,'日本語学','Japanese Linguistics','7',NULL,NULL), (981,60,200,'その他','Others','8',NULL,NULL), (982,60,200,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (983,60,201,'概論','Introduction','0',NULL,NULL), (984,60,201,'その他','Others','8',NULL,NULL), (985,60,201,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (986,60,202,'概論','Introduction','0',NULL,NULL), (987,60,202,'その他','Others','8',NULL,NULL), (988,60,202,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (989,60,203,'概論','Introduction','0',NULL,NULL), (990,60,203,'スペイン文学','Literature in Spain','1',NULL,NULL), (991,60,203,'ラテンアメリカ文学','Literature in Latin America','2',NULL,NULL), (992,60,203,'その他','Others','8',NULL,NULL), (993,60,203,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (994,60,204,'概論','Introduction','0',NULL,NULL), (995,60,204,'文学理論','Theory of Literature','1',NULL,NULL), (996,60,204,'その他','Others','8',NULL,NULL), (997,60,204,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (998,61,205,'総合社会科学','General Social Science','0',NULL,NULL), (999,61,205,'社会科学の今日的課題','Contemporary Issues of The Social Science','1',NULL,NULL), (1000,61,205,'現代文化','Contemporary Japan','2',NULL,NULL), (1001,61,205,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1002,61,206,'シチズンシップ・政府','Citizenship/Government','0',NULL,NULL), (1003,61,206,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1004,61,207,'産業・企業・労働','Industry/Company','0',NULL,NULL), (1005,61,207,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1006,61,208,'グローバル社会','Global Society','0',NULL,NULL), (1007,61,208,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1008,61,209,'人権・福祉','Human Rights/Welfare','0',NULL,NULL), (1009,61,209,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1010,61,210,'環境・計画','Environment/Planning','0',NULL,NULL), (1011,61,210,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1012,61,211,'思想・文化','Thought/Culture','0',NULL,NULL), (1013,61,211,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1014,61,212,'都市','Urban Studies','0',NULL,NULL), (1015,61,212,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1016,62,213,'概論','Introduction','0',NULL,NULL), (1017,62,213,'比較文化','Comparative Culture','1',NULL,NULL), (1018,62,213,'ジェンダー論','Gender','2',NULL,NULL), (1019,62,213,'カルチュラルスタディーズ','Cultural Studies','3',NULL,NULL), (1020,62,213,'その他','Others','8',NULL,NULL), (1021,62,213,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1022,62,214,'概論','Introduction','0',NULL,NULL), (1023,62,214,'美術','Art','1',NULL,NULL), (1024,62,214,'映像','Cinema','2',NULL,NULL), (1025,62,214,'パフォーマンス','Performance','3',NULL,NULL), (1026,62,214,'音楽','Music','4',NULL,NULL), (1027,62,214,'文学','Literature','5',NULL,NULL), (1028,62,214,'メディア論','Media','6',NULL,NULL), (1029,62,214,'イメージ論','Image theories','7',NULL,NULL), (1030,62,214,'その他','Others','8',NULL,NULL), (1031,62,214,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1032,62,215,'概論','Introduction','0',NULL,NULL), (1033,62,215,'生体医工学','Biomedical Engineering','1',NULL,NULL), (1034,62,215,'生体材料学','Biocompatible Material','2',NULL,NULL), (1035,62,215,'医用システム','Medical System','3',NULL,NULL), (1036,62,215,'医療技術評価学','Health Technology Assessment','4',NULL,NULL), (1037,62,215,'その他','Others','8',NULL,NULL), (1038,62,215,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1039,62,216,'概論','Introduction','0',NULL,NULL), (1040,62,216,'多様性','Diversity','1',NULL,NULL), (1041,62,216,'関係構成','Human and Social Relationship','2',NULL,NULL), (1042,62,216,'人間発達','Human Development','3',NULL,NULL), (1043,62,216,'福祉社会','Welfare Society','4',NULL,NULL), (1044,62,216,'心身論','Mind-Body Theory','5',NULL,NULL), (1045,62,216,'その他','Others','8',NULL,NULL), (1046,62,216,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1047,63,217,'基礎演習','Basic Study Practice','0',NULL,NULL), (1048,63,217,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1049,64,218,'保健体育','Health and Physical Education','0',NULL,NULL), (1050,64,218,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1051,65,219,'教職科目','Teacher-Training Course Program','0',NULL,NULL), (1052,65,219,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1053,66,220,'留学','Global Study Program','0',NULL,NULL), (1054,66,220,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1055,67,221,'総合/学際','General Studies','0',NULL,NULL), (1056,67,221,'卒業論文/研究、修士/博士論文','Graduation Paper/Master\'s Thesis/Doctoral Thesis','9',NULL,NULL), (1057,68,222,'指定なし','N/A','Z',NULL,NULL); /*!40000 ALTER TABLE `thirds` ENABLE KEYS */; UNLOCK TABLES; # Dump of table types # ------------------------------------------------------------ DROP TABLE IF EXISTS `types`; CREATE TABLE `types` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `code` varchar(5) COLLATE utf8mb4_unicode_ci NOT NULL, `jp` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `en` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; LOCK TABLES `types` WRITE; /*!40000 ALTER TABLE `types` DISABLE KEYS */; INSERT INTO `types` (`id`, `code`, `jp`, `en`, `created_at`, `updated_at`) VALUES (1,'L','講義','Lecture','2020-04-01 09:35:31','2020-04-01 09:35:31'), (2,'S','演習/ゼミ','Seminar','2020-04-01 09:35:31','2020-04-01 09:35:31'), (3,'W','実習/実験/実技','Practical Training/Experiment/Skill Practice','2020-04-01 09:35:31','2020-04-01 09:35:31'), (4,'F','外国語','Foreign Language','2020-04-01 09:35:31','2020-04-01 09:35:31'), (5,'P','実践形式/フィールドワーク/インターンシップ/ボランティア など','Practice/Field Work/Internship/Volunteer etc.','2020-04-01 09:35:31','2020-04-01 09:35:31'), (6,'G','研究指導','Research Guidance','2020-04-01 09:35:31','2020-04-01 09:35:31'), (7,'T','論文','Thesis','2020-04-01 09:35:31','2020-04-01 09:35:31'), (8,'B','対面授業 + オンデマンド授業','Face-to-Face Class + On Demand Class','2020-04-01 09:35:31','2020-04-01 09:35:31'), (9,'O','オンデマンド授業','On Demand Class','2020-04-01 09:35:31','2020-04-01 09:35:31'), (10,'X','その他','Others','2020-04-01 09:35:31','2020-04-01 09:35:31'), (11,'Z','指定なし','Null',NULL,NULL); /*!40000 ALTER TABLE `types` ENABLE KEYS */; UNLOCK TABLES; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/app/Jugyou.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Jugyou extends Model { public function posts() { return $this->hasMany('Post'); } protected $table = 'classes'; public function dept() { return $this->belongsTo('App\Dept'); } public function language() { return $this->belongsTo('App\Language'); } public function term() { return $this->belongsTo('App\Term'); } public function campus() { return $this->belongsTo('App\Campus'); } public function profs() { return $this->belongsToMany('App\Prof', 'class_profs', 'class_id'); } public function rooms() { return $this->belongsToMany('App\Room', 'class_rooms', 'class_id'); } public function class_cat() { return $this->hasMany('App\ClassCat', 'class_id'); } public function class_prof() { return $this->hasMany('App\ClassProf', 'class_id'); } public function class_room() { return $this->hasMany('App\ClassRoom', 'class_id'); } public function period() { return $this->hasMany('App\Period', 'class_id'); } public function detail() { return $this->hasOne('App\Detail', 'class_id'); } public function review() { return $this->hasMany('App\Review', 'class_id'); } }
ba31f2065183dbf51bff4ceb814f1921f7b9dced
[ "SQL", "PHP" ]
12
PHP
kentozuka/103api
9bc3f8402e9212ca928d12fb0fda2bff1e41ca89
9d3fa13a42b5557b207e62b2382cb8ad86f78f69
refs/heads/main
<file_sep>export const getMappedResponse = response => { if (response.Error) { return []; } else { return response.Search; } };
f0adb420fab7a83275054a9777f0e936745f2339
[ "JavaScript" ]
1
JavaScript
kanishka-malhotra/movies-autocomplete
9f4bccf5c41000ca88642f3261bd4a751b9e9c7c
ecc3772a6bef049170180d38a262530c32ccdca9
refs/heads/main
<file_sep>import React, { useCallback, useEffect } from "react"; import { generatePath, useHistory, useParams } from "react-router-dom"; import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import { func, string } from "prop-types"; import { PATHS, BUTTON_SIZE, SEARCH_PLACEHOLDER_TEXT } from "consts"; import { getMoviesByParams, changeSearchValue, requestMoviesSuccess } from "actions"; import { moviesSortByType } from "types"; import Button from "components/shared/button"; import { FindMovieSectionWrapper, FindMovieTitle, SearchForm, StyledInput } from "components/findMovieSection/findMovieSection.styled"; const FindMovieSection = ({ moviesSortBy, searchValue, activeGenre, onMoviesByParamsGet, onSearchValueChange, onMoviesNotFound }) => { const history = useHistory(); const { value: searchValueFromURL } = useParams(); useEffect(() => { if (searchValueFromURL) { const params = { search: searchValueFromURL, sortBy: moviesSortBy, searchBy: "title", filter: activeGenre }; onSearchValueChange(searchValueFromURL); onMoviesByParamsGet(params); } }, [searchValueFromURL, activeGenre]); useEffect(() => { if (searchValue) { const path = generatePath(PATHS.RESULTS, { value: searchValue }); history.push(path); } }, []); const handleInputSearchChange = useCallback(({ target }) => { onSearchValueChange(target.value); }); const handleSearchFormSubmit = useCallback( (e) => { e.preventDefault(); const path = generatePath(searchValue ? PATHS.RESULTS : PATHS.HOME, searchValue && { value: searchValue }); if (searchValue) { const params = { search: searchValue, sortBy: moviesSortBy, searchBy: "title", filter: activeGenre }; onMoviesByParamsGet(params); } else { onMoviesNotFound([]); } history.push(path); }, [searchValue, moviesSortBy, activeGenre] ); return ( <FindMovieSectionWrapper> <FindMovieTitle>Find your movie</FindMovieTitle> <SearchForm data-testid="find-movie-form" onSubmit={handleSearchFormSubmit}> <StyledInput primary rounded data-testid="find-movie-input" value={searchValue} onChange={handleInputSearchChange} placeholder={SEARCH_PLACEHOLDER_TEXT} /> <Button primary rounded size={BUTTON_SIZE.lg}> Search </Button> </SearchForm> </FindMovieSectionWrapper> ); }; FindMovieSection.propTypes = { moviesSortBy: moviesSortByType, searchValue: string, activeGenre: string, onMoviesByParamsGet: func, onSearchValueChange: func, onMoviesNotFound: func }; const mapStateToProps = (state) => ({ moviesSortBy: state.app.moviesSortBy, searchValue: state.app.searchValue, activeGenre: state.app.activeGenre }); const mapDispatchToProps = (dispatch) => ({ onMoviesByParamsGet: bindActionCreators(getMoviesByParams, dispatch), onSearchValueChange: bindActionCreators(changeSearchValue, dispatch), onMoviesNotFound: bindActionCreators(requestMoviesSuccess, dispatch) }); export default connect(mapStateToProps, mapDispatchToProps)(FindMovieSection); <file_sep>import * as utils from "utils"; import { SORT_BY_VALUES } from "consts"; describe("Utilities testing", () => { it("getGenreId: should get genre id", () => { const genreValue = "Adventure"; const genreId = utils.getGenreId(genreValue); expect(genreId).toEqual(1333); }); it("getYearFromReleaseDate: should get year from release date", () => { const releaseDate = "2000.01.01"; const year = utils.getYearFromReleaseDate(releaseDate); expect(year).toEqual("2000"); }); it("getValueToSortBy: should get value to sort by ('vote_average')", () => { const sortBy = utils.getValueToSortBy(SORT_BY_VALUES.RATING.value); expect(sortBy).toEqual("vote_average"); }); it("getValueToSortBy: should get value to sort by ('release_date')", () => { const sortBy = utils.getValueToSortBy(SORT_BY_VALUES.RELEASE_DATE.value); expect(sortBy).toEqual("release_date"); }); }); <file_sep>import { css } from "styled-components"; import { colors } from "assets/styles/theme/colors"; export const buttonColors = { primary: css` background-color: ${colors.vinous.light}; color: ${colors.orange.light}; &:hover { background-color: ${colors.vinous.original}; } &:active { background-color: ${colors.vinous.dark}; } `, secondary: css` background-color: ${colors.beige.light}; color: ${colors.transparent.black_09}; &:hover { background-color: ${colors.beige.original}; } &:active { background-color: ${colors.beige.dark}; } ` }; <file_sep>import React, { useCallback, useMemo } from "react"; import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import { func, oneOf, oneOfType } from "prop-types"; import { useFormik } from "formik"; import { MODAL_TYPES } from "consts"; import { modalsDefaultState } from "reducers/defaultStates"; import { modalValuesAddType, modalValuesEditType } from "types"; import { setModalValues } from "actions"; import Button from "components/shared/button"; import DatePicker from "components/shared/datePicker"; import { genresList, validationSchema } from "components/modals/shared/updateMovieFields/updateMovieFields.constants"; import { ModalLabel, ModalButtonWrapper } from "components/modals/shared/styles/modals.styled"; import { ModalForm, ModalInput, ModalField, ModalDropdown, ModalFieldError } from "components/modals/shared/updateMovieFields/updateMovieFields.styled"; const UpdateMovieFields = ({ movieValues = {}, type, onModalValuesUpdate, onFieldsSubmit }) => { const formik = useFormik({ enableReinitialize: true, initialValues: movieValues, validationSchema, validateOnChange: false, validateOnBlur: true, onSubmit: (values) => { const { id, poster_path, genres, title, release_date, overview, runtime } = values; const newValues = { id, title: title || modalsDefaultState[type].title, poster_path: poster_path || modalsDefaultState[type].poster_path, release_date: new Date(release_date) || modalsDefaultState[type].release_date, genres: genres || modalsDefaultState[type].genres, overview: overview || modalsDefaultState[type].overview, runtime: (runtime && String(runtime)) || modalsDefaultState[type].runtime }; onModalValuesUpdate(newValues, type); onFieldsSubmit(newValues); } }); const submitButtonText = useMemo(() => (type === MODAL_TYPES.ADD_MOVIE ? "Submit" : "Save"), [type]); const handleResetClick = useCallback( (e) => { e.preventDefault(); formik.resetForm(movieValues); }, [movieValues] ); return ( <ModalForm data-testid="add-movie-modal-submit" onSubmit={formik.handleSubmit}> <ModalField> <ModalLabel htmlFor="title">Title</ModalLabel> <ModalInput value={formik.values.title} onChange={formik.handleChange} id="title" placeholder="Write title" type="text" autoComplete="off" /> {Boolean(formik.errors.title) && <ModalFieldError>{formik.errors.title}</ModalFieldError>} </ModalField> <ModalField> <ModalLabel htmlFor="release_date">Release Date</ModalLabel> <DatePicker date={formik.values.release_date} onDateChange={(date) => formik.setFieldValue("release_date", date)} id="release_date" placeholderText="Select date" autoComplete="off" /> {Boolean(formik.errors.release_date) && <ModalFieldError>{formik.errors.release_date}</ModalFieldError>} </ModalField> <ModalField> <ModalLabel htmlFor="poster_path">Movie URL</ModalLabel> <ModalInput value={formik.values.poster_path} onChange={formik.handleChange} id="poster_path" placeholder="Insert movie URL" type="text" autoComplete="off" /> {Boolean(formik.errors.poster_path) && <ModalFieldError>{formik.errors.poster_path}</ModalFieldError>} </ModalField> <ModalField> <ModalLabel htmlFor="genre">Genre</ModalLabel> <ModalDropdown id="genre" options={genresList} selectedOptions={formik.values.genres} defaultLabel="Select genre" onSelect={(options) => formik.setFieldValue("genres", options)} multiSelect /> {Boolean(formik.errors.genres) && <ModalFieldError>{formik.errors.genres}</ModalFieldError>} </ModalField> <ModalField> <ModalLabel htmlFor="overview">Overview</ModalLabel> <ModalInput value={formik.values.overview} onChange={formik.handleChange} id="overview" placeholder="Write overview" type="text" autoComplete="off" /> {Boolean(formik.errors.overview) && <ModalFieldError>{formik.errors.overview}</ModalFieldError>} </ModalField> <ModalField> <ModalLabel htmlFor="runtime">Runtime</ModalLabel> <ModalInput value={formik.values.runtime} onChange={formik.handleChange} id="runtime" placeholder="Write runtime" type="text" autoComplete="off" /> {Boolean(formik.errors.runtime) && <ModalFieldError>{formik.errors.runtime}</ModalFieldError>} </ModalField> <ModalButtonWrapper> <Button primary rounded onClick={handleResetClick}> Reset </Button> <Button rounded type="submit"> {submitButtonText} </Button> </ModalButtonWrapper> </ModalForm> ); }; UpdateMovieFields.propTypes = { movieValues: oneOfType([modalValuesAddType, modalValuesEditType]), type: oneOf([MODAL_TYPES.ADD_MOVIE, MODAL_TYPES.EDIT_MOVIE]), onModalValuesUpdate: func, onFieldsSubmit: func }; const mapStateToProps = (state, ownProps) => ({ movieValues: state.modals[ownProps.type] }); const mapDispatchToProps = (dispatch) => ({ onModalValuesUpdate: bindActionCreators(setModalValues, dispatch) }); export default connect(mapStateToProps, mapDispatchToProps)(UpdateMovieFields); <file_sep>import styled, { createGlobalStyle } from "styled-components"; import { ResetStyles } from "assets/styles/reset.styled"; import { BaseStyles } from "assets/styles/base.styled"; export const GlobalStyles = createGlobalStyle` ${ResetStyles} ${BaseStyles} `; export const Wrapper = styled.div` position: relative; display: flex; flex-direction: column; height: 100%; z-index: 0; `; export const Main = styled.main` flex: 1 0 auto; background-color: ${({ theme }) => theme.colors.vinous.light}; `; <file_sep>import styled, { css } from "styled-components"; export const BaseStyles = css` html, body, #root { height: 100%; } `; export const Logo = styled.img` height: 40px; `; <file_sep>import { combineReducers } from "redux"; import { appReducer } from "reducers/appReducer"; import { moviesReducer } from "reducers/moviesReducer"; import { modalsReducer } from "reducers/modalsReducer"; export const rootReducer = combineReducers({ app: appReducer, movies: moviesReducer, modals: modalsReducer }); <file_sep>import React from "react"; import { render as rtlRender } from "@testing-library/react"; import { createStore } from "redux"; import { Provider } from "react-redux"; import { rootReducer } from "reducers"; import { ThemeProvider } from "styled-components"; const render = (ui, { initialState, theme, store = createStore(rootReducer, initialState), ...renderOptions } = {}) => { const wrapper = ({ children }) => ( <Provider store={store}>{theme ? <ThemeProvider theme={theme}>{children}</ThemeProvider> : { children }}</Provider> ); return rtlRender(ui, { wrapper, ...renderOptions }); }; export * from "@testing-library/react"; export { render }; <file_sep>export * from "./app.styled"; export * from "./base.styled"; export * from "./mixins.styled"; <file_sep>// No mixins yet <file_sep>const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); module.exports = { entry: { main: path.resolve(__dirname, "../src/index.jsx") }, output: { path: path.resolve(__dirname, "../dist"), filename: "[name].bundle.js", publicPath: "/" }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ title: "Movies UI", favicon: path.resolve(__dirname, "../public/favicon.ico"), template: path.resolve(__dirname, "../public/template.html"), filename: "index.html" }) ], module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: "babel-loader" }, { test: /\.(ico|gif|png|jpg|jpeg)$/i, type: "asset/resource" }, { test: /\.(woff(2)?|eot|ttf|otf|svg|)$/, type: "asset/inline" }, { test: /\.css$/i, use: ["style-loader", "css-loader"] } ] }, resolve: { extensions: [".js", ".jsx"], alias: { actions: path.resolve(__dirname, "../src/actions"), api: path.resolve(__dirname, "../src/api"), assets: path.resolve(__dirname, "../src/assets"), components: path.resolve(__dirname, "../src/components"), consts: path.resolve(__dirname, "../src/constants"), hooks: path.resolve(__dirname, "../src/hooks"), reducers: path.resolve(__dirname, "../src/reducers"), routes: path.resolve(__dirname, "../src/routes"), store: path.resolve(__dirname, "../src/store"), tests: path.resolve(__dirname, "../src/tests"), types: path.resolve(__dirname, "../src/types"), utils: path.resolve(__dirname, "../src/utils") } } }; <file_sep>export { default } from "./updateMovieFields"; <file_sep>import { ALL_GENRES_OPTION } from "consts"; import { genres } from "consts/genres"; import * as Yup from "yup"; export const genresList = genres.filter((genre) => genre.value !== ALL_GENRES_OPTION.value); export const validationSchema = Yup.object().shape({ title: Yup.string().required("Title is required.").max(100, "Title is too long."), poster_path: Yup.string().url("Invalid URL.").required("URL is required."), release_date: Yup.date().typeError("Date must be selected.").required("Date is required."), genres: Yup.array(Yup.object().shape({ id: Yup.number(), value: Yup.string() })) .required("Genre is required.") .min(1, "At least 1 genre must be selected."), overview: Yup.string().required("Overview is required.").max(500, "Overview is too long."), runtime: Yup.number() .typeError("Runtime must be a number.") .required("Runtime is required.") .max(1000, "Runtime is too big.") }); <file_sep>import React, { useCallback, useMemo } from "react"; import { generatePath, useHistory } from "react-router"; import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import { func, string } from "prop-types"; import { setMoviesSortBy, getMoviesByParams, requestMoviesSuccess } from "actions"; import { SORT_BY_OPTIONS, PATHS } from "consts"; import { getValueToSortBy } from "utils"; import { moviesSortByType } from "types"; import { SortingSpan, MoviesSortingWrapper, StyledDropdown } from "components/resultsSection/moviesSorting/moviesSorting.styled"; const MoviesSorting = ({ valueToSortBy, searchValue, activeGenre, onSortByChange, onNewMoviesUpdate, onMoviesNotFound }) => { const history = useHistory(); const selectedOption = useMemo( () => SORT_BY_OPTIONS.find((option) => getValueToSortBy(option.value) === valueToSortBy), [valueToSortBy] ); const handleOptionSelect = useCallback( (newOption) => { const [newSelectedOption] = newOption; const path = generatePath(searchValue ? PATHS.RESULTS : PATHS.HOME, searchValue && { value: searchValue }); if (searchValue) { const sortBy = getValueToSortBy(newSelectedOption.value); onNewMoviesUpdate({ sortBy, search: searchValue, searchBy: "title", filter: activeGenre }); } else { onMoviesNotFound([]); } history.push(path); onSortByChange(newSelectedOption.value); }, [searchValue, activeGenre] ); return ( <MoviesSortingWrapper> <SortingSpan>Sort By</SortingSpan> <StyledDropdown primary options={SORT_BY_OPTIONS} selectedOptions={[selectedOption]} onSelect={handleOptionSelect} /> </MoviesSortingWrapper> ); }; MoviesSorting.propTypes = { valueToSortBy: moviesSortByType, searchValue: string, activeGenre: string, onSortByChange: func, onNewMoviesUpdate: func, onMoviesNotFound: func }; const mapStateToProps = (state) => ({ valueToSortBy: state.app.moviesSortBy, searchValue: state.app.searchValue, activeGenre: state.app.activeGenre }); const mapDispatchToProps = (dispatch) => ({ onSortByChange: bindActionCreators(setMoviesSortBy, dispatch), onNewMoviesUpdate: bindActionCreators(getMoviesByParams, dispatch), onMoviesNotFound: bindActionCreators(requestMoviesSuccess, dispatch) }); export default connect(mapStateToProps, mapDispatchToProps)(MoviesSorting); <file_sep>export * from "./appActions"; export * from "./moviesActions"; export * from "./modalsActions"; <file_sep>## Movies UI --- ### DEPLOYMENT Will be filled. - [**Movies UI Website link**](https://google.com/ "Movies UI") --- ### TOOLS USING Will be filled. --- ### OVERVIEW The idea is to create a single page application, which will allow users: - to search, - to add, - to delete movies from the Movies DB database. --- ### Local Movies API Service GitHub Repository with local Movies API Service implementation: https://github.com/VarvaraZadnepriak/MoviesAPI.ReactJS To start local Movies API service, you should: 1. Clone Movies API Service repository 2. Run the following command to install node modules: `npm i` 3. Run the following command to start Movies API Service: `npm start` Movies API Service will be available on http://localhost:4000/. API Swagger documentation will be available on http://localhost:4000/api-docs. --- ### Interface requirements Design is available via [InVision prototype](https://projects.invisionapp.com/share/F9VXQ7IMZGY#/screens/406802250). There’s no need to implement pixel perfect responsive design. Design can be implemented schematically. --- #### DEVELOPMENT @ 2021 <NAME> (@melk0sha) <file_sep>import { modalsDefaultState } from "reducers/defaultStates"; import { SET_MODAL_VALUES } from "consts/actions"; const initialState = modalsDefaultState; export const modalsReducer = (state = initialState, action) => { switch (action.type) { case SET_MODAL_VALUES: return { ...state, [action.payload.modalType]: { ...action.payload.values } }; default: return state; } }; <file_sep>import styled from "styled-components"; export const AlertContainer = styled.div` position: fixed; display: ${({ show }) => (show ? "flex" : "none")}; top: 0; left: 0; bottom: 0; right: 0; padding: 20px; height: auto; flex-direction: column; justify-content: center; align-items: center; z-index: 4; `; export const AlertWrapper = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 30px; border-radius: 3px; background-color: ${({ theme }) => theme.colors.vinous.dark}; `; export const AlertText = styled.span` color: ${({ theme }) => theme.colors.white}; font-size: 1rem; margin-bottom: 20px; `; <file_sep>import { MODAL_TYPES } from "consts"; const movieProperties = { title: "", release_date: "", poster_path: "", genres: [], overview: "", runtime: "" }; export const modalsDefaultState = { [MODAL_TYPES.ADD_MOVIE]: { ...movieProperties }, [MODAL_TYPES.EDIT_MOVIE]: { id: null, ...movieProperties }, [MODAL_TYPES.DELETE_MOVIE]: { id: null } }; <file_sep>import styled from "styled-components"; import ActionMenu from "components/shared/actionMenu"; export const MovieWrapper = styled.div` display: flex; flex-direction: column; min-width: 200px; padding: 25px; color: ${({ theme }) => theme.colors.white}; &:hover { background-color: ${({ theme }) => theme.colors.vinous.dark}; } `; export const MovieImageWrapper = styled.div` position: relative; `; export const MovieImage = styled.img` height: 320px; border-radius: 3px; cursor: pointer; `; export const MovieInfoWrapper = styled.div` display: flex; justify-content: space-between; align-items: flex-start; margin-top: 10px; `; export const MovieTitle = styled.h3` max-width: 165px; font-size: 1.6rem; color: ${({ theme }) => theme.colors.white}; `; export const MovieYear = styled.span` line-height: 2rem; font-size: 1rem; color: ${({ theme }) => theme.colors.grey.light}; `; export const MovieGenres = styled.span` max-width: 200px; margin-top: 10px; font-size: 1rem; color: ${({ theme }) => theme.colors.grey.light}; text-transform: lowercase; &:first-letter { text-transform: uppercase; } `; export const StyledActionMenu = styled(ActionMenu)` position: absolute; top: 20px; right: 20px; `; <file_sep>import React, { useCallback, useMemo, useState } from "react"; import { generatePath, useLocation } from "react-router-dom"; import { HashLink } from "react-router-hash-link"; import { connect } from "react-redux"; import { func, number, string } from "prop-types"; import { bindActionCreators } from "redux"; import { requestMoviesSuccess } from "actions"; import { BUTTON_SIZE, PATHS } from "consts"; import Button from "components/shared/button"; import Modal from "components/shared/modal"; import AddMovieModal from "components/modals/addMovieModal"; import { Logo } from "assets/styles"; import { HeaderWrapper, LogoWrapper, StyledHashLink } from "components/header/header.styled"; import logoImage from "assets/images/logo.png"; const [RESULTS_PATH] = PATHS.RESULTS.split(":"); const Header = ({ searchValue, moviesLength, onMoviesNotFound }) => { const { pathname } = useLocation(); const [isModalShown, setModalShown] = useState(false); const handleModalShowingChange = useCallback(() => { setModalShown((prevState) => !prevState); }, [setModalShown]); const handleLinkClick = useCallback(() => { if (!searchValue && moviesLength) { onMoviesNotFound([]); } }, [searchValue, moviesLength]); const linkTo = useMemo(() => { const path = `${searchValue ? PATHS.RESULTS : PATHS.HOME}#`; return generatePath(path, { value: searchValue }); }, [searchValue]); return ( <HeaderWrapper> <LogoWrapper> <HashLink smooth to={linkTo} onClick={handleLinkClick}> <Logo src={logoImage} alt="Logo" /> </HashLink> </LogoWrapper> {pathname === PATHS.HOME || pathname.includes(RESULTS_PATH) ? ( <Button data-testid="add-movie-btn" rounded size={BUTTON_SIZE.sm} onClick={handleModalShowingChange}> Add movie </Button> ) : ( <StyledHashLink smooth to={linkTo} onClick={handleLinkClick}> Back to movie search </StyledHashLink> )} <Modal show={isModalShown} onClose={handleModalShowingChange}> <AddMovieModal onAddingSubmit={handleModalShowingChange} /> </Modal> </HeaderWrapper> ); }; Header.propTypes = { searchValue: string, moviesLength: number, onMoviesNotFound: func }; const mapStateToProps = (state) => ({ searchValue: state.app.searchValue, moviesLength: state.movies.movieList.length }); const mapDispatchToProps = (dispatch) => ({ onMoviesNotFound: bindActionCreators(requestMoviesSuccess, dispatch) }); export default connect(mapStateToProps, mapDispatchToProps)(Header); <file_sep>import styled from "styled-components"; import { device } from "assets/styles/device"; import Input from "components/shared/input"; import mainBackgroundImage from "assets/images/background.jpg"; const getTextOutlineByColor = (color) => `${color} 1px 1px 0, ${color} -1px 1px 0, ${color} 1px -1px 0, ${color} -1px -1px 0`; export const FindMovieSectionWrapper = styled.div` position: relative; display: flex; flex-direction: column; justify-content: center; align-items: center; min-height: 600px; margin-top: -70px; padding: 70px 10% 0; background-image: url(${mainBackgroundImage}); background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; background-color: ${({ theme }) => theme.colors.vinous.original}; &::after { content: ""; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: ${({ theme }) => theme.colors.transparent.black_05}; z-index: 1; } * { position: relative; z-index: 2; } `; export const FindMovieTitle = styled.h1` margin: 0 10px 50px; text-shadow: ${({ theme }) => getTextOutlineByColor(theme.colors.black)}; color: ${({ theme }) => theme.colors.white}; font-size: 3rem; `; export const SearchForm = styled.form` display: flex; flex-wrap: wrap; justify-content: center; width: 100%; `; export const StyledInput = styled(Input)` min-width: 300px; margin-bottom: 20px; @media ${device.tablet} { margin-bottom: 0; } `; <file_sep>import styled, { css } from "styled-components"; import { BUTTON_SIZE } from "consts"; export const StyledButton = styled.button` ${({ size, theme, primary, rounded }) => css` display: flex; justify-content: center; align-items: center; ${theme.buttonSizes[BUTTON_SIZE[size]]} margin: 0 10px; border: none; border-radius: ${rounded ? "40px" : "3px"}; white-space: nowrap; ${primary ? theme.buttonColors.primary : theme.buttonColors.secondary} transition: background-color 0.2s ease-out; cursor: pointer; box-shadow: 0px 0px 5px -1px ${theme.colors.transparent.black_08}; `} `; <file_sep>import React, { useCallback, useMemo, useRef, useState } from "react"; import { arrayOf, bool, string } from "prop-types"; import { useOnClickOutside } from "hooks"; import { dropdownOptionType } from "types"; import { DropdownWrapper, DropdownHeader, DropdownList, ListItem } from "components/shared/dropdown/dropdown.styled"; const Dropdown = ({ id, className, options = [], defaultLabel = "", selectedOptions = [], onSelect, primary = false, multiSelect = false }) => { const [isOpen, setOpen] = useState(false); const dropdownWrapperRef = useRef(null); useOnClickOutside(dropdownWrapperRef, () => setOpen(false)); const handleHeaderClick = useCallback(() => setOpen((prevState) => !prevState), [setOpen]); const handleOptionChange = useCallback( (newOption) => { // TODO: Refactor this part --------- let newOptions = [newOption]; if (multiSelect) { const newOptionIndex = selectedOptions.findIndex((option) => option.id === newOption.id); if (newOptionIndex !== -1) { selectedOptions.splice(newOptionIndex, 1); newOptions = [...selectedOptions]; } else { newOptions = [...selectedOptions, newOption]; } } setOpen(false); onSelect(newOptions); // --------- }, [onSelect, setOpen, multiSelect, selectedOptions] ); const OptionItems = useMemo( () => options?.map((option, index) => ( <ListItem primary={primary} onClick={() => handleOptionChange(option)} key={option.id || index}> {option.value} </ListItem> )), [options, handleOptionChange] ); const selectedOptionsText = useMemo(() => selectedOptions.map((selectedOption) => selectedOption.value).join(", "), [ selectedOptions ]); return ( <DropdownWrapper id={id} primary={primary} className={className} ref={dropdownWrapperRef} opened={isOpen} onClick={(e) => e.preventDefault()} > <DropdownHeader primary={primary} isLabel={!!defaultLabel && !selectedOptionsText} onClick={handleHeaderClick}> {selectedOptionsText || defaultLabel} </DropdownHeader> {isOpen && !!options.length && <DropdownList primary={primary}>{OptionItems}</DropdownList>} </DropdownWrapper> ); }; Dropdown.propTypes = { id: string, className: string, options: arrayOf(dropdownOptionType), defaultLabel: string, selectedOptions: arrayOf(dropdownOptionType), primary: bool, multiSelect: bool }; export default Dropdown; <file_sep>import React from "react"; import { fireEvent } from "@testing-library/react"; import { render } from "tests/helpers/render"; import { mockStore } from "tests/helpers/mockStore"; import { theme } from "assets/styles/theme"; import Header from "components/header"; import "@testing-library/jest-dom/extend-expect"; jest.mock("react-datepicker/dist/react-datepicker.css", () => {}); jest.mock("react-router-dom", () => ({ useLocation: jest.fn().mockReturnValue({ pathname: "/" }), generatePath: jest.fn().mockReturnValue("url") })); jest.mock("react-router-hash-link", () => ({ HashLink: jest.fn().mockReturnValue(<div></div>) })); jest.mock("components/shared/modal", () => jest.fn().mockReturnValue(<div></div>)); describe("<Header /> component testing", () => { const initialState = { movies: { movieList: [{ id: 1, title: "Movie" }] }, app: { searchValue: "" } }; it("should render a Header component with initial state", () => { const store = mockStore(initialState); const { container } = render(<Header />, { store, theme }); expect(container).toMatchSnapshot(); }); it("should click on button and change modal showing state", () => { const store = mockStore(initialState); const { container, getByTestId } = render(<Header />, { store, theme }); fireEvent.click(getByTestId("add-movie-btn")); expect(container).toMatchSnapshot(); }); }); <file_sep>import styled from "styled-components"; export const ErrorBoundaryWrapper = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; min-height: 100vh; padding: 20%; background-color: ${({ theme }) => theme.colors.vinous.original}; color: ${({ theme }) => theme.colors.white}; `; export const ErrorBoundaryTitle = styled.h2` margin-bottom: 20px; font-size: 2rem; font-weight: bold; text-align: center; `; export const ErrorBoundarySpan = styled.span` padding: 10px; font-size: 1rem; text-align: center; `; <file_sep>import configureMockStore from "redux-mock-store"; import thunk from "redux-thunk"; const middlewares = [thunk]; const configuredMockStore = configureMockStore(middlewares); const mockStore = (initialState) => configuredMockStore(initialState); export { mockStore }; <file_sep>import React, { Component } from "react"; import { ErrorBoundaryWrapper, ErrorBoundaryTitle, ErrorBoundarySpan } from "components/errorBoundary/errorBoundary.styled"; class ErrorBoundary extends Component { state = { hasError: false, error: null, errorInfo: null }; static getDerivedStateFromError = () => { return { hasError: true }; }; componentDidCatch = (error, errorInfo) => { this.setState({ error, errorInfo }); }; render() { const { hasError, error, errorInfo } = this.state; const { children } = this.props; return hasError ? ( <ErrorBoundaryWrapper> <ErrorBoundaryTitle>Oops! Something went wrong.</ErrorBoundaryTitle> {errorInfo && ( <> <ErrorBoundarySpan>Details:</ErrorBoundarySpan> {error && <ErrorBoundarySpan>{error?.toString()}</ErrorBoundarySpan>} {errorInfo.componentStack && <ErrorBoundarySpan>{errorInfo.componentStack}</ErrorBoundarySpan>} </> )} </ErrorBoundaryWrapper> ) : ( children ); } } export default ErrorBoundary; <file_sep>import React, { useCallback, useMemo, useRef, useState } from "react"; import { arrayOf, func, number, shape, string } from "prop-types"; import { useOnClickOutside } from "hooks"; import { ActionMenuWrapper, ActionMenuCircleWrapper, ActionMenuCircle, ActionMenuOptions, ActionMenuOption, Close } from "components/shared/actionMenu/actionMenu.styled"; const ActionMenu = ({ className, options = [], onOptionClick }) => { const [isCircleHidden, setCircleHidden] = useState(false); const actionMenuWrapperRef = useRef(null); useOnClickOutside(actionMenuWrapperRef, () => setCircleHidden(false)); const handleActionMenuClick = useCallback(() => { setCircleHidden((prevState) => !prevState); }, [setCircleHidden]); const Options = useMemo( () => options.map((option, index) => ( <ActionMenuOption key={option.id || index} onClick={() => onOptionClick(option)}> {option.value} </ActionMenuOption> )), [options, onOptionClick] ); return ( <ActionMenuWrapper className={className} ref={actionMenuWrapperRef}> <ActionMenuCircleWrapper onClick={handleActionMenuClick} hidden={isCircleHidden}> <ActionMenuCircle /> <ActionMenuCircle /> <ActionMenuCircle /> </ActionMenuCircleWrapper> <ActionMenuOptions hidden={!isCircleHidden}> {Options} <Close onClick={handleActionMenuClick} /> </ActionMenuOptions> </ActionMenuWrapper> ); }; ActionMenu.propTypes = { className: string, options: arrayOf( shape({ id: number, value: string }) ), onOptionClick: func }; export default ActionMenu; <file_sep>import styled from "styled-components"; import { HashLink } from "react-router-hash-link"; import { device } from "assets/styles/device"; export const HeaderWrapper = styled.header` position: relative; display: flex; justify-content: space-between; align-items: center; width: 100%; padding: 15px 30px; background-color: ${({ theme }) => theme.colors.transparent.black_04}; z-index: 2; box-shadow: 0px 1px 5px 0px ${({ theme }) => theme.colors.transparent.black_08}; `; export const LogoWrapper = styled.div` width: 55px; height: 40px; overflow: hidden; @media ${device.tablet} { width: auto; } `; export const StyledHashLink = styled(HashLink)` display: flex; justify-content: center; align-items: center; height: 36px; margin: 0 10px; padding: 6px 18px; font-size: 1rem; border: none; border-radius: 40px; white-space: nowrap; text-decoration: none; ${({ theme }) => theme.buttonColors.secondary} transition: background-color 0.2s ease-out; cursor: pointer; `; <file_sep>import styled from "styled-components"; export const ActionMenuWrapper = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; `; export const ActionMenuCircleWrapper = styled.div` display: ${({ hidden }) => (hidden ? "none" : "flex")}; flex-direction: column; justify-content: center; align-items: center; width: 35px; height: 35px; border-radius: 50%; background-color: ${({ theme }) => theme.colors.transparent.white_08}; cursor: pointer; `; export const ActionMenuCircle = styled.div` width: 5px; height: 5px; margin: 1px; border-radius: 50%; background-color: ${({ theme }) => theme.colors.grey.dark}; `; export const ActionMenuOptions = styled.ul` display: ${({ hidden }) => (hidden ? "none" : "flex")}; flex-direction: column; justify-content: center; align-items: center; min-height: 50px; min-width: 50px; padding-top: 30px; border-radius: 3px; color: ${({ theme }) => theme.colors.grey.dark}; background-color: ${({ theme }) => theme.colors.white}; `; export const ActionMenuOption = styled.li` display: flex; justify-content: flex-end; width: 100%; padding: 6px 15px; font-size: 1rem; cursor: pointer; &:hover { background-color: ${({ theme }) => theme.colors.beige.original}; } &:active { background-color: ${({ theme }) => theme.colors.beige.dark}; } `; export const Close = styled.span` position: absolute; right: 10px; top: 10px; width: 15px; height: 15px; opacity: 0.3; cursor: pointer; &:hover { opacity: 1; } &::before, &::after { position: absolute; left: 6px; content: ""; height: 15px; width: 2px; background-color: ${({ theme }) => theme.colors.black}; } &::before { transform: rotate(45deg); } &::after { transform: rotate(-45deg); } `; <file_sep>import React from "react"; import { fireEvent } from "@testing-library/react"; import { render } from "tests/helpers/render"; import { mockStore } from "tests/helpers/mockStore"; import MovieSection from "components/movieSection"; import { theme } from "assets/styles/theme"; import "@testing-library/jest-dom/extend-expect"; describe("<MovieSection /> component testing", () => { const initialState = { movies: { movieList: [] }, app: { searchValue: "" } }; const initialStateWithMovie = { movies: { movieList: [ { id: 123, title: "Movie", vote_average: 7, release_date: "01.01.2000", poster_path: "poster_path", overview: "overview", tagline: "tagline", genres: ["Genre"], runtime: 1 } ] }, app: { searchValue: "Movie" } }; it("should render a MovieSection component with initial state", () => { const store = mockStore(initialState); const noMovieFoundText = "Sorry, but no movie was found."; const { container, getByText } = render(<MovieSection />, { theme, store }); expect(getByText(noMovieFoundText)).toBeInTheDocument(); expect(container).toMatchSnapshot(); }); it("should handle an incorrect image url and replace it with correct one", () => { const store = mockStore(initialStateWithMovie); const [{ id, title }] = initialStateWithMovie.movies.movieList; const { container, getByText, getByAltText } = render(<MovieSection movieId={String(id)} />, { theme, store }); fireEvent.error(getByAltText(title)); expect(getByText(title)).toBeInTheDocument(); expect(container).toMatchSnapshot(); }); }); <file_sep>import React from "react"; import { DatePickerComponent } from "components/shared/datePicker/datePicker.styled"; import "react-datepicker/dist/react-datepicker.css"; const DatePicker = ({ date, onDateChange: handleDateChange, ...props }) => { return <DatePickerComponent {...props} selected={date} dateFormat="yyyy-MM-dd" onChange={handleDateChange} />; }; export default DatePicker; <file_sep>import React from "react"; import { ThemeProvider } from "styled-components"; import { GlobalStyles, Wrapper, Main } from "assets/styles"; import { theme } from "assets/styles/theme"; import ErrorBoundary from "components/errorBoundary"; import Footer from "components/footer"; import Header from "components/header"; import Routes from "routes"; const App = () => ( <ThemeProvider theme={theme}> <ErrorBoundary> <Wrapper> <Header /> <Main> <Routes /> </Main> <Footer /> </Wrapper> </ErrorBoundary> <GlobalStyles /> </ThemeProvider> ); export default App; <file_sep>import React from "react"; import { fireEvent, waitFor } from "@testing-library/react"; import { render } from "tests/helpers/render"; import { mockStore } from "tests/helpers/mockStore"; import { theme } from "assets/styles/theme"; import { MODAL_TYPES } from "consts"; import AddMovieModal from "components/modals/addMovieModal"; import "@testing-library/jest-dom/extend-expect"; jest.mock("react-datepicker/dist/react-datepicker.css", () => {}); describe("<AddMovieModal /> component testing", () => { const initialState = { app: { moviesSortBy: "release_date", searchValue: "Movie", activeGenre: "All" }, modals: { [MODAL_TYPES.ADD_MOVIE]: { title: "Title", release_date: new Date("01-01-2000"), poster_path: "https://www.google.com/", genres: [{ id: 1332, value: "Action" }], overview: "Overview", runtime: "1" } } }; it("should render a AddMovieModal component with initial state", () => { const store = mockStore(initialState); const { container } = render(<AddMovieModal />, { store, theme }); expect(container).toMatchSnapshot(); }); it("should handle form submit", async () => { const store = mockStore(initialState); const onAddingSubmit = jest.fn(); const { getByTestId } = render(<AddMovieModal onAddingSubmit={onAddingSubmit} />, { store, theme }); const form = getByTestId("add-movie-modal-submit"); fireEvent.submit(form); await waitFor(() => expect(onAddingSubmit).toHaveBeenCalled()); }); it("should handle form submit with empty searchValue", async () => { const initialStateWithEmptySearchValue = { ...initialState, app: { ...initialState.app, searchValue: "" } }; const store = mockStore(initialStateWithEmptySearchValue); const onAddingSubmit = jest.fn(); const { getByTestId } = render(<AddMovieModal onAddingSubmit={onAddingSubmit} />, { store, theme }); const form = getByTestId("add-movie-modal-submit"); fireEvent.submit(form); await waitFor(() => expect(onAddingSubmit).toHaveBeenCalled()); }); }); <file_sep>import React from "react"; import { render } from "tests/helpers/render"; import { theme } from "assets/styles/theme"; import Footer from "components/footer"; import "@testing-library/jest-dom/extend-expect"; describe("<Footer /> component testing", () => { it("should render a Footer component with initial state", () => { const { container, getByAltText } = render(<Footer />, { theme }); expect(getByAltText("Logo")).toBeInTheDocument(); expect(container).toMatchSnapshot(); }); }); <file_sep>import React, { useCallback, useMemo } from "react"; import { bindActionCreators } from "redux"; import { generatePath } from "react-router-dom"; import { connect } from "react-redux"; import { HashLink } from "react-router-hash-link"; import { func } from "prop-types"; import { ACTION_MENU_MOVIE_VALUES, ACTION_MENU_MOVIE_OPTIONS, PATHS, MODAL_TYPES } from "consts"; import { modalsDefaultState } from "reducers/defaultStates"; import { movieType } from "types"; import { setModalValues } from "actions"; import { getYearFromReleaseDate, getGenreId } from "utils"; import { MovieWrapper, MovieImageWrapper, MovieImage, MovieInfoWrapper, MovieTitle, MovieGenres, MovieYear, StyledActionMenu } from "components/resultsSection/movies/movie/movie.styled"; import noImagePicture from "assets/images/no_picture.jpg"; const Movie = ({ movie = {}, onOptionClick, onModalValuesUpdate }) => { const { id, poster_path, genres, title, release_date, overview, runtime } = movie; const genresText = useMemo(() => genres.join(", "), [genres]); const year = useMemo(() => getYearFromReleaseDate(release_date), [release_date]); const handleOptionClick = useCallback( (option) => { const type = option.id === ACTION_MENU_MOVIE_VALUES.EDIT.id ? MODAL_TYPES.EDIT_MOVIE : MODAL_TYPES.DELETE_MOVIE; if (type === MODAL_TYPES.EDIT_MOVIE) { const movieGenres = genres.map((genre) => ({ id: getGenreId(genre), value: genre })); onModalValuesUpdate( { id, title: title || modalsDefaultState[type].title, poster_path: poster_path || modalsDefaultState[type].poster_path, release_date: new Date(release_date) || modalsDefaultState[type].release_date, genres: movieGenres || modalsDefaultState[type].genres, overview: overview || modalsDefaultState[type].overview, runtime: (runtime && String(runtime)) || modalsDefaultState[type].runtime }, MODAL_TYPES.EDIT_MOVIE ); } else if (type === MODAL_TYPES.DELETE_MOVIE) { onModalValuesUpdate({ id }, MODAL_TYPES.DELETE_MOVIE); } onOptionClick(type); }, [movie, onModalValuesUpdate, onOptionClick] ); const handleSrcError = useCallback(({ target }) => { target.src = noImagePicture; }, []); return ( <MovieWrapper> <MovieImageWrapper> <StyledActionMenu options={ACTION_MENU_MOVIE_OPTIONS} onOptionClick={handleOptionClick} /> <HashLink smooth to={generatePath(`${PATHS.MOVIE}#`, { id })}> <MovieImage src={poster_path} alt={title} onError={handleSrcError} /> </HashLink> </MovieImageWrapper> <MovieInfoWrapper> <MovieTitle>{title}</MovieTitle> <MovieYear>{year}</MovieYear> </MovieInfoWrapper> <MovieGenres>{genresText}</MovieGenres> </MovieWrapper> ); }; Movie.propTypes = { movie: movieType, onOptionClick: func, onModalValuesUpdate: func }; const mapStateToProps = (_state, ownProps) => ({ movie: ownProps.movie }); const mapDispatchToProps = (dispatch) => ({ onModalValuesUpdate: bindActionCreators(setModalValues, dispatch) }); export default connect(mapStateToProps, mapDispatchToProps)(Movie); <file_sep>import styled from "styled-components"; import { device } from "assets/styles/device"; export const ResultsSectionWrapper = styled.div` position: relative; display: flex; flex-direction: column; padding: 20px 20px 50px; background-color: ${({ theme }) => theme.colors.vinous.original}; box-shadow: 0px -1px 5px 0px ${({ theme }) => theme.colors.transparent.black_08}; @media ${device.tablet} { padding: 20px 100px 50px; } `; export const ResultsSectionHeader = styled.div` display: flex; flex-wrap: wrap; justify-content: center; border-bottom: 5px solid ${({ theme }) => theme.colors.vinous.dark}; @media ${device.laptop} { justify-content: flex-end; } `; export const MoviesFoundSpan = styled.span` display: flex; padding: 20px; font-size: 1rem; color: ${({ theme }) => theme.colors.white}; `; export const NoMovieFoundSpan = styled.span` display: flex; justify-content: center; align-items: center; padding: 150px 0; font-size: 2.5rem; color: ${({ theme }) => theme.colors.white}; `; <file_sep>export { default } from "./editMovieModal"; <file_sep>import styled from "styled-components"; import Dropdown from "components/shared/dropdown"; export const MoviesSortingWrapper = styled.div` position: relative; top: 1px; display: flex; `; export const SortingSpan = styled.span` display: flex; justify-content: center; align-items: center; height: 50px; padding: 20px; color: ${({ theme }) => theme.colors.grey.original}; white-space: nowrap; text-transform: uppercase; font-size: 1rem; `; export const StyledDropdown = styled(Dropdown)` justify-content: center; min-width: 157px; text-transform: uppercase; `; <file_sep>import { CLEAR_REQUEST_RESULT, REQUEST_MOVIES_SUCCESS, REQUEST_MOVIES_ERROR } from "consts/actions"; const initialState = { error: false, movieList: [], genres: [] }; export const moviesReducer = (state = initialState, action) => { switch (action.type) { case REQUEST_MOVIES_SUCCESS: return { ...state, movieList: [...action.payload] }; case REQUEST_MOVIES_ERROR: return { ...state, error: true }; case CLEAR_REQUEST_RESULT: return { ...state, error: false }; default: return state; } }; <file_sep>import React from "react"; import { Link } from "react-router-dom"; import { PATHS } from "consts"; import { NotFoundWrapper, NotFoundTitle, NotFoundSpan } from "components/notFoundPage/notFoundPage.styled"; const notFoundPage = () => ( <NotFoundWrapper> <NotFoundTitle>404</NotFoundTitle> <NotFoundSpan>The page you were looking for doesn't exist.</NotFoundSpan> <NotFoundSpan> We suggest you getting back to <Link to={PATHS.HOME}>Home page</Link>. </NotFoundSpan> </NotFoundWrapper> ); export default notFoundPage; <file_sep>import React from "react"; import { useParams } from "react-router"; import MovieSection from "components/movieSection"; import ResultsSection from "components/resultsSection"; const Movie = () => { const { id } = useParams(); return ( <> <MovieSection movieId={id} /> <ResultsSection /> </> ); }; export default Movie; <file_sep>import styled from "styled-components"; export const NotFoundWrapper = styled.div` display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; margin-top: -70px; padding: 70px 10% 0; background-color: ${({ theme }) => theme.colors.vinous.light}; `; export const NotFoundTitle = styled.h3` color: ${({ theme }) => theme.colors.white}; font-size: 8rem; padding: 10px; `; export const NotFoundSpan = styled.span` color: ${({ theme }) => theme.colors.white}; font-size: 1rem; padding: 5px; `; <file_sep>const mediaSize = { mobileS: "320px", mobileM: "375px", mobileL: "425px", tablet: "768px", laptop: "1024px", laptopL: "1440px", desktop: "2560px" }; export const device = { mobileS: `(min-width: ${mediaSize.mobileS})`, mobileM: `(min-width: ${mediaSize.mobileM})`, mobileL: `(min-width: ${mediaSize.mobileL})`, tablet: `(min-width: ${mediaSize.tablet})`, laptop: `(min-width: ${mediaSize.laptop})`, laptopL: `(min-width: ${mediaSize.laptopL})`, desktop: `(min-width: ${mediaSize.desktop})` }; <file_sep>import styled from "styled-components"; import { ModalSpan } from "components/modals/shared/styles/modals.styled.js"; export const StyledModalSpan = styled(ModalSpan)` margin: 0 10px 10px; text-transform: uppercase; `; <file_sep>import React from "react"; import NotFoundPage from "components/notFoundPage"; const NotFound = () => <NotFoundPage />; export default NotFound; <file_sep>export const genres = [ { id: 1331, value: "All" }, { id: 1332, value: "Action" }, { id: 1333, value: "Adventure" }, { id: 1334, value: "Science Fiction" }, { id: 1335, value: "Fantasy" }, { id: 1336, value: "Thriller" }, { id: 1337, value: "Drama" }, { id: 1338, value: "Family" }, { id: 1339, value: "Comedy" }, { id: 1340, value: "Horror" }, { id: 1341, value: "TV Movie" }, { id: 1342, value: "Documentary" }, { id: 1343, value: "History" }, { id: 1344, value: "Mystery" }, { id: 1345, value: "Crime" }, { id: 1346, value: "Romance" }, { id: 1347, value: "Music" }, { id: 1348, value: "Animation" }, { id: 1349, value: "War" }, { id: 1350, value: "Western" } ]; <file_sep>import React from "react"; import { createPortal } from "react-dom"; import { bool, element, func } from "prop-types"; import { ModalContainer, ModalWrapper, ModalCloseIcon } from "components/shared/modal/modal.styled"; const modalParentElement = document.getElementById("root"); const Modal = ({ show = false, children, onClose }) => { return createPortal( <ModalContainer show={show}> <ModalWrapper show={show}> {children} <ModalCloseIcon onClick={onClose} /> </ModalWrapper> </ModalContainer>, modalParentElement ); }; Modal.propTypes = { show: bool, children: element, onClose: func }; export default Modal; <file_sep>export { default } from "./moviesSorting"; <file_sep>import styled from "styled-components"; export const FooterWrapper = styled.footer` display: flex; justify-content: center; align-items: center; flex: 0 0 auto; width: 100%; padding: 30px; background-color: ${({ theme }) => theme.colors.vinous.dark}; `; <file_sep>export { default } from "./addMovieModal"; <file_sep>import styled from "styled-components"; import DatePicker from "react-datepicker"; export const DatePickerComponent = styled(DatePicker)` flex: 1 1 auto; max-width: 700px; width: 100%; height: 40px; padding: 10px 20px; margin: 0 10px; border: none; border-radius: ${({ rounded }) => (rounded ? "40px" : "3px")}; background-color: ${({ theme }) => theme.colors.brown.original}; font-size: 1rem; color: ${({ theme }) => theme.colors.white}; transition: background-color 0.2s ease-out; box-shadow: 0px 0px 3px -1px ${({ theme }) => theme.colors.transparent.black_08}; &:focus { background-color: ${({ theme }) => theme.colors.brown.dark}; } &::placeholder { color: ${({ theme }) => theme.colors.white}; opacity: 0.6; } `; <file_sep>import styled from "styled-components"; import Input from "components/shared/input"; import Dropdown from "components/shared/dropdown"; export const ModalForm = styled.form` display: flex; justify-content: flex-end; flex-wrap: wrap; .react-datepicker__input-container { padding: 0 20px 0 0; } `; export const ModalInput = styled(Input)` height: 40px; padding: 10px 20px; font-size: 1rem; `; export const ModalField = styled.div` position: relative; display: flex; flex-direction: column; width: 100%; max-width: 50%; `; export const ModalDropdown = styled(Dropdown)` height: 40px; margin: 0 10px; border-radius: 3px; div { justify-content: flex-start; } `; export const ModalFieldError = styled.span` position: absolute; bottom: -17px; right: 15px; display: flex; justify-content: flex-end; font-size: 0.7rem; color: ${({ theme }) => theme.colors.red}; `; <file_sep>### Task 9. Testing Write unit tests for your application (consider using Jest, @testing-library/react or Enzyme, react-test-renderer, React-test-utils, etc.) Subtasks: 1. Cover 1 simple presentational component with snapshot tests. 2. Cover 1 reducer and all its actions with unit-tests. 3. Measure coverage level with coverage report. 4. Cover “Add movie” modal dialog components with unit-tests, mock all external dependencies using Jest mocks. **Evaluation criteria** 2 - Subtask 1 is implemented 3 - Subtasks 2 and 3 are implemented 4 - Subtask 4 “Add movie” modal dialog and all its components coverage > 70% 5 - Global coverage > 90%. Added unit tests for hooks --- ### Task 8. Routing Create routing for your application (via React Router). Add 404 (error page) and ‘No movies found’ page. Link app states between each other with React Router. By default, user lands on a new page with empty results state. When user clicks on a film item, redirect them to: _localhost/film/id_. Handle invalid URLs, display a 404 page, where user will be redirected in case of invalid URL. On switching search type or sorting type you shouldn’t switch any routes. When user performs a new search, you should redirect them to: _localhost/search/Search%20Query_. When a new user lands on the page with such URL, you should perform search and display results. **Evaluation criteria** 2.1 - Add 404 and “No movies found” pages with markup 2.2 - Have 2+ pages which displays on different URLs 3 - Implement displaying 404 page for all invalid URLs 4 - By default, user lands on a new page with empty results page 5.1 - When user performs a search on the page, change URL and show search results 5.2 - When new user enters the site using direct link with search parameters – show search results --- ### Task 7. Forms 1. Implement «Add movie» form. 2. Implement «Edit movie» form. Required validation criteria: http://localhost:4000/api-docs **Evaluation criteria** 2 - Installed formik 3 - Implementation of “Add movie” form with validation 4 - Implementation of “Edit movie” form with validation 5 - Use hooks from formik --- ### Task 6. Redux 1. Go through API docs in swagger: http://localhost:4000/api-docs 2. Make your components perform real AJAX requests. Implement data fetches as async actions and pass data to your components with redux. 3. Implement creating, editing and updating films according to the design operations as redux actions. 4. Implement filtering and sorting (by genre, rating, and release date) as redux actions. **Evaluation criteria** 2 - All data fetches done as actions and received from store by components 3 - Creating, editing, deleting and updating (CRUD operations) of films are done as redux actions 4 - Filtering by release date and rating done as redux actions 5 - Sorting by genre is done as redux actions --- ### Task 5: Hooks Implement markup and styles for ["Movie details"](https://projects.invisionapp.com/share/F9VXQ7IMZGY/#/screens/407583174) page. In your project, change Class components into Functional components and use hooks where applicable. **Evaluation criteria** 2 - Implement “Movie details” page. Use “useState” hooks 3 - Use “useCallback” hooks 4 - Use “useEffect” hooks 5 - Usage of custom hooks (discuss with your mentor) --- ### Task 4. Components. Part 2 Implement markup and styles for ["Add movie"](https://projects.invisionapp.com/share/F9VXQ7IMZGY/#/screens/406802247), ["Edit"](https://projects.invisionapp.com/share/F9VXQ7IMZGY/#/screens/406802252), ["Delete"](https://projects.invisionapp.com/share/F9VXQ7IMZGY/#/screens/406802251) modal windows and "sorting". No need to implement real API calls. Only add pages with mocked data. No need to implement hooks in this task. **Evaluation criteria** 2 - Implementation of markup and styles 3 - Use stateless/stateful approach 4 - Use React synthetic events 5 - Use lifecycle methods (discuss with mentor) --- ### Task 3: Components. Part 1 Write components implementing HTML markup for required design for home page of [InVision prototype](https://projects.invisionapp.com/share/F9VXQ7IMZGY/#/screens/406802250) (Only UI part). For this part, no need to implement API calls and routing, the task can be done with mocked data. Use [`<ErrorBoundary>`](https://reactjs.org/docs/error-boundaries.html) component for catching and displaying errors . You could create one component and wrap all your application or use several components. **Evaluation criteria** 2 - Markup is done with React Components and React Fragments (parent-child) 3 - Apply styles (no need to do pixel perfect and strict colors following) 4 - Use PropTypes 5 - Use <ErrorBoundary> component for catching and displaying errors --- ### Task 2: Webpack Create package.json file and install React, Redux, React-Redux, React-Router, Jest. Install and configure Webpack & Babel to get build artifact by running npm command. Set DEV and PROD build configuration. Use env variables, dev server, optimizations for PROD build. Set up testing. You should have test command in your package.json file, which will run your future tests. Don’t use any React boilerplate (like create-react-app) for this task. **Evaluation criteria** 2 - Installed React, Redux, React-Redux, React-Router, Jest 3 - Configured Webpack 4 - Configured Babel. Configured tests script 5 - Have DEV and PROD build commands (use env variables) <file_sep>import styled, { css } from "styled-components"; export const GenresWrapper = styled.div` display: flex; flex-wrap: wrap; justify-content: center; `; export const Genre = styled.span` ${({ active, theme }) => css` position: relative; top: 3px; display: flex; justify-content: center; align-items: center; min-width: 50px; height: 50px; padding: ${active ? "20px" : "20px 20px 23px"}; text-transform: uppercase; color: ${theme.colors.white}; font-size: 1rem; border-bottom: ${active && `3px solid ${theme.colors.beige.light}`}; cursor: pointer; &:hover { background-color: ${theme.colors.vinous.dark}; } `} `; <file_sep>export const colors = { white: "#FFFFFF", black: "#000000", red: "#FF0000", green: "#008000", vinous: { dark: "#271315", light: "#422427", original: "#371B1E" }, beige: { dark: "#E0B578", light: "#FFDFB4", original: "#FFD397" }, brown: { dark: "#150B0D", light: "#301D1F", original: "#1E0F12" }, orange: { light: "#E0D7C6", original: "#FFD486" }, grey: { dark: "#4C4C4C", light: "#9E9E9E", original: "#909090" }, transparent: { black_04: "rgba(0, 0, 0, 0.4)", black_05: "rgba(0, 0, 0, 0.5)", black_08: "rgba(0, 0, 0, 0.8)", black_09: "rgba(0, 0, 0, 0.9)", white_08: "rgba(255, 255, 255, 0.8)" } }; <file_sep>import { css } from "styled-components"; export const ResetStyles = css` * { margin: 0; padding: 0; box-sizing: border-box; list-style: none; outline: 0; // TODO: Think about accessibility. font-family: "Cabin", Arial, sans-serif; } `; <file_sep>import React, { useCallback } from "react"; import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import { func, string } from "prop-types"; import { MODAL_TYPES } from "consts"; import { moviesSortByType } from "types"; import { alertShow, addMovieByData, getMoviesByParams, requestMoviesSuccess } from "actions"; import UpdateMovieFields from "components/modals/shared/updateMovieFields"; import { ModalMovieWrapper, ModalTitle } from "components/modals/shared/styles/modals.styled"; const AddMovieModal = ({ moviesSortBy, onMovieAdd, searchValue, activeGenre, onNewMoviesUpdate, onAddingSubmit, onAlertShow, onMoviesNotFound }) => { const handleAddMovieSubmit = useCallback( async (values) => { await onMovieAdd(values); onAddingSubmit(); if (searchValue) { await onNewMoviesUpdate({ sortBy: moviesSortBy, search: searchValue, searchBy: "title", filter: activeGenre }); } else { onMoviesNotFound([]); } onAlertShow(); }, [moviesSortBy, searchValue, activeGenre, onAddingSubmit] ); return ( <ModalMovieWrapper> <ModalTitle>Add movie</ModalTitle> <UpdateMovieFields type={MODAL_TYPES.ADD_MOVIE} onFieldsSubmit={handleAddMovieSubmit} /> </ModalMovieWrapper> ); }; AddMovieModal.propTypes = { moviesSortBy: moviesSortByType, searchValue: string, activeGenre: string, onMovieAdd: func, onNewMoviesUpdate: func, onAddingSubmit: func, onAlertShow: func, onMoviesNotFound: func }; const mapStateToProps = (state) => ({ moviesSortBy: state.app.moviesSortBy, searchValue: state.app.searchValue, activeGenre: state.app.activeGenre }); const mapDispatchToProps = (dispatch) => ({ onMovieAdd: bindActionCreators(addMovieByData, dispatch), onNewMoviesUpdate: bindActionCreators(getMoviesByParams, dispatch), onAlertShow: bindActionCreators(alertShow, dispatch), onMoviesNotFound: bindActionCreators(requestMoviesSuccess, dispatch) }); export default connect(mapStateToProps, mapDispatchToProps)(AddMovieModal); <file_sep>import * as actions from "actions/modalsActions"; import * as types from "consts/actions"; import { MODAL_TYPES } from "consts"; describe("Modals Actions testing", () => { it("should create an action to set modal values", () => { const modalValues = { title: "Title" }; const values = { values: modalValues, modalType: MODAL_TYPES.ADD_MOVIE }; const expectedAction = { type: types.SET_MODAL_VALUES, payload: values }; expect(actions.setModalValues(modalValues, MODAL_TYPES.ADD_MOVIE)).toEqual(expectedAction); }); }); <file_sep>import React from "react"; import { Switch, Route } from "react-router-dom"; import { PATHS } from "consts"; import Home from "routes/Home"; import Movie from "routes/Movie"; import NotFound from "routes/NotFound"; const Routes = () => ( <Switch> <Route exact path={PATHS.HOME} component={Home} /> <Route path={PATHS.MOVIE} component={Movie} /> <Route path={PATHS.RESULTS} component={Home} /> <Route component={NotFound} /> </Switch> ); export default Routes; <file_sep>import { modalsReducer } from "reducers/modalsReducer"; import { modalsDefaultState } from "reducers/defaultStates"; import * as types from "consts/actions"; import { MODAL_TYPES } from "consts"; describe("Modals Reducer testing", () => { it("should return the initial state", () => { expect(modalsReducer(undefined, {})).toEqual(modalsDefaultState); }); it("should handle SET_MODAL_VALUES", () => { const expectedState = { [MODAL_TYPES.ADD_MOVIE]: { title: "Movie" } }; const action = { type: types.SET_MODAL_VALUES, payload: { values: { title: "Movie" }, modalType: MODAL_TYPES.ADD_MOVIE } }; expect(modalsReducer({}, action)).toEqual(expectedState); }); }); <file_sep>export { default } from "./deleteMovieModal"; <file_sep>import React from "react"; import { bool, func } from "prop-types"; import Button from "components/shared/button"; import { AlertContainer, AlertWrapper, AlertText, StyledButton } from "components/shared/alert/alert.styled"; const ERROR_MESSAGE = "Oops! Something went wrong."; const SUCCESS_MESSAGE = "Operation completed successfully."; const Alert = ({ show, isError, onClose: handleClose }) => ( <AlertContainer show={show}> <AlertWrapper> <AlertText>{isError ? ERROR_MESSAGE : SUCCESS_MESSAGE}</AlertText> <Button onClick={handleClose}>OK</Button> </AlertWrapper> </AlertContainer> ); Alert.propTypes = { isError: bool, show: bool, onClose: func }; export default Alert; <file_sep>import axios from "axios"; import { ALL_GENRES_OPTION } from "consts"; import { CLEAR_REQUEST_RESULT, REQUEST_MOVIES_SUCCESS, REQUEST_MOVIES_ERROR } from "consts/actions"; const moviesUrl = "http://localhost:4000/movies"; const defaultSortOrder = "desc"; export const getMoviesByParams = (params) => async (dispatch) => { try { if (params.filter === ALL_GENRES_OPTION.value) { delete params.filter; } const response = await axios.get(moviesUrl, { params: { ...params, sortOrder: params.sortOrder || defaultSortOrder } }); const movies = response.data; dispatch(requestMoviesSuccess(movies.data)); } catch (e) { dispatch(requestMoviesError()); } }; export const addMovieByData = (data) => async (dispatch) => { try { await axios.post(moviesUrl, { ...data, runtime: +data.runtime || 0, genres: data.genres.map((genre) => genre.value) }); } catch (e) { dispatch(requestMoviesError()); } }; export const deleteMovieById = (id) => async (dispatch) => { try { await axios.delete(`${moviesUrl}/${id}`, { id }); } catch (e) { dispatch(requestMoviesError()); } }; export const getMovieById = (id) => async (dispatch) => { try { const response = await axios.get(`${moviesUrl}/${id}`, { id }); const movie = response.data; dispatch(requestMoviesSuccess([movie])); } catch (e) { dispatch(requestMoviesError()); } }; export const updateMovieByData = (data) => async (dispatch) => { try { const updatedData = { ...data }; Object.keys(updatedData).forEach((key) => !updatedData[key] && delete updatedData[key]); await axios.put(moviesUrl, { ...updatedData, runtime: +updatedData.runtime || 0, genres: updatedData.genres.map((genre) => genre.value) }); } catch (e) { dispatch(requestMoviesError()); } }; export const requestMoviesSuccess = (movies) => ({ type: REQUEST_MOVIES_SUCCESS, payload: movies }); export const requestMoviesError = (error) => ({ type: REQUEST_MOVIES_ERROR, payload: error }); export const clearRequestResult = () => ({ type: CLEAR_REQUEST_RESULT }); <file_sep>import { buttonSizes } from "assets/styles/theme/buttonSizes.styled"; import { colors } from "assets/styles/theme/colors"; import { buttonColors } from "assets/styles/theme/buttonColors.styled"; export const theme = { colors, buttonSizes, buttonColors }; <file_sep>import { appReducer } from "reducers/appReducer"; import * as types from "consts/actions"; import { SORT_BY_DEFAULT_VALUE, ALL_GENRES_OPTION, SORT_BY_VALUES } from "consts"; describe("App Reducer testing", () => { it("should return the initial state", () => { const initialState = { moviesSortBy: SORT_BY_DEFAULT_VALUE, alertShown: false, searchValue: "", activeGenre: ALL_GENRES_OPTION.value }; expect(appReducer(undefined, {})).toEqual(initialState); }); it("should handle SET_MOVIES_SORT_BY", () => { const expectedState = { moviesSortBy: "vote_average" }; const action = { type: types.SET_MOVIES_SORT_BY, payload: SORT_BY_VALUES.RATING.value }; expect(appReducer({}, action)).toEqual(expectedState); }); it("should handle ALERT_SHOW", () => { const expectedState = { alertShown: true }; const action = { type: types.ALERT_SHOW }; expect(appReducer({}, action)).toEqual(expectedState); }); it("should handle ALERT_HIDE", () => { const expectedState = { alertShown: false }; const action = { type: types.ALERT_HIDE }; expect(appReducer({}, action)).toEqual(expectedState); }); it("should handle CHANGE_SEARCH_VALUE", () => { const searchValue = "Movie"; const expectedState = { searchValue }; const action = { type: types.CHANGE_SEARCH_VALUE, payload: searchValue }; expect(appReducer({}, action)).toEqual(expectedState); }); it("should handle CHANGE_ACTIVE_GENRE", () => { const activeGenre = "Adventure"; const expectedState = { activeGenre }; const action = { type: types.CHANGE_ACTIVE_GENRE, payload: activeGenre }; expect(appReducer({}, action)).toEqual(expectedState); }); }); <file_sep>import React from "react"; import { bool, object, string } from "prop-types"; import { StyledInput } from "components/shared/input/input.styled"; const Input = ({ className, primary = false, rounded = false, ...props }) => ( <StyledInput className={className} primary={primary} rounded={rounded} {...props} /> ); Input.propTypes = { className: string, primary: bool, rounded: bool, props: object }; export default Input; <file_sep>import { ALERT_SHOW, ALERT_HIDE, CHANGE_SEARCH_VALUE, CHANGE_ACTIVE_GENRE, SET_MOVIES_SORT_BY } from "consts/actions"; export const setMoviesSortBy = (newSortByValue) => ({ type: SET_MOVIES_SORT_BY, payload: newSortByValue }); export const alertShow = () => ({ type: ALERT_SHOW }); export const alertHide = () => ({ type: ALERT_HIDE }); export const changeSearchValue = (newValue) => ({ type: CHANGE_SEARCH_VALUE, payload: newValue }); export const changeActiveGenre = (newGenre) => ({ type: CHANGE_ACTIVE_GENRE, payload: newGenre }); <file_sep>import React from "react"; import FindMovieSection from "components/findMovieSection"; import ResultsSection from "components/resultsSection"; const Home = () => ( <> <FindMovieSection /> <ResultsSection /> </> ); export default Home;
92feab690513c27131ee23b2ff5e13fe17be1d23
[ "JavaScript", "Markdown" ]
70
JavaScript
melk0sha/movies-ui
20897679c2fc70a4bb5c33b62642af90afd5ea8e
996246d4ef1fbb941d5a37808a3b11a8fb0be9ce
refs/heads/master
<repo_name>davidbordeleau/rails-mister-cocktail<file_sep>/app/models/dose.rb class Dose < ApplicationRecord belongs_to :cocktail belongs_to :ingredient validates :cocktail_id, :ingredient_id, :description, :presence => true validates :ingredient_id, uniqueness: { scope: :cocktail_id } end <file_sep>/db/seeds.rb # 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 rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) url = "http://www.allcocktails.net/gallery/moloko-plus-cocktail/moloko-plus-cocktail.jpg" # Character.create(name: 'Luke', movie: movies.first) Ingredient.create(name: "lemon") Ingredient.create(name: "ice") Ingredient.create(name: "mint leaves") b = Cocktail.create(name: "B & B") b.remote_photo_url = url b.save a = Cocktail.create(name: "The Blenheim") a.remote_photo_url = url a.save c = Cocktail.new(name: "Blow my Skull Off") c.remote_photo_url = url c.save
53b66dd23464b413c11e862459fa047cdc2e6d27
[ "Ruby" ]
2
Ruby
davidbordeleau/rails-mister-cocktail
7aab27ce8315935a0c19e515b3d081efddd24ccb
141dbd16b1a6c8c9b6395f50ea115322e20239bb
refs/heads/main
<repo_name>cojocarion/patterns<file_sep>/src/Adapter.java import java.util.ArrayList; import java.util.List; interface Shape { void draw(); void resize(); String description(); boolean isHide(); } class Rectangle implements Shape { @Override public void draw() { System.out.println("Desenare Dreptunghi"); } @Override public void resize() { System.out.println("Redimensionare dreptunghi"); } @Override public String description() { return "Obiect dreptunghiular"; } @Override public boolean isHide() { return false; } } class Circle implements Shape { @Override public void draw() { System.out.println("Desenare Cerc"); } @Override public void resize() { System.out.println("Redimensionare cerc"); } @Override public String description() { return "Obiect cerc"; } @Override public boolean isHide() { return false; } } class Drawing { List<Shape> shapes = new ArrayList<Shape>(); public Drawing() { super(); } public void addShape(Shape shape) { shapes.add(shape); } public List<Shape> getShapes() { return new ArrayList<Shape>(shapes); } public void draw() { if (shapes.isEmpty()) { System.out.println("Nimic de desenat!"); } else { shapes.stream().forEach(shape -> shape.draw()); } } public void resize() { if (shapes.isEmpty()) { System.out.println("Nimic de redimensionat!"); } else { shapes.stream().forEach(shape -> shape.resize()); } } } public class Adapter { public static void main(String[] args) { System.out.println("Crearea desenului de forme ... "); Drawing drawing = new Drawing(); drawing.addShape(new Rectangle()); drawing.addShape(new Circle()); System.out.println("Desenare..."); drawing.draw(); System.out.println("Redimensionare..."); drawing.resize(); } } <file_sep>/src/Bridge.java import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; abstract class Vehicle { protected List<WorkShop> workshops = new ArrayList<WorkShop>(); public Vehicle() { super(); } public boolean joinWorkshop(WorkShop workshop) { return workshops.add(workshop); } public abstract void manufacture(); public abstract int minWorkTime(); } class Bike extends Vehicle { @Override public void manufacture() { System.out.println("Manufactoring Bike..."); workshops.stream().forEach(workshop -> workshop.work(this)); System.out.println("Done."); System.out.println(); } @Override public int minWorkTime() { return 5; } } class Car extends Vehicle { @Override public void manufacture() { System.out.println("Manufactoring Car"); workshops.stream().forEach(workshop -> workshop.work(this)); System.out.println("Done."); System.out.println(); } @Override public int minWorkTime() { return 10; } } class Bus extends Vehicle { @Override public void manufacture() { System.out.println("Manufactoring Bus"); workshops.stream().forEach(workshop -> workshop.work(this)); System.out.println("Done."); System.out.println(); } @Override public int minWorkTime() { return 20; } } abstract class WorkShop { public abstract void work(Vehicle vehicle); } class ProduceWorkShop extends WorkShop { public ProduceWorkShop() { super(); } @Override public void work(Vehicle vehicle) { System.out.print("Producing... "); long timeToTake = 300 * vehicle.minWorkTime(); try { TimeUnit.MILLISECONDS.sleep(timeToTake); } catch (InterruptedException exp) { //some } System.out.printf("(Time taken: %d millis), Done.\n", timeToTake); } } class AssembleWorkShop extends WorkShop { public AssembleWorkShop() { super(); } @Override public void work(Vehicle vehicle) { System.out.print("Assembling... "); long timeToTake = 200 * vehicle.minWorkTime(); try { TimeUnit.MILLISECONDS.sleep(timeToTake); } catch (InterruptedException exp) { // nothing to do for now. } System.out.printf("(Time taken: %d millis), Done.\n", timeToTake); } } class PaintWorkShop extends WorkShop { public PaintWorkShop() { super(); } @Override public void work(Vehicle vehicle) { System.out.print("Painting... "); long timeToTake = 100 * vehicle.minWorkTime(); try { TimeUnit.MILLISECONDS.sleep(timeToTake); } catch (InterruptedException exp) { // nothing to do for now. } System.out.printf("(Time taken: %d millis), Done.\n", timeToTake); } } class RepairWorkShop extends WorkShop { public RepairWorkShop() { super(); } @Override public void work(Vehicle vehicle) { System.out.print("Repairing... "); long timeToTake = 150 * vehicle.minWorkTime(); try { TimeUnit.MILLISECONDS.sleep(timeToTake); } catch (InterruptedException exp) { // nothing to do for now. } System.out.printf("(Time taken: %d millis), Done.\n", timeToTake); } } class TestWorkShop extends WorkShop { public TestWorkShop() { super(); } @Override public void work(Vehicle vehicle) { System.out.print("Testing... "); long timeToTake = 50 * vehicle.minWorkTime(); try { TimeUnit.MILLISECONDS.sleep(timeToTake); } catch (InterruptedException exp) { } System.out.printf("(Time taken: %d millis), Done.\n", timeToTake); } } public class Bridge { public static void main(String[] args) { Vehicle bike = new Bike(); bike.joinWorkshop(new ProduceWorkShop()); bike.joinWorkshop(new AssembleWorkShop()); bike.joinWorkshop(new TestWorkShop()); bike.manufacture(); Vehicle car = new Car(); car.joinWorkshop(new ProduceWorkShop()); car.joinWorkshop(new AssembleWorkShop()); car.joinWorkshop(new PaintWorkShop()); car.joinWorkshop(new TestWorkShop()); car.manufacture(); Vehicle bus = new Bus(); bus.joinWorkshop(new RepairWorkShop()); bus.joinWorkshop(new AssembleWorkShop()); bus.joinWorkshop(new TestWorkShop()); bus.manufacture(); } }
054b96c5092add96e47dd7adf0dc9786ee1b8c0c
[ "Java" ]
2
Java
cojocarion/patterns
4aaa788e6128ea4e8d415e79879b24b5e11f8487
2a85aca4d2cb8b14e0115fcfbd6e5c97be09f59b
refs/heads/master
<repo_name>chroder/php-ews<file_sep>/EWSType/SensitivityChoicesType.php <?php /** * Contains EWSType_SensitivityChoicesType. */ /** * Indicates the sensitivity level of an item. * * @package php-ews\Enumerations */ class EWSType_SensitivityChoicesType extends EWSType { /** * Indiciates theat the item is confidential. * * @since Exchange 2007 * * @var string */ const CONFIDENTIAL = 'Confidential'; /** * Indiciates theat the item has a normal sensativity. * * @since Exchange 2007 * * @var string */ const NORMAL = 'Normal'; /** * Indiciates theat the item is personal. * * @since Exchange 2007 * * @var string */ const PERSONAL = 'Personal'; /** * Indiciates theat the item is private. * * @since Exchange 2007 * * @var string */ const PRIVATE_ITEM = 'Private'; /** * Element value. * * @var string */ public $_; /** * Returns the value of this object as a string. * * @return string */ public function __toString() { return $this->_; } }
4d6d1da2c4b50a61ff9d62b9927e5e4d2a9161b9
[ "PHP" ]
1
PHP
chroder/php-ews
9c28da6dc97212572e39895fd654f4983e7bc078
f602bef6981bf69a4ee13e4a6eeee61aef744948
refs/heads/master
<repo_name>ojieprado/userapi<file_sep>/README.md # API Backend Node.js Diagnostic Exam An easy way to get started with a Express server with MySQL with Node.js. ## Features A basic user management system API implementing authentication (login page), CRUD functions, wherein admin can: - Add a new user - Edit a user - Delete a user - View list of all users in the system - Allow multiple users to be removed - User must have fields ## Requirements - [node & npm](https://nodejs.org/en/) - [GitHub Repository](https://github.com/) - [Mysql](https://dev.mysql.com/) ## Installation - `git clone`[userapi] - `cd userapi` - `npm install` - `[start Mysql]` - `run query.sql on db` - `npm start` - optional: include _.env_ in your _.gitignore_ ### User Routes - visit http://localhost:3000 - [POST] /user - Insert one user - [GET] /users - Get all user - [GET] /user/:id - Get User by Id - [PUT] /user/:id - Update one user - [DELETE] /user/:id - Delete one user - [POST] /users - Delete each user<file_sep>/app/controller/auth.controller.js // import User model const User = require('../model/user.model'); const { HASH_STRING } = process.env; // import jsonwebtoken const jwt = require('jsonwebtoken'), const bcrypt = require('bcryptjs'); //DEFINE CONTROLLER FUNCTIONS // User Register function exports.register = (req, res) => { let newUser = new User(req.body); newUser.hash_password = bcrypt.hashSync(req.body.password, 10); newUser.save((err, user) => { if (err) { res.status(500).send({ message: err }); } user.hash_password = <PASSWORD>; res.status(201).json(user); }); }; // User Sign function exports.signIn = (req, res) => { User.findEmail({ email: req.body.email }, (err, data) => { if (err) throw err; if (!data) { res.status(401).json({ message: 'Authentication failed. User not found.' }); } else { bcrypt.compare(req.body.password, data.password, (err, res) => { if (err) { return res.status(401).send({ msg: 'Username or password is incorrect!' }); } if (res) { const token = jwt.sign({ username: result[0].username, userId: result[0].id }, 'SECRETKEY', { expiresIn: '7d' } ); } }); } }; // User Register function exports.loginRequired = (req, res, next) => { if (req.user) { res.json({ message: 'Authorized User, Action Successful!' }); } else { res.status(401).json({ message: 'Unauthorized user!' }); } };<file_sep>/app/model/user.model.js const mySql = require('./db.model'); class User { constructor(user) { this.firstname = user.firstname; this.lastname = user.lastname; this.address = user.address; this.postcode = user.postcode; this.phone = user.phone; this.email = user.email; this.username = user.username; this.password = user.<PASSWORD>; }; // Create New User static insertOne(newUser, result) { mySql.query("INSERT INTO usertbl SET ?", newUser, (err, res) => { if (err) { console.log("error: ", err); result(err, null); return; } result(null, { id: res.insertId, ...newUser }); }); } // FindOne User static findOne(UserId, result) { mySql.query(`SELECT * FROM usertbl WHERE id = ${UserId}`, (err, res) => { if (err) { console.log("error: ", err); result(err, null); return; } if (res.length) { console.log("found User: ", res[0]); result(null, res[0]); return; } result({ msg: "Not_Found" }, null); }); } static findEmail(email, result) { mySql.query(`SELECT * FROM usertbl WHERE email = ${email}`, (err, res) => { if (err) { console.log("error: ", err); result(err, null); return; } if (res.length) { console.log("found User: ", res[0]); result(null, res[0]); return; } result({ msg: "Not_Found" }, null); }); } // Get All User static findAll(result) { mySql.query("SELECT * FROM usertbl", (err, res) => { if (err) { console.log("error: ", err); result(null, err); return; } console.log("usertbl: ", res); result(null, res); }); } // UpdateOne User static updateOne(id, User, result) { mySql.query( "UPDATE usertbl SET email = ?, name = ?, active = ? WHERE id = ?", [User.email, User.name, User.active, id], (err, res) => { if (err) { console.log("error: ", err); result(null, err); return; } if (res.affectedRows == 0) { // not found User with the id result({ msg: "Not_Found" }, null); return; } console.log("updated User: ", { id: id, ...User }); result(null, { id: id, ...User }); } ); } // removeOne User static deleteOne(id, result) { mySql.query("DELETE FROM usertbl WHERE id = ?", id, (err, res) => { if (err) { console.log("error: ", err); result(null, err); return; } if (res.affectedRows == 0) { // not found User with the id result({ kind: "not_found" }, null); return; } console.log("deleted User with id: ", id); result(null, res); }); } // removeEach User static deleteEach(ids, result) { mySql.query("DELETE FROM usertbl WHERE id IN (?)", ids, (err, res) => { if (err) { console.log("error: ", err); result(null, err); return; } console.log(`deleted ${res.affectedRows} usertbl`); result(null, res); }); } }; module.exports = User;<file_sep>/app/model/db.model.js const mysql = require('mysql'); const { DB_HOST, DB_USER, DB_PWD, DB_NAME } = process.env; //local mysql db connection const mysqlDb = mysql.createConnection({ host: DB_HOST, user: DB_USER, password: <PASSWORD>, database: DB_NAME }); mysqlDb.connect((err) => { if (err) { console.log('Error in connection'); throw err; } else { console.log("Database Connected"); } }); module.exports = mysqlDb;<file_sep>/app/controller/user.controller.js const Model = require("../model/user.model"); const { HASH_STRING } = process.env; // Create and Save a new User exports.create = (req, res) => { // Validate request if (!req.body) { res.status(400).send({ message: "Content can not be empty!" }); } // Create a User const User = new User({ firstname: req.body.firstname, lastname: req.body.lastname, address: req.body.address, postcode: req.body.postcode, phone: req.body.phone, email: req.body.email, username: req.body.username, password: <PASSWORD> }); // Save User in the database Model.insertOne(User, (err, data) => { const errMsg = "Error occurred while creating the User."; if (err) res.status(500).send({ message: err.message || errMsg }); else res.send(data); }); }; // Retrieve all Users from the database. exports.findAll = (req, res) => { const errMsg = "Error occurred while retrieving Users."; if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer') || !req.headers.authorization.split(' ')[1]) { return res.status(422).json({ message: "Please provide the token", }); } Model.findAll((err, data) => { if (err) res.status(500).send({ message: err.message || errMsg }); else res.send(data); }); }; // Find a single User with a UserId exports.findOne = (req, res) => { if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer') || !req.headers.authorization.split(' ')[1]) { return res.status(422).json({ message: "Please provide the token", }); } Model.findOne(req.params.UserId, (err, data) => { if (err) { if (err.msg === "Not_Found") { res.status(404).send({ message: `Not found User with id ${req.params.UserId}.` }); } else { res.status(500).send({ message: "Error retrieving User with id " + req.params.UserId }); } } else res.send(data); }); }; // Update a User identified by the UserId in the request exports.updateOne = (req, res) => { // Validate Request if (!req.body) { res.status(400).send({ message: "Content can not be empty!" }); } if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer') || !req.headers.authorization.split(' ')[1]) { return res.status(422).json({ message: "Please provide the token", }); } Model.updateOne( req.params.UserId, new User(req.body), (err, data) => { if (err) { if (err.msg === "Not_Found") { res.status(404).send({ message: `Not found User with id ${req.params.UserId}.` }); } else { res.status(500).send({ message: "Error updating User with id " + req.params.UserId }); } } else res.send(data); } ); }; // Delete a User with the specified UserId in the request exports.deleteOne = (req, res) => { if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer') || !req.headers.authorization.split(' ')[1]) { return res.status(422).json({ message: "Please provide the token", }); } Model.deleteOne(req.params.UserId, (err, data) => { if (err) { if (err.msg === "Not_Found") { res.status(404).send({ message: `Not found User with id ${req.params.UserId}.` }); } else { res.status(500).send({ message: "Could not delete User with id " + req.params.UserId }); } } else res.send({ message: `User was deleted successfully!` }); }); }; // Delete all Users from the database. exports.deleteEach = (req, res) => { if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer') || !req.headers.authorization.split(' ')[1]) { return res.status(422).json({ message: "Please provide the token", }); } Model.deleteEach(req.body.ids, (err, data) => { const errMsg = "Some error occurred while removing all Users."; if (err) res.status(500).send({ message: err.message || errMsg }); else res.send({ message: `All Users were deleted successfully!` }); }); };<file_sep>/query.sql CREATE DATABASE `userdb`; USE `userdb`; CREATE TABLE IF NOT EXISTS `usertbl` ( id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, firstname varchar(50) NOT NULL, lastname varchar(50) NOT NULL, address varchar(250) NOT NULL, postcode varchar(10) NOT NULL, phone varchar(15) NOT NULL, email varchar(50) NOT NULL, username varchar(50) NOT NULL, password varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; <file_sep>/app/routes/index.js module.exports = app => { const User = require("../controller/user.controller"); const Auth = require('../controllers/auth.controller'); // Create a new Customer app.post("/user", User.create); // Retrieve all Customers app.get("/users", Auth.loginRequired, User.findAll); // Retrieve a single Customer with customerId app.get("/user/:id", Auth.loginRequired, User.findOne); // Update a Customer with customerId app.put("/user/:id", Auth.loginRequired, User.updateOne); // Delete a Customer with customerId app.delete("/user/:id", Auth.loginRequired, User.deleteOne); // Create each Customer app.delete("/users", Auth.loginRequired, User.deleteEach); };
3c9d2417f969e4aee8eaedb8bc73c794fcec8b17
[ "Markdown", "SQL", "JavaScript" ]
7
Markdown
ojieprado/userapi
efddae71885b8c687472e83455ea73acaf6393af
594271c7fe80bf27357b68272225a3ac629c99a8
refs/heads/main
<repo_name>senaprojects/BASIC_TKINTER<file_sep>/README.md # BASIC_TKINTER Greet the user by getting input from them.(like Hello...with their name) <file_sep>/ph.py from tkinter import * root=Tk() root.title("GREET USER") root.geometry("300x300") def click(): name=entry.get() show=str("Hello Dear "+ name +"!") mesg['text']=show label=Label(root,text="Enter your name :",font=("times",16)) label.place(x=20,y=20) entry=Entry(root,text="") entry.place(x=175,y=25,width=100,height=20) Button(root,text='click Me',command=click,fg='green',font=('times',16)).place(x=100,y=200) mesg=Label(text="",font=("times",16),fg='blue') mesg.place(x=50,y=100) mainloop()
c2d04f2373e58a0517db2de1c0f9794525aadd72
[ "Markdown", "Python" ]
2
Markdown
senaprojects/BASIC_TKINTER
75e3e98c956b8ebaa863a5d2bdf3af3820ce8807
7537851642ff95dd610d95a41bee3fc1fc390762
refs/heads/master
<file_sep>const service = require("../services/user-service"); class UserController { constructor() {} addUser = async (req, res) => { try { const result = await service.add(req.body); // age password login res.status(201).send(result); } catch (e) { res.status(400).send({ error: e.message }); } }; deleteUser = async (req, res) => { try { await service.del(req.params.id); res.status(201).send(); } catch (e) { res.status(400).send({ error: e.message }); } }; updateUser = async (req, res) => { try { await service.update(req.body); res.status(201).send(); } catch (e) { res.status(400).send({ error: e.message }); } }; getUser = async (req, res) => { try { const result = await service.get(req.params.id); res.send(result); } catch (e) { res.status(400).send({ error: e.message }); } }; getAllUser = async (req, res) => { try { const result = await service.getAll(); res.send(result); } catch (e) { res.status(400).send({ error: e.message }); } }; login = async (req, res) => { try { const result = await service.login(req.body); // password + name res.status(201).send(result); } catch (e) { res.status(400).send({ error: e.message }); } }; logout = async (req, res) => { try { res.send({ responce: "successfully logout" }); } catch (e) { res.status(400).send({ error: e.message }); } }; addPetToUser = async (req, res) => { // Добавления питомца try { const result = await service.addPet(req.body); // name id res.status(201).send(result); } catch (e) { res.status(400).send({ error: e.message }); } }; getUserWithPets = async (req, res) => { //получение всех питомцов пользователя try { const result = await service.getPets(req.params.id); res.status(201).send(result); } catch (e) { res.status(400).send({ error: e.message }); } }; } module.exports = UserController; <file_sep>const Sequelize = require("sequelize"); require('dotenv').config(); //console.log(process.env.host, process.env.user, process.env.database, process.env.password) module.exports = new Sequelize(process.env.database, process.env.user, process.env.password, { dialect: "mysql", host: process.env.host, define: { timestamps: false } });
729858e63929d6bfceaf338fb27ea3b2b1edc0bd
[ "JavaScript" ]
2
JavaScript
Gelelus/CrudWithSequelize
a9df46341f97f0df8a99af724dc37d5cb671fbdd
cb873ff59454204e80425e857f960ed7198e934c
refs/heads/master
<repo_name>MrSlimCoder/karachi<file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/3-parsing-url-params/server/index.js // require installed packages import express from 'express'; import middlewareConfig from './config/middleware'; import dbConnect from './config/db'; import { PostRoutes } from './modules'; const port = '3000'; // db connection dbConnect(); // initiate express const app = express(); // middleware middlewareConfig(app); app.use('/api', [PostRoutes]); // render index page app.get('/', function(req, res, next) { res.send('Express REST API Application is running!'); }); // start a server on port 3000 app.listen(port, function() { console.log('server up and running at port ' + port); }); <file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/1-node-express-mongodb/app/car/route.js // get component's controller const ctrl = require('./controller'); // get express module from the node_modules const express = require('express'); // express.Router returns a express Router middleware const router = express.Router(); // we add our own custom middleware in the above middleware router.post('/add',ctrl.insert); // we expose the router as a module module.exports = router;<file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/1-node-express-mongodb/config/dbConnection.js var config = require('./environment'); var mongoose = require('mongoose'); module.exports = function () { mongoose.connect(config.mongoUrl); // get the connection's instance const dbConnection = mongoose.connection; // bind events on connection's instance dbConnection.on('error', function () { console.log('Could not connect to mongodb'); }); dbConnection.once('open', function () { console.log('connected to mongodb'); }); process.on( "SIGINT", shutDown ); process.on( "SIGTERM", shutDown ); process.on( "SIGHUP", shutDown ); } function shutDown() { mongoose.connection.close(function () { console.log('Connection has been successfully closed, see you again soon!'); process.exit(0); }); }<file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/3-parsing-url-params/server/modules/post/controller.js import Post from './model'; export const createPost = async (req, res) => { const { title, description, category, subCategory } = req.body; const newPost = new Post({ title, description, category, subCategory }); try { return res.status(201).json({ post: await newPost.save() }) } catch(e) { return res.status(e.status).json({ error: true, message: 'Error with Post' }); } } export const getAllPosts = async (req, res) => { const params = req.query; console.log('Query Params Object:', params); try { return res.status(200).json({ posts: await Post.find({ ...params }) }); } catch (e) { return res.status(e.status).json({ error: true, message: 'Error with Post' }); } } export const getPost = async (req, res) => { console.log('URL Params Object:', req.params) const { id } = req.params try { return res.status(200).json({ posts: await Post.find({ _id: id }) }); } catch (e) { return res.status(e.status).json({ error: true, message: 'Error with Post' }); } }<file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/3-parsing-url-params/README.md ## Parsing URL Params and sending back appropriate data ## Name: <NAME> ## Slides: http://slides.com/tehseensiddiq/parsing-url-params<file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/4-file-uploads-multer/core/controllers/files.js module.exports = { fileUpload: fileUpload } function fileUpload (req, res, next) { res.json({ success: true, msg: 'file(s) upload successful' }) } <file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/3-parsing-url-params/server/modules/post/index.js import Post from './model'; import PostRoutes from './routes'; export { PostRoutes, Post };<file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/1-node-express-mongodb/app.js // require installed packages const dbConnection=require('./config/dbConnection'); const config = require('./config/environment'); const express = require('express'); // connect with the database dbConnection(); // initiate express const app = express(); // c require('./app/app')(app); // start a server on port 3000 app.listen(config.port,function(){ console.log('server up and running at port '+config.port); })<file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/2-parsing-json-payload/README.md # Parsing JSON payload and saving data in MongoDB # nodeschool-workshop # Name: <NAME> # Slides: https://slides.com/adeelhussain/parsing-data-and-save-into-mongodb/ <file_sep>/README.md # NodeSchool Karachi [![Join the chat at https://gitter.im/nodeschool/karachi](https://badges.gitter.im/nodeschool/karachi.svg)](https://gitter.im/nodeschool/karachi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) **We will be having links related to our meetup/events here in the [events](https://github.com/nodeschool/karachi/events) folder in this repo** NodeSchool is a series of open source workshops that teach web software skills. Individuals are encouraged to do the [workshoppers](http://nodeschool.io/) on their own or at one of the NodeSchool events around the world. The workshopper tutorials are used as the course curriculum, while mentors are here to help attendees work through challenges. * Website: [https://nodeschool.io/karachi/](https://nodeschool.io/karachi/) * Facebook: **[@nskarachi](https://web.facebook.com/nskarachi/)** * Gitter: [https://gitter.im/nodeschool/karachi](https://gitter.im/nodeschool/karachi) ## Want to attend? Keep your self up to date with our [Facebook](https://web.facebook.com/nskarachi/) page for event updates. ### Want to mentor or help organize? If you are interested in mentoring, please make a [Pull Request](https://github.com/nodeschool/karachi/pulls) to add yourself to this list. We also ask you to read over [Event Mentor Best Practices](https://github.com/nodeschool/organizers/wiki/Event-Mentor-Best-Practices) on what it's like being a mentor prior to signing up. Make sure to put some links of your past work! - [@ahsanayaz](https://github.com/ahsanayaz) - [@smkamranqadri](https://github.com/smkamranqadri) - [@farazmurtaza](https://github.com/farazmurtaza) - [@saadqamar](https://github.com/SaadQamar01) If you've come to a few NodeSchool events, we encourage you to mentor! :tada: ### Code of Conduct - [Code of Conduct for Nodeschool Karachi](code-of-conduct.md) - [No photography without an individual's permission](https://adainitiative.org/2013/07/another-way-to-attract-women-to-conferences-photography-policies/) <file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/4-file-uploads-multer/README.md ## Understanding and implementing File Uploads with multer Slides: https://slides.com/aitchkhan/express-file-upload Presenter: <NAME> #Express File Upload Using Multer with DiskStorage option<file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/3-parsing-url-params/server/config/db.js import mongoose from 'mongoose'; const mongoUrl = 'mongodb://localhost/test'; export default () => { // establish db connection mongoose.connect(mongoUrl); mongoose.connection .once('open', function() { console.log('MongoDB running'); }) .on('error', function(err) { console.error(err); }); }; <file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/1-node-express-mongodb/README.md nodeschool-workshop name: <NAME> slides: https://slides.com/bilalalam/deck#/ <file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/2-parsing-json-payload/config/db.js var mongoose = require("mongoose"); var mongoUrl = 'mongodb://localhost/test'; module.exports = function () { mongoose.connect(mongoUrl); mongoose.connection .once('open', function () { console.log('MongoDB running'); }) .on('error', function (err) { console.log(err); }); }; <file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/2-parsing-json-payload/public/javascripts/main.js var $userForm = $('#userForm'); var $submitBtn = $('#saveBtn'); $userForm.on('submit', function (evt){ evt.preventDefault(); var nameField = $('#userName').val(); var age = $('#age').val(); if( !nameField || !age ) return; $submitBtn.attr('default', true ); callAjax({ url: "/users", method: "post", data: { name: nameField, age: age } }) .then(function (){ alert('Added successfully!'); //Empty the form field $('#userName').val(''); $('#age').val(''); }, function (err){ console.log('ERROR in saving user', err); }) .always(function (){ $submitBtn.attr('default', false); }) /* .always(function (){ $submitBtn.attr('default', false); }) .success(function (){ alert('Added successfully!'); }).error(function (err){ console.log('ERROR in saving user', err); }) */; return false; }) function callAjax(config){ return $.ajax({ url: config.url, method: config.method, data: config.data }); } function getUsers (){ }<file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/4-file-uploads-multer/core/middlewares/files.js const path = require('path') const multer = require('multer') const mimeType = require('mime-types') const uploadDir = path.join(__dirname, '../../tmp/') const storage = multer.diskStorage({ filename: (req, file, cb) => { const ext = mimeType.extension(file.mimetype) cb(null, `file-${Date.now()}.${ext}`) }, destination: (req, file, cb) => { cb(null, uploadDir) } }) const upload = multer({ storage: storage }) const uploadPicture = multer({ storage: storage, fileFilter: _imgFilter }) module.exports = { uploadSingle, uploadArray, uploadFields, uploadProfilePic } function uploadSingle () { return upload.single('file') } function uploadArray () { return upload.array('files', 4) // first param is for key against which the multer is expecting files, // other is maxCount allowed } function uploadFields () { return upload.fields({ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 5 }) } function uploadProfilePic () { return uploadPicture.single('image') } function _imgFilter (req, file, cb) { if (!file.originalname.match(/\.(png|jpeg|jpg|gif)/)) { cb(new Error('Only images are allowed'), false) // setting the second param } cb(null, true) } <file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/3-parsing-url-params/server/modules/post/routes.js import { Router } from 'express'; import * as PostController from './controller'; const routes = new Router(); // Route for creating post routes.post('/post', PostController.createPost); // Route for getting all Posts routes.get('/post', PostController.getAllPosts); // Route for getting single Post with the help of Url Param routes.get('/post/:id/:test', PostController.getPost); export default routes; <file_sep>/events/meetup-2__rest-apis-workshop/workshop-content/1-node-express-mongodb/app/car/controller.js // import the component's model const Car=require('./model'); // expose a set of operations module.exports = { insert : (req,res)=>{ // create a new instance of the model const car = new Car({ model:'2000', name:'Mehran', color:'purple' }); // call save funtion on that model's instance car.save((err)=>{ if(err){ // return error res.status(500).json({message :"something went wrong"}); }else{ // return success res.status(200).json({message:"car added successfully"}); } }); } }
b99a77a10a350cb192be3640eea47ae6db9373ee
[ "JavaScript", "Markdown" ]
18
JavaScript
MrSlimCoder/karachi
5aaaebf1c40308f24db049e0bb0f724664fd17b8
9a667178184a8e6a8ed2fa8fb5e7ea84ecaa832f
refs/heads/master
<file_sep>import re from os.path import basename, splitext, dirname class LArgsParserException(Exception): pass def without_extension(text): result, _ = splitext(text) return result def extension(text): _, result = splitext(text) return result class LArgsParser(object): def __init__(self, template, delimiter, begin_bracket, end_bracket): self.delimiter = delimiter self.template = template self.subs_pattern = re.compile("\\"+begin_bracket + r'[^\''+begin_bracket+']*' + "\\"+end_bracket) functions = { 'b': basename, 'e': without_extension, 'E': extension, 'd': dirname, } def _parse(self, expression, text, text_tokens): operations = re.findall(r'(\d+|\w)', expression) result = text for op in operations: if op.isdecimal(): op = int(op) result = text_tokens[op - 1] if op <= len(text_tokens) else '' else: if op in self.functions: result = self.functions[op](result) else: raise LArgsParserException('Invalid operation: {}'.format(op)) return result expr_match = self.expressions_pattern.match(expression) if not expr_match: raise LArgsParserException("Invalid expression: {}".format(expression)) t_index, t_basename, t_ext = expr_match.groups() if t_index != '': t_index = int(t_index) if t_index >= len(text_tokens) + 1: return '' result = text_tokens[t_index - 1] else: result = text if t_basename: result = basename(result) if t_ext: result, _ = splitext(result) return result def sub(self, text): text_tokens = text.split(self.delimiter) def repl(match): expression = match.group(0) return self._parse(expression, text, text_tokens) # print(text, ',', self.template) # print(self.subs_pattern) return self.subs_pattern.sub(repl, self.template) <file_sep>from setuptools import setup setup( name='largs', version='0.0.1', packages=['lpargs'], url='', license='', author='nikita', author_email='', description='', entry_points={ 'console_scripts': [ 'largs = lpargs.cli:main' ] } ) <file_sep>from __future__ import absolute_import import argparse from argparse import Namespace import sys from collections import deque from lpargs.parser import LArgsParser from shlex import quote def parse_args(): raw_args = deque(sys.argv) args = Namespace(brackets='{}', delimiter=',', template=[]) raw_args.popleft() while raw_args: arg = raw_args.popleft() if arg in {'-d', '--delimiter'}: args.delimiter = raw_args.popleft() elif arg in {'-b', '--brackets'}: args.brackets = raw_args.popleft() else: args.template = [arg] + list(raw_args) break return args def main(): args = parse_args() template = ' '.join( quote(arg).replace('\-', '-') for arg in args.template ) begin_bracket, end_bracket = args.brackets parser = LArgsParser( template=template, delimiter=args.delimiter, begin_bracket=begin_bracket, end_bracket=end_bracket, ) for line in sys.stdin: line = line.strip() res = parser.sub(line) print(res) if __name__ == '__main__': main()
bd36ba0ad2cf74fca8074706aade65cbd54efacd
[ "Python" ]
3
Python
lpenguin/lpargs
87b20c948ec345aca817bc73fd21f00dedc1b5a6
4f2a7abc581a6c9c77f27bf9872a06f840b03d78
refs/heads/master
<file_sep>const processDomains = (domainsText) => { return domainsText.split('\n'); } export default processDomains; <file_sep>//made with help from https://gist.github.com/Davidblkx/e12ab0bb2aff7fd8072632b396538560 module.exports = (stringA, stringB) => { if(!stringA || !stringB) { console.log(`Didn't provide 2 strings!`); return; } let matrix = []; for(let i = 0; i <= stringA.length; i++) { let newArray = []; newArray.length = stringB.length+1; matrix.push(newArray); } if(!stringA.length > 0) return stringB.length; if(!stringB.length > 0) return stringA.length; for (let i = 0; i <= stringA.length; matrix[i][0] = i++) { } for (let j = 0; j <= stringB.length; matrix[0][j] = j++) { } //console.log('matrix', matrix); for (let i = 0; i < stringA.length; i++) { for (let j = 0; j < stringB.length; j++) { let cost = stringB[j] === stringA[i] ? 0 : 1; matrix[i+1][j+1] = Math.min( Math.min(matrix[i][j+1] + 1, matrix[i+1][j] + 1), matrix[i][j] + cost); } } return matrix[stringA.length][stringB.length]; } // // Initialization of matrix with row size source1Length and columns size source2Length // for (var i = 0; i <= source1Length; matrix[i, 0] = i++) { } // for (var j = 0; j <= source2Length; matrix[0, j] = j++) { } // // Calculate rows and collumns distances // for (var i = 1; i <= source1Length; i++) // { // for (var j = 1; j <= source2Length; j++) // { // var cost = (source2[j - 1] == source1[i - 1]) ? 0 : 1; // matrix[i, j] = Math.Min( // Math.Min(matrix[i - 1, j] + 1, matrix[i, j - 1] + 1), // matrix[i - 1, j - 1] + cost); <file_sep>import { useState } from 'react'; import styled from 'styled-components'; import api from './utilities/api'; import processDomains from './utilities/processDomains'; const App = () => { const [domainsText, setDomainsText] = useState(''); const [domains, setDomains] = useState([]); const [results, setResults] = useState(null); const handleChangeDomainsText = (newDomainsText) => { setDomainsText(newDomainsText); setDomains(processDomains(newDomainsText)); } const handleSubmit = async () => { const results = await api.analyzeDomains(domains) .then(res => { setResults(res.data); }) .catch(err => { console.log('err', err); }); } return ( <Container> <LeftContainer> <h1>Domain-analyzer</h1> <DomainsTextArea value={domainsText} onChange={e => handleChangeDomainsText(e.target.value)} /><br /> <button onClick={handleSubmit} disabled={domains.length === 0} > Check Domains </button> </LeftContainer> <RightContainer> <h3>Results</h3> <Divider /> {results && results.map((result, index) => ( <ResultContainer key={index}> <span><b>{result.checkedDomain}</b> != {result.safeDomain}</span><br /> <span style={{ fontSize: 12 }}> Levenshtein Distance: {result.distance} </span> </ResultContainer> )) } </RightContainer> </Container> ); } export default App; const Container = styled.div` display: flex; flex-wrap: wrap; `; const LeftContainer = styled.div` min-width: 360px; display: flex; flex-direction: column; padding: 8px; `; const RightContainer = styled.div` min-width: 360px; display: flex; flex-direction: column; align-items: stretch; padding: 8px; `; const Divider = styled.div` width: 100%; height: 1px; background-color: rgba(0, 0, 0, .34); margin-bottom: 16px; `; const DomainsTextArea = styled.textarea` `; const ResultContainer = styled.div` padding: 8px; background-color: rgba(255, 80, 80, .3); `;
0b741d5ad8859e569843177a76b4b9d5ea736f05
[ "JavaScript" ]
3
JavaScript
wingfield4/cs6387-domain-distance
9ea8b96a8b908604bd0c09270c625c81cfcf08fb
cfb191a341d956b14d2586a82d11d9243a699c34
refs/heads/master
<repo_name>antony-jr/nextjs<file_sep>/server.js var express = require('express'); var indexRouter = require('./routes/index'); var apiRouter = require('./routes/api') var server = express(); server.use('/', indexRouter); server.use('/api', apiRouter); module.exports = server;<file_sep>/webjs/pages/admin.js import React from 'react'; import Link from 'next/link'; import { withRouter } from 'next/router'; import PlugPrompt from '../plugs/prompt'; class Admin extends React.Component { constructor(props) { super(props); this.state = { menuData: [{ name: '表格增删改查', path: '/learnsql' }, { name: 'demo2', path: '/demo2' }] } } componentDidMount () { const setData = this.state.menuData.map((item) => { item.active = false; if (item.path === this.props.router.route) { item.active = true; } return item; }); this.setState({menuData: setData}); } render() { return ( <div className="plug-admin"> <div className="admin-top"></div> <div className="admin-body"> <div className="menu-warp"> {this.state.menuData.map( (item) => { return ( <Link href={`${item.path}`} key={item.name}> <div className={['item', item.active ? 'active' : ''].join(' ')}> {item.name} </div> </Link> ) })} </div> <div className="slot-content">{this.props.children}</div> </div> <PlugPrompt /> <style jsx>{` .plug-admin { position: absolute; top: 0; left: 0; right: 0; bottom: 0; font-size: 14px; } .admin-top { position: fixed; top: 0; left: 0; right: 0; height: 50px; background: rgb(84, 92, 100); box-sizing: border-box; border-bottom: 5px solid #5FB878; } .admin-body { padding-top: 50px; height: 100%; box-sizing: border-box; } .menu-warp { width: 200px; height: 100%; float: left; box-sizing: border-box; background: rgb(84, 92, 100); color: #fff; } .menu-warp .item { height: 50px; line-height: 50px; padding-left: 30px; cursor: pointer; font-size: 15px; } .menu-warp .item.active { color: rgb(255, 208, 75); } .menu-warp .item:hover { background: rgb(67, 74, 80); } .slot-content { width: calc(100% - 200px); height: 100%; float: right; background: rgb(237, 237, 239); } `}</style> </div> ) } } export default withRouter(Admin); <file_sep>/pages/index - 副本.js // import Header from '../comps/header'; import Admin from '../comps/admin'; import Link from 'next/link'; // import fetch from 'isomorphic-unfetch'; // const PostLink = props => ( // <li> // <Link href={`/post?id=${props.id}`} as={`/p/${props.id}`}> // <a>{props.name}</a> // </Link> // </li> // ) // const Index = (props) => ( // <div> // <Header></Header> // <h1>Batman TV Show</h1> // <ul> // { // props.shows.map(show => ( // <PostLink id={show.id} name={show.name} key={show.id}/> // )) // } // </ul> // </div> // ) // Index.getInitialProps = async function() { // // const res = await fetch('https://api.tvmaze.com/search/shows?q=batman'); // // const data = await res.json(); // const data = [{ // id: 'aa', // name: '第一个' // }, { // id: 'bb', // name: '第二个' // }, { // id: 'cc', // name: '第三个' // }, { // id: 'dd', // name: '第四个' // }] // console.log(`Show data fetched. Count: ${data.length}`); // return { // shows: data.map(entry => entry) // } // } class Index extends React.Component { constructor(props) { super(props); this.state = { menuData: [{ name: '表格增删改查' }, { name: 'demo2' }] } } handleMenuChecked(item) { debugger } render() { return ( <Admin menuData={this.state.menuData} onMenuChecked={this.handleMenuChecked}> admin </Admin> ) } } export default Index<file_sep>/webjs/plugs/formitem.js import React from 'react'; class PlugFormItem extends React.Component { constructor(props) { super(props); } render() { return ( <div className={'form-item'}> <label className={'label'}>{this.props.label + ':'}</label> <div className={'content'}>{this.props.children}</div> <style jsx>{` .form-item { display: inline-block; width: 50%; } .label { width: 70px; display: inline-block; color: #777; text-align: right; padding-right: 12px; font-weight: bold; vertical-align: text-top; } .content { display: inline-block; vertical-align: text-top; } `}</style> </div> ) } } export default PlugFormItem; <file_sep>/pages/index.js import React from 'react'; import Admin from '../webjs/pages/admin'; import Home from '../webjs/pages/home'; class Index extends React.Component { render() { return ( <Admin> <Home /> </Admin> ) } } export default Index<file_sep>/webjs/plugs/dialog.js import React from 'react'; class Dialog extends React.Component { constructor(props) { super(props); } onClose () { this.props.onClose(); } render() { return ( <div className={'plug-dialog'} style={{'display': this.props.visible ? 'block' : 'none'}}> <div className={'mask'}> <div className={'main'}> <div className={'main-header'}> <div className={'title'}>{this.props.title}</div> <div className={'close'} onClick={() => this.onClose()}>x</div> </div> <div className={'main-body'}> {this.props.children} </div> <div>{this.props.footer}</div> </div> </div> <style jsx>{` .plug-dialog .mask { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.6); } .plug-dialog .main { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #fff; } .main-header { height: 48px; line-height: 48px; background: #f7faff; padding: 0 20px; } .main-header .title { } .main-header .close { position: absolute; top: 0; right: 20px; cursor: pointer; font-size: 18px; } `}</style> </div> ) } } export default Dialog; <file_sep>/README.md # nextjs >A next(react)+express+mysql demo ##### 运行步骤: 1.下载项目并进入根目录,初始化项目 `npm install` 2.添加MySQL设置 `打开 /mysql/config.js文件,设置数据库的host、user、password、database以连接数据库。` 3.运行项目 `npm run dev` 4.在浏览器打开 `浏览器地址输入localhost:3000` <file_sep>/routes/api.js var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var sqlConfig = require('../mysql/config'); var connection = mysql.createConnection(sqlConfig); // 获取导航菜单 router.get('/getMenu', (req, res) => { // 手动创建菜单 var sql = `CREATE TABLE IF NOT EXISTS menu_data ( menu_id INT UNSIGNED AUTO_INCREMENT, menu_name VARCHAR(5) NOT NULL, PRIMARY KEY ( menu_id ) )ENGINE=InnoDB DEFAULT CHARSET=utf8;`; connection.query(sql, (err, result) => { if (!err) { } }); // 查询数据 function selectData() { var clSql = `SELECT menu_name FROM menu_data;`; connection.query(clSql, (err, result) => { if (!err) { if (result.length) { res.send(result); } else { var crData = `INSERT INTO menu_data (menu_name) VALUES ('demo1'), ('demo2'); `; connection.query(crData, (err, result) => { if (!err) { selectData(); } }) } } }) } selectData(); }); // 获取数据 router.get('/getData', (req, res) => { // 创建表 let sql = `CREATE TABLE IF NOT EXISTS person_data ( person_id INT UNSIGNED AUTO_INCREMENT, name VARCHAR(10) NOT NULL, sex VARCHAR(5), age VARCHAR(5), des VARCHAR(100), PRIMARY KEY ( person_id ) )ENGINE=InnoDB DEFAULT CHARSET=utf8;`; connection.query(sql, (err, result) => { if (!err) { } }); // 查询表 let querySql = 'SELECT * FROM person_data;'; connection.query(querySql, (err, result) => { if (!err) { res.send(result); } }) }); // 增加一条数据 router.get('/addInfo', (req, res) => { if (req.query.person_id) { delete req.query.person_id; } let key = Object.keys(req.query).join(','); let val = Object.values(req.query).map((e) => `"${e}"`).join(','); let sql = `INSERT INTO person_data (${key}) VALUES (${val}) `; connection.query(sql, (err, result) => { if (!err) { res.send({success: true}); } }) }); // 删除一条数据 router.get('/delInfo', (req, res) => { let sql = `DELETE FROM person_data WHERE person_id=${req.query.id};`; connection.query(sql, (err, result) => { if (!err) { res.send({success: true}); } }) }); // 修改一条数据 router.get('/modInfo', (req, res) => { let id = req.query.person_id; let arr = []; if (req.query.person_id) { delete req.query.person_id; } for (let key in req.query) { arr.push(`${key}="${req.query[key]}"`); } const vals = arr.join(','); let sql = `UPDATE person_data SET ${vals} WHERE person_id=${id};`; connection.query(sql, (err, result) => { if (!err) { res.send({success: true}); } else { console.log(err) } }) }); module.exports = router;<file_sep>/pages/learnsql.js import React from 'react'; import { withRouter } from 'next/router'; import Axios from 'axios'; import Admin from '../webjs/pages/admin'; import PlugTable from '../webjs/plugs/table'; import PlugDialog from '../webjs/plugs/dialog'; import PlugFormItem from '../webjs/plugs/formitem'; class Sql extends React.Component { constructor(props) { super(props); this.state = { thead: [ {label: '姓名', prop: 'name', type: 'default'}, {label: '性别', prop: 'sex', type: 'default'}, {label: '年龄', prop: 'age', type: 'default'}, {label: '描述', prop: 'des', type: 'default'}, {label: '操作', operation: [{name: '修改'}, {name: '删除'}], type: 'operation'} ], tableData: [], dialogTitle: '新增', dialogVisible: false, formData: { name: '', sex: '', age: '', des: '' } } } componentDidMount () { this.getTableData(); } initFormData () { this.setState(Object.assign(this.state.formData, { name: '', sex: '', age: '', des: '' })); } getTableData () { Axios.get('/api/getData').then((res) => { this.setState({tableData: res.data}); }) } handlerClose () { this.setState({dialogVisible: false}); } onOpenDialog () { this.setState({dialogVisible: true}); this.initFormData(); this.setState({dialogTitle: '新增'}); } onConfirm () { if (this.state.dialogTitle === '新增') { let params = this.state.formData; Axios.get('/api/addInfo', {params: params}).then((res) => { if (res.data.success) { // React.$prompt('新增成功!'); } }) } if (this.state.dialogTitle === '修改') { let params = this.state.formData; Axios.get('/api/modInfo', {params: params}).then((res) => { if (res.data.success) { React.$prompt('修改成功!'); } }) } this.getTableData(); this.handlerClose(); } inputVal (label, value) { let obj = {}; obj[label] = value; this.setState(Object.assign(this.state.formData, obj)); } handlerOperation(name, lineData) { if (name === '修改') { this.setState({dialogTitle: name}); this.setState({dialogVisible: true}); this.setState(Object.assign(this.state.formData, lineData)); } if (name === '删除') { const params = { id: lineData.person_id }; Axios.get('/api/delInfo', {params: params}).then((res) => { if (res.data.success) { this.getTableData(); React.$prompt('删除成功!'); } }) } } render() { const dialogFooter = ( <div className={'dialog-footer'}> <button onClick={() => this.setState({dialogVisible: false})}>取消</button> <button onClick={() => this.onConfirm()}>确定</button> <style jsx>{` .dialog-footer { padding: 8px 10px; text-align: right; } button { background: #fff; border: 1px solid #999; border-radius: 3px; padding: 6px 12px; cursor: pointer; out-inline: none; margin-left: 12px; } `}</style> </div> ); const formData = this.state.formData; const dialogContent = ( <div className={'mod-form'}> <div className={'form-line'}> <PlugFormItem label="姓名"> <input type="text" value={formData.name} placeholder="请输入姓名" onChange={(e) => this.inputVal('name', e.target.value)} /> </PlugFormItem> <PlugFormItem label="性别"> <input type="text" value={formData.sex} placeholder="请输入性别" onChange={(e) => this.inputVal('sex', e.target.value)} /> </PlugFormItem> </div> <div> <PlugFormItem label="年龄"> <input type="text" value={formData.age} placeholder="请输入年龄" onChange={(e) => this.inputVal('age', e.target.value)} /> </PlugFormItem> <PlugFormItem label="描述"> <textarea name="" id="" rows="3" value={formData.des} placeholder="请输入描述" onChange={(e) => this.inputVal('des', e.target.value)} ></textarea> </PlugFormItem> </div> <style jsx>{` .mod-form { width: 600px; padding: 40px 30px; } .form-line { margin-bottom: 30px; } input { height: 24px; padding-left: 4px; } textarea,input { width: 175px; border:1px solid #bbb; } `}</style> </div> ); return ( <Admin> <div className="learSql"> <div className={'optWarp'}> <button onClick={() => this.onOpenDialog()}>新增</button> </div> <PlugTable thead={this.state.thead} tableData={this.state.tableData} onOperation={(name, lineData) => this.handlerOperation(name, lineData)} /> <PlugDialog title={this.state.dialogTitle} footer={dialogFooter} children={dialogContent} visible={this.state.dialogVisible} onClose={() => this.handlerClose()} > </PlugDialog> </div> <style jsx>{` .learSql { padding: 100px; } .optWarp { overflow: hidden; padding-bottom: 20px; } .optWarp button { float: right; background: #fff; border: 1px solid #999; border-radius: 3px; padding: 6px 10px; cursor: pointer; } `}</style> </Admin> ) } } export default withRouter(Sql);
8b660bdb1b15b8e4c1b73961f0325d703888586c
[ "JavaScript", "Markdown" ]
9
JavaScript
antony-jr/nextjs
4ad2f0511fc4810a54e399a362457cca9cf52b26
8e5f38272600d41c14f256007d6808448dc0bf48
refs/heads/master
<file_sep>var sesion = false; firebase.auth().onAuthStateChanged(user => { if (user) { console.log('user logged in: ', user); //$('#menuRegistro').append(" <li><img src='" +user.photoURL+ "' id='iconFoto'/></li>"); $('#login').hide(); $('#loginOut').show(); $('#fotoGoogle').append(" <img src='" + user.photoURL + "' id='iconFoto'/>"); $('.info').append("<p><i id='nombreUsuario' class='fas fa-phone-alt'></i> " + user.displayName + "</p>"); $('.info').append("<p><i id='emailUsuario' class='far fa-envelope'></i> " + user.email + "</p>"); $('.registroOculto').show(); usuario = user; guardarDatos(user); sesion = true; } else { console.log('user logged out'); $('#loginOut').hide(); $('#iconFoto').hide(); $('#login').show(); $('.registroOculto').hide(); $('.formulario3').hide(); if (sesion) { location.reload(); sesion = false; } } }) //login var provider = new firebase.auth.GoogleAuthProvider(); var usuario; var urlImagen; var fileButton = document.getElementById("dato9"); //vigilar foto fileButton.addEventListener('change', function (e) { console.log("holllllllla"); //obtener archivo var file = e.target.files[0]; //crear un store ref var storageRef = firebase.storage().ref('mis_fotos/' + file.name); // subir archivo var task = storageRef.put(file); task.then(snapshot => snapshot.ref.getDownloadURL()) .then(url => { urlImagen = url; }) }) //actualiza la galeria al detectar cambios var starCountRef = firebase.database().ref('mascotas/'); starCountRef.on('child_added', (snapshot) => { var ax1 = snapshot.val().fotografia; var ax2 = snapshot.val().estado; var ax3 = snapshot.val().tipo; var ax4 = snapshot.val().color; var ax5 = snapshot.val().tamaño; var ax6 = snapshot.val().ubicacion; var ax7 = snapshot.val().fecha; var ax8 = snapshot.val().telefono; var axxx = ` <div class='foto'> <img class='img-hover' src="${ax1}"> <div class='oculto' > <a class='prueba' title=' <h2 style="margin-top: 20px;margin-bottom: 20px;">Estado: ${ax2}</h2> <h2 style="margin-top: 20px;margin-bottom: 20px;">tamaño: ${ax5}</h2> <h2 style="margin-top: 20px;margin-bottom: 20px;">Dirección: ${ax6}</h2> <h2 style="margin-top: 20px;margin-bottom: 20px;">Fecha: ${ax7}</h2> <h2 style="margin-top: 20px;margin-bottom: 20px;">Telefono: ${ax8}</h2> ' href="${ax1}" data-lightbox='roadtrip'> <img class='img-hover' src="${ax1}" alt=''> </a> </div> </div>`; $("#galeria").append(axxx); $(document).ready(function () { $('.foto').hover(function () { $(this).find('.oculto').fadeIn(); $(this).find('.img-hover').addClass('agrandar'); }, function () { $(this).find('.oculto').fadeOut(); $(this).find('.img-hover').removeClass('agrandar'); }) }) }); //obtiene los datos del formulario (function () { 'use strict'; window.addEventListener('load', function () { // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission var validation = Array.prototype.filter.call(forms, function (form) { form.addEventListener('submit', function (event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } if (form.checkValidity() === true) { var mascota = { tipo: document.getElementById("dato1").value, raza: document.getElementById("dato2").value, estado: document.getElementById("dato3").value, nombre: document.getElementById("dato4").value, edad: document.getElementById("dato5").value, color: document.getElementById("dato6").value, tamaño: document.getElementById("dato7").value, salud: document.getElementById("dato8").value, fotografia: urlImagen, descripcion: document.getElementById("dato10").value, ubicacion: document.getElementById("dato11").value, fecha: document.getElementById("dato12").value, uid: usuario.uid, nombreUsuario: usuario.displayName, emailUsuario: usuario.email, fotoUsuario: usuario.photoURL, telefono: document.getElementById("dato13").value } firebase.database().ref("mascotas/").push(mascota) sw = 0; } form.classList.add('was-validated'); }, false); }); }, false); })(); $('#login').click(function () { firebase.auth() .signInWithPopup(provider) .then((result) => { usuario = result.user; }); }) function guardarDatos(user) { var usuario = { uid: user.uid, nombre: user.displayName, email: user.email, foto: user.photoURL } firebase.database().ref("usuarios/" + user.uid).set(usuario) } $('#loginOut').click(function () { firebase.auth().signOut() .then(function () { console.log('Salir'); }) .catch(function (error) { console.log('error'); }) }) $('.menu-icon').click(function () { $('nav').slideToggle(); }) $('#tipoRegistro1').click(function () { console.log((this).id); document.getElementById("tipoRegistro1").className = "btn btn-success btn-lg active"; document.getElementById("tipoRegistro2").className = "btn btn-secondary btn-lg active"; document.getElementById("tipoRegistro3").className = "btn btn-secondary btn-lg active"; $('#formulario1').show(); $('#formulario3').hide(); }) $('#tipoRegistro2').click(function () { document.getElementById("tipoRegistro1").className = "btn btn-secondary btn-lg active"; document.getElementById("tipoRegistro2").className = "btn btn-success btn-lg active"; document.getElementById("tipoRegistro3").className = "btn btn-secondary btn-lg active"; $('#formulario1').hide(); $('#formulario3').hide(); }) var sw = 0; $('#tipoRegistro3').click(function () { document.getElementById("tipoRegistro1").className = "btn btn-secondary btn-lg active"; document.getElementById("tipoRegistro2").className = "btn btn-secondary btn-lg active"; document.getElementById("tipoRegistro3").className = "btn btn-success btn-lg active"; $('#formulario1').hide(); $('#formulario3').hide(); $('#formulario3').show(); console.log(usuario); //----------------- if (sw == 0) { sw = 1; console.log("esta es la base de datos"); var cont = 0; starCountRef.on('child_added', (snapshot) => { cont = cont + 1; if (snapshot.val().uid == usuario.uid) { var ax1 = snapshot.val().fotografia; var ax2 = snapshot.val().estado; var ax3 = snapshot.val().tipo; var ax4 = snapshot.val().color; var ax5 = snapshot.val().tamaño; var ax6 = snapshot.val().ubicacion; var ax7 = snapshot.val().fecha; var ax8 = snapshot.val().telefono; var aux = ` <div class="ej1"> <img class='imagenForm3' src="${ax1}"> <div class="ej2"> <p class='infMascota'>Estado: ${ax2}</p> <p class='infMascota'>tamaño: ${ax5}</p> <p class='infMascota'>Dirección: ${ax6}</p> <p class='infMascota'>Fecha: ${ax7}</p> <p class='infMascota'>Telefono: ${ax8}</p> <button type="button" class="btn btn-danger">Eliminar</button> </div> </div> `; $("#imagen_de_mascota").append(aux); } }); } //----------------- })
4a15ab7b2b5ec2b2f4b2514be2d0b6548b6676ad
[ "JavaScript" ]
1
JavaScript
RamirezInformation/proyecto-mascotas
e48e5092a8848dea61bec3031d47e543b9a93e84
34da6d1748087e710a81e959fb28cd3edc0d56eb
refs/heads/master
<file_sep><?php namespace AirLST\CoreSdk\Api\Workers\Traits; /** * Trait AirLSTCrudResourceTrait * * @package AirLST\CoreSdk\Api\Workers\Traits * * @author <NAME> <<EMAIL>> */ trait AirLSTCrudResourceTrait { /** * @param $id * @return array|null */ public function find($id): ?array { return $this->doRequest($this->getCrudEntityPath($id)) ? $this->extractDataFromLastResponse() : null; } /** * @param string $path * @return string */ protected function getCrudEntityPath(string $path = ''): string { return rtrim($this->getEntityPrefix(), '/') . '/' . ltrim($path, '/'); } /** * @return string */ abstract protected function getEntityPrefix(): string; /** * @param $id * @param array $dataForUpdate * @return array|null */ public function update($id, array $dataForUpdate): ?array { return $this->doRequest($this->getCrudEntityPath($id), 'PUT', $dataForUpdate) ? $this->extractDataFromLastResponse() : null; } /** * @param array $dataForUpdate * @return array|null */ public function create(array $dataForUpdate): ?array { return $this->doRequest($this->getCrudEntityPath(), 'POST', $dataForUpdate) ? $this->extractDataFromLastResponse() : null; } /** * @param $id * @return array */ public function delete($id): bool { return $this->doRequest( $this->getCrudEntityPath($id), 'DELETE', [ 'force' => true ] ) ? true : false; } } <file_sep><?php namespace AirLST\CoreSdk\Api\Workers; use AirLST\CoreSdk\Api\Abstracts\ApiWorker; use AirLST\CoreSdk\Api\Workers\Traits\AirLSTSoftDeleteResourceTrait; use AirLST\CoreSdk\Api\Workers\Traits\HasFastPipeTrait; /** * Class RsvpWorker * * @package AirLST\CoreSdk\Api\Workers * * @author <NAME> <<EMAIL>> */ class RsvpWorker extends ApiWorker { use AirLSTSoftDeleteResourceTrait, HasFastPipeTrait; protected ?int $guestlistId = null; /** * @param $code * @return array|null * @throws \Throwable */ public function findByCode($code): ?array { return $this->doRequest( 'guestlists/'.$this->guestlistId.'/find-rsvp-by-code', 'GET', [ 'code' => $code ] ) ? $this->extractDataFromLastResponse() : null; } /** * @return string */ protected function getEntityPrefix(): string { return 'rsvps'; } /** * @return string */ protected function getEntityFastPipePrefix(): string { if (!$this->getGuestlistId()) { return 'fp/rsvps'; } else { return 'fp/guestlists/' . $this->getGuestlistId() . '/rsvps'; } } /** * @return int|null */ public function getGuestlistId(): ?int { return $this->guestlistId; } /** * @param int|null $guestlistId * @return RsvpWorker */ public function setGuestlistId(?int $guestlistId): RsvpWorker { $this->guestlistId = $guestlistId; return $this; } } <file_sep><?php namespace AirLST\CoreSdk\Api\Workers\Traits; /** * Trait AirLSTSoftDeleteResourceTrait * * @package AirLST\CoreSdk\Api\Workers\Traits * * @author <NAME> <<EMAIL>> */ trait AirLSTSoftDeleteResourceTrait { use AirLSTCrudResourceTrait; /** * @param $id * @return array|null */ public function archive($id): ?array { return $this->doRequest( $this->getCrudEntityPath($id), 'DELETE', [ 'force' => false ] ) ? $this->extractDataFromLastResponse() : null; } /** * @param $id * @return array|null */ public function restore($id): ?array { return $this->doRequest($this->getCrudEntityPath($id) . '/restore', 'PUT') ? $this->extractDataFromLastResponse() : null; } } <file_sep><?php namespace AirLST\CoreSdk\Facades; use AirLST\CoreSdk\Api\Workers\BbbRoomWorker; use AirLST\CoreSdk\Api\Workers\ContactWorker; use AirLST\CoreSdk\Api\Workers\GuestlistWorker; use AirLST\CoreSdk\Api\Workers\ProfileWorker; use AirLST\CoreSdk\Api\Workers\RsvpWorker; use Illuminate\Support\Facades\Facade; /** * Class AirLSTCoreApi * * @package AirLST\CoreSdk\Facades * * @author <NAME> <<EMAIL>> * * @method static GuestlistWorker guestlist() * @method static RsvpWorker rsvp() * @method static ContactWorker contact() * @method static BbbRoomWorker bbbRooms() * @method static ProfileWorker profile() */ class AirLSTCoreApi extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'airlst.core-api'; } } <file_sep><?php namespace AirLST\CoreSdk\Api; use AirLST\CoreSdk\Api\Abstracts\ApiWorker; use AirLST\CoreSdk\Api\Exceptions\WorkerNotFoundException; use AirLST\CoreSdk\Api\Workers\BbbRoomWorker; use AirLST\CoreSdk\Api\Workers\ContactWorker; use AirLST\CoreSdk\Api\Workers\GuestlistWorker; use AirLST\CoreSdk\Api\Workers\ProfileWorker; use AirLST\CoreSdk\Api\Workers\RsvpWorker; use Illuminate\Support\Arr; /** * Class WorkerCreator * * @package AirLST\CoreSdk\Api * * @author <NAME> <<EMAIL>> */ class WorkerCreator { protected array $availableWorkers = [ 'guestlist' => GuestlistWorker::class, 'rsvp' => RsvpWorker::class, 'contact' => ContactWorker::class, 'bbbRooms' => BbbRoomWorker::class, 'profile' => ProfileWorker::class, ]; /** * @param $name * @param $arguments * * @return ApiWorker * @throws WorkerNotFoundException */ public function __call($name, $arguments) { if (Arr::has($this->availableWorkers, $name)) { $className = Arr::get($this->availableWorkers, $name); /** @var ApiWorker $newInstance */ $newInstance = new $className(...$arguments); if($token = config('airlst-sdk.api.auth_token')) { $newInstance->setAuthorizationToken($token); } return $newInstance; } throw new WorkerNotFoundException('No worker for key "' . $name . '" was found'); } } <file_sep><?php namespace AirLST\CoreSdk\Api\Workers; use AirLST\CoreSdk\Api\Abstracts\ApiWorker; use AirLST\CoreSdk\Api\Workers\Traits\AirLSTSoftDeleteResourceTrait; use AirLST\CoreSdk\Api\Workers\Traits\HasFastPipeTrait; /** * Class GuestlistWorker * * @package AirLST\CoreSdk\Api\Workers * * @author <NAME> <<EMAIL>> */ class GuestlistWorker extends ApiWorker { use AirLSTSoftDeleteResourceTrait, HasFastPipeTrait; /** * @return string */ protected function getEntityPrefix(): string { return 'guestlists'; } /** * @return string */ protected function getEntityFastPipePrefix(): string { return 'fp/guestlists'; } } <file_sep><?php namespace AirLST\CoreSdk\Api\Workers; use AirLST\CoreSdk\Api\Abstracts\ApiWorker; use AirLST\CoreSdk\Api\Workers\Traits\AirLSTCrudResourceTrait; use AirLST\CoreSdk\Api\Workers\Traits\HasFastPipeTrait; /** * Class RsvpWorker * * @package AirLST\CoreSdk\Api\Workers * * @author <NAME> <<EMAIL>> */ class BbbRoomWorker extends ApiWorker { use AirLSTCrudResourceTrait, HasFastPipeTrait; protected ?int $guestlistId = null; /** * @param int $roomId * @return array */ public function getRsvpsForRoom(int $roomId): array { $curGuestlistId = $this->getGuestlistId(); $this->setGuestlistId(null); $this->doRequest($this->getCrudEntityPath($roomId . '/rsvps')); $this->setGuestlistId($curGuestlistId); return $this->extractDataFromLastResponse(); } /** * @return int|null */ public function getGuestlistId(): ?int { return $this->guestlistId; } /** * @param int|null $guestlistId * @return BbbRoomWorker */ public function setGuestlistId(?int $guestlistId): BbbRoomWorker { $this->guestlistId = $guestlistId; return $this; } /** * @param int $roomId * @param int $rsvpId * @param array $extraBbbParameters * @return array|null * @throws \Throwable */ public function getRoomJoinUrlForRsvp(int $roomId, int $rsvpId, array $extraBbbParameters = []): ?array { $curGuestlistId = $this->getGuestlistId(); $this->setGuestlistId(null); $this->doRequest( $this->getCrudEntityPath($roomId . '/join/' . $rsvpId), 'POST', [ 'bbb_parameters' => $extraBbbParameters ] ); $this->setGuestlistId($curGuestlistId); return $this->extractDataFromLastResponse(); } /** * @return string */ protected function getEntityPrefix(): string { return 'rooms'; } /** * @return string */ protected function getEntityFastPipePrefix(): string { if (!$this->getGuestlistId()) { return 'fp/rooms'; } else { return 'fp/guestlists/' . $this->getGuestlistId() . '/rooms'; } } } <file_sep><?php namespace AirLST\CoreSdk\Api\Workers\Traits; /** * Trait HasFastPipeTrait * * @package AirLST\CoreSdk\Api\Workers\Traits * * @author <NAME> <<EMAIL>> */ trait HasFastPipeTrait { /** * @param array $fields * @param array $filters * @param array $sort * @param array $pagination * @param array $extendedRootData * @return array|null */ public function getFpList( array $fields = ['id'], array $filters = [], array $sort = ['id' => 'asc'], array $pagination = ['perPage' => 25, 'page' => 1], array $extendedRootData = [] ): ?array { if (!$this->doRequest( $this->getEntityFastPipePath(), 'POST', array_merge([ 'fields' => $fields, 'filters' => $filters, 'sort' => $sort, 'pagination' => $pagination ], $extendedRootData) )) { return null; }; return $this->extractDataFromLastResponse(true); } /** * @param string $path * @return string */ protected function getEntityFastPipePath(string $path = ''): string { return rtrim($this->getEntityFastPipePrefix(), '/') . '/' . ltrim($path, '/'); } /** * @return string */ abstract protected function getEntityFastPipePrefix(): string; /** * @return array|null */ public function getFpListDefinition(): ?array { if (!$this->doRequest( $this->getEntityFastPipePath('definition'), 'GET', )) { return null; }; return $this->extractDataFromLastResponse(true); } } <file_sep><?php namespace AirLST\CoreSdk; use Illuminate\Http\Request; use Illuminate\Support\Arr; /** * Class Webhooks * * @package AirLST\CoreSdk * * @author <NAME> <<EMAIL>> */ class Webhook { /** * @var Request */ private Request $request; /** * Webhook constructor. * @param Request $request */ public function __construct(Request $request) { $this->request = $request; } /** * @return bool */ public function validate(): bool { $requestSignature = $this->request->header('x-airlst-webhook-signature'); if (!$requestSignature) { return false; } $mySignature = hash_hmac( 'sha256', $this->request->getContent(), config('airlst-sdk.webhooks.secret') ); return $requestSignature === $mySignature; } /** * @return array */ public function getEventInformation(): array { return (array) $this->request->get('event'); } /** * @return array */ public function getRequestBody(): array { return $this->request->all(); } } <file_sep><?php return [ 'api' => [ 'base_uri' => env('AIRLST_CORE_SDK_API_BASE_URI', 'https://v1.api.airlst.com/api'), 'debug' => boolval(env('AIRLST_CORE_SDK_API_DEBUG', false)), 'auth_token' => env('AIRLST_CORE_SDK_API_AUTH_TOKEN'), ], 'webhooks' => [ 'secret' => env('AIRLST_CORE_SDK_WEBHOOK_SECRET') ] ]; <file_sep><?php namespace AirLST\CoreSdk\Api\Exceptions; /** * Class AirLSTApiException * * @package AirLST\CoreSdk\Api\Exceptions * * @author <NAME> <<EMAIL>> */ abstract class AirLSTApiException extends \Exception implements \Throwable { } <file_sep><?php namespace AirLST\CoreSdk\Api\Workers; use AirLST\CoreSdk\Api\Abstracts\ApiWorker; use AirLST\CoreSdk\Api\Workers\Traits\AirLSTSoftDeleteResourceTrait; use AirLST\CoreSdk\Api\Workers\Traits\HasFastPipeTrait; /** * Class ContactWorker * * @package AirLST\CoreSdk\Api\Workers * * @author <NAME> <<EMAIL>> */ class ContactWorker extends ApiWorker { use AirLSTSoftDeleteResourceTrait, HasFastPipeTrait; /** * @return string */ protected function getEntityPrefix(): string { return 'contacts'; } /** * @return string */ protected function getEntityFastPipePrefix(): string { return 'fp/contacts'; } } <file_sep><?php namespace AirLST\CoreSdk\Api\Exceptions; /** * Class WorkerNotFoundException * * @package AirLST\CoreSdk\Api\Exceptions * * @author <NAME> <<EMAIL>> */ class WorkerNotFoundException extends AirLSTApiException { } <file_sep><?php namespace AirLST\CoreSdk; use AirLST\CoreSdk\Api\WorkerCreator; /** * Class ServiceProvider * * @package AirLST\CoreSdk * * @author <NAME> <<EMAIL>> */ class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** * */ public function register() { parent::register(); $this->mergeConfigFrom( __DIR__ . '/../config/airlst-sdk.php', 'airlst-sdk' ); $this->app->bind('airlst.core-api', function ($app) { return new WorkerCreator(); }); } /** * */ public function boot() { $this->publishes([ __DIR__ . '/../config/airlst-sdk.php' => config_path('airlst-sdk.php'), ], 'config'); } } <file_sep># AirLST Laravel SDK Package ## Usage ### Example of general retrieve and work of a worker (using guestlists for this example) ```php use AirLST\Core\Facades\AirLSTCoreApi; $apiWorker = AirLSTCoreApi::guestlist(); // Retrieve a single guestlist $singleGuestlist = $apiWorker->find($id); // Create a new guestlist $newCreatedGuestlist = $apiWorker->create($id, ['name' => 'New guestlist']); // Update a existing guestlist $updatedGuestlist = $apiWorker->create($id, ['name' => 'Updated guestlist']); // Archive a guestlist $archivedGuestlist = $apiWorker->archive($id); // Restore a archived guestlist $restoredGuestlist = $apiWorker->restore($id); // Permanently delete a guestlist $guestlistIsDelete = $apiWorker->delete($id); ``` ## Current available workers | Facade function | Worker class | |----|----| | `AirLSTCoreApi::contact()` | `\AirLST\CoreSdk\Api\Workers\ContactWorker` | | `AirLSTCoreApi::guestlist()` | `\AirLST\CoreSdk\Api\Workers\GuestlistWorker` | | `AirLSTCoreApi::rsvp()` | `\AirLST\CoreSdk\Api\Workers\RsvpWorker` | <file_sep><?php namespace AirLST\CoreSdk\Api\Abstracts; use GuzzleHttp\Client; use GuzzleHttp\Exception\ServerException; use Illuminate\Support\Arr; use Illuminate\Support\Str; use Psr\Http\Message\ResponseInterface; /** * Class ApiWorker * * @package AirLST\CoreSdk\Api\Abstracts * * @author <NAME> <<EMAIL>> */ abstract class ApiWorker { /** * @var string|null */ protected ?string $authorizationToken = null; /** * @var array */ protected array $extendedHeaders = []; /** * @var Client */ protected Client $client; /** * @var ResponseInterface|null */ protected ?ResponseInterface $lastResponse = null; /** * ApiWorker constructor. */ public function __construct() { $this->client = new Client([ 'base_uri' => $this->getBaseUri() ]); } /** * @return string */ public function getBaseUri(): string { return rtrim(config('airlst-sdk.api.base_uri'), '/') . '/'; } /** * @return array */ public function getExtendedHeaders(): array { return $this->extendedHeaders; } /** * @param array $extendedHeaders */ public function setExtendedHeaders(array $extendedHeaders): void { $this->extendedHeaders = $extendedHeaders; } /** * @return ResponseInterface|null */ public function getLastResponse(): ?ResponseInterface { return $this->lastResponse; } /** * @param string $path * @param string $method * @param array $parameters * @param array $extendedHeaders * @return bool */ protected function doRequest( string $path, string $method = 'GET', array $parameters = [], array $extendedHeaders = [] ): bool { $method = Str::upper($method); $requestOptions = [ 'headers' => $this->prepareRequestHeaders($extendedHeaders) ]; if ($method === 'GET') { $requestOptions['query'] = $parameters; } else { $requestOptions['json'] = $parameters; } try { $response = $this->client->request( $method, trim(ltrim($path, '/')), $requestOptions ); $this->lastResponse = $response; } catch (\Throwable $e) { if ($e instanceof ServerException) { $this->lastResponse = $e->getResponse(); } if (config('airlst-sdk.api.debug')) { throw $e; } return false; } return true; } /** * @param array $extendedHeaders * @return array */ protected function prepareRequestHeaders(array $extendedHeaders): array { $out = $this->extendedHeaders; if ($this->getAuthorizationToken()) { $out['Authorization'] = 'Bearer ' . $this->getAuthorizationToken(); } return array_merge( $out, $extendedHeaders ); } /** * @return string|null */ public function getAuthorizationToken(): ?string { return $this->authorizationToken; } /** * @param string|null $authorizationToken */ public function setAuthorizationToken(?string $authorizationToken): void { $this->authorizationToken = $authorizationToken; } /** * @param bool $returnFullResponse * @return array|null */ protected function extractDataFromLastResponse(bool $returnFullResponse = false) { $content = $this->lastResponse->getBody()->getContents(); switch (Arr::first($this->lastResponse->getHeader('Content-Type'))) { case 'application/json': $responseData = json_decode($content, true); if (!$returnFullResponse) { $responseData = Arr::get($responseData, 'data', null); } return $responseData; default: return $content; } } } <file_sep><?php namespace AirLST\CoreSdk\Api\Workers; use AirLST\CoreSdk\Api\Abstracts\ApiWorker; /** * Class ProfileWorker * * @package AirLST\CoreSdk\Api\Workers * * @author <NAME> <<EMAIL>> */ class ProfileWorker extends ApiWorker { /** * @param bool $withCompany * @return array|null * @throws \Throwable */ public function getProfile(bool $withCompany = false): ?array { $data = []; if ($withCompany) { $data['include'] = 'company'; } if (!$this->doRequest('auth/profile', 'GET', $data)) { return null; } return $this->extractDataFromLastResponse(); } }
48d8b1d6799d4fdfca7120eabf575142a60066e7
[ "Markdown", "PHP" ]
17
PHP
airlst/core-sdk
fb66da8aa901846398c98ec8800eae99c4157a57
dd2bf3d42a10a5bd512fa24dd9e777c89b338401
refs/heads/master
<file_sep>require 'test_helper' require 'cache_assertions' require 'marshaling_assertions' class DefaultCacheTest < Minitest::Test include CacheAssertions include MarshalingAssertions def cache ActiveSupport::Cache.lookup_store(:db_store) end def setup repository.delete_all end def repository ActiveSupport::Cache::DbItem end end <file_sep># frozen_string_literal: true class DbCacheStoreCreate<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %> def change create_table :<%= table_name %>, id: false do |t| t.string :key t.text :entry t.integer :version, default: 1 t.datetime :expired_at t.datetime :deleted_at end add_index :<%= table_name %>, :expired_at add_index :<%= table_name %>, :deleted_at add_index :<%= table_name %>, :key end end <file_sep>module MarshalingAssertions class DummyObject attr_reader :x, :y def initialize(x:, y:) @x = x @y = y end def cache_key "#{@x}/#{@y}" end end def dummy_object DummyObject.new(x: 1, y: 'test') end def test_caching_objects cache.fetch(dummy_object.cache_key) do dummy_object end object = cache.read(dummy_object.cache_key) assert_equal 1, object.x assert_equal 'test', object.y end def test_cache_large_objects cache.fetch(dummy_object.cache_key) do 'x' * 300 end result = cache.read(dummy_object.cache_key) assert_equal 300, result.length end end <file_sep># frozen_string_literal: true require 'simplecov' SimpleCov.start require 'pry' require 'minitest/autorun' require './lib/db_cache_store' ActiveRecord::Base.logger = nil ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ':memory:' ) ActiveRecord::Schema.define do create_table ActiveSupport::Cache::DbItem::TABLE_NAME do |table| table.string :key table.text :entry table.integer :version, default: 1 table.datetime :expired_at table.datetime :deleted_at end create_table 'custom_caches' do |table| table.string :key table.text :entry table.integer :version, default: 1 table.datetime :expired_at table.datetime :deleted_at end end class CustomCacheModel < ActiveSupport::Cache::DbItem self.table_name = 'custom_caches' end <file_sep>require 'active_record' module ActiveSupport module Cache class DbItem < ActiveRecord::Base TABLE_NAME = 'db_cache_store_items' self.table_name = TABLE_NAME def entry serialized_value = attributes['entry'] YAML.load(serialized_value) if serialized_value end def value entry.value end def expired? entry.expired? end end end end <file_sep>require "db_cache_store/version" require 'active_support/cache/db_store' module DbCacheStore end <file_sep>module CacheAssertions def test_presence assert cache end def test_read_write_scenario cache.write 1, 42 assert_equal 42, cache.read(1) db_item = repository.find_by(key: 1) refute db_item.deleted_at refute db_item.expired_at end def test_expiration_scenario cache.write 1, 42, expires_in: -1.day assert_nil cache.read(1) refute cache.exist?(1) db_item = repository.find_by(key: 1) assert db_item.expired_at refute db_item.deleted_at end def test_value_overwrite cache.write 1, 42, expires_in: 1.day cache.write 1, 43, expires_in: 2.day assert_equal 43, cache.read(1) assert_equal 42, cache.read(1, version: 1) assert_equal 43, cache.read(1, version: 2) db_item = repository.find_by(key: 1, version: 1) refute db_item.expired_at refute db_item.deleted_at second_db_item = repository.find_by(key: 1, version: 2) refute second_db_item.expired_at refute second_db_item.deleted_at end def test_expired_value_overwrite cache.write 1, 42, expires_in: -1.day assert_nil cache.read(1) cache.write 1, 43, expires_in: 1.day assert_equal 43, cache.read(1) end def test_expired_at_ignore cache.write 1, 42, expires_in: 1.day assert_equal 42, cache.read(1) db_record = repository.find_by(key: 1) refute db_record.expired_at? end def test_cleanup cache.write 1, 42, expires_in: -1.day cache.write 2, 42, expires_in: 1.day cache.read 1 cache.read 2 cache.cleanup assert_equal 1, repository.where(deleted_at: nil).count assert_equal 2, repository.count end def test_clear cache.write 1, 42 cache.write 1, 43 cache.write 2, 44 cache.clear refute cache.read(1) refute cache.read(2) end def test_namespace cache.write 1, 42, namespace: 'test' assert_equal 42, cache.read('test:1') assert_equal 42, cache.read('1', namespace: 'test') end def test_delete cache.write 1, 42 cache.delete 1 refute cache.read(1) db_item = repository.find_by(key: 1) assert db_item.expired_at? refute db_item.deleted_at? end def test_fetch_without_options cache.fetch(1) do 42 end cache.fetch(1) do refute true end assert_equal 42, cache.read(1) end def test_fetch_with_force_option cache.fetch(1) do 42 end cache.fetch(1, force: true) do 43 end assert_equal 43, cache.read(1) end end <file_sep># DbCacheStore Alternative rails cache engine, that will use database with `activerecord` ![What!?](https://media.giphy.com/media/3mJMxWRhmeiGukabki/giphy.gif) ## Install Add this line to your application's Gemfile: ```ruby gem 'db-cache-store' ``` ## Usage ### Global Usage It's __NOT__ recommened to use it as global application cache because it's slow. Supported rails versions: '>= 5.0', '< 5.2' First you need to genereate table: ```ruby DbCacheStore: db_cache_store:migration [TABLE_NAME=db_cache_store_items] ``` Then declare your cache model and update configuration in application.rb: ```ruby class MyCacheRepository < ActiveSupport::Cache::DbItem self.table_name = :cache_items end ``` ```ruby config.cache_store = :db_cache_store, repository: MyCacheRepository ``` ### Local usage ```ruby cache_store = ActiveSupport::Cache.lookup_store(:db_store, repository: MyCacheRepository) ``` ## Development After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment. `rake` will run unit tests ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/caulfield/db-cache-store <file_sep>require 'test_helper' require 'cache_assertions' class CustomRepositoryTest < Minitest::Test include CacheAssertions def cache ActiveSupport::Cache.lookup_store(:db_store, repository: repository) end def setup repository.delete_all end def repository CustomCacheModel end end <file_sep>require 'active_support/cache' require 'active_support/cache/db_item' module ActiveSupport module Cache class DbStore < Store attr_reader :repository def initialize(options = {}) super(options) @repository = options.fetch(:repository, DbItem) end def clear(options = {}) @repository.update_all(deleted_at: Time.now) end def cleanup(options = {}) @repository.where.not(expired_at: nil).update_all(deleted_at: Time.now) end private def read_entry(key, options = {}) scope = @repository.where(expired_at: nil).where(deleted_at: nil).order(version: :desc) if options[:version] scope = scope.where(version: options[:version]) end scope.find_by(key: key) end def write_entry(key, entry, options = nil) @repository.create \ key: key, entry: YAML.dump(entry), version: (read_entry(key, options)&.version.to_f + 1) end def delete_entry(key, options = nil) read_entry(key)&.touch(:expired_at) end end end end <file_sep># frozen_string_literal: true require 'test_helper' module DbCacheStore class VersionTest < Minitest::Test def test_version_exist refute_nil ::DbCacheStore::VERSION end end end <file_sep>require 'rails/generators/base' module DbCacheStore module Generators class MigrationGenerator < Rails::Generators::Base include Rails::Generators::Migration argument :table_name, type: :string, default: ActiveSupport::Cache::DbItem::TABLE_NAME desc "Generates a migration for given TABLE to use it as cache storage." source_root File.expand_path("../templates", __FILE__) def generate_migration migration_template "migration.rb", "db/migrate/db_cache_store_create_#{table_name}.rb" end def migration_version "[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" end def self.next_migration_number(dir) Time.now.utc.strftime("%Y%m%d%H%M%S") end end end end
4f62285631c744bf627a2f6aafe692570d3c82ed
[ "Markdown", "Ruby" ]
12
Ruby
caulfield/db-cache-store
fcc7029b4f9f41e48c512d0d44f4f82ab93aeecb
179d02596e96678e6851f59286b765da01ce620e
refs/heads/master
<file_sep>using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { int[] bille = new int[7] { 500, 200, 100, 50, 20, 10, 5 }; double[] mone = new double[5] { 0.50, 0.25, 0.10, 0.05, 0.01 }; int[] cantidadBilletes = new int[7]; int[] cantidadMonedas = new int[5]; decimal importe; Console.Write("Ingrese su importe: $ "); importe = Convert.ToDecimal(Console.ReadLine()); for (int i = 0; i < bille.Length; i++) { while (importe >= bille[i]) { importe = importe - bille[i]; cantidadBilletes[i] = cantidadBilletes[i] + 1; if (importe < bille[i]) Console.WriteLine("Cantidad de billetes " + bille[i] + ":" + cantidadBilletes[i]); } } for (int j = 0; j < mone.Length; j++) { while (importe >= Convert.ToDecimal(mone[j])) { importe = importe - Convert.ToDecimal(mone[j]); cantidadMonedas[j] = cantidadMonedas[j] + 1; if (importe < Convert.ToDecimal(mone[j])) Console.WriteLine("Cantidad de monedas " + mone[j] + ":" + cantidadMonedas[j]); } } Console.Read(); } } }
a67641caebca7b65c8d178ae5cecd3c539cf0d07
[ "C#" ]
1
C#
leandrosalazar/EjercicioBilletesMonedas
feb6fb02fcf7130fffb3d48ba0fd3e85430eab17
b94ae470b7038b06a22b5ff8143e487e166eb0e1
refs/heads/master
<file_sep>import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.util.Random; public class DanielExperiment2 extends Application { Random random = new Random(); BorderPane borderPane = new BorderPane(); Label lblTop = new Label("Top"); Label lblBottom = new Label("Bottom"); Label lblLeft = new Label("Left"); Label lblRight = new Label("Right"); Label lblCenter = new Label("Center"); Button btnEventHandlerClass = new Button("Event Hander Class"); Button btnAnonymousInnerClass = new Button("Anonymous Inner Class"); Button btnLambdaExpression = new Button("Lambda Expression"); HBox hbButtons = new HBox(); public void start(Stage stage) { borderPane.setBottom(lblBottom); borderPane.setTop(lblTop); borderPane.setLeft(lblLeft); borderPane.setRight(lblRight); hbButtons.getChildren().addAll(btnEventHandlerClass, btnAnonymousInnerClass, btnLambdaExpression); hbButtons.setAlignment(Pos.CENTER); borderPane.setCenter(hbButtons); borderPane.setAlignment(lblBottom, Pos.CENTER); borderPane.setAlignment(lblTop, Pos.CENTER); borderPane.setAlignment(lblLeft, Pos.CENTER); borderPane.setAlignment(lblRight, Pos.CENTER); borderPane.setAlignment(lblCenter, Pos.CENTER); EventHandlerClass handlerClass = new EventHandlerClass(); btnEventHandlerClass.setOnAction(handlerClass); btnAnonymousInnerClass.setOnAction( new EventHandler() { public void handle(Event event) { System.out.println("AnonymousInnerClass"); } }); btnLambdaExpression.setOnAction((e) -> {System.out.println("LambdaExpression");}); Scene scene = new Scene(borderPane); stage.setScene(scene); stage.setWidth(800); stage.setHeight(600); stage.show(); } } class EventHandlerClass implements EventHandler { @Override public void handle(Event event) { System.out.println("EventHandlerClass"); } } <file_sep>/** * * UI Controls and Multimedia - Geometry: Two circles intersect. * Written by <NAME> * * Requirements: * Complete exercise 16.8 * Centered at the top of the window display "Two circles intersect?" followed by either a "Yes" or "No". * Beneath this text, display two circles. * Beneath the circles display two tables side by side. * The left tablePane displays information about circlePane 1. * The right tablePane displays information about circlePane 2. * For each tablePane, display a row and column describing the following: * Center x * Center y * Radius * Beneath the fields, there must be a button with the text "Redraw circles". * When clicking and holding on the circlePane, the user must be able to move the position of the circlePane. * Moving the circlePane causes the information about the circlePane to update. * When clicking on the "Redraw Circles" button, the circles return to their original size and position. * */ import javafx.application.Application; import javafx.geometry.HPos; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.GridPane; import javafx.scene.shape.Circle; import javafx.scene.paint.Color; import javafx.scene.control.Label; import javafx.scene.control.TextField; public class DanielAssignment3 extends Application { // Class properties GridPane gridPane = new GridPane(); // Main pane. Pane circlePane = new Pane(); // Pane for circles. Label title = new Label("Two circles intersect? No"); // Text above circles. // Class properties related to the red circle and it's table. Circle redCircle = new Circle(50, Color.RED); Label redCircleTitle = new Label("Red Circle"); Label redCircleCenterX = new Label("Center X:"); Label redCircleCenterY = new Label("Center Y:"); Label redCircleRadius = new Label("Radius:"); TextField redCircleCenterXValue = new TextField(); TextField redCircleCenterYValue = new TextField(); TextField redCircleRadiusValue = new TextField(); // Class properties related to the red circle and it's table. Circle blueCircle = new Circle(50, Color.BLUE); Label blueCircleTitle = new Label("Blue Circle"); Label blueCircleCenterX = new Label("Center X:"); Label blueCircleCenterY = new Label("Center Y:"); Label blueCircleRadius = new Label("Radius:"); TextField blueCircleCenterXValue = new TextField(); TextField blueCircleCenterYValue = new TextField(); TextField blueCircleRadiusValue = new TextField(); // The redraw button. Button redrawButton = new Button("Redraw Circles"); @Override public void start (Stage stage) { // Ensure the circles are transparent so we can see the overlap. redCircle.setOpacity(0.5); blueCircle.setOpacity(0.5); // Map all of the nodes and actions with event handlers. redCircle.setOnMouseDragged(e -> { dragHandler(e, redCircle);}); blueCircle.setOnMouseDragged(e -> { dragHandler(e, blueCircle);}); redrawButton.setOnAction(e -> { initialize(); }); // Title, circles, and button spanning across all 4 columns in various rows. Ensure they are centered. gridPane.add(title, 0, 0, 4, 1); GridPane.setHalignment(title, HPos.CENTER); gridPane.add(redrawButton, 0, 6, 4, 1); GridPane.setHalignment(redrawButton, HPos.CENTER); gridPane.add(circlePane, 0, 1, 4, 1); circlePane.getChildren().addAll(redCircle, blueCircle); // All red circle related nodes going down columns 0 and 1. gridPane.add(redCircleTitle, 0, 2, 2, 1); gridPane.add(redCircleCenterX, 0, 3, 1, 1); gridPane.add(redCircleCenterXValue, 1, 3, 1, 1); gridPane.add(redCircleCenterY, 0, 4, 1, 1); gridPane.add(redCircleCenterYValue, 1, 4, 1, 1); gridPane.add(redCircleRadius, 0, 5, 1, 1); gridPane.add(redCircleRadiusValue, 1, 5, 1, 1); // All blue circle related nodes going down columns 2 and 3. gridPane.add(blueCircleTitle, 2, 2, 2, 1); gridPane.add(blueCircleCenterX, 2, 3, 1, 1); gridPane.add(blueCircleCenterXValue, 3, 3, 1, 1); gridPane.add(blueCircleCenterY, 2, 4, 1, 1); gridPane.add(blueCircleCenterYValue, 3, 4, 1, 1); gridPane.add(blueCircleRadius, 2, 5, 1, 1); gridPane.add(blueCircleRadiusValue, 3, 5, 1, 1); // Initialize all of the Nodes with values. initialize(); gridPane.setOnMouseDragged(e -> checkOverlap()); // Setting up and displaying the scene. Scene scene = new Scene(gridPane); stage.setScene(scene); stage.show(); } /** * Given a MouseEvent object and a Circle object, update the circles's Center X and Center Y properties to match * that of the mouse location. * * @param e The MouseEvent object. * @param c The Circle Object that will be modified. */ public void dragHandler(MouseEvent e, Circle c) { c.setCenterX(e.getX()); c.setCenterY(e.getY()); } /** * Update the Class fields so that they reflect the position and radius of the circles including the TextField * values and the text within the "title" label. */ public void checkOverlap() { // Logic that validates overlap. if(redCircle.getBoundsInParent().intersects(blueCircle.getBoundsInParent())) { title.setText("Two circles intersect? Yes"); } else { title.setText("Two circles intersect? No"); } // Update fields in red table. redCircleCenterXValue.setText(String.valueOf(redCircle.getCenterX())); redCircleCenterYValue.setText(String.valueOf(redCircle.getCenterY())); redCircleRadiusValue.setText(String.valueOf(redCircle.getRadius())); // Update fields in blue table. blueCircleCenterXValue.setText(String.valueOf(blueCircle.getCenterX())); blueCircleCenterYValue.setText(String.valueOf(blueCircle.getCenterY())); blueCircleRadiusValue.setText(String.valueOf(blueCircle.getRadius())); } /** * Sets the initial values for the red and blue circle and calls checkOverlap to populate fields before the user * interacts with the UI. */ public void initialize() { redCircle.setCenterX(100); redCircle.setCenterY(60); blueCircle.setCenterX(300); blueCircle.setCenterY(60); checkOverlap(); } public static void main (String[] args) { launch(); } } <file_sep># prog78005 Advanced Object Oriented Programming with Java course assignments at Sheridan College * For more information about the course, see [the course description](https://caps.sheridancollege.ca/products/PROG78005__AdvancedObjectorientedProgrammingWithJava.aspx) * For more information about the program, see [the program description](https://caps.sheridancollege.ca/products/java-foundations.aspx) <file_sep>/** * * 21 - Card Game * The card game will allow you to utilize JavaFX and Object Oriented Programming. * * Rules of the game: * Draw cards from the dealer's shuffled deck. * 21 is an automatic win for the dealer always wins on a draw * If the dealer gets 17 or more he must stand (cannot draw any more cards) * * Card values: * Jack, Queen King = 10 * Ace can be 1 or 11 * Cards 1 to 10 are the card value * Hold logic, when the player feels they have enough points to win (remember under 21). * The hold will allow the control to switch to the dealer * There should be two boxButtons - Draw & Hold * When switching to the dealer, the dealer should draw until a win (greater than the players score) or the dealers draw is greater than 21 (when the player has won). * Messaging should be presented when the player has won or lost. * */ import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.util.ArrayList; import java.util.Random; public class DanielProject1 extends Application { // Fields (UI Related) GridPane pane = new GridPane(); HBox boxButtons = new HBox(); Button btnDraw = new Button("Draw"); Button btnHold = new Button("Hold"); // Fields (Game related) ArrayList<Card> deck = new ArrayList<>(); Player dealer = new Player("Dealer"); Player player = new Player("Player"); Random random = new Random(); @Override public void start(Stage stage) { // Mash up the UI nodes from the player classes to the application ui. pane.add(dealer.lblName, 0, 0, 1, 1); pane.add(dealer.boxHand, 0, 1, 1, 1); pane.add(player.lblName, 0, 2, 1, 1); pane.add(player.boxHand, 0, 3, 1, 1); boxButtons.getChildren().addAll(btnDraw, btnHold); pane.add(boxButtons, 0, 4, 1, 1); // Populate the deck with cards final String[] suits = {"clubs", "diamonds", "hearts", "spades"}; final String[] values = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"}; for (int suitIndex = 0; suitIndex < suits.length; suitIndex++) { for (int valueIndex = 0; valueIndex < values.length; valueIndex++) { deck.add(new Card(suits[suitIndex],values[valueIndex])); } } // Add handlers for the buttons. btnDraw.setOnAction(e -> drawHandler()); btnHold.setOnAction(e -> holdHandler()); // Showtime. Scene scene = new Scene(pane); stage.setScene(scene); stage.setTitle("DanielProject1"); stage.setWidth(800); stage.setResizable(false); stage.show(); } /** * Handles events when clicking the draw button. */ public void drawHandler() { player.draw(deck); // Player draws from the deck. player.render(); // Update the UI to reflect the new hand. player.updateLabelPoints(); // Update the labels to reflect the points. if(player.isAbove21()) { player.updateLabelLoser(); dealer.updateLabelWinner(); // Game is over, btnHold.setDisable(true); btnDraw.setDisable(true); } } /** * Handles events when clicking the hold button. */ public void holdHandler() { // Dealer draws if number is less than 17 and less than or equal to the players points. while(dealer.getPoints() < 17 || dealer.getPoints() <= player.getPoints()) { dealer.draw(deck); dealer.render(); dealer.updateLabelPoints(); // Dealer loses if goes above 21. if(dealer.isAbove21()){ dealer.updateLabelLoser(); player.updateLabelWinner(); break; } // Dealer wins if the number is greater than the players points. else if (dealer.getPoints() > player.getPoints()){ player.updateLabelLoser(); dealer.updateLabelWinner(); break; } // Dealer wins ties. else if (dealer.getPoints() == 21) { player.updateLabelLoser(); dealer.updateLabelWinner(); break; } } // Game is over, btnHold.setDisable(true); btnDraw.setDisable(true); } public static void main (String[] args) { launch(args); } /** * This class is used to instantiate objects representing playing cards. */ class Card { // Fields private String suit; private String faceValue; private String filename; private int pointValue; private Image imageFile; private ImageView imageFileView; // Constructors Card(String suit, String faceValue) { this.suit = suit.toLowerCase(); this.faceValue = faceValue.toLowerCase(); this.filename = faceValue + "_of_" + suit + ".png"; // Attempt to get images from various sources. try { // Attempt to get the file from the local "static" folder. this.imageFile = new Image("static/" + this.filename, 200, 200, true, true); } catch(IllegalArgumentException e) { // On exception, attempt ot get the file from the github repo. System.out.println("Could not find images in the 'static' folder, downloading from GitHub."); String fullFilename = "https://raw.githubusercontent.com/danieldsj/prog78005/master/src/static/" + this.filename; this.imageFile = new Image(fullFilename, 200, 200, true, true); } this.imageFileView = new ImageView(this.imageFile); // Calculate the point value of the card. Assume aces are worth 11 points at first. switch(this.getFaceValue()) { case "jack": this.setPointValue(10); break; case "queen": this.setPointValue(10); break; case "king": this.setPointValue(10); break; case "ace": this.setPointValue(11); break; default: this.setPointValue(Integer.valueOf(this.getFaceValue())); break; } } // Getter methods public String getSuit() { return this.suit; } public String getFaceValue() { return this.faceValue; } public String getFilename() { return this.filename; } public Image getImageFile() { return this.imageFile;} public ImageView getImageFileView() { return this.imageFileView; } public int getPointValue() { return this.pointValue; } // Setter methods public void setPointValue(int value) { this.pointValue = value; } } /** * This class is used to instantiate objects representing players or dealers. */ class Player { // Fields ArrayList<Card> hand; Random random; HBox boxHand; Label lblName; String name; // Constructors Player(String name) { this.hand = new ArrayList<>(); this.random = new Random(); this.boxHand = new HBox(); this.lblName = new Label(name); this.boxHand.setMinHeight(200); this.name = name; } // Getter methods public HBox getBoxHand() { return this.boxHand; } public Label getLblName() { return this.lblName; } public ArrayList<Card> getHand() { return this.hand; } // Methods /** * Given a deck, randomize an index value within the correct range. Get that card and pace it in the Player * object's hand. Remove card from the deck. * * @param deck An ArrayList<Card> object from which we remove a random card. */ public void draw(ArrayList<Card> deck) { int cardIndex = random.nextInt(deck.size() -1); this.hand.add(deck.get(cardIndex)); deck.remove(cardIndex); } /** * Add an image of the Card to an HBox representing the players hand in the UI. */ public void render() { for (Card card : this.getHand()) { if(!(this.getBoxHand().getChildren().contains(card.getImageFileView()))) { this.getBoxHand().getChildren().add(card.getImageFileView()); } } } /** * Calculates the point values of the players hand. * * @return */ public int getPoints() { int result = 0; for(Card e: this.hand) { result += e.getPointValue(); } return result; } /** * Returns true if the Player object has aces in it's hand. * * @return whether the player has aces in it's hand. */ public Boolean hasAces() { for(Card card: this.getHand()) { if (card.getPointValue() == 11) { return true; } } return false; } /** * Update the Player object's label to include the amount of points it hads. */ public void updateLabelPoints() { this.getLblName().setText(this.name + " (" + this.getPoints() + ")"); } /** * Update the Player object's label so that it indicates it has won. */ public void updateLabelWinner() { this.getLblName().setText(this.getLblName().getText() + " WINNER!"); } /** * Update the Player object's label so that it indicates it has lost. */ public void updateLabelLoser() { this.getLblName().setText(this.getLblName().getText() + " LOSER!"); } /** * Determines whether the Player object has exceeded 21. * * @return Boolean representing whether the Player object has exceeded 21. */ public Boolean isAbove21() { // If we are above 21. if(this.getPoints() > 21){ // While we still have aces. while(this.hasAces()) { // Iterate over each card. for(Card card: this.getHand()) { // If it's an ace. if(card.getPointValue() == 11) { // Reduce it's value to 1. card.setPointValue(1); this.updateLabelPoints(); break; } } // If it results in the number being less than or equal to 21, return false. if(this.getPoints() <= 21) { return false; } } return true; } return false; } } }<file_sep>/** * * JavaFX Basics - Pick Four Cards * Written by <NAME> * * Requirements: * Must have a refresh button that says "Refresh" on it. * User must be able to click the button. * Upon clicking the "Refresh" button, display 4 random cards from the 52 cards in a playing deck. * */ import javafx.application.Application; import javafx.geometry.HPos; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.GridPane; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.util.Random; import java.util.ArrayList; public class DanielAssignment2 extends Application { private GridPane grid = new GridPane(); /** * Since this is a subclass of a JavaFX Application, we must override the start method. * * @param stage The default Stage object. */ @Override public void start (Stage stage) { // We need to create a GridPane object for the scene. //GridPane grid = new GridPane(); // Populate row with images of random cards. handleRefresh(); // Create a refresh button. Button button = new Button("Refresh"); // Make sure the button is centered. grid.setHalignment(button, HPos.CENTER); // When clicked, the button should randomize cards again. button.setOnAction( (e) -> handleRefresh() ); // Lambda for the win! // Add the button to the grid. grid.add(button, 0, 1, 4, 1); // Create a new Scene object using the GridPane object. Scene scene = new Scene(grid); // Set the Stage object to use the Scene object above. stage.setScene(scene); // Provide a friendly title. stage.setTitle("Daniel Assignment 2"); // Show the Stage object. stage.show(); } /** * Populate that row with images of 4 random playing cards. * */ public void handleRefresh() { // Instance of random class to generate random numbers. Random random = new Random(); // Four suits and thirteen face values. final String[] suits = {"clubs", "diamonds", "hearts", "spades"}; final String[] values = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"}; // Generate a single list of cards to randomize over. ArrayList<String> filenames = new ArrayList<>(); for (int suitIndex = 0; suitIndex < suits.length; suitIndex++) { for (int valueIndex = 0; valueIndex < values.length; valueIndex++) { filenames.add(values[valueIndex] + "_of_" + suits[suitIndex] + ".png"); // System.out.println(values[valueIndex] + "_of_" + suits[suitIndex] + ".png"); } } // Variable for the filenames. String randomFilename; String fullPath; // Randomize 4 numbers and add the correspon ding image file, to the grid. for(int i = 0; i < 4; i++) { randomFilename = filenames.get(random.nextInt(filenames.size())); try { // Attempt to get the file from the local "static" folder. fullPath = "static/" + randomFilename; grid.add(new ImageView(new Image(fullPath, 200, 200, true, true)), i, 0 ); } catch(IllegalArgumentException e) { // On exception, attempt ot get the file from the github repo. fullPath = "https://raw.githubusercontent.com/danieldsj/prog78005/master/src/static/" + randomFilename; grid.add(new ImageView(new Image(fullPath, 200, 200, true, true)), i, 0 ); } } } /** * Launches the JavaFX application. * * @param args Optional command line arguments that are promptly ignored. */ public static void main (String[] args) { launch(); } } <file_sep>/** * Binary I/O - Address Book * Written by <NAME> * * Requirements: * Adds addresses. * Updates addresses. * Stores addresses. * Retrieves addresses. * An address is comprised of the following: * Name - 32 bytes. * Street - 32 bytes. * City - 20 bytes. * State - 2 bytes. * Zip - 5 bytes. * There must be the following buttons: * An "Add" button. * A "First" button. * A "Next" button. * A "Previous" button. * A "Last" button. * An "Update" button. * */ import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.io.*; import java.util.ArrayList; public class DanielAssignment4 extends Application { // FIELDS! // Layout things GridPane pane = new GridPane(); // The main grid. HBox buttons = new HBox(); // HBox for the buttons. // Labels Label lblName = new Label("Name "); Label lblStreet = new Label("Street "); Label lblCity = new Label("City "); Label lblState = new Label("State "); Label lblZip = new Label("Zip "); // Text Fields TextField tfName = new TextField(); TextField tfStreet = new TextField(); TextField tfCity = new TextField(); TextField tfState = new TextField(); TextField tfZip = new TextField(); // Buttons Button btnAdd = new Button("Add"); Button btnFirst = new Button("First"); Button btnPrevious = new Button("Previous"); Button btnNext = new Button("Next"); Button btnLast = new Button("Last"); Button btnUpdate = new Button("Update"); // The list and current index. ArrayList<DanielAssignment4Address> addressList = new ArrayList<>(); int currentIndex; @Override public void start(Stage stage) { // Add Label objects to grid. pane.add(lblName, 0, 0); pane.add(lblStreet, 0, 1); pane.add(lblCity, 0, 2); pane.add(lblState, 0, 3); pane.add(lblZip, 0, 4); // Add TextField objects to grid. pane.add(tfName, 1, 0); pane.add(tfStreet, 1, 1); pane.add(tfCity, 1,2); pane.add(tfState, 1, 3); pane.add(tfZip, 1, 4); // Add buttons to HBox. then to grid. buttons.getChildren().addAll(btnAdd, btnFirst, btnPrevious, btnNext, btnLast, btnUpdate); pane.add(buttons, 0, 5, 2, 1); // Adding padding. buttons.setPadding(new Insets(10, 0, 0, 0)); pane.setPadding(new Insets(10,10,10,10)); // Handlers for each button. btnAdd.setOnAction( e -> addHandler()); btnFirst.setOnAction(e -> firstHandler()); btnLast.setOnAction(e -> lastHandler()); btnNext.setOnAction(e -> nextHandler()); btnPrevious.setOnAction(e -> previousHandler()); btnUpdate.setOnAction(e -> updateHandler()); tfName.setOnKeyTyped(e -> handleTextLimits(tfName, 32)); tfStreet.setOnKeyTyped(e -> handleTextLimits(tfStreet, 32)); tfCity.setOnKeyTyped(e -> handleTextLimits(tfCity, 20)); tfState.setOnKeyTyped(e -> handleTextLimits(tfState, 2)); tfZip.setOnKeyTyped(e -> handleTextLimits(tfZip, 5)); // Load data saved on disk if present. loadData(); // Update the text fields with contents of addressArray if any. updateTextFields(); // Shake and bake. Scene scene = new Scene(pane); stage.setScene(scene); stage.setTitle("Daniel Assignment 4"); stage.show(); } public static void main (String[] args) { launch(args); } /** * Adds DanielAssignment4Address objects to the addressList ArrayList. */ public void addHandler() { addressList.add(new DanielAssignment4Address(tfName.getText(), tfStreet.getText(), tfCity.getText(), tfState.getText(), tfZip.getText())); saveData(); } /** * Sets the currentIndex to zero and updates the textFields. */ public void firstHandler() { currentIndex = 0; updateTextFields(); } /** * Sets the currentIndex to the size of the addressList - 1 and updates the textFields. */ public void lastHandler() { currentIndex = addressList.size() - 1; updateTextFields(); } /** * Increments the currentIndex if it isn't already at the maximum value and updates the textFields. */ public void nextHandler() { if(!(currentIndex == addressList.size() - 1)) { currentIndex += 1; } updateTextFields(); } /** * Prevents user for putting too much text in textFields. * * @param textField The TextField object with a limit. * @param limit The limit of the TextField object. */ public void handleTextLimits(TextField textField, int limit) { if (textField.getText().length() == limit) { textField.setText(textField.getText(0, limit - 1)); textField.positionCaret(limit -1 ); } } /** * Decrements the currentIndex if it isn't already at the minimum value and updates the textFields. */ public void previousHandler() { if(!(currentIndex == 0)) { currentIndex -= 1; } updateTextFields(); } /** * Modify the object in the addressList with the currentIndex with the text in the fields. */ public void updateHandler() { addressList.get(currentIndex).name = tfName.getText(); addressList.get(currentIndex).street = tfStreet.getText(); addressList.get(currentIndex).city = tfCity.getText(); addressList.get(currentIndex).state = tfState.getText(); addressList.get(currentIndex).zip = tfZip.getText(); saveData(); // Save data after evey modification. } /** * Refreshes the value in the text fields to reflect the currentIndex value. */ public void updateTextFields() { if(addressList.size() > 0) { tfName.setText(addressList.get(currentIndex).name); tfStreet.setText(addressList.get(currentIndex).street); tfCity.setText(addressList.get(currentIndex).city); tfState.setText(addressList.get(currentIndex).state); tfZip.setText(addressList.get(currentIndex).zip); } } /** * Saves a serialized version of the addressList object into a file. */ public void saveData() { try { File file = new File("DanielAssignment4.dat"); if(!(file.exists())) { file.createNewFile(); } FileOutputStream outputFile = new FileOutputStream("DanielAssignment4.dat"); ObjectOutputStream outputStream = new ObjectOutputStream(outputFile); outputStream.writeObject(addressList); outputStream.close(); } catch(Exception e) { e.printStackTrace(); } } /** * Loads a serialized version of the addressList object from a file. */ public void loadData() { try { FileInputStream file = new FileInputStream("DanielAssignment4.dat"); ObjectInputStream input = new ObjectInputStream(file); addressList = (ArrayList) input.readObject(); input.close(); } catch(FileNotFoundException e) { System.out.println("No data file found."); } catch(Exception e) { e.printStackTrace(); } } }
8c8400bf0fa184795f73d2930f0f06a54956be6e
[ "Markdown", "Java" ]
6
Java
danieldsj/prog78005
62f2876786894a86dc65c37e4e4619f7a68ee7a6
46296a9e0053a7312815a659a2f2151cc9df89d5
refs/heads/master
<file_sep>package androidPages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.concurrent.TimeUnit; import io.appium.java_client.AppiumDriver; import io.appium.java_client.TouchAction; public class CamPreview_ModeMenu { private AppiumDriver driver; WebDriverWait wait; /* String midModeLocator = "className(\"android.widget.FrameLayout\").clickable(true).instance(1)"; String rightModeLocator = "className(\"android.widget.FrameLayout\").clickable(true).instance(2)"; String fourthModeLocator = "className(\"android.widget.FrameLayout\").clickable(true).instance(3)";*/ String depthModeSelector = "text(\"Depth\")"; String burstSelector = "text(\"Burst\")"; public CamPreview_ModeMenu(AppiumDriver drive) { driver = drive; wait = new WebDriverWait(driver, 10); driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); } //Now not used anymore because of new design /* public CamPreview_ModeMenu scrollToRight(Integer reps) throws InterruptedException{ Thread.sleep(800); WebElement midMode = driver.findElementByAndroidUIAutomator(midModeLocator); WebElement rightMode = driver.findElementByAndroidUIAutomator(rightModeLocator); int startX = util.getCenterXCoordinate(rightMode); int startY = util.getCenterYCoordinate(rightMode); int endX = util.getCenterXCoordinate(midMode); int endY = util.getCenterYCoordinate(midMode); //TouchAction scrollRight = new TouchAction(driver).press(rightMode).moveTo(midMode).release(); for (int n = 0; n < reps; n++) { wait.until(ExpectedConditions.invisibilityOfElementLocated(MobileBy.AndroidUIAutomator(fourthModeLocator))); new TouchAction(driver).press(startX, startY).moveTo(endX, endY).release().perform(); Thread.sleep(800); } return this; }*/ public CamPreview_Depth selectDepthMode() throws InterruptedException{ Thread.sleep(300); WebElement depthIcon = driver.findElementByAndroidUIAutomator(depthModeSelector); new TouchAction(driver).tap(depthIcon).perform(); return new CamPreview_Depth(driver); } public CamPreviewBurst_SubMenu selectBurstMode() throws InterruptedException{ Thread.sleep(300); WebElement burstIcon = driver.findElementByAndroidUIAutomator(burstSelector); new TouchAction(driver).tap(burstIcon).perform(); return new CamPreviewBurst_SubMenu(driver); } } <file_sep>package androidPages; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.concurrent.TimeUnit; import io.appium.java_client.AppiumDriver; public class CamPreviewSingle_SubMenu { private AppiumDriver driver; WebDriverWait wait; String hdrSelector = "textStartsWith(\"HDR\")"; String smileSelector = "textStartsWith(\"Smile\")"; public CamPreviewSingle_SubMenu(AppiumDriver drive) { driver = drive; wait = new WebDriverWait(driver, 10); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } public CamPreview_HDR turnHDROn() throws InterruptedException{ Thread.sleep(300); driver.findElementByAndroidUIAutomator(hdrSelector).click(); return new CamPreview_HDR(driver); } public CamPreview_Single turnHDROff() throws InterruptedException{ Thread.sleep(300); driver.findElementByAndroidUIAutomator(hdrSelector).click(); return new CamPreview_Single(driver); } public CamPreview_Smile turnSmileOn() throws InterruptedException{ Thread.sleep(300); driver.findElementByAndroidUIAutomator(hdrSelector).click(); return new CamPreview_Smile(driver); } public CamPreview_Single turnSmileOff() throws InterruptedException{ Thread.sleep(300); driver.findElementByAndroidUIAutomator(hdrSelector).click(); return new CamPreview_Single(driver); } } <file_sep>package androidPages; import java.util.concurrent.TimeUnit; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileBy; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class CamPreview_Depth { private AppiumDriver driver; WebDriverWait wait; String shutterBtnLocator = "description(\"Shutter button\")"; String clickableShutterBtnLocator = "description(\"Shutter button\").clickable(true).enabled(true)"; String modeBtnLocator = "description(\"Show switch camera mode list\")"; String viceCamRedBorderLocator = "resourceId(\"com.intel.camera22:id/vice_camera_highlight_border_view1\")"; public CamPreview_Depth(AppiumDriver drive) { driver = drive; wait = new WebDriverWait(driver, 10); driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); } public CamPreview_Depth capture(Integer numberOfCaptures, Integer msTimeBetweenTaps) throws InterruptedException{ wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AndroidUIAutomator(clickableShutterBtnLocator))); for (int n = 0; n < numberOfCaptures; n++) { wait.until(ExpectedConditions.invisibilityOfElementLocated(MobileBy.AndroidUIAutomator(viceCamRedBorderLocator))); //wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AndroidUIAutomator(clickableShutterBtnLocator))); driver.findElementByAndroidUIAutomator(shutterBtnLocator).click(); System.out.printf("..%d", n); Thread.sleep(msTimeBetweenTaps); } System.out.println(); return this; } public CamPreview_ModeMenu tapModeItem() { driver.findElementByAndroidUIAutomator(modeBtnLocator).click(); return new CamPreview_ModeMenu(driver); } } <file_sep>package androidPages; import java.util.concurrent.TimeUnit; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileBy; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class CamPreview_HDR { private AppiumDriver driver; WebDriverWait wait; String clickableShutterBtnLocator = "description(\"Shutter button\").clickable(true).enabled(true)"; String processingTextLocator = "textStartsWith(\"Processing\")"; String modeBtnLocator = "description(\"Show switch camera mode list\")"; public CamPreview_HDR(AppiumDriver drive) { driver = drive; wait = new WebDriverWait(driver, 8); driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); } public CamPreview_HDR capture(Integer numberOfCaptures, Integer msTimeBetweenTaps) throws InterruptedException{ wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AndroidUIAutomator(clickableShutterBtnLocator))); WebElement shutterBtn = driver.findElementByAndroidUIAutomator(clickableShutterBtnLocator); for (int n = 0; n < numberOfCaptures; n++) { wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AndroidUIAutomator(modeBtnLocator))); //wait.until(ExpectedConditions.invisibilityOfElementLocated(MobileBy.AndroidUIAutomator(processingTextLocator))); shutterBtn.click(); System.out.printf("..%d", n); Thread.sleep(msTimeBetweenTaps); } return this; } } <file_sep>package androidPages; import java.util.concurrent.TimeUnit; import io.appium.java_client.AppiumDriver; public class CamPreviewDepth_ModeMenu { private AppiumDriver driver; String shutterBtnLocator = "description(\"Shutter button\")"; public CamPreviewDepth_ModeMenu(AppiumDriver driver) { this.driver = driver; driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } public CamPreviewDepth_ModeMenu scrollToRight(Integer reps) throws InterruptedException{ Thread.sleep(500); for (int n = 0; n < reps; n++) { driver.findElementByAndroidUIAutomator(shutterBtnLocator).click(); } return this; } } <file_sep>package androidTests; import org.openqa.selenium.*; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.interactions.HasTouchScreen; import org.openqa.selenium.interactions.TouchScreen; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteTouchScreen; import org.openqa.selenium.remote.RemoteWebDriver; import java.io.File; import java.net.URL; import java.util.*; import static org.junit.Assert.*; public class Data { public static final String PHOTO_DATA_INFO = "When you turn this option on, photo data is attached " + "to your photo files. This means the data moves with your photo files when you move them " + "out of your phone to your computer. It also means that other apps on the phone may be able " + "to see the data as well.\n\n" + "When you turn this option off, photo data is not attached to your photo files, but standard " + "technical photo data (EXIF) is still kept. If you had previously attached this data to your " + "photos and then decide to turn this option off, that data remains with those photos but is " + "not added to any new photo you take. Note that the Gallery app always has access to this data. " + "For example, if you choose to add an event name to a photo in Gallery, this information is kept " + "in a secure area of your phone and Gallery uses it to organize your photos around events. " + "If you remove the event name from that photo, the event is then removed from Gallery also."; public static final String TURN_ON_BLUETOOTH_PROMPT = "To use Bluetooth services, you must first turn on Bluetooth.\n\nTurn on Bluetooth now?\n\n"; public static final String REMEMBER_LOCATION = "Remember location? Enable geo location to save the " + "location the photo was taken. Other applications will have access to this information."; } <file_sep>package androidTests; import androidPages.CamPreview_Depth; import androidPages.CamPreview_FBurst; import androidPages.CamPreview_HDR; import androidPages.CamPreview_SBurst; import androidPages.CamPreview_Single; import androidPages.CamPreview_GeoTagMessage; import androidPages.BB; import androidPages.CamPreview_Smile; import androidPages.CamPreview_Video; import androidPages.SinglePreview_Settings; import static org.junit.Assert.*; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileBy; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.net.URL; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class TestSocialCam23_Landscape_BB_BAT { private AppiumDriver driver; private CamPreview_GeoTagMessage geoTagMsg; private CamPreview_Single singlePreview; private BB util; WebDriverWait wait; String pathTo100ANDRO = "/sdcard/DCIM/100ANDRO"; @Before public void setUp() throws Exception{ // set up appium: specify the path to the app folder from your computer. Only if you need to install the apk //File app = new File("C:\\Users\\trieutdx\\Downloads\\apks\\Social Apps", "SocialGallery22_ARM.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(CapabilityType.BROWSER_NAME, ""); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("platformVersion", "4.4"); capabilities.setCapability("deviceName", "BB"); capabilities.setCapability("deviceOrientation", "landscape"); //New //The line below is used only when the apk needs to be installed. //capabilities.setCapability("app", app.getAbsolutePath()); capabilities.setCapability("appPackage", "com.intel.camera22"); capabilities.setCapability("appActivity", ".Camera"); driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); wait = new WebDriverWait(driver, 8); geoTagMsg = new CamPreview_GeoTagMessage(driver); util = new BB(driver); singlePreview = geoTagMsg.checkGeoLocationMessage(); } @After public void tearDown() throws Exception { driver.closeApp(); driver.quit(); } //@Test public void testSingleCapture20X() throws Exception{ System.out.println("@@@...Running testSingleCapture20X...@@@"); Thread.sleep(10000); int filesToCapture = 1000; int filesPreCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder before capture.\n", filesPreCapture); singlePreview.capture(filesToCapture, 800); Thread.sleep(2000); int filesAfterCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder after capture.\n", filesAfterCapture); int filesCaptured = filesAfterCapture - filesPreCapture; if (filesCaptured == filesToCapture) System.out.printf("'%d' Single Shot images were captured out of the specified number of '%d'!\n", filesCaptured, filesToCapture); else { System.out.printf("'%d' Single Shot images were captured out of the specified number of '%d'. Capture failed!!\n", filesCaptured, filesToCapture); assertTrue(false); } System.out.println("@@@...Finished testSingleCapture20X...@@@"); } //@Test public void testDepthCapture20X() throws InterruptedException{ System.out.println("@@@...Running testDepthCapture20X...@@@"); int filesToCapture = 20; int filesPreCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder before depth capture.\n", filesPreCapture); CamPreview_Depth depthPreview = singlePreview.switchToDepthMode(); depthPreview.capture(filesToCapture, 500); Thread.sleep(2000); int filesAfterCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder after depth capture.\n", filesAfterCapture); int filesCaptured = filesAfterCapture - filesPreCapture; if (filesCaptured == filesToCapture) System.out.printf("'%d' depth images were captured out of the specified number of '%d'!\n", filesCaptured, filesToCapture); else { System.out.printf("'%d' depth images were captured out of the specified number of '%d'. Capture failed!!\n", filesCaptured, filesToCapture); assertTrue(false); } System.out.println("@@@...Finished testDepthCapture20X...@@@"); } //@Test public void testFastBurstCapture20X() throws InterruptedException{ System.out.println("@@@...Running testFastBurstCapture20X...@@@"); int filesPerSet = 10; int setsToCapture = 20; int filesPreCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder before fast burst capture.\n", filesPreCapture); CamPreview_FBurst fBurstPreview = singlePreview.switchToFBurstMode(); fBurstPreview.capture(setsToCapture, 500); Thread.sleep(2000); int filesAfterCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder after fast burst capture.\n", filesAfterCapture); int filesCaptured = filesAfterCapture - filesPreCapture; if (filesCaptured == (setsToCapture * filesPerSet)) System.out.printf("'%d' fast burst images were captured out of the specified number of '%d'!\n", (filesCaptured/filesPerSet), setsToCapture); else { System.out.printf("'%d' fast burst images were captured out of the specified number of '%d'. Capture failed!!\n", (filesCaptured/filesPerSet), setsToCapture); assertTrue(false); } System.out.println("@@@...Finished testFastBurstCapture20X...@@@"); } //@Test public void testSlowBurstCapture20X() throws InterruptedException{ System.out.println("@@@...Running testSlowBurstCapture20X...@@@"); int filesPerSet = 10; int setsToCapture = 20; int filesPreCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder before slow burst capture.\n", filesPreCapture); CamPreview_SBurst sBurstPreview = singlePreview.switchToSBurstMode(); sBurstPreview.capture(setsToCapture, 500); Thread.sleep(2000); int filesAfterCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder after slow burst capture.\n", filesAfterCapture); int filesCaptured = filesAfterCapture - filesPreCapture; if (filesCaptured == (setsToCapture * filesPerSet)) System.out.printf("'%d' slow burst images were captured out of the specified number of '%d'!\n", (filesCaptured/filesPerSet), setsToCapture); else { System.out.printf("'%d' slow burst images were captured out of the specified number of '%d'. Capture failed!!\n", (filesCaptured/filesPerSet), setsToCapture); assertTrue(false); } System.out.println("@@@...Finished testSlowBurstCapture20X...@@@"); } //@Test public void testTempHDRCapture() throws Exception{ System.out.println("@@@...Running testTempHDRCapture...@@@"); Thread.sleep(8000); int filesToCapture = 400; int filesPreCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder before capture.\n", filesPreCapture); CamPreview_HDR preview = new CamPreview_HDR(driver); preview.capture(filesToCapture, 400); Thread.sleep(1000); int filesAfterCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder after capture.\n", filesAfterCapture); int filesCaptured = filesAfterCapture - filesPreCapture; if (filesCaptured == filesToCapture) System.out.printf("'%d' images were captured out of the specified number of '%d'!\n", filesCaptured, filesToCapture); else { System.out.printf("'%d' images were captured out of the specified number of '%d'. Capture failed!!\n", filesCaptured, filesToCapture); assertTrue(false); } System.out.println("@@@...Finished testTempHDRCapture...@@@"); } //@Test public void testTempSmileCapture() throws Exception{ System.out.println("@@@...Running testTempSmileCapture...@@@"); Thread.sleep(8000); int filesToCapture = 500; int filesPreCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder before capture.\n", filesPreCapture); CamPreview_Smile preview = new CamPreview_Smile(driver); preview.capture(filesToCapture, 400); Thread.sleep(1000); int filesAfterCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder after capture.\n", filesAfterCapture); int filesCaptured = filesAfterCapture - filesPreCapture; if (filesCaptured == filesToCapture) System.out.printf("'%d' images were captured out of the specified number of '%d'!\n", filesCaptured, filesToCapture); else { System.out.printf("'%d' images were captured out of the specified number of '%d'. Capture failed!!\n", filesCaptured, filesToCapture); assertTrue(false); } System.out.println("@@@...Finished testMultipleCapture...@@@"); } //@Test public void testTempVideoCapture() throws Exception{ System.out.println("@@@...Running testTempVideoCapture...@@@"); Thread.sleep(8000); int filesToCapture = 500; int filesPreCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder before capture.\n", filesPreCapture); CamPreview_Video preview = new CamPreview_Video(driver); preview.capture(filesToCapture, 400); Thread.sleep(2000); int filesAfterCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder after capture.\n", filesAfterCapture); int filesCaptured = filesAfterCapture - filesPreCapture; if (filesCaptured == filesToCapture) System.out.printf("'%d' images were captured out of the specified number of '%d'!\n", filesCaptured, filesToCapture); else { System.out.printf("'%d' images were captured out of the specified number of '%d'. Capture failed!!\n", filesCaptured, filesToCapture); assertTrue(false); } System.out.println("@@@...Finished testTempVideoCapture...@@@"); } //@Test public void testTempDepthCapture() throws InterruptedException{ System.out.println("@@@...Running testTempDepthCapture...@@@"); Thread.sleep(8000); int filesToCapture = 1000; int filesPreCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder before depth capture.\n", filesPreCapture); CamPreview_Depth depthPreview = new CamPreview_Depth(driver); depthPreview.capture(filesToCapture, 500); Thread.sleep(2000); int filesAfterCapture = util.findNumberOfFiles(pathTo100ANDRO); System.out.printf("'%d' files are found in 100ANDRO folder after depth capture.\n", filesAfterCapture); int filesCaptured = filesAfterCapture - filesPreCapture; if (filesCaptured == filesToCapture) System.out.printf("'%d' depth images were captured out of the specified number of '%d'!\n", filesCaptured, filesToCapture); else { System.out.printf("'%d' depth images were captured out of the specified number of '%d'. Capture failed!!\n", filesCaptured, filesToCapture); assertTrue(false); } System.out.println("@@@...Finished testTempDepthCapture...@@@"); } @Test public void testSingleSettingsChange() throws Exception{ String modeBtnLocator = "description(\"Show switch camera mode list\")"; String hdrON = "text(\"HDR\nON\")"; String smileON = "text(\"Smile\nON\")"; Thread.sleep(8000); System.out.println("@@@...testSingleSettingsChange...@@@"); String cameraFacing = util.getCameraDirection(); String cameraMode = util.getCameraMode(); System.out.printf("Camera direction: '%s'", cameraFacing); System.out.printf("Camera mode: '%s'", cameraMode); SinglePreview_Settings singleSettingsMenu = singlePreview.tapSettingsIcon(); if (singleSettingsMenu.menuIsOpen()) System.out.println("Settings menu is open!"); else System.out.println("Settings menu is not open!"); util.tapScreen(.5, .5); wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AndroidUIAutomator(modeBtnLocator))); driver.findElementByAndroidUIAutomator(modeBtnLocator).click(); Thread.sleep(4000); WebElement el= driver.findElementByAndroidUIAutomator(hdrON); String textAttribute = el.getAttribute("android:textColor"); System.out.printf("Text color attribute: '%s'", textAttribute); System.out.println("@@@...testSingleSettingsChange...@@@"); } }<file_sep>package androidTests; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.interactions.HasTouchScreen; import org.openqa.selenium.interactions.TouchScreen; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteTouchScreen; import org.openqa.selenium.remote.RemoteWebDriver; import java.io.File; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.regex.*; import java.util.*; import org.openqa.selenium.internal.Locatable; import org.openqa.selenium.remote.RemoteWebElement; import static org.junit.Assert.*; public class TestSocialCameraBAT_Portrait_SBY { private WebDriver driver; private WebElement menu; private WebDriverWait wait; @Before public void setUp() throws Exception { // set up appium: specify the path to the app folder from your computer. Only if you need to install the apk //File app = new File("C:\\Users\\trieutdx\\Downloads\\apks\\Social Apps", "SocialGallery22_ARM.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("device","Android"); capabilities.setCapability("deviceOrientation", "portrait"); //New capabilities.setCapability(CapabilityType.BROWSER_NAME, ""); capabilities.setCapability(CapabilityType.VERSION, "4.4"); capabilities.setCapability(CapabilityType.PLATFORM, "Windows"); //The line below is used only when the apk needs to be installed. //capabilities.setCapability("app", app.getAbsolutePath()); capabilities.setCapability("app-package", "com.intel.camera22"); capabilities.setCapability("app-activity", ".Camera"); driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); if (!driver.findElements(By.name(Data.REMEMBER_LOCATION)).isEmpty()) { Dut.tap(driver, "name", "Cancel", 1, 500); } if (Dut.getCamDirection(driver) == 2) { wait = new WebDriverWait(driver, 15); Dut.tap(driver, "name", "Front and back camera switch", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); Dut.wait(driver, 500); } } @After public void tearDown() throws Exception { driver.quit(); } @Test public void checkDisplayedElementsInSingleMode(){ wait = new WebDriverWait(driver, 15); Dut.wait(driver, 500); String changeMode = "com.intel.camera22:id/mode_button"; String groupSingle = "com.intel.camera22:id/mode_wave_photo"; String modeVideo = "com.intel.camera22:id/mode_wave_video"; String groupBurst = "com.intel.camera22:id/mode_wave_burst"; String modePerfect = "com.intel.camera22:id/mode_wave_perfectshot"; String modePanorama = "com.intel.camera22:id/mode_wave_panorama"; String modeHDR = "com.intel.camera22:id/mode_wave_hdr"; String modeSmile = "com.intel.camera22:id/mode_wave_smile"; String modeSBurst = "com.intel.camera22:id/mode_wave_burst_slow"; String modeFBurst = "com.intel.camera22:id/mode_wave_burst_fast"; System.out.println("@@@...Running checkDisplayedElementsInSingleMode...@@@"); //Verify Shutter button availability assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); Dut.changeMode(driver, "single"); //Capture a single shot image, verify thumbnail existence and go to Gallery. Then delete the image. Dut.imageCapture(driver, "single", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1000); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Verify Change Mode icon availability assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); assertTrue(Dut.verifyExist(driver, "id", groupBurst)); assertTrue(Dut.verifyExist(driver, "id", modePerfect)); assertTrue(Dut.verifyExist(driver, "id", modePanorama)); //Verify shooting mode icons under the Single group by switching to Video mode first and then clicking on the Single group icon Dut.tap(driver, "id", modeVideo, 1, 100); Dut.tap(driver, "id", groupSingle, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeHDR)); assertTrue(Dut.verifyExist(driver, "id", modeSmile)); //Tap on the Burst group and verify the modes under it: Dut.tap(driver, "id", groupBurst, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeFBurst)); assertTrue(Dut.verifyExist(driver, "id", modeSBurst)); //Tap on the Single shooting group and then tap outside to get out Dut.tap(driver, "id", groupSingle, 1, 100); Dut.tap(driver, 0.2, 0.3); //Verify icons on the left menu assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); assertTrue(Dut.verifyExist(driver, "name", "Flash settings")); assertTrue(Dut.verifyExist(driver, "name", "Face recognition")); assertTrue(Dut.verifyExist(driver, "name", "Front and back camera switch")); //Switch to front-facing camera to verify displayed icons Dut.tap(driver, "name", "Front and back camera switch", 1, 500); //Verify icons on the left menu assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); assertTrue(Dut.verifyExist(driver, "name", "Face recognition")); assertTrue(Dut.verifyExist(driver, "name", "Front and back camera switch")); //Verify the shutter button and change mode icon exists assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Capture a single shot image on front-facing camera, verify thumbnail existence and go to Gallery. Then delete the image. Dut.imageCapture(driver, "single", 1, 800); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1000); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); //Tap outside and switch to back-facing camera Dut.tap(driver, 0.2, 0.2); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); Dut.wait(driver, 500); Dut.tap(driver, "name", "Front and back camera switch", 1, 500); System.out.println("@@@...Finished checkDisplayedElementsInSingleMode...@@@"); } @Test public void checkDisplayedElementsInSmileMode(){ wait = new WebDriverWait(driver, 15); Dut.wait(driver, 500); String changeMode = "com.intel.camera22:id/mode_button"; String groupSingle = "com.intel.camera22:id/mode_wave_photo"; String modeVideo = "com.intel.camera22:id/mode_wave_video"; String groupBurst = "com.intel.camera22:id/mode_wave_burst"; String modePerfect = "com.intel.camera22:id/mode_wave_perfectshot"; String modePanorama = "com.intel.camera22:id/mode_wave_panorama"; String modeHDR = "com.intel.camera22:id/mode_wave_hdr"; String modeSmile = "com.intel.camera22:id/mode_wave_smile"; String modeSBurst = "com.intel.camera22:id/mode_wave_burst_slow"; String modeFBurst = "com.intel.camera22:id/mode_wave_burst_fast"; System.out.println("@@@...Running checkDisplayedElementsInSmileMode...@@@"); //Change to Smile Cam mode Dut.changeMode(driver, "smile"); //Verify Shutter button availability assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); //Capture an image in Smile mode, verify thumbnail existence and go to Gallery. Then delete the image. Dut.imageCapture(driver, "smile", 1, 300, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1000); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Verify Change Mode icon availability assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); assertTrue(Dut.verifyExist(driver, "id", groupBurst)); assertTrue(Dut.verifyExist(driver, "id", modePerfect)); assertTrue(Dut.verifyExist(driver, "id", modePanorama)); //Verify shooting mode icons under the Single group by switching to Video mode first and then clicking on the Single group icon Dut.tap(driver, "id", modeVideo, 1, 100); Dut.tap(driver, "id", groupSingle, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeHDR)); assertTrue(Dut.verifyExist(driver, "id", modeSmile)); //Tap on the Burst group and verify the modes under it: Dut.tap(driver, "id", groupBurst, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeFBurst)); assertTrue(Dut.verifyExist(driver, "id", modeSBurst)); //Tap on the Single shooting group and then tap on Smile Cam Dut.tap(driver, "id", groupSingle, 1, 500); Dut.tap(driver, "id", modeSmile, 1, 300); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Verify icons on the left menu assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); assertTrue(Dut.verifyExist(driver, "name", "Flash settings")); //Wait until the left menu disappear, then try pulling it out again. //wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Camera settings"))); Dut.wait(driver, 5500); Dut.tap(driver, "id", "com.intel.camera22:id/second_menu_indicator_bar", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Change back to Single mode Dut.changeMode(driver, "single"); System.out.println("@@@...Finished checkDisplayedElementsInSmileMode...@@@"); } @Test public void checkDisplayedElementsInHDRMode(){ wait = new WebDriverWait(driver, 15); Dut.wait(driver, 500); String changeMode = "com.intel.camera22:id/mode_button"; String groupSingle = "com.intel.camera22:id/mode_wave_photo"; String modeVideo = "com.intel.camera22:id/mode_wave_video"; String groupBurst = "com.intel.camera22:id/mode_wave_burst"; String modePerfect = "com.intel.camera22:id/mode_wave_perfectshot"; String modePanorama = "com.intel.camera22:id/mode_wave_panorama"; String modeHDR = "com.intel.camera22:id/mode_wave_hdr"; String modeSmile = "com.intel.camera22:id/mode_wave_smile"; String modeSBurst = "com.intel.camera22:id/mode_wave_burst_slow"; String modeFBurst = "com.intel.camera22:id/mode_wave_burst_fast"; System.out.println("@@@...Running checkDisplayedElementsInHDRMode...@@@"); //Change to HDR mode Dut.changeMode(driver, "hdr"); //Verify Shutter button availability assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); //Capture an HDR image, verify thumbnail existence and go to Gallery. Then delete the image. Dut.imageCapture(driver, "hdr", 1, 700); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1000); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Verify Change Mode icon availability assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); assertTrue(Dut.verifyExist(driver, "id", groupBurst)); assertTrue(Dut.verifyExist(driver, "id", modePerfect)); assertTrue(Dut.verifyExist(driver, "id", modePanorama)); //Verify shooting mode icons under the Single group by switching to Video mode first and then clicking on the Single group icon Dut.tap(driver, "id", modeVideo, 1, 100); Dut.tap(driver, "id", groupSingle, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeHDR)); assertTrue(Dut.verifyExist(driver, "id", modeSmile)); //Tap on the Burst group and verify the modes under it: Dut.tap(driver, "id", groupBurst, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeFBurst)); assertTrue(Dut.verifyExist(driver, "id", modeSBurst)); //Tap on the Single shooting group and then tap HDR Dut.tap(driver, "id", groupSingle, 1, 500); Dut.tap(driver, "id", modeHDR, 1, 300); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Verify icons on the left menu assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); assertTrue(Dut.verifyExist(driver, "name", "Face recognition")); //Wait until the left menu disappear, then try pulling it out again. //wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Camera settings"))); Dut.wait(driver, 5500); Dut.tap(driver, "id", "com.intel.camera22:id/second_menu_indicator_bar", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Change back to Single mode Dut.changeMode(driver, "single"); System.out.println("@@@...Finished checkDisplayedElementsInHDRMode...@@@"); } @Test public void checkDisplayedElementsInVideoMode(){ wait = new WebDriverWait(driver, 15); Dut.wait(driver, 500); String changeMode = "com.intel.camera22:id/mode_button"; String groupSingle = "com.intel.camera22:id/mode_wave_photo"; String modeVideo = "com.intel.camera22:id/mode_wave_video"; String groupBurst = "com.intel.camera22:id/mode_wave_burst"; String modePerfect = "com.intel.camera22:id/mode_wave_perfectshot"; String modePanorama = "com.intel.camera22:id/mode_wave_panorama"; String modeHDR = "com.intel.camera22:id/mode_wave_hdr"; String modeSmile = "com.intel.camera22:id/mode_wave_smile"; String modeSBurst = "com.intel.camera22:id/mode_wave_burst_slow"; String modeFBurst = "com.intel.camera22:id/mode_wave_burst_fast"; System.out.println("@@@...Running checkDisplayedElementsInVideoMode...@@@"); //Change to Video mode Dut.changeMode(driver, "video"); //Verify Shutter button availability assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); //Capture a video file, verify thumbnail existence and go to Gallery. Then delete the file. Dut.imageCapture(driver, "video", 1, 700); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1000); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Verify Change Mode icon availability assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); assertTrue(Dut.verifyExist(driver, "id", groupBurst)); assertTrue(Dut.verifyExist(driver, "id", modePerfect)); assertTrue(Dut.verifyExist(driver, "id", modePanorama)); //Verify shooting mode icons under the Single group by clicking on the Single group icon Dut.tap(driver, "id", groupSingle, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeHDR)); assertTrue(Dut.verifyExist(driver, "id", modeSmile)); //Tap on the Burst group and verify the modes under it: Dut.tap(driver, "id", groupBurst, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeFBurst)); assertTrue(Dut.verifyExist(driver, "id", modeSBurst)); //Tap on the Video shooting group and then tap outside to get out Dut.tap(driver, "id", modeVideo, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); assertTrue(Dut.verifyExist(driver, "name", "Flash settings")); assertTrue(Dut.verifyExist(driver, "name", "Front and back camera switch")); //Wait until the left menu disappear, then try pulling it out again. //wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Camera settings"))); Dut.wait(driver, 5500); Dut.tap(driver, "id", "com.intel.camera22:id/second_menu_indicator_bar", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Switch to front-facing camera to verify displayed icons Dut.tap(driver, "name", "Front and back camera switch", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Verify icons on the left menu assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); assertTrue(Dut.verifyExist(driver, "name", "Front and back camera switch")); //Verify the shutter button and change mode icon exists assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Capture a single shot image on front-facing camera, verify thumbnail existence and go to Gallery. Then delete the image. Dut.imageCapture(driver, "video", 1, 700); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1000); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); //Tap outside and switch to back-facing camera Dut.tap(driver, 0.2, 0.2); //Wait until the left menu disappear, then try pulling it out again. //wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Camera settings"))); Dut.wait(driver, 5300); Dut.tap(driver, "id", "com.intel.camera22:id/second_menu_indicator_bar", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); Dut.tap(driver, "name", "Front and back camera switch", 1, 700); Dut.wait(driver, 500); //Change back to Single mode Dut.changeMode(driver, "single"); System.out.println("@@@...Finished checkDisplayedElementsInVideoMode...@@@"); } @Test public void checkDisplayedElementsInFastBurst(){ wait = new WebDriverWait(driver, 15); Dut.wait(driver, 500); String changeMode = "com.intel.camera22:id/mode_button"; String groupSingle = "com.intel.camera22:id/mode_wave_photo"; String modeVideo = "com.intel.camera22:id/mode_wave_video"; String groupBurst = "com.intel.camera22:id/mode_wave_burst"; String modePerfect = "com.intel.camera22:id/mode_wave_perfectshot"; String modePanorama = "com.intel.camera22:id/mode_wave_panorama"; String modeHDR = "com.intel.camera22:id/mode_wave_hdr"; String modeSmile = "com.intel.camera22:id/mode_wave_smile"; String modeSBurst = "com.intel.camera22:id/mode_wave_burst_slow"; String modeFBurst = "com.intel.camera22:id/mode_wave_burst_fast"; System.out.println("@@@...Running checkDisplayedElementsInFastBurst...@@@"); //Change to Fast Burst mode Dut.changeMode(driver, "fburst"); //Verify Shutter button availability assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); //Capture a fast burst, verify thumbnail existence and go to Gallery. Then delete the file. Dut.imageCapture(driver, "fburst", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 2000); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Verify Change Mode icon availability assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); assertTrue(Dut.verifyExist(driver, "id", groupBurst)); assertTrue(Dut.verifyExist(driver, "id", modePerfect)); assertTrue(Dut.verifyExist(driver, "id", modePanorama)); //Verify shooting mode icons under the Single group by clicking on the Single group icon Dut.tap(driver, "id", groupSingle, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeHDR)); assertTrue(Dut.verifyExist(driver, "id", modeSmile)); //Tap on the Burst group and verify the modes under it: Dut.tap(driver, "id", groupBurst, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeFBurst)); assertTrue(Dut.verifyExist(driver, "id", modeSBurst)); //Tap on the fast burst mode Dut.tap(driver, "id", modeFBurst, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); //Wait until the left menu disappear, then try pulling it out again. Dut.wait(driver, 5500); Dut.tap(driver, "id", "com.intel.camera22:id/second_menu_indicator_bar", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Change back to Single mode Dut.changeMode(driver, "single"); System.out.println("@@@...Finished checkDisplayedElementsInFastBurst...@@@"); } @Test public void checkDisplayedElementsInSlowBurst(){ wait = new WebDriverWait(driver, 15); Dut.wait(driver, 500); String changeMode = "com.intel.camera22:id/mode_button"; String groupSingle = "com.intel.camera22:id/mode_wave_photo"; String modeVideo = "com.intel.camera22:id/mode_wave_video"; String groupBurst = "com.intel.camera22:id/mode_wave_burst"; String modePerfect = "com.intel.camera22:id/mode_wave_perfectshot"; String modePanorama = "com.intel.camera22:id/mode_wave_panorama"; String modeHDR = "com.intel.camera22:id/mode_wave_hdr"; String modeSmile = "com.intel.camera22:id/mode_wave_smile"; String modeSBurst = "com.intel.camera22:id/mode_wave_burst_slow"; String modeFBurst = "com.intel.camera22:id/mode_wave_burst_fast"; System.out.println("@@@...Running checkDisplayedElementsInSlowBurst...@@@"); //Change to Slow Burst mode Dut.changeMode(driver, "sburst"); //Verify Shutter button availability assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); //Capture a slow burst, verify thumbnail existence and go to Gallery. Then delete the file. Dut.imageCapture(driver, "sburst", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 500); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Verify Change Mode icon availability assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); assertTrue(Dut.verifyExist(driver, "id", groupBurst)); assertTrue(Dut.verifyExist(driver, "id", modePerfect)); assertTrue(Dut.verifyExist(driver, "id", modePanorama)); //Verify shooting mode icons under the Single group by clicking on the Single group icon Dut.tap(driver, "id", groupSingle, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeHDR)); assertTrue(Dut.verifyExist(driver, "id", modeSmile)); //Tap on the Burst group and verify the modes under it: Dut.tap(driver, "id", groupBurst, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeFBurst)); assertTrue(Dut.verifyExist(driver, "id", modeSBurst)); //Tap on the Slow Burst mode Dut.tap(driver, "id", modeSBurst, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); //Wait until the left menu disappear, then try pulling it out again. Dut.wait(driver, 5500); Dut.tap(driver, "id", "com.intel.camera22:id/second_menu_indicator_bar", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Change back to Single mode Dut.changeMode(driver, "single"); System.out.println("@@@...Finished checkDisplayedElementsInSlowBurst...@@@"); } @Test public void checkDisplayedElementsInPerfectshot(){ wait = new WebDriverWait(driver, 15); Dut.wait(driver, 500); String changeMode = "com.intel.camera22:id/mode_button"; String groupSingle = "com.intel.camera22:id/mode_wave_photo"; String modeVideo = "com.intel.camera22:id/mode_wave_video"; String groupBurst = "com.intel.camera22:id/mode_wave_burst"; String modePerfect = "com.intel.camera22:id/mode_wave_perfectshot"; String modePanorama = "com.intel.camera22:id/mode_wave_panorama"; String modeHDR = "com.intel.camera22:id/mode_wave_hdr"; String modeSmile = "com.intel.camera22:id/mode_wave_smile"; String modeSBurst = "com.intel.camera22:id/mode_wave_burst_slow"; String modeFBurst = "com.intel.camera22:id/mode_wave_burst_fast"; System.out.println("@@@...Running checkDisplayedElementsInPerfectshot...@@@"); //Change to Perfect Shot mode Dut.changeMode(driver, "perfect"); //Verify Shutter button availability assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); //Capture a Perfect Shot image, verify thumbnail existence and go to Gallery. Then delete the file. Dut.imageCapture(driver, "perfect", 1, 4000); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 500); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Verify Change Mode icon availability assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); assertTrue(Dut.verifyExist(driver, "id", groupBurst)); assertTrue(Dut.verifyExist(driver, "id", modePerfect)); assertTrue(Dut.verifyExist(driver, "id", modePanorama)); //Verify shooting mode icons under the Single group by clicking on the Single group icon Dut.tap(driver, "id", groupSingle, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeHDR)); assertTrue(Dut.verifyExist(driver, "id", modeSmile)); //Tap on the Burst group and verify the modes under it: Dut.tap(driver, "id", groupBurst, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeFBurst)); assertTrue(Dut.verifyExist(driver, "id", modeSBurst)); //Tap on the Perfectshot mode Dut.tap(driver, "id", modePerfect, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); //Wait until the left menu disappear, then try pulling it out again. Dut.wait(driver, 5500); Dut.tap(driver, "id", "com.intel.camera22:id/second_menu_indicator_bar", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Change back to Single mode Dut.changeMode(driver, "single"); System.out.println("@@@...Finished checkDisplayedElementsInPerfectshot...@@@"); } @Test public void checkDisplayedElementsInPanorama(){ wait = new WebDriverWait(driver, 15); Dut.wait(driver, 500); String changeMode = "com.intel.camera22:id/mode_button"; String groupSingle = "com.intel.camera22:id/mode_wave_photo"; String modeVideo = "com.intel.camera22:id/mode_wave_video"; String groupBurst = "com.intel.camera22:id/mode_wave_burst"; String modePerfect = "com.intel.camera22:id/mode_wave_perfectshot"; String modePanorama = "com.intel.camera22:id/mode_wave_panorama"; String modeHDR = "com.intel.camera22:id/mode_wave_hdr"; String modeSmile = "com.intel.camera22:id/mode_wave_smile"; String modeSBurst = "com.intel.camera22:id/mode_wave_burst_slow"; String modeFBurst = "com.intel.camera22:id/mode_wave_burst_fast"; System.out.println("@@@...Running checkDisplayedElementsInPanorama...@@@"); //Change to Panorama mode Dut.changeMode(driver, "panorama"); //Verify Shutter button availability assertTrue(Dut.verifyExist(driver, "name", "Shutter button")); //Capture a Panorama image, verify thumbnail existence and go to Gallery. Then delete the file. Dut.imageCapture(driver, "panorama", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 500); //Tap on the thumbnail Dut.tap(driver, "name", "Most recent photo", 1, 100); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.name("Most recent photo"))); Dut.wait(driver, 1500); //Delete the image folder to clean up Dut.goToAlbumView(driver, "Full View"); Dut.deleteFolder(driver, "100ANDRO", 3); Dut.wait(driver, 700); Dut.sendKeyEvent(driver, 4); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Verify Change Mode icon availability assertTrue(Dut.verifyExist(driver, "id", changeMode)); //Tap of the mode icon to verify other icons Dut.tap(driver, "id", changeMode, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(groupSingle))); //Verify the group icons (Single grouple, Video group, Burst group, Perfectshot group, and Panorama group assertTrue(Dut.verifyExist(driver, "id", groupSingle)); assertTrue(Dut.verifyExist(driver, "id", modeVideo)); assertTrue(Dut.verifyExist(driver, "id", groupBurst)); assertTrue(Dut.verifyExist(driver, "id", modePerfect)); assertTrue(Dut.verifyExist(driver, "id", modePanorama)); //Verify shooting mode icons under the Single group by clicking on the Single group icon Dut.tap(driver, "id", groupSingle, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeHDR)); assertTrue(Dut.verifyExist(driver, "id", modeSmile)); //Tap on the Burst group and verify the modes under it: Dut.tap(driver, "id", groupBurst, 1, 500); assertTrue(Dut.verifyExist(driver, "id", modeFBurst)); assertTrue(Dut.verifyExist(driver, "id", modeSBurst)); //Tap on the Panorama mode Dut.tap(driver, "id", modePanorama, 1, 100); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); assertTrue(Dut.verifyExist(driver, "name", "Camera settings")); //Wait until the left menu disappear, then try pulling it out again. Dut.wait(driver, 5500); Dut.tap(driver, "id", "com.intel.camera22:id/second_menu_indicator_bar", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Camera settings"))); //Change back to Single mode Dut.changeMode(driver, "single"); System.out.println("@@@...Finished checkDisplayedElementsInPanorama...@@@"); } @Test public void testCameraModeChanging(){ wait = new WebDriverWait(driver, 15); Dut.wait(driver, 500); String changeMode = "com.intel.camera22:id/mode_button"; String groupSingle = "com.intel.camera22:id/mode_wave_photo"; String modeVideo = "com.intel.camera22:id/mode_wave_video"; String groupBurst = "com.intel.camera22:id/mode_wave_burst"; String modePerfect = "com.intel.camera22:id/mode_wave_perfectshot"; String modePanorama = "com.intel.camera22:id/mode_wave_panorama"; String modeHDR = "com.intel.camera22:id/mode_wave_hdr"; String modeSmile = "com.intel.camera22:id/mode_wave_smile"; String modeSBurst = "com.intel.camera22:id/mode_wave_burst_slow"; String modeFBurst = "com.intel.camera22:id/mode_wave_burst_fast"; System.out.println("@@@...Running testCameraModeChanging...@@@"); //Change to HDR Dut.changeMode(driver, "hdr"); //Change back to Single Shot Dut.changeMode(driver, "single"); //Change to Smile Cam Dut.changeMode(driver, "smile"); //Change back to Single Shot Dut.changeMode(driver, "single"); //Change to Video mode Dut.changeMode(driver, "video"); //Change back to Single Shot Dut.changeMode(driver, "single"); //Change to Slow Burst Dut.changeMode(driver, "sburst"); //Change back to Single Shot Dut.changeMode(driver, "single"); //Change to Fast Burst mode Dut.changeMode(driver, "fburst"); //Change back to Single Shot Dut.changeMode(driver, "single"); //Change to Perfectshot mode Dut.changeMode(driver, "perfect"); //Change back to Single Shot Dut.changeMode(driver, "single"); //Change to Panorama mode Dut.changeMode(driver, "panorama"); //Change back to Single Shot Dut.changeMode(driver, "single"); //Switch to Single Shot, front camera Dut.tap(driver, "name", "Front and back camera switch", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Change to Video mode on front camera Dut.changeMode(driver, "video"); //Change back to Single Shot front camera Dut.changeMode(driver, "single"); //Switch to Single Shot, back camera Dut.tap(driver, "name", "Front and back camera switch", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Change to HDR so that we can test switching to other modes from HDR Dut.changeMode(driver, "hdr"); //Change to Smile Cam Dut.changeMode(driver, "smile"); //Change back to HDR Dut.changeMode(driver, "hdr"); //Change to Video mode Dut.changeMode(driver, "video"); //Change back to HDR Dut.changeMode(driver, "hdr"); //Change to Slow Burst Dut.changeMode(driver, "sburst"); //Change back to HDR Dut.changeMode(driver, "hdr"); //Change to Fast Burst mode Dut.changeMode(driver, "fburst"); //Change back to HDR Dut.changeMode(driver, "hdr"); //Change to Perfectshot mode Dut.changeMode(driver, "perfect"); //Change back to HDR Dut.changeMode(driver, "hdr"); //Change to Panorama mode Dut.changeMode(driver, "panorama"); //Change back to HDR Dut.changeMode(driver, "hdr"); //Change to Smile Cam mode so that we can test switching to other modes from Smile Cam Dut.changeMode(driver, "smile"); //Change to Video mode Dut.changeMode(driver, "video"); //Change back to Smile Cam Dut.changeMode(driver, "smile"); //Change to Slow Burst Dut.changeMode(driver, "sburst"); //Change back to Smile Cam Dut.changeMode(driver, "smile"); //Change to Fast Burst mode Dut.changeMode(driver, "fburst"); //Change back to Smile Cam Dut.changeMode(driver, "smile"); //Change to Perfectshot mode Dut.changeMode(driver, "perfect"); //Change back to Smile Cam Dut.changeMode(driver, "smile"); //Change to Panorama mode Dut.changeMode(driver, "panorama"); //Change back to Smile Cam Dut.changeMode(driver, "smile"); //Change to Video mode so that we can test switching to other modes from Video Dut.changeMode(driver, "video"); //Change to Slow Burst Dut.changeMode(driver, "sburst"); //Change back to Video mode Dut.changeMode(driver, "video"); //Change to Fast Burst mode Dut.changeMode(driver, "fburst"); //Change back to Video mode Dut.changeMode(driver, "video"); //Change to Perfectshot mode Dut.changeMode(driver, "perfect"); //Change back to Video mode Dut.changeMode(driver, "video"); //Change to Panorama mode Dut.changeMode(driver, "panorama"); //Change back to Video mode Dut.changeMode(driver, "video"); //Switch to Video, front camera Dut.tap(driver, "name", "Front and back camera switch", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Switch back to Video, back camera Dut.tap(driver, "name", "Front and back camera switch", 1, 500); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Shutter button"))); //Change to Slow Burst mode so that we can test switching to other modes from Slow Burst Dut.changeMode(driver, "sburst"); //Change to Fast Burst mode Dut.changeMode(driver, "fburst"); //Change back to Slow Burst mode Dut.changeMode(driver, "sburst"); //Change to Perfectshot mode Dut.changeMode(driver, "perfect"); //Change back to Slow Burst mode Dut.changeMode(driver, "sburst"); //Change to Panorama mode Dut.changeMode(driver, "panorama"); //Change back to Slow Burst mode Dut.changeMode(driver, "sburst"); //Change to Fast Burst mode so that we can test switching to other modes from Fast Burst Dut.changeMode(driver, "fburst"); //Change to Perfectshot mode Dut.changeMode(driver, "perfect"); //Change back to Fast Burst mode Dut.changeMode(driver, "fburst"); //Change to Panorama mode Dut.changeMode(driver, "panorama"); //Change back to Fast Burst mode Dut.changeMode(driver, "fburst"); //Change to Perfectshot mode so that we can test switching to other modes from Perfectshot Dut.changeMode(driver, "perfect"); //Change to Panorama mode Dut.changeMode(driver, "panorama"); //Change back to Perfectshot mode Dut.changeMode(driver, "perfect"); //Change back to Single mode Dut.changeMode(driver, "single"); System.out.println("@@@...Finished testCameraModeChanging...@@@"); } //@Test /* public void testNewMethods(){ wait = new WebDriverWait(driver, 10); //menu = driver.findElement(By.name("More options")); System.out.println("@@@...Running testNewMethods...@@@"); Dut.wait(driver, 2000); WebElement element = driver.findElement(By.name("Shutter button")); JavascriptExecutor js = (JavascriptExecutor) driver; HashMap<String, Integer> tapObject = new HashMap<String, Integer>(); tapObject.put("element", (Integer)((RemoteWebElement) element).getId()); tapObject.put("duration", 4); js.executeScript("mobile: longClick", tapObject); // HashMap<String, Integer> tapObject = new HashMap<String, Integer>(); // tapObject.put("element", element); // JavascriptExecutor js = (JavascriptExecutor) driver; // HashMap<String, Integer> tapObject = new HashMap<String, Integer>(); // tapObject.put("x", 360); // in pixels from left // tapObject.put("y", 1190); // in pixels from top // tapObject.put("duration", 4); // js.executeScript("mobile: complexTap", tapObject); // js.executeScript("mobile: complexTap", ["touchCount": 1, "x": 360, "y": 1190, "duration": 4, "element": element]); //Dut.longTap(driver, 360, 1190); // System.out.printf("Element id: %s\n", ((RemoteWebElement) element).getId()); System.out.println("@@@...Finished testNewMethods...@@@"); } */ }<file_sep>package androidPages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.concurrent.TimeUnit; import io.appium.java_client.AppiumDriver; import io.appium.java_client.TouchAction; public class SinglePreview_Settings { private AppiumDriver driver; WebDriverWait wait; String depthModeSelector = "text(\"Depth\")"; String burstSelector = "text(\"Burst\")"; String settingNameContainer = "resourceId(\"com.intel.camera22:id/setting_item_name\").enabled(true)"; public SinglePreview_Settings(AppiumDriver drive) { driver = drive; wait = new WebDriverWait(driver, 10); driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); } public boolean menuIsOpen() { if (!driver.findElementsByAndroidUIAutomator(settingNameContainer).isEmpty()) return true; else return false; } public CamPreview_Depth selectDepthMode() throws InterruptedException{ Thread.sleep(300); WebElement depthIcon = driver.findElementByAndroidUIAutomator(depthModeSelector); new TouchAction(driver).tap(depthIcon).perform(); return new CamPreview_Depth(driver); } public CamPreviewBurst_SubMenu selectBurstMode() throws InterruptedException{ Thread.sleep(300); WebElement burstIcon = driver.findElementByAndroidUIAutomator(burstSelector); new TouchAction(driver).tap(burstIcon).perform(); return new CamPreviewBurst_SubMenu(driver); } } <file_sep>package androidPages; // import org.openqa.selenium.*; // import org.openqa.selenium.By; // import org.openqa.selenium.support.ui.WebDriverWait; // import org.openqa.selenium.support.ui.ExpectedConditions; // import org.openqa.selenium.interactions.HasTouchScreen; // import org.openqa.selenium.interactions.TouchScreen; // import org.openqa.selenium.remote.CapabilityType; // import org.openqa.selenium.remote.RemoteTouchScreen; // import org.openqa.selenium.remote.RemoteWebDriver; // import org.openqa.selenium.internal.Locatable; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.internal.Locatable; import org.openqa.selenium.remote.DesiredCapabilities; import java.util.HashMap; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; // import java.net.URL; // import java.text.ParseException; // import java.text.SimpleDateFormat; // import java.util.regex.*; // import java.util.*; import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.AppiumDriver; import io.appium.java_client.TouchAction; import static org.junit.Assert.*; import static org.junit.Assert.*; public class BB { private AppiumDriver driver; public BB(AppiumDriver driver) { this.driver = driver; } // Method to put the driver to sleep for a number of mili-seconds public static void wait(Integer milisec) { try { Thread.sleep(milisec); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } // Method to tap on a coordinate in percentage public void tapScreen(Double x_percent, Double y_percent) { JavascriptExecutor js = (JavascriptExecutor) driver; HashMap<String, Double> tapObject = new HashMap<String, Double>(); tapObject.put("x", x_percent); // in percentage of the screen width from the left tapObject.put("y", y_percent); // in percentage of the screen height from the top js.executeScript("mobile: tap", tapObject); } // Method to find the number of files from a particular folder on the device. public int findNumberOfFiles(String dFolderPath) throws InterruptedException { int numOfFiles = 0; Thread.sleep(500); try { ProcessBuilder process = new ProcessBuilder("adb", "shell", "ls", dFolderPath, "|", "wc", "-l"); Process p = process.start(); //Thread.sleep(5000); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; p.waitFor(); while ((line = br.readLine()) != null) { if (!line.equals("")) numOfFiles = Integer.parseInt(line); } } catch (Exception e){ System.out.println(e); } return numOfFiles; } // Method to retrieve a certain value from the camera preference xml files public String getValueFromXML(String fileName, String filterTerm, String searchPattern, Integer searchGroupIndex) throws InterruptedException { String xmlPath = "/data/data/com.intel.camera22/shared_prefs/"; String xmlLine = ""; Thread.sleep(500); try { ProcessBuilder process = new ProcessBuilder("adb", "shell", "cat", xmlPath + fileName, "|", "grep", filterTerm); Process p = process.start(); Thread.sleep(5000); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; p.waitFor(); while ((line = br.readLine()) != null) { if (!line.equals("")) xmlLine = line.toString(); } } catch (Exception e){ System.out.println(e); } Pattern compiledPattern = Pattern.compile(searchPattern); Matcher m = compiledPattern.matcher(xmlLine); String xmlValue = ""; if (m.find()) { xmlValue = m.group(searchGroupIndex).toString(); System.out.printf("The value for the '%s' filter is '%s'.\n", filterTerm, xmlValue); } else { System.out.println("Could not retrieve a value from the camera preference xml files!"); assertTrue(false); } return xmlValue; } // Method to get the current camera mode public String getCameraMode() throws InterruptedException{ String modeBtnLocator = "description(\"Show switch camera mode list\")"; String hdrON = "text(\"HDR\nON\")"; String smileON = "text(\"Smile\nON\")"; String currentMode = ""; Thread.sleep(500); String valueString = getValueFromXML("mode_selected.xml", "Mode", "value=.(\\d+).", 1); Integer valueInt = Integer.parseInt(valueString); switch(valueInt){ case 1: driver.findElementByAndroidUIAutomator(modeBtnLocator).click(); Thread.sleep(400); if (!driver.findElementsByAndroidUIAutomator(hdrON).isEmpty()) { System.out.println("Current mode is HDR."); currentMode = "hdr"; tapScreen(0.5, 0.5); break; } else if (!driver.findElementsByAndroidUIAutomator(smileON).isEmpty()) { System.out.println("Current mode is Smile."); currentMode = "smile"; tapScreen(0.5, 0.5); break; } else { System.out.println("Current mode is Single Shot."); currentMode = "single"; tapScreen(0.5, 0.5); break; } case 5: System.out.println("Current mode is Burst."); currentMode = "burst"; break; case 7: System.out.println("Current mode is Perfectshot."); currentMode = "perfect"; break; case 9: System.out.println("Current mode is Video."); currentMode = "video"; break; case 11: System.out.println("Current mode is Panorama."); currentMode = "pano"; break; case 12: System.out.println("Current mode is Depth."); currentMode = "depth"; break; default: System.out.println("Current camera mode is not recognized."); assertTrue(false); } return currentMode; } // Method to get the current camera facing direction public String getCameraDirection() throws InterruptedException{ String currentDirection = ""; Thread.sleep(500); String valueString = getValueFromXML("com.intel.camera22_preferences_0.xml ", "id_key", ">(\\d+)<", 1); Integer valueInt = Integer.parseInt(valueString); switch(valueInt){ case 0: System.out.println("Camera is back-facing."); currentDirection = "back"; break; case 1: System.out.println("Camera is front-facing."); currentDirection = "front"; break; default: System.out.println("Current camera mode is not recognized."); assertTrue(false); } return currentDirection; } // Method to remove a folder from the device public void deleteDeviceFolder(String dFolderPath, int waitTime) { try { ProcessBuilder process = new ProcessBuilder("adb", "shell", "rm", "-r", dFolderPath); process.start(); Thread.sleep(waitTime); process = new ProcessBuilder("adb", "shell", "am", "broadcast", "-a", "android.intent.action.MEDIA_MOUNTED", "-d", "file:///mnt/sdcard"); process.start(); Thread.sleep(waitTime); } catch (Exception e){} } // Method to calculate a WebElement x-coordinate public int getCenterXCoordinate(WebElement el) { //Find the item's upper left point. Point p = ((Locatable)el).getCoordinates().onPage(); //Find the item's width to calculate its center int itemWidth = el.getSize().width; int xCoordinate = p.x + (itemWidth / 2); System.out.printf("X coordinate is %d\n", xCoordinate); return xCoordinate; } // Method to calculate a WebElement y-coordinate public int getCenterYCoordinate(WebElement el) { //Find the item's upper left point. Point p = ((Locatable)el).getCoordinates().onPage(); System.out.printf("Y coordinate is %d\n", p.y); //Find the item's height to calculate its center int itemHeight = el.getSize().height; int yCoordinate = p.y + (itemHeight / 2); System.out.printf("Y coordinate is %d\n", yCoordinate); return yCoordinate; } } <file_sep>applicationUrl=C:\\Appium2\\Appium\\SocialCam23_BB device=android<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.intel.socialcam</groupId> <artifactId>socialcam23_bb</artifactId> <version>1.0-SNAPSHOT</version> <properties> <applicationUrl>C:\\Appium2\\Appium\\SocialCam23_BB</applicationUrl> <device>android</device> </properties> <build> <testResources> <testResource> <directory>src/test/resources</directory> <filtering>true</filtering> </testResource> </testResources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.17</version> <executions> <execution> <id>acceptance-test</id> <phase>integration-test</phase> <goals> <goal>test</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>LATEST</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.2</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.2.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.5.RELEASE</version> </dependency> <dependency> <groupId>io.appium</groupId> <artifactId>java-client</artifactId> <version>2.1.0</version> </dependency> </dependencies> </project><file_sep>package androidPages; import java.util.concurrent.TimeUnit; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileBy; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class CamPreview_Smile { private AppiumDriver driver; WebDriverWait wait; String clickableShutterBtnLocator = "description(\"Shutter button\").clickable(true).enabled(true)"; String modeBtnLocator = "description(\"Show switch camera mode list\")"; String clickableModeBtnLocator = "description(\"Show switch camera mode list\").clickable(true).enabled(true)"; public CamPreview_Smile(AppiumDriver drive) { driver = drive; wait = new WebDriverWait(driver, 15); driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); } public CamPreview_Smile capture(Integer numberOfCaptures, Integer msTimeBetweenTaps) throws InterruptedException{ wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AndroidUIAutomator(clickableShutterBtnLocator))); WebElement shutterBtn = driver.findElementByAndroidUIAutomator(clickableShutterBtnLocator); for (int n = 0; n < numberOfCaptures; n++) { wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AndroidUIAutomator(modeBtnLocator))); shutterBtn.click(); Thread.sleep(1300); //wait.until(ExpectedConditions.invisibilityOfElementLocated(MobileBy.AndroidUIAutomator(clickableModeBtnLocator))); shutterBtn.click(); Thread.sleep(msTimeBetweenTaps); } return this; } }
be70fe7e0f1352b4b0777616caaf1dd352a68fb5
[ "Java", "Maven POM", "INI" ]
13
Java
andrewtdinh/AppiumScripts2
4d135b9e4f24837d79c72662944c6327acfbe698
97b0c5cfa60a7bd6a5909248919950a4d0a290c3
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; use App\User; class PostController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { if(request()->has('sort')){ $posts = Post::where('Fname', request('sort')) ->paginate(5)->appends('sort', request('sort')); } $posts = Post::orderBy('Fname','asc')->paginate(5); return view('posts.index')->with('posts', $posts); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('posts.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'Fname'=>'required|min:3|max:50', 'Lname'=>'required|min:3|max:50', 'Mnumber'=>'required|min:10|max:10', 'Hnumber'=>'required|min:10|max:10', ]); //Create new Post $post = new Post; $post->Fname = $request->input('Fname'); $post->Lname = $request->input('Lname'); $post->Mnumber = $request->input('Mnumber'); $post->Hnumber = $request->input('Hnumber'); $post->user_id = auth()->user()->id; $post->save(); return redirect('/posts')->with('success', 'Contact Created'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $post = Post::find($id); return view('posts.show')->with('posts', $post); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $post = Post::find($id); if(auth()->user()->id !==$post->user_id){ return redirect('/posts')->with('error', 'This is not ur contact'); } return view('posts.edit')->with('post', $post); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'Fname'=>'required|min:3|max:50', 'Lname'=>'required|min:3|max:50', 'Mnumber'=>'required|min:10|max:10', 'Hnumber'=>'required|min:10|max:10', ]); //Create new Post $post = Post::find($id); $post->Fname = $request->input('Fname'); $post->Lname = $request->input('Lname'); $post->Mnumber = $request->input('Mnumber'); $post->Hnumber = $request->input('Hnumber'); $post->save(); return redirect('/posts')->with('success', 'Contact Updated'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $post = Post::find($id); if(auth()->user()->id !==$post->user_id){ return redirect('/posts')->with('error', 'This is not ur contact'); } $post -> delete(); return redirect('/posts')->with('success', 'Contact Removed'); } }
a96b20cd3db53125ceff22cccc453d08245d4f58
[ "PHP" ]
1
PHP
N-Stefanov/PhoneBook
0f565835771098be206eaaa8662142746974a64d
576c6271fd062bb00a44818d2b26fcc50c185579
refs/heads/master
<repo_name>pombredanne/ST3-Find-on-npm<file_sep>/FindPackage.py import sublime import sublime_plugin import re import webbrowser class FindPackageCommand(sublime_plugin.TextCommand): def run(self, edit): view = self.view region = view.sel()[0] if not region.empty(): text = view.substr(region) else: selection = view.sel()[0] text = view.substr(view.line(selection)) strings = re.findall(r"['\"](.*?)['\"]", text) if len(strings): package = strings[-1] url = "https://www.npmjs.com/package/{}".format(package) webbrowser.open_new_tab(url) <file_sep>/README.md # ST3-Find-on-npm Right click an import/require statement in Sublime Text to go to it's NPM page Currently only tested in ST3 ## TODO - [ ] Check line contains import/require - [ ] Better handling of multiple selection regions - [ ] Improve package name search (not just last string in region) - [ ] Don't run on relative paths - [ ] Add tests - [ ] Add option to view on github - [ ] Add option to view on local filesystem
7be7243a56899708b9b87d75d6ef17eea03764c5
[ "Markdown", "Python" ]
2
Python
pombredanne/ST3-Find-on-npm
6d01d182d3da9d08c59c6c06cf9bee278007d219
c7c4df07c9e2fe50a8ff772173ce5a014a90f818
refs/heads/master
<repo_name>Surya2709/personal-linux-voice-assistant<file_sep>/skills.py from __future__ import print_function import pickle import engine import auth_google import Audio import os import sys import pytz import datetime import time import requests,json import urllib import socket import subprocess import webbrowser import wikipedia import pyscreenshot as ImageGrab from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from googlesearch import * import strlists import bs4 from bs4 import BeautifulSoup as soup def fetch_google_news(): try: news_url="https://news.google.com/news/rss" Client=urlopen(news_url) xml_page=Client.read() Client.close() soup_page=soup(xml_page,"xml") news_list=soup_page.findAll("item") # Print news title, url and publish date for news in news_list: print(news.title.text) engine.speak(news.title.text) except: engine.speak('something went wrong master,it seems our internet connection felt to be failed master!') def wikipedia_search(): try: engine.speak("what to search in wikipedia master?please tell me again clearly master") search_string=Audio.get_audio() engine.speak("searching master") print(wikipedia.summary(search_string, sentences=2)) engine.speak(wikipedia.summary(search_string, sentences=2)) except: engine.speak("sorry master no results found!") def get_events(day,service): try: # Call the Calendar API date = datetime.datetime.combine(day, datetime.datetime.min.time()) end_date = datetime.datetime.combine(day, datetime.datetime.max.time()) utc = pytz.UTC date = date.astimezone(utc) end_date = end_date.astimezone(utc) events_result = service.events().list(calendarId='primary', timeMin=date.isoformat(), timeMax=end_date.isoformat(), singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: engine.speak("No upcoming events found master ") else: engine.speak("you have "+len(events)+"events on this day.") for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) start_time = str(start.split("T")[1].split("-")[0]) if int(start_time.split(":")[0]) < 12: start_time = start_time + "am" else: start_time =str(int(start_time.split(":")[0])-12) + start_time.split(":")[1] start_time = start_time + "pm" engine.speak(event["summary"]+ "at" + start_time) except: pass def google_search(text): try: IPaddress=socket.gethostbyname(socket.gethostname()) if IPaddress=="127.0.0.1": engine.speak("there is something wrong while connecting master") else: url='https://www.google.com/search?q=' search_url=url+text engine.speak("connecting master") webbrowser.get('google-chrome').open_new_tab(search_url) except: pass def youtube_search(text): try: IPaddress=socket.gethostbyname(socket.gethostname()) if IPaddress=="127.0.0.1": engine.speak("there is something wrong while connecting master") else: url='https://www.youtube.com/results?search_query=' search_url=url+text engine.speak("opening results master") webbrowser.get('google-chrome').open_new_tab(search_url) except: pass def scrnshot(): try: im = ImageGrab.grab() im.save('screenshot.png') im.show() except: pass def get_weather(text): api_key = "<KEY>" base_url = "http://api.openweathermap.org/data/2.5/weather?" complete_url = base_url + "appid=" + api_key + "&q=" + text response = requests.get(complete_url) x=response.json() try: if x["cod"] != "404": y = x["main"] current_temperature = y["temp"] current_pressure = y["pressure"] current_humidiy = y["humidity"] z = x["weather"] weather_description = z[0]["description"] print(" Temperature (in kelvin unit) = " + str(current_temperature) + "\n atmospheric pressure (in hPa unit) = " + str(current_pressure) + "\n humidity (in percentage) = " + str(current_humidiy) + "\n description = " + str(weather_description)) engine.speak(" Temperature (in kelvin unit) = " + str(current_temperature) + "\n atmospheric pressure (in hPa unit) = " + str(current_pressure) + "\n humidity (in percentage) = " + str(current_humidiy) + "\n description = " + str(weather_description)) else: engine.speak("sorry master I am unable to find the city master") except: engine.speak("sorry master something happened while checking weather") pass def get_date(text): text = text.lower() today = datetime.date.today() if text.count("today") > 0: return today day = -1 day_of_week = -1 month = -1 year = today.year for word in text.split(): if word in strlists.MONTHS: month = strlists.MONTHS.index(word) + 1 elif word in strlists.DAYS: day_of_week = strlists.DAYS.index(word) elif word.isdigit(): day = int(word) else: for ext in strlists.DAY_EXTENTIONS: found = word.find(ext) if found > 0: try: day = int(word[:found]) except: pass if month < today.month and month != -1: # if the month mentioned is before the current month set the year to the next year = year+1 # This is slighlty different from the video but the correct version if month == -1 and day != -1: # if we didn't find a month, but we have a day if day < today.day: month = today.month + 1 else: month = today.month # if we only found a dta of the week if month == -1 and day == -1 and day_of_week != -1: current_day_of_week = today.weekday() dif = day_of_week - current_day_of_week if dif < 0: dif += 7 if text.count("next") >= 1: dif += 7 return today + datetime.timedelta(dif) if month== -1 or day ==-1: pass return None return datetime.date(month=month, day=day, year=year) def note(text): date=datetime.datetime.now() file_name = str(date).replace(":","-") + "note.txt" with open(file_name,"w") as f: f.write(text) subprocess.Popen(["pluma",file_name]) <file_sep>/README.md # personal-linux-voice-assistant Our system is an intelligent virtual assistant (IVA) or intelligent personal assistant (IPA).Our system is a software agent that can perform tasks or services for an individual based on commands or questions. It is completely made for the usage of this system in Linux operating systems. This system is programmed in python 3 and it uses speech recognition library in python 3. Our software features many advanced features such as voice commanded operations such as Event Remainders, Weather forecasting, You-tube search, Google search, Wikipedia search, Opening of Applications, Voice typing and keyboard controls. Our system uses python speech recognition library to extract data from the user speech data. The personal Linux voice assistant ease out the use of Linux system by making the operating system more user friendly. <file_sep>/main.py #!/usr/bin/env python from __future__ import print_function import pickle import engine import auth_google import skills import Audio import openfun import os import datetime import requests,json import urllib import strlists import voicetyping SERVICE = auth_google.authenticate_google() while True: print ("listening....") text = Audio.get_audio() if text.count(strlists.WAKE1) > 0: engine.speak("yes master proceed") text = Audio.get_audio() if text.count(strlists.WAKE2) > 0: engine.speak("I am ready master") text = Audio.get_audio() if text.count(strlists.WAKE3) > 0: engine.speak("yes master,i am here") text = Audio.get_audio() if text.count(strlists.WAKE4) > 0: engine.speak("I am ready master") text = Audio.get_audio() if text.count(strlists.WAKE5) > 0: engine.speak("yeah master") text = Audio.get_audio() if text.count(strlists.WAKE6) > 0: engine.speak("I am ready master") text = Audio.get_audio() if text.count(strlists.WAKE7) > 0: engine.speak("yes master") text = Audio.get_audio() if text.count(strlists.WAKE8) > 0: engine.speak("I am ready master") text = Audio.get_audio() if text.count(strlists.WAKE9) > 0: engine.speak("yes i am master") text = Audio.get_audio() for phrase in strlists.GREETING_STR1: if phrase in text: engine.speak("yes master") else: pass for phrase in strlists.GREETING_STR2: if phrase in text: engine.speak("I am fine master") for phrase in strlists.CALENDAR_STRS: if phrase in text: date = skills.get_date(text) if date: skills.get_events(date,SERVICE) else: engine.speak("Please say again master ,I can't understand") for phrase in strlists.WEATHER_STRS: if phrase in text: engine.speak("which place master?") area = Audio.get_audio() skills.get_weather(area) engine.speak("Anything Else Master?") break for phrase in strlists.SEARCH_STRS: for phrase in strlists.SEARCH_GOOGLE_STR: if phrase in text: engine.speak("what to search master?,please tell me again") text = Audio.get_audio() skills.google_search(text) engine.speak("searching master!") break for phrase in strlists.SEARCH_WIKIPEDIA_STR: if phrase in text: skills.wikipedia_search() break for phrase in strlists.SEARCH_YOUTUBE_STR: if phrase in text: engine.speak("what to search master ?,please tell me!") query = Audio.get_audio() skills.youtube_search(query) break for phrase in strlists.NOTE_STRS: if phrase in text: engine.speak("what would you like me to write down master?") note_text = Audio.get_audio() skills.note(note_text) engine.speak("I've made a note of that.") break for phrase in strlists.SCREENSHOT_STR: if phrase in text: engine.speak("taking screen shot master") skills.scrnshot() break for phrase in strlists.ASKFOR_GAME: if phrase in text: engine.speak("do you want to play chess master?") text = Audio.get_audio() if "yes" in text: openfun.xboard() else: engine.speak("ok master") for phrase in strlists.VOICETYPING_STR: if phrase in text: for phrase in strlists.ON_STR: if phrase in text: engine.speak("voice typing ready master") engine.speak("please use the command switch off voice typing to return me to the normal mode master") voicetyping.typein() break for phrase in strlists.START_STR: if phrase in text: for phrase in strlists.HTTP_STR: if phrase in text: engine.speak("turning on the ngnix http server master") openfun.http_start() break for phrase in strlists.POSTGRESQL_STR: if phrase in text: engine.speak("turning on the postgresql server master") openfun.postgresql_start() break for phrase in strlists.SSHD_STR: if phrase in text: engine.speak("turning on the sshd sever master") openfun.sshd_start() break for phrase in strlists.WIFI_STR: if phrase in text: engine.speak("turning on the wifi master") openfun.wifi_on() break for phrase in strlists.BLUETOOTH_STR: if phrase in text: engine.speak("turning on the bluetooth master") openfun.bluetooth_on() break for phrase in strlists.RESTART_STR: if phrase in text: for phrase in strlists.HTTP_STR: if phrase in text: engine.speak("restarting the ngnix http server master") openfun.http_restart() break for phrase in strlists.POSTGRESQL_STR: if phrase in text: engine.speak("restarting the postgresql server master") openfun.postgresql_restart() break for phrase in strlists.SSHD_STR: if phrase in text: engine.speak("restarting the sshd sever master") openfun.sshd_restart() break for phrase in strlists.WIFI_STR: if phrase in text: engine.speak("restarting the wifi master") openfun.wifi_off() openfun.wifi_on() break for phrase in strlists.BLUETOOTH_STR: if phrase in text: engine.speak("restarting the bluetooth master") openfun.bluetooth_off() openfun.bluetooth_on() break else: pass for phrase in strlists.STOP_STR: if phrase in text: for phrase in strlists.HTTP_STR: if phrase in text: engine.speak("turning off ngnix http server master") openfun.http_stop() break for phrase in strlists.POSTGRESQL_STR: if phrase in text: engine.speak("turning off postgresql server master") openfun.postgresql_stop() break for phrase in strlists.SSHD_STR: if phrase in text: engine.speak("turning off sshd sever master") openfun.sshd_stop() break for phrase in strlists.WIFI_STR: if phrase in text: engine.speak("turning off wifi master") openfun.wifi_off() break for phrase in strlists.BLUETOOTH_STR: if phrase in text: engine.speak("turning off bluetooth master") openfun.bluetooth_off() break else: pass #opeing the apps loop starts here #################################### #################################### #################################### for phrase in strlists.OPEN_STR: if phrase in text: for phrase in strlists.GOOGLE_STR: if phrase in text: engine.speak("opening google chrome master") openfun.google() break for phrase in strlists.FIREFOX_STR: if phrase in text: engine.speak("opening firefox master") openfun.firefox() break for phrase in strlists.CAMERA_STR: if phrase in text: engine.speak("opening the camera master") openfun.camera() break for phrase in strlists.AIRCRACK_STR: if phrase in text: engine.speak("opening the aircrack-ng master") openfun.aircrack() break for phrase in strlists.AIRGEDDON_STR: if phrase in text: engine.speak("opening the the airgeddon master") openfun.airgeddon() break for phrase in strlists.BURPSUITE_STR: if phrase in text: engine.speak("opening the burpsuiute master!") openfun.burpsuite() break for phrase in strlists.ETTERCAP_GRAPH_STR: if phrase in text: engine.speak("opening the ettercap graph") openfun.ettercap_graphical() break for phrase in strlists.GO_BUSTER_STR: if phrase in text: engine.speak("opening the go buster master!") openfun.gobuster() break for phrase in strlists.JOHNNY_STR: if phrase in text: engine.speak("opening the johnny tool master!") openfun.johnny() break for phrase in strlists.KAYAK_CAR_HACKING_TOOL: if phrase in text: engine.speak("opening the kayak car tool master!") openfun.ophcrack() break for phrase in strlists.OWASP_STR: if phrase in text: engine.speak("opening the owasp master!") openfun.owasp() break for phrase in strlists.WEEVELY_STR: if phrase in text: engine.speak("opening the weevely master!") openfun.weevely() break for phrase in strlists.WIRESHARK_STR: if phrase in text: engine.speak("opening the wire shark master!") openfun.wireshark() break for phrase in strlists.ZENMAP_STR: if phrase in text: engine.speak("opening the zenmap tool master!") openfun.zenmap() break for phrase in strlists.DNS_ANALYSIS: if phrase in text: engine.speak("opening the dns analysis tootl master!") openfun.dnsanalysis() break for phrase in strlists.IDPS_IPS_IDENTOFICATION_STR: if phrase in text: engine.speak("openin the idps ips identification tool master!") openfun.idps_ips_identification() break for phrase in strlists.LIVE_HOST_IDENTIFIER_STR: if phrase in text: engine.speak("opeing the idps ips identifying tool master!") openfun.live_host_identification() break for phrase in strlists.NETWORK_OR_PORT_SCANNER_STR: if phrase in text: engine.speak("opening the network or port scanner tool master!") openfun.network_or_port_scanner() break for phrase in strlists.OSINT_ANALYSIS_STR: if phrase in text: engine.speak("opening the o s i n t tool master!") openfun.osint_analysis() break for phrase in strlists.ROUTE_ANALYSIS_STR: if phrase in text: engine.speak("opening the route analysis tool master!") openfun.route_analysis() break for phrase in strlists.MALTEGO_STR: if phrase in text: engine.speak("opening the maltego tool master!") openfun.maltego() break for phrase in strlists.ARMITAGE_STR: if phrase in text: engine.speak("opening the armitage tool master!") openfun.armitage() break for phrase in strlists.SBM_ANALYSIS_STR: if phrase in text: engine.speak("opening the SBM analysis tools master") openfun.sbm_analysis() break for phrase in strlists.SNMP_ANALYSIS_STR: if phrase in text: engine.speak("opening the SNMP analysis master") openfun.snmp_analysis() break for phrase in strlists.SSL_ANALYSIS_STR: if phrase in text: engine.speak("opening the SSL analysis master") openfun.ssl_analysis() break for phrase in strlists.AMAP_STR: if phrase in text: engine.speak("opening the AMAP master") openfun.amap() break for phrase in strlists.DMITRY_STR: if phrase in text: engine.speak("opening the Dimitri master") openfun.dmitry() break for phrase in strlists.DNMAP_SERVER_STR: if phrase in text: engine.speak("opening the dnmap server master!") openfun.dnmap_server() break for phrase in strlists.DNMAP_CLIENT_STR: if phrase in text: engine.speak("opening the dnmap client master") openfun.dnmap_client() break for phrase in strlists.IKE_STR: if phrase in text: engine.speak("opening the ike tool master!") openfun.ike_scan() break for phrase in strlists.NET_DISCOVER_STR: if phrase in text: engine.speak("opening the net discover master") openfun.net_discover() break for phrase in strlists.POF_TOOL_STR: if phrase in text: engine.speak("opening the pof master!") openfun.pOf() break for phrase in strlists.RECON_NG_STR: if phrase in text: engine.speak("opening the recon ng master") openfun.recon_ng() break for phrase in strlists.CISCO_STR: if phrase in text: engine.speak("opening the cisco master") openfun.cisco_tools() break for phrase in strlists.FUZZING_TOOL_STR: if phrase in text: engine.speak("opening the fuzzing tool master") openfun.fuzzing_tools() break for phrase in strlists.OPEN_VAS_SCANNER_TOOL_STR: if phrase in text: engine.speak("opening the open vas scanner master") openfun.open_vas_scanner() break for phrase in strlists.STRESS_TESTING_TOOL_STR: if phrase in text: engine.speak("opening the stress testing tools master") openfun.stress_testing() break for phrase in strlists.VOIP_TOOLS_STR: if phrase in text: engine.speak("opening the voip tools master") openfun.voip_tool() break for phrase in strlists.GOLISMERO_STR: if phrase in text: engine.speak("opening the golismero master") openfun.golismero() break for phrase in strlists.LYNIS_STR: if phrase in text: engine.speak("opening the lynis tool master") openfun.lynis() break for phrase in strlists.UNIX_PRISEV_CHECK: if phrase in text: engine.speak("opening the unix preserve check master") openfun.unix_privesv_check() break for phrase in strlists.FILE_MANAGER_STR: if phrase in text: engine.speak("opening the file manager master") openfun.file_manger_or_places() break for phrase in strlists.DOCUMENTS_STR: if phrase in text: engine.speak("opening the documents master") openfun.documents() break for phrase in strlists.DESKTOP_STR: if phrase in text: engine.speak("opening the desktop master") openfun.desktop() break for phrase in strlists.DOWNLOADS_STR: if phrase in text: engine.speak("opening the downloads master") openfun.Downloads() break for phrase in strlists.MUSIC_STR: if phrase in text: engine.speak("opening the pictures master") openfun.pictures() break for phrase in strlists.PICTURES_STR: if phrase in text: engine.speak("opening the pictures master") openfun.pictures() break for phrase in strlists.VIDEOS_STR: if phrase in text: engine.speak("opening the videos master") openfun.videos() break for phrase in strlists.TRASH_STR: if phrase in text: engine.speak("opening the trash master") openfun.trash() break for phrase in strlists.CMS_AND_FRAMEWORK_STR: if phrase in text: engine.speak("opening the cms and framework master") openfun.cms_and_framework() break for phrase in strlists.WPSCAN_STR: if phrase in text: engine.speak("opening the wps scan master") openfun.cms_and_framework() break for phrase in strlists.WIG_STR: if phrase in text: engine.speak("opening the wig master") openfun.wig() break for phrase in strlists.UA_TESTER_STR: if phrase in text: engine.speak("opening the ua tester master") openfun.ua_tester() break for phrase in strlists.WEBCRAWLER_AND_DIRECTORY_STR: if phrase in text: engine.speak("opening the webcrawler and directory tool master") openfun.web_crawlers_and_directory() break for phrase in strlists.APACHE_USER_STR: if phrase in text: engine.speak("opening the apache user tool master") openfun.apache_users() break for phrase in strlists.UNISCAN_STR: if phrase in text: engine.speak("opening the uni scan master") openfun.uniscan_gui() break for phrase in strlists.WEB_VULNERABILITY_STR: if phrase in text: engine.speak("opening the web vulnerability master") openfun.web_vulnerability_scanner() break for phrase in strlists.CADAVAR_STR: if phrase in text: engine.speak("opening the cadavar master") openfun.cadaver() break for phrase in strlists.CLUSTERD_STR: if phrase in text: engine.speak("opening the clustered master") openfun.clusterd() break for phrase in strlists.DAV_TEST_STR: if phrase in text: engine.speak("opening the dav test master") openfun.davtest() break for phrase in strlists.DEBLAZE_STR: if phrase in text: engine.speak("opening the de blaze master") openfun.deblaze() break for phrase in strlists.FIMAP_STR: if phrase in text: engine.speak("opening the fimap master") openfun.fimap() break for phrase in strlists.GRABBER_STR: if phrase in text: engine.speak("opening the grabber master") openfun.grabber() break for phrase in strlists.JBOSS_AUTOPWN_WIN_STR: if phrase in text: engine.speak("opening the jboss auto pwn master") openfun.jboss_autopwn_win() break for phrase in strlists.JBOSS_AUTOPWN_LINUX_STR: if phrase in text: engine.speak("opening the jboss auto pwn linux master") openfun.jboss_autopwn_linux() break for phrase in strlists.JOOMSCAN_STR: if phrase in text: engine.speak("opening the joom scan master") openfun.joomscan() break for phrase in strlists.JQSL_STR: if phrase in text: engine.speak("opening the jqsl master") openfun.jsql() break for phrase in strlists.PAD_BUSTER_STR: if phrase in text: engine.speak("opening the pad buster master") openfun.padbuster() break for phrase in strlists.SKIP_FISH_STR: if phrase in text: engine.speak("opening the skip fish master") openfun.skipfish() break for phrase in strlists.WAPITI_STR: if phrase in text: engine.speak("opening the wapiti master") openfun.wapiti() break for phrase in strlists.WEBSPLOIT_STR: if phrase in text: engine.speak("opening the web sploit master") openfun.websploit() break for phrase in strlists.WHATWEB_STR: if phrase in text: engine.speak("opening the what web master") openfun.whatweb() break for phrase in strlists.XSSER_STR: if phrase in text: engine.speak("opening the xsser master") openfun.xsser() break for phrase in strlists.COMMIX_STR: if phrase in text: engine.speak("opening the commix master") openfun.commix() break for phrase in strlists.HTTRACK_STR: if phrase in text: engine.speak("opening the httrack master") openfun.httrack() break for phrase in strlists.WEBSCARAB_STR: if phrase in text: engine.speak("opening the webscarab master") openfun.webscarab() break for phrase in strlists.DATABASE_EXPLOIT: if phrase in text: engine.speak("opening the database exploit master") openfun.database_exploit() break for phrase in strlists.MDB_EXPORT_STR: if phrase in text: engine.speak("opening the mdb export master") openfun.mdb_export() break for phrase in strlists.MDB_HEXDUMP_STR: if phrase in text: engine.speak("opening the mdb hex dump master") openfun.mdb_hexdump() break for phrase in strlists.MDB_PARSER_CSV_STR: if phrase in text: engine.speak("opening the mdb parser csv master") openfun.mdb_parsecsv() break for phrase in strlists.MDB_SQL_STR: if phrase in text: engine.speak("opening the mdb sql master") openfun.mdb_sql() break for phrase in strlists.MDB_TABLES_STR: if phrase in text: engine.speak("opening the mdb tables master") openfun.mdb_tables() break for phrase in strlists.OSCANNER_STR: if phrase in text: engine.speak("opening the os scanner master") openfun.oscanner() break for phrase in strlists.SID_GUESSER_STR: if phrase in text: engine.speak("opening the sid guesser master") openfun.sidguesser() break for phrase in strlists.SQL_LITE_DATABASE_BROWSER_STR: if phrase in text: engine.speak("opening the sql lite database browser master") openfun.sql_lite_database_browser() break for phrase in strlists.POMPEM_STR: if phrase in text: engine.speak("opening the pompem master") openfun.pompem() break for phrase in strlists.SANDI_GUI_STR: if phrase in text: engine.speak("opening the sandi gui master") openfun.sandi_gui() break for phrase in strlists.IPV6_TOOLS_STR: if phrase in text: engine.speak("opening the ipv6 tools master") openfun.ipv6_tools() break for phrase in strlists.FAKE_ROUTER_STR: if phrase in text: engine.speak("opening the fake router master") openfun.fake_router6() break for phrase in strlists.DENIAL6_STR: if phrase in text: engine.speak("opening the denial 6 master") openfun.denial6 break for phrase in strlists.MSFVENOM_STE: if phrase in text: engine.speak("opening the msf venom master") openfun.msfvenom() break for phrase in strlists.METASPLOIT_STR: if phrase in text: engine.speak("opening the metasploit master") openfun.metasploit() break for phrase in strlists.PAYLOAD_GENERATOR_STR: if phrase in text: engine.speak("opening the payload generator master") openfun.payload_generator() break for phrase in strlists.SHELL_NOOB_STR: if phrase in text: engine.speak("opening the shell noob master") openfun.shellnoob() break for phrase in strlists.SOCIAL_ENGINEERING_TOOLS_STR: if phrase in text: engine.speak("opening the social engineering tool master") openfun.social_engineering_tool() break for phrase in strlists.TERMINETER_STR: if phrase in text: engine.speak("opening the termineter master") openfun.termineter() break for phrase in strlists.SQL_MAP_STR: if phrase in text: engine.speak("opening the sql map master") openfun.sqlmap() break for phrase in strlists.BEEF_XSS_FRAMEWORK: if phrase in text: engine.speak("opening the beef xss framework master") openfun.beef_xss_framework() break for phrase in strlists.BBQSQL_STR: if phrase in text: engine.speak("opening the bbsql master") openfun.bbqsql() break for phrase in strlists.AV_EVASION_STR: if phrase in text: engine.speak("opening the av evasion master") openfun.av_evasion() break for phrase in strlists.HYPERION_STR: if phrase in text: engine.speak("opening the hyperion master") openfun.hyperion() break for phrase in strlists.SHELLTER_STR: if phrase in text: engine.speak("opening the shellter master") openfun.shellter() break for phrase in strlists.OS_BACKDOOR_STR: if phrase in text: engine.speak("opening the os back door master") openfun.os_backdoors() break for phrase in strlists.CRYPT_CAT_STR: if phrase in text: engine.speak("opening the crypt cat master") openfun.crypt_cat() break for phrase in strlists.DBD_STR: if phrase in text: engine.speak("opening the dbd master") openfun.dbd() break for phrase in strlists.SBD_STR: if phrase in text: engine.speak("opening the sbd master") openfun.sbd() break for phrase in strlists.TUNNELING_AND_EXFILTRATION_TOOL_STR: if phrase in text: engine.speak("opening the tunneling and exfiltration master") openfun.tunneling_and_exfiltration_tool() break for phrase in strlists.IODINE_STR: if phrase in text: engine.speak("opening the iodine master") openfun.iodine() break for phrase in strlists.PROXY_CHAINS_STR: if phrase in text: engine.speak("opening the proxy chains master") openfun.proxychains() break for phrase in strlists.PTUNNEL_STR: if phrase in text: engine.speak("opening the ptunnel master") openfun.ptunnel() break for phrase in strlists.SSLH_STR: if phrase in text: engine.speak("opening the sslh master") openfun.sslh() break for phrase in strlists.UDP_TUNNEL_STR: if phrase in text: engine.speak("opening the udp tunnel master") openfun.udp_tunnel() break for phrase in strlists.WEB_BACKDOOR_STR: if phrase in text: engine.speak("opening the web backdoor master") openfun.web_backdoor() break for phrase in strlists.NISHANG_STR: if phrase in text: engine.speak("opening the nishang master") openfun.nishang() break for phrase in strlists.WEBACOO_STR: if phrase in text: engine.speak("opening the webacoo master") openfun.webacoo() break for phrase in strlists.BDF_PROXY_STR: if phrase in text: engine.speak("opening the bdf proxy master") openfun.bdf_proxy() break for phrase in strlists.WINDOWS_BINARIES_STR: if phrase in text: engine.speak("opening the windows binaries master") openfun.windows_binaries() break for phrase in strlists.HASH_AND_PASSWORD_STR: if phrase in text: engine.speak("opening the hash and password attack master") openfun.hash_and_password_dump() break for phrase in strlists.WCE_STR: if phrase in text: engine.speak("opening the wce master") openfun.wce() break for phrase in strlists.PASSING_HASH_ATTACK_TOOL_STR: if phrase in text: engine.speak("opening the passing hash attack tool master") openfun.passing_hash_attack_tool() break for phrase in strlists.PTH_NET_STR: if phrase in text: engine.speak("opening the pth net master") openfun.pth_net() break for phrase in strlists.PTH_OPEN_CLIENT_STR: if phrase in text: engine.speak("opening the pth open client master") openfun.pth_open_change_client() break for phrase in strlists.PTH_SMGGET_STR: if phrase in text: engine.speak("opening the pth smgget master") openfun.pth_smbget() break for phrase in strlists.CYMOTHOA_STR: if phrase in text: engine.speak("opening the cymothoa master") openfun.cymothoa() break for phrase in strlists.INTERSECT_STR: if phrase in text: engine.speak("opening the intersect master") openfun.intersect() break for phrase in strlists.POWERSPLOIT_STR: if phrase in text: engine.speak("opening the power sploit master") openfun.powersploit() break for phrase in strlists.LOCAL_ATTACK_TOOLS: if phrase in text: engine.speak("opening the local attack tool master") openfun.local_attack_tool() break for phrase in strlists.CACHE_DUMP_STR: if phrase in text: engine.speak("opening the cache dump master") openfun.cachedump() break for phrase in strlists.OPHCRACK_CLI_STR: if phrase in text: engine.speak("opening the ophcrack cli master") openfun.ophcrackcli() break for phrase in strlists.PWDUMP_STR: if phrase in text: engine.speak("opening the pw dump master") openfun.pwdump() break for phrase in strlists.SAMDUMP_STR: if phrase in text: engine.speak("opening the sam dump master") openfun.samdump2() break for phrase in strlists.OFFLINE_PASSWORD_ATTACK_TOOL_STR: if phrase in text: engine.speak("opening the offline password attack tool master") openfun.offline_password_attack_tool() break for phrase in strlists.CRACKLE_STR: if phrase in text: engine.speak("opening the crackle master") openfun.crackle() break for phrase in strlists.FCRAKZIP_STR: if phrase in text: engine.speak("opening the f crack zip master") openfun.fcrakzip() break for phrase in strlists.HASH_CAT_STR: if phrase in text: engine.speak("opening the hash cat master") openfun.hashcat() break for phrase in strlists.JOHN_STR: if phrase in text: engine.speak("opening the john master") openfun.john() break for phrase in strlists.PDF_CRACK_STR: if phrase in text: engine.speak("opening the pdf crack master") openfun.pdfcrack() break for phrase in strlists.PYRIT_STR: if phrase in text: engine.speak("opening the pyrit master") openfun.pyrit() break for phrase in strlists.RAINBOW_CRACK_STR: if phrase in text: engine.speak("opening the rainbow master") openfun.rainbowcrack() break for phrase in strlists.RAR_CRACK_STR: if phrase in text: engine.speak("opening the rar crack master") openfun.rarcrack() break for phrase in strlists.SIP_CRACK_STR: if phrase in text: engine.speak("opening the sip crack master") openfun.sipcrack() break for phrase in strlists.SUCRACK_STR: if phrase in text: engine.speak("opening the sucrack master") openfun.sucrack() break for phrase in strlists.TRUE_CRACK_STR: if phrase in text: engine.speak("opening the true crack master") openfun.truecrack() break for phrase in strlists.ONLINE_PASSWORD_CRACK_STR: if phrase in text: engine.speak("opening the online password crack master") openfun.online_password_attack_tool() break for phrase in strlists.BRUTESPRAY_STR: if phrase in text: engine.speak("opening the brutespray master") openfun.brutespray() break for phrase in strlists.CHANGE_ME_STR: if phrase in text: engine.speak("opening the change me master") openfun.changeme() break for phrase in strlists.HYDRA_STR: if phrase in text: engine.speak("opening the hydra master") openfun.hydra() break for phrase in strlists.MEDUSA_STR: if phrase in text: engine.speak("opening the medusa master") openfun.medusa() break for phrase in strlists.NCRACK_STR: if phrase in text: engine.speak("opening the ncrack master") openfun.webscarab() break for phrase in strlists.ONE_SIXTY_ONE: if phrase in text: engine.speak("opening the one sixty one master") openfun.onesixtyone() break for phrase in strlists.PATATOR_STR: if phrase in text: engine.speak("opening the patator master") openfun.patator() break for phrase in strlists.XHYDRA_STR: if phrase in text: engine.speak("opening the xhydra master") openfun.xhydra() break for phrase in strlists.WORDLIST_TOOLS: if phrase in text: engine.speak("opening the wordlist master") openfun.wordlist_tools() break for phrase in strlists.CEWL_STR: if phrase in text: engine.speak("opening the CEWL master") openfun.cewl() break for phrase in strlists.CRUNCH_STR: if phrase in text: engine.speak("opening the crunch master") openfun.crunch() break for phrase in strlists.MASKGEN_STR: if phrase in text: engine.speak("opening the mask gen master") openfun.maskgen() break for phrase in strlists.PIPAL_STR: if phrase in text: engine.speak("opening the pipal master") openfun.pipal() break for phrase in strlists.POLICY_GEN: if phrase in text: engine.speak("opening the policy gen master") openfun.policygen() break for phrase in strlists.STATSGEN_STR: if phrase in text: engine.speak("opening the stats gen master") openfun.statsgen() break for phrase in strlists.WORDLISTS_STR: if phrase in text: engine.speak("opening the wordlists master") openfun.wordlists() break for phrase in strlists.FIND_MY_HASH: if phrase in text: engine.speak("opening the find my hash master") openfun.find_my_hash() break for phrase in strlists.HASHID_STR: if phrase in text: engine.speak("opening the hash id master") openfun.hashid() break for phrase in strlists.HASH_IDENTIFIER_STR: if phrase in text: engine.speak("opening the hash identifier master") openfun.hash_identifier() break for phrase in strlists.WIFITE_STR: if phrase in text: engine.speak("opening the wifite master") openfun.webscarab() break for phrase in strlists.BLUETOOTH_STR: if phrase in text: engine.speak("opening the bluetooth hacking tool master") openfun.bluetooth_hackingtool() break for phrase in strlists.BLUELOG_STR: if phrase in text: engine.speak("opening the blue log master") openfun.bluelog() break for phrase in strlists.BLUE_RANGER_STR: if phrase in text: engine.speak("opening the blue ranger master") openfun.blueranger() break for phrase in strlists.BT_SCANNER_STR: if phrase in text: engine.speak("opening the bt scanner master") openfun.btscanner() break for phrase in strlists.RED_FANG_STR: if phrase in text: engine.speak("opening the red fang scanner master") openfun.redfang() break for phrase in strlists.GEN_KEYS_STR: if phrase in text: engine.speak("opening the gen keys scanner master") openfun.genkeys() break for phrase in strlists.HACK_RF_INFO_STR: if phrase in text: engine.speak("opening the bt hack rf info master") openfun.hackrf_info() break for phrase in strlists.UBERTOOTH_UTIL: if phrase in text: engine.speak("opening the bt ubertooth util master") openfun.ubertooth_util() break for phrase in strlists.RFID_AND_NFC_TOOLS: if phrase in text: engine.speak("opening the rfid and nfc tools master") openfun.rfid_and_nfc_tools() break for phrase in strlists.SOFTWARE_DETAILED_RADIO_STR: if phrase in text: engine.speak("opening the software detailed radio master") openfun.software_detailed_radio() break for phrase in strlists.INSPECTRUM_STR: if phrase in text: engine.speak("opening the inspectrum master") openfun.inspectrum() break for phrase in strlists.RFCAT_STR: if phrase in text: engine.speak("opening the scanner master") openfun.btscanner() break for phrase in strlists.GNU_RADIO_COMPANION_STR: if phrase in text: engine.speak("opening the gnu radio companion master") openfun.gnu_radio_companion() break for phrase in strlists.FERN_WIFI_CRACKER_STR: if phrase in text: engine.speak("opening the fern wifi cracker master") openfun.fern_wifi_cracker() break for phrase in strlists.MDK3_STR: if phrase in text: engine.speak("opening the mdk3 master") openfun.mdk3() break for phrase in strlists.PIXIE_WPS_STR: if phrase in text: engine.speak("opening the pixie wps master") openfun.pixiewps() break for phrase in strlists.REAVER_STR: if phrase in text: engine.speak("opening reaver master") openfun.reaver() break for phrase in strlists.NETWORK_SNIFFERS_STR: if phrase in text: engine.speak("opening network sniffers master") openfun.network_sniffers() break for phrase in strlists.HEX_INJECT_STR: if phrase in text: engine.speak("opening the hex inject master") openfun.hexinject() break for phrase in strlists.CHAOS_READER_STR: if phrase in text: engine.speak("opening the chaos reader master") openfun.chaosreader() break for phrase in strlists.DARK_STAT_STR: if phrase in text: engine.speak("opening dark stat master") openfun.darkstat() break for phrase in strlists.NET_SNIFF_STR: if phrase in text: engine.speak("opening net sniff master") openfun.netsniff_ng() break for phrase in strlists.NFSPY_STR: if phrase in text: engine.speak("opening NF spy master") openfun.nfspy() break for phrase in strlists.WEBSPY_STR: if phrase in text: engine.speak("opening webspy master") openfun.webspy() break for phrase in strlists.SSLSNIFF_STR: if phrase in text: engine.speak("opening SSL sniff master") openfun.sslsniff() break for phrase in strlists.SPOOFING_AND_MITM_STR: if phrase in text: engine.speak("opening spoofing and mitm") openfun.spoofing_and_mitm() break for phrase in strlists.PARASITE6_STR: if phrase in text: engine.speak("opening parasite 6 master") openfun.parasite6() break for phrase in strlists.WIFI_HONEY_STR: if phrase in text: engine.speak("opening wifi honey master") openfun.wifi_honey() break for phrase in strlists.BETTTER_CAP_SRT: if phrase in text: engine.speak("opening better cap master") openfun.bettercap() break for phrase in strlists.ETHERRAPE_STR: if phrase in text: engine.speak("opening ether rape master") openfun.etherrape() break for phrase in strlists.HAMSTER_STR: if phrase in text: engine.speak("opening hamster master") openfun.hamster() break for phrase in strlists.IMPACKET_STR: if phrase in text: engine.speak("opening impacket master") openfun.impacket() break for phrase in strlists.MACCHANGER_STR: if phrase in text: engine.speak("opening mac changer master") openfun.macchanger() break for phrase in strlists.MITM_PROXY_STR: if phrase in text: engine.speak("opening MITM proxy master") openfun.mitm_proxy() break for phrase in strlists.RESPONDER_STR: if phrase in text: engine.speak("opening responder master") openfun.responder() break for phrase in strlists.DIGITAL_FORENSIC_TOOL: if phrase in text: engine.speak("opening digital forensic tool master") openfun.digital_forensic_tool() break for phrase in strlists.FORENSIC_CARVING_TOOL: if phrase in text: engine.speak("opening forensic carving tool master") openfun.forensic_carving_tools() break for phrase in strlists.PDF_FORENSIC_TOOL: if phrase in text: engine.speak("opening pdf forensic tool master") openfun.pdf_forensic_tool() break for phrase in strlists.AUTOSPY_STR: if phrase in text: engine.speak("opening auto spy master") openfun.autospy() break for phrase in strlists.BIN_WALK_STR: if phrase in text: engine.speak("opening bin walk master") openfun.binwalk() break for phrase in strlists.BULK_EXTRACTOR_STR: if phrase in text: engine.speak("opening bulk extractor master") openfun.bulk_extractor() break for phrase in strlists.CHKROOTKIT_STR: if phrase in text: engine.speak("opening chk root kit master") openfun.chkrootkit() break for phrase in strlists.FOREMOST_STR: if phrase in text: engine.speak("opening fore most master") openfun.foremost() break for phrase in strlists.GALLETA_STR: if phrase in text: engine.speak("opening galleta master") openfun.galleta() break for phrase in strlists.HASH_DEEP_STR: if phrase in text: engine.speak("opening hash deep master") openfun.hashdeep() break for phrase in strlists.RKHUNTER_STR: if phrase in text: engine.speak("opening rkhunter master") openfun.rkhunter() break for phrase in strlists.VOLA_FOX_STR: if phrase in text: engine.speak("opening vola fox master") openfun.volafox() break for phrase in strlists.VOLATILITY_STR: if phrase in text: engine.speak("opening volatility master") openfun.volatility() break for phrase in strlists.VARA_STR: if phrase in text: engine.speak("opening vara master") openfun.vara() break for phrase in strlists.AUTOMOTIVE_STR: if phrase in text: engine.speak("opening automotive master") openfun.automotive_tools() break for phrase in strlists.DEBUGER_STR: if phrase in text: engine.speak("opening debugger master") openfun.debugger() break for phrase in strlists.JAVA_SNOOP_STR: if phrase in text: engine.speak("opening javasnoop master") openfun.javasnoop() break for phrase in strlists.DECOMPILERS_STR: if phrase in text: engine.speak("opening decompilers master") openfun.decompilers() break for phrase in strlists.JAD_STR: if phrase in text: engine.speak("opening jad master") openfun.jad() break for phrase in strlists.DIASSEMBLER_STR: if phrase in text: engine.speak("opening diassembler master") openfun.diassembler() break for phrase in strlists.FLASM_STR: if phrase in text: engine.speak("opening flasm master") openfun.flasm() break for phrase in strlists.RADARE_2_FRAMEWORK_STR: if phrase in text: engine.speak("opening radare 2 frame work master") openfun.radare_2_framework() break for phrase in strlists.APK_TOOL_STR: if phrase in text: engine.speak("opening apk tool master") openfun.apktool() break for phrase in strlists.CLANG_STR: if phrase in text: engine.speak("opening clang master") openfun.clang() break for phrase in strlists.CASEFILES_STR: if phrase in text: engine.speak("opening case files master") openfun.casefile() break for phrase in strlists.EYE_WITNESS_STR: if phrase in text: engine.speak("opening eye witness master") openfun.eyewitness() break for phrase in strlists.META_GOOFIL_STR: if phrase in text: engine.speak("opening meta goofil master") openfun.metagoofil() break for phrase in strlists.FARADAY_IDE_STR: if phrase in text: engine.speak("opening faraday ide master") openfun.faradayide() break for phrase in strlists.DBEAVER_STR: if phrase in text: engine.speak("opening d beaver master") openfun.dbeaver() break for phrase in strlists.GEANY_STR: if phrase in text: engine.speak("opening geany master") openfun.geany() break for phrase in strlists.GIT_COLA_STR: if phrase in text: engine.speak("opening git cola master") openfun.git_cola() break for phrase in strlists.GIT_DAG_STR: if phrase in text: engine.speak("opening git dag master") openfun.git_dag() break for phrase in strlists.MELD_STR: if phrase in text: engine.speak("opening meld master") openfun.meld() break for phrase in strlists.SUBLIME_STR: if phrase in text: engine.speak("opening sublime master") openfun.sublime() break else: pass for phrase in strlists.ZEAL_STR: if phrase in text: engine.speak("opening zeal master") openfun.zeal() break for phrase in strlists.XRC_STR: if phrase in text: engine.speak("opening XRC tool master") openfun.XRC_ed() break for phrase in strlists.BRASERO_STR: if phrase in text: engine.speak("opening brasero master") openfun.brasero() break for phrase in strlists.CHEESE_STR: if phrase in text: engine.speak("opening cheese master") openfun.cheese() break for phrase in strlists.LMMS_STR: if phrase in text: engine.speak("opening lmms master") openfun.lmms() break for phrase in strlists.MPV_MEDIA_PLAYER_STR: if phrase in text: engine.speak("opening MPV media player master") openfun.mpv_media_player() break for phrase in strlists.SOUND_KONVERTER: if phrase in text: engine.speak("opening sound converter master") openfun.sound_konverter() break for phrase in strlists.TIMIDITY_STR: if phrase in text: engine.speak("opening tmidity master") openfun.timidity() break for phrase in strlists.VOKO_SCREEN_STR: if phrase in text: engine.speak("opening voko screen master") openfun.vokoscreen() break for phrase in strlists.BLEACH_BIT_STR: if phrase in text: engine.speak("opening bleach bit master") openfun.bleach_bit() break for phrase in strlists.CAJA_STR: if phrase in text: engine.speak("opening caja master") openfun.caja() break for phrase in strlists.DCONFEDITOR_STR: if phrase in text: engine.speak("opening dconfeditor master") openfun.dconfeditor() break for phrase in strlists.DVDISASTER_STR: if phrase in text: engine.speak("opening dv disaster master") openfun.dvdisaster() break for phrase in strlists.GDEBI_STR: if phrase in text: engine.speak("opening gdebi master") openfun.gdebi() break for phrase in strlists.GPARTED_STR: if phrase in text: engine.speak("opening gparted master") openfun.gparted() break for phrase in strlists.GUYMAGER_STR: if phrase in text: engine.speak("opening guymager master") openfun.guymager() break for phrase in strlists.HTOP_STR: if phrase in text: engine.speak("opening H top master") openfun.htop() break for phrase in strlists.LOG_FILE_VIEWER_STR: if phrase in text: engine.speak("opening log file viewer master") openfun.log_file_viewer() break for phrase in strlists.NEOVIM_STR: if phrase in text: engine.speak("opening neovim master") openfun.neovim() break for phrase in strlists.GQRX_STR: if phrase in text: engine.speak("opening gqrx master") openfun.gqrx() break for phrase in strlists.QBITTORRENT_STR: if phrase in text: engine.speak("opening qbittorrent master") openfun.qbittorrent() break for phrase in strlists.REMMINA_BROWSER_STR: if phrase in text: engine.speak("opening remmina master") openfun.remmina_browser() break for phrase in strlists.TOR_BROWSER_STR: if phrase in text: engine.speak("opening tor browser master") openfun.tor_Browser() break for phrase in strlists.CONTROL_CENTER_0R_SETTINGS_STR: if phrase in text: engine.speak("opening control center master") openfun.control_center_or_settings() break for phrase in strlists.TWEAKS_STR: if phrase in text: engine.speak("opening tweaks master") openfun.tweaks() break for phrase in strlists.SYSTEM_MONITOR_PROCESSOR_USE: if phrase in text: engine.speak("opening system monitor master") openfun.system_monitor_processor_use() break for phrase in strlists.NMAP_STR: if phrase in text: engine.speak("opening nmap") openfun.nmap() break for phrase in strlists.TERMINAL_STR: if phrase in text: engine.speak("opening terminal master") openfun.terminal() break for pharse in strlists.PLUMA_STR: if phrase in text: engine.speak("opening pluma master") openfun.pluma() break for phrase in strlists.NITKO_STR: if phrase in text: engine.speak("opening the nitko scanner master!") openfun.nitko() break for phrase in strlists.CALC_STR: if phrase in text: engine.speak("opening calculator master!") openfun.calc() break for phrase in strlists.NVIM_STR: if phrase in text: engine.speak("openig the nvim text editor master") openfun.nvim() break for phrase in strlists.VSCODE_STR: if phrase in text: engine.speak("opening visual studio code master!") openfun.vscode() break for pharse in strlists.ANONSURF_STR: if phrase in text: engine.speak("starting anonsurf master") openfun.anonsurf() break for phrase in strlists.LIBREOFFICE_STR: if phrase in text: for phrase in strlists.LIBREOFFICE_BASE: if phrase in text: engine.speak("opening the libre office base master!") openfun.libre_office_base() break for phrase in strlists.LIBREOFFICE_CALC: if phrase in text: engine.speak("opening the libreoffice calc master!") openfun.libre_office_calc() for phrase in strlists.LIBREOFFICE_DRAW: if phrase in text: engine.speak("opening the libreoffice draw master!") openfun.libre_office_draw() break for phrase in strlists.LIBREOFFICE_IMPRESS: if phrase in text: engine.speak("opening the libreoffice impress master!") openfun.libre_office_impress() break for phrase in strlists.LIBREOFFICE_WRITER: if phrase in text: engine.speak("opening the libre office writer master!") openfun.libre_office_writer() break for phrase in strlists.LIBREOFFICE_MATH: if phrase in text: engine.speak("opneing the libreoffice maths master!") openfun.libre_office_math() break break for phrase in strlists.CHESS_STR: if phrase in text: engine.speak("opening the xboard master!") openfun.xboard() break for phrase in strlists.PHOTOEDITOR_STR: if phrase in text: engine.speak("opening the gimp image manupulation program") openfun.photoeditor() break #################################### #open apps loop closes here #################################### #################################### <file_sep>/openfun.py import os def terminal(): os.system("gnome-terminal") def aircrack(): os.system("gnome-terminal -e 'sudo aircrack-ng'") def airgeddon(): os.system("gnome-terminal -e 'sudo airgeddon'") def burpsuite(): os.system("gnome-terminal -e 'sudo burpsuite'") def ed_debugger(): os.system("gnome-terminal -e 'sudo edb'") def ettercap_graphical(): os.system("gnome-terminal -e 'sudo ettercap'") def gobuster(): os.system("gnome-terminal -e 'sudo gobuster'") def johnny(): os.system("gnome-terminal -e 'sudo johnny'") def kayak_car_hacking_tool(): os.system("gnome-terminal -e 'sudo kayak'") def ophcrack(): os.system("gnome-terminal -e 'sudo ophcrack'") def owasp(): os.system("gnome-terminal -e 'sudo owasp-zap'") def weevely(): os.system("gnome-terminal -e 'sudo weeveley'") def wireshark(): os.system("gnome-terminal -e 'sudo wireshark'") def zenmap(): os.system("gnome-terminal -e 'sudo zenmap'") def dnsanalysis(): os.system("gnome-terminal -e 'sudo dnstracer'") def idps_ips_identification(): os.system("gnome-terminal -e 'sudo fragroute'") def live_host_identification(): os.system("gnome-terminal -e 'sudo hping3'") def network_or_port_scanner(): os.system("gnome-terminal -e 'sudo nmap'") def osint_analysis(): os.system("gnome-terminal -e 'sudo maltego'") def route_analysis(): os.system("gnome-terminal -e 'sudo intrace'") def maltego(): os.system("gnome-terminal -e 'sudo maltego'") def armitage(): os.system("gnome-terminal -e 'sudo armitage'") ############################################################### ############################################################### def sbm_analysis(): os.system("gnome-terminal -e 'sudo nbtscan'") def snmp_analysis(): os.system("gnome-terminal -e 'sudo snmp-check'") def smtb_analysis(): os.system("gnome-terminal -e 'sudo swaks'") def ssl_analysis(): os.system("gnome-terminal -e 'sudo sslscan'") def amap(): os.system("gnome-terminal -e 'sudo amap'") def dmitry(): os.system("gnome-terminal -e 'sudo dmitry'") def dnmap_server(): os.system("gnome-terminal -e 'sudo dnmap-server'") def dnmap_client(): os.system("gnome-terminal -e 'sudo dnmap-client'") def ike_scan(): os.system("gnome-terminal -e 'sudo ike-scan'") def net_discover(): os.system("gnome-terminal -e 'netdiscover'") def pOf(): os.system("gnome-terminal -e 'pOf'") def recon_ng(): os.system("gnome-terminal -e 'recon-ng'") def cisco_tools(): os.system("gnome-terminl -e 'cisco-auditing-tool'") def fuzzing_tools(): os.system("gnome-terminal -e 'powerfuzzer'") def open_vas_scanner(): os.system("gnome-terminal -e 'openvas-gsd'") def stress_testing(): os.system("gnome-terminal -e 'flood_router6'") def voip_tool(): os.system("gnome-terminal -e 'svcrack'") def golismero(): os.system("gnome-terminal -e 'golismero'") def lynis(): os.system("gnome-terminal -e 'lynis'") def unix_privesv_check(): os.system("gnome-terminal -e 'unix-privesc-check'") def file_manger_or_places(): os.system("gnome-terminal -e 'nautilus'") def documents(): os.system("gnome-termnal -e 'nautilus Documents'") def desktop(): os.system("gnome-terminal -e 'nautilus Desktop'") def Downloads(): os.system("gnome-terminal -e 'nautilus Downloads'") def music(): os.system("gnome-terminal -e 'nautilus Music'") def pictures(): os.system("gnome-terminal -e 'nautilus Pictures'") def videos(): os.system("gnome-terminal -e 'nautilus Videos'") def trash(): os.system("gnome-terminal -e 'nautilus Trash'") def cms_and_framework(): os.system("gnome-terminal -e 'wpscan'") def wig(): os.system("gnome-terminal -e 'wig'") def ua_tester(): os.system("gnome-terminal -e 'ua-tester'") def web_crawlers_and_directory(): os.system("gnome-terminal -e 'dirbuster'") def apache_users(): os.system("gnome-terminal -e 'apache-users'") def uniscan_gui(): os.system("gnome-terminal -e 'uniscan-gui'") def web_vulnerability_scanner(): os.system("gnome-terminal -e 'nitko'") def cadaver(): os.system("gnome-terminal -e 'cadaver'") def clusterd(): os.system("gnome-terminal -e 'clusterd'") def davtest(): os.system("gnome-terminal -e 'davtest'") def deblaze(): os.system("gnome-terminal -e 'deblaze'") def fimap(): os.system("gnome-terminal -e 'fimap'") def grabber(): os.system("gnome-terminal -e 'grabber'") def jboss_autopwn_linux(): os.system("gnome-terminal -e 'jboss-autopwn-linux'") def jboss_autopwn_win(): os.system("gnome-terminal -e 'jboss-autopwn-win'") def joomscan(): os.system("gnome-terminal -e 'joomscan'") def jsql(): os.system("gnome-terminal -e 'jsql'") def padbuster(): os.system("gnome-terminal -e 'padbuster'") def skipfish(): os.system("gnome-terminal -e 'skipfish'") def wapiti(): os.system("gnome-terminal -e 'wapiti'") def websploit(): os.system("gnome-terminal -e 'websploit'") def whatweb(): os.system("gnome-terminal -e 'whatweb'") def xsser(): os.system("gnome-terminal -e 'xsser'") def commix(): os.system("gnome-terminal -e 'commix'") def httrack(): os.system("gnome-terminal -e 'httrack'") def webscarab(): os.system("gnome-terminal -e 'webscarab'") def database_exploit(): os.system("gnome-terminal -e 'mdb-sql'") def mdb_export(): os.system("gnome-terminal -e 'mdb-export'") def mdb_hexdump(): os.system("gnome-terminal -e 'mdb-hexdump'") def mdb_parsecsv(): os.system("gnome-terminal -e 'mdb-parsecsv'") def mdb_sql(): os.system("gnome-terminal -e 'mdb-sql'") def mdb_tables(): os.system("gnome-terminal -e 'mdb-tables'") def oscanner(): os.system("gnome-terminal -e 'oscanner'") def sidguesser(): os.system("gnome-terminal -e 'sidguesser'") def sql_lite_database_browser(): os.system("gnome-terminal -e 'sqlitebrowser'") def pompem(): os.system("gnome-terminal -e 'pompem'") def sandi_gui(): os.system("gnome-terminal -e 'sandi-gui'") def ipv6_tools(): os.system("gnome-terminal -e 'flood_router6'") def fake_router6(): os.system("gnome-terminal -e 'fake_router6'") def fake_router26(): os.system("gnome-terminal -e 'fake_router26'") def denial6(): os.system("gnome-terminal -e 'denial6'") def msfvenom(): os.system("gnome-terminal -e 'msfvenom'") def metasploit(): os.system("gnome-terminal -e 'msfconsole'") def payload_generator(): os.system("gnome-terminal -e 'u3-pwn'") def shellnoob(): os.system("gnome-terminal -e 'shellnoob'") def social_engineering_tool(): os.system("gnome-terminal -e 'setoolkit'") def termineter(): os.system("gnome-terminal -e 'termineter'") def sqlmap(): os.system("gnome-terminal -e 'sqlmap'") def beef_xss_framework(): os.system("gnome-terminal -e 'beef-xss'") def bbqsql(): os.system("gnome-terminal -e 'bbqsql'") def av_evasion(): os.system("gnome-terminal -e 'exe2hex'") def hyperion(): os.system("gnome-terminal -e 'hyperion'") def shellter(): os.system("gnome-terminal -e 'shellter'") def os_backdoors(): os.system("gnome-terminal -e 'backdoor-factory'") def crypt_cat(): os.system("gnome-terminal -e 'cryptcat'") def dbd(): os.system("gnome-terminal -e 'dbd'") def sbd(): os.system("gnome-terminal -e 'sbd'") def tunneling_and_exfiltration_tool(): os.system("gnome-terminal -e 'proxytunnel'") def iodine(): os.system("gnome-terminal -e 'iodine'") def proxychains(): os.system("gnome-terminal -e 'proxychains'") def ptunnel(): os.system("gnome-terminal -e 'ptunnel'") def sslh(): os.system("gnome-terminal -e 'sslh'") def udp_tunnel(): os.system("gnome-terminal -e 'udptunnel'") def web_backdoor(): os.system("gnome-terminal -e 'laudanum'") def nishang(): os.system("gnome-terminal -e 'nishang'") def webacoo(): os.system("gnome-terminal -e 'webacoo'") def bdf_proxy(): os.system("gnome-terminal -e 'bdfproxy'") def windows_binaries(): os.system("gnome-terminal -e 'windows-binaries'") def hash_and_password_dump(): os.system("gnome-terminal -e 'mimikatz'") def wce(): os.system("gnome-terminal -e 'wce'") def passing_hash_attack_tool(): os.system("gnome-terminal -e 'pth-curl'") def pth_net(): os.system("gnome-terminal -e 'pth-net'") def pth_open_change_client(): os.system("gnome-terminal -e 'pth-openchangeclient'") def pth_smbget(): os.system("gnome-terminal -e 'pth-sbmget'") def cymothoa(): os.system("gnome-terminal -e 'cymothoa'") def intersect(): os.system("gnome-terminal -e 'intersect'") def powersploit(): os.system("gnome-terminal -e 'powersploit'") def local_attack_tool(): os.system("gnome-terminal -e 'chntpw'") def cachedump(): os.system("gnome-terminal -e 'cachedump'") def ophcrackcli(): os.system("gnome-terminal -e 'ophcrack-cli'") def pwdump(): os.system("gnome-terminal -e 'pwdump'") def samdump2(): os.system("gnome-terminal -e 'samdump2'") def offline_password_attack_tool(): os.system("gnome-terminal -e 'rcracki_mt'") def crackle(): os.system("gnome-terminal -e 'crackle'") def fcrakzip(): os.system("gnome-terminal -e 'fcrackzip'") def hashcat(): os.system("gnome-terminal -e 'hashcat'") def john(): os.system("gnome-terminal -e 'john'") def pdfcrack(): os.system("gnome-terminal -e 'pdfcrack'") def pyrit(): os.system("gnome-terminal -e 'pyrit'") def rainbowcrack(): os.system("gnome-terminal -e 'rainbowcrack'") def rarcrack(): os.system("gnome-terminal -e 'rarcrack'") def sipcrack(): os.system("gnome-terminal -e 'sipcrack'") def sucrack(): os.system("gnome-terminal -e 'sucrack'") def truecrack(): os.system("gnome-terminal -e 'truecrack'") def online_password_attack_tool(): os.system("gnome-terminal -e 'keimpx'") def brutespray(): os.system("gnome-terminal -e 'brutespray'") def changeme(): os.system("gnome-terminal -e 'changeme'") def hydra(): os.system("gnome-terminal -e 'hydra'") def medusa(): os.system("gnome-terminal -e 'medusa'") def ncrack(): os.system("gnome-terminal -e 'ncrack'") def onesixtyone(): os.system("gnome-terminal -e 'onesixtyone'") def patator(): os.system("gnome-terminal -e 'patator'") def xhydra(): os.system("gnome-terminal -e 'xhydra'") def wordlist_tools(): os.system("gnome-terminal -e 'rsmangler'") def cewl(): os.system("gnome-terminal -e 'cewl'") def crunch(): os.system("gnome-terminal -e 'crunch'") def maskgen(): os.system("gnome-terminal -e 'maskgen'") def pipal(): os.system("gnome-terminal -e 'pipal'") def policygen(): os.system("gnome-terminal -e 'policygen'") def statsgen(): os.system("gnome-terminal -e 'statsgen'") def wordlists(): os.system("gnome-terminal -e 'wordlists'") def find_my_hash(): os.system("gnome-terminal -e 'findmyhash'") def hashid(): os.system("gnome-terminal -e 'hashid'") def hash_identifier(): os.system("gnome-terminal -e 'hash-identifier'") def wifihacking_tool(): os.system("gnome-terminal -e 'sudo airgeddon'") def wifite(): os.system("gnome-terminal -e 'sudo wifite'") def bluetooth_hackingtool(): os.system("gnome-terminal -e 'bluelog'") def bluelog(): os.system("gnome-terminal -e 'bluelog'") def blueranger(): os.system("gnome-terminal -e 'blueranger'") def btscanner(): os.system("gnome-terminal -e 'btscanner'") def redfang(): os.system("gnome-terminal -e 'redfang'") def genkeys(): os.system("gnome-terminal -e 'genkeys'") def hackrf_info(): os.system("gnome-terminal -e 'hackrf_info'") def ubertooth_util(): os.system("gnome-terminal -e 'ubertooth-util -h'") def rfid_and_nfc_tools(): os.system("gnome-terminal -e 'mfoc'") def software_detailed_radio(): os.system("gnome-terminal -e 'inspectrum'") def inspectrum(): os.system("gnome-terminal -e 'inspectrum'") def rfcat(): os.system("gnome-terminal -e 'rfcat'") def gnu_radio_companion(): os.system("gnome-terminal -e 'gnuradio_companion'") def fern_wifi_cracker(): os.system("gnome-terminal -e 'sudo fern-wifi-cracker'") def mdk3(): os.system("gnome-terminal -e 'mdk3'") def pixiewps(): os.system("gnome-terminal -e 'pixiewps'") def reaver(): os.system("gnome-terminal -e 'reaver'") def network_sniffers(): os.system("gnome-terminal -e 'webmitm'") def hexinject(): os.system("gnome-terminal -e 'hexinject'") def chaosreader(): os.system("gnome-terminal -e 'chaosreader'") def darkstat(): os.system("gnome-terminal -e 'darkstat'") def netsniff_ng(): os.system("gnome-terminal -e 'netsniff-ng'") def nfspy(): os.system("gnome-terminal -e 'nfspy'") def webspy(): os.system("gnome-terminal -e 'webspy'") def sslsniff(): os.system("gnome-terminal -e 'sslsniff'") def spoofing_and_mitm(): os.system("gnome-terminal -e 'dnschef'") def parasite6(): os.system("gnome-terminal -e 'parasite6'") def wifi_honey(): os.system("gnome-terminal -e 'wifi-honey'") def bettercap(): os.system("gnome-terminal -e 'bettercap'") def etherrape(): os.system("gnome-terminal -e 'etherrape'") def hamster(): os.system("gnome-terminal -e 'hamster'") def impacket(): os.system("gnome-terminal -e 'impacket'") def macchanger(): os.system("gnome-terminal -e 'macchanger'") def mitm_proxy(): os.system("gnome-terminal -e 'mitmproxy'") def responder(): os.system("gnome-terminal -e 'resonder'") def digital_forensic_tool(): os.system("gnome-terminal -e 'extundelete'") def forensic_carving_tools(): os.system("gnome-terminal -e 'pasco'") def forensic_imaging_tool(): os.system("gnome-terminal -e 'guymager'") def pdf_forensic_tool(): os.system("gnome-terminal -e 'pdf-parser'") def autospy(): os.system("gnome-terminal -e 'autospy'") def binwalk(): os.system("gnome-terminal -e 'binwalk'") def bulk_extractor(): os.system("gnome-terminal -e 'bulk_extractor'") def chkrootkit(): os.system("gnome-terminal -e 'chkrootkit'") def foremost(): os.system("gnome-terminal -e 'foremost'") def galleta(): os.system("gnome-terminal -e 'galleta'") def hashdeep(): os.system("gnome-terminal -e 'hashdeep'") def rkhunter(): os.system("gnome-terminal -e 'rkhunter'") def volafox(): os.system("gnome-terminal -e 'sudo volafox'") def volatility(): os.system("gnome-terminal -e 'volatility'") def vara(): os.system("gnome-terminal -e 'vara'") def automotive_tools(): os.system("gnome-terminal -e 'sudo kayak'") def debugger(): os.system("gnome-terminal -e 'gdb -h'") def javasnoop(): os.system("gnome-terminal -e 'javasnoop'") def decompilers(): os.system("gnome-terminal -e 'dex2jar'") def jad(): os.system("gnome-terminal -e 'jad'") def diassembler(): os.system("gnome-terminal -e 'smali'") def flasm(): os.system("gnome-terminal -e 'flasm'") def radare_2_framework(): os.system("gnome-terminal -e 'radare2'") def apktool(): os.system("gnome-terminal -e 'apktool'") def clang(): os.system("gnome-terminal -e 'clang'") def casefile(): os.system("gnome-terminal -e 'casefile'") def eyewitness(): os.system("gnome-terminal -e 'eyewitness'") def metagoofil(): os.system("gnome-terminal -e 'metagoofil'") def faradayide(): os.system("gnome-terminal -e 'python-farday'") def dbeaver(): os.system("gnome-terminal -e 'dbeaver'") def geany(): os.system("gnome-terminal -e 'geany'") def git_cola(): os.system("gnome-terminal -e 'git-cola'") def git_dag(): os.system("gnome-terminal -e 'git-dag'") def meld(): os.system("gnome-terminal -e 'meld'") def sublime(): os.system("gnome-terminal -e 'sublime'") def zeal(): os.system("gnome-terminal -e 'zeal'") def XRC_ed(): os.system("gnome-terminal -e 'xrcced'") def brasero(): os.system("gnome-terminal -e 'brasero'") def cheese(): os.system("gnome-terminal -e 'cheese'") def lmms(): os.system("gnome-terminal -e 'lmms'") def mpv_media_player(): os.system("gnome-terminal -e 'mpv'") def sound_konverter(): os.system("gnome-terminal -e 'soundkonverter'") def timidity(): os.system("gnome-terminal -e 'timidity'") def vokoscreen(): os.system("gnome-terminal -e 'vokoscreen'") def bleach_bit(): os.system("gnome-terminal -e 'bleachbit'") def caja(): os.system("gnome-terminal -e 'caja'") def dconfeditor(): os.system("gnome-terminal -e 'dconf-editor") def dvdisaster(): os.system("gnome-terminal -e 'dvdisaster'") def gdebi(): os.system("gnome-terminal -e 'gdebi'") def gparted(): os.system("gnome-terminal -e 'gparted'") def guymager(): os.system("gnome-terminal -e 'guymager'") def htop(): os.system("gnome-terminal -e 'htop'") def log_file_viewer(): os.system("gnome-terminal -e 'logfile-viewer'") def neovim(): os.system("gnome-terminal -e 'neovim'") def gqrx(): os.system("gnome-terminal -e 'gqrx'") def hexcat(): os.system("gnome-terminal -e 'hexcat'") def qbittorrent(): os.system("gnome-terminal -e 'qbittorrent'") def remmina_browser(): os.system("gnome-terminal -e 'remmina'") def tor_Browser(): os.system("gnome-terminal -e 'tor'") def control_center_or_settings(): os.system("gnome-terminal -e 'mate-control-center'") def tweaks(): os.system("gnome-terminal -e 'mate-tweak'") def system_monitor_processor_use(): os.system("gnome-terminal -e 'mate-system-monitor") def screen_lock(): os.system("gnome-terminal -e 'mate-screensaver-commmand -l'") def texteditor(): os.system("gnome-terminal -e 'pluma'") ######################################################### #starting services added here #'''''''''''''''''''''''''''''''''''''''' def http_restart(): os.system("gnome-terminal -e 'sudo ngnix restart'") def http_start(): os.system("gnome-terminal -e 'sudo ngnix start'") def http_stop(): os.system("gnome-terminal -e 'sudo ngnix stop'") def postgresql_start(): os.system("gnome-terminal -e 'sudo postgresql start'") def postgresql_restart(): os.system("gnome-terminal -e 'sudo postgresql restart'") def postgresql_stop(): os.system("gnome-terminal -e 'sudo postgresql stop'") def sshd_start(): os.system("gnome-terminal -e 'sudo sshd start'") def sshd_restart(): os.system("gnome-terminal -e 'sudo shd restart'") def sshd_stop(): os.system("gnome-terminal -e 'sudo sshd stop'") def wifi_on(): os.system("gnome-terminal -e 'sudo ifconfig wlan0 up'") def wifi_off(): os.system("gnome-terminal -e 'sudo ifconfig wlan0 down'") def bluetooth_on(): os.system("gnome-terminal -e 'sudo rfkill unblock bluetooth'") def bluetooth_off(): os.system("gnome-terminal -e 'sudo rfkill block bluetooth'") ############################################################## def google(): os.system("gnome-terminal -e 'google-chrome' ") def firefox(): os.system("gnome-terminal -e 'firefox'") def nmap(): os.system("gnome-terminal -e 'nmap") def pluma(): os.system("gnome-terminal -e 'pluma") def nitko(): os.system("gnome-terminal -e 'nitko") def calc(): os.system("gnome-terminal -e 'mate-calc'") def camera(): os.system("gnome-terminal -e 'cheese'") def nvim(): os.system("gnome-terminal -e 'nvim'") def libre_office(): os.system("gnome-terminal -e 'libreoffice'") def vscode(): os.system("gnome-terminal -e 'codium'") def anonsurf(): os.system("gnome-terminal -e 'anonsurf start'") def libre_office_base(): os.system("gnome-terminal -e 'libreoffice --base'") def libre_office_calc(): os.system("gnome-terminal -e 'libreoffice --calc'") def libre_office_draw(): os.system("gnome-terminal -e 'libreoffice --draw'") def libre_office_impress(): os.system("gnome-terminal -e 'libreoffice --impress'") def libre_office_writer(): os.system("gnome-terminal -e 'libreoffice --writer'") def libre_office_math(): os.system("gnome-terminal -e 'libreoffice --math'") def xboard(): os.system("gnome-terminal -e 'xboard'") def photoeditor(): os.system("gnome-terminal -e 'gimp'") <file_sep>/Audio.py from __future__ import print_function import requests,json import urllib import datetime import speech_recognition as sr import os def get_audio(): r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) said = "" try: said = r.recognize_google(audio) print(said) except Exception as e: print("Exception: " + str(e)) return said.lower() <file_sep>/strlists.py OPEN_STR =["open","launch"] START_STR=['start','launch'] RESTART_STR=['restart'] STOP_STR=['stop'] SWITCH_STR = ["switch"] SWITCHON_STR = ['switch on'] PRESS_STR = ["press"] ON_STR = ["on"] OFF_STR = ["off"] MONTHS = ["january", "february", "march", "april", "may", "june","july", "august", "september","october", "november", "december"] DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] DAY_EXTENTIONS = ["rd", "th", "st", "nd"] CALENDAR_STRS = ["what do i have","what are my plans","check my events ","check plans","do i have anything planned","do i have plans","am i busy ","what are the plans"] WAKE1 = "hello baby" WAKE2 = "hey baby" WAKE3 = "are you there" WAKE4 = "are you listening baby" WAKE5 = "wake up baby" WAKE6 = "are you ready" WAKE7 = "baby" WAKE8 = "baby are you ready" WAKE9 = "you are listening right?" GREETING_STR1 = ["hello","hi"] GREETING_STR2 = ["how are you"] SEARCH_STRS = ["search"] SEARCH_GOOGLE_STR=["in google"] SEARCH_YOUTUBE_STR = ["in youtube","youtube search"] SEARCH_WIKIPEDIA_STR = ["in wikipedia","wiki","wikipedia"] NOTE_STRS = ["make a note",'create a note','create note','make notes',"make a file", "create a file","create new file","write this down","create file "] WEATHER_STRS = ["check weather"," get weather condition","how is the weather","weather report","climate"] FETCH_GOOGLE_NEWS_STR = ["fetch google news","get headlines","today's news","get news","read news","news today","get today's news","news"] CAMERA_STR = ["camera" ,"webcam","cheese"] GOOGLE_STR=["google","google chrome","chrome"] FIREFOX_STR=["firefox","mozilla firefox"] NMAP_STR=["nmap"] TERMINAL_STR=["terminal"] PLUMA_STR=["pluma","p l u m a",'text editor'] NITKO_STR=["nitko","nitko scanner"] LIBREOFFICE_STR=["libre office","libreoffice","office"] LIBREOFFICE_BASE=["base"] LIBREOFFICE_CALC=["calc","calculator"] LIBREOFFICE_DRAW=["draw"] LIBREOFFICE_IMPRESS=["impressed"] LIBREOFFICE_WRITER=["writer",'word editor'] CALC_STR=["calc","calculator"] NVIM_STR=["nvim","nvim text editor","vim","vim text editor"] SCREENSHOT_STR=["screen shot","screenshot"] VSCODE_STR=["vs code","visual studio code","vs codium","vs ide","codium"] ANONSURF_STR=["anonsurf","anonymous surfing","surfing anonymously"] LIBREOFFICE_MATH = ["math","maths"] CHESS_STR = ["chess","xboard","chess board","chessgame","chess game"] ASKFOR_GAME=["game","let's play a game"] PHOTOEDITOR_STR = ["gimp","photo editor","image manupulation"] KEYBOARD_STR = ["keyboard","the keyboard"] VOICETYPING_STR=["voice typing "] VOICETYPING_KEYPRESSES_STR = ["backspace","delete", "space bar","space", "enter","tab","delete","capslock","numlock","left","right","open","new","page up","page down","save","select all","cut","copy","paste","italics","italic","undo","redo","bold","underline","click"] AIRCRACK_STR = ["air crack","aircrack","aircrak ng","air crack ng"] AIRGEDDON_STR = ["airgeddon",'air jordan','air z on'] BURPSUITE_STR = ["burpsuite",'burp suite'] ED_DEBUGGER_STR = ["ed debugger","e d debugger","debugger"] ETTERCAP_GRAPH_STR = ["ettercap graph","etter cap graph","etter graph"] GO_BUSTER_STR = ["go buster","gobuster"] JOHNNY_STR = ["johny","johnny"] KAYAK_CAR_HACKING_TOOL =["kayak","kayak hacking tool","kayak car hacker","car hacker"] OPHCRACK_STR = ["ophcrack","op crack"] OWASP_STR = ["OWASP",'o w a s p','o wasp'] WEEVELY_STR =["weevely","weevely tool",'weebly'] WIRESHARK_STR = ["wireshark","wire shark"] ZENMAP_STR = ["zen map","zenmap"] DNS_ANALYSIS = ["dns analysis","domain name server analysis","dns lookup"] IDPS_IPS_IDENTOFICATION_STR = ["idps ips","idps ips identification","idps ips tool"] LIVE_HOST_IDENTIFIER_STR=["live host identifier","live host identifier tool","live host identify tool"] NETWORK_OR_PORT_SCANNER_STR=["network scanner","port scanner","network scanner tool"] OSINT_ANALYSIS_STR=["osint tool","osint analysis",'o s i n t','o s i n t tool'] ROUTE_ANALYSIS_STR=["route analyser",'root analyser',"intrace","route analyse tool"] MALTEGO_STR=["maltego tool","maltego","malt ego"] ARMITAGE_STR=["armitage","armitage tool",'armytage'] SBM_ANALYSIS_STR =[" SBM analysis tool","sbm tool"," nbt scan","sbm analyzer"] SNMP_ANALYSIS_STR =["snmp tool",'snmp anlysis','snmp analysis tool',"snmp analyser","snmp check","snmp checker"] SSL_ANALYSIS_STR = ["ssl analyser","ssl tool","ssl analyse tool","ssl checker"] AMAP_STR = ["amap","a map"] DMITRY_STR =["dmitry","de mitry","d mitry",'dimitry','dimitri'] DNMAP_SERVER_STR=["dnmap server","dn map server","d nmap server"] DNMAP_CLIENT_STR=["dnmap client","dn map client","d nmap client"] IKE_STR=["ike scane","i k e scan","ike scanner"] NET_DISCOVER_STR =["net discover tool","net discoverer"] POF_TOOL_STR = ["pOf tool","pof scanner","pof scanning"] RECON_NG_STR=["recon ng tool","recon tool","re con tool","recon scanner","recon"] CISCO_STR=["cisco tool","cisco","cisco scanner","cis co analyser"] FUZZING_TOOL_STR=["fuzzing tool ","fuzzing"] OPEN_VAS_SCANNER_TOOL_STR=["open vas scanner","open was "] STRESS_TESTING_TOOL_STR=["stress test","stress tester","stress testing"] VOIP_TOOLS_STR=["voip tool", "v oip tools"] GOLISMERO_STR=["golismero","golis mero"] LYNIS_STR=["lynis","linnis","l y n i s"] UNIX_PRISEV_CHECK=["unix preserve check","unix check","preserve check"] FILE_MANAGER_STR=["nautilus","file manager","places","place"] DOCUMENTS_STR=["documents","document"] DESKTOP_STR=["desktop","desktops"] DOWNLOADS_STR=["downloads","download"] MUSIC_STR=["music","musics"] PICTURES_STR=["pictures","picture"] VIDEOS_STR=["videos","video"] TRASH_STR=["trash","trashs","recycle bin","deleted items"] CMS_AND_FRAMEWORK_STR=["cms framework tool","cms tool"] WPSCAN_STR=["wpscan","cms wpscan"] WIG_STR=["wig ",".wig tool"] UA_TESTER_STR=["ua tester","ua testing tool"] WEBCRAWLER_AND_DIRECTORY_STR=["webcrawler tool","directory traverse tool"] APACHE_USER_STR=["apache user","apache-users"] UNISCAN_STR=["uniscan gui","uniscan","gui uniscan"] WEB_VULNERABILITY_STR=["web vulnerability scanner","vulnerability scanner"] CADAVAR_STR=["cadavar","kadavar","kedavar"] CLUSTERD_STR=["clusterd","clustered","cluster","cluster tool"] DAV_TEST_STR=["dev test","davtest","devtest","dave test"] DEBLAZE_STR=["deblaze","de blaze","d blaze","t blaze","the blaze"] FIMAP_STR=["fimap","five map ","fee map","fiemap","fymap","fly map"] GRABBER_STR=["grabber","grab her","grab air"] JBOSS_AUTOPWN_WIN_STR=["jey boss auto","jboss auto win"] JBOSS_AUTOPWN_LINUX_STR=["jboss auto linux","jey boss auto"] JOOMSCAN_STR=["zoom scan","joom scan"] JQSL_STR=["jsql","j sql"] PAD_BUSTER_STR=["bad buster","pad buster"] SKIP_FISH_STR=["skip fish","skip phish"] WAPITI_STR=["wapiti","vaapiti"] WEBSPLOIT_STR=["web sploit","websploit"] WHATWEB_STR=["what web","whatweb"] XSSER_STR=["xsser","x s s e r"] COMMIX_STR=["commix","commics","comics"] HTTRACK_STR=["httrack","ht track"] WEBSCARAB_STR=["web scrap","webscrap"] DATABASE_EXPLOIT=["database exploit","databases exploit"] MDB_EXPORT_STR=["mdb export"," m d b s t r","mdb s t r"] MDB_HEXDUMP_STR=["mdb hex dump","mdb hexdump"] MDB_PARSER_CSV_STR=["mdb parser csv","mdb parser","parser mdb","csv parser"] MDB_SQL_STR=["mdb sql","sql mdb",] MDB_TABLES_STR=["mdb tables","tables mdb"] OSCANNER_STR=["o scanner"] SID_GUESSER_STR=["sit guesser ","said guesser"] SQL_LITE_DATABASE_BROWSER_STR=["sql lite database browser","sql database browser"] POMPEM_STR=["pompem","pom pem"] SANDI_GUI_STR=["sandy gui","sandi gui"] IPV6_TOOLS_STR=["ipv6 tools","ipv6 tools"] FAKE_ROUTER_STR=["fake router"] DENIAL6_STR=["denial 6 ","denial six","daniel six"] MSFVENOM_STE=["msf venom","venom"] METASPLOIT_STR=["metasploit","msf console"] PAYLOAD_GENERATOR_STR=["payload generator","pay load generator"] SHELL_NOOB_STR=["shell noob","noob shell"] SOCIAL_ENGINEERING_TOOLS_STR=["social engineering tools","set tool","set tool","social engineering tool"] TERMINETER_STR=["terminator","termineter"] SQL_MAP_STR=["sql map"] BEEF_XSS_FRAMEWORK=["beef xss framework","beef framework"] BBQSQL_STR=["bbqsql",'bbq sql',"borbeque sql"] AV_EVASION_STR=['av evasion'] HYPERION_STR=['hyper ion','hyperion'] SHELLTER_STR=['shelter tool','shelter'] OS_BACKDOOR_STR=['os backdoor','back door factory'] CRYPT_CAT_STR=['crypt cat','script cat'] DBD_STR=['dbd','dbd tool'] SBD_STR=['sbd','sbd tool'] TUNNELING_AND_EXFILTRATION_TOOL_STR=['tunneling ','exfiltration tool','proxy tunnel'] IODINE_STR=['iodine'] PROXY_CHAINS_STR=['proxy chain tool','proxy chains'] PTUNNEL_STR=['ptunnel','be tunnel','p tunnel'] SSLH_STR=['sslh tool','sslh'] UDP_TUNNEL_STR=['udp tunnel'] WEB_BACKDOOR_STR=['web backdoor','lauda num'] NISHANG_STR=['nishang','nisha tool'] WEBACOO_STR=['webacoo','web cool'] BDF_PROXY_STR=['bdf proxy','bdf'] WINDOWS_BINARIES_STR=['window binaries','windows binaries'] HASH_AND_PASSWORD_STR=['hash and password dump'] WCE_STR=['wce','w c e'] PASSING_HASH_ATTACK_TOOL_STR=['passing hash attack tool','hashing attack tool'] PTH_NET_STR=['pth net'] PTH_OPEN_CLIENT_STR=['pth open change client'] PTH_SMGGET_STR=['pth smg get','pthsmg get','pitch smg get'] CYMOTHOA_STR=['cymathoa'] INTERSECT_STR=['intersect'] POWERSPLOIT_STR=['power sploit','power spoil'] LOCAL_ATTACK_TOOLS=['loacl attack tools','chntpw'] CACHE_DUMP_STR=['cache dump'] OPHCRACK_CLI_STR=['opchcrack cli','ophcrack command line interface','off crack cli'] PWDUMP_STR=['pw dump'] SAMDUMP_STR=['samdump 2','sam dump 2'] OFFLINE_PASSWORD_ATTACK_TOOL_STR=['offline password attack tool'] CRACKLE_STR=['crackle'] FCRAKZIP_STR=['f crack zip','fcrack zip'] HASH_CAT_STR=['hash cat','hashcat'] JOHN_STR=['john'] PDF_CRACK_STR=['pdf crack'] PYRIT_STR=['pirate','pyrit'] RAINBOW_CRACK_STR=['rainbow','rainbow crack'] RAR_CRACK_STR=['rar crack','rare crack'] SIP_CRACK_STR=['ship crack','sip crack'] SUCRACK_STR=['sue crack','shoe crack','su crack'] TRUE_CRACK_STR=['true crack'] ONLINE_PASSWORD_CRACK_STR=['online password crack ','online password attack tool'] BRUTESPRAY_STR=['brute spray','brutespray'] CHANGE_ME_STR=['change me'] HYDRA_STR=['hydra'] MEDUSA_STR=['medussa','medusa'] NCRACK_STR=['n crack','in crack'] ONE_SIXTY_ONE=['one sixty one','161'] PATATOR_STR=['patator','pay eater'] XHYDRA_STR=['x hydra','ex hydra'] WORDLIST_TOOLS=['rs mangler','word list tools'] CEWL_STR=['cewl','c e w l'] CRUNCH_STR=['crunch'] MASKGEN_STR=['mask gen'] PIPAL_STR=['pipe all','pi pal','pipal'] POLICY_GEN=['policy gen','policygen'] STATSGEN_STR=['stats gen','states gen'] WORDLISTS_STR=['word lists'] FIND_MY_HASH=['find my hash'] HASHID_STR=['hash id'] HASH_IDENTIFIER_STR=['hash identifier'] WIFITE_STR=['wifite','wi-fi it'] BLUETOOTH_STR=['blue tooth hacking tool'] BLUELOG_STR=['blue log'] BLUE_RANGER_STR=['blue ranger'] BT_SCANNER_STR=['bt scanner'] RED_FANG_STR=['red fang'] GEN_KEYS_STR=['gen keys','gen key'] HACK_RF_INFO_STR=['hack rf info'] UBERTOOTH_UTIL=['uber tooth util'] RFID_AND_NFC_TOOLS=['rfid and nfc tools','rfid tools','nfc tools'] SOFTWARE_DETAILED_RADIO_STR=['software detailed radio'] INSPECTRUM_STR=['in spectrum','inspector drum'] RFCAT_STR=['rf cat'] GNU_RADIO_COMPANION_STR=['gnu radio companion'] FERN_WIFI_CRACKER_STR=['fern wifi cracker','fern'] MDK3_STR=['mdk3'] PIXIE_WPS_STR=['pixie wps'] REAVER_STR=['river','reaver'] NETWORK_SNIFFERS_STR=['network sniffers'] HEX_INJECT_STR=['hex inject'] CHAOS_READER_STR=['chaos reader'] DARK_STAT_STR=['dark statistics','dark stats'] NET_SNIFF_STR=['net sniffer','net sniff'] NFSPY_STR=['nf spy'] WEBSPY_STR=['web spy'] SSLSNIFF_STR=['ssl sniff'] SPOOFING_AND_MITM_STR=['mitm','spoofing and mitm'] PARASITE6_STR=['parasite6'] WIFI_HONEY_STR=['wifi honey'] BETTTER_CAP_SRT=['better cap'] ETHERRAPE_STR=['ether rape','etherrape'] HAMSTER_STR=['hamster'] IMPACKET_STR=['im packet'] MACCHANGER_STR=['mac changer'] MITM_PROXY_STR=['mitm proxy'] RESPONDER_STR=['responder'] DIGITAL_FORENSIC_TOOL=['digital forensic tool'] FORENSIC_CARVING_TOOL=['pasco','forensic carving tool'] PDF_FORENSIC_TOOL=['pdf forensic tool'] AUTOSPY_STR=['auto spy'] BIN_WALK_STR=['bin walk'] BULK_EXTRACTOR_STR=['bulk extractor'] CHKROOTKIT_STR=['chk root kit'] FOREMOST_STR=['foremost'] GALLETA_STR=['galleta'] HASH_DEEP_STR=['hash deep'] RKHUNTER_STR=['rk hunter'] VOLA_FOX_STR=['vola fox','ola fox'] VOLATILITY_STR=['volatility'] VARA_STR=['vara'] AUTOMOTIVE_STR=['automotive tools'] DEBUGER_STR=['debugger','gdb'] JAVA_SNOOP_STR=['java snoop'] DECOMPILERS_STR=['decompilers',"decompiling tool"] JAD_STR=['jad'] DIASSEMBLER_STR=['smali'] FLASM_STR=['flasm'] RADARE_2_FRAMEWORK_STR=['radar 2 framework','radare 2'] APK_TOOL_STR=['apk tool'] CLANG_STR=['clang'] CASEFILES_STR=['case file'] EYE_WITNESS_STR=['eye witness str'] META_GOOFIL_STR=['meta goofil'] FARADAY_IDE_STR=['farday ide'] DBEAVER_STR=['de beaver','debeaver'] GEANY_STR=['geany'] GIT_COLA_STR=['git cola'] GIT_DAG_STR=['git dag'] MELD_STR=['meld'] SUBLIME_STR=['sublime'] ZEAL_STR=['zeal'] XRC_STR=['xrc','xrcced'] BRASERO_STR=['brasero'] CHEESE_STR=['cheese'] LMMS_STR=['lmms'] MPV_MEDIA_PLAYER_STR=['mpv media player'] SOUND_KONVERTER=['sound converter'] TIMIDITY_STR=['timidity'] VOKO_SCREEN_STR=['voko screen'] BLEACH_BIT_STR=['bleach bit'] CAJA_STR=['caja','gaja','kaja'] DCONFEDITOR_STR=['dconfeditor','deconfigured editor','deconfiguration editor'] DVDISASTER_STR=['dv disaster'] GDEBI_STR=['g debi'] GPARTED_STR=['gpart','g part','g parted'] GUYMAGER_STR=['guy mager','guy imager'] HTOP_STR=['htop','h top','running threads','running process'] LOG_FILE_VIEWER_STR=['log file viewer'] NEOVIM_STR=['neovim'] GQRX_STR=['gqrx'] HEXCAT_STR='hex cat' QBITTORRENT_STR=['bittorrent','qbittorrent'] REMMINA_BROWSER_STR=['remmina browser','remmina'] TOR_BROWSER_STR=['tor','tor browser'] CONTROL_CENTER_0R_SETTINGS_STR=['settings','control panel','control center','mate settings','mate control panel'] TWEAKS_STR=['tweaks','tweak'] SYSTEM_MONITOR_PROCESSOR_USE=['procesor usage','system monitor','ram usage'] HTTP_STR=['ngnix','http server'] POSTGRESQL_STR=['postgre sql','sql server'] SSHD_STR=['sshd'] WIFI_STR=['wifi','wi-fi'] BLUETOOTH_STR=['blue tooth','bluetooth','Bluetooth'] <file_sep>/voicetyping.py from pynput.keyboard import Key,Controller import time import Audio import strlists import os import engine import pyautogui def typein(): try: while 1: text = Audio.get_audio() k=Controller() if text in strlists.VOICETYPING_KEYPRESSES_STR: for phrase in strlists.VOICETYPING_KEYPRESSES_STR: if "select all" in text: pyautogui.hotkey('ctrl','a') elif "undo" in text: pyautogui.hotkey('ctrl','z') elif "redo" in text: pyautogui.hotkey('ctrl','y') elif "copy" in text: pyautogui.hotkey('ctrl','c') elif "paste" in text: pyautogui.hotkey('ctrl','v') elif "italic" in text: pyautogui.hotkey('ctrl','i') elif "cut" in text: pyautogui.hotkey('ctrl','x') pass elif phrase in text: pyautogui.press(phrase) elif 'switch off voice typing' in text: engine.speak("getting out of voice typing master") time.sleep(2) break else: k.type(text) continue except: engine.speak("something went wrong master!!") <file_sep>/engine.py import os import pyttsx3 def speak(text): engine = pyttsx3.init() engine.setProperty('rate', 150) engine.setProperty('volume',1.0) voices = engine.getProperty('voices') engine.setProperty('voice', voices[2].id) engine.say(text) engine.runAndWait()
44cf6e1c978062bd1162bc18b95e505679148293
[ "Markdown", "Python" ]
8
Python
Surya2709/personal-linux-voice-assistant
3291edca028046f9741d321c69008d4aa087df07
c9dd21f7b290c520ee2d48dc848bf304d231fba0
refs/heads/master
<repo_name>naimul-ferdous/testingJupyter<file_sep>/hello.py def hello(): i=0 while True: print(i) i= i+1 print('Hello') hello()
dcff136aacc8b55297e3c5b50fd11afd8a1e3795
[ "Python" ]
1
Python
naimul-ferdous/testingJupyter
04471191dc51bb8c1e5c491278b84c584414ed1c
90c06b31d42b0d4d0d9a5ed82b6d976e9d72cd73
refs/heads/main
<repo_name>RiverWillett07/Which-Basketball-Player-are-you<file_sep>/script.js let counter=0; $("button").click(function() { counter=counter+1; let question_one_input = $(".question-one").val(); let question_two_input = parseInt($(".question-two").val()); if (question_one_input === "A" && question_two_input === 1) { $(".result").text("<NAME>"); } else if (question_one_input === "B" && question_two_input === 1) { $(".result").text("<NAME>"); } else if (question_one_input === "C" && question_two_input === 1) { $(".result").text ("<NAME>"); } else if (question_one_input === "A" && question_two_input === 2) { $(".result").text ("<NAME>"); } else if (question_one_input === "B" && question_two_input === 2) { $(".result").text ("<NAME>"); } else if (question_one_input === "C" && question_two_input === 2) { $(".result").text ("<NAME>"); } else if (question_one_input === "A" && question_two_input === 3) { $(".result").text ("<NAME>"); } else if (question_one_input === "B" && question_two_input === 3) { $(".result").text ("<NAME>"); } else if (question_one_input === "C" && question_two_input === 3) { $(".result").text ("<NAME>"); } else{ $(".result").text ("Invalid Answer"); } });
a3fe3830bed5cc7655a0dcdfe998227dea05c2eb
[ "JavaScript" ]
1
JavaScript
RiverWillett07/Which-Basketball-Player-are-you
7fd6bf80898da4c0f83e114588c508b7c47f53a9
9b9cf456f42475e8c4bdca16d8953a132ca3c556
refs/heads/master
<file_sep>//============================================================================ // Name : ADS.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; typedef struct { int n; }TInfo; typedef struct s_nodo{ TInfo info; struct s_nodo* sig; }TNode; typedef TNode* TStack; void createStack(TStack* p){ *p = NULL; } int push(TStack* p, TInfo* n){ TNode* nn = malloc(sizeof(TNode)); if (nn==NULL){ return 0; }else{ nn->info = *n; nn->sig = *p; *p = nn; return 1; } } int main() { cout << "Inicializando pila" << endl; // prints !!!Hello World!!! createStack() return 0; } <file_sep>/* * Stack.h * * Created on: Jul 24, 2017 * Author: ubuntumate */ #ifndef STACK_H_ #define STACK_H_ class Stack { private: public: Stack(); virtual ~Stack(); }; #endif /* STACK_H_ */
37656a711ac853d34bee70aaef792c57ae30e300
[ "C++" ]
2
C++
PabloSoligo2014/ADS
f23692069dba1ad7263518d03082ce7c28bf62c5
b2b55fd2fcb6736f4a19eec9c82e5330bd059ea4
refs/heads/master
<repo_name>caiomartin/PDM_01<file_sep>/app/src/main/java/com/programacaoplus/projetoespecial_/somaDoisNumeros.java package com.programacaoplus.projetoespecial_; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.text.DecimalFormat; public class somaDoisNumeros extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_soma_dois_numeros); Onclic(); } public void Onclic(){ final Button cal = (Button)findViewById(R.id.calcular); cal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EditText n1 = (EditText) findViewById(R.id.n1); EditText n2 = (EditText) findViewById(R.id.n2); String s1 = n1.getText().toString(); String s2 = n2.getText().toString(); TextView res = (TextView) findViewById(R.id.resultado); if (verifica(s1, s2)) { res.setText("Preenche os campos!"); } else { double num1 = Double.parseDouble(n1.getText().toString()); double num2 = Double.parseDouble(n2.getText().toString()); double soma; soma = num1 + num2; DecimalFormat df = new DecimalFormat("0.0"); res.setText("Soma: " + df.format(soma)); } } }); } public void voltar(View view) { Intent tela = new Intent(this, MainActivity.class); startActivity(tela); } public boolean verifica(String s1, String s2){ if(s1.equals("") || s2.equals("")) return true; else return false; } } <file_sep>/app/src/main/java/com/programacaoplus/projetoespecial_/operacoesAritimeticas.java package com.programacaoplus.projetoespecial_; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.text.DecimalFormat; public class operacoesAritimeticas extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_operacoes_aritimeticas); soma(); subtracao(); divisao(); multiplicacao(); } public void soma(){ final Button cal = (Button)findViewById(R.id.soma); cal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EditText n1 = (EditText) findViewById(R.id.n1); EditText n2 = (EditText) findViewById(R.id.n2); String s1 = n1.getText().toString(); String s2 = n2.getText().toString(); TextView res = (TextView) findViewById(R.id.resultado); if (verifica(s1, s2)) { res.setText("Preenche os campos!"); } else { double num1 = Double.parseDouble(n1.getText().toString()); double num2 = Double.parseDouble(n2.getText().toString()); double soma; soma = num1 + num2; DecimalFormat df = new DecimalFormat("0.0"); res.setText("Resultado: " + df.format(soma)); } } }); } public void subtracao(){ final Button cal = (Button)findViewById(R.id.subtracao); cal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EditText n1 = (EditText) findViewById(R.id.n1); EditText n2 = (EditText) findViewById(R.id.n2); String s1 = n1.getText().toString(); String s2 = n2.getText().toString(); TextView res = (TextView) findViewById(R.id.resultado); if(verifica(s1,s2)){ res.setText("Preenche os campos!"); }else { double num1 = Double.parseDouble(n1.getText().toString()); double num2 = Double.parseDouble(n2.getText().toString()); double soma; soma = num1 - num2; DecimalFormat df = new DecimalFormat("0.0"); res.setText("Resultado: " + df.format(soma)); } } }); } public void divisao(){ final Button cal = (Button)findViewById(R.id.divisao); cal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EditText n1 = (EditText) findViewById(R.id.n1); EditText n2 = (EditText) findViewById(R.id.n2); String s1 = n1.getText().toString(); String s2 = n2.getText().toString(); TextView res = (TextView) findViewById(R.id.resultado); if(verifica(s1,s2)){ res.setText("Preenche os campos!"); }else { Double num1 = Double.parseDouble(s1); Double num2 = Double.parseDouble(s2); double soma; soma = num1 / num2; DecimalFormat df = new DecimalFormat("0.0"); res.setText("Resultado: " + df.format(soma)); } } }); } public void multiplicacao(){ final Button cal = (Button)findViewById(R.id.multiplicacao); cal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EditText n1 = (EditText) findViewById(R.id.n1); EditText n2 = (EditText) findViewById(R.id.n2); String s1 = n1.getText().toString(); String s2 = n2.getText().toString(); TextView res = (TextView) findViewById(R.id.resultado); if(verifica(s1,s2)){ res.setText("Preenche os campos!"); }else { double num1 = Double.parseDouble(n1.getText().toString()); double num2 = Double.parseDouble(n2.getText().toString()); double soma; soma = num1 * num2; DecimalFormat df = new DecimalFormat("0.0"); res.setText("Resultado: " + df.format(soma)); } } }); } public boolean verifica(String s1, String s2){ if(s1.equals("") || s2.equals("")) return true; else return false; } public void voltar(View view) { Intent tela = new Intent(this, MainActivity.class); startActivity(tela); } } <file_sep>/app/src/main/java/com/programacaoplus/projetoespecial_/MainActivity.java package com.programacaoplus.projetoespecial_; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void openSomaDOisNumeros(View view) { Intent tela = new Intent(this, somaDoisNumeros.class); startActivity(tela); } public void openareaDoTriangulo(View view) { Intent tela = new Intent(this, areaDoTriangulo.class); startActivity(tela); } public void openMediaTresNotas(View view) { Intent tela = new Intent(this, MediaTresNotas.class); startActivity(tela); } public void openOperacoesAritimeticas(View view) { Intent tela = new Intent(this, operacoesAritimeticas.class); startActivity(tela); } public void openAliquotaIr(View view) { Intent tela = new Intent(this, aliquotaIr.class); startActivity(tela); } public void openMediaDosPesos(View view) { Intent tela = new Intent(this, MesdiaDosPesos.class); startActivity(tela); } }<file_sep>/README.md Trabalhos de Programação para dispositivos Móveis ======== <img src="http://imageshack.com/a/img924/4941/26qbFv.png" width="49%">
f46aa6920d51d8dd2b28e2f39911ef531916a687
[ "Markdown", "Java" ]
4
Java
caiomartin/PDM_01
11a531a169328a54a75e35a024d7aa60444b2b76
eaa449b9e412b762b4928b8bbcc732a4f86bbfb9
refs/heads/master
<file_sep>package Utils; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import AppAnalyzer.Configs; public class ErrorLogger { public synchronized static void writeError(String error){ PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter(new FileWriter(Configs.errorFile, true))); out.write(error); } catch (IOException e) { e.printStackTrace(); } finally{ out.close(); } } } <file_sep>package Utils; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.firefox.internal.ProfilesIni; import AppAnalyzer.Configs; public class DownloadUtils { String downloadLoc; DownloadThread dt; AndroidAppPushDownloaderThread adt; public DownloadUtils(){ } public void startDownloadApps(){ dt = new DownloadThread(); dt.start(); adt= new AndroidAppPushDownloaderThread(); adt.start(); } public void stopDownloadApps(){ dt.keepGoing=false; adt.keepGoing=false; } } <file_sep>package Utils; import java.io.File; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By.ByClassName; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import net.anthavio.phanbedder.Phanbedder; public class AndroidPlayStoreHelper { PhantomJSDriver driver; public AndroidPlayStoreHelper() { //Phanbedder to the rescue! File phantomjs = Phanbedder.unpack(); DesiredCapabilities dcaps = new DesiredCapabilities(); dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, phantomjs.getAbsolutePath()); driver = new PhantomJSDriver(dcaps); } public String[] getLastUpdatedAndOsVersion(String packageName){ String date=""; String osVersion=""; //Usual Selenium stuff... driver.get("https://play.google.com/store/apps/details?id="+packageName); // System.out.println(driver.getPageSource().contains("ijgewerkt")); List<WebElement> we= driver.findElements(By.className(("details-section-contents"))); //System.out.println(we.size()); for (int i = 0; i < we.size(); i++) { if(we.get(i).getAttribute("innerHTML").contains("ijgewerkt")){ //System.out.println("YEPPAAAA"); List<WebElement> we2=we.get(i).findElements(By.className("meta-info")); for (int j = 0; j < we2.size(); j++) { if(we2.get(j).getAttribute("innerHTML").contains("itemprop=\"operating")){ WebElement we3=we2.get(j); osVersion=we3.getText().split("\n")[1]; //System.out.println(osVersion); } if(we2.get(j).getAttribute("innerHTML").contains("itemprop=\"date")){ WebElement we3=we2.get(j); date=we3.getText().split("\n")[1]; // System.out.println(date); } } } } driver.quit(); return new String[]{date,osVersion}; } }<file_sep>import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import org.apache.commons.exec.util.StringUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import Utils.DBUtils; public class CordovaAnalyser { static String endResultString; public static void main(String args[]) { // doAllVersions(); // doAllCSPStuff(); // doAllJSFrameWorkChecks(); // checkPluginOrigin(); // countAllEvals(); doDeepCSPAnalysis(); //checkFileTransderPlugin(); } static void checkFileTransderPlugin() { try { ArrayList<String> results = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader("filetransferapps.txt")); String appname; appname = br.readLine(); while (appname != null) { String pathToAppSource = "/Volumes/Seagate/AppAnalysis/apps/decompfiles/" + appname; ArrayList<File> listOfFilesAl = new ArrayList<File>(); listf(pathToAppSource, listOfFilesAl); for(int i = 0; i < listOfFilesAl.size(); i++){ if(listOfFilesAl.get(i).getName().endsWith(".js")||listOfFilesAl.get(i).getName().endsWith(".html")){ BufferedReader brfile = new BufferedReader(new FileReader(listOfFilesAl.get(i))); String line; while ((line = brfile.readLine()) != null) { if(line.contains(".download(")){ results.add("DOWNLOAD;"+line.trim()+";"+listOfFilesAl.get(i)); System.out.println("DOWNLOAD:\t"+line.trim()); } if(line.contains(".upload(")){ results.add("UPLOAD;"+line.trim()+";"+listOfFilesAl.get(i)); System.out.println("UPLOAD:\t"+line.trim()); } } } } appname = br.readLine(); } System.out.println(results); Path file = Paths.get("resultsfiletransfer.txt"); Files.write(file, results, Charset.forName("UTF-8")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //////////////////////////////// static int countMatches(String input, String word) { int index = input.indexOf(word); int count = 0; while (index != -1) { count++; input = input.substring(index + 1); index = input.indexOf(word); } return count; } private static void doDeepCSPAnalysis() { try (BufferedReader br = new BufferedReader(new FileReader("cspsdef.txt"))) { int totalProcessedLines = 0; int amountofunsafeEvals = 0; int amountofunsafeInlines = 0; int amountofhttp = 0; ArrayList<String> lijstje = new ArrayList<String>(); String line; while ((line = br.readLine()) != null) { if (!line.equals("")) { totalProcessedLines = totalProcessedLines + 1; if (line.toLowerCase().contains("unsafe-eval")) { amountofunsafeEvals = amountofunsafeEvals + 1; } if (line.toLowerCase().contains("unsafe-inline")) { amountofunsafeInlines = amountofunsafeInlines + 1; } int tempamountofhttp = countMatches(line.toLowerCase(), "http") - countMatches(line.toLowerCase(), "https") - countMatches(line.toLowerCase(), "http-equiv"); if (tempamountofhttp > 0) { amountofhttp = amountofhttp + 1; lijstje.add(line+ "\n"); } else { System.err.println("da kan ier gwnweg nie"); } } } System.out.println("totallll: " + totalProcessedLines); System.out.println("unsafeEvals: " + amountofunsafeEvals); System.out.println("unsafeInline: " + amountofunsafeInlines); System.out.println("http: " + amountofhttp); System.out.println(lijstje); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static int checkforEval(String pathToAppSource) { int teller = 0; // alle files binnen die map ophalen String wwwDirPath = pathToAppSource + "/assets/www/"; ArrayList<File> listOfFilesAl = new ArrayList<File>(); listf(wwwDirPath, listOfFilesAl); // allemaal doorzoekenenenene for (int i = 0; i < listOfFilesAl.size(); i++) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(listOfFilesAl.get(i))); String currentLine = br.readLine(); while (currentLine != null) { if (currentLine.toLowerCase().contains("crosswalk")) { teller++; } currentLine = br.readLine(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return teller; } static void countAllEvals() { int totalevals = 0; ArrayList<String> al = DBUtils.getAllPhoneGapApps(); Map<String, Integer> resultmap = new HashMap<String, Integer>(); // System.out.println(al); for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i)); String pathToAppSource = "/Volumes/Seagate/AppAnalysis/apps/decompfiles/" + al.get(i); int amountOfEvals = checkforEval(pathToAppSource); System.out.println("evals found for " + al.get(i) + ": " + amountOfEvals); totalevals = totalevals + amountOfEvals; resultmap.put(al.get(i), amountOfEvals); } System.out.println(resultmap); System.out.println(totalevals); try { PrintWriter pw = new PrintWriter(new FileWriter("crosswalks.csv")); for (Map.Entry<String, Integer> entry : resultmap.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); pw.println(entry.getKey() + ";" + entry.getValue()); } pw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static void checkPluginOrigin() { // alle plugins per app (average plugins per app) Map<String, ArrayList<String>> m1 = DBUtils.getPluginMaps().get(0); // alle apps per plugin (gebruiken voor tellerke, en om na te kijken // welke plugin van store komt) Map<String, ArrayList<String>> m2 = DBUtils.getPluginMaps().get(1); // resultmap aanmaken Map<String, Boolean> mres = new HashMap<String, Boolean>(); // arrayList van alle plugins in de store ArrayList<String> al = new ArrayList<String>(); // vullen BufferedReader br = null; try { br = new BufferedReader(new FileReader("PluginMapping.csv")); String inp = br.readLine(); while (inp != null) { al.add(inp.split(";")[1]); inp = br.readLine(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { } } // System.out.println(al); int total = 0; int juist = 0; int fout = 0; int totalgewogen = 0; int juistgewogen = 0; int foutgewogen = 0; for (Map.Entry<String, ArrayList<String>> entry : m2.entrySet()) { String plugin = entry.getKey(); if (al.contains(plugin)) { mres.put(plugin, true); juist++; juistgewogen = juistgewogen + entry.getValue().size(); } else { mres.put(plugin, false); fout++; foutgewogen = foutgewogen + entry.getValue().size(); } total++; totalgewogen = totalgewogen + entry.getValue().size(); } System.out.println(mres); System.out.println(total + " " + juist + " " + fout); System.out.println(totalgewogen + " " + juistgewogen + " " + foutgewogen); // inlezen alle plugins. } static void doAllJSFrameWorkChecks() { ArrayList<String> al = DBUtils.getAllPhoneGapApps(); Map<String, ArrayList<String>> resultmap = new HashMap<String, ArrayList<String>>(); int teller = 0; for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i)); String pathToAppSource = "/Volumes/Seagate/AppAnalysis/apps/decompfiles/" + al.get(i); ArrayList<String> foundjsFrameworks = checkForJSFrameworks(pathToAppSource); if (foundjsFrameworks.size() > 0) { teller++; } for (int j = 0; j < foundjsFrameworks.size(); j++) { String foundjsfw = foundjsFrameworks.get(j); System.out.println(foundjsfw); if (resultmap.containsKey(foundjsfw)) { resultmap.get(foundjsfw).add(al.get(i)); } else { resultmap.put(foundjsfw, new ArrayList<String>()); resultmap.get(foundjsfw).add(al.get(i)); } } } for (String name : resultmap.keySet()) { String key = name.toString(); String value = resultmap.get(name).toString(); System.out.println(key + ";" + value); } for (String name : resultmap.keySet()) { String key = name.toString(); String value = resultmap.get(name).size() + ""; System.out.println(key + ";" + value); } System.out.println("Totaal aantal onderzochte pg apps: " + teller); } static void doAllCSPStuff() { endResultString = ""; ArrayList<String> al = DBUtils.getAllPhoneGapApps(); Map<String, ArrayList<String>> resultmap = new HashMap<String, ArrayList<String>>(); for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i)); String pathToAppSource = "/Volumes/Seagate/AppAnalysis/apps/decompfiles/" + al.get(i); String foundVersion = checkForCSP(pathToAppSource); System.out.println(foundVersion); if (resultmap.containsKey(foundVersion)) { resultmap.get(foundVersion).add(al.get(i)); } else { resultmap.put(foundVersion, new ArrayList<String>()); resultmap.get(foundVersion).add(al.get(i)); } } for (String name : resultmap.keySet()) { String key = name.toString(); String value = resultmap.get(name).toString(); System.out.println(key + ";" + value); } for (String name : resultmap.keySet()) { String key = name.toString(); String value = resultmap.get(name).size() + ""; System.out.println(key + ";" + value); } try { PrintWriter out = new PrintWriter("cspsdef.txt"); out.println(endResultString); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static void doAllVersions() { ArrayList<String> al = DBUtils.getAllPhoneGapApps(); Map<String, ArrayList<String>> resultmap = new HashMap<String, ArrayList<String>>(); for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i)); String pathToAppSource = "/Volumes/Seagate/AppAnalysis/apps/decompfiles/" + al.get(i); String foundVersion = getCordovaVersion(pathToAppSource); System.out.println(foundVersion); if (resultmap.containsKey(foundVersion)) { resultmap.get(foundVersion).add(al.get(i)); } else { resultmap.put(foundVersion, new ArrayList<String>()); resultmap.get(foundVersion).add(al.get(i)); } } for (String name : resultmap.keySet()) { String key = name.toString(); String value = resultmap.get(name).toString(); System.out.println(key + ";" + value); } for (String name : resultmap.keySet()) { String key = name.toString(); String value = resultmap.get(name).size() + ""; System.out.println(key + ";" + value); } } public static void listf(String directoryName, ArrayList<File> files) { File directory = new File(directoryName); // get all the files from a directory File[] fList = directory.listFiles(); if (fList != null) { for (File file : fList) { if (file.isFile()) { files.add(file); } else if (file.isDirectory()) { listf(file.getAbsolutePath(), files); } } } } public static ArrayList<String> checkForJSFrameworks(String pathToAppSource) { ArrayList<String> al = new ArrayList<>(); String wwwDirPath = pathToAppSource + "/assets/www/"; // get all items from the WWWdirectory. File wwwFolder = new File(wwwDirPath); ArrayList<File> listOfFilesAl = new ArrayList<File>(); listf(wwwDirPath, listOfFilesAl); // File[] listOfFiles = wwwFolder.listFiles(); if (listOfFilesAl != null) { for (int i = 0; i < listOfFilesAl.size(); i++) { System.out.println(listOfFilesAl.get(i).toString()); if (listOfFilesAl.get(i).toString().toLowerCase().contains("sencha")) { al.add("sencha"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("jquery")) { al.add("jquery"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("ionic")) { al.add("ionic"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("famous")) { al.add("famous"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("famo.us")) { al.add("famo.us"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("ratchet")) { al.add("ratchet"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("lungo")) { al.add("lungo"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("junior")) { al.add("junior"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("onsen")) { al.add("onsen"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("intel")) { al.add("intel"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("kendo")) { al.add("kendo"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("angular")) { al.add("angular"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("zepto")) { al.add("zepto"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("limejs")) { al.add("limejs"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("jqtouch")) { al.add("jqtouch"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("mobilize")) { al.add("mobilize"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("dhtmlx")) { al.add("dhtmlx"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("enyo")) { al.add("enyo"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("tabris")) { al.add("tabris"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("xdk")) { al.add("xdk"); } if (listOfFilesAl.get(i).toString().toLowerCase().contains("bootstrap")) { al.add("bootstrap"); } } if (al.size() == 0) { al.add("No Known Js FrameWork Used"); } // dupes verwijderen.... al = new ArrayList<String>(new LinkedHashSet<String>(al)); } return al; } static String checkForCSP(String pathToAppSource) { String hasCSPInHTML = "false"; String checkstring = "http-equiv=\"Content-Security-Policy\""; String filePath = pathToAppSource + "/assets/www/index.html"; File file = new File(filePath); if (file.exists()) { try { BufferedReader br = new BufferedReader(new FileReader(file)); String currentLine = br.readLine(); while (currentLine != null && hasCSPInHTML.equals("false")) { if (currentLine.toLowerCase().contains(checkstring.toLowerCase())) { hasCSPInHTML = "true"; System.out.println(currentLine); endResultString = endResultString + currentLine.trim() + "\n"; } else { currentLine = br.readLine(); } } } catch (IOException ioe) { ioe.printStackTrace(); } } else { hasCSPInHTML = "index not found"; } return hasCSPInHTML; } static String getCordovaVersion(String pathToAppSource) { // remake of this method String version = "Not Found"; String tool = "Tool Unknown"; String filePath = pathToAppSource + "/assets/www/"; // kijken of een een phonegap.js of cordova.js file is File dir = new File(filePath + "/cordova.js"); File dir2 = new File(filePath + "/phonegap.js"); if (dir.exists() || dir2.exists()) { File cordovaFile = null; if (dir.exists()) { tool = "cordova"; cordovaFile = dir; } else { cordovaFile = dir2; tool = "phonegap"; } boolean versionFound = false; BufferedReader br; try { br = new BufferedReader(new FileReader(cordovaFile)); String currentLine = br.readLine(); while (currentLine != null && !versionFound) { if (currentLine.contains("var PLATFORM_VERSION_BUILD_LABEL") || currentLine.contains("var CORDOVA_JS_BUILD_LABEL")) { version = currentLine.split("'")[1]; versionFound = true; } else { currentLine = br.readLine(); } } } catch (IOException e) { version = "Version Not Found error1"; } } else { // versienummer staat in de naam normaal gezien File fileDir = new File(filePath); FileFilter fileFilter = new WildcardFileFilter("cordova*.js"); File[] files = fileDir.listFiles(fileFilter); if (files != null && files.length != 0) { tool = "cordova"; version = files[0].toString().split("www/cordova")[1]; } else { fileFilter = new WildcardFileFilter("phonegap*.js"); files = fileDir.listFiles(fileFilter); if (files != null && files.length != 0) { tool = "phonegap"; version = files[0].toString().split("www/phonegap")[1]; } else { version = "Version Not Found 2"; } } } return tool + " " + version; } } <file_sep>package GUI; import java.util.ArrayList; import AppAnalyzer.Configs; import Utils.DBUtils; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableArray; import javafx.collections.ObservableList; import javafx.scene.chart.PieChart; import javafx.scene.control.ListView; public class GeneralOverviewThread extends Thread { static boolean keepUpdating; ListView<String> cptListView; ListView<String> overallListView; PieChart pcCPT; PieChart pcOverview; public GeneralOverviewThread(ListView<String> lv1, ListView<String> lv2, PieChart pc1, PieChart pc2) { overallListView = lv1; cptListView = lv2; pcCPT = pc1; pcOverview = pc2; keepUpdating=false; } public void stopUpdating(){ keepUpdating=false; try { this.finalize(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void generateOverallListView() { ArrayList<String> al = new ArrayList<String>(); al.add("KEYWORDS: "); al.add("\t Total: " + DBUtils.getAmount("KEYWORDS", "") + ", Checked: " + DBUtils.getAmount("KEYWORDS", "CHECKED IS 1")); al.add("\t Total permissions found: " + DBUtils.getAmount(Configs.table_permissions, "")); al.add("FOUND APPS: "); al.add("\t Total apps found: " + DBUtils.getAmount(Configs.table_foundapps, "")); al.add("\t Apps downloaded: " + DBUtils.getAmount(Configs.table_foundapps, "STAGE > 0")); al.add("\t Apps decompiled: " + DBUtils.getAmount(Configs.table_foundapps, "STAGE > 1")); al.add("\t Manifests found: " + DBUtils.getAmount(Configs.table_foundapps, "STAGE > 2")); al.add("\t Manifests analyzed for cpt usage: " + DBUtils.getAmount(Configs.table_foundapps, "STAGE > 3")); al.add("ERRORS: "); al.add("\t Download failed (DLer1): " + DBUtils.getAmount(Configs.table_foundapps, "FAILED = 1")); al.add("\t Download failed (DLer2): " + DBUtils.getAmount(Configs.table_foundapps, "FAILED = 11")); al.add("\t Decompilation failed: " + DBUtils.getAmount(Configs.table_foundapps, "FAILED = 2")); al.add("\t Finding manifest failed: " + DBUtils.getAmount(Configs.table_foundapps, "FAILED = 3")); al.add("\t Manifest useless: " + DBUtils.getAmount(Configs.table_foundapps, "FAILED = 4")); al.add(""); al.add("SOM AANGERAAKTE APPS: " + DBUtils.getAmount(Configs.table_foundapps, "STAGE <> 0 or FAILED <> 0")); ObservableList<String> observableList = FXCollections.observableList(al); Platform.runLater(new Runnable() { @Override public void run() { overallListView.setItems(observableList); // if you change the UI, do it here ! } }); } public void generateCPTListView() { ArrayList<String> al = new ArrayList<String>(); al.add("CROSS PLATFORM TOOLS FOUND: "); al.add("\t No CPT: " + DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.nativeorunknown + "'")); al.add("\t PhoneGap: " + DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_phonegap + "'")); al.add("\t Adobe Air: " + DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_adobeair + "'")); al.add("\t NativeScript: " + DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_nativescript + "'")); al.add("\t React Native: " + DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_react + "'")); al.add("\t Titanium: " + DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_titanium + "'")); al.add("\t Unity: " + DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_unity + "'")); al.add("\t Xamarin: " + DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_xamarin + "'")); ObservableList<String> observableList = FXCollections.observableList(al); Platform.runLater(new Runnable() { @Override public void run() { cptListView.setItems(observableList); // if you change the UI, do it here ! } }); } public void generateCPTPieChart() { ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList( new PieChart.Data("No CPT", DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.nativeorunknown + "'")), new PieChart.Data("PhoneGap", DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_phonegap + "'")), new PieChart.Data("Adobe Air", DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_adobeair + "'")), new PieChart.Data("NativeScript", DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_nativescript + "'")), new PieChart.Data("React Native", DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_react + "'")), new PieChart.Data("Titanium", DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_titanium + "'")), new PieChart.Data("Unity", DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_unity + "'")), new PieChart.Data("Xamarin", DBUtils.getAmount(Configs.table_foundapps, "CPT IS '" + Configs.cpt_xamarin + "'"))); Platform.runLater(new Runnable() { @Override public void run() { pcCPT.setTitle("FOUND CPTs"); pcCPT.setData(pieChartData); } }); } public void generateOverviewPieChart() { int downloadedapps = DBUtils.getAmount(Configs.table_foundapps, "STAGE IS 1"); int decompiledapps = DBUtils.getAmount(Configs.table_foundapps, "STAGE IS 2"); int analyzedapps = DBUtils.getAmount(Configs.table_foundapps, "STAGE > 3"); ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList( new PieChart.Data("\t Failed Apps", DBUtils.getAmount(Configs.table_foundapps, "FAILED > 0")), new PieChart.Data("\t Downloaded Stage", downloadedapps), new PieChart.Data("\t Decompiled Stage", decompiledapps), new PieChart.Data("\t Analyzed", analyzedapps)); Platform.runLater(new Runnable() { @Override public void run() { pcOverview.setTitle("PROCESSED APPS"); pcOverview.setData(pieChartData); } }); } public void run() { keepUpdating=true; while (keepUpdating) { generateOverallListView(); generateCPTListView(); generateCPTPieChart(); generateOverviewPieChart(); try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { this.finalize(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package controllers; import GUI.GeneralOverviewThread; import GUI.TableHelper; import Utils.AndroidMarket; import Utils.AppAnalyzerUtils; import Utils.DownloadUtils; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.chart.PieChart; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.Tab; import javafx.scene.control.TableView; import javafx.scene.control.TextField; public class MainController { AndroidMarket androidMarket; DownloadUtils downloadUtils; AppAnalyzerUtils appAnalyzerUtils; GeneralOverviewThread got; // crawler @FXML private Button crawlerStart; @FXML private Button crawlerStop; @FXML private Label crawlerCurrentActionLabel; @FXML private Label crawlerProgressLabel; // downloader @FXML private Button downloaderStart; @FXML private Button downloaderStop; @FXML private Label downloaderCurrentActionLabel; @FXML private Label downloaderProgressLabel; // analyzer // decompiler @FXML private Button decompilerStart; @FXML private Button decompilerStop; @FXML private Label decompilerCurrentActionLabel; @FXML private Label decompilerProgressLabel; // analyzer @FXML private Button analyzerStart; @FXML private Button analyzerStop; @FXML private Label analyzerCurrentActionLabel; @FXML private Label analyzerProgressLabel; // DB SECTION // General DB @FXML private Button GeneralDBLookup; @FXML private TextField generalDBInput; @FXML private TableView<ObservableList<String>> GeneralDBTable; // CRAWLER @FXML private Button DBCrawlerRefreshButton; @FXML private TableView<ObservableList<String>> DBCrawlerTableView; // APP OVERVIEW @FXML private Button DBAppOverViewRefreshButton; @FXML private TableView<ObservableList<String>> DBAppOverviewTableView; // PhoneGap @FXML private Button DBPhonegapRefreshButton; @FXML private TableView<ObservableList<String>> DBPhonegapTableView; //OVERVIEWTAB @FXML private ListView informationOverviewGeneralInfoListViewCPT; @FXML private ListView informationOverviewGeneralInfoListView; @FXML private PieChart informationOverviewPieChartCPT; @FXML private PieChart informationOverviewPieChart; @FXML private Tab informationOverviewTab; // crawler code public void initializeCrawlerScreen() { crawlerStop.setDisable(true); crawlerCurrentActionLabel.setText("crawler currently idle"); crawlerProgressLabel.setText("todo"); crawlerStart.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { crawlerStartAction(); } }); crawlerStop.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { crawlerStopAction(); } }); } public void crawlerStartAction() { System.out.println("crawler started"); crawlerCurrentActionLabel.setText("starting crawler..."); if (androidMarket == null) { androidMarket = new AndroidMarket(); } androidMarket.startGetAppNames(); crawlerCurrentActionLabel.setText("crawler running"); crawlerStart.setDisable(true); crawlerStop.setDisable(false); } public void crawlerStopAction() { System.out.println("stopping crawler..."); crawlerCurrentActionLabel.setText("stopping crawler when possible..."); androidMarket.stopGetAppNames(); } public void updateCrawlerStopped() { crawlerStart.setDisable(false); crawlerStop.setDisable(true); crawlerCurrentActionLabel.setText("crawler currently idle."); } // downloader code public void initializeDownloaderScreen() { downloaderStop.setDisable(true); downloaderCurrentActionLabel.setText("downloader currently idle"); downloaderProgressLabel.setText("todo"); downloaderStart.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { downloaderStartAction(); } }); downloaderStop.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { downloaderStopAction(); } }); } public void downloaderStartAction() { System.out.println("downloader started"); downloaderCurrentActionLabel.setText("starting downloader..."); if (downloadUtils == null) { downloadUtils = new DownloadUtils(); } downloadUtils.startDownloadApps(); downloaderCurrentActionLabel.setText("downloader running"); downloaderStart.setDisable(true); downloaderStop.setDisable(false); } public void downloaderStopAction() { System.out.println("stopping downloader..."); downloaderCurrentActionLabel.setText("stopping downloader when possible..."); downloadUtils.stopDownloadApps(); } public void updateDownloaderStopped() { downloaderStart.setDisable(false); downloaderStop.setDisable(true); downloaderCurrentActionLabel.setText("downloader currently idle."); } // analyser code // decompiler public void initializeDecompilerScreen() { decompilerStop.setDisable(true); decompilerCurrentActionLabel.setText("decompiler currently idle"); decompilerProgressLabel.setText("todo"); decompilerStart.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { decompilerStartAction(); } }); decompilerStop.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { decompilerStopAction(); } }); } public void decompilerStartAction() { System.out.println("decompiler started"); decompilerCurrentActionLabel.setText("starting decompiler..."); if (appAnalyzerUtils == null) { appAnalyzerUtils = new AppAnalyzerUtils(); } appAnalyzerUtils.startDecompileApps(); decompilerCurrentActionLabel.setText("decompiler running"); decompilerStart.setDisable(true); decompilerStop.setDisable(false); } public void decompilerStopAction() { System.out.println("stopping decompiler..."); decompilerCurrentActionLabel.setText("stopping decompiler when possible..."); appAnalyzerUtils.stopDecompileApps(); } public void updateDecompilerStopped() { decompilerStart.setDisable(false); decompilerStop.setDisable(true); decompilerCurrentActionLabel.setText("decompiler currently idle."); } // analyzer public void initializeAnalyzerScreen() { analyzerStop.setDisable(true); analyzerCurrentActionLabel.setText("analyzer currently idle"); analyzerProgressLabel.setText("todo"); analyzerStart.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { analyzerStartAction(); } }); analyzerStop.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { analyzerStopAction(); } }); } public void analyzerStartAction() { System.out.println("analyzer started"); analyzerCurrentActionLabel.setText("starting analyzer..."); if (appAnalyzerUtils == null) { appAnalyzerUtils = new AppAnalyzerUtils(); } appAnalyzerUtils.startAnalyzeApps(); analyzerCurrentActionLabel.setText("analyzer running"); analyzerStart.setDisable(true); analyzerStop.setDisable(false); } public void analyzerStopAction() { System.out.println("stopping analyzer..."); analyzerCurrentActionLabel.setText("stopping analyzer when possible..."); appAnalyzerUtils.stopAnalyzeApps(); } public void updateAnalyzerStopped() { analyzerStart.setDisable(false); analyzerStop.setDisable(true); analyzerCurrentActionLabel.setText("analyzer currently idle."); } // DB code public void initializeDBTab() { GeneralDBLookup.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { GeneralDBTable.getItems().clear(); GeneralDBTable.getColumns().clear(); String input = generalDBInput.getText(); TableHelper.fillTable(input, GeneralDBTable); } }); DBCrawlerRefreshButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { DBCrawlerTableView.getItems().clear(); DBCrawlerTableView.getColumns().clear(); TableHelper.fillTable("SELECT * FROM KEYWORDS;", DBCrawlerTableView); } }); DBAppOverViewRefreshButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { DBAppOverviewTableView.getItems().clear(); DBAppOverviewTableView.getColumns().clear(); TableHelper.fillTable("SELECT * FROM FOUNDAPPS;", DBAppOverviewTableView); } }); DBPhonegapRefreshButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { DBPhonegapTableView.getItems().clear(); DBPhonegapTableView.getColumns().clear(); TableHelper.fillTable("SELECT * FROM FOUNDAPPS WHERE CPT IS 'PhoneGap';", DBPhonegapTableView); } }); } //overviewTab starter public void initializeOverviewTab(){ informationOverviewTab.setOnSelectionChanged(new EventHandler<Event>() { @Override public void handle(Event e){ if(informationOverviewTab.isSelected()){ got= new GeneralOverviewThread(informationOverviewGeneralInfoListView,informationOverviewGeneralInfoListViewCPT,informationOverviewPieChartCPT,informationOverviewPieChart); got.start(); }else{ got.stopUpdating(); } } }); } // Alertdialog public static void ShowAlert(String title, String contentText) { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle(title); alert.setHeaderText(null); alert.setContentText(contentText); alert.showAndWait(); } } <file_sep>package Utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import AppAnalyzer.Configs; public class DBUtils { public synchronized static ArrayList<String> getAllPhoneGapApps() { ArrayList<String> list = new ArrayList<String>(); Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt .executeQuery("SELECT NAME FROM " + Configs.table_foundapps + " WHERE CPT IS 'PhoneGap';"); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { list.add(rs.getString(1)); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return list; } public synchronized static ArrayList<Map<String, ArrayList<String>>> getPluginMaps() { Map<String, ArrayList<String>> pluginAppMap = new HashMap<String, ArrayList<String>>(); Map<String, ArrayList<String>> appPluginMap = new HashMap<String, ArrayList<String>>(); Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM " + Configs.table_plugins_phonegap + ";"); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { String app = rs.getString(1); String plugin = rs.getString(3); // plugin-app map if (pluginAppMap.containsKey(plugin)) {// plugin bestaat al pluginAppMap.get(plugin).add(app); } else {// plugin bestaat ng niet pluginAppMap.put(plugin, new ArrayList<String>()); pluginAppMap.get(plugin).add(app); } // --------------------------------------------- // app-permission map if (appPluginMap.containsKey(app)) {// app bestaat al appPluginMap.get(app).add(plugin); } else {// app bestaat ng niet appPluginMap.put(app, new ArrayList<String>()); appPluginMap.get(app).add(plugin); } } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ArrayList<Map<String, ArrayList<String>>> ret = new ArrayList<Map<String, ArrayList<String>>>(); ret.add(appPluginMap); ret.add(pluginAppMap); return ret; } public synchronized static String getNextNonXMLPGApp() { String ret = null; Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt .executeQuery("SELECT * FROM " + Configs.table_phonegap_analysis + " WHERE CONFIG IS 0 LIMIT 1;"); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { ret = rs.getString(1); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return ret; } public synchronized static ArrayList<String> getUnusedPhoneGapApps() { ArrayList<String> list = new ArrayList<String>(); Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT NAME FROM " + Configs.table_foundapps + " WHERE CPT IS 'PhoneGap' AND NAME NOT IN (SELECT NAME FROM " + Configs.table_phonegap_analysis + ");"); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { list.add(rs.getString(1)); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return list; } public synchronized static void addPhoneGapPlugin(String app, String pluginName, String pluginPackageName, String version) { addValue(Configs.table_plugins_phonegap, "'" + app + "','" + pluginName + "','" + pluginPackageName + "','" + version + "'"); } public synchronized static void addPhoneGapAppToDedicatedTable(String app, String config, String plugins) { addValue(Configs.table_phonegap_analysis, "'" + app + "','" + config + "','" + plugins + "'"); } public synchronized static void addPermission(String app, String Permission) { addValue(Configs.table_permissions, "'" + app + "','" + Permission + "'"); } public synchronized static void setConfigXmlStatus(String app, String state) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_phonegap_analysis + " SET CONFIG = '" + state + "' WHERE name = '" + app + "'"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized static void setPGPluginStatus(String app, String state) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_phonegap_analysis + " SET PLUGINS = '" + state + "' WHERE name = '" + app + "'"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized static int getAmount(String tableName, String where) { int ret = 0; Connection c = null; Statement stmt = null; ArrayList<String> al = new ArrayList<String>(); try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); String statement = ""; if (where.equals("")) { statement = "SELECT COUNT(*) FROM " + tableName + ";"; } else { statement = "SELECT COUNT(*) FROM " + tableName + " WHERE " + where + ";"; } ResultSet rs = stmt.executeQuery(statement); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { ret = rs.getInt(1); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return ret; } public synchronized static String getAppFromStage(int stage) { String ret = null; Connection c = null; Statement stmt = null; ArrayList<String> al = new ArrayList<String>(); try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM " + Configs.table_foundapps + " WHERE STAGE IS " + stage + " AND FAILED IS 0 LIMIT 1;"); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { ret = rs.getString(1); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return ret; } public synchronized static void setCPT(String appName, String cpt) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); // tabellen maken als ze nog niet bestaan // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_foundapps + " SET CPT = '" + cpt + "' WHERE name = '" + appName + "'"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized static void setStage(String appName, int stage) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); // tabellen maken als ze nog niet bestaan // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_foundapps + " SET STAGE = " + stage + " WHERE name = '" + appName + "'"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized static void setFailedState(String appName, int failedStage) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); // tabellen maken als ze nog niet bestaan // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_foundapps + " SET FAILED = " + failedStage + " WHERE name = '" + appName + "'"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // UNTESTED function public synchronized static void setDownloaded(String keyword) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); // tabellen maken als ze nog niet bestaan // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_foundapps + " SET STAGE = " + Configs.stage_downloaded + " WHERE name = '" + keyword + "'"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // UNTESTED function public synchronized static void setNotDownloaded(String keyword) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_foundapps + " SET STAGE = " + Configs.stage_new + " WHERE name = '" + keyword + "'"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized static void fixFoundApps() { Connection c = null; Statement stmt = null; ResultSet rs; ArrayList<String> to1 = new ArrayList<String>(); ArrayList<String> to0 = new ArrayList<String>(); // ArrayList<String> al = new ArrayList<String>(); try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); rs = stmt.executeQuery("SELECT * FROM " + Configs.table_foundapps); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); boolean stage1 = false; while (rs.next()) { int failedstate = rs.getInt(15); if (rs.getString(1).equals("com.WomenPajamas.troxoapps")) { stage1 = true; } if (failedstate == 11 && !stage1) { to1.add(rs.getString(1)); } // if(failedstate==11&&stage1){ // to0.add(rs.getString(1)); // } } rs.close(); /* */ } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); for (int i = 0; i < to1.size(); i++) { DBUtils.setFailedState(to1.get(i), 1); } for (int i = 0; i < to0.size(); i++) { DBUtils.setFailedState(to0.get(i), 0); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized static ArrayList<String> getDownloadedNotAnalyzedApps() { Connection c = null; Statement stmt = null; ArrayList<String> al = new ArrayList<String>(); try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM " + Configs.table_foundapps + " WHERE STAGE IS " + Configs.stage_downloaded + " AND FAILED IS 0;"); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { al.add(rs.getString(1)); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return al; } public synchronized static ArrayList<String> getNonDownloadedApps() { Connection c = null; Statement stmt = null; ArrayList<String> al = new ArrayList<String>(); try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt .executeQuery("SELECT * FROM " + Configs.table_foundapps + " WHERE STAGE IS 0 AND FAILED IS 0;"); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { al.add(rs.getString(1)); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return al; } public synchronized static String getUnusedKeyword() { String ret = null; Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt .executeQuery("SELECT * FROM " + Configs.table_keywords + " WHERE CHECKED IS 0 LIMIT 1;"); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { ret = rs.getString(1); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return ret; } // UNTESTED CODE. TODO public synchronized static void setDownloadFailed(String keyword) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + AppAnalyzer.Configs.dbName); // tabellen maken als ze nog niet bestaan // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_foundapps + " SET FAILED = 1 WHERE name = '" + keyword + "' AND FAILED = 0"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized static void setKeywordUsed(String keyword) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + AppAnalyzer.Configs.dbName); // tabellen maken als ze nog niet bestaan // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_keywords + " SET CHECKED = 1 WHERE name = '" + keyword + "' AND CHECKED = 0"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // //deze functie later uitcommenten!!!!!! public synchronized static void dropTable(String tableName) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + AppAnalyzer.Configs.dbName); // tabellen maken als ze nog niet bestaan // table voor zoekwoorden stmt = c.createStatement(); String sql = "DROP TABLE IF EXISTS " + tableName; stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Table deleted successfully"); } public synchronized static void createTablesIfNeeded() { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + AppAnalyzer.Configs.dbName); // tabellen maken als ze nog niet bestaan // table voor zoekwoorden stmt = c.createStatement(); String sql = "CREATE TABLE IF NOT EXISTS KEYWORDS " + "(NAME TEXT UNIQUE NOT NULL, " + " CHECKED INT NOT NULL)"; stmt.executeUpdate(sql); stmt.close(); // table voor apps stmt = c.createStatement(); sql = "CREATE TABLE IF NOT EXISTS FOUNDAPPS " + "(NAME TEXT UNIQUE NOT NULL, " + " CREATOR TEXT NOT NULL, " + " DISPLAYEDNAME TEXT NOT NULL, " + " VERSION INT NOT NULL, " + " DOWNLOADCOUNT TEXT NOT NULL, " + " TYPE TEXT NOT NULL, " + " CATEGORY TEXT NOT NULL, " + " RATING DOUBLE NOT NULL, " + " RATINGCOUNT INT NOT NULL, " + " INSTALLSIZE INT NOT NULL, " + " LASTUPDATE TEXT NOT NULL, " + " OSVERSIONREQ TEXT NOT NULL, " + " TIMEOFDOWNLOAD LONG NOT NULL, " + " STAGE INT NOT NULL, " + " FAILED INT NOT NULL, " + " CPT TEXT NOT NULL)"; stmt.executeUpdate(sql); stmt.close(); // table voor PhoneGapAnalyse stmt = c.createStatement(); sql = "CREATE TABLE IF NOT EXISTS " + Configs.table_phonegap_analysis + " " + "(NAME TEXT UNIQUE NOT NULL, " + " CONFIG TEXT NOT NULL, " + " PLUGINS TEXT NOT NULL)"; stmt.executeUpdate(sql); stmt.close(); // table voor PhoneGap Plugins stmt = c.createStatement(); sql = "CREATE TABLE IF NOT EXISTS " + Configs.table_plugins_phonegap + " " + "(NAME TEXT NOT NULL, " + " PLUGINNAME TEXT NOT NULL, " + " PLUGINPACKAGENAME TEXT NOT NULL, " + " VERSION TEXT NOT NULL)"; stmt.executeUpdate(sql); stmt.close(); // table permissions stmt = c.createStatement(); sql = "CREATE TABLE IF NOT EXISTS PERMISSIONTABLE " + "(NAME TEXT NOT NULL, " + " PERMISSION TEXT NOT NULL)"; stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Table created successfully"); } public synchronized static void addValue(String tableName, String inputString) { Connection c = null; Statement stmt = null; String overhead = null; switch (tableName) { case "KEYWORDS": { overhead = AppAnalyzer.Configs.db_KeywordsOverhead; break; } case "FOUNDAPPS": { overhead = AppAnalyzer.Configs.db_FoundAppsOverhead; break; } case "PERMISSIONTABLE": { overhead = AppAnalyzer.Configs.db_PermissionsOverhead; break; } case Configs.table_phonegap_analysis: { overhead = AppAnalyzer.Configs.db_PgAnalysisOverhead; break; } case Configs.table_plugins_phonegap: { overhead = AppAnalyzer.Configs.db_PgPluginOverhead; break; } default: break; } try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + AppAnalyzer.Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); String sql = "INSERT OR IGNORE INTO " + tableName + " " + overhead + " " + "VALUES (" + inputString + " );"; System.out.println(sql); stmt.executeUpdate(sql); c.commit(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Value added successfully"); } // untested, but should work public synchronized static void fillKeywordsFromFile(String path) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(path)); String inp; while ((inp = br.readLine()) != null) { DBUtils.addValue(Configs.table_keywords, "'" + inp + "',0"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public synchronized static void printTable(String tableName) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + AppAnalyzer.Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName + ";"); ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) System.out.print(", "); String columnName = rsmd.getColumnName(i); System.out.print(columnName); } System.out.println(""); while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) System.out.print(", "); String columnValue = rs.getString(i); System.out.print(columnValue); } System.out.println(""); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Table printed successfully"); } public synchronized static void writeQueryResultToCsv(String query, String out) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(out)); Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + AppAnalyzer.Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery(query); ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) { System.out.print(", "); writer.write(";"); } String columnName = rsmd.getColumnName(i); writer.write(columnName); System.out.print(columnName); } System.out.println(""); writer.write("\n"); while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) { System.out.print(", "); writer.write(";"); } String columnValue = rs.getString(i); System.out.print(columnValue); writer.write(columnValue); } System.out.println(""); writer.write("\n"); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Table written to CSV file."); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //////////////////////////////////// public synchronized static void writeTableToCsv(String tableName, String out) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(out)); Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + AppAnalyzer.Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName + ";"); ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) { System.out.print(", "); writer.write(";"); } String columnName = rsmd.getColumnName(i); writer.write(columnName); System.out.print(columnName); } System.out.println(""); writer.write("\n"); while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) { System.out.print(", "); writer.write(";"); } String columnValue = rs.getString(i); System.out.print(columnValue); writer.write(columnValue); } System.out.println(""); writer.write("\n"); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Table written to CSV file."); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized static String sanitize(String inp) { inp = inp.replace("'", ""); inp = inp.replace("\\", ""); inp = inp.replace(",", "."); return inp; } public synchronized static void setDownloadTime(String appName, long currentTimeMillis) { Connection c = null; Statement stmt = null; try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); // tabellen maken als ze nog niet bestaan // table voor zoekwoorden stmt = c.createStatement(); String sql = "UPDATE " + Configs.table_foundapps + " SET TIMEOFDOWNLOAD = " + currentTimeMillis + " WHERE name = '" + appName + "'"; System.out.println(sql); stmt.executeUpdate(sql); stmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized static String getAppFromFailedState(int failedState) { String ret = null; Connection c = null; Statement stmt = null; ArrayList<String> al = new ArrayList<String>(); try { // starten Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:" + Configs.dbName); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM " + Configs.table_foundapps + " WHERE FAILED IS " + failedState + " LIMIT 1;"); ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { ret = rs.getString(1); } rs.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } finally { try { stmt.close(); c.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return ret; } } <file_sep>package Utils; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.Files; import java.util.Scanner; import AppAnalyzer.Configs; import javafx.application.Platform; public class AppAnalyzerThread extends Thread { static boolean keepGoing; public AppAnalyzerThread() { keepGoing = true; } public void run() { String appName = getNextApp(); while (keepGoing && appName != null) { // getmanifest String fileLoc = Configs.decompiledTempFilesLoc + "/" + appName; File manifest = getAndroidManifest(fileLoc); // check cpu usage if (manifest != null) { checkCPTUsage(manifest, appName); } appName = getNextApp(); } Platform.runLater(new Runnable() { @Override public void run() { GUI.Main.getMainController().updateAnalyzerStopped(); } }); try { this.finalize(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getNextApp() { System.out.println("in getNextApp"); String ret = null; ret = DBUtils.getAppFromStage(Configs.stage_decompiled); while (keepGoing && ret == null) { try { Thread.sleep(10000); } catch (InterruptedException e) { System.err.println("error bij wachten - mag niet gebeuren"); } ret = DBUtils.getAppFromStage(Configs.stage_decompiled); } return ret; } public static File getAndroidManifest(String fileLoc) { File f = new File(fileLoc); File[] matchingFiles = f.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("AndroidManifest") && name.endsWith("xml"); } }); String appName = fileLoc.split("/")[fileLoc.split("/").length - 1]; if (matchingFiles.length == 0) { // GEEN MANIFEST GEVONDEN => Failed state aanpassen DBUtils.setFailedState(appName, Configs.failed_manifestNotFound); return null; } else { // manifest wegschrijven naar map waar alle manifests terecht moeten // komen File manifestFile = matchingFiles[0]; try { Files.copy(manifestFile.toPath(), new File(Configs.allManifests + "/" + appName + "_AndroidManifest.xml").toPath()); DBUtils.setStage(appName, Configs.stage_manifest); } catch (IOException e) { System.out.println( "probleemke bij wegkopieren van de manifestfile, kan normaal gezien niet mis gaan...."); // TODO Auto-generated catch block e.printStackTrace(); } return manifestFile; } } public static String checkCPTUsage(File man, String appName) { String manif = ""; Scanner sc = null; try { sc = new Scanner(man); while (sc.hasNextLine()) { manif = manif + sc.nextLine(); } } catch (FileNotFoundException e) { // DIT OPVANGEN? // Kan nrml niet... // TODO Auto-generated catch block e.printStackTrace(); } String CPT = Configs.nativeorunknown; if (manif.length() < 10) { // MANIFEST IS USELESS DBUtils.setFailedState(appName, Configs.failed_manifestUseless); } else { String manifLC = manif.toLowerCase(); // PHONEGAP if (manifLC.contains("cordova") || manifLC.contains("phonegap")) { CPT = Configs.cpt_phonegap; } // XAMARIN if (manifLC.contains("monoruntime") || manifLC.contains("xamarin")) { CPT = Configs.cpt_xamarin; } // ADOBE AIR if (manifLC.contains("air.")) { CPT = Configs.cpt_adobeair; } // TITANIUM if (manifLC.contains("titanium.")) { CPT = Configs.cpt_titanium; } // React if (manifLC.contains(".react.")) { CPT = Configs.cpt_react; } // Nativescript if (manifLC.contains(".tns.") || manifLC.contains("nativescript")) { CPT = Configs.cpt_nativescript; } // Unity if (manifLC.contains("unityplayer") || manifLC.contains("unity3d") || manifLC.contains(".unityactivity")) { CPT = Configs.cpt_unity; } } DBUtils.setCPT(appName, CPT); DBUtils.setStage(appName, Configs.stage_analysedForCpt); return CPT; } } <file_sep>package Utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.commons.io.monitor.FileEntry; import AppAnalyzer.Configs; import javafx.application.Platform; public class DecompilerThread extends Thread { static boolean keepGoing; public DecompilerThread() { keepGoing=true; } public void run() { //get all files String appName= getNextApp(); while(keepGoing&&appName!=null){ File f = new File(Configs.tempfilesLoc + "/" + appName + ".apk"); if (f.exists()) { FileEntry fileEntry = new FileEntry(f); if (!alreadyDecompiled(fileEntry.getName())) { decompileApp(fileEntry.getName()); }else{ System.out.println("was al gedecompiled (look into this)"); } } else { System.out.println("was niet gedownload, wordt terug op niet gedownload gezet"); DBUtils.setNotDownloaded(appName); ErrorLogger.writeError(System.currentTimeMillis()+": app: " + appName + " was not downloaded yet"); } appName=getNextApp(); } Platform.runLater(new Runnable() { @Override public void run() {GUI.Main.getMainController().updateDecompilerStopped(); // Update/Query the FX classes here } }); try { this.finalize(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getNextApp(){ System.out.println("in get next app"); String ret = null; ret=DBUtils.getAppFromStage(Configs.stage_downloaded); while(keepGoing&&ret==null){ try { Thread.sleep(10000); } catch (InterruptedException e) { System.err.println("error bij wachten - mag niet gebeuren"); } ret=DBUtils.getAppFromStage(Configs.stage_downloaded); } return ret; } private static boolean alreadyDecompiled(String name) { String folderName = name.substring(0, name.length() - 4); System.out.println(folderName); // hier heb ik iets raar gedaan, werkt mogelijk nie for (final File fileEntry : new File(Configs.decompiledTempFilesLoc) .listFiles()) { // System.out.println(fileEntry.getName()); if (fileEntry.getName().equals(folderName)) { System.out.println("app: " + folderName + " was already decompiled"); DBUtils.setStage(folderName, Configs.stage_decompiled); ErrorLogger.writeError(System.currentTimeMillis()+": app: " + name + " was already decompiled"); return true; } } System.out.println("app: " + name + " was not decompiled already"); return false; } private static void decompileApp(String name) { System.out.println("decompiling " + name); try { ProcessBuilder pb = new ProcessBuilder( "java", "-jar", Configs.locationAPKtool, "d", "--frame-path", "/Users/michielwillocx/Downloads/apkstudio-2/binaries/apktool/", Configs.tempfilesLoc + "/" + name, "-o", Configs.decompiledTempFilesLoc + "/" + name.substring(0, name.length() - 4)); Process p; p = pb.start(); // uitprinten command line output String output = ""; BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); BufferedReader reader2 = new BufferedReader(new InputStreamReader( p.getErrorStream())); String line = ""; while ((line = reader.readLine()) != null) { output = output + line + "\n"; } while ((line = reader2.readLine()) != null) { output = output + line + "\n"; } //System.out.println(output); int tttt = p.waitFor(); //STAGE AANPASSEN NAAR GEDEDOMPILEERD DBUtils.setStage(name.substring(0,name.length()-4), Configs.stage_decompiled); //ALS HET GEDECOMPILEERD IS: originele APK file verwijderen. FileHelper.removeFile(Configs.tempfilesLoc + "/" + name); } catch (IOException | InterruptedException e) { //Decomile failed DBUtils.setFailedState(name, Configs.failed_decomp); // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package GUI; import controllers.MainController; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import javafx.scene.Parent; import javafx.scene.Scene; public class Main extends Application { static MainController controller; @Override public void start(Stage stage) { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("MainPage.fxml")); Parent root=loader.load(); Scene scene = new Scene(root,1600,800); controller = loader.<MainController>getController(); controller.initializeAnalyzerScreen(); controller.initializeDecompilerScreen(); controller.initializeCrawlerScreen(); controller.initializeDownloaderScreen(); controller.initializeDBTab(); controller.initializeOverviewTab(); stage.setTitle("App Analyzer"); stage.setScene(scene); stage.show(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } public static MainController getMainController(){ return controller; } } <file_sep>package Utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.UnreachableBrowserException; import AppAnalyzer.Configs; import javafx.application.Platform; import net.anthavio.phanbedder.Phanbedder; public class AndroidAppPushDownloaderThread extends Thread { static final String username = "<FILL IN EMAIL ADRESS>"; static final String password = "<FILL IN PASSWORD>"; boolean keepGoing; FirefoxDriver driver; DesiredCapabilities dcaps; FirefoxProfile profile; public AndroidAppPushDownloaderThread() { profile = new FirefoxProfile(); profile.setPreference("browser.download.folderList", 2); profile.setPreference("browser.download.dir", Configs.tempfilesLocPrimary); profile.setPreference("browser.download.manager.alertOnEXEOpen", false); profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.android.package-archive, application/octet-stream"); profile.setPreference("browser.download.manager.showWhenStarting", false); profile.setPreference("browser.download.manager.focusWhenStarting", false); profile.setPreference("browser.download.useDownloadDir", true); profile.setPreference("browser.helperApps.alwaysAsk.force", false); profile.setPreference("browser.download.manager.alertOnEXEOpen", false); profile.setPreference("browser.download.manager.closeWhenDone", true); profile.setPreference("browser.download.manager.showAlertOnComplete", true); profile.setPreference("browser.download.manager.useWindow", false); profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false); profile.setPreference("pdfjs.disabled", true); File file = new File("adblock_plus-2.7.3-sm+tb+fx+an.xpi"); try { profile.addExtension(file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } profile.setPreference("extensions.firebug.currentVersion", "1.8.1"); keepGoing = true; driver = new FirefoxDriver(profile); } @Override public void run() { loginToPlayStore(); String packageName = getNextApp(); while (keepGoing && packageName != null) { downloadAppViaPush(packageName); packageName = getNextApp(); } Platform.runLater(new Runnable() { @Override public void run() { if (DownloadThread.keepGoing == false) { GUI.Main.getMainController().updateDownloaderStopped(); } } }); try { this.finalize(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String getNextApp() { String ret = null; ret = DBUtils.getAppFromFailedState(Configs.failed_dl); while (keepGoing && ret == null) { try { Thread.sleep(10000); } catch (InterruptedException e) { System.err.println("error bij wachten - mag niet gebeuren"); } ret = DBUtils.getAppFromFailedState(Configs.failed_dl); } return ret; } public void screenshotDriver() { File srcFile = driver.getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(srcFile, new File("test.png")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void loginToPlayStore() { // TODO driver.get("https://play.google.com/store/apps/details?id=com.viber.voip"); WebElement loginKnop = driver.findElement(By.cssSelector(".gb_Je.gb_Ha.gb_rb")); System.out.println(loginKnop.getAttribute("innerHTML")); loginKnop.click(); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // fill in username WebElement usernameField = driver.findElement(By.cssSelector(".input-wrapper.focused")) .findElement(By.id("Email")); usernameField.sendKeys(username); // press next WebElement nextButton = driver.findElement(By.cssSelector(".rc-button.rc-button-submit")); nextButton.click(); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // fill in password WebElement passwordField = driver.findElement(By.id("password-shown")).findElement(By.id("Passwd")); passwordField.sendKeys(<PASSWORD>); WebElement loginButton = driver.findElement(By.id("signIn")); loginButton.click(); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // screenshotDriver(); } public void downloadAppViaPush(String packageName) { if (driver == null) { driver = new FirefoxDriver(profile); loginToPlayStore(); } try { driver.get("https://play.google.com/store/apps/details?id=" + packageName); WebElement installButton = driver.findElement( By.cssSelector(".apps.large.play-button.buy-button-container.is_not_aquired_or_preordered")); installButton.click(); Thread.sleep(2000); WebElement installButtonConfirm = driver.findElement(By.id("purchase-ok-button")); installButtonConfirm.click(); Thread.sleep(1000); // kijken of het gedownload is (pas als het gedlt en geinstalleerd // is komt het in de adb shell pm list packages lijst terecht. boolean downloaded = false; long startTime = System.currentTimeMillis(); while (!downloaded) { // 15 sec slapen voordat we opnieuw gaan testen Thread.sleep(15000); Process p = new ProcessBuilder("adb", "shell", "pm", "list", "packages").start(); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } String line = ""; String out = ""; while ((line = input.readLine()) != null) { out = out + line + "\n"; } // System.out.println(out); if (out.contains(packageName)) { downloaded = true; } if (startTime < System.currentTimeMillis() - (60 * 1000 * 10)) { throw new DownloadException("timeout bij downloaden door pushen naar phone"); } } // pad naar packagename lezen Process p = new ProcessBuilder("adb", "shell", "pm", "path", packageName).start(); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } String line = ""; String out = ""; while ((line = input.readLine()) != null) { out = out + line; } System.out.println("pad naar package: " + out); // app naar de harddisk weg schrijven p = new ProcessBuilder("adb", "pull", out.split("package:")[1], Configs.tempfilesLoc + "/" + packageName + ".apk").start(); input = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } line = ""; out = ""; while ((line = input.readLine()) != null) { out = out + line + "\n"; } while ((line = err.readLine()) != null) { out = out + line + "\n"; } System.out.println(out); // app terug verwijderen van den telefoon p = new ProcessBuilder("adb", "uninstall", packageName).start(); while ((line = input.readLine()) != null) { out = out + line + "\n"; } while ((line = err.readLine()) != null) { out = out + line + "\n"; } System.out.println(out); DBUtils.setDownloaded(packageName); DBUtils.setFailedState(packageName, Configs.failed_no); DBUtils.setDownloadTime(packageName, System.currentTimeMillis()); } catch (UnreachableBrowserException ube) { try { driver.quit(); } catch (Exception eee) { } driver = new FirefoxDriver(profile); ErrorLogger.writeError( "(ALTDL)Nieuwe driver moeten maken - UnreachableBrowserException: " + System.currentTimeMillis()); loginToPlayStore(); } catch (Exception e) { DBUtils.setFailedState(packageName, 11); e.printStackTrace(); } } } <file_sep># Security Analysis of Cordova Applications in Google Play This Git repository provides Java code, used in the paper "Security Analysis of Cordova Applications in Google Play", presented at FARES workshop, collocated at he ARES 2017 conference, located in Reggio Calabria, Italy. This repository contains the Java project used for the analysis. Most configurations (such as paths to required resources) can be adjusted in the Configs.java file. Nevertheless, it's possible that minor changes elsewhere in the code are required to make everything work. The code used in this work depends on several other tools: - Selenium (http://www.seleniumhq.org) - APKTool (https://ibotpeaches.github.io/Apktool/) - Android-Market-API (https://github.com/jberkel/android-market-api) <file_sep>package Utils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.w3c.dom.Document; import com.google.common.base.CaseFormat; import javafx.application.Platform; import net.anthavio.phanbedder.Phanbedder; public class AndroidMarketThreadNoMarketAPI extends Thread { PhantomJSDriver driver; // FirefoxDriver driver; boolean done; boolean keepGoing; String keyword; public AndroidMarketThreadNoMarketAPI() { File phantomjs = Phanbedder.unpack(); DesiredCapabilities dcaps = new DesiredCapabilities(); dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, phantomjs.getAbsolutePath()); driver = new PhantomJSDriver(dcaps); // driver = new FirefoxDriver(); done = false; keepGoing = true; } public void run() { // keyword = getNextKeyword(); keyword = "pis"; // while (keepGoing && keyword != null) { ArrayList<String> packageNames = new ArrayList<String>(); done = false; // pagina openen en naar beneden scrollen driver.get("https://play.google.com/store/search?q=" + keyword + "&c=apps"); boolean scrolledtothemax = scrollAsDownAsPossible(); System.out.println(scrolledtothemax); File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(srcFile, new File("/Users/michielwillocx/Desktop/screenshotteke.png")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<WebElement> apps = driver.findElements(By.cssSelector(".preview-overlay-container")); System.out.println(apps.size()); for (int i = 0; i < apps.size(); i++) { String pname = apps.get(i).getAttribute("data-docid"); System.out.println(pname); packageNames.add(pname); } for (int i = 0; i < packageNames.size(); i++) { String pname = packageNames.get(i); driver.get("https://play.google.com/store/apps/details?id=" + pname); String dlbuttintext = driver.findElement(By.cssSelector(".price.buy.id-track-click.id-track-impression")) .getAttribute("innerHTML"); //eerst checken of het ne gratis app is. if (!dlbuttintext.toLowerCase().contains("<span>kopen")) { String packageName = pname; String creator = "";// OK String displayedName = "";// OK int version = 0;// NOTOK NOTOK --> manifest String dlCount = "";// OK String type = "";// ? String category = "";// ? double rating = 0;// OK int ratingCount = 0;// OK int installSize = 0;// OK String lastUpdate = "";// OK String osVersionNeeded = "";// OK // displayedName WebElement dispnameElem = driver.findElement(By.className("id-app-title")); displayedName = dispnameElem.getAttribute("innerHTML"); WebElement creatorElem = driver.findElement(By.cssSelector(".document-subtitle.primary")); creator = creatorElem.findElement(By.tagName("span")).getAttribute("innerHTML"); List<WebElement> scoreElem = driver.findElements(By.className("score-container")); try { rating = Double.parseDouble(scoreElem.get(0) .findElement(By.xpath("//meta[@itemprop='ratingValue']")).getAttribute("content")); } catch (Exception e) { rating = -1.0; } try { ratingCount = Integer.parseInt(scoreElem.get(0) .findElement(By.xpath("//meta[@itemprop='ratingCount']")).getAttribute("content")); } catch (Exception e) { rating = -1; } List<WebElement> wes = driver.findElement(By.cssSelector(".details-section.metadata")) .findElement(By.className("details-section-contents")) .findElements(By.cssSelector(".meta-info")); for (int j = 0; j < wes.size(); j++) { // System.out.println(wes.get(j).getAttribute("innerHTML")); // last update: if (wes.get(j).findElement(By.className("title")).getAttribute("innerHTML").contains("ijgewerkt")) { lastUpdate = wes.get(j).findElement(By.className("content")).getAttribute("innerHTML"); } // dlcount: if (wes.get(j).findElement(By.className("title")).getAttribute("innerHTML") .contains("nstallaties")) { dlCount = wes.get(j).findElement(By.className("content")).getAttribute("innerHTML").trim(); } // installsize: size omzetten naar een int if (wes.get(j).findElement(By.className("title")).getAttribute("innerHTML").contains("rootte")) { String temp = wes.get(j).findElement(By.className("content")).getAttribute("innerHTML"); if (temp.contains("M")) { try { installSize = (int) Math.round(Double.parseDouble(temp.split("M")[0].trim().replace(",", "."))*(1024*1024)); } catch (NumberFormatException nfe) { nfe.printStackTrace(); installSize = -1; } } else { installSize = -1; } } // Osversionneeded: if (wes.get(j).findElement(By.className("title")).getAttribute("innerHTML") .contains("ndroid vereist")) { osVersionNeeded = wes.get(j).findElement(By.className("content")).getAttribute("innerHTML") .trim(); } } System.out.println("\nlastUpdate: " + lastUpdate + "\npackageName: " + packageName + "\ncreator: " + creator + "\ndisplayedName: " + displayedName + "\nversion: " + version + "\ndlCount: " + dlCount + "\ntype: " + type + "\ncategory: " + category + "\nrating: " + rating + "\nratingCount: " + ratingCount + "\ninstallSize: " + installSize + "\nosVersionNeeded: " + osVersionNeeded); } else { System.err.println("Dit was een betalende app (testing purposes)"); } } // nieuw keyword opvragen // } /* * Platform.runLater(new Runnable() { * * @Override public void run() { * GUI.Main.getMainController().updateCrawlerStopped(); // Update/Query * the FX classes here } }); * * try { this.finalize(); } catch (Throwable e) { // TODO Auto-generated * catch block e.printStackTrace(); } */ } private boolean scrollAsDownAsPossible() { int teller = 0; JavascriptExecutor jse = (JavascriptExecutor) driver; WebElement temp; boolean scrollFinishedSuccess = true; By selBy = By.tagName("body"); int currentScrollHeight = 0; String previousPage = ""; String currentPage = ""; boolean done = false; while (!done) { temp = driver.findElement(By.id("show-more-button")); if (temp.isDisplayed()) { temp.click(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); return false; } } currentScrollHeight = currentScrollHeight + 200; try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } jse.executeScript("window.scrollTo(0," + currentScrollHeight + ");", ""); currentPage = driver.getPageSource(); if (currentPage.equals(previousPage)) { teller++; if (teller > 30) { done = true; } } else { teller = 0; previousPage = currentPage; } } return scrollFinishedSuccess; } public String getNextKeyword() { System.out.println("in get next keyword"); String ret = null; ret = DBUtils.getUnusedKeyword(); while (keepGoing && ret == null) { try { Thread.sleep(10000); } catch (InterruptedException e) { System.err.println("error bij wachten - mag niet gebeuren"); } ret = DBUtils.getUnusedKeyword(); } return ret; } } <file_sep>package PhoneGapUtils; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.io.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import AppAnalyzer.Configs; import Utils.DBUtils; public class PhoneGapAnalyzerUtils { public static void populateDedicatedPhoneGapTable(){ ArrayList<String>list = DBUtils.getUnusedPhoneGapApps(); for (int i = 0; i < list.size(); i++) { DBUtils.addPhoneGapAppToDedicatedTable(list.get(i), "0", "0"); } } public static boolean getConfigXML(String packageName) { boolean ret = true; File xmlFile = Paths.get("/Volumes/Seagate/AppAnalysis/apps/decompfiles/" + packageName + "/res/xml/config.xml") .toFile(); System.out.println(xmlFile.getPath()); if (xmlFile.exists()) { try { FileUtils.copyFile(xmlFile, new File(Configs.pg_configFiles + "/" + packageName + "_config.xml")); DBUtils.setConfigXmlStatus(packageName, "1"); } catch (IOException e) { DBUtils.setConfigXmlStatus(packageName, "3"); ret = false; e.printStackTrace(); } } else { // todo DBUtils.setConfigXmlStatus(packageName, "2"); ret = false; } return ret; } public static boolean findAllPlugins(String packageName) { boolean ret = true; Map<String, String> foundPluginList = new HashMap<String, String>(); try { File xmlDocument = Paths.get(Configs.pg_configFiles + "/" + packageName + "_config.xml").toFile(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document document = documentBuilder.parse(xmlDocument); NodeList plugins = document.getElementsByTagName("feature"); for (int i = 0; i < plugins.getLength(); i++) { Element plugin = (Element) plugins.item(i); foundPluginList.put(plugin.getAttribute("name"), ((Element) (plugin.getElementsByTagName("param").item(0))).getAttribute("value")); } System.out.println("Total plugins: " + foundPluginList.size()); plugins = document.getElementsByTagName("plugin"); for (int i = 0; i < plugins.getLength(); i++) { Element plugin = (Element) plugins.item(i); foundPluginList.put(plugin.getAttribute("name"), plugin.getAttribute("value")); } if (foundPluginList.size() < 1) { ret = false; System.out.println("no plugins found in config list"); DBUtils.setPGPluginStatus(packageName, "2"); } else { System.out.println("Total plugins: " + foundPluginList.size()); for (String key : foundPluginList.keySet()){ System.out.println(key + " - " + foundPluginList.get(key)); DBUtils.addPhoneGapPlugin(packageName, key, foundPluginList.get(key), "-1");} } DBUtils.setPGPluginStatus(packageName, "1"); } catch (Exception e) { ret = false; DBUtils.setPGPluginStatus(packageName, "3"); e.printStackTrace(); } return ret; } }
a0f9860e5cf5495f258f2707e6a79477cc5cad75
[ "Markdown", "Java" ]
14
Java
MichielWillocx/CodovaAnalysisStore
cf4283bbc3c8ead63f2dfeadbaf75b98a18bb311
ddb985550973b84787981073e0e452166edb19bf
refs/heads/master
<file_sep><?php $db ['db_host'] = "localhost"; $db ['db_user'] = "root"; $db ['db_pass'] = ""; $db ['db_name'] = "cms"; foreach ($db as $key => $value){ define(strtoupper($key), $value); } $connection =mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME); if(!$connection) { echo "Error occurred"; } ?>
4381631fe9599dfaf5ac5f874c9ec1614c248c1a
[ "PHP" ]
1
PHP
ArminasPilotas/CMS-project
cf029ef992e8bba21537fdaf2096a2ce379d5e96
fea619df3a71ba5371973abfbf75654f53959593
refs/heads/master
<repo_name>JFaure06/dossier_www<file_sep>/Base-php/boutique/projet-boutique.php <?php /** * Created by PhpStorm. * User: julien * Date: 31/01/19 * Time: 13:35 */ $articles = array( 1 => array("Nom" => "D3 EVO/NRG 2019", "Prix" => 1849.99, "url" => "photo/101d3-10020_2.jpg", ), 2 => array("Nom" => "HO SYNDICATE ALPHA 2019", "Prix" => 1599.99, "url" => "photo/H90000006_1024x1024.jpg", ), 3 => array("Nom" => "RADAR VAPOR PRO BUILD 2019", "Prix" => 1799.99, "url" => "19000045341635_1024x1024.jpg", ), ); /*$articles = array("Nom" => "D3 NRG 2019", "Prix" => 1849.99, "url" => "photo/D3-NRG.jpg", "desc" => "Le ski EVO est l\"évolution du ski ARC (plus large sur toute sa surface) Cela permet d\"avoir un ski plus rapide ainsi que plus stable. Vous ne perdrez pas en rotation dans les virages avec ce ski a d\"avantage de concavité. Ce ski a la caractéristique de tourner très rond, idéal pour tous les skieurs cherchant un ski performant mais pardonnant les erreurs " );*/ ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Waterski and French in The Alps</title> <link href="https://fonts.googleapis.com/css?family=Ubuntu Condensed" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="boutique.css"> </head> <body> <!--HEADER --> <header class="header-home"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="boutique.php"><i class="material-icons text-warning">home</i></a> </li> <li class="nav-item"> <a class="nav-link" href="produits.php">Produits</a> </li> <li class="nav-item"> <a class="nav-link " href="contact.php">Contact</a> </li> </ul> </div> </nav> <div class="container-fluid mt-5 pt-5"> <div class="row p-2 d-flex flex-column flex-md-row"> <div class="col-md-4 container-fluid d-flex justify-content-center align-items-center order-1 order-md-1"> <h2 class="order-3 text-info text-secondary">SKIS DE SLALOM</h2> </div> <div class="col-md-8 container-fluid d-flex align-items-center order-2 order-md-2"> <p class="">Découvrez un grand choix de ski de slalom pour homme, femme et enfant. Que vous soyez amateur ou compétiteur, vous trouverez une large gamme de monoskis nautique parmi les plus grandes marques comme D3, Radar et HO. Notre gamme de ski de slalom de compétition 100% carbone et ultra léger. Vous pouvez contacter directement notre conseiller (coatch de ski nautique) qui répondra à toutes vos questions techniques et vous proposera un devis complet et adapté à votre gabarit, niveau et budget. </p> </div> </div> </div> </header> <main> <?php foreach ($articles as $value){ ?> <div class="card text-center" style="width: 50rem;"> <img src="<?php echo $articles["url"]; ?>" class="card-img-top img-article" alt="photo_Ski"> <div class="card-body"> <h3 class="card-title"><?php echo $articles["Nom"];?></h3> <p class="card-text btn btn-primary"><?php echo $articles["Prix"];?>$</p> </div> </div> <?php } ?> </main> </body> </html> <file_sep>/test/panier.php <?php session_start(); include_once 'Include/functions.php'; include_once 'Include/database_WSFIA.php'; include_once 'Include/function_Database.php'; $db = MaConnexion(); $var = GetProduits($db); if (isset($_POST["qt"])) { } else { $select = 1; } foreach ($articles as $panier) { /* si dans ma recherche pas clé existe j'affiche*/ if (array_key_exists($panier["id"], $_POST)) { /*j'appel ma fonction*/ } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Waterski and French in The Alps</title> <link href="https://fonts.googleapis.com/css?family=Ubuntu Condensed" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="boutique.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="<KEY>" crossorigin="anonymous"> </head> <body> <!--HEADER --> <?php include 'Header.php'; ?> <main> <h1>Panier</h1> <form method="post" action="panier.php"> <p class="mt-2">Commande :</p> <?php /*initialisation du total a 0*/ $total = 0; /*une boucle qui parcours mon tableau d'articles et celui mon panier*/ foreach ($articles as $panier) { /* si dans ma recherche pas clé existe j'affiche*/ if (array_key_exists($panier["id"], $_POST)) { /*j'appel ma fonction*/ $quantite = "qt" . $panier["id"]; $delete = "delete" . $panier["id"]; if (isset($_POST[$delete])) { echo "delete"; } /*articlePanier($panier, $_POST[$quantite]);*/ if (isset($_POST[$quantite])) { $total += $panier["Prix"] * $_POST[$quantite]; } else { $total += $panier["Prix"]; } } } echo $total . " $"; ?> <input type="submit" value="refresh" class="btn btn-dark"> </form> </main> <!--FOOTER --> <?php include 'Footer.php'; ?> </body> </html><file_sep>/article.php <?php include_once 'Include/database_WSFIA.php'; include_once 'Include/functions.php'; include_once 'Include/function_Database.php'; var_dump($_GET); $produitid = $_GET['id']; //$db = MaConnexion(); $article = GetProduit($produitid); ?> <?php include 'Header.php'; ?> <main> <?php afficheArticle($article); ?> </main> <!--FOOTER --> <?php include 'Footer.php'; ?> <file_sep>/Include/functions.php <?php /* ma fonction est composé d'une card qui reçois les information de mes articles*/ function afficheCatalogue(array $article) { ?> <div class="col-md-6"> <div class="card text-center shadow p-3 mb-5 bg-grey rounded" style="width: 50rem;"> <a href="article.php?id=<?php echo $article["idArticle"]; ?>"> <img src="photo/Catalogue/Ski/<?php echo $article["Image"]; ?>" class="card-img-top img-article w-25" alt="photo_Ski"> </a> <div class="card-body"> <h3 class="card-title"><?php echo $article["Nom"]; ?></h3> <p class="card-text btn btn-primary"><?php echo $article["Prix"]; ?> $</p> </div> <input type="checkbox" name="produit[]" id="<?php echo $article["idArticle"]; ?>" value="<?php echo $article["idArticle"]; ?>" class="container-fluid d-flex justify-align-center"/> <label for="case">Add to Card</label> </div> </div> <?php } /* ma fonction affiche le contenue et description des mes articles venant de ma BDD*/ function afficheArticle($article) { ?> <h1 class="text-center titreArticle"><?php echo $article ["Nom"] ?></h1> <div class="container-fluid mt-5"> <div class="row d-flex align-items-center"> <img src="photo/Catalogue/Ski/<?php echo $article ["Image"]; ?>" class="img-fluid col-md-3 order-1"> <article class="col-md-9 justify-items-center order-2"> <p><?php echo $article ["Description"] ?></p> </article> </div> </div> <div class="text-center"> <p class="btn btn-primary btn-lg mt-5 "><?php echo $article ["Prix"] ?>$</p> </div> <?php } function articlePanier($panier, $quantite) { ?> <div class="d-flex justify-content-center"> <div class="card text-center shadow p-3 mb-5 bg-grey rounded row" style="width: 50rem;"> <img src="Catalogue/photo/Ski/<?php echo $panier["Image"]; ?>" class="card-img-top img-article" alt="photo_Ski"> <div class="card-body"> <h3 class="card-title"><?php echo $panier["Nom"]; ?></h3> <p class="card-text btn btn-primary"><?php echo $panier["Prix"]; ?> $</p> </div> <select name="qt<?php echo $panier["idArticle"]; ?>" class="w-25"> <option <?php if ($quantite == 1) { echo "selected"; } ?> value="1">1 </option> <option <?php if ($quantite == 2) { echo "selected"; } ?> value="2">2 </option> <option <?php if ($quantite == 3) { echo "selected"; } ?> value="3">3 </option> <option <?php if ($quantite == 4) { echo "selected"; } ?> value="4">4 </option> </select> <input type="hidden" name="<?php echo $panier["idArticle"]; ?>" id="<?php echo $panier["idArticle"]; ?>" value="on" class="container-fluid d-flex justify-align-center"/> <input type="submit" value="delete" name="delete<?php echo $panier["idArticle"]; ?>" class="btn btn-danger w-25"> </div> </div> <?php } function totalPanier() { $liste = $_POST(); $total = 0; foreach ($liste as $panier) { $total += $panier["Prix"] * $_POST["qt"]; } return $total; } function creationPanier() { if (!isset($_SESSION['panier'])) { $_SESSION['panier'] = array(); } return true; } function ajouterArticle($id, $Nom, $Qts, $Prix) { //Si le panier existe /*if (creationPanier() ) {*/ //Si le produit existe déjà on ajoute seulement la quantité $positionProduit = array_search($id, $_SESSION['panier']); if ($positionProduit != false) { $_SESSION['panier'][$id]['qts'] += $Qts; } else { //Sinon on ajoute le produit $_SESSION['panier'][$id] = [ 'Nom' => $Nom, 'Qts' => $Qts, 'Prix' => $Prix, ]; } /*} else echo "Un problème est survenu veuillez contacter l'administrateur du site.";*/ } function supprimerArticle($id) { unset($_SESSION['panier'][$id]); //Si le panier existe /*if (creationPanier() && !isVerrouille()) { $tmp = array(); $tmp['Nom'] = array(); $tmp['Qts'] = array(); $tmp['Prix'] = array(); $tmp['verrou'] = $_SESSION['panier']['verrou']; for ($i = 0; $i < count($_SESSION['panier']['Nom']); $i++) { if ($_SESSION['panier']['Nom'][$i] !== $Nom) { array_push($tmp['Nom'], $_SESSION['panier']['Nom'][$i]); array_push($tmp['Qts'], $_SESSION['panier']['Qts'][$i]); array_push($tmp['Prix'], $_SESSION['panier']['Prix'][$i]); } } $_SESSION['panier'] = $tmp; //j'efface mon panier temporaire unset($tmp); } else echo "Un problème est survenu veuillez contacter l'administrateur du site.";*/ } function MontantGlobal() { $total = 0; foreach ($_SESSION['panier'] as $articledupanier) { $total += ($articledupanier['price'] * $articledupanier['qte']); } return $total; } function calculFraisdeport() { $poidspanier = 0; foreach ($_SESSION['panier'] as $articledupanier) { $poidspanier += $articledupanier['Weight']; if ($poidspanier > 0 && $poidspanier < 500) { $fraisdeport = 5; } elseif ($poidspanier >= 500 && $poidspanier < 2000) { $fraisdeport = $articledupanier['Weight'] * 0.1; } else { $fraisdeport = $articledupanier['Weight'] * 0; } } return $fraisdeport; } <file_sep>/test-article.php <?php /** * Created by PhpStorm. * User: julien * Date: 04/02/19 * Time: 10:43 */ include_once 'database_WSFIA.php'; include_once 'functions.php'; include_once 'function_Database.php'; var_dump($_GET); $produitid = $_GET['id']; $db = MaConnexion(); $article = GetProduit($db); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Waterski and French in The Alps</title> <link href="https://fonts.googleapis.com/css?family=Ubuntu Condensed" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="boutique.css"> </head> <body> <!--HEADER --> <header class="header-home "> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="boutique.php"><i class="material-icons text-warning">home</i></a> </li> <li class="nav-item"> <a class="nav-link" href="catalogue.php">catalogue</a> </li> <li class="nav-item"> <a class="nav-link " href="contact.php">Contact</a> </li> </ul> </div> </nav> <div class="container-fluid mt-5 pt-5"> <div class="row p-2 d-flex flex-column flex-md-row"> <div class="col-md-4 align-items-center order-1 order-md-1"> <h2 class="text-info text-secondary">SKIS DE SLALOM</h2> </div> <div class="col-md-8 container-fluid d-flex align-items-center order-2 order-md-2"> <p class="">Découvrez un grand choix de ski de slalom pour homme, femme et enfant. Que vous soyez amateur ou compétiteur, vous trouverez une large gamme de monoskis nautique parmi les plus grandes marques comme D3, Radar et HO. Notre gamme de ski de slalom de compétition 100% carbone et ultra léger. Vous pouvez contacter directement notre conseiller (coach de ski nautique) qui répondra à toutes vos questions techniques et vous proposera un devis complet et adapté à votre gabarit, niveau et budget. </p> </div> </div> </div> </header> <main> <?php afficheArticle($article); ?> </main> </body> </html> <file_sep>/JF-Shop/exo_boutique.sql SELECT * FROM Boutique.Adress;<file_sep>/Base-php/boutique/Article.php <?php /** * Created by PhpStorm. * User: julien * Date: 04/02/19 * Time: 10:43 */ var_dump($_GET); $produitid = $_GET['id']; $articles = array( array("id" => "1", "Nom" => "D3 EVO/NRG 2019", "Prix" => 1849.99, "url" => "photo/ski-de-slalom-d3.jpg", "desc" => "<p>En D3, nous comprenons que vous êtes unique et que vous construisez des skis avec différents styles de skieurs. Nous proposons deux skis de slalom haut de gamme différents mais égaux ; chacun avec sa propre philosophie de conception très distincte offrant deux chemins différents pour le même objectif ultime - plus de bouées et un meilleur ski.</p> <h6><strong>EVO - Contrôle intuitif</strong></h6> <p>Imaginez un ski qui anticipe intuitivement chacun de vos mouvements, déchire en un tournemain et suscite tout simplement la confiance. EVO est ce ski. Le tout nouveau EVO est la prochaine évolution de l'ARC. Avec des virages plus rapides et plus complets des deux côtés du parcours, l’EVO est lisse et prévisible, sans surprises. Mais ne vous y trompez pas… L'EVO a le cœur d'un guerrier. L'EVO crée instantanément de la vitesse en dehors du virage et crée un angle progressif dans le sillage. L'héritage de l'EVO provient du record du monde ARC. Si vous avez aimé l'ARC, vous devez absolument faire l'expérience de l'EVO.</p> <p>Rapide, sans effort et intuitif, voilà le EVO</p> <h6><strong>NRG - Performance puissante</strong></h6> <p> le premier tour, il est évident que ce n’est pas un autre ski. Le NRG délivre une puissance comme vous ne l’avez jamais vue auparavant. Le pouvoir de tenir un angle incroyable à travers les sillages. Pouvoir pivoter instantanément et construire un angle avec une efficacité incroyable. Bénéficiant du concave le plus profond de tous les skis D3 à ce jour, le NRG a la capacité de créer une connexion entre l’eau et le skieur qui doit être expérimentée. Le NRG tire ses tours symétriques d’un pattern rocker très agressif. Si votre objectif est de créer le plus d’ espace possible avant la prochaine bouée, le NRG est le ski qu'il vous faut..</p> <p>Puissant, stable, agressif, voilà le NRG</p>", "size" => "<strong>Disponible en 5 tailles : 64\", 65\", 66\", 67\" et 68\"</strong>", ), array("id" => "2", "Nom" => "GOODE REVOLUTION 2019", "Prix" => 2090.00, "url" => "photo/ReVoangle.jpg", "desc" => "<p>Présentation du RéVolution, un nouveau ski de GOODE qui offre une performance améliorée grâce à des percées dans la conception de la construction, de nouvelles fibres de carbone et un système de résine avancé. Le résultat est un ski offrant un rebond plus rapide et plus progressif, plus durable et pesant un quart de livre de moins que tout autre GOODE à ce jour.</p> <p>Les améliorations apportées améliorent considérablement la cohérence et les performances globales d'une forme dont le lignage gagnant comprend un championnat Big Dawg et plusieurs titres nationaux des États-Unis, y compris la victoire du slalom Open Mens. </p> <p>\"Cette forme est un gagnant éprouvé, mais grâce à un processus de recherche et développement de deux ans, nous avons pu augmenter les scores les plus élevés, ainsi que la convivialité et la prévisibilité\", a déclaré <NAME>, fondateur et président de GOODE Skis.</p> <p>Un nouveau processus de construction interne avancé comprend une dorsale interne allant de la queue du ski au sommet du tunnel. Cette fonctionnalité conduit à une «montée et descente» plus progressive du virage au premier sillage. </p> <p>\"La manière dont le ski s'adapte et rebondit après le virage est l'un des aspects les plus importants de la performance dans la conception des skis de slalom\", a déclaré <NAME>, président et fondateur de GOODE Skis. «Si le ski met trop de temps à se remettre en forme, vous perdez de la vitesse. Mais si elle rebondit trop vite et dans un mouvement saccadé, le ski peut être très incohérent. Le flex et le rebond de la RéVolution sont plus rapides que tous les autres skis que nous ayons jamais fabriqués, mais ils le font de manière très douce, pour des performances exceptionnelles sur lesquelles vous pouvez compter. »</p> <p>Grâce à un nouveau système de résine de fibre de carbone, les ingénieurs de GOODE ont pu augmenter la durabilité du ski tout en réduisant le poids, augmentant ainsi l'efficacité transversale et réduisant la traînée - ainsi que le travail supplémentaire qui y est associé. Les caractéristiques supplémentaires de la RéVolution comprennent un noyau résistant à l’eau et un rapport flex / torsion raffiné et plus tolérant.</p> <h6><strong>Ce que les grands skieurs disent de la RéVolution:</strong></h6> <p>Stable, prévisible et rapide sur tous les parcours. Ce ski est sans effort. ”- <NAME><br> «Cela vous fait penser à un grand ski et prend les angles comme un petit ski. C'est le meilleur ski que GOODE ait jamais construit. »- <NAME><br> «La RéVolution nécessite 20% moins d’efforts croisés que tous mes précédents skis, ce qui me permet de me rendre à la bouée plus tôt et plus facilement.» - <NAME><br> «Ce ski a une vitesse incroyablement rapide, mais contrôlable. Les virages à l'arrière sont incroyables et la direction transversale est exceptionnelle. »- <NAME> </p> <ul> <li>Inserts en laiton installés en usine</li> <li>Finbox de précision</li> <li>Garantie de cinq ans</li> <li>Fait à la main à Ogden, Utah, USA</li> </ul>" ), array("id" => "3", "Nom" => "HO SYNDICATE ALPHA 2019", "Prix" => 1599.99, "url" => "photo/Syndicate-alpha.jpg", "desc" => "<p>Syndicate Alpha s’appuie sur le succès de la conception de Syndicate PRO. Asher, Travers, LaPoint et Wingerter ont passé la saison 2018 à peaufiner une itération lâche et légère du design de Syndicate PRO; le tout nouveau 2019 Syndicate Alpha. L’Alpha partage le même profil de largeur que le Syndicate PRO, mais il est conçu avec une profondeur concave moins profonde dans la queue du ski et un rocker à la pointe plus plate, pour une sensation de liberté et de légèreté sur l’eau. Avec moins d'appui que le PRO, l'Alpha accélère avec moins d'effort physique et des projets plus larges au second sillage. La queue concave moins profonde permet à l'Alpha d'avoir plus de dérive de virage pour les finitions de virages serrés. Optimisé pour les skieurs qui préfèrent une faible traînée, moins d’effort physique, des skis rapides, légers et qui tournent vite, le Syndicate Alpha est prêt pour le combat. Qui ose gagne.</p> <h6><strong>Caractéristiques du produit:</strong></h6> <p>Pro Build désigne un noyau PMI et Textreme Carbon infusé avec Innegra. Le PMI est la mousse la plus légère et la plus réactive que l’argent puisse acheter, permettant au skieur d’obtenir un angle plus atteignable du virage et la capacité de le tenir à travers les sillages. Textreme permet au ski de fléchir instantanément et de manière uniforme, donnant au skieur plus de vitesse à partir d'un point plus large. Le Pro Build Vapor est tout ce qu'un skieur de compétition a toujours voulu, conçu pour performer entre 32 et 36 km / h et dans les parcours de slalom aux niveaux élites. C'est le modèle de choix de notre équipe Pro mais il est également idéal pour ceux qui cherchent à améliorer leurs compétences à tous les niveaux. Tout ce que vous avez à faire est de choisir une couleur!</p> <h6><strong>Mettant en vedette:</strong></h6> <p> • Profilé Syndicate PRO pour une accélération maximale et l'initiation automatique des virages<br> • Une queue concave pour une dérive accrue dans les virages serrés<br> • Une bascule plus plate crée une plate-forme stable à laquelle les skieurs peuvent faire confiance<br> • Flex rigide en torsion: conserve sa forme même en cas de forte charge pour une accélération optimale à la fin du virage.<br> • SpeedSkin en fibre de carbone: base de ski à texture laminaire avancée pour réduire la traînée de ski et augmenter la vitesse, avec un poids de ski 20% inférieur!<br> • Fait à la main à Seattle, Washington, USA<br> - Activé NFC - Informations fournies simplement. </p>", "size" => "<strong>Disponible en 5 tailles : 65\", 66\", 67\" et 68\"</strong>" ), array("id" => "4", "Nom" => "RADAR VAPOR PRO BUILD 2019", "Prix" => 1799.99, "url" => "photo/RADAR-VAPOR.jpg", "desc" => "<p>Voici le plus léger ski du marché avec son nouveau carbone PMI utilisé dans l\"industrie de l’aérospatiale<br> Le Vapor 2019 redéfinit complètement ce que nous pensions auparavant possible sur un ski. Une largeur supplémentaire à travers la queue rend le ski plus droit et permet une vitesse plus constante. La zone située directement sous votre pied avant a une conicité accrue, ce qui permet au ski de se déplacer plus facilement dans la fin du virage et permet à la hauteur de la spatule de rester constante, augmentant ainsi l'efficacité. Le large point du ski a été avancé, vous permettant de vous tenir sur le pied avant en toute confiance. Le résultat: un ski porteur de vitesse et qui crée un angle meilleur que tout le marché.</p> <h6><strong>Pro Build Vapor</strong></h6> <p>Pro Build désigne un noyau PMI et Textreme Carbon infusé avec Innegra. Le PMI est la mousse la plus légère et la plus réactive que l’argent puisse acheter, permettant au skieur d’obtenir un angle plus atteignable du virage et la capacité de le tenir à travers les sillages. Textreme permet au ski de fléchir instantanément et de manière uniforme, donnant au skieur plus de vitesse à partir d'un point plus large. Le Pro Build Vapor est tout ce qu'un skieur de compétition a toujours voulu, conçu pour performer entre 32 et 36 km / h et dans les parcours de slalom aux niveaux élites. C'est le modèle de choix de notre équipe Pro mais il est également idéal pour ceux qui cherchent à améliorer leurs compétences à tous les niveaux. Tout ce que vous avez à faire est de choisir une couleur!</p> <h6><strong>Mettant en vedette:</strong></h6> <p> - PMI Core - Léger, haute densité, la plupart des réponses.<br> - Textreme Carbon - Des composites plus légers et plus résistants.<br> - Innegra - Réduit les bavardages pour une conduite plus stable.<br> - CorFlex - Optimiser le flex dans les virages de votre ski.<br> - Activé NFC - Informations fournies simplement. </p>", "size" => "<strong>Disponible en 5 tailles : 64\", 65\", 66\", 67\" et 68\"</strong>" ), ); $sizeski = array("taille" => "<h6><strong>Tableau de taille :</strong></h6> <p>64\" (163 cm) - 50kg<br> 65\" (165 cm) entre 50 et 65kg<br> 66\" (167 cm) entre 65 et 78kg<br> 67\" (170 cm) entre 72 et 85kg<br> 68\" (173 cm) + 85kg</p>"); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Waterski and French in The Alps</title> <link href="https://fonts.googleapis.com/css?family=Ubuntu Condensed" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="boutique.css"> </head> <body> <!--HEADER --> <header class="header-home "> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="boutique.php"><i class="material-icons text-warning">home</i></a> </li> <li class="nav-item"> <a class="nav-link" href="produits.php">Produits</a> </li> <li class="nav-item"> <a class="nav-link " href="contact.php">Contact</a> </li> </ul> </div> </nav> <div class="container-fluid mt-5 pt-5"> <div class="row p-2 d-flex flex-column flex-md-row"> <div class="col-md-4 align-items-center order-1 order-md-1"> <h2 class="text-info text-secondary">SKIS DE SLALOM</h2> </div> <div class="col-md-8 container-fluid d-flex align-items-center order-2 order-md-2"> <p class="">Découvrez un grand choix de ski de slalom pour homme, femme et enfant. Que vous soyez amateur ou compétiteur, vous trouverez une large gamme de monoskis nautique parmi les plus grandes marques comme D3, Radar et HO. Notre gamme de ski de slalom de compétition 100% carbone et ultra léger. Vous pouvez contacter directement notre conseiller (coatch de ski nautique) qui répondra à toutes vos questions techniques et vous proposera un devis complet et adapté à votre gabarit, niveau et budget. </p> </div> </div> </div> </header> <?php foreach ($articles as $value){ if ($value["id"] == $produitid){ echo "trouve".$value["id"]; ?> <main> <h1 class="text-center titreArticle"><?php echo $value ["Nom"] ?></h1> <div class="container-fluid mt-5"> <div class="row d-flex align-items-center"> <img src="<?php echo $value ["url"]; ?>" class="img-fluid col-md-3 order-1"> <article class="col-md-9 justify-items-center order-2"> <p><?php echo $value ["desc"] ?><br><?php echo $value ["size"] ?></p> <p><?php echo $sizeski ["taille"] ?></p> </article> </div> </div> <div class="text-center"> <p class="btn btn-primary btn-lg mt-5 "><?php echo $value ["Prix"] ?>$</p> </div> </main> <?php } } ?> </body> </html> <file_sep>/test.php <?php /** * Created by PhpStorm. * User: julien * Date: 13/02/19 * Time: 09:07 */ try { $bdd = new PDO('mysql:host=localhost;dbname=Boutique;charset=utf8', 'julien', 'Juju26500'); $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e){ echo 'echec lors de la connexion : ' . $e->getMessage(); } /* $reponse = $bdd->query('select * from Article'); while ($donnees = $reponse->fetch()){ echo $donnees['Nom'] . ' coute ' . $donnees['Prix'] . ' $' . '<br />'; } $reponse->closeCursor(); */ $reponse = $bdd->query('select * from Article where idArticle in (1,4)'); while ($donnees = $reponse->fetch()) { echo $donnees['Nom'] . ' coute ' . $donnees['Prix'] . ' $' . '<br />'; } $reponse->closeCursor(); ?><file_sep>/panier_2.php <?php session_start(); include_once 'Include/functions.php'; require 'Include/function_Database.php'; //$db = MaConnexion(); if (!isset($_SESSION['panier'])) { $_SESSION['panier'] = []; } //Ajout un article au panier if (isset($_POST['ajoutPanier'])) { foreach ($_POST['produit'] as $article) { if (array_key_exists($article, $_SESSION['panier'])) { //var_dump("maj"); $_SESSION['panier'][$article]['qte']++; } else { //Sinon on ajoute le produit //var_dump("ajout"); $articleSelect = GetProduit("toto", $article); $_SESSION['panier'][$article] = [ 'id' => $articleSelect['idArticle'], 'img' => $articleSelect['Image'], 'name' => $articleSelect['Nom'], 'qte' => 1, 'price' => $articleSelect['Prix'], 'Weight' => $articleSelect['Poids'], ]; } } } //var_dump($_SESSION['panier']); // Modification des articles dans la session if (isset($_POST['modificationArticle'])) { // foreach ($_POST['quantite'] as $id => $qts) { $_SESSION['panier'][$id]['qte'] = $qts; } } // Suppression d'un article dans la session if (isset($_POST['suppressionArticle'])) { // unset($_SESSION['panier'][$_POST['suppressionArticle']]); } // Suppression du panier if (isset($_POST['deletetocard'])) { unset($_SESSION['panier']); $_SESSION['panier'] = array(); } // Maj Stock if (isset($_POST['validationCommande'])){ foreach () } // Code de listage et de calcul du total $ttc = MontantGlobal(); //Calcule des frais de port $fdp = calculFraisdeport(); include 'Header.php'; ?> <form method="post" action="panier_2.php"> <table class="table"> <thead> <tr> <th>Nom</th> <th>prix par article</th> <th>quantité</th> </tr> </thead> <tbody> <?php foreach ($_SESSION['panier'] as $articledupanier) { ?> <tr> <td> <?= $articledupanier['name'] ?> </td> <td> <?= number_format($articledupanier['price'] * $articledupanier['qte'], 2, ',', ' ') ?> $ </td> <td> <input type="number" name="quantite[<?= $articledupanier['id']; ?>]" value="<?= $articledupanier['qte']; ?>"/> <button name="suppressionArticle" type="submit" value="<?= $articledupanier['id']; ?>" class="btn btn-warning">delete </button> </td> </tr> <?php } ?> </tbody> <tfoot> <tr> <td>Frais de port : <?= number_format($fdp, 2, ',', ' ') ?></td> </tr> <tr> <td>Tva 20%</td> </tr> <tr> <td>Total <?= number_format($ttc, 2, ',', ' ') ?> $ ttc</td> </tr> </tfoot> </table> <input type="submit" name="validationCommande" value="valider le panier" class="btn btn-dark"> <input type="submit" name="modificationArticle" value="refresh" class="btn btn-dark"> <input type="submit" name="deletetocard" value="Vider le panier" class="btn btn-danger"> </form><file_sep>/Include/function_Database.php <?php //function MaConnexion() //{ try { $bdd = new PDO('mysql:host=localhost;dbname=Boutique;charset=utf8', 'julien', 'Juju26500') or die("Impossible de se connecter au serveur"); return $bdd; }catch(PDOException $e){ echo "error".$e; } //} function GetProduits() { global $bdd; $stmt = $bdd->query('select * from Article'); $result = $stmt->fetchAll(); return $result; } /* fonction avec requète*/ function GetProduit($id) { global $bdd; $stmt = $bdd->prepare('select * from Article where idArticle= :id'); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->execute(); $result = $stmt->fetch(); return $result; } function insertArticle($Nom,$Description,$Prix,$Stock){ global $bdd; $stmt = $bdd ->prepare("INSERT INTO Article (Nom, Description, Prix, Stock) VALUES (:Nom, :Description, :Prix, :Stock)"); $stmt -> bindParam(':Nom', $Nom, PDO::PARAM_STR); $stmt -> bindParam(':Description', $Description,PDO::PARAM_STR); $stmt -> bindParam(':Prix', $Prix, PDO::PARAM_INT); $stmt -> bindParam(':Stock', $Stock,PDO::PARAM_INT); $stmt -> execute(); } function MajStock(){ global $bdd; $stmt = $bdd ->prepare("UPDATE Article set Stock = (Stock - :qtepanier) Where Article.idArticle = :id"); $stmt -> bindParam(':qtepanier', $orderqte['qty'],PDO::PARAM_INT); $stmt -> bindParam(':id', $orderqty['id'],PDO::PARAM_INT); } /* fonction2 avec requète function GetProduit2($connexionbdd, $produitid) { $sql = 'select * from Article where idArticle=?'; $stmt = $connexionbdd->prepare($sql); $stmt->execute([$produitid]); $result = $stmt->fetch(); return $result; }*/<file_sep>/Catalogue.php <?php /** * Created by PhpStorm. * User: julien * Date: 31/01/19 * Time: 13:35 */ include_once 'functions.php'; include_once 'function_Database.php'; $db = MaConnexion(); $var = GetProduit($db); ?> <header class="header-home "> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="boutique.php"><i class="material-icons text-warning">home</i></a> </li> <li class="nav-item"> <a class="nav-link" href="catalogue.php">catalogue</a> </li> <li class="nav-item"> <a class="nav-link " href="contact.php">Contact</a> </li> </ul> </div> </nav> <div class="container-fluid mt-5 pt-5"> <div class="row p-2 d-flex flex-column flex-md-row"> <div class="col-md-4 align-items-center order-1 order-md-1"> <h2 class="text-info text-secondary">SKIS DE SLALOM</h2> </div> <div class="col-md-8 container-fluid d-flex align-items-center order-2 order-md-2"> <p class="">Découvrez un grand choix de ski de slalom pour homme, femme et enfant. Que vous soyez amateur ou compétiteur, vous trouverez une large gamme de monoskis nautique parmi les plus grandes marques comme D3, Radar et HO. Notre gamme de ski de slalom de compétition 100% carbone et ultra léger. Vous pouvez contacter directement notre conseiller (coatch de ski nautique) qui répondra à toutes vos questions techniques et vous proposera un devis complet et adapté à votre gabarit, niveau et budget. </p> </div> </div> </div> </header> <file_sep>/Base-php/Site_test1.php <?php /** * Created by PhpStorm. * User: julien * Date: 31/01/19 * Time: 13:35 */ $articles = ["D3" => "101d3-10020_2.jpg", "HO" => "H90000006_1024x1024.jpg", "RADAR" => "19000045341635_1024x1024.jpg"]; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Waterski and French in The Alps</title> <link href="https://fonts.googleapis.com/css?family=Ubuntu Condensed" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/app.css"> </head> <body> <header> <h1 class="">E-Shop</h1> </header> <main> <div class="container-fluid"> </div> </main> </body> </html> <file_sep>/Include/oserfunction.php <?php /** * Created by PhpStorm. * User: julien * Date: 13/02/19 * Time: 10:59 */ function jdebug($var){ highlight_string("<?php\n\$data =\n" . var_export($var, true) . ";\n?>"); }<file_sep>/BDD/Boutique.sql SELECT * FROM Boutique.Article;<file_sep>/test/Site_test1.php <?php /** * Created by PhpStorm. * User: julien * Date: 31/01/19 * Time: 13:35 */ /*$articles = array( 1 => array('Nom' => "D3", 'Prix' => 1849.99, 'url' => 'photo/101d3-10020_2.jpg', 'desc' => '' ), 2 => array('Nom' => "HO SYNDICATE ALPHA 2019", 'Prix' => 1599.99, 'url' => 'photo/H90000006_1024x1024.jpg', 'desc' => '' ), 3 => array('Nom' => "RADAR VAPOR PRO BUILD 2019", 'Prix' => 1799.99, 'url' => '19000045341635_1024x1024.jpg', 'desc' => 'Voici le plus léger ski du marché avec son nouveau carbone PMI utilisé dans l\'industrie de l’aérospatiale' ), ) */ $produit1 = array("Nom" => "D3 NRG 2019", "Prix" => 1849.99, "url" => "photo/D3-NRG.jpg", "desc" => "Le ski EVO est l\'évolution du ski ARC (plus large sur toute sa surface) Cela permet d\'avoir un ski plus rapide ainsi que plus stable. Vous ne perdrez pas en rotation dans les virages avec ce ski a d\'avantage de concavité. Ce ski a la caractéristique de tourner très rond, idéal pour tous les skieurs cherchant un ski performant mais pardonnant les erreurs " ); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Waterski and French in The Alps</title> <link href="https://fonts.googleapis.com/css?family=Ubuntu Condensed" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="boutique.css"> </head> <body> <header> <h1 class="text-center">E-Shop</h1> </header> <main> <?php //foreach ($produit1 as $value){ ?> <div class="card text-center" style="width: 50rem;"> <img src="<?php echo $produit1["url"]; ?>" class="card-img-top img-fluid w-25" alt="photo_D3"> <div class="card-body"> <h3 class="card-title"><?php echo $produit1["Nom"];?></h3> <p class="card-text"><?php echo $produit1["desc"];?></p> <p class="card-text btn btn-primary"><?php echo $produit1["Prix"];?>$</p> </div> </div> <?php //} ?> </main> </body> </html> <file_sep>/catalogue.php <?php session_start(); require 'Include/functions.php'; include_once 'Include/database_WSFIA.php'; include_once 'Include/function_Database.php'; //$db = MaConnexion(); $articles = GetProduits(); include 'Header.php'; ?> <main> <div class="container-fluid"> <form method="post" action="panier_2.php"> <input type="hidden" name="ajoutPanier"> <div class="row"> <?php foreach ($articles as $article) { afficheCatalogue($article); } ?> </div> <div class="row"> <div class="col-md-12 d-flex justify-content-center"> <input type="submit" value="Add to card" class="btn btn-success"> </div> </div> </form> </div> </main> <!--FOOTER --> <?php include 'Footer.php'; ?> <file_sep>/boutique.php <?php /** * Created by PhpStorm. * User: julien * Date: 05/02/19 * Time: 09:03 */ ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Waterski and French in The Alps</title> <link href="https://fonts.googleapis.com/css?family=Ubuntu Condensed" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="boutique.css"> </head> <body> <!--HEADER --> <header class="header-home"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="boutique.php"><i class="material-icons text-warning">home</i></a> </li> <li class="nav-item"> <a class="nav-link" href="catalogue.php">Produits</a> </li> <li class="nav-item"> <a class="nav-link " href="contact.php">Contact</a> </li> </ul> </div> </nav> <div class="container-fluid mt-5 pt-5"> <div class="row p-2 d-flex flex-column flex-md-row"> <div class="col-md-4 container-fluid d-flex justify-content-center align-items-center order-1 order-md-1"> <h2 class="order-3 text-info text-secondary">Waterski and French in The Alps</h2> </div> <div class="col-md-8 container-fluid d-flex align-items-center order-2 order-md-2"> <div> <img src="" class="img-fluid" alt="logo">> </div> </div> </div> </div> </header> <file_sep>/Include/database_WSFIA.php <?php /** * Created by PhpStorm. * User: julien * Date: 06/02/19 * Time: 09:45 */ /*$articles = array("Nom" => "D3 NRG 2019", "Prix" => 1849.99, "url" => "photo/D3-NRG.jpg", "desc" => "Le ski EVO est l\"évolution du ski ARC (plus large sur toute sa surface) Cela permet d\"avoir un ski plus rapide ainsi que plus stable. Vous ne perdrez pas en rotation dans les virages avec ce ski a d\"avantage de concavité. Ce ski a la caractéristique de tourner très rond, idéal pour tous les skieurs cherchant un ski performant mais pardonnant les erreurs " );*/ $articles = array( array("id" => "1", "Nom" => "D3 EVO/NRG 2019", "Prix" => 1849.99, "url" => "photo/ski-de-slalom-d3.jpg", "desc" => "<p>En D3, nous comprenons que vous êtes unique et que vous construisez des skis avec différents styles de skieurs. Nous proposons deux skis de slalom haut de gamme différents mais égaux ; chacun avec sa propre philosophie de conception très distincte offrant deux chemins différents pour le même objectif ultime - plus de bouées et un meilleur ski.</p> <h6><strong>EVO - Contrôle intuitif</strong></h6> <p>Imaginez un ski qui anticipe intuitivement chacun de vos mouvements, déchire en un tournemain et suscite tout simplement la confiance. EVO est ce ski. Le tout nouveau EVO est la prochaine évolution de l'ARC. Avec des virages plus rapides et plus complets des deux côtés du parcours, l’EVO est lisse et prévisible, sans surprises. Mais ne vous y trompez pas… L'EVO a le cœur d'un guerrier. L'EVO crée instantanément de la vitesse en dehors du virage et crée un angle progressif dans le sillage. L'héritage de l'EVO provient du record du monde ARC. Si vous avez aimé l'ARC, vous devez absolument faire l'expérience de l'EVO.</p> <p>Rapide, sans effort et intuitif, voilà le EVO</p> <h6><strong>NRG - Performance puissante</strong></h6> <p> le premier tour, il est évident que ce n’est pas un autre ski. Le NRG délivre une puissance comme vous ne l’avez jamais vue auparavant. Le pouvoir de tenir un angle incroyable à travers les sillages. Pouvoir pivoter instantanément et construire un angle avec une efficacité incroyable. Bénéficiant du concave le plus profond de tous les skis D3 à ce jour, le NRG a la capacité de créer une connexion entre l’eau et le skieur qui doit être expérimentée. Le NRG tire ses tours symétriques d’un pattern rocker très agressif. Si votre objectif est de créer le plus d’ espace possible avant la prochaine bouée, le NRG est le ski qu'il vous faut..</p> <p>Puissant, stable, agressif, voilà le NRG</p>", "size" => "<strong>Disponible en 5 tailles : 64\", 65\", 66\", 67\" et 68\"</strong>", ), array("id" => "2", "Nom" => "GOODE REVOLUTION 2019", "Prix" => 2090.00, "url" => "photo/ReVoangle.jpg", "desc" => "<p>Présentation du RéVolution, un nouveau ski de GOODE qui offre une performance améliorée grâce à des percées dans la conception de la construction, de nouvelles fibres de carbone et un système de résine avancé. Le résultat est un ski offrant un rebond plus rapide et plus progressif, plus durable et pesant un quart de livre de moins que tout autre GOODE à ce jour.</p> <p>Les améliorations apportées améliorent considérablement la cohérence et les performances globales d'une forme dont le lignage gagnant comprend un championnat Big Dawg et plusieurs titres nationaux des États-Unis, y compris la victoire du slalom Open Mens. </p> <p>\"Cette forme est un gagnant éprouvé, mais grâce à un processus de recherche et développement de deux ans, nous avons pu augmenter les scores les plus élevés, ainsi que la convivialité et la prévisibilité\", a déclaré <NAME>, fondateur et président de GOODE Skis.</p> <p>Un nouveau processus de construction interne avancé comprend une dorsale interne allant de la queue du ski au sommet du tunnel. Cette fonctionnalité conduit à une «montée et descente» plus progressive du virage au premier sillage. </p> <p>\"La manière dont le ski s'adapte et rebondit après le virage est l'un des aspects les plus importants de la performance dans la conception des skis de slalom\", a déclaré Dave Goode, président et fondateur de GOODE Skis. «Si le ski met trop de temps à se remettre en forme, vous perdez de la vitesse. Mais si elle rebondit trop vite et dans un mouvement saccadé, le ski peut être très incohérent. Le flex et le rebond de la RéVolution sont plus rapides que tous les autres skis que nous ayons jamais fabriqués, mais ils le font de manière très douce, pour des performances exceptionnelles sur lesquelles vous pouvez compter. »</p> <p>Grâce à un nouveau système de résine de fibre de carbone, les ingénieurs de GOODE ont pu augmenter la durabilité du ski tout en réduisant le poids, augmentant ainsi l'efficacité transversale et réduisant la traînée - ainsi que le travail supplémentaire qui y est associé. Les caractéristiques supplémentaires de la RéVolution comprennent un noyau résistant à l’eau et un rapport flex / torsion raffiné et plus tolérant.</p> <h6><strong>Ce que les grands skieurs disent de la RéVolution:</strong></h6> <p>Stable, prévisible et rapide sur tous les parcours. Ce ski est sans effort. ”- <NAME><br> «Cela vous fait penser à un grand ski et prend les angles comme un petit ski. C'est le meilleur ski que GOODE ait jamais construit. »- <NAME><br> «La RéVolution nécessite 20% moins d’efforts croisés que tous mes précédents skis, ce qui me permet de me rendre à la bouée plus tôt et plus facilement.» - <NAME><br> «Ce ski a une vitesse incroyablement rapide, mais contrôlable. Les virages à l'arrière sont incroyables et la direction transversale est exceptionnelle. »- <NAME> </p> <ul> <li>Inserts en laiton installés en usine</li> <li>Finbox de précision</li> <li>Garantie de cinq ans</li> <li>Fait à la main à Ogden, Utah, USA</li> </ul>" ), array("id" => "3", "Nom" => "HO SYNDICATE ALPHA 2019", "Prix" => 1599.99, "url" => "photo/Syndicate-alpha.jpg", "desc" => "<p>Syndicate Alpha s’appuie sur le succès de la conception de Syndicate PRO. Asher, Travers, LaPoint et Wingerter ont passé la saison 2018 à peaufiner une itération lâche et légère du design de Syndicate PRO; le tout nouveau 2019 Syndicate Alpha. L’Alpha partage le même profil de largeur que le Syndicate PRO, mais il est conçu avec une profondeur concave moins profonde dans la queue du ski et un rocker à la pointe plus plate, pour une sensation de liberté et de légèreté sur l’eau. Avec moins d'appui que le PRO, l'Alpha accélère avec moins d'effort physique et des projets plus larges au second sillage. La queue concave moins profonde permet à l'Alpha d'avoir plus de dérive de virage pour les finitions de virages serrés. Optimisé pour les skieurs qui préfèrent une faible traînée, moins d’effort physique, des skis rapides, légers et qui tournent vite, le Syndicate Alpha est prêt pour le combat. Qui ose gagne.</p> <h6><strong>Caractéristiques du produit:</strong></h6> <p>Pro Build désigne un noyau PMI et Textreme Carbon infusé avec Innegra. Le PMI est la mousse la plus légère et la plus réactive que l’argent puisse acheter, permettant au skieur d’obtenir un angle plus atteignable du virage et la capacité de le tenir à travers les sillages. Textreme permet au ski de fléchir instantanément et de manière uniforme, donnant au skieur plus de vitesse à partir d'un point plus large. Le Pro Build Vapor est tout ce qu'un skieur de compétition a toujours voulu, conçu pour performer entre 32 et 36 km / h et dans les parcours de slalom aux niveaux élites. C'est le modèle de choix de notre équipe Pro mais il est également idéal pour ceux qui cherchent à améliorer leurs compétences à tous les niveaux. Tout ce que vous avez à faire est de choisir une couleur!</p> <h6><strong>Mettant en vedette:</strong></h6> <p> • Profilé Syndicate PRO pour une accélération maximale et l'initiation automatique des virages<br> • Une queue concave pour une dérive accrue dans les virages serrés<br> • Une bascule plus plate crée une plate-forme stable à laquelle les skieurs peuvent faire confiance<br> • Flex rigide en torsion: conserve sa forme même en cas de forte charge pour une accélération optimale à la fin du virage.<br> • SpeedSkin en fibre de carbone: base de ski à texture laminaire avancée pour réduire la traînée de ski et augmenter la vitesse, avec un poids de ski 20% inférieur!<br> • Fait à la main à Seattle, Washington, USA<br> - Activé NFC - Informations fournies simplement. </p>", "size" => "<strong>Disponible en 5 tailles : 65\", 66\", 67\" et 68\"</strong>" ), array("id" => "4", "Nom" => "RADAR VAPOR PRO BUILD 2019", "Prix" => 1799.99, "url" => "photo/RADAR-VAPOR.jpg", "desc" => "<p>Voici le plus léger ski du marché avec son nouveau carbone PMI utilisé dans l\"industrie de l’aérospatiale<br> Le Vapor 2019 redéfinit complètement ce que nous pensions auparavant possible sur un ski. Une largeur supplémentaire à travers la queue rend le ski plus droit et permet une vitesse plus constante. La zone située directement sous votre pied avant a une conicité accrue, ce qui permet au ski de se déplacer plus facilement dans la fin du virage et permet à la hauteur de la spatule de rester constante, augmentant ainsi l'efficacité. Le large point du ski a été avancé, vous permettant de vous tenir sur le pied avant en toute confiance. Le résultat: un ski porteur de vitesse et qui crée un angle meilleur que tout le marché.</p> <h6><strong>Pro Build Vapor</strong></h6> <p>Pro Build désigne un noyau PMI et Textreme Carbon infusé avec Innegra. Le PMI est la mousse la plus légère et la plus réactive que l’argent puisse acheter, permettant au skieur d’obtenir un angle plus atteignable du virage et la capacité de le tenir à travers les sillages. Textreme permet au ski de fléchir instantanément et de manière uniforme, donnant au skieur plus de vitesse à partir d'un point plus large. Le Pro Build Vapor est tout ce qu'un skieur de compétition a toujours voulu, conçu pour performer entre 32 et 36 km / h et dans les parcours de slalom aux niveaux élites. C'est le modèle de choix de notre équipe Pro mais il est également idéal pour ceux qui cherchent à améliorer leurs compétences à tous les niveaux. Tout ce que vous avez à faire est de choisir une couleur!</p> <h6><strong>Mettant en vedette:</strong></h6> <p> - PMI Core - Léger, haute densité, la plupart des réponses.<br> - Textreme Carbon - Des composites plus légers et plus résistants.<br> - Innegra - Réduit les bavardages pour une conduite plus stable.<br> - CorFlex - Optimiser le flex dans les virages de votre ski.<br> - Activé NFC - Informations fournies simplement. </p>", "size" => "<strong>Disponible en 5 tailles : 64\", 65\", 66\", 67\" et 68\"</strong>" ), ); $sizeski = array("taille" => "<h6><strong>Tableau de taille :</strong></h6> <p>64\" (163 cm) - 50kg<br> 65\" (165 cm) entre 50 et 65kg<br> 66\" (167 cm) entre 65 et 78kg<br> 67\" (170 cm) entre 72 et 85kg<br> 68\" (173 cm) + 85kg</p>"); ?>
9da50062f0f617a6a6eee1b1b7205728dc9b1cd1
[ "SQL", "PHP" ]
18
PHP
JFaure06/dossier_www
ad3f4772cf161f6283f2da53a6afe0fad8a977de
b37294284a97ff424bcbc31a2eaebd0a7f3730df
refs/heads/master
<file_sep># SaaS Mag - Fastest Growing Companies Scraper This is a simple python script that scrapes the fastest growing companies from the Saas Mag website, along with company data, and writes it into a neatly formatted CSV file. ## Installation Required Packages: * requests==2.22.0 Use the package manager [pip](https://pip.pypa.io/en/stable/) to install the required packages. ```bash pip install -r requirements.txt ``` or ```bash pip install requests ``` ## Usage 1) Ensure all packages are installed. 2) Run `Python scraper.py`. The CSV file will be created in your current working directory. ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.<file_sep>import requests import csv def create_dictionary(): """ 1) Replicates the same AJAX call that 'https://www.saasmag.com/saas-1000-2018/' posts to retrive data shown in table. 2) Pulls the necessary data from URL and stores it in a dictionary named 'company_dict'. 3) Returns dictionary. Output -> { rank : {Company info : value} } """ url = r"https://www.saasmag.com/wp-admin/admin-ajax.php?action=companydatatable_action&year=2018" session = requests.Session() session.get("https://www.saasmag.com/saas-1000-2018") formdata = { 'draw': ['1'], 'columns[0][data]': ['0'], 'columns[0][name]': '', 'columns[0][searchable]': ['true'], 'columns[0][orderable]': ['false'], 'columns[0][search][value]': '', 'columns[0][search][regex]': ['false'], 'columns[1][data]': ['1'], 'columns[1][name]': '', 'columns[1][searchable]': ['true'], 'columns[1][orderable]': ['false'], 'columns[1][search][value]': '', 'columns[1][search][regex]': ['false'], 'columns[2][data]': ['2'], 'columns[2][name]': '', 'columns[2][searchable]': ['true'], 'columns[2][orderable]': ['false'], 'columns[2][search][value]': '', 'columns[2][search][regex]': ['false'], 'columns[3][data]': ['3'], 'columns[3][name]': '', 'columns[3][searchable]': ['true'], 'columns[3][orderable]': ['false'], 'columns[3][search][value]': '', 'columns[3][search][regex]': ['false'], 'columns[4][data]': ['4'], 'columns[4][name]': '', 'columns[4][searchable]': ['true'], 'columns[4][orderable]': ['false'], 'columns[4][search][value]': '', 'columns[4][search][regex]': ['false'], 'columns[5][data]': ['5'], 'columns[5][name]': '', 'columns[5][searchable]': ['true'], 'columns[5][orderable]': ['false'], 'columns[5][search][value]': '', 'columns[5][search][regex]': ['false'], 'columns[6][data]': ['6'], 'columns[6][name]': '', 'columns[6][searchable]': ['true'], 'columns[6][orderable]': ['false'], 'columns[6][search][value]': '', 'columns[6][search][regex]': ['false'], 'columns[7][data]': ['7'], 'columns[7][name]': '', 'columns[7][searchable]': ['true'], 'columns[7][orderable]': ['false'], 'columns[7][search][value]': '', 'columns[7][search][regex]': ['false'], 'columns[8][data]': ['8'], 'columns[8][name]': '', 'columns[8][searchable]': ['true'], 'columns[8][orderable]': ['false'], 'columns[8][search][value]': '', 'columns[8][search][regex]': ['false'], 'columns[9][data]': ['9'], 'columns[9][name]': '', 'columns[9][searchable]': ['true'], 'columns[9][orderable]': ['false'], 'columns[9][search][value]': '', 'columns[9][search][regex]': ['false'], 'columns[10][data]': ['10'], 'columns[10][name]': '', 'columns[10][searchable]': ['true'], 'columns[10][orderable]': ['false'], 'columns[10][search][value]': '', 'columns[10][search][regex]': ['false'], 'columns[11][data]': ['11'], 'columns[11][name]': '', 'columns[11][searchable]': ['false'], 'columns[11][orderable]': ['false'], 'columns[11][search][value]': '', 'columns[11][search][regex]': ['false'], 'order[0][column]': ['11'], 'order[0][dir]': ['asc'], 'start': ['0'], 'length': ['1994'], 'search[value]': '', 'search[regex]': ['false']} headers = { "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8", "Accept" : "application/json, text/javascript, */*; q=0.01", "Accept-Encoding" : "gzip, deflate, br", "User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:60.0) Gecko/20100101 Firefox/60.0"} response = session.post(url, headers=headers, data=formdata).json() # Converts json file. company_data = response['data'] company_dict = {} # Empty dictionary created. for company in company_data: company_dict[company[0]] = { 'Rank' : company[0], 'Name' : company[1], # Grabs relevant data for every company from 'City' : company[4], # json file & adds it to our previously 'State' : company[5], # created dictionary. 'Employees' : company[8], 'Growth (%)' : company[9], 'Accelerator/Investor' : company[10], 'Website' : company[2], 'LinkedIn' : company[3]} return company_dict # Returns dictionary that we can now write to CSV. def write_to_csv(): """ 1) Calls 'create_dictionary()' to return business data dictionary. 2) Writes returned dictionary into a CSV file named '2018 SAAS 1000.csv'. """ dictionary = create_dictionary() # Calls 'create_dictionary()' to return business data. with open('2018 SAAS 1000.csv', 'w') as fp: writer = csv.DictWriter(fp, fieldnames=['Rank', 'Name', 'City', 'State', 'Employees', 'Growth (%)', 'Accelerator/Investor', 'Website', 'LinkedIn']) writer.writeheader() for value in dictionary.values(): writer.writerow((value)) print("\nData exported to CSV.\n") write_to_csv() # Finally, we call the write_to_csv() # function which scrapes the data, # then writes it to a CSV.
b294f16ad7447bb7e6c0649b334c761281090472
[ "Markdown", "Python" ]
2
Markdown
LukeHoweth/SaasMag
4bcc3dad3ed2bab5d1508da19703b3ab5f4302b4
5ae023a4f6360c63cf86d967a1a851f4a3e5bd6f
refs/heads/master
<file_sep>package slash_test import ( "net/http" "github.com/nlopes/slack" "os" "encoding/json" "google.golang.org/appengine" "strings" "log" "io/ioutil" "google.golang.org/appengine/urlfetch" ) type Search struct { Key string EngineId string Type string Count string } type Result struct { Items []struct { Link string `json:"link"` } `json:"items"` } func Init() { http.HandleFunc("/cmd", handler) appengine.Main() } func handler(w http.ResponseWriter, r *http.Request) { s, err := slack.SlashCommandParse(r) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } if !s.ValidateToken(os.Getenv("VERIFICATION_TOKEN")) { w.WriteHeader(http.StatusUnauthorized) return } switch s.Command { case "/image": response := &slack.Msg{Text: SearchImage(r, s.Text), ResponseType: "in_channel"} image, err := json.Marshal(response) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(image) default: w.WriteHeader(http.StatusInternalServerError) return } } func SearchImage(r *http.Request, word string) string { baseUrl := "https://www.googleapis.com/customsearch/v1" s := Search{os.Getenv("CUSTOM_SEARCH_KEY"), os.Getenv("CUSTOM_SEARCH_ENGINE_ID"), "image", "1"} word = strings.TrimSpace(word) url := baseUrl + "?key=" + s.Key + "&cx=" + s.EngineId + "&searchType=" + s.Type + "&num=" + s.Count + "&q=" + word return ParseJson(r, url) } func ParseJson(r *http.Request, url string) string { var imageUrl = "not search image" ctx := appengine.NewContext(r) httpClient := urlfetch.Client(ctx) response, err := httpClient.Get(url) if err != nil { log.Fatal(ctx, "html: %v", err) } if response != nil { defer response.Body.Close() } body, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) } jsonBytes := ([]byte)(body) data := new(Result) if err := json.Unmarshal(jsonBytes, data); err != nil { log.Println("json error:", err) } if data.Items != nil { imageUrl = data.Items[0].Link } return imageUrl }
a9e2542e79554476d71278dafba4639c93d3a7e4
[ "Go" ]
1
Go
JinOketani/slash_test
1ba58e64367b17e7daae1725d7e3ae6308543921
4c9eb4691d68f52a9bd91f1715550de6628a68b4