branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>mato75/bitchin-timers2<file_sep>/platforms/ios/www/js/timers/helpers.js 'use strict'; angular.module('ParseTime.Module', ['Constants.Module']) .factory('ParseTime',['HOURS', 'MINUTES', 'SECONDS', function (HOURS, MINUTES, SECONDS) { return { hmsToMsOnly: function (str) { var p = str.split(':'), s = 0, m = 1; while (p.length > 0) { s += m * parseInt(p.pop(), 10); m *= 60; } return s * 1000; }, timersFormat: function (time) { var sec = 0, min = 0, hour = 0; if (time >= HOURS) { hour = Math.floor(time / HOURS); min = Math.floor((time % HOURS) / MINUTES); sec = ((time % HOURS) % MINUTES) / SECONDS; return hour + ':' + min + ':' + sec.toFixed(2); } if (time >= MINUTES) { min = Math.floor(time / MINUTES); sec = (time % MINUTES) / SECONDS; return min + ':' + sec.toFixed(2); } sec = (time / SECONDS) % SECONDS; return sec.toFixed(2); }, timersFormatSeconds: function (time) { var sec = 0; sec = (time / SECONDS) % SECONDS; return parseInt(sec); } } }]) ; <file_sep>/www/js/user/setuser.js 'use strict'; angular.module('User.Module') .factory('UpdateUser', [ '$http', 'HTTP_URL', function ($http, HTTP_URL) { return { put: function (mail, info) { return $http({ method: 'POST', url: HTTP_URL + '/update/account', params: { mail: mail, info: info } }); } } } ]) .controller('SetUserCtrl', [ '$scope', '$cookieStore', 'UserInfo', 'UpdateUser', function ($scope, $cookieStore, UserInfo, UpdateUser) { var alerts = []; $scope.alerts = alerts; $scope.user = UserInfo; $scope.updateUser = function () { var newInfo = { 'password': <PASSWORD>, 'name': UserInfo.name }; if (UserInfo.password === null) newInfo = { 'name': UserInfo.name }; UpdateUser.put(UserInfo.mail, newInfo) .success(function (data, status, headers, config) { $scope.closeAlert(); UserInfo.clear(); UserInfo.user = data.user; if (UserInfo.password !== null) { $cookieStore.remove('user'); $cookieStore.put('user', { mail: data.auth.mail, password: <PASSWORD> }); } alerts.push({ msg: 'Yes! Your account was modified.', type: 'success' }); }).error(function (err) { if (err['error-tag'] === 'error-update-account') { alerts.push({ msg: 'Sorry! Something went terribly wrong. Try again!', type: 'danger' }); return; } alerts.push({ msg: err.error.message, type: 'danger' }); }); }; $scope.closeAlert = function (index) { index = index || 0; alerts.splice(index, 1); } } ]) .factory('DeleteUser', [ '$http', 'HTTP_URL', function ($http, HTTP_URL) { return { delete: function (mail) { return $http({ method: 'DELETE', url: HTTP_URL + '/update/account', params: { mail: mail } }); } } } ]) .controller('DeleteUserCtrl', [ '$scope', '$cookieStore', 'DeleteUser', function ($scope, $cookieStore, DeleteUser) { var alerts = []; $scope.alerts = alerts; $scope.dismissModal = function () { $scope.$dismiss(); }; $scope.deleteUser = function () { DeleteUser.delete($cookieStore.get('user').mail) .success(function (data, status, headers, config) { $scope.closeAlert(); UserInfo.clear(); $cookieStore.remove('user'); $scope.$close(); $scope.changeModules(); $scope.$broadcast('nextModule', 'login'); }).error(function (err) { if (err['error-tag'] === 'error-removing-user') { alerts.push({ msg: 'Sorry! Something went terribly wrong. Try again!', type: 'danger' }); return; } alerts.push({ msg: err.error.message, type: 'danger' }); }); }; $scope.closeAlert = function (index) { index = index || 0; alerts.splice(index, 1); } } ]) ; <file_sep>/www/js/timers/countdown.js 'use strict'; angular.module('Timers.Module') .service('Countdown', function () { var countdown = { timer: null, reps: null, action: 'Start' }; return { get countdown() { return countdown; }, get timer() { return countdown.timer; }, set timer(t) { countdown.timer = t; }, get reps() { return countdown.reps; }, set reps(t) { countdown.reps = t; }, get action() { return countdown.action; }, set action(t) { countdown.action = t; }, clear: function () { this.timer = null; this.reps = null; this.action = 'Start'; } }; }) .factory('CountdownTimer', [ '$rootScope', '$timeout', 'TIMERS_DELAY', 'ParseTime', function (rootScope, timeout, TIMERS_DELAY, ParseTime) { var before = null, now = null, timer = null; var countdown = { time: 30000, def: 30000 }; return { set countdown(def) { countdown.def = def; }, get countdown() { return countdown; }, get time() { return ParseTime.timersFormat(countdown.time); }, get def() { return countdown.def; }, set def(d) { countdown.def = d; }, increase: function () { countdown.def += 30000; countdown.time = this.def; }, decrease: function () { countdown.def -= 30000; countdown.time = this.def; }, start: function () { var that = this; //that.stop(); before = Date.now(); rootScope.$emit('countdown-start'); (function interval() { now = Date.now(); var elapsed = now - before; countdown.time -= elapsed > TIMERS_DELAY ? elapsed : TIMERS_DELAY; before = Date.now(); if (countdown.time <= 0) { that.stop(); countdown.time = 0; return; } rootScope.$emit('countdown-change'); timer = timeout(interval, TIMERS_DELAY); })(); }, stop: function () { var that = this; timeout.cancel(timer); timer = null; rootScope.$emit('countdown-stop'); }, clear: function () { countdown.time = this.def; before = null; now = null; if (timer !== null) { timeout.cancel(timer); timer = null; } } }; } ]) .controller('CountdownCtrl', [ '$rootScope', '$scope', 'Countdown', 'CountdownTimer', 'Repetitions', 'WaitToStart', function ($rootScope, $scope, Countdown, CountdownTimer, Repetitions, WaitToStart) { function create() { CountdownTimer.clear(); Countdown.timer = CountdownTimer; } function doReps() { Repetitions.clear(); Countdown.repetitions = Repetitions; } $scope.Countdown = Countdown; $scope.WaitToStart = WaitToStart; $scope.toStartWorkout = false; Countdown.action = 'Start'; $scope.create = function () { create(); doReps(); }; $scope.Countdown.increase = function () { if (Countdown.timer === null) create(); CountdownTimer.increase(); }; $scope.Countdown.decrease = function () { if (Countdown.timer === null) create(); if (CountdownTimer.def <= 30000) return; CountdownTimer.decrease(); }; $scope.Countdown.doIt = function (action) { if (action.toLowerCase() === 'start') { WaitToStart.clear(); WaitToStart.start(); } if (action.toLowerCase() === 'stop') { if (Countdown.timer !== null) CountdownTimer.stop(); } }; $scope.Countdown.increaseReps = function () { if (Countdown.repetitions === null) doReps(); Repetitions.increase(); }; $rootScope.$on('countdown-stop', function (event) { event.stopPropagation(); Countdown.action = 'Start'; }, true); $rootScope.$on('countdown-start', function (event) { event.stopPropagation(); $scope.toStartWorkout = false; Countdown.action = 'Stop'; }, true); $rootScope.$on('wait-stop', function (event) { event.stopPropagation(); $scope.create(); CountdownTimer.start(); Countdown.action = 'Stop'; }, true); $rootScope.$on('wait-start', function (event) { event.stopPropagation(); $scope.create(); angular.element(document.querySelector('.timer-countdownStartAudio'))[0].play(); $scope.toStartWorkout = true; }, true); } ]) ; <file_sep>/www/js/user/connect.js 'use strict'; angular.module('User.Module') .controller('ConnectCtrl', [ '$scope', 'HTTP_URL', 'TWITTER', 'FACEBOOK', function ($scope, HTTP_URL, TWITTER, FACEBOOK) { $scope.urls = { twitter: HTTP_URL + TWITTER, facebook: HTTP_URL + FACEBOOK }; } ]) ; <file_sep>/www/js/timers/interval.js 'use strict'; angular.module('Timers.Module') .service('Interval', function () { var interval = { "action": "Start", "exercise": null }; return { get interval() { return interval; }, get exercise() { return interval.exercise; }, set exercise(t) { interval.exercise = t; }, get action() { return interval.action; }, set action(t) { interval.action = t; }, clear: function () { this.exercise = null; this.action = "Start"; } }; }) .factory('IntervalTimer', [ '$rootScope', '$timeout', 'TIMERS_DELAY', 'ParseTime', 'Repetitions', function (rootScope, timeout, TIMERS_DELAY, ParseTime, Repetitions) { var before = null, now = null, timer = null; var interval = { time: 30000, def: 30000, round: 0, repetitions: Repetitions, todo: null, total: 0 }; return { set interval(def) { interval.def = def; }, get interval() { return interval; }, set time(t) { interval.time = t; }, get time() { return ParseTime.timersFormat(interval.time); }, get def() { return interval.def; }, set def(d) { interval.def = d; }, set round(r) { interval.round = r; }, get round() { return interval.round; }, set totalReps(t) { interval.total = t; }, get totalReps() { return interval.total; }, set todoRounds(t) { interval.todo = t; }, get todoRounds() { interval.todo; }, get reps() { return interval.repetitions.reps; }, increase: function () { interval.def += 30000; interval.time = this.def; }, decrease: function () { interval.def -= 30000; interval.time = this.def; }, addReps: function () { interval.repetitions.increase(); }, clearReps: function () { interval.repetitions.clear(); }, roundComplete: function () { if (interval.todo !== null && interval.todo === 0) { this.stop(); return; } interval.todo--; interval.round++; }, increaseTotal: function () { interval.total += interval.repetitions.reps; }, start: function () { var that = this; that.stop(); if (interval.todo !== null && interval.todo === 0) { return; } before = Date.now(); rootScope.$emit('interval-start'); that.roundComplete(); (function delay() { now = Date.now(); var elapsed = now - before; interval.time -= elapsed > TIMERS_DELAY ? elapsed : TIMERS_DELAY; before = Date.now(); if (interval.time <= 0) { that.increaseTotal(); that.reset(); that.start(); return; } rootScope.$emit('interval-change'); timer = timeout(delay, TIMERS_DELAY); })(); }, stop: function () { var that = this; timeout.cancel(timer); timer = null; rootScope.$emit('interval-stop'); }, reset: function () { interval.time = this.def; before = null; now = null; this.clearReps(); if (timer !== null) { timeout.cancel(timer); timer = null; } }, clear: function () { this.reset(); this.totalReps = 0; this.round = 0; } }; } ]) .controller('IntervalCtrl', [ '$rootScope', '$scope', 'Interval', 'IntervalTimer', 'WaitToStart', function ($rootScope, $scope, Interval, IntervalTimer, WaitToStart) { $scope.Interval = Interval; $scope.WaitToStart = WaitToStart; $scope.toStartWorkout = false; Interval.action = "Start"; function create() { IntervalTimer.clear(); Interval.exercise = IntervalTimer; } $scope.create = function () { create(); }; $scope.Interval.increase = function () { if (Interval.exercise === null) create(); IntervalTimer.increase(); }; $scope.Interval.decrease = function () { if (Interval.exercise === null) create(); if (IntervalTimer.def === 30000) return; IntervalTimer.decrease(); }; $scope.Interval.doIt = function (action) { if (action.toLowerCase() === 'start') { WaitToStart.clear(); WaitToStart.start(); } if (action.toLowerCase() === 'stop') { if (Interval.exercise !== null) IntervalTimer.stop(); } }; $scope.Interval.increaseReps = function () { if (Interval.exercise === null) create(); IntervalTimer.addReps(); }; $rootScope.$on("interval-stop", function (event) { event.stopPropagation(); Interval.action = "Start"; }, true); $rootScope.$on("interval-start", function (event) { event.stopPropagation(); $scope.toStartWorkout = false; Interval.action = "Stop"; }, true); $rootScope.$on('wait-stop', function (event) { event.stopPropagation(); $scope.create(); IntervalTimer.start(); Interval.action = 'Stop'; }, true); $rootScope.$on('wait-start', function (event) { event.stopPropagation(); $scope.create(); angular.element(document.querySelector('.timer-countdownStartAudio'))[0].play(); $scope.toStartWorkout = true; }, true); } ]) ; <file_sep>/www/js/user/setdetails.js 'use strict'; angular.module('User.Module') .controller('SetUserDetailsCtrl', [ '$scope', '$cookieStore', 'UserInfo', 'UpdateUser', function ($scope, $cookieStore, UserInfo, UpdateUser) { var alerts = []; $scope.alerts = alerts; $scope.user = UserInfo; $scope.updateUser = function () { UpdateUser.put(UserInfo.mail, { 'born': UserInfo.born, 'box': UserInfo.box, 'location': UserInfo.location, 'weight': UserInfo.weight, 'height': UserInfo.height, 'wunit': UserInfo.wunit, 'hunit': UserInfo.hunit }) .success(function (data, status, headers, config) { $scope.closeAlert(); UserInfo.clear(); UserInfo.user = data.user; alerts.push({ msg: 'Yes! Your account details was modified.', type: 'success' }); }).error(function (err) { if (err['error-tag'] === 'error-update-account') { alerts.push({ msg: 'Sorry! Something went terribly wrong. Try again!', type: 'danger' }); return; } alerts.push({ msg: err.error.message, type: 'danger' }); }); }; $scope.closeAlert = function (index) { index = index || 0; alerts.splice(index, 1); }; $scope.openDatepicker = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; } ]) .controller('HeightUnitCtrl', [ '$scope', 'UserInfo', 'HEIGHT_UNITS', function ($scope, UserInfo, HEIGHT_UNITS) { $scope.heightUnits = HEIGHT_UNITS; $scope.ok = function (unit) { $scope.$close(); UserInfo.hunit = unit.name; }; } ]) .controller('WeightUnitCtrl', [ '$scope', 'UserInfo', 'WEIGHT_UNITS', function ($scope, UserInfo, WEIGHT_UNITS) { $scope.weightUnits = WEIGHT_UNITS; $scope.ok = function (unit) { $scope.$close(); UserInfo.wunit = unit.name; }; } ]) ; <file_sep>/www/js/user/details.js 'use strict'; angular.module('User.Module', [ 'Constants.Module' ]) .service('UserInfo', function () { var user = { name: null, mail: null, password: null, // imgUrl: null, born: null, box: null, location: null, // rss: [], // quotes: [], weight: null, height: null, wunit: null, hunit: null, activities: [] }; return { set user(u) { if ('name' in u) this.name = u.name; if ('password' in u) this.password = <PASSWORD>; if ('mail' in u) this.mail = u.mail; if ('born' in u) this.born = u.born; if ('box' in u) this.box = u.box; if ('location' in u) this.location = u.location; if ('weight' in u) this.weight = u.weight; if ('height' in u) this.height = u.height; if ('wunit' in u) this.wunit = u.wunit; if ('hunit' in u) this.hunit = u.hunit; }, get user() { return user; }, set name(name) { user.name = name; }, get name() { return user.name; }, set password(w) { user.password = w; }, get password() { return user.password; }, set mail(mail) { user.mail = mail; }, get mail() { return user.mail; }, // set imgUrl(n) { // user.imgUrl = n; // }, // get imgUrl() { // return user.imgUrl; // }, set born(r) { user.born = new Date(r); }, get born() { return user.born; }, set box(t) { user.box = t; }, get box() { return user.box; }, set location(e) { user.location = e; }, get location() { return user.location; }, set weight(e) { user.weight = e; }, get weight() { return user.weight; }, set height(d) { user.height = d; }, get height() { return user.height; }, set wunit(t) { user.wunit = t; }, get wunit() { return user.wunit; }, set hunit(t) { user.hunit = t; }, get hunit() { return user.hunit; }, set activities(t) { user.activities = t; }, get activities() { var act = []; var cact = user.activities; var groups = {}; for (var i in cact) { var item = cact[i]; var name = item.name; if (groups[name]) { groups[name].push(parseInt(item.completed)); } else { groups[name] = [parseInt(item.completed)]; } }; for (var i in groups) { var key = i; var group = groups[i]; group.sort(function (a, b) { if (a > b) return -1; if (a < b) return 1; return 0; }); } cact.forEach(function (i, item) { item["pb"] = groups[item.name][0] == item.completed; }); var i = cact.length - 1; for (i; i >= 0; i--) { act.push(cact[i]) } return act; }, clear: function () { this.name = null; this.password = <PASSWORD>; this.mail = null; this.born = []; this.box = null; this.location = null; this.weight = null; this.height = null; this.wunit = null; this.hunit = null; this.activities = []; } }; }) .factory('GetUser', [ '$http', 'HTTP_URL', function ($http, HTTP_URL) { return { get: function (mail, password) { return $http({ method: 'GET', url: HTTP_URL + '/user', params: { "mail": mail, "password": <PASSWORD> } }) } } } ]) .controller('DetailsCtrl', [ '$scope', '$cookieStore', 'UserInfo', 'GetUser', function ($scope, $cookieStore, UserInfo, GetUser) { $scope.user = UserInfo; } ]) .controller('ActionModalCtrl', [ '$rootScope', '$scope', 'ACTIONS', function ($rootScope, $scope, ACTIONS) { $scope.actions = ACTIONS; $scope.ok = function (action) { $scope.$close(); $rootScope.$broadcast('nextModule', action); }; } ]) ; <file_sep>/www/js/constants.js angular.module('Constants.Module', []) .constant('LOGIN_MODULES', ['login']) .constant('MAIN_MODULES',['details', 'timers']) .constant("NAVIGATION", { // login 'login': { id: 'login', 'title': 'Login', isSubTab: false, nav: 'login/' }, // url: 'views/login/login.html --> ng-include' 'signin': { id: 'signin', 'title': 'Sign In', isSubTab: true, nav: 'login/signin' }, 'signup': { id: 'signup', 'title': 'Sign Up', isSubTab: true, nav: 'login/signup' }, // user 'details': { id: 'details', 'title': 'Info', isSubTab: false, nav: 'user/details' }, 'setuser': { id: 'setuser', 'title': 'Modify Account', isSubTab: true, nav: 'user/setuser' }, 'setdetails': { id: 'setdetails', 'title': 'Modify Details', isSubTab: true, nav: 'user/setdetails' }, 'connect': { id: 'connect', 'title': 'Connect With', isSubTab: true, nav: 'user/connect' }, // timers 'timers': { id:'timers', 'title': 'Timers', isSubTab: false, nav: 'timers/' }, 'stopwatch': { id: 'stopwatch', 'title': 'Stopwatch', isSubTab: true, nav: 'timers/stopwatch' }, 'countdown': { id: 'countdown', 'title': 'Countdown', isSubTab: true, nav: 'timers/countdown' }, 'interval': { id: 'interval', 'title': 'Interval', isSubTab: true, nav: 'timers/interval' }, 'tabata': { id: 'tabata', 'title': 'Tabata', isSubTab: true, nav: 'timers/tabata' }, 'appInfo': { id: 'appInfo', 'title': 'Info', isSubTab: true, nav: 'info' } }) .constant('ACTIONS', [ { id: "activity", title: "Activity", icon: "fa-play" }, // { name: "records", title: "Records", icon: "icon-trophy" }, { id: "setuser", title: "Account", icon: "fa-check" }, { id: "setdetails", title: "Details", icon: "fa-info" }, { id: "connect", title: "Social", icon: "fa-globe" }, { id: "goodbye", title: "Goodbye", icon: "fa-power-off" } ]) .constant('WEIGHT_UNITS', [ { name: "kg", title: "kg", icon: "fa-anchor" }, { name: "lbs", title: "lbs", icon: "fa-beer" } ]) .constant('HEIGHT_UNITS', [ { name: "cm", title: "cm", icon: "fa-ellipsis-v" }, { name: "ft", title: "ft", icon: "fa-filter" } ]) .constant('HTTP_URL', 'http://192.168.1.22:3000') .constant('TWITTER', '/oauth/twitter') .constant('FACEBOOK', '/oauth/facebook') .constant('TIMERS', [ { id: "stopwatch", title: "Stopwatch", icon: "fa-clock-o" }, { id: "countdown", title: "Countdown", icon: "fa-tachometer" }, { id: "interval", title: "Interval", icon: "fa-signal" }, { id: "tabata", title: "Tabata", icon: "fa-rocket" } ]) .constant('TIMERS_DELAY', 10) .constant('SECONDS', 1000) .constant('HOURS', 3600000) .constant('MINUTES', 60000) ; <file_sep>/www/js/app.js 'use strict'; angular.module('BitchinApp', [ 'ngRoute', 'ngAnimate', 'ngTouch', 'ngCookies', 'ngResource', 'ui.bootstrap', 'Constants.Module', 'User.Module', 'Timers.Module' ]) .controller('AppCtrl', [ '$scope', '$location', '$rootScope', '$window', '$cookieStore','$modal', 'MAIN_MODULES', 'LOGIN_MODULES', 'NAVIGATION', 'UserInfo', 'GetUser', function ( $scope, $location, $rootScope, $window, $cookieStore, $modal, MAIN_MODULES, LOGIN_MODULES, NAVIGATION, UserInfo, GetUser) { angular.element(document.querySelector('.timer-countdownStartAudio'))[0].play(); angular.element(document.querySelector('.timer-countdownStartAudio'))[0].pause(); var module = NAVIGATION.login; var modules = LOGIN_MODULES; var stack = [module.id]; // $cookieStore.remove('user'); $scope.credentialsOk = function () { var credentials = $cookieStore.get('user'); if (credentials === undefined) { modules = LOGIN_MODULES; return; } GetUser.get(credentials.mail, credentials.password) .success(function (data, status, headers, config) { UserInfo.user = data.user; modules = MAIN_MODULES; module = NAVIGATION.details; stack = [module.id]; }) .error(function (err) { if (err['error-tag'] === 'user-is-passed') UserInfo.clear(); modules = LOGIN_MODULES; module = NAVIGATION.login stack = [module.id]; }) .then(function () { $scope.$emit('moduleSelected', module.id, null); }); }; $scope.changeModules = function () { if ($cookieStore.get('user') !== undefined) { modules = MAIN_MODULES; return; } modules = LOGIN_MODULES; }; $scope.credentialsOk(); $scope.slideAnimation = 'slide-right'; $scope.next = function (sModule) { $scope.slideAnimation = 'slide-right'; var oModule = module.id; if (sModule === undefined) { var current = modules.indexOf(module.id); var nModule = current === modules.length - 1 ? modules[0] : modules[current + 1]; stack = [nModule]; $scope.$emit('moduleSelected', nModule, oModule); return; } if (modules.indexOf(sModule) === -1) stack.push(sModule); else stack = [sModule]; $scope.$emit('moduleSelected', sModule, oModule); }; $scope.previous = function (sModule) { $scope.slideAnimation = 'slide-left'; var oModule = module.id; if (sModule === undefined) { var nModule = null; if (stack.length > 1) { stack.pop(); nModule = stack[stack.length - 1]; $scope.$emit('moduleSelected', nModule, oModule); return; } var current = modules.indexOf(module.id); nModule = current === 0 ? modules[modules.length - 1] : modules[current - 1]; stack = [nModule]; $scope.$emit('moduleSelected', nModule, oModule); return; } if (modules.indexOf(sModule) === -1) stack.pop(); else stack = [sModule]; $scope.$emit('moduleSelected', sModule, oModule); }; $rootScope.$on('nextModule', function (e, module) { // e.stopPropagation(); if (!module) { return; } $scope.next(module); }); $rootScope.$on('previousModule', function (e, module) { // e.stopPropagation(); if (!module) { $scope.previous(); return; } $scope.previous(module); }); $scope.$on('moduleSelected', function (e, nModule, oModule) { e.stopPropagation(); if (!nModule) { console.log('New module not defined, so there will be no change in navigation'); return; } if (nModule === oModule) { console.log('New module the same as old module, so there will be no change in navigation'); return; } module = NAVIGATION[nModule]; $scope.module = module; $location.path(module.nav); }, true); $scope.openModal = function (url) { $modal.open({ templateUrl: url }); }; } ]) .config(function ($routeProvider, $locationProvider) { $routeProvider .when('/login', { templateUrl: 'views/login/login.html' }) .when('/login/signup', { templateUrl: 'views/login/signup.html' }) .when('/login/signin', { templateUrl: 'views/login/signin.html' }) .when('/user/details', { templateUrl: 'views/user/details.html' }) .when('/user/setuser', { templateUrl: 'views/user/setuser.html' }) .when('/user/setdetails', { templateUrl: 'views/user/setdetails.html' }) .when('/user/connect', { templateUrl: 'views/user/connect.html' }) .when('/timers', { templateUrl: 'views/timers/timers.html' }) .when('/timers/stopwatch', { templateUrl: 'views/timers/stopwatch.html' }) .when('/timers/countdown', { templateUrl: 'views/timers/countdown.html' }) .when('/timers/tabata', { templateUrl: 'views/timers/tabata.html' }) .when('/timers/interval', { templateUrl: 'views/timers/interval.html' }) .otherwise({ redirectTo: '/login' }); // $locationProvider.html5Mode(true); }) .run(function ($rootScope) { $rootScope.$on('$routeChangeSuccess', function (e, current, previous) {}); }) // .directive("ngTap", function () { // return function ($scope, $element, $attributes) { // var tapped; // tapped = false; // $element.bind("click", function () { // if (!tapped) { // return $scope.$apply($attributes["ngTap"]); // } // }); // $element.bind("touchstart", function (event) { // return tapped = true; // }); // $element.bind("touchmove", function (event) { // tapped = false; // return event.stopImmediatePropagation(); // }); // return $element.bind("touchend", function () { // if (tapped) { // return $scope.$apply($attributes["ngTap"]); // } // }); // }; // }) ; <file_sep>/www/js/login/signin.js 'use strict'; angular.module('User.Module') .factory('SignIn', [ '$http', 'HTTP_URL', function ($http, HTTP_URL) { return { post: function (mail, password) { return $http({ method: 'POST', url: HTTP_URL + '/oauth/sing/in', params: { mail: mail, password: <PASSWORD> } }) } } } ]) .controller('SignInCtrl', [ '$rootScope', '$scope', '$cookieStore', 'UserInfo', 'SignIn', function ($rootScope, $scope, $cookieStore, UserInfo, SignIn) { var alerts = []; $scope.alerts = alerts; $scope.user = UserInfo; $scope.signIn = function () { $scope.closeAlert(); SignIn.post(UserInfo.mail, UserInfo.password) .success(function (data, status, headers, config) { UserInfo.clear(); UserInfo.user = data.user; $cookieStore.remove('user'); $cookieStore.put('user', { mail: data.auth.mail, password: <PASSWORD> }); $scope.changeModules(); $rootScope.$broadcast('nextModule', 'details'); // $location.url('/'); //$scope.screen = 'validate-mail'; }).error(function (err) { if (err['error-tag'] === 'wrong-pass-or-user') { alerts.push({ msg: 'Oops! You entered and invalid username or password. Try again!', type: 'danger' }); return; } alerts.push({ msg: err.error.message, type: 'danger' }); }); } $scope.closeAlert = function (index) { index = index || 0; alerts.splice(index, 1); }; } ]) .factory('ForgotPassword', [ '$http', 'HTTP_URL', function ($http, HTTP_URL) { return { post: function (mail) { return $http({ method: 'POST', url: HTTP_URL + '/forgot/password', params: { mail: mail } }) } } } ]) .controller('ForgotPasswordCtrl', [ '$scope', '$timeout', 'ForgotPassword', function ($scope, $timeout, ForgotPassword) { var alerts = []; $scope.alerts = alerts; $scope.forgotPassword = function (mail) { $scope.closeAlert(); ForgotPassword.post(mail) .success(function (data, status, headers, config) { alerts.push({ msg: 'Password was send to mail address', type: 'success' }); $timeout(function () { $scope.$close(); }, 300); }).error(function (err) { alerts.push({ msg: 'Oops! You entered and invalid mail address. Try again!', type: 'danger' }); }); }; $scope.closeAlert = function (index) { index = index || 0; alerts.splice(index, 1); }; } ]) ; <file_sep>/www/js/login/signup.js 'use strict'; angular.module('User.Module') .factory('SignUp', [ '$http', 'HTTP_URL', function ($http, HTTP_URL) { return { post: function (user) { return $http({ method: 'POST', url: HTTP_URL + '/oauth/sing/up', params: { user: user, remember: true } }) } } } ]) .controller('SignUpCtrl', [ '$rootScope', '$scope', '$cookieStore', 'UserInfo', 'SignUp', function ($rootScope, $scope, $cookieStore, UserInfo, SignUp) { var alerts = []; $scope.alerts = alerts; $scope.user = UserInfo; $scope.signUp = function () { $scope.closeAlert(); SignUp.post(UserInfo.user) .success(function (data, status, headers, config) { UserInfo.clear(); UserInfo.user = data.user; $cookieStore.remove('user'); $cookieStore.put('user', { mail: data.auth.mail, password: <PASSWORD> }); $scope.changeModules(); $rootScope.$broadcast('nextModule', 'details'); // $location.url('/'); //$scope.screen = 'validate-mail'; }).error(function (err) { if (err['error-tag'] === 'error-add') { alerts.push({ msg: 'Oh snap! Change a few things up and try submitting again.', type: 'danger' }); return; } alerts.push({ msg: err.error.message, type: 'danger' }); }); } $scope.closeAlert = function (index) { index = index || 0; alerts.splice(index, 1); }; } ]) ; <file_sep>/platforms/ios/www/js/app.js 'use strict'; angular.module('BitchinApp', [ 'ngRoute', 'ngAnimate', 'ngTouch', 'ui.bootstrap', 'Constants.Module', 'Timers.Module' ]) .controller('AppCtrl', [ '$scope', '$location', '$rootScope', '$window', 'MAIN_MODULES', 'NAVIGATION', function ($scope, $location, $rootScope, $window, MAIN_MODULES, NAVIGATION) { angular.element(document.querySelector('.timer-countdownStartAudio'))[0].play(); angular.element(document.querySelector('.timer-countdownStartAudio'))[0].pause(); var module = NAVIGATION.timers; var stack = [module.id]; $scope.slideAnimation = 'slide-right'; $scope.next = function (sModule) { $scope.slideAnimation = 'slide-right'; var oModule = module.id; if (sModule === undefined) { var current = MAIN_MODULES.indexOf(module.id); var nModule = current === MAIN_MODULES.length - 1 ? MAIN_MODULES[0] : MAIN_MODULES[current + 1]; stack = [nModule]; $scope.$emit('moduleSelected', nModule, oModule); return; } if (MAIN_MODULES.indexOf(sModule) === -1) stack.push(sModule); else stack = [sModule]; $scope.$emit('moduleSelected', sModule, oModule); }; $scope.previous = function (sModule) { $scope.slideAnimation = 'slide-left'; var oModule = module.id; if (sModule === undefined) { var nModule = null; if (stack.length > 1) { stack.pop(); nModule = stack[stack.length - 1]; $scope.$emit('moduleSelected', nModule, oModule); return; } var current = MAIN_MODULES.indexOf(module.id); nModule = current === 0 ? MAIN_MODULES[MAIN_MODULES.length - 1] : MAIN_MODULES[current - 1]; stack = [nModule]; $scope.$emit('moduleSelected', nModule, oModule); return; } if (MAIN_MODULES.indexOf(sModule) === -1) stack.pop(); else stack = [sModule]; $scope.$emit('moduleSelected', sModule, oModule); }; $scope.$on('moduleSelected', function (e, nModule, oModule) { e.stopPropagation(); if (!nModule) { console.log('New module not defined, so there will be no change in navigation'); return; } if (nModule === oModule) { console.log('New module the same as old module, so there will be no change in navigation'); return; } module = NAVIGATION[nModule]; $scope.module = module; $location.path(module.nav); }, true); $scope.$emit('moduleSelected', 'timers', null); } ]) .controller('AppInfoCtrl', [ '$scope', '$location', '$rootScope', '$window', 'MAIN_MODULES', 'NAVIGATION', function ($scope, $location, $rootScope, $window, MAIN_MODULES, NAVIGATION) { } ]) .config(function ($routeProvider, $locationProvider) { $routeProvider .when('/timers', { templateUrl: 'views/timers/timers.html' }) .when('/info', { templateUrl: 'views/info.html' }) .when('/timers/stopwatch', { templateUrl: 'views/timers/stopwatch.html' }) .when('/timers/countdown', { templateUrl: 'views/timers/countdown.html' }) .when('/timers/tabata', { templateUrl: 'views/timers/tabata.html' }) .when('/timers/interval', { templateUrl: 'views/timers/interval.html' }) .otherwise({ redirectTo: '/timers' }); // $locationProvider.html5Mode(true); }) .run(function ($rootScope) { $rootScope.$on('$routeChangeSuccess', function (e, current, previous) {}); }) // .directive("ngTap", function () { // return function ($scope, $element, $attributes) { // var tapped; // tapped = false; // $element.bind("click", function () { // if (!tapped) { // return $scope.$apply($attributes["ngTap"]); // } // }); // $element.bind("touchstart", function (event) { // return tapped = true; // }); // $element.bind("touchmove", function (event) { // tapped = false; // return event.stopImmediatePropagation(); // }); // return $element.bind("touchend", function () { // if (tapped) { // return $scope.$apply($attributes["ngTap"]); // } // }); // }; // }) ;
cdb1cbf60e8b2c70da90fcb2aaedbb6d309b37fa
[ "JavaScript" ]
12
JavaScript
mato75/bitchin-timers2
9ec788f427377c6fac6d948303c3cb85b1507a16
0aff0e2a27c2b3fe8359f3a42753859c8d08641d
refs/heads/master
<file_sep>require "pry" def starts_with_a_vowel?(word) word.scan(/\A[aeiouAEIOU]/).length >= 1 ? true : false end def words_starting_with_un_and_ending_with_ing(text) text.scan(/un\w+ing\b/) end def words_five_letters_long(text) text.scan(/\b\w{5}\b/) end text = "hello my name is daniel the great" puts words_five_letters_long(text) def first_word_capitalized_and_ends_with_punctuation?(text) text.scan(/\A[A-Z].+[^a-zA-Z0-9]\z/).length != 0 ? true : false end def valid_phone_number?(phone) if phone.match(/[^\d\s()-]/) || phone.scan(/\d/).length != 10 false else true end end
7fd920cac8c9f34e9094b2472b70272621d69bfe
[ "Ruby" ]
1
Ruby
danpaulgo/regex-lab-v-000
6c4580a67c8fce9905edcc63683222bb123bdc7d
03504a3bbf815bab130789f56d8bb6cc54c7bef3
refs/heads/main
<file_sep>rasa~=3.3.0a1 rasa-sdk~=3.3.0 # if you change this, make sure to change the Dockerfile to match paho-mqtt==1.6.1 click==8.0.4 -r actions/requirements-actions.txt <file_sep># Jokebot - Rasa Demo Bot This is a Rasa demo bot. You can try the bot out at [https://avkana.com/jokebot](https://avkana.com/jokebot). You can ask for Geek jokes, Corny jokes. Also, Kanye, Ron Swanson, Creed, Breaking Bad, Inspiring or Trump quotes. ## ToDo - Brainy quote, `https://github.com/Hemil96/Brainyquote-API` - Github Actions pipeline - Google Assistant integration - NLU test data - Core test data - rasa validate - Support [multi-intents](https://blog.rasa.com/how-to-handle-multiple-intents-per-input-using-rasa-nlu-tensorflow-pipeline/?_ga=2.50044902.1771157212.1575170721-2034915719.1563294018) ## New Features **Oct 2022** - Upgrade to 3.0 **Jan 2021:** - GitHub actions - Build actions docker image - Creed quotes - Kanye quotes, `https://api.kanye.rest/?format=text` ## Test Curl ``` curl --location --request POST 'http://localhost:5055/webhook' \ --data-raw '{ "next_action": "action_kanye", "sender_id": "postman", "tracker": { "sender_id": "default", "slots": {}, "latest_message": {}, "latest_event_time": 1535092548.4191391, "followup_action": "action_listen", "events": [] }, "domain": { "config": {}, "intents": [], "entities": [], "slots": {} } }' ``` ``` curl --location --request POST 'http://rasa-production:5005/webhooks/rest/webhook' --header 'Content-Type: application/x-www-form-urlencoded' --data-raw '{"sender": "postman","message": "hello" }' curl --location --request POST 'http://localhost/webhooks/rest/webhook' --header 'Content-Type: application/x-www-form-urlencoded' --data-raw '{"sender": "postman","message": "hello" }' curl --location --request POST 'http://localhost:5005/webhooks/rest/webhook' --header 'Content-Type: application/x-www-form-urlencoded' --data-raw '{"sender": "postman","message": "hello" }' ```<file_sep># -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from typing import Dict, Text, Any, List, Union, Type, Optional import typing import logging import requests import json import re import csv import random # from . import otel # import tracing from rasa_sdk.events import SlotSet, AllSlotsReset, EventType from rasa_sdk.types import DomainDict from rasa_sdk import Tracker, FormValidationAction from rasa_sdk.executor import CollectingDispatcher, Action # from rasa_core.trackers import ( # DialogueStateTracker, ActionExecuted, # EventVerbosity) # from rasa_core.policies.fallback import FallbackPolicy # from rasa_core.domain import Domain from datetime import datetime, date, time, timedelta # from rasa_core.utils import AvailableEndpoints # from rasa_core.tracker_store import TrackerStore logger = logging.getLogger(__name__) vers = "vers: 0.1.3, date: Apr 27, 2022" logger.debug(vers) # otel.init_tracer("action_server") # tracer = tracing.init_tracer("action_server") def get_last_event_for( tracker, event_type: Text, action_names_to_exclude: List[Text] = None, skip: int = 0, ) -> Optional[Any]: def filter_function(e): has_instance = e if e["event"] == event_type: has_instance = e excluded = e["event"] != event_type or ( ( e["event"] == event_type and ( (e["parse_data"]["intent"]["name"] == "domicile") or (e["parse_data"]["intent"]["name"] == "customertype") ) ) ) return has_instance and not excluded filtered = filter(filter_function, reversed(tracker.events)) for i in range(skip): next(filtered, None) return next(filtered, None) def log_slots(tracker): # import copy # Log currently set slots logger.debug("tracker now has {} events".format(len(tracker.events))) prev_user_event = get_last_event_for(tracker, "user", skip=1) logger.debug( "event.text: {}, intent: {}, confidence: {}".format( prev_user_event["text"], prev_user_event["parse_data"]["intent"]["name"], prev_user_event["parse_data"]["intent"]["confidence"], ) ) feedback_answer = tracker.get_slot("feedback") logger.debug("feedback: {}".format(feedback_answer)) class ActionKanye(Action): def name(self): # define the name of the action which can then be included in training stories return "action_kanye" def run(self, dispatcher, tracker, domain): # with tracing.extract_start_span( # tracer, domain.get("headers"), self.name() # ): # r = requests.get("https://api.kanye.rest") request = json.loads(requests.get("https://api.kanye.rest").text) joke = request["quote"] # extract a joke from returned json response dispatcher.utter_message(joke) # send the message back to the user return [] class ActionChuck(Action): def name(self): # define the name of the action which can then be included in training stories return "action_chuck" def run(self, dispatcher, tracker, domain): request = json.loads(requests.get("https://api.chucknorris.io/jokes/random").text) # make an apie call joke = request["value"] # extract a joke from returned json response dispatcher.utter_message(joke) # send the message back to the user return [] class ActionRon(Action): def name(self): # define the name of the action which can then be included in training stories return "action_ron" def run(self, dispatcher, tracker, domain): # what your action should do request = json.loads( requests.get("https://ron-swanson-quotes.herokuapp.com/v2/quotes").text ) # make an apie call logger.debug("request: {}".format(request)) joke = request[0] + " - <NAME>" logger.debug("joke: {}".format(joke)) dispatcher.utter_message(joke) # send the message back to the user return [] class ActionBreakingBad(Action): def name(self): # define the name of the action which can then be included in training stories return "action_breaking" def run(self, dispatcher, tracker, domain): # what your action should do request = json.loads( requests.get("https://breaking-bad-quotes.herokuapp.com/v1/quotes").text ) # make an apie call author = request[0]["author"] quote = request[0]["quote"] message = quote + " - " + author # message = quote + ' - [' + author + '](' + permalink + ')' dispatcher.utter_message(message) # send the message back to the user return [] class ActionCorny(Action): def name(self): # define the name of the action which can then be included in training stories return "action_corny" def run(self, dispatcher, tracker, domain, **kwargs): # what your action should do request = "API Failure" author = "" try: author = "" quote = "Sorry, API Service down" req = requests.get("https://official-joke-api.appspot.com/random_joke") if req.status_code == 200: request = json.loads(req.text) # make an api call author = request["punchline"] quote = request["setup"] except requests.exceptions.RequestException as e: logger.error(f"HTTP Error: {e}") message = quote + " - " + author # message = quote + ' - [' + author + '](' + permalink + ')' dispatcher.utter_message(message) # send the message back to the user return [] class ActionInspiring(Action): def name(self): # define the name of the action which can then be included in training stories return "action_inspiring" def run(self, dispatcher, tracker, domain): # what your action should do request = requests.get("https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json") if request.status_code == 200: logger.info("request.text: {}".format(request.text)) fixed = re.sub(r'(?<!\\)\\(?!["\\/bfnrt]|u[0-9a-fA-F]{4})', r"", request.text) resp = json.loads(fixed) author = resp["quoteAuthor"] quote = resp["quoteText"] permalink = resp["quoteLink"] # message = quote + ' - ' + author + ' ' + permalink message = quote + " - [" + author + "](" + permalink + ")" else: message = "quote service error (exceeded max free quotes?), error: " + str(request.status_code) # dispatcher.utter_message(message) #send the message back to the user dispatcher.utter_message(message) # send the message back to the user return [] class ActionGeek(Action): def name(self): # define the name of the action which can then be included in training stories return "action_geek" def run(self, dispatcher, tracker, domain): # what your action should do request = json.loads(requests.get("http://quotes.stormconsultancy.co.uk/random.json").text) # make an apie call author = request["author"] quote = request["quote"] permalink = request["permalink"] # message = quote + ' - ' + author + ' ' + permalink message = quote + " - [" + author + "](" + permalink + ")" dispatcher.utter_message(message) # send the message back to the user return [] class ActionTrump(Action): def name(self): # define the name of the action which can then be included in training stories return "action_trump" def run(self, dispatcher, tracker, domain): # what your action should do request = json.loads( requests.get("https://api.whatdoestrumpthink.com/api/v1/quotes/random").text ) # make an apie call joke = request["message"] + " - <NAME>" dispatcher.utter_message(joke) # send the message back to the user return [] class ActionCreed(Action): def __init__(self): self.quotes = [ "I wanna do a cartwheel. But real casual like. Not enough to make a big deal out of it, but I know everyone saw it. One stunning, gorgeous cartwheel", "I've been involved in a number of cults, both a leader and a follower. You have more fun as a follower, but you make more money as a leader.", "Just pretend like we're talking until the cops leave.", "I already won the lottery. I was born in the US of A baby. And as backup I have a Swiss passport.", "The Taliban's the worst. Great heroin though.", "I run a small fake-ID company from my car with a laminating machine that I swiped from the Sheriff's station.", "Ryan, you told Toby that Creed has a distinct old man smell", "I know exactly what he's talking about, I sprout mung beans on a damp paper towel in my desk drawer, very nutritious but they smell like death", "Nobody steals from <NAME>atton and gets away with it. The last person to do this disappeared. His name: <NAME>.", "The only difference between me and a homeless man is this job. I will do whatever it takes to survive… like I did when I was a homeless man.", "I am not offended by homosexuality, in the sixties I made love to many, many women, often outdoors in the mud & rain. It's possible a man could've slipped in there. There'd be no way of knowing.", "You ever notice you can only ooze two things? Sexuality and pus.", ] def name(self): return "action_creed" def run(self, dispatcher, tracker, domain): n = random.randint(0, len(self.quotes) - 1) dispatcher.utter_message(self.quotes[n]) # send the message back to the user return [] class ActionDuckingTimeRange(Action): """Calculate time range ToDo: - Support additional grains (week, month, year) - Start date must be before end, when `time_from` is set, could be a later date - Fixup future dates - Handle null duckling entity, "start last weds" - Relative statements - "add a week" """ def name(self) -> Text: return "action_time_range" def _extractRange(self, duckling_time, grain): import re range = dict() range["from"] = duckling_time range["to"] = duckling_time if grain == "day": # strip timezone because of strptime limitation - https://bugs.python.org/issue22377 # 2020-02-06T00:00:00.000-08:00 # duckling_time = re.sub(r'\.000', r' ', duckling_time) # duckling_time = duckling_time[:19] logger.info(f"time w/o ms: {duckling_time}") duckling_dt = datetime.strptime(duckling_time, "%Y-%m-%dT%H:%M:%S") # dt = datetime.strptime("2020-03-07T00:00:00 -07:00", "%Y-%m-%dT%H:%M:%S %z") logger.info(f"duckling_dt: {duckling_dt}") dt_delta = duckling_dt + timedelta(hours=24) range["to"] = dt_delta.strftime("%Y-%m-%dT%H:%M:%S%z") return range def run(self, dispatcher, tracker, domain) -> List[EventType]: # existing slot values from_time = tracker.get_slot("from_time") to_time = tracker.get_slot("to_time") # duckling value duckling_time = tracker.get_slot("time") logger.info( f"duckling_time: {type(duckling_time)}, value: {duckling_time}, to_time: {to_time}, from_time: {from_time}" ) # do we have a range if type(duckling_time) is dict: from_time = tracker.get_slot("time")["from"][:19] to_time = tracker.get_slot("time")["to"][:19] else: logger.info(f"latest_message: {tracker.latest_message}") entities = tracker.latest_message.get("entities", []) logger.info(f"entities 1: {entities}") entities = {e["entity"]: e["value"] for e in entities} logger.info(f"entities: {entities}") additional_info = tracker.latest_message.get("entities", [])[0]["additional_info"] logger.info(f"grain: {additional_info['grain']}") state = tracker.current_state() intent = state["latest_message"]["intent"]["name"] logger.info(f"intent: {intent}") if intent == "time_from" and to_time: logger.info(f"setting from_time: {duckling_time[:19]}") from_time = duckling_time[:19] else: range = self._extractRange(duckling_time[:19], additional_info["grain"]) from_time = range["from"] to_time = range["to"] # entities = {e["entity"]: e["value"] for e in entities} # logger.info(f"entities 2: {entities}") # entities_json = json.dumps(entities) # date = datetime.datetime.now().strftime("%d/%m/%Y") # dispatcher.utter_message(text=entities_json) logger.info(f"from: {from_time} to: {to_time}") dispatcher.utter_message(text=f"from: {from_time}\n to: {to_time}") return [SlotSet("from_time", from_time), SlotSet("to_time", to_time)] <file_sep> | Phrase/Feature | Description | | --- | --- | | Add coins | SOL, DOT, AVAX, TRX, MATIC, NEAR, ALGO, ATOM, BTRST, APE | | Allow "Cancel", "Goodbye" | Support [AMAZON.Cancel intent](https://developer.amazon.com/docs/custom-skills/standard-built-in-intents.html#about-canceling-and-stopping) | | Improved validation | Validate slots against slot definitions (if possible) | | "Remove all" | Erase all entries from list | | Screen formatting | Improved layout | | "Abbreviated speech" | option for devices with displays, when enabled skill doesn't speak each price on systems with displays | | "Version" | Speak current version of skill | | [Slack Notifications](https://gist.github.com/vgeshel/1dba698aed9e8b39a464) | Send Usage Stats and Errors to Slack | | Integrate with Altpocket.io | get list of currencies from existing user portfolio | | Other [portfolio](https://steemit.com/bitcoin/@pedrombraz/the-best-way-to-track-your-crypto-portfolio) integrations | | <file_sep>version: "3" services: card_balance_1: image: postman/newman_alpine33 network_mode: host command: run golf_ballmoved.json -e localhost_env.json -r cli -k volumes: - .:/etc/newman <file_sep>#!/bin/sh VERS=1.1.1 REGISTRY=ghcr.io/rgstephens #REGISTRY=stephens IMAGE=jokebot #K8S_DEPLOYMENT=bandonbrawl #K8S_NAMESPACE=gstephens echo Building ${REGISTRY}/${IMAGE}:${VERS} if [ -z "$CR_PAT" ]; then echo "must set CR_PAT" exit 1 fi echo $CR_PAT | docker login ghcr.io -u USERNAME --password-stdin time docker buildx build --platform linux/amd64 --output=type=registry --tag ${REGISTRY}/${IMAGE}:${VERS} --tag ${REGISTRY}/${IMAGE}:latest . #time docker buildx build --platform linux/amd64,linux/arm64 --output=type=registry --tag ${REGISTRY}/${IMAGE}:${VERS} --tag ${REGISTRY}/${IMAGE}:latest . docker push ${REGISTRY}/${IMAGE} --all-tags #kubectl config use-context default #kubectl rollout restart deploy ${K8S_DEPLOYMENT} -n ${K8S_NAMESPACE} docker pull ${REGISTRY}/${IMAGE}:${VERS} <file_sep>[flake8] # Match the black line length (default 88), # rather than using the flake8 default of 79: max-line-length = 88 <file_sep># Dockerfile from https://hub.docker.com/r/rasa/rasa-sdk/dockerfile # Git Repo from https://github.com/RasaHQ/rasa-sdk #FROM python:3.6-slim #FROM rasa/rasa-sdk:${RASA_SDK_VERSION} FROM rasa/rasa-sdk:2.8.2 ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Americas/Los_Angeles SHELL ["/bin/bash", "-c"] #RUN echo $UID USER root #RUN ls -l /app RUN apt-get update -qq && \ apt-get install -y --no-install-recommends \ vim \ emacs \ build-essential && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* # mkdir /app RUN ls -l / USER 1001 #RUN mkdir /app WORKDIR /app # Copy as early as possible so we can cache ... COPY requirements* . RUN python -m pip install --upgrade pip USER root RUN pip install -r requirements.txt --no-cache-dir USER 1001 COPY . . #RUN pip install -e . --no-cache-dir VOLUME ["/app/actions"] EXPOSE 5055 ENTRYPOINT ["./entrypoint.sh"] CMD ["start", "--actions", "actions"]<file_sep>import requests author = "" quote = "Service down" req = requests.get("https://official-joke-api.appspot.com/random_joke") if req.status_code == 200: request = json.loads(req) # make an api call author = request["punchline"] quote = request["setup"] <file_sep>pytablewriter requests ruamel.yaml # 5.3.0 #python-socketio==">=4.4,<6" # 4.2.0 #python-engineio==">=4,<6,!=5.0.0" aiohttp==3.7.4 paho-mqtt==1.6.1 numpy<file_sep>Docker Hub [image](https://hub.docker.com/r/stephens/jokebot/tags?page=1&ordering=last_updated) Notes on building the action agent image: - Setup build using [rasa-action-server-gha](https://github.com/RasaHQ/rasa-action-server-gha) # Local Action Agent Build ```sh cd actions export CR_PAT=xxx ./build.sh #docker build -t stephens/jokebot:test . #docker tag stephens/jokebot:test stephens/jokebot:1.0.2 ``` <file_sep>FROM rasa/rasa-sdk:3.3.0 ENV TZ=Americas/Los_Angeles COPY actions /app/actions USER root RUN /opt/venv/bin/python -m pip install --upgrade pip RUN pip install --no-cache-dir -r /app/actions/requirements-actions.txt USER 1001 CMD ["start", "--actions", "actions"]<file_sep>from typing import Any, Optional, Text, Dict, List from rasa_sdk import Action, Tracker, FormValidationAction from rasa_sdk.events import SessionStarted, ActionExecuted, SlotSet from rasa_sdk.types import DomainDict from rasa_sdk.executor import CollectingDispatcher, Action import logging from importlib.metadata import version logger = logging.getLogger(__name__) vers = "Vers: 1.1.3, Date: Oct 15, 2022" class ActionSessionStart(Action): def name(self) -> Text: return "action_session_start" async def run(self, dispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: channel = tracker.get_latest_input_channel() metadata = tracker.get_slot("session_started_metadata") events = [SessionStarted(), ActionExecuted("action_listen")] # resp.aud; // aud(ience) stores the actions project id # req.headers['x-forwarded-host'] 'x-original-url' logger.debug(f"channel: {channel}") logger.debug(f"metadata: {metadata}") if channel and channel.startswith("google"): events.append(SlotSet("bot_name", "mqtt")) elif metadata and metadata["handler"]: events.append(SlotSet("bot_name", "mqtt")) else: events.append(SlotSet("bot_name", "joke")) # the session should begin with a `session_started` event and an `action_listen` # as a user message follows return events class ActionVersion(Action): def name(self): logger.info("ActionVersion self called") logger.info(f"rasa-sdk: {version('rasa-sdk')}") # define the name of the action which can then be included in training stories return "action_version" def run(self, dispatcher, tracker, domain): rasa_sdk_version = version('rasa-sdk') logger.info(f">> rasa-sdk version: {rasa_sdk_version}") dispatcher.utter_message(f"Rasa SDK: {rasa_sdk_version}\nActions: {vers}") return [] class ActionShowSlots(Action): def name(self): logger.info("ActionVersion self called") # define the name of the action which can then be included in training stories return "action_show_slots" def run(self, dispatcher, tracker, domain): with tracing.extract_start_span(tracer, domain.get("headers"), self.name()): msg = "Slots:\n" for k, v in tracker.slots.items(): msg += f" {k} | {v}\n" dispatcher.utter_message(msg) return [] def get_last_event_for( tracker, event_type: Text, action_names_to_exclude: List[Text] = None, skip: int = 0, ) -> Optional[Any]: def filter_function(e): has_instance = e if e["event"] == event_type: has_instance = e excluded = e["event"] != event_type or ( ( e["event"] == event_type and ( (e["parse_data"]["intent"]["name"] == "domicile") or (e["parse_data"]["intent"]["name"] == "customertype") ) ) ) return has_instance and not excluded filtered = filter(filter_function, reversed(tracker.events)) for i in range(skip): next(filtered, None) return next(filtered, None) def intentHistoryStr(tracker, skip, past): msg = "" prev_user_event = get_last_event_for(tracker, "user", skip=skip) if not prev_user_event: return "No prev msg" logger.info( "event.text: {}, intent: {}, confidence: {}".format( prev_user_event["text"], prev_user_event["parse_data"]["intent"]["name"], prev_user_event["parse_data"]["intent"]["confidence"], ) ) msg = "Ranked F1 scores:\n" msg += ( "* " + prev_user_event["parse_data"]["intent"]["name"] + " (" + "{:.4f}".format(prev_user_event["parse_data"]["intent"]["confidence"]) + ")\n" ) for i in range(past - 1): msg += ( "* " + prev_user_event["parse_data"]["intent_ranking"][i + 1]["name"] + " (" + "{:.4f}".format(prev_user_event["parse_data"]["intent_ranking"][i + 1]["confidence"]) + ")\n" ) return msg # msg += "* " + prev_user_event["parse_data"]["intent_ranking"][2]["name"] + " (" + "{:.4f}".format(prev_user_event["parse_data"]["intent_ranking"][2]["confidence"]) + ")\n" # msg += "* " + prev_user_event["parse_data"]["intent_ranking"][3]["name"] + " (" + "{:.4f}".format(prev_user_event["parse_data"]["intent_ranking"][3]["confidence"]) + ")" class ActionF1Scores(Action): def name(self): print("ActionLastIntent self called") # define the name of the action which can then be included in training stories return "action_f1_score" def run(self, dispatcher, tracker, domain): # what your action should do msg = intentHistoryStr(tracker, 1, 4) dispatcher.utter_message(msg) # send the message back to the user return []
d3c5e5035fc6230a17258bf7812663d125d6f371
[ "YAML", "Markdown", "INI", "Python", "Text", "Dockerfile", "Shell" ]
13
Text
rgstephens/jokebot
b9a1eafacdc38fa21c5a328aafaeb2d5a1fb86b8
ca181dc8d704a8647cbdd3df35dddf280554bfd9
refs/heads/master
<file_sep>from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): """ Description: User profile of the person """ user=models.OneToOneField(User,null=True,blank=True) mobile=models.CharField(max_length=180) status=models.IntegerField(default=0) otp=models.CharField(max_length=180,null=True) created_at=models.DateTimeField(auto_now=True) def __unicode__(self): return self.user.username <file_sep>from django.conf.urls import include, url from django.contrib import admin from tarasapp.views import * urlpatterns = [ url(r'^testmessage/', sendmessage), url(r'^adduser/', sendotp), url(r'^verifyuser/', verifyotp), ]<file_sep>from django.conf.urls import include, url from django.contrib import admin from .views import * urlpatterns = [ url(r'^', index), ] <file_sep>from django.shortcuts import render from django.conf import settings import random import requests from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from tarasapp.models import * # Create your views here. @csrf_exempt def sendmessage(request): response={} response['result']="Sorry" if request.method == 'POST': otp=random.randint(1000,9999) postdata={} postdata['authkey']=settings.MSG91_AUTH_KEY postdata['mobiles']=request.POST['mobile'] postdata['message']="This is a test message" postdata['route']="4" postdata['sender']=settings.MSG91_SENDER_ID postdata['response']='json' output=requests.post(settings.MSG_URL,data=postdata) response['result']=output.content return JsonResponse(response) @csrf_exempt def sendotp(request): response={} response['result']="Sorry" if request.method == 'POST': if request.POST['apikey']==settings.API_KEY: mobileno=request.POST['mobileno'] try: up=UserProfile.objects.get(mobile=mobileno) up.status=0 except: up=UserProfile() up.mobile=mobileno otp=random.randint(1000,9999) up.otp=otp up.save() postdata={} postdata['authkey']=settings.MSG91_AUTH_KEY postdata['mobiles']=request.POST['mobile'] postdata['message']="Hello\nWelcome to TARAS API. Your OTP is "+str(otp) postdata['route']="4" postdata['sender']=settings.MSG91_SENDER_ID postdata['response']='json' output=requests.post(settings.MSG_URL,data=postdata) response['result']="Successfully sent otp" response['success']="1" else: response['result']="Invalid api Key" response['success']="0" return JsonResponse(response) @csrf_exempt def verifyotp(request): response={} response['result']="Sorry" if request.method == 'POST': if request.POST['apikey']==settings.API_KEY: mobileno=request.POST['mobileno'] try: up=UserProfile.objects.get(mobile=mobileno) if up.otp == request.POST['otp']: if not up.user: up.status=2 else: up.status=1 response['status']=str(up.status) up.save() response['success']="1" else: response['result']="Invalid otp code" response['success']="0" except: response['result']="Invalid mobile no" response['success']="0" else: response['result']="Invalid api Key" response['success']="0" return JsonResponse(response) <file_sep>from django.apps import AppConfig class TarasappConfig(AppConfig): name = 'tarasapp' <file_sep>from __future__ import unicode_literals from django.db import models # Create your models here. class Accident(models.Model): location = models.CharField(max_length = 100) injuries = models.IntegerField(default=0) deaths = models.IntegerField(default=0) vehicle = models.CharField(max_length = 100, null = True) lon = models.CharField(max_length = 100, null = True) lat = models.CharField(max_length = 100, null = True) date = models.DateTimeField(blank = True) def __unicode__(self): return self.location+":\t"+str(self.lat)+","+str(self.lon)<file_sep>import datetime import csv import time import os import requests import re import urllib os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Traffic.settings') import django django.setup() from datetime import datetime from Accidents.models import * import urllib import json from django.core import serializers googleGeocodeUrl = 'http://maps.googleapis.com/maps/api/geocode/json?' def get_coordinates(query, from_sensor=False): query = query.encode('utf-8') params = { 'address': query, 'sensor': "true" if from_sensor else "false" } url = googleGeocodeUrl + urllib.urlencode(params) json_response = urllib.urlopen(url) response = json.loads(json_response.read()) if response['results']: location = response['results'][0]['geometry']['location'] latitude, longitude = location['lat'], location['lng'] print query, latitude, longitude else: latitude, longitude = None, None print query, "<no results>" return latitude, longitude all_accidents = [] def get_coordinates_map(query): q = query query = urllib.quote(query.strip()) # police%20headquartera%2C%20warangal%2C%20india&oq=police%20headquartera%2C%20warangal%2C%20india& url = "https://www.google.co.in/search?tbm=map&fp=1&authuser=0&hl=en&pb=!4m9!1m3!1d13084.518433867801!2d79.53223145!3d17.983126149999997!2m0!3m2!1i787!2i662!4f13.1!7i10!10b1!12m6!2m3!5m1!2b0!20e3!10b1!16b1!19m3!2m2!1i392!2i106!20m44!2m2!1i203!2i100!3m1!2i4!6m6!1m2!1i86!2i86!1m2!1i408!2i256!7m30!1m3!1e1!2b0!3e3!1m3!1e2!2b1!3e2!1m3!1e2!2b0!3e3!1m3!1e3!2b0!3e3!1m3!1e4!2b0!3e3!1m3!1e8!2b0!3e3!1m3!1e3!2b1!3e2!2b1!4b1!9b0!22m6!1sivrfVtw_05W4BOK6tpAK!4m1!2i11887!7e81!12e3!18e15!24m3!2b1!5m1!5b1!26m3!2m2!1i80!2i92!30m28!1m6!1m2!1i0!2i0!2m2!1i458!2i662!1m6!1m2!1i737!2i0!2m2!1i787!2i662!1m6!1m2!1i0!2i0!2m2!1i787!2i20!1m6!1m2!1i0!2i642!2m2!1i787!2i662!37m1!1e81!42b1&q="+query+"&oq="+query+"&gs_l=maps.12..115i144.17203.38040.2.42035.44.44.0.0.0.0.6016.10631.3j17j5j2j9-1.28.0....0...1ac.1.64.maps..60.30.11312.0.&tch=1&ech=2&psi=ivrfVtw_05W4BOK6tpAK.1457519202769.1" r = requests.get(url) x = r.content pattern = "(?P<latlon>[0-9][0-9]\.[0-9]*\,[0-9][0-9]\.[0-9]*)" r = re.findall(pattern, x) lat_lon = r[0].split(",") print lat_lon lat = float(lat_lon[0]) lon = float(lat_lon[1]) print q, lat,lon return lat,lon def upload_csv(file,start): all_accidents = [] year = file.split(".")[0] finds = {} not_founds = [] f = open(file, 'r') c = csv.reader(f) num = 0 c.next() rows = [] for row in c: rows.append(row) # print rows for row in rows: ind = int(row[0]) if ind<start: continue # print row[1] # num += 1 # print type(row) a = Accident() a.location = row[1] # print "______________________________", row[1] loc = row[1] + ", Warangal, India" print "FETCHING" lat, lon = get_coordinates_map(loc) valid = lat < 19.0 # if valid: # not_founds.append(loc) # else: # finds[loc] = [lat,lon] if valid: a.lat = str(lat) a.lon = str(lon) elif not valid: all_others = Accident.objects.filter(location__startswith = loc[0]) print "________________________________________________________________________" for index, accident in enumerate(all_others): print index, accident.location print "________________________________________________________________________" print "DId not find coordinates for "+ row[1] i = raw_input("Enter -1 if not found any previous location to enter. Else, enter the index") if i == "-1": lat = raw_input("Enter the latitude") lon = raw_input("enter the longitude") a.lat = (lat) a.lon = (lon) else: print "already exists" i = int(i) a.lat = (all_others[i].lat) a.lon =(all_others[i].lon) inj_death = row[3].split() if row[3] == "_" or row[3] == "-": a.deaths = 0 a.injuries = 0 else: if inj_death[1] == 'death': a.deaths = int(inj_death[0]) elif inj_death[1] == 'injured': a.injuries = int(inj_death[0]) a.vehicle = row[6] dt = datetime(int(year),1,1) a.date = dt a_dict = json.loads(serializers.serialize('json', [ a, ])) print type(a_dict) print len(a_dict) print a_dict[0]["fields"] all_accidents.append(a_dict[0]["fields"]) time.sleep(1) a.save() # print num f = open(year+".json", "w") json.dump(all_accidents, f) f.close() # print finds # print not_founds upload_csv("2008.csv",15) print all_accidents # lat,lon = get_coordinates("NIT main gate, Warangal, India") # print lat, lon # get_coordinates_map("Police headquarters, Warangal, India")<file_sep>from django.shortcuts import render from .models import * # Create your views here. def index(request): accidents = Accident.objects.all(); for accident in accidents: print type(accident.location) print accident.location accident.location = accident.location.encode('utf-8').replace("\n","") return render(request, "Accidents/index2.djt", {'accidents':accidents})
404fef6f289671484f638fcc9d57820da8dc9e8b
[ "Python" ]
8
Python
projecttaras/EPICS-proj
4739f4c01c15689f129ced326608ca8898d8bc4a
a9070783af5ab0d47559de093ef97c7170b959c4
refs/heads/master
<repo_name>soju6jan/downloader_video<file_sep>/logic_aniplus.py # -*- coding: utf-8 -*- ######################################################### # python import os, sys, traceback, re, json, threading, base64 from datetime import datetime, timedelta import copy # third-party import requests # third-party from flask import request, render_template, jsonify from sqlalchemy import or_, and_, func, not_, desc # sjva 공용 from framework import db, scheduler, path_data, socketio from framework.util import Util from plugin import LogicModuleBase, FfmpegQueueEntity, FfmpegQueue, default_route_socketio # 패키지 from .plugin import P logger = P.logger ModelSetting = P.ModelSetting ######################################################### headers = { 'Accept': 'application/json, text/plain, */*', 'Accept-Language':'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7', 'Content-Type':'application/json;charset=UTF-8', 'Host':'api.aniplustv.com:3100', 'Origin':'https://www.aniplustv.com', 'Referer':'https://www.aniplustv.com/', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36', } class LogicAniplus(LogicModuleBase): db_default = { 'aniplus_db_version' : '1', 'aniplus_download_path' : os.path.join(path_data, P.package_name, 'aniplus'), 'aniplus_max_ffmpeg_process_count': '1', 'aniplus_current_code' : '', 'aniplus_search_keyword' : '', 'aniplus_id' : '', 'aniplus_auto_start' : 'False', 'aniplus_interval' : '30 7 * * *', 'aniplus_auto_make_folder' : 'True', 'aniplus_order_recent' : 'True', 'aniplus_incompleted_auto_enqueue' : 'True', 'aniplus_insert_episode_title' : 'False', 'aniplus_auto_mode_all' : 'False', 'aniplus_auto_code_list' : 'all', } def __init__(self, P): super(LogicAniplus, self).__init__(P, 'setting', scheduler_desc='Aniplus 자동 다운로드') self.name = 'aniplus' default_route_socketio(P, self) def process_menu(self, sub, req): arg = P.ModelSetting.to_dict() arg['sub'] = self.name if sub in ['setting', 'queue', 'list', 'request']: if sub == 'request' and req.args.get('content_code') is not None: arg['aniplus_current_code'] = req.args.get('content_code') if sub == 'setting': job_id = '%s_%s' % (self.P.package_name, self.name) arg['scheduler'] = str(scheduler.is_include(job_id)) arg['is_running'] = str(scheduler.is_running(job_id)) return render_template('{package_name}_{module_name}_{sub}.html'.format(package_name=P.package_name, module_name=self.name, sub=sub), arg=arg) return render_template('sample.html', title='%s - %s' % (P.package_name, sub)) def process_ajax(self, sub, req): try: if sub == 'search': keyword = request.form['keyword'] P.ModelSetting.set('aniplus_search_keyword', keyword) data = requests.post('https://api.aniplustv.com:3100/search', headers=headers, data=json.dumps({"params":{"userid":ModelSetting.get('aniplus_id'),"strFind":keyword,"gotoPage":1, 'token':get_token()}})).json() return jsonify({'ret':'success', 'data':data}) elif sub == 'analysis': code = request.form['code'] P.ModelSetting.set('aniplus_current_code', code) data = self.get_series_info(code) self.current_data = data return jsonify({'ret':'success', 'data':data}) elif sub == 'add_queue': ret = {} info = json.loads(request.form['data']) ret['ret'] = self.add(info) return jsonify(ret) elif sub == 'entity_list': return jsonify(self.queue.get_entity_list()) elif sub == 'queue_command': ret = self.queue.command(req.form['command'], int(req.form['entity_id'])) return jsonify(ret) elif sub == 'add_queue_checked_list': data = json.loads(request.form['data']) def func(): count = 0 for tmp in data: add_ret = self.add(tmp) if add_ret.startswith('enqueue'): self.socketio_callback('list_refresh', '') count += 1 notify = {'type':'success', 'msg' : u'%s 개의 에피소드를 큐에 추가 하였습니다.' % count} socketio.emit("notify", notify, namespace='/framework', broadcast=True) thread = threading.Thread(target=func, args=()) thread.daemon = True thread.start() return jsonify('') elif sub == 'web_list': return jsonify(ModelAniplusItem.web_list(request)) elif sub == 'db_remove': return jsonify(ModelAniplusItem.delete_by_id(req.form['id'])) except Exception as e: P.logger.error('Exception:%s', e) P.logger.error(traceback.format_exc()) def setting_save_after(self): if self.queue.get_max_ffmpeg_count() != P.ModelSetting.get_int('aniplus_max_ffmpeg_process_count'): self.queue.set_max_ffmpeg_count(P.ModelSetting.get_int('aniplus_max_ffmpeg_process_count')) def scheduler_function(self): date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') data = requests.post('https://api.aniplustv.com:3100/updateWeek', headers=headers, data=json.dumps({"params":{"userid":ModelSetting.get('aniplus_id'),"curDate":date, 'token':get_token()}})).json()[0]['listData'] data = list(reversed(data)) conent_code_list = P.ModelSetting.get_list('aniplus_auto_code_list', '|') for item in data: if date.find(item['startDate']) == -1: continue if 'all' not in conent_code_list and str(item['contentSerial']) not in conent_code_list: continue db_entity = ModelAniplusItem.get_by_aniplus_id(item['contentPartSerial']) if db_entity is not None: continue content_info = self.get_series_info(item['contentSerial']) if P.ModelSetting.get_bool('aniplus_auto_mode_all'): for episode_info in content_info['episode']: add_ret = self.add(episode_info) if add_ret.startswith('enqueue'): self.socketio_callback('list_refresh', '') else: episode_info = content_info['episode'][0] if content_info['recent'] else content_info['episode'][-1] add_ret = self.add(episode_info) if add_ret.startswith('enqueue'): self.socketio_callback('list_refresh', '') def plugin_load(self): # 2021-05-02 db에 아무것도 없을때 init전에 None 세팅 self.queue = FfmpegQueue(P, P.ModelSetting.get_int('aniplus_max_ffmpeg_process_count')) self.current_data = None self.queue.queue_start() if P.ModelSetting.get_bool('aniplus_incompleted_auto_enqueue'): def func(): data = ModelAniplusItem.get_list_incompleted() for db_entity in data: add_ret = self.add(db_entity.aniplus_info) if add_ret.startswith('enqueue'): self.socketio_callback('list_refresh', '') thread = threading.Thread(target=func, args=()) thread.daemon = True thread.start() def reset_db(self): db.session.query(ModelAniplusItem).delete() db.session.commit() return True ######################################################### def add(self, episode_info): if self.is_exist(episode_info): return 'queue_exist' else: db_entity = ModelAniplusItem.get_by_aniplus_id(episode_info['contentPartSerial']) if db_entity is None: entity = AniplusQueueEntity(P, self, episode_info) if entity.available: ModelAniplusItem.append(entity.as_dict()) self.queue.add_queue(entity) return 'enqueue_db_append' else: self.queue.command('remove', entity.entity_id) return 'fail' elif db_entity.status != 'completed': entity = AniplusQueueEntity(P, self, episode_info) self.queue.add_queue(entity) return 'enqueue_db_exist' else: return 'db_completed' def get_series_info(self, code): try: if self.current_data is not None and 'code' in self.current_data and self.current_data['code'] == code and self.current_data['recent'] == ModelSetting.get_bool('aniplus_order_recent'): return self.current_data data = {} data['code'] = code tmp = requests.get('https://api.aniplustv.com:3100/itemInfo?contentSerial={code}'.format(code=code), headers=headers).json() if tmp[0]['intReturn'] == 0: data['info'] = tmp[0]['listData'][0] tmp = requests.get('https://api.aniplustv.com:3100/itemPart?contentSerial={code}&userid={id}'.format(code=code, id=ModelSetting.get('aniplus_id')), headers=headers).json() if tmp[0]['intReturn'] == 0: data['episode'] = tmp[0]['listData'] if P.ModelSetting.get_bool('aniplus_order_recent') == False: data['episode'] = list(reversed(data['episode'])) data['recent'] = ModelSetting.get_bool('aniplus_order_recent') return data except Exception as e: P.logger.error('Exception:%s', e) P.logger.error(traceback.format_exc()) return {'ret':'exception', 'log':str(e)} def is_exist(self, info): for e in self.queue.entity_list: if e.info['contentPartSerial'] == info['contentPartSerial']: return True return False class AniplusQueueEntity(FfmpegQueueEntity): def __init__(self, P, module_logic, info): super(AniplusQueueEntity, self).__init__(P, module_logic, info) self.season = 1 self.available = self.make_episode_info() def refresh_status(self): self.module_logic.socketio_callback('status', self.as_dict()) def info_dict(self, tmp): for key, value in self.info.items(): tmp[key] = value tmp['season'] = self.season tmp['aniplus_info'] = self.info return tmp def donwload_completed(self): db_entity = ModelAniplusItem.get_by_aniplus_id(self.info['contentPartSerial']) if db_entity is not None: db_entity.status = 'completed' db_entity.complated_time = datetime.now() db_entity.save() def make_episode_info(self): try: data = requests.get('https://www.aniplustv.com/aniplus2020Api/base64encode.asp?codeString={userid}'.format(userid=ModelSetting.get('aniplus_id')), headers=headers).text userid2 = data.replace('{"codeString":"', '').replace('"}', '') data = requests.get('https://www.aniplustv.com/aniplus2020Api/base64encode.asp?codeString={time}|was|{subPartSerial2}/{userid}@{userid2}'.format( time=(datetime.now() + timedelta(hours=1)).strftime('%Y%m%d%H%M%S'), subPartSerial2=self.info['subPartSerial2'], userid=ModelSetting.get('aniplus_id'), userid2=userid2 ), headers=headers).text crypParam = data.replace('{"codeString":"', '').replace('"}', '') data = requests.post('https://api.aniplustv.com:3100/vodUrl', headers=headers, json={"params":{"userid":ModelSetting.get('aniplus_id'),"subPartSerial":self.info['subPartSerial2'],"crypParam":crypParam, 'authId': base64.b64encode(ModelSetting.get('aniplus_id').encode('utf-8')).decode('utf-8'), 'token': get_token()}} ).json()[0] if 'use1080' in data and data['use1080'] != '': self.quality = '1080p' self.url = data['use1080'] elif 'fileName1080p' in data and data['fileName1080p'] != '': self.quality = '1080p' self.url = data['fileName1080p'] elif 'fileName720p' in data and data['fileName720p'] != '': self.quality = '720p' self.url = data['fileName720p'] elif 'fileName480p' in data and data['fileName480p'] != '': self.quality = '480p' self.url = data['fileName480p'] else: return False match = re.compile(r'(?P<title>.*?)\s*((?P<season>\d+)%s)' % (u'기')).search(self.info['title']) if match: content_title = match.group('title').strip() if 'season' in match.groupdict() and match.group('season') is not None: self.season = int(match.group('season')) else: content_title = self.info['title'] self.season = 1 if content_title.find(u'극장판') != -1: ret = '%s.%s-SAP.mp4' % (content_title, self.quality) else: ret = '%s.S%sE%s.%s-SAP.mp4' % (content_title, str(self.season).zfill(2), str(self.info['part']).zfill(2), self.quality) self.filename = Util.change_text_for_use_filename(ret) self.savepath = P.ModelSetting.get('aniplus_download_path') if P.ModelSetting.get_bool('aniplus_auto_make_folder'): folder_name = Util.change_text_for_use_filename ( content_title.strip() ) self.savepath = os.path.join(self.savepath, folder_name) self.filepath = os.path.join(self.savepath, self.filename) if not os.path.exists(self.savepath): os.makedirs(self.savepath) return True except Exception as e: P.logger.error('Exception:%s', e) P.logger.error(traceback.format_exc()) class ModelAniplusItem(db.Model): __tablename__ = '{package_name}_aniplus_item'.format(package_name=P.package_name) __table_args__ = {'mysql_collate': 'utf8_general_ci'} __bind_key__ = P.package_name id = db.Column(db.Integer, primary_key=True) created_time = db.Column(db.DateTime) completed_time = db.Column(db.DateTime) reserved = db.Column(db.JSON) content_code = db.Column(db.String) season = db.Column(db.Integer) episode_no = db.Column(db.Integer) title = db.Column(db.String) episode_title = db.Column(db.String) aniplus_id = db.Column(db.String) quality = db.Column(db.String) filepath = db.Column(db.String) filename = db.Column(db.String) savepath = db.Column(db.String) video_url = db.Column(db.String) thumbnail = db.Column(db.String) status = db.Column(db.String) aniplus_info = db.Column(db.JSON) def __init__(self): self.created_time = datetime.now() def __repr__(self): return repr(self.as_dict()) def as_dict(self): ret = {x.name: getattr(self, x.name) for x in self.__table__.columns} ret['created_time'] = self.created_time.strftime('%Y-%m-%d %H:%M:%S') ret['completed_time'] = self.completed_time.strftime('%Y-%m-%d %H:%M:%S') if self.completed_time is not None else None return ret def save(self): db.session.add(self) db.session.commit() @classmethod def get_by_id(cls, id): return db.session.query(cls).filter_by(id=id).first() @classmethod def get_by_aniplus_id(cls, aniplus_id): return db.session.query(cls).filter_by(aniplus_id=aniplus_id).first() @classmethod def delete_by_id(cls, id): db.session.query(cls).filter_by(id=id).delete() db.session.commit() return True @classmethod def web_list(cls, req): ret = {} page = int(req.form['page']) if 'page' in req.form else 1 page_size = 30 job_id = '' search = req.form['search_word'] if 'search_word' in req.form else '' option = req.form['option'] if 'option' in req.form else 'all' order = req.form['order'] if 'order' in req.form else 'desc' query = cls.make_query(search=search, order=order, option=option) count = query.count() query = query.limit(page_size).offset((page-1)*page_size) lists = query.all() ret['list'] = [item.as_dict() for item in lists] ret['paging'] = Util.get_paging_info(count, page, page_size) return ret @classmethod def make_query(cls, search='', order='desc', option='all'): query = db.session.query(cls) if search is not None and search != '': if search.find('|') != -1: tmp = search.split('|') conditions = [] for tt in tmp: if tt != '': conditions.append(cls.filename.like('%'+tt.strip()+'%') ) query = query.filter(or_(*conditions)) elif search.find(',') != -1: tmp = search.split(',') for tt in tmp: if tt != '': query = query.filter(cls.filename.like('%'+tt.strip()+'%')) else: query = query.filter(cls.filename.like('%'+search+'%')) if option == 'completed': query = query.filter(cls.status == 'completed') query = query.order_by(desc(cls.id)) if order == 'desc' else query.order_by(cls.id) return query @classmethod def get_list_incompleted(cls): return db.session.query(cls).filter(cls.status != 'completed').all() @classmethod def append(cls, q): item = ModelAniplusItem() item.content_code = q['contentSerial'] item.aniplus_id = q['contentPartSerial'] item.episode_no = q['part'] item.title = q['title'] item.episode_title = q['subTitle'] item.season = q['season'] item.quality = q['quality'] item.filepath = q['filepath'] item.filename = q['filename'] item.savepath = q['savepath'] item.video_url = q['url'] item.thumbnail = q['img'] item.status = 'wait' item.aniplus_info = q['aniplus_info'] item.save() def get_token(): return base64.b64encode(datetime.now().strftime('%Y%m%d%H%M%S').encode('utf-8')).decode('utf-8') <file_sep>/logic_ani365.py # -*- coding: utf-8 -*- ######################################################### # python import os, sys, traceback, re, json, threading from datetime import datetime import copy # third-party import requests # third-party from flask import request, render_template, jsonify from sqlalchemy import or_, and_, func, not_, desc # sjva 공용 from framework import db, scheduler, path_data, socketio from framework.util import Util from framework.common.util import headers from plugin import LogicModuleBase, FfmpegQueueEntity, FfmpegQueue, default_route_socketio from tool_base import d # 패키지 from .plugin import P logger = P.logger ######################################################### class LogicAni365(LogicModuleBase): db_default = { 'ani365_db_version' : '1', 'ani365_url' : 'https://www.ani365.org', 'ani365_download_path' : os.path.join(path_data, P.package_name, 'ani365'), 'ani365_auto_make_folder' : 'True', 'ani365_auto_make_season_folder' : 'True', 'ani365_finished_insert' : u'[완결]', 'ani365_max_ffmpeg_process_count': '1', 'ani365_order_desc' : 'False', 'ani365_auto_start' : 'False', 'ani365_interval' : '* 5 * * *', 'ani365_auto_mode_all' : 'False', 'ani365_auto_code_list' : 'all', 'ani365_current_code' : '', 'ani365_incompleted_auto_enqueue' : 'True', 'ani365_image_url_prefix_series' : 'https://www.jetcloud.cc/series/', 'ani365_image_url_prefix_episode' : 'https://www.jetcloud-list.cc/thumbnail/', } current_headers = None def __init__(self, P): super(LogicAni365, self).__init__(P, 'setting', scheduler_desc='ani365 자동 다운로드') self.name = 'ani365' default_route_socketio(P, self) def process_menu(self, sub, req): arg = P.ModelSetting.to_dict() arg['sub'] = self.name if sub in ['setting', 'queue', 'list', 'request']: if sub == 'request' and req.args.get('content_code') is not None: arg['ani365_current_code'] = req.args.get('content_code') if sub == 'setting': job_id = '%s_%s' % (self.P.package_name, self.name) arg['scheduler'] = str(scheduler.is_include(job_id)) arg['is_running'] = str(scheduler.is_running(job_id)) return render_template('{package_name}_{module_name}_{sub}.html'.format(package_name=P.package_name, module_name=self.name, sub=sub), arg=arg) return render_template('sample.html', title='%s - %s' % (P.package_name, sub)) def process_ajax(self, sub, req): try: if sub == 'analysis': code = request.form['code'] P.ModelSetting.set('ani365_current_code', code) data = self.get_series_info(code) self.current_data = data return jsonify({'ret':'success', 'data':data}) elif sub == 'add_queue': ret = {} info = json.loads(request.form['data']) ret['ret'] = self.add(info) return jsonify(ret) elif sub == 'entity_list': return jsonify(self.queue.get_entity_list()) elif sub == 'queue_command': ret = self.queue.command(req.form['command'], int(req.form['entity_id'])) return jsonify(ret) elif sub == 'add_queue_checked_list': data = json.loads(request.form['data']) def func(): count = 0 for tmp in data: add_ret = self.add(tmp) if add_ret.startswith('enqueue'): self.socketio_callback('list_refresh', '') count += 1 notify = {'type':'success', 'msg' : u'%s 개의 에피소드를 큐에 추가 하였습니다.' % count} socketio.emit("notify", notify, namespace='/framework', broadcast=True) thread = threading.Thread(target=func, args=()) thread.daemon = True thread.start() return jsonify('') elif sub == 'web_list': return jsonify(ModelAni365Item.web_list(request)) elif sub == 'db_remove': return jsonify(ModelAni365Item.delete_by_id(req.form['id'])) except Exception as e: P.logger.error('Exception:%s', e) P.logger.error(traceback.format_exc()) def setting_save_after(self): if self.queue.get_max_ffmpeg_count() != P.ModelSetting.get_int('ani365_max_ffmpeg_process_count'): self.queue.set_max_ffmpeg_count(P.ModelSetting.get_int('ani365_max_ffmpeg_process_count')) def scheduler_function(self): url = P.ModelSetting.get('ani365_url') + '/get-series' param = {'_ut' : '', 'dateft':''} data, LogicAni365.current_headers = self.get_json_with_auth_session(None, url, param) conent_code_list = P.ModelSetting.get_list('ani365_auto_code_list', '|') for k1, day in data.items(): if int(k1) < 8: for content in day if type(day) == type([]) else day.values(): if content['_s'] in conent_code_list or 'all' in conent_code_list: content_info = self.get_series_info(content['_s']) if len(content_info['episode']) == 0: continue if P.ModelSetting.get_bool('ani365_auto_mode_all'): for episode_info in content_info['episode']: add_ret = self.add(episode_info) if add_ret.startswith('enqueue'): self.socketio_callback('list_refresh', '') else: episode_info = content_info['episode'][-1] if content_info['episode_order'] == 'asc' else content_info['episode'][0] add_ret = self.add(episode_info) if add_ret.startswith('enqueue'): self.socketio_callback('list_refresh', '') def plugin_load(self): # 2021-05-02 db에 아무것도 없을때 init전에 None 세팅 self.queue = FfmpegQueue(P, P.ModelSetting.get_int('ani365_max_ffmpeg_process_count')) self.current_data = None self.queue.queue_start() if P.ModelSetting.get_bool('ani365_incompleted_auto_enqueue'): def func(): url = P.ModelSetting.get('ani365_url') + '/get-series' param = {'_ut' : '', 'dateft':''} data, LogicAni365.current_headers = self.get_json_with_auth_session(None, url, param) data = ModelAni365Item.get_list_incompleted() for db_entity in data: add_ret = self.add(db_entity.ani365_info) if add_ret.startswith('enqueue'): self.socketio_callback('list_refresh', '') thread = threading.Thread(target=func, args=()) thread.daemon = True thread.start() def reset_db(self): db.session.query(ModelAni365Item).delete() db.session.commit() return True ######################################################### def add(self, episode_info): if self.is_exist(episode_info): return 'queue_exist' else: db_entity = ModelAni365Item.get_by_ani365_id(episode_info['_id']) if db_entity is None: entity = Ani365QueueEntity(P, self, episode_info) ModelAni365Item.append(entity.as_dict()) self.queue.add_queue(entity) return 'enqueue_db_append' elif db_entity.status != 'completed': entity = Ani365QueueEntity(P, self, episode_info) self.queue.add_queue(entity) return 'enqueue_db_exist' else: return 'db_completed' def get_series_info(self, code): try: if self.current_data is not None and 'code' in self.current_data and self.current_data['code'] == code: return self.current_data if code.startswith('http'): code = code.split('detail/')[1] referer = P.ModelSetting.get('ani365_url') + '/kr/detail/' + code url = P.ModelSetting.get('ani365_url') + '/get-series-detail' param = {'_si' : code, '_sea':''} data, LogicAni365.current_headers = self.get_json_with_auth_session(referer, url, param) if data is None: return data['code'] = code data['episode_order'] = 'asc' for epi in data['episode']: epi['day'] = data['day'] epi['content_code'] = data['code'] if P.ModelSetting.get_bool('ani365_order_desc'): data['episode'] = list(reversed(data['episode'])) data['list_order'] = 'desc' return data except Exception as e: P.logger.error('Exception:%s', e) P.logger.error(traceback.format_exc()) return {'ret':'exception', 'log':str(e)} def is_exist(self, info): for e in self.queue.entity_list: if e.info['_id'] == info['_id']: return True return False # /kr 만 set-cookie를 보냄 # 무조건 쿠키확보 후 referer None이면 바로 url로, None이 아니면 referer 거쳐서 def get_json_with_auth_session(self, referer, url, data): try: headers = { #'Accept' : 'application/json, text/plain, */*', #'Accept-Language':'ko-KR,ko;q=0.8,en-US;q=0.5,en;q=0.3', #'Connection':'keep-alive', #'Content-Type':'application/x-www-form-urlencoded;charset=utf-8;', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36', } session = requests.Session() home = P.ModelSetting.get('ani365_url') + '/kr' res = session.get(home) headers['Authorization'] = res.text.split('$http.defaults.headers.common[\'Authorization\'] = "')[1].strip().split('"')[0] headers['Cookie'] = f"ci_session={res.headers['Set-Cookie'].split('ci_session=')[1].split(';')[0]}; USERCONTRY=kr; LANGU=kr;" #logger.warning(d(headers)) if referer is not None: res = session.get(referer) res = session.post(url, headers=headers, data=data) #logger.warning(res.text) logger.debug('get_json_with_auth_session status_code : %s', res.status_code) return res.json(), headers except Exception as exception: logger.error('Exception:%s', exception) logger.error(traceback.format_exc()) return None, None class Ani365QueueEntity(FfmpegQueueEntity): def __init__(self, P, module_logic, info): super(Ani365QueueEntity, self).__init__(P, module_logic, info) self.vtt = None self.season = 1 self.content_title = None self.make_episode_info() def refresh_status(self): self.module_logic.socketio_callback('status', self.as_dict()) def info_dict(self, tmp): for key, value in self.info.items(): tmp[key] = value tmp['vtt'] = self.vtt tmp['season'] = self.season tmp['content_title'] = self.content_title tmp['ani365_info'] = self.info return tmp def donwload_completed(self): db_entity = ModelAni365Item.get_by_ani365_id(self.info['_id']) if db_entity is not None: db_entity.status = 'completed' db_entity.complated_time = datetime.now() db_entity.save() def make_episode_info(self): try: url = 'https://www.jetcloud-list.cc/kr/episode/' + self.info['va'] text = requests.get(url, headers=headers).text match = re.compile('src\=\"(?P<video_url>http.*?\.m3u8)').search(text) if match: tmp = match.group('video_url') m3u8_text = requests.get(tmp, headers=headers).text.strip() self.url = m3u8_text.split('\n')[-1].strip() logger.debug(self.url) self.quality = self.url.split('/')[-1].split('.')[0] match = re.compile(r'src\=\"(?P<vtt_url>http.*?kr.vtt)').search(text) if match: self.vtt = u'%s' % match.group('vtt_url') match = re.compile(r'(?P<title>.*?)\s*((?P<season>\d+)%s)?\s*((?P<epi_no>\d+)%s)' % (u'기', u'화')).search(self.info['title']) if match: self.content_title = match.group('title').strip() if 'season' in match.groupdict() and match.group('season') is not None: self.season = int(match.group('season')) epi_no = int(match.group('epi_no')) ret = '%s.S%sE%s.%s-SA.mp4' % (self.content_title, '0%s' % self.season if self.season < 10 else self.season, '0%s' % epi_no if epi_no < 10 else epi_no, self.quality) else: self.content_title = self.info['title'] P.logger.debug('NOT MATCH') ret = '%s.720p-SA.mp4' % self.info['title'] self.filename = Util.change_text_for_use_filename(ret) self.savepath = P.ModelSetting.get('ani365_download_path') if P.ModelSetting.get_bool('ani365_auto_make_folder'): if self.info['day'].find(u'완결') != -1: folder_name = '%s %s' % (P.ModelSetting.get('ani365_finished_insert'), self.content_title) else: folder_name = self.content_title folder_name = Util.change_text_for_use_filename ( folder_name.strip() ) self.savepath = os.path.join(self.savepath, folder_name) if P.ModelSetting.get_bool('ani365_auto_make_season_folder'): self.savepath = os.path.join(self.savepath, 'Season %s' % int(self.season)) self.filepath = os.path.join(self.savepath, self.filename) if not os.path.exists(self.savepath): os.makedirs(self.savepath) from framework.common.util import write_file, convert_vtt_to_srt srt_filepath = os.path.join(self.savepath, self.filename.replace('.mp4', '.ko.srt')) # 2021-07-13 by lapis #if not os.path.exists(srt_filepath): if self.vtt is not None and not os.path.exists(srt_filepath): vtt_data = requests.get(self.vtt, headers=LogicAni365.current_headers).text srt_data = convert_vtt_to_srt(vtt_data) write_file(srt_data, srt_filepath) self.headers = LogicAni365.current_headers except Exception as e: P.logger.error('Exception:%s', e) P.logger.error(traceback.format_exc()) class ModelAni365Item(db.Model): __tablename__ = '{package_name}_ani365_item'.format(package_name=P.package_name) __table_args__ = {'mysql_collate': 'utf8_general_ci'} __bind_key__ = P.package_name id = db.Column(db.Integer, primary_key=True) created_time = db.Column(db.DateTime) completed_time = db.Column(db.DateTime) reserved = db.Column(db.JSON) content_code = db.Column(db.String) season = db.Column(db.Integer) episode_no = db.Column(db.Integer) title = db.Column(db.String) episode_title = db.Column(db.String) ani365_va = db.Column(db.String) ani365_vi = db.Column(db.String) ani365_id = db.Column(db.String) quality = db.Column(db.String) filepath = db.Column(db.String) filename = db.Column(db.String) savepath = db.Column(db.String) video_url = db.Column(db.String) vtt_url = db.Column(db.String) thumbnail = db.Column(db.String) status = db.Column(db.String) ani365_info = db.Column(db.JSON) def __init__(self): self.created_time = datetime.now() def __repr__(self): return repr(self.as_dict()) def as_dict(self): ret = {x.name: getattr(self, x.name) for x in self.__table__.columns} ret['created_time'] = self.created_time.strftime('%Y-%m-%d %H:%M:%S') ret['completed_time'] = self.completed_time.strftime('%Y-%m-%d %H:%M:%S') if self.completed_time is not None else None return ret def save(self): db.session.add(self) db.session.commit() @classmethod def get_by_id(cls, id): return db.session.query(cls).filter_by(id=id).first() @classmethod def get_by_ani365_id(cls, ani365_id): return db.session.query(cls).filter_by(ani365_id=ani365_id).first() @classmethod def delete_by_id(cls, id): db.session.query(cls).filter_by(id=id).delete() db.session.commit() return True @classmethod def web_list(cls, req): ret = {} page = int(req.form['page']) if 'page' in req.form else 1 page_size = 30 job_id = '' search = req.form['search_word'] if 'search_word' in req.form else '' option = req.form['option'] if 'option' in req.form else 'all' order = req.form['order'] if 'order' in req.form else 'desc' query = cls.make_query(search=search, order=order, option=option) count = query.count() query = query.limit(page_size).offset((page-1)*page_size) lists = query.all() ret['list'] = [item.as_dict() for item in lists] ret['paging'] = Util.get_paging_info(count, page, page_size) return ret @classmethod def make_query(cls, search='', order='desc', option='all'): query = db.session.query(cls) if search is not None and search != '': if search.find('|') != -1: tmp = search.split('|') conditions = [] for tt in tmp: if tt != '': conditions.append(cls.filename.like('%'+tt.strip()+'%') ) query = query.filter(or_(*conditions)) elif search.find(',') != -1: tmp = search.split(',') for tt in tmp: if tt != '': query = query.filter(cls.filename.like('%'+tt.strip()+'%')) else: query = query.filter(cls.filename.like('%'+search+'%')) if option == 'completed': query = query.filter(cls.status == 'completed') query = query.order_by(desc(cls.id)) if order == 'desc' else query.order_by(cls.id) return query @classmethod def get_list_incompleted(cls): return db.session.query(cls).filter(cls.status != 'completed').all() @classmethod def append(cls, q): item = ModelAni365Item() item.content_code = q['content_code'] item.season = q['season'] item.episode_no = q['epi_queue'] item.title = q['content_title'] item.episode_title = q['title'] item.ani365_va = q['va'] item.ani365_vi = q['_vi'] item.ani365_id = q['_id'] item.quality = q['quality'] item.filepath = q['filepath'] item.filename = q['filename'] item.savepath = q['savepath'] item.video_url = q['url'] item.vtt_url = q['vtt'] item.thumbnail = q['thumbnail'] item.status = 'wait' item.ani365_info = q['ani365_info'] item.save()
73ba3b8932e2bd641876aced1d2cfc768ee4ed1a
[ "Python" ]
2
Python
soju6jan/downloader_video
4eb10cacf1487136e4225f77a036740f9da10128
dc3762110ce14714fd562c00446649e1a5b5faf0
refs/heads/master
<repo_name>glllcs/fabcontroley<file_sep>/functions.php <?php /** * Theme functions and definitions * * @package fabcontroley */ if ( ! function_exists( 'fabcontroley_theme_defaults' ) ) : /** * Customize theme defaults. * * @since 1.0.0 * * @param array $defaults Theme defaults. * @param array Custom theme defaults. */ function fabcontroley_theme_defaults( $defaults ) { $defaults['enable_slider'] = false; $defaults['enable_hero_content'] = false; $defaults['blog_column_type'] = 'column-3'; $defaults['excerpt_count'] = 25; return $defaults; } endif; add_filter( 'fabulist_default_theme_options', 'fabcontroley_theme_defaults', 99 ); if ( ! function_exists( 'fabcontroley_enqueue_styles' ) ) : /** * Load assets. * * @since 1.0.0 */ function fabcontroley_enqueue_styles() { wp_enqueue_style( 'fabcontroley-style-parent', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'fabcontroley-style', get_stylesheet_directory_uri() . '/style.css', array( 'fabcontroley-style-parent' ), '1.0.0' ); } endif; add_action( 'wp_enqueue_scripts', 'fabcontroley_enqueue_styles', 99 ); /** * Register Google fonts * * @return string Google fonts URL for the theme. */ function fabulist_fonts_url() { $fonts_url = ''; $fonts = array(); $subsets = 'latin,latin-ext'; /* translators: If there are characters in your language that are not supported by Work Sans, translate this to 'off'. Do not translate into your own language. */ if ( 'off' !== _x( 'on', 'Work Sans font: on or off', 'fabulist' ) ) { $fonts[] = 'Work Sans:100,200,300,400,500,600,700,800'; } /* translators: If there are characters in your language that are not supported by Inconsolata, translate this to 'off'. Do not translate into your own language. */ if ( 'off' !== _x( 'on', 'Inconsolata font: on or off', 'fabulist' ) ) { $fonts[] = 'Inconsolata:100,200,300,400,500,600,700,800'; } $query_args = array( 'family' => urlencode( implode( '|', $fonts ) ), 'subset' => urlencode( $subsets ), ); if ( $fonts ) { $fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' ); } return esc_url_raw( $fonts_url ); } if ( ! function_exists( 'fabcontroley_site_info' ) ) : /** * Site info codes */ function fabcontroley_site_info() { $copyright = fabulist_theme_option('copyright_text'); ?> <div class="site-info"> <div class="wrapper"> <?php if ( ! empty( $copyright ) ) : ?> <div class="copyright"> <p> <?php echo fabulist_santize_allow_tags( $copyright ); ?> </p> <p> <?php printf( esc_html__( ' Fabulist by %1$sShark Themes%2$s. Desenvolvido por @glllcs.', 'fabulist' ), '<a href="' . esc_url( 'http://sharkthemes.com/' ) . '" target="_blank">','</a>' ); if ( function_exists( 'the_privacy_policy_link' ) ) { the_privacy_policy_link( ' | ' ); } ?> </p> </div><!-- .copyright --> <?php endif; ?> </div><!-- .wrapper --> </div><!-- .site-info --> <?php } endif; add_action( 'fabcontroley_site_info_action', 'fabcontroley_site_info', 10 );<file_sep>/footer.php <?php /** * The template for displaying the footer * * Contains the closing of the #content div and all content after. * * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials * * @package fabulist */ /** * fabulist_site_content_ends_action hook * * @hooked fabulist_site_content_ends - 10 * */ do_action( 'fabulist_site_content_ends_action' ); /** * fabulist_footer_start_action hook * * @hooked fabulist_footer_start - 10 * */ do_action( 'fabulist_footer_start_action' ); /** * fabulist_site_info_action hook * * @hooked fabulist_site_info - 10 * */ do_action( 'fabcontroley_site_info_action' ); /** * fabulist_footer_ends_action hook * * @hooked fabulist_footer_ends - 10 * @hooked fabulist_slide_to_top - 20 * */ do_action( 'fabulist_footer_ends_action' ); /** * fabulist_page_ends_action hook * * @hooked fabulist_page_ends - 10 * */ do_action( 'fabulist_page_ends_action' ); wp_footer(); /** * fabulist_body_html_ends_action hook * * @hooked fabulist_body_html_ends - 10 * */ do_action( 'fabulist_body_html_ends_action' );
217734c42405cd7abe2168ad96333d99e2ebcc34
[ "PHP" ]
2
PHP
glllcs/fabcontroley
7838c927e4e354ac17608c90c958aacc006d2a51
9cedba6e824b593971ff13e7ebc8acf809f35075
refs/heads/master
<repo_name>deepaknalore/DistributedSystems-P2<file_sep>/Socket/client_threaded.py #Taken from: https://www.geeksforgeeks.org/socket-programming-multi-threading-python/ # Import socket module import time import socket import argparse from datetime import datetime ipList = ["c220g1-030811.wisc.cloudlab.us", "ms0619.utah.cloudlab.us", "clnode216.clemson.cloudlab.us"] def Main(args): # local host IP '127.0.0.1' host = '127.0.0.1' # Define the port on which you want to connect port = 12345 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # connect to server on local computer s.connect((args.server_host,port)) start_time = time.time() number_of_minutes = 10 while time.time() < (start_time + (60 * number_of_minutes)): # message you send to server #message = "I am the client speaking " # message sent to server #client_id = input("Enter the client id for testing purpose\n") #message = message + str(client_id) message = "Hi" time_to_log = datetime.utcnow() time_before_send = time.time() s.send(message.encode('ascii')) # messaga received from server data = s.recv(1024) time_after_receive = time.time() print(data) #time_after_receive = float(data.decode('ascii').split(':')[1].strip(' ')) latency = ((time_after_receive - time_before_send)*1000) / 2.0 with open(str(args.server_host) + ".csv", "a") as fd: fd.write(str(time_to_log) + "," + str(latency) + "\n") s.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='To get the server host') parser.add_argument('--server_host', type=str, default='127.0.0.1') args = parser.parse_args() print(args.server_host) Main(args) <file_sep>/Implementation/app/routes1.py from app import app from datetime import datetime from flask import request, render_template, jsonify, make_response, abort from collections import defaultdict from _thread import * import time import logging log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) my_server_id = "wisconsin" my_cluster = "wisconsin" servers = ['wisconsin', 'clemson', 'utah'] log = [] latency_dict = defaultdict(dict) # latency_dict['wisconsin']['wisconsin'] = 0.08 # latency_dict['wisconsin']['clemson'] = 12.5 # latency_dict['wisconsin']['utah'] = 17.5 # latency_dict['clemson']['clemson'] = 0.02 # latency_dict['clemson']['wisconsin'] = 13.0 # latency_dict['clemson']['utah'] = 25.0 # latency_dict['utah']['utah'] = 0.3 # latency_dict['utah']['wisconsin'] = 18.0 # latency_dict['utah']['clemson'] = 25.0 latency_dict['wisconsin']['wisconsin'] = 82 latency_dict['wisconsin']['clemson'] = 12512 latency_dict['wisconsin']['utah'] = 17534 latency_dict['clemson']['clemson'] = 22 latency_dict['clemson']['wisconsin'] = 13056 latency_dict['clemson']['utah'] = 25124 latency_dict['utah']['utah'] = 326 latency_dict['utah']['wisconsin'] = 18822 latency_dict['utah']['clemson'] = 25024 def handleRequest(client_id, client_cluster, info): my_latency = latency_dict[client_cluster][my_cluster] all_latencies = [] for server in servers: all_latencies.append(latency_dict[client_cluster][server]) max_latency = max(all_latencies) if client_cluster == "clemson": max_latency = 100000.0 append_message = str(client_cluster) + ":" + str(client_id) + ":" + str(info) add_time = time.time() + (max_latency - my_latency + 2000)*(10**(-6)) while time.time() < add_time: continue log.append(append_message) return @app.route('/filewrite', methods = ['GET']) def fileWriter(): global log with open(my_server_id + "." + "log", 'w') as f: for entry in log: f.write(entry + "\n") log = [] return jsonify({"Request": True}), 200 @app.route('/request', methods = ['POST']) def endpoint(): if not request.json or not 'client_id' in request.json or not 'info' in request.json: abort(400) try: client_id = request.json['client_id'] client_cluster = request.json['cluster'] info = request.json['info'] my_latency = latency_dict[client_cluster][my_cluster] max_latency = my_latency for server in servers: max_latency = max(max_latency, latency_dict[client_cluster][server]) append_message = str(client_cluster) + ":" + str(client_id) + ":" + str(info) time.sleep((max_latency - my_latency + 4000)*(10**(-6))) log.append(append_message) return jsonify({"Request": True}), 200 except Exception as e: print(e) return jsonify({"Request": False}), 500 # @app.route('/initialize', methods = ['GET']) # def initialize(): # print("In main") # parser = argparse.ArgumentParser(description='To get the server host') # parser.add_argument('--server_id', type=str, default='wisconsin', description='Please enter the server cluster') # args = parser.parse_args() # my_server_id = str(args.server_id) # my_server_cluster = str(args.server_id) # start_new_thread(fileWriter, f()) <file_sep>/Implementation/app/routes.py from app import app from datetime import datetime from flask import request, render_template, jsonify, make_response, abort from collections import defaultdict from _thread import * import time my_server_id = "wisconsin" my_cluster = "wisconsin" servers = ['wisconsin', 'clemson', 'utah'] log = [] latency_dict = defaultdict(dict) latency_dict['wisconsin']['wisconsin'] = 0.08 latency_dict['wisconsin']['clemson'] = 12.5 latency_dict['wisconsin']['utah'] = 17.5 latency_dict['clemson']['clemson'] = 0.02 latency_dict['clemson']['wisconsin'] = 13 latency_dict['clemson']['utah'] = 25 latency_dict['utah']['utah'] = 0.3 latency_dict['utah']['wisconsin'] = 18 latency_dict['utah']['clemson'] = 25 def handleRequest(client_id, client_cluster, info): my_latency = latency_dict[client_cluster][my_cluster] all_latencies = [] for server in servers: all_latencies.append(latency_dict[client_cluster][server]) max_latency = max(all_latencies) append_message = str(client_cluster) + ":" + str(client_id) + ":" + str(info) if max_latency == my_latency: log.append(append_message) else: add_time = time.time() + (max_latency - my_latency)*(10**(-3)) while time.time() < add_time: continue log.append(append_message) return @app.route('/filewrite', methods = ['GET']) def fileWriter(): global log with open(my_server_id + "." + "log", 'w') as f: for entry in log: f.write(entry + "\n") log = [] return jsonify({"Request": True}), 200 @app.route('/request', methods = ['POST']) def endpoint(): if not request.json or not 'client_id' in request.json or not 'info' in request.json: abort(400) try: client_id = request.json['client_id'] client_cluster = request.json['cluster'] info = request.json['info'] start_new_thread(handleRequest, (client_id, client_cluster, info,)) return jsonify({"Request": True}), 200 except Exception as e: print(e) return jsonify({"Request": False}), 500 # @app.route('/initialize', methods = ['GET']) # def initialize(): # print("In main") # parser = argparse.ArgumentParser(description='To get the server host') # parser.add_argument('--server_id', type=str, default='wisconsin', description='Please enter the server cluster') # args = parser.parse_args() # my_server_id = str(args.server_id) # my_server_cluster = str(args.server_id) # start_new_thread(fileWriter, f()) <file_sep>/test.py import time from _thread import * l = [] previous_time = time.time() count = 0 while count < 1000: current_time = time.time() l.append((current_time-previous_time)*10**3) previous_time = current_time count += 1 print(sum(l)/len(l)) def func(): i = 1 return l = [] count = 0 while count < 1000: start_time = time.time() start_new_thread(func, ()) end_time = time.time() l.append((end_time-start_time)*10**3) count += 1 print(sum(l)/len(l)) <file_sep>/latency_info/error_timeline.py # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from matplotlib import pyplot as plt # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import os for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) # Any results you write to the current directory are saved as output. import seaborn as sns from scipy.stats import norm log1=[] log2=[] log3=[] with open('/kaggle/input/12clog1/log1.txt') as file: log1=[x.split(' ') for x in file.readlines()] with open('/kaggle/input/12clog1/log2.txt') as file: log2=[x.split(' ') for x in file.readlines()] with open('/kaggle/input/12clog1/log3.txt') as file: log3=[x.split(' ') for x in file.readlines()] cnt=0 Y=[] last=0 avg=0 print('Log sizes',len(log1),len(log2),len(log3)) for i in range(len(log2)): if log2[i][0]!=log1[i][0] or log3[i][0]!=log1[i][0]: cnt+=1 Y.append(i-last) last=i avg+=i-last sns.scatterplot(range(len(Y)),Y) mean,std=norm.fit(data=np.array(Y)) print(f'Total mismatches {cnt}') plt.ylim(0,800) print(f'mean, std: {mean},{std}')<file_sep>/Implementation/logs/compare_log.py from collections import defaultdict DIRECTORY = 'New/' files = [DIRECTORY + 'wisconsin.log', DIRECTORY + 'clemson.log', DIRECTORY + 'utah.log'] file_wise_ops = defaultdict(list) for file in files: with open(file, 'r') as f: file_wise_ops[file] = list(f) def compare_files(): length = len(file_wise_ops[files[0]]) total_count = 0 error_count = 0 for i in range(0, length): total_count += 1 val1 = file_wise_ops[files[0]][i] val2 = file_wise_ops[files[1]][i] val3 = file_wise_ops[files[2]][i] if val1 != val2 or val2 != val3 or val3 != val1: error_count += 1 return error_count*100 / total_count def get_error(list1, list2): total_count = 0 error_count = 0 for i in range(len(list1)): total_count += 1 if list1[i] != list2[i]: error_count += 1 return error_count * 100 / total_count def pair_wise_compare(): pair_wise_errors = defaultdict(lambda : defaultdict(float)) file_pairs = [[files[0], files[1]], [files[1], files[2]], [files[2], files[0]]] for file_pair in file_pairs: pair_wise_errors[file_pair[0]][file_pair[1]] = get_error(file_wise_ops[file_pair[0]], file_wise_ops[file_pair[1]]) return pair_wise_errors if __name__ == "__main__": error_percent = compare_files() print(error_percent) pair_wise_errors_dict = pair_wise_compare() for key1 in pair_wise_errors_dict: for key2 in pair_wise_errors_dict[key1]: print(key1, key2, pair_wise_errors_dict[key1][key2]) <file_sep>/Implementation/client.py from gevent import monkey; monkey.patch_all() import requests import json import random from gevent.pool import Pool p = Pool(10) # clemson utah CLUSTER = "wisconsin" CLIENT_ID = "client_1" SERVER_LIST = ["http://clnode216.clemson.cloudlab.us:5000/"] payload = {'client_id': CLIENT_ID, 'cluster': CLUSTER} headers = { 'Content-Type': 'application/json' } def fetch(server): response = requests.request("POST", server + "request", headers=headers, data=json.dumps(payload)) data = response.json() print(data) #initialize for server in SERVER_LIST: payload['info'] = random.randrange(1, 1000) fetch(server) # for i in range(100): # payload['info'] = random.randrange(1, 1000) # for server in SERVER_LIST: # p.spawn(fetch,server) # p.join() # # for server in SERVER_LIST: # requests.request("GET", server + 'filewrite') <file_sep>/Utils/ContinuousPingGenerator.py import subprocess import time from datetime import datetime pingCount = 1 count = 0 #ipList = ['www.google.com'] ipList = ["c220g1-030811.wisc.cloudlab.us", "ms0619.utah.cloudlab.us", "clnode216.clemson.cloudlab.us"] startTime = time.time() numberofMinutes = 10 def WritePingStats(): t = datetime.utcnow() for ip in ipList: p = subprocess.Popen(["ping", "-c " + str(pingCount),ip], stdout = subprocess.PIPE) out = str(p.communicate()[0]) timeUnit = out.split()[-1][:2] averageLatency = str(out.split()[-2]).split('/')[1] maxLatency = str(out.split()[-2]).split('/')[2] stdDev = str(out.split()[-2]).split('/')[3] print(str(maxLatency) + str(timeUnit)) print(str(averageLatency) + str(timeUnit)) print(stdDev) with open(str(ip) + ".csv", "a") as fd: fd.write(str(t) + "," + averageLatency + "," + maxLatency + "," + stdDev + "\n") while time.time() < (startTime + (60 * numberofMinutes)): WritePingStats() <file_sep>/Socket/client.py #Taken from: https://www.geeksforgeeks.org/socket-programming-python/ import socket import time client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('0.0.0.0', 8080)) count = 1 while True: count += 1 if count == 5: client.close() client.send(b"I am CLIENT") time.sleep(5) from_server = client.recv(4096).decode("utf-8") #client.close() print(from_server)<file_sep>/Readme.md #Distributed System - Project 2
b04982789496611589b05010560cc668739076d9
[ "Markdown", "Python" ]
10
Python
deepaknalore/DistributedSystems-P2
56824142f39b5ade0588faff96edd410ab7e2f72
3464ca72d5f2ad2978f9cf173f6ecf4b080ae463
refs/heads/main
<file_sep>package com.lwazir.project.schoolManagementsystem.errors; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.BAD_REQUEST) public class UserAlreadyExist extends RuntimeException { public UserAlreadyExist(String message) { super(message); // TODO Auto-generated constructor stub } } <file_sep>import { ThreeSixtyOutlined } from "@material-ui/icons"; import { Alert } from "@material-ui/lab"; import React,{ Component } from "react" import CourseService from "../../api/CourseService"; import "./courses.css"; import IconButton from '@material-ui/core/IconButton'; import Collapse from '@material-ui/core/Collapse'; import Button from '@material-ui/core/Button'; import CloseIcon from '@material-ui/icons/Close'; import NewCourse from './NewCourse'; import CustomAlert from "../utility/Alerts/CustomAlerts"; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from "../../Authentication/AuthenticationService"; import EditCourse from "./EditCourse"; export default class ManageCourses extends Component{ constructor(props){ super(props) this.state={ courses:[], selectedCourseId:'', selectedCourse:'', showModal:false, showEditModal:false, message:null, errorMessage:null } this.clickHandler = this.clickHandler.bind(this) this.setModalShow = this.setModalShow.bind(this) this.addCourse = this.addCourse.bind(this) this.setEditModalShow = this.setEditModalShow.bind(this); this.onEditCourse = this.onEditCourse.bind(this); this.updateCourse = this.updateCourse.bind(this); } addCourse(){ this.setModalShow() //this.props.history.push('/editUser/-1') } onEditCourse(){ this.setEditModalShow() } updateCourse(newCourseName){ CourseService.editCourse(this.state.selectedCourseId,newCourseName).then( response=>{ this.setEditModalShow(); } ).catch(error=>console.log(error)) } setEditModalShow(){ if(this.state.showEditModal){ this.setState({ showEditModal:false }) this.refreshCoursesList(); } else{ this.setState({ showEditModal:true }) } } componentDidMount(){ this.refreshCoursesList(); } refreshCoursesList= () => { AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); CourseService.executeRetrieveAllCoursesService() .then( response=>{ console.log(response.data) this.setState({ courses:response.data }) } ) } setModalShow(){ if(this.state.showModal){ this.setState({ showModal:false }) this.refreshCoursesList(); } else{ this.setState({ showModal:true }) } } onDelete = (id) => { CourseService.executeDeleteCourseById(id).then(response=>{ console.log(response.data); this.refreshCoursesList(); }).catch(error => { this.setState({ errorMessage:'The Course Can not be deleted!' }) }); } onHide = () => { this.setState({ errorMessage:null }) } clickHandler(courseId,name){ this.props.history.push(`/admin/courses/${courseId}/${name}`) } render(){ return ( <> { this.state.errorMessage!=null && <CustomAlert errorMessage={this.state.errorMessage} severity='error' onCancel = {this.onHide}/> } <NewCourse show={this.state.showModal} onHide={this.setModalShow}/> <EditCourse show={this.state.showEditModal} onHide={this.setEditModalShow} courseName={this.state.selectedCourse} onUpdate ={this.updateCourse} /> <div className="container"> <div className="scroller"> <table className="table"> <thead> <tr> <th>Course Id</th> <th>Course Name</th> </tr> </thead> <tbody> { this.state.courses.map( (course,index)=> <tr key={index}> <td>{course.courseId}</td> <td>{course.courseName}</td> <td><button className="btn btn-warning" onClick= {()=>{this.onDelete(course.courseId)}}>Delete</button></td> <td><button className="btn btn-success" onClick= {()=>{ this.setState({ selectedCourse:course.courseName, selectedCourseId:course.courseId },()=> this.onEditCourse()) }} >Update</button></td> <td><button className="btn btn-success" onClick= {()=>{this.clickHandler(course.courseId,course.courseName)}} >View Details</button></td> </tr> ) } </tbody> </table> <button className="btn btn-success" style={{ position:"relative",left:5 ,marginRight:10}} onClick={this.addCourse}> New Course </button> </div> </div> </> ); } }<file_sep>import { Button, InputBase, ListItem } from '@material-ui/core'; import {Component} from 'react'; import CourseService from '../../api/CourseService'; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from '../../Authentication/AuthenticationService'; import ListCardItem from '../ListCardItem'; import SearchBar from '../utility/SearchBar'; import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box' import Grid from '@material-ui/core/Grid'; import { CssBaseline } from '@material-ui/core'; import '../PupilList.css'; import SelectPupil from './SelectPupilModal'; import DeleteIcon from '@material-ui/icons/Delete'; import { AddOutlined, ArchiveRounded, EditOutlined, PageviewOutlined } from '@material-ui/icons'; import IconButton from '@material-ui/core/IconButton'; import Tooltip from '@material-ui/core/Tooltip'; import ArchiveIcon from '@material-ui/icons/Archive'; import AddSubject from './AddSubject'; import SubjectService from '../../api/SubjectService'; import CustomAlert from '../utility/Alerts/CustomAlerts'; export default class CourseDetails extends Component{ constructor(props){ super(props) this.state={ id:this.props.match.params.id, courseName:this.props.match.params.name, courseDetials:[], pupils:[], showModal:false, message:null, alertMessage:'', showSuccess:false, showError:false, showAddSubject:false } } componentDidMount(){ this.refreshSubjects(); } refreshSubjects = () => { AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); this.getAllPupilsByCourseId(this.state.id); CourseService.executeCourseById(this.state.id).then( response=>{ console.log('Subjects: '+response.data) this.setState({ courseDetials:response.data, //subjects:response.data.subjects }) console.log(this.state.courseDetials); }); } setModalShow = ()=>{ this.props.history.push(`/courses/${this.state.id}/${this.state.courseName}/pupils`); } getAllPupilsByCourseId = (courseId) => { CourseService.executeAllPupilByCourseId(courseId) .then( response => { this.setState({ pupils:response.data, }) console.log(this.state.pupils); } ) } deAssignPupilFromCourse = (courseId,pupilId) =>{ console.log("CourseId :"+courseId+" pupilId: "+pupilId); CourseService.deAssignPupil(courseId,pupilId).then( (response) => { console.log(response); // if(response.status==200){ this.refreshSubjects(); // } } ) } deleteSubject = (courseId,subjectName)=>{ console.log("deleteSubject"); CourseService.deleteSubjectbyId(courseId,subjectName).then( (response) => { console.log(response.data); this.refreshSubjects(); } ).catch(error=>{ console.log(error); }); } setShowAddSubject = () =>{ const subId ='new' this.props.history.push(`/courses/${this.state.id}/${this.state.courseName}/add/${subId}`) } archiveSubject = (name)=>{ let requestBody={ archiveStatus:true, subjectName:name } SubjectService.archiveSubject(requestBody).then( response =>{ //console.log(response.statusText+' '+response.status) this.setState({ showSuccess: true, alertMessage:'Subject is Archived!' }) this.refreshSubjects(); } ).catch(error=>{ this.setState({ showError:true, alertMessage:"This Subject Can not be Archived" }) }) } onHide = ()=>{ this.setState({ showError:false, showSuccess:false, alertMessage:'' }) } render(){ return ( <> <div className="root"> <CssBaseline/> <Grid container spacing={3} direction="row" justify="center" alignItems="center" > <div className="scroller"> {this.state.showError && <CustomAlert errorMessage={this.state.alertMessage} severity='error' onCancel = {this.onHide}/>} {this.state.showSuccess && <CustomAlert errorMessage={this.state.alertMessage} severity='success' onCancel = {this.onHide}/>} <Grid item xs={12}> <Paper elevation={2} className="paper"> <Box> <h2>{this.state.courseName}</h2> <div className="containter"> <Button style={{display:'flex',float:'right'}} startIcon={<AddOutlined />} color="primary" variant="contained" onClick={this.setModalShow}>Add Pupil</Button> </div> <ul className="pupilList"> { this.state.pupils.length==0?<h3>No Pupils Assigned Yet!!</h3>: this.state.pupils.map( (pupil,index)=> <ListCardItem key={index} name={pupil.firstName +' '+pupil.lastName} avgGrade ={pupil.avgGrade} onDeAssign={()=>this.deAssignPupilFromCourse(this.state.id,pupil.pupilId)}/> ) } </ul> </Box> </Paper> </Grid> <Grid item xs={12}> <Paper elevation={2} className="paper"> <Box> <h3>List Of Subjects: </h3> <table className="table"> <thead> <tr> <th>Course Id</th> <th>Subject Name</th> <th>Is Archived</th> <th>Lecturer Name</th> <th className = "addSubject"> <IconButton onClick = {this.setShowAddSubject}> <Tooltip title="Add New Subject"> <AddOutlined/> </Tooltip> </IconButton> </th> </tr> </thead> <tbody> { this.state.courseDetials.map( (c, index) => <tr key= {index}> <td>{c.courseId}</td> <td>{c.subjectName}</td> <td>{c.archived?'Yes' : <IconButton onClick={()=>this.archiveSubject(c.subjectName)}> <Tooltip title="Archive Subject"> <ArchiveRounded/> </Tooltip> </IconButton> } </td> <td>{c.teacherFirstName } {c.teacherLastName}</td> <td> {!c.archived && <IconButton onClick={()=>this.deleteSubject(c.courseId,c.subjectName)}> <Tooltip title="Delete"> <DeleteIcon/> </Tooltip> </IconButton> } </td> <td> {!c.archived && <IconButton onClick={()=>{this.props.history.push(`/course/${this.state.id}/${this.state.courseName}/edit/${c.subjectName}`)}}> <Tooltip title="Edit"> <EditOutlined/> </Tooltip> </IconButton> } </td> </tr> ) } </tbody> </table> </Box> </Paper> </Grid> </div> </Grid> </div> </> ); } }<file_sep>package com.lwazir.project.schoolManagementsystem.model.joins.dto; public class GetTeacherIdByUsername { private Long teacherId; private String firstName; private String LastName; private Long id; public GetTeacherIdByUsername(Long teacherId, String firstName, String lastName, Long id) { super(); this.teacherId = teacherId; this.firstName = firstName; LastName = lastName; this.id = id; } public Long getTeacherId() { return teacherId; } public void setTeacherId(Long teacherId) { this.teacherId = teacherId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return LastName; } public void setLastName(String lastName) { LastName = lastName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } <file_sep>import React,{Component} from 'react' import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box' import Grid from '@material-ui/core/Grid'; import { Button, InputBase, ListItem } from '@material-ui/core'; import { CssBaseline } from '@material-ui/core'; import Typography from '@material-ui/core/Typography'; import TeacherService from '../../api/TeacherService'; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from '../../Authentication/AuthenticationService'; import PageviewSharpIcon from '@material-ui/icons/PageviewSharp'; import DeleteIcon from '@material-ui/icons/Delete'; import { AddOutlined, ArchiveRounded, ArrowRight, EditOutlined, PageviewOutlined, Refresh } from '@material-ui/icons'; import IconButton from '@material-ui/core/IconButton'; import Tooltip from '@material-ui/core/Tooltip'; import PupilService from '../../api/PupilService'; export default class PupilDashboard extends Component{ constructor(props){ super(props) this.state ={ id:'', testRecords:[], username:this.props.match.params.name } this.loadPupilIdByUsername = this.loadPupilIdByUsername.bind(this); this.loadPupilSubjectsWithAvgGrades = this.loadPupilSubjectsWithAvgGrades.bind(this); this.refresh = this.refresh.bind(this); this.viewDetails = this.viewDetails.bind(this); } componentDidMount(){ this.refresh() } refresh(){ AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); this.loadPupilIdByUsername() // this.loadPupilSubjectsWithAvgGrades() } loadPupilIdByUsername(){ PupilService.fetchPupilDetailsByPupilUsername(this.state.username).then( response=>{ this.setState({ id:response.data.pupilId },()=>this.loadPupilSubjectsWithAvgGrades()) console.log(response.data.pupilId) } ).catch(error=>console.log(error)) } loadPupilSubjectsWithAvgGrades(){ console.log(this.state.id) PupilService.fetchAssignedSubjectWithAvgGrades(this.state.id).then( response=>{ this.setState({ testRecords:response.data }) console.log(this.state.testRecords) } ) } viewDetails(subjectName){ this.props.history.push(`/${this.state.id}/subjectView/${subjectName}`) } render(){ return ( <div className="root"> <CssBaseline/> <Grid container spacing={1} > <Grid item xs={12}> <Paper elevation={2} className="paper"> <Box> <table className="table"> <thead> <tr> <th>Subject Name</th> <th>Average Grade</th> </tr> </thead> <tbody> { this.state.testRecords.map( testRecord => <tr> <td>{testRecord.subjectName}</td> <td>{testRecord.grade==null?0:testRecord.grade}</td> <td> <IconButton onClick={()=>this.viewDetails(testRecord.subjectName)}> <Tooltip title="Click To View Details.."> <ArrowRight/> </Tooltip> </IconButton> </td> </tr> ) } </tbody> </table> </Box> </Paper> </Grid> </Grid> </div> ); } }<file_sep>package com.lwazir.project.schoolManagementsystem.model.joins.dto; public class ArchiveSubjectDTO { private boolean archiveStatus; private String subjectName; public ArchiveSubjectDTO(boolean archiveStatus, String subjectName) { super(); this.archiveStatus = archiveStatus; this.subjectName = subjectName; } public boolean isArchiveStatus() { return archiveStatus; } public void setArchiveStatus(boolean archiveStatus) { this.archiveStatus = archiveStatus; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } } <file_sep>package com.lwazir.project.schoolManagementsystem.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import com.lwazir.project.schoolManagementsystem.model.Subject; import com.lwazir.project.schoolManagementsystem.model.Teacher; import com.lwazir.project.schoolManagementsystem.model.joins.dto.PupilsAssignedToSubjectByIdDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.SubjectByCourseIdDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.SubjectDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.SubjectsPerTeacherDTO; @Transactional public interface SubjectRepository extends JpaRepository<Subject,String> { @Query("SELECT new com.lwazir.project.schoolManagementsystem.model.joins.dto.SubjectDTO(" + " s.subjectName, " + "s.subjectDescription, " + "s.lecturer.id, " + "s.isArchived, " + "u.firstName, " + "u.LastName) " + "FROM Subject as s Left Join User as u on s.lecturer.id = u.teacher.id " +"where s.subjectName = :name" ) SubjectDTO fetchSubjectDetails(@Param("name") String subjectName); @Query( "SELECT new com.lwazir.project.schoolManagementsystem.model.joins.dto.PupilsAssignedToSubjectByIdDTO( " + "map.pupilId, " + "u.firstName, " + "u.LastName ) " + "From PupilsSubjectsMap as map " + "Inner Join Pupil as p " + "on p.id=map.pupilId " + "Inner Join User as u " + "on u.id=p.user.id " + "where map.subjectId=:subjectId order by map.pupilId ASC" ) List<PupilsAssignedToSubjectByIdDTO> getAllPupilBySubjectId(@Param("subjectId") String subjectId); @Modifying @Query("update Subject as s set " + "s.isArchived = :value" + " where s.subjectName = :subjectName ") void archiveSubject( @Param("value") boolean archive, @Param("subjectName") String subjectName); @Query("Select new com.lwazir.project.schoolManagementsystem.model.joins.dto.SubjectByCourseIdDTO( s.subjectName ) from Subject as s where s.course.courseId=:courseId") List<SubjectByCourseIdDTO> fetchAllSubejectByCourseId(@Param("courseId") Long courseId); @Modifying @Query("update Subject as s set " + "s.subjectName = :value, " + "s.subjectDescription= :description" + " where s.subjectName = :subjectName") void updateDescriptionAndNameSubject( @Param("value") String modifiedSubjectName, @Param("description") String desc, @Param("subjectName") String subjectName); @Modifying @Query("update Subject as s set " + "s.course.courseId = :value, " + "s.lecturer.id= :teacherId" + " where s.subjectName = :subjectName") void deassignCourseAndTeacherFromSubject( @Param("value") Long courseId, @Param("teacherId") Long teacherId, @Param("subjectName") String subjectName); //TODO:Fetching Active and Archived Subjects @Query("Select new com.lwazir.project.schoolManagementsystem.model.joins.dto.SubjectsPerTeacherDTO( " + "s.course.courseId, " + "c.courseName, " + "s.subjectName, " + "s.isArchived ) " + "From Subject as s" + " Left Join Course as c " + "on c.courseId=s.course.courseId " + "where s.lecturer.id = :teacherId and s.isArchived=false") List<SubjectsPerTeacherDTO> fetchAllActiveSubjectsByTeacherId(@Param("teacherId") Long teacherId); @Query("Select new com.lwazir.project.schoolManagementsystem.model.joins.dto.SubjectsPerTeacherDTO( " + "s.course.courseId, " + "c.courseName, " + "s.subjectName, " + "s.isArchived ) " + "From Subject as s" + " Left Join Course as c " + "on c.courseId=s.course.courseId " + "where s.lecturer.id = :teacherId and s.isArchived=true") List<SubjectsPerTeacherDTO> fetchAllArchivedSubjectsByTeacherId(@Param("teacherId") Long teacherId); } <file_sep>import { Component } from "react"; import {Link} from 'react-router-dom' import { withRouter } from 'react-router'; import AuthenticationService, { USER_ID, USER_ROLE } from "../../Authentication/AuthenticationService"; class HeaderComponent extends Component{ constructor(props){ super(props) this.state={ name:sessionStorage.getItem(USER_ID), } } render(){ const isUserLoggedIn = AuthenticationService.isUserLoggedIn(); console.log(isUserLoggedIn); return( <header> <nav className="navbar navbar-expand-md navbar-dark bg-dark"> <ul className="navbar-nav"> {(sessionStorage.getItem("USER_ROLE") ==="ADMIN" && isUserLoggedIn )&& <li><Link className="nav-link" to={`/admin/dashboard/${this.state.name}`}>Home</Link></li>} {( sessionStorage.getItem("USER_ROLE") ==="ADMIN" && isUserLoggedIn) && <li><Link className="nav-link" to="/users">Users</Link></li>} </ul> <ul className="navbar-nav navbar-collapse justify-content-end"> {!isUserLoggedIn && <li><Link className="nav-link" to="/login">Login</Link></li>} {isUserLoggedIn && <li><Link className="nav-link" to="/logout" onClick={AuthenticationService.logout}>Logout</Link></li>} </ul> </nav> </header> ); } } export default withRouter(HeaderComponent);<file_sep>import { ThreeSixtyOutlined } from "@material-ui/icons"; import { Alert } from "@material-ui/lab"; import React,{ Component } from "react" import IconButton from '@material-ui/core/IconButton'; import Collapse from '@material-ui/core/Collapse'; import Button from '@material-ui/core/Button'; import CloseIcon from '@material-ui/icons/Close'; export default function CustomAlert(props){ return ( <Collapse in={props.errorMessage!=null}> <Alert severity={props.severity} action={ <IconButton aria-label="close" color="inherit" size="small" onClick={() => { props.onCancel(); }} > <CloseIcon fontSize="inherit" /> </IconButton> } > {props.errorMessage} </Alert> </Collapse> ); }<file_sep>package com.lwazir.project.schoolManagementsystem.utility; import java.awt.Color; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import java.util.stream.Stream; import javax.servlet.http.HttpServletResponse; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.lwazir.project.schoolManagementsystem.model.User; public class UserPDFGenerator { public static ByteArrayInputStream UserPDFReport (List<User> users) { Document document = new Document(); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { PdfWriter.getInstance(document, out); document.open(); // Add Text to PDF file -> Font font = FontFactory.getFont(FontFactory.COURIER, 14, BaseColor.BLACK); Paragraph para = new Paragraph("Users Table", font); para.setAlignment(Element.ALIGN_CENTER); document.add(para); document.add(Chunk.NEWLINE); PdfPTable table = new PdfPTable(4); // Add PDF Table Header -> Stream.of("ID", "Name", "Role","CreatedAt").forEach(headerTitle -> { PdfPCell header = new PdfPCell(); Font headFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD); header.setBackgroundColor(BaseColor.LIGHT_GRAY); header.setHorizontalAlignment(Element.ALIGN_CENTER); header.setBorderWidth(2); header.setPhrase(new Phrase(headerTitle, headFont)); table.addCell(header); }); for (User user : users) { PdfPCell idCell = new PdfPCell(new Phrase(user.getId(). toString())); idCell.setPaddingLeft(4); idCell.setVerticalAlignment(Element.ALIGN_MIDDLE); idCell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(idCell); PdfPCell nameCell = new PdfPCell(new Phrase (user.getName())); nameCell.setPaddingLeft(4); nameCell.setVerticalAlignment(Element.ALIGN_MIDDLE); nameCell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(nameCell); PdfPCell roleCell = new PdfPCell(new Phrase (String.valueOf(user.getRole()))); roleCell.setVerticalAlignment(Element.ALIGN_MIDDLE); roleCell.setHorizontalAlignment(Element.ALIGN_RIGHT); roleCell.setPaddingRight(4); table.addCell(roleCell); PdfPCell createdAtCell = new PdfPCell(new Phrase (String.valueOf(user.getCreatedAt().toGMTString()))); createdAtCell.setVerticalAlignment(Element.ALIGN_MIDDLE); createdAtCell.setHorizontalAlignment(Element.ALIGN_RIGHT); createdAtCell.setPaddingRight(4); table.addCell(createdAtCell); } document.add(table); document.close(); } catch (DocumentException e) { } return new ByteArrayInputStream(out.toByteArray()); } } <file_sep>package com.lwazir.project.schoolManagementsystem.model.joins.dto; public class PupilsAssignedToSubjectByIdDTO { private Long pupilId; private String firstName; private String lastName; public PupilsAssignedToSubjectByIdDTO(Long pupilId, String firstName, String lastName) { super(); this.pupilId = pupilId; this.firstName = firstName; this.lastName = lastName; } public Long getPupilId() { return pupilId; } public void setPupilId(Long pupilId) { this.pupilId = pupilId; } 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; } } <file_sep>import React,{Component} from 'react' import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box' import Grid from '@material-ui/core/Grid'; import { Button, InputBase, ListItem } from '@material-ui/core'; import './css/grid.css'; import { CssBaseline } from '@material-ui/core'; import Typography from '@material-ui/core/Typography'; import TeacherService from '../../api/TeacherService'; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from '../../Authentication/AuthenticationService'; import PageviewSharpIcon from '@material-ui/icons/PageviewSharp'; import DeleteIcon from '@material-ui/icons/Delete'; import { AddOutlined, ArchiveRounded, EditOutlined, PageviewOutlined, PictureAsPdf } from '@material-ui/icons'; import IconButton from '@material-ui/core/IconButton'; import Tooltip from '@material-ui/core/Tooltip'; import NewTest from './NewTest'; import EditTest from './EditTest'; import SubjectService from '../../api/SubjectService'; export default class SubjectDashboard extends Component{ constructor(props){ super(props) this.state ={ test_name:'', test_id:'', showEditTestModal:false, subjectName:this.props.match.params.subjectName, teacherName:this.props.match.params.name, showModal:false, subjectDetails:{}, pupils:[], tests:[] } this.loadPupilsBySubjectID = this.loadPupilsBySubjectID.bind(this); this.loadSubjectDetails = this.loadSubjectDetails.bind(this); this.addTokentoAuthenticatioHeader = this.addTokentoAuthenticatioHeader.bind(this); this.loadAllTestBySubjectName = this.loadAllTestBySubjectName.bind(this); this.onHide = this.onHide.bind(this); this.showNewTestModal = this.showNewTestModal.bind(this); this.refresh = this.refresh.bind(this); this.onHideEditTestModal = this.onHideEditTestModal.bind(this); this.delete = this.delete.bind(this); this.viewDetails = this.viewDetails.bind(this); this.exportPdf = this.exportPdf.bind(this); } viewDetails(id,testName,subjectName){ this.props.history.push(`/test/subject/${subjectName}/${id}/${testName}`); } onHide(){ this.setState({ showModal:false, }) this.refresh(); } showNewTestModal(){ this.setState({ showModal:true }) } componentDidMount(){ this.refresh(); } refresh(){ this.addTokentoAuthenticatioHeader(); this.loadSubjectDetails(); this.loadPupilsBySubjectID(); this.loadAllTestBySubjectName(); } addTokentoAuthenticatioHeader(){ AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); } loadAllTestBySubjectName(){ TeacherService.fetchAllTestsBySubjectName(this.state.subjectName) .then(response=>{ this.setState({ tests:response.data }) }) .catch(error=>console.log(error)) } loadSubjectDetails(){ SubjectService.getSubjectDetailsByName(this.state.subjectName).then( response=>{ this.setState({ subjectDetails:response.data }) console.log(this.state.subjectDetails) } ).catch(error=>console.log(error)) } delete(testId){ console.log(`${testId}`); TeacherService.deleteTest(testId).then( response=>{ this.refresh(); } ).catch(error=>console.log(error)) } loadPupilsBySubjectID(){ TeacherService.getAllPupilsWithGrades(this.state.subjectName).then(response=>{ this.setState({ pupils:response.data }) }).catch(error=>{ console.log(error); }) } onHideEditTestModal(){ this.setState({ showEditTestModal:false, test_name:'' }) this.refresh(); } exportPdf(){ TeacherService.exportPupilListWithAverageGrade(this.state.subjectName) .then(response => { console.log(response); const filename = response.headers['content-disposition'].split('filename=')[1]; console.log("FileName: "+filename); const blob = new Blob([response.data],{type:response.data.type}); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.setAttribute('download', filename); //or any other extension document.body.appendChild(link); link.click(); link.remove(); window.URL.revokeObjectURL(url); }); } render(){ return ( <div className="root"> <NewTest show={this.state.showModal} subjectName={this.state.subjectName} onHide={this.onHide} /> <EditTest show={this.state.showEditTestModal} subjectName={this.state.subjectName} onHide={this.onHideEditTestModal} testId={this.state.test_id} testName={this.state.test_name} /> <CssBaseline/> <Grid container spacing={3} direction="row" justify="center" alignItems="center" > <Grid item xs={4}> <Paper elevation={3} className="paper"> <Box> <Typography variant='h5' className="heading">{this.state.subjectName}</Typography> <Typography variant ='subtitle1' className="subtext"><b>Tutor: </b>{this.state.teacherName}</Typography> <Typography variant ='subtitle2' align="left" className="subtext"><b>Description: </b> {this.state.subjectDetails.description==null?'No Description':this.state.subjectDetails.description}</Typography> <Typography variant ='subtitle2' align="left" className="subtext"><b>Archived: </b>{this.state.subjectDetails.is_archived==true?'Yes':'No'}</Typography> </Box> </Paper> </Grid> <Grid item xs={8}> <Paper elevation={2} className="paper"> <Box> <table className="table"> <thead> <tr> <th>Pupil Id</th> <th>Pupil Name</th> <th>Avg Grade</th> </tr> </thead> <tbody> { this.state.pupils.length==0? <Typography variant="h6" align="center">No Pupils are Assigned to this Subject!</Typography> : this.state.pupils.map( pupil=> <tr> <td>{pupil.pupilId}</td> <td>{`${pupil.pupilFirstName} ${pupil.pupilLastName}`}</td> <td>{pupil.avgGrade==null?0:pupil.avgGrade}</td> </tr> ) } </tbody> </table> </Box> </Paper> </Grid> <Grid item xs={12}> <Paper className="paper" elevation={2}> {!this.state.subjectDetails.is_archived && <Button style={{float:'right',marginTop:10,marginRight:10,marginBottom:10,}} startIcon={<AddOutlined />} color="primary" variant="contained" onClick={this.showNewTestModal} > Add Test </Button>} <Box> <table className="table"> <thead> <tr> <th>Test Id</th> <th>Test Name</th> <th>createdAt</th> </tr> </thead> <tbody> { this.state.tests.map( test=> <tr> <td>{test.id}</td> <td>{`${test.testName}`}</td> <td>{`${test.createdAt}`}</td> {!this.state.subjectDetails.is_archived && <td> <IconButton onClick={()=>this.delete(test.id)}> <Tooltip title="Delete Test"> <DeleteIcon/> </Tooltip> </IconButton> </td>} <td> <IconButton onClick={()=>this.viewDetails(test.id,test.testName,this.state.subjectName)}> <Tooltip title="View Details of this test!"> <PageviewSharpIcon/> </Tooltip> </IconButton> </td> {!this.state.subjectDetails.is_archived && <td> <IconButton onClick={()=>{ let id =test.id; let name= test.testName; console.log(`Icon Button:${id} ${name}`) this.setState({ test_id: id, test_name: name },function(){ console.log(`Icon Button: checking state: ${this.state.test_id} ${this.state.test_name}`) this.setState({ showEditTestModal:true }) }) }}> <Tooltip title="Edit"> <EditOutlined/> </Tooltip> </IconButton> </td>} </tr> ) } </tbody> </table> </Box> </Paper> </Grid> </Grid> </div> ); } }<file_sep>import React,{ Component } from "react"; import UsersListComponent from "./AdminView/UsersListComponent"; import {BrowserRouter as Router,Route, Switch, Link} from 'react-router-dom' import HelloWorldService from "../api/HelloWorldService"; import AuthenticationService from "../Authentication/AuthenticationService"; export default class WelcomePage extends Component { constructor(props){ super(props) this.retrieveHelloWorldBeanMessage = this.retrieveHelloWorldBeanMessage.bind(this) this.helloWorldSuccessMessage = this.helloWorldSuccessMessage.bind(this) this.retrieveHelloWorldBeanPathVariableMessage = this.retrieveHelloWorldBeanPathVariableMessage.bind(this) this.getExpiryDate = this.getExpiryDate.bind(this) this.state ={ welcomeMessage : '' } } getExpiryDate(){ return AuthenticationService.getExpiryDateFromToken(); } render(){ return ( <> <h1>Welcome {sessionStorage.getItem("USER_ROLE")} And Expiry Date is :{this.getExpiryDate()}!</h1> { sessionStorage.getItem("USER_ROLE") == "ADMIN" && <div className="container"> {this.props.match.params.name}.You Can Manage all users <Link to="/users">here</Link> </div>} <div className="container"> Click <button onClick={this.retrieveHelloWorldBeanPathVariableMessage} className="btn btn-success">here</button> to get a customized welcome message! </div> <div className="container"> {this.state.welcomeMessage} </div> </> ); } retrieveHelloWorldBeanMessage(){ HelloWorldService.executeHelloWorldBeanService() .then(response => this.helloWorldSuccessMessage(response)); } retrieveHelloWorldBeanPathVariableMessage(){ HelloWorldService.executeHelloWorldBeanPathVariableService(this.props.match.params.name) .then(response => this.helloWorldSuccessMessage(response)) .catch(error => this.helloWorldErrorMessage(error)); } helloWorldSuccessMessage(response){ console.log(response); this.setState({ welcomeMessage:response.data.message }); } helloWorldErrorMessage(error){ console.log(error.response); this.setState({ welcomeMessage:error.response.data.details }); } }<file_sep>insert into User values (6,'goyal',sysdate(),'aditya','$2a$10$lEeILILXBEG41X8XUBN/gee86FGTYV3BuATbhjpFDaeqSMK8XHfFC','PUPIL','agoyal',null) insert into User values (7,'shukla',sysdate(),'susheel','$2a$10$lEeILILXBEG41X8XUBN/gee86FGTYV3BuATbhjpFDaeqSMK8XHfFC','PUPIL','sushukla',null) insert into Teacher values (1) insert into Teacher values (2) insert into Teacher values (3) insert into User values (8,'Wilson',sysdate(),'Sam','$2a$10$lEeILILXBEG41X8XUBN/gee86FGTYV3BuATbhjpFDaeqSMK8XHfFC','TEACHER','teacher1',1) insert into User values (9,'White',sysdate(),'Mike','$2a$10$lEeILILXBEG41X8XUBN/gee86FGTYV3BuATbhjpFDaeqSMK8XHfFC','TEACHER','teacher2',2) insert into User values (10,'Muller',sysdate(),'Angela','$2a$10$lEeILILXBEG41X8XUBN/gee86FGTYV3BuATbhjpFDaeqSMK8XHfFC','TEACHER','teacher3',3) insert into Pupil values(2,0,null,7) insert into Pupil values(1,0,null,6) insert into Course values(1,'Master in Automotive Software Engineering') insert into Course values(2,'Master in Web Engineering') insert into Subject values('Formal Specification And Verfication',false,'This is basics Formal Specification for Automive softwares',1,1) insert into Subject values('Realtime Systems',false,'Introuction to Realtime Time System and scheduling policies',1,1) insert into Subject values('Automotive Software Engineering',false,'Introduction to principle of Automotive Software Technology',1,2) insert into Subject values('Data Structure and Algorithms',false,'Introduction to Data Structure and Different Algorithms',2,1) insert into Subject values('Database Management Systems',false,'Basic Concepts of DBMS',2,1) insert into Subject values('Neurocomputing',false,'Breif Introduction to Deep Learning and Machine Learning',2,2) <file_sep>package com.lwazir.project.schoolManagementsystem.controllers; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RestController; import com.lwazir.project.schoolManagementsystem.model.Pupil; import com.lwazir.project.schoolManagementsystem.model.PupilTestRecord; import com.lwazir.project.schoolManagementsystem.model.PupilsSubjectsMap; import com.lwazir.project.schoolManagementsystem.model.Subject; import com.lwazir.project.schoolManagementsystem.model.Test; import com.lwazir.project.schoolManagementsystem.model.User; import com.lwazir.project.schoolManagementsystem.model.joins.dto.AllAssignedSubjectsWithAvgGradeByPupilIdDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.AllTestBySubjectId; import com.lwazir.project.schoolManagementsystem.model.joins.dto.GetAllPupilsDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.GetPupilIdByUsername; import com.lwazir.project.schoolManagementsystem.model.joins.dto.SubjectByCourseIdDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.TestDetailsDTO; import com.lwazir.project.schoolManagementsystem.repository.PupilRepository; import com.lwazir.project.schoolManagementsystem.repository.PupilTestRecordRepository; import com.lwazir.project.schoolManagementsystem.repository.PupilsSubjectsMapRepository; import com.lwazir.project.schoolManagementsystem.repository.SubjectRepository; import com.lwazir.project.schoolManagementsystem.repository.TestRepository; import com.lwazir.project.schoolManagementsystem.repository.UserRepository; @RestController //Allowing request from http://localhost:4500/ @CrossOrigin(origins = "http://localhost:4500/",exposedHeaders = {"Content-Disposition"}) public class PupilController { @Autowired PupilRepository pupilRepo; @Autowired SubjectRepository subjectRepo; @Autowired PupilsSubjectsMapRepository repo; @Autowired TestRepository testRepo; @Autowired PupilTestRecordRepository testRecordRepo; @Autowired UserRepository userRepo; @GetMapping(path= "/pupil") public List<GetAllPupilsDTO> getAllPupil(){ return pupilRepo.fetchAllPupils(); } @GetMapping("/pupil/{username}/GetDetails") public GetPupilIdByUsername fetchPupilByUsername(@PathVariable String username) { return userRepo.fetchPupilIdByUsername(username); } @GetMapping("/pupil/{pupilId}/{subjectName}/tests") public List<AllTestBySubjectId> fetchAllTestBySubjectId( @PathVariable Long pupilId, @PathVariable String subjectName){ return testRecordRepo.fetchTestBySubjectsId(subjectName, pupilId); } @GetMapping("/pupil/{pupilId}/AssignedSubjects") public List<AllAssignedSubjectsWithAvgGradeByPupilIdDTO> fetchAssignedSubjects(@PathVariable Long pupilId){ return pupilRepo.fetchAssignedSubjectWithGradesByPupilId(pupilId); } @GetMapping(path= "/pupil/{id}") public User getPupilById(@PathVariable Long id){ return pupilRepo.findById(id).get().getUser(); } @PutMapping(path="/course/{courseId}/assign/pupil/{pupilId}") public ResponseEntity<Object> assignPupil( @PathVariable Long courseId, @PathVariable Long pupilId) { Pupil pupil = pupilRepo.findById(pupilId).get(); if(pupil.getCourse()!=null) { Long prevCourseId=pupil.getCourse().getCourseId()==null?0:pupil.getCourse().getCourseId(); if(prevCourseId!=0) { List<SubjectByCourseIdDTO> subjects = subjectRepo.fetchAllSubejectByCourseId(prevCourseId); try { //List<PupilsSubjectsMap> map = repo.findAll(); for(SubjectByCourseIdDTO s : subjects) { List<AllTestBySubjectId> allTestOfDeassignedPupils = testRecordRepo.fetchTestBySubjectsId(s.getSubjectName(), pupilId); for(AllTestBySubjectId testRecord: allTestOfDeassignedPupils) { testRecordRepo.deleteTestRecordByPupilIdAndTestId(testRecord.getTestId(), pupilId); } repo.deleteByPupilIdAndSubjectId(pupilId, s.getSubjectName()); } pupilRepo.deAssignPupil(null, pupilId); }catch(Exception e) { System.out.println(e.getMessage()); } } } pupilRepo.assignPupil( courseId, pupilId); List<SubjectByCourseIdDTO> subjects = subjectRepo.fetchAllSubejectByCourseId(courseId); try { List<PupilsSubjectsMap> map = repo.findAll(); for(SubjectByCourseIdDTO s : subjects) { List<TestDetailsDTO> tests = testRepo.fetchTestBySubjectId(s.getSubjectName()); if(!tests.isEmpty() || tests!=null) { Set<PupilTestRecord> testRecords=tests .stream() .map( test->{ PupilTestRecord testRecord = new PupilTestRecord(); testRecord.setPupilId(pupilId); testRecord.setTestId(test.getId()); return testRecord; //testRecordRepo.save(testRecord); }).collect(Collectors.toSet()); List<PupilTestRecord> savedTestRecords= testRecordRepo.saveAll(testRecords); } PupilsSubjectsMap newPupilSubjectMap = new PupilsSubjectsMap(); newPupilSubjectMap.setPupilId(pupilId); newPupilSubjectMap.setSubjectId(s.getSubjectName()); map.add(newPupilSubjectMap); } repo.saveAll(map); }catch(Exception e) { System.out.println(e.getMessage()); } //pupil.setSubjects(assignedSubjects); //pupilRepo.save(pupil); return ResponseEntity.ok().build(); } @PutMapping(path="/course/{courseId}/pupil/{pupilId}") public ResponseEntity<Object> deassignPupil(@PathVariable Long courseId,@PathVariable Long pupilId){ List<SubjectByCourseIdDTO> subjects = subjectRepo.fetchAllSubejectByCourseId(courseId); try { //List<PupilsSubjectsMap> map = repo.findAll(); for(SubjectByCourseIdDTO s : subjects) { List<AllTestBySubjectId> allTestOfDeassignedPupils = testRecordRepo.fetchTestBySubjectsId(s.getSubjectName(), pupilId); for(AllTestBySubjectId testRecord: allTestOfDeassignedPupils) { testRecordRepo.deleteTestRecordByPupilIdAndTestId(testRecord.getTestId(), pupilId); } repo.deleteByPupilIdAndSubjectId(pupilId, s.getSubjectName()); } pupilRepo.deAssignPupil(null, pupilId); }catch(Exception e) { System.out.println(e.getMessage()); } return ResponseEntity.ok().build(); } } <file_sep>import { Button} from 'react-bootstrap'; import TextField from '@material-ui/core/TextField'; import { Alert } from '@material-ui/lab'; import CourseService from '../../api/CourseService'; import SubjectService from '../../api/SubjectService'; import React,{ Component } from "react"; import { Formik, Form, Field, ErrorMessage } from 'formik'; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from "../../Authentication/AuthenticationService"; export default class AddSubject extends Component { constructor(props){ super(props) this.state = { courseId:this.props.match.params.id, courseName:this.props.match.params.name, subId:this.props.match.params.subjectId, enteredDescription:'', enteredSubjectName: null, selectedTeacher:'', allTeachers :[] } this.onSubmit = this.onSubmit.bind(this) this.validate = this.validate.bind(this) this.onClose = this.onClose.bind(this) } onClose(){ this.props.history.push(`/admin/courses/${this.state.courseId}/${this.state.courseName}`) } componentDidMount() { AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); if (this.state.subId === 'new') { SubjectService.getAllTeachers().then( (response)=>{ this.setState({ allTeachers:response.data }) console.log(this.state.allTeachers) } ).catch(error=>{ console.log(error); }) } } validate(values) { let errors = {} if (!values.subjectName) { errors.subjectName = 'Enter the Subject Name' } if (!values.teacher) { errors.teacher = 'Select A Teacher' } return errors } onSubmit(values) { // let username = AuthenticationService.getLoggedInUserName() let subjectDetails = { subjectName: values.subjectName, subjectDescription:values.description, teacherId:values.teacher //targetDate: values.targetDate } console.log(subjectDetails); if (this.state.subId == 'new') { SubjectService.addSubject(this.state.courseId,subjectDetails).then( response => this.onClose() ).catch(error => console.log(error)) } else { //UserService.updateUser(this.state.id, userDetails) // .then(() => this.props.history.push('/users')) } console.log(values); } render(){ let { subjectName, courseName } = this.state return ( <> <center> <div className="container"> <Formik initialValues={{ subjectName, courseName}} onSubmit={this.onSubmit} validateOnChange={false} validateOnBlur={false} validate={this.validate} enableReinitialize={true} > { (props) => ( <Form> <ErrorMessage name="subjectName" component="div" className="alert alert-warning" /> <ErrorMessage name="teacher" component="div" className="alert alert-warning" /> <fieldset className="form-group"> <label style={{ display: 'flex',marginTop: 5,marginBottom:5 }}><b>Subject Name:</b></label> <Field className="form-control" type="text" name="subjectName" /> </fieldset> <fieldset className="form-group"> <label style={{ display: 'flex',marginTop: 5,marginBottom:5 }}><b>Course Name:</b></label> <Field className="form-control" readOnly type="text" name="courseName" /> </fieldset> <fieldset className="form-group"> <label style={{ display: 'flex',marginTop: 5,marginBottom:5 }}><b>Subject Description:</b></label> <Field className="form-control" type="text" name="description" /> </fieldset> <fieldset> <label htmlFor="Teacher" style={{ display: 'flex',marginTop: 5,marginBottom:5 }}> <b>Lecturers:</b> </label> <Field as="select" className="form-control" name="teacher" > <option value="" label="Select a Teacher" /> { this.state.allTeachers.map ((item,index)=> // console.log(index +' '+item) <option value={item.teacherId} label={item.firstName +' ' +item.lastName} /> )} </Field> </fieldset> <button className="btn btn-success" type="submit">Save</button> <Button variant="secondary" onClick={this.onClose}> Close </Button> </Form> )} </Formik> </div> </center> </> ); } } <file_sep>package com.lwazir.project.schoolManagementsystem.model.joins.dto; public class PupilTestGradeDetailsDTO { private Long pupilId; private String pupilFName; private String pupilLast; private Long testId; private Double testGrade; private String subjectName; private String subjectDescription; private Boolean isSubjectArchived; public PupilTestGradeDetailsDTO( Long pupilId, String pupilFName, String pupilLast, Long testId, Double testGrade, String subjectName, String subjectDescription, Boolean isSubjectArchived) { super(); this.pupilId = pupilId; this.pupilFName = pupilFName; this.pupilLast = pupilLast; this.testId = testId; this.testGrade = testGrade; this.subjectName = subjectName; this.subjectDescription = subjectDescription; this.isSubjectArchived = isSubjectArchived; } public Long getPupilId() { return pupilId; } public void setPupilId(Long pupilId) { this.pupilId = pupilId; } public String getPupilFName() { return pupilFName; } public void setPupilFName(String pupilFName) { this.pupilFName = pupilFName; } public String getPupilLast() { return pupilLast; } public void setPupilLast(String pupilLast) { this.pupilLast = pupilLast; } public Long getTestId() { return testId; } public void setTestId(Long testId) { this.testId = testId; } public Double getTestGrade() { return testGrade; } public void setTestGrade(Double testGrade) { this.testGrade = testGrade; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getSubjectDescription() { return subjectDescription; } public void setSubjectDescription(String subjectDescription) { this.subjectDescription = subjectDescription; } public Boolean getIsSubjectArchived() { return isSubjectArchived; } public void setIsSubjectArchived(Boolean isSubjectArchived) { this.isSubjectArchived = isSubjectArchived; } } <file_sep>package com.lwazir.project.schoolManagementsystem.controllers; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.lwazir.project.schoolManagementsystem.errors.UserNotFoundException; import com.lwazir.project.schoolManagementsystem.model.Pupil; import com.lwazir.project.schoolManagementsystem.model.PupilsSubjectsMap; import com.lwazir.project.schoolManagementsystem.model.Subject; import com.lwazir.project.schoolManagementsystem.model.Teacher; import com.lwazir.project.schoolManagementsystem.model.User; import com.lwazir.project.schoolManagementsystem.model.joins.dto.GetPupilIdByUsername; import com.lwazir.project.schoolManagementsystem.model.joins.dto.GetTeacherIdByUsername; import com.lwazir.project.schoolManagementsystem.model.joins.dto.GetUserIdDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.SubjectsPerTeacherDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.isTeacherAssignedSubjectDTO; import com.lwazir.project.schoolManagementsystem.repository.PupilRepository; import com.lwazir.project.schoolManagementsystem.repository.PupilsSubjectsMapRepository; import com.lwazir.project.schoolManagementsystem.repository.SubjectRepository; import com.lwazir.project.schoolManagementsystem.repository.TeacherRepository; import com.lwazir.project.schoolManagementsystem.repository.UserRepository; import com.lwazir.project.schoolManagementsystem.utility.UserPDFGenerator; @RestController //Allowing request from http://localhost:4500/ @CrossOrigin(origins = "http://localhost:4500/",exposedHeaders = {"Content-Disposition"}) public class UserController { @Autowired UserRepository repo; @Autowired PupilRepository pupilRepo; @Autowired TeacherRepository teacherRepo; @Autowired SubjectRepository subjRepo; @Autowired PupilsSubjectsMapRepository pupilSubjectRepo; @GetMapping(path= "/users") public List<User> getAllUsers() { return repo.findAll(); } @GetMapping(path= "/users/{id}") public User getUserById(@PathVariable Long id) { return repo.findById(id).get(); } @GetMapping(path= "/GetUserIDByName/{name}") public GetUserIdDTO getUserIdByUsername(@PathVariable String name) { return repo.fetchUserIdByUsername(name); } @GetMapping(path="/users/teacherId/{name}") public GetTeacherIdByUsername fetchTeacherIdByUserName(@PathVariable String name) { try { return repo.fetchTeacherIdByUsername(name); }catch(Exception e) { throw new RuntimeException(e.getMessage()); } } @GetMapping(path="/users/export/pdf",produces= MediaType.APPLICATION_PDF_VALUE) public ResponseEntity<InputStreamResource> userReport() throws IOException { List<User> usersList = repo.findAll(); ByteArrayInputStream bis = UserPDFGenerator.UserPDFReport(usersList); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "inline; filename=usersReport.pdf"); return ResponseEntity .ok() .headers(headers) .contentType(MediaType.APPLICATION_PDF) .body(new InputStreamResource(bis)); } //TODO: Implementating Validation in Spring boot using //@Valid Annotation @PostMapping(path="/addUser") public ResponseEntity<Object> addUser( @RequestBody User user) { User savedUser; try { user.setCreatedAt(new Date()); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String encodedPassword=encoder.encode(user.getPassword()); if(user.getRole().equals("TEACHER")) { Teacher teacher = new Teacher(); Teacher savedTeacher=teacherRepo.save(teacher); if(savedTeacher!=null) { user.setTeacher(savedTeacher); } user.setPassword(<PASSWORD>); //user.setTeacher(new Teacher(0)); savedUser = repo.save(user); //Set the uri of created resource into the response URI createdResourceUri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedUser.getId()).toUri(); //Return Created status return ResponseEntity.created(createdResourceUri).build(); } else if(user.getRole().equals("PUPIL")) { user.setPassword(<PASSWORD>); //user.setTeacher(new Teacher(0)); savedUser = repo.save(user); if(savedUser!=null ) { if(savedUser.getRole().equals("PUPIL")){ Pupil pupil = new Pupil(); pupil.setUser(savedUser); pupilRepo.save(pupil); } } //Set the uri of created resource into the response URI createdResourceUri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedUser.getId()).toUri(); //Return Created status return ResponseEntity.created(createdResourceUri).build(); } }catch(Exception e) { throw new RuntimeException(e.getMessage()); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } @DeleteMapping(path= "/delete/{id}") public ResponseEntity<Object> deleteUserById(@PathVariable Long id) { try { User user = repo.findById(id).get(); if(user.getRole().equalsIgnoreCase("TEACHER")) { //isTeacherAssignedSubjectDTO result = repo.checkIfTeacherIsAssignedToSubject(id); List<SubjectsPerTeacherDTO> activeSubjects = subjRepo.fetchAllActiveSubjectsByTeacherId(user.getTeacher().getId()); if(activeSubjects.isEmpty()) { repo.deleteById(id); return ResponseEntity.accepted().build(); } else { return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Teacher is Assigned to Subject"); } }else if(user.getRole().equalsIgnoreCase("PUPIL")) { GetPupilIdByUsername pupil = repo.fetchPupilIdByUsername(user.getUsername()); List<PupilsSubjectsMap> map = pupilSubjectRepo.findAll(); List<PupilsSubjectsMap> assignedPupils = map.stream() .filter( p->p.getPupilId().equals(pupil.getPupilId()) ) .collect(Collectors.toList()); if(assignedPupils.isEmpty()) { pupilRepo.deleteById(pupil.getPupilId()); repo.deleteById(id); return ResponseEntity.accepted().build(); } else { return ResponseEntity.status(HttpStatus.FORBIDDEN) .body("Pupil is Assigned to a Subject"); } }else if(user.getRole().equalsIgnoreCase("ADMIN")) { List<User> users = repo.findAll(); Set<User> allAdmins = users .stream() .filter(u->u.getRole().equalsIgnoreCase("ADMIN")) .collect(Collectors.toSet()); if(allAdmins.size()>1) { repo.deleteById(id); return ResponseEntity.accepted().build(); }else { return ResponseEntity.status(HttpStatus.FORBIDDEN) .body("You can't Delete Yourself!"); } } return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); }catch(Exception e) { throw new UserNotFoundException("error "+e.getMessage()); } } @DeleteMapping(path= "/delete") public void deleteAll() { try { repo.deleteAll(); }catch(Exception e) { throw new RuntimeException("Delete All Operation Failed!"); } } @PutMapping(path="/users/{id}") public ResponseEntity<Object> updateUser( @PathVariable Long id, @Valid @RequestBody User user){ try { User extractedUser=repo.findById(id).get(); extractedUser.setFirstName(user.getFirstName()); extractedUser.setLastName(user.getLastName()); extractedUser.setId(id); extractedUser.setUsername(user.getUsername()); extractedUser.setRole(user.getRole()); String password =<PASSWORD>(); if(password!=null) { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String encodedPassword=encoder.encode(user.getPassword()); extractedUser.setPassword(encodedPassword); //repo.deleteById(id); // ExtractedUser.setLastName() repo.save(extractedUser); }else { //repo.deleteById(id); // ExtractedUser.setLastName() repo.save(extractedUser); } }catch(Exception e) { System.out.println(e.getMessage()); throw new UserNotFoundException("User Not Found!"); } return ResponseEntity.ok().build(); } } <file_sep>import { Modal, ModalBody ,Button} from 'react-bootstrap'; import React,{useState} from 'react'; import TextField from '@material-ui/core/TextField'; import { Alert } from '@material-ui/lab'; import { Component } from 'react'; import TeacherService from '../../api/TeacherService'; export default class UpdateGradeModal extends Component{ constructor(props){ super(props) this.state={ enteredGrade:'', showError:false } this.submitHandler = this.submitHandler.bind(this); this.handleGradeFieldChanged = this.handleGradeFieldChanged.bind(this); } componentDidMount(){ this.setState({ enteredGrade:'', showError:false }) } handleGradeFieldChanged(event) { this.setState({ enteredGrade:event.target.value }) } submitHandler(){ if(this.state.enteredGrade.length==0) { this.setState({ showError:true }) } else{ let newGrade = this.state.enteredGrade; this.setState({ enteredGrade:'' }) this.props.onSubmit(newGrade); } } render(){ return( <> <Modal show={this.props.show} onHide={this.props.onHide} > <Modal.Header closeButton> Add / Edit Grade </Modal.Header> <Modal.Body> <div className="container"> {this.state.showError && <Alert severity="error">Please Enter the grade!</Alert>} <TextField variant="outlined" margin="normal" required fullWidth id="grade" label="grade" name="grade" value={this.state.enteredGrade} onChange={this.handleGradeFieldChanged} autoFocus /> </div> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={this.props.onHide}> Close </Button> <Button variant="primary" onClick={this.submitHandler}> Save Changes </Button> </Modal.Footer> </Modal> </> ); } }<file_sep>package com.lwazir.project.schoolManagementsystem.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.lwazir.project.schoolManagementsystem.model.Teacher; import com.lwazir.project.schoolManagementsystem.model.joins.dto.GetAllPupilsDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.GetAllTeachersDTO; import com.lwazir.project.schoolManagementsystem.model.joins.dto.PupilTestGradeDetailsDTO; public interface TeacherRepository extends JpaRepository<Teacher,Long>{ @Query("Select new com.lwazir.project.schoolManagementsystem.model.joins.dto.GetAllTeachersDTO( "+ "t.id, "+ "u.firstName, "+ "u.LastName "+ ") "+ "from Teacher as t "+ "Left Join "+ "User as u on u.teacher.id=t.id" ) List<GetAllTeachersDTO> fetchAllTeachers(); } <file_sep> import { Modal, ModalBody ,Button} from 'react-bootstrap'; import React,{useState,useEffect, Component} from 'react'; import TextField from '@material-ui/core/TextField'; import { Alert } from '@material-ui/lab'; import CourseService from '../../api/CourseService'; import { makeStyles } from '@material-ui/core/styles'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import ListItemText from '@material-ui/core/ListItemText'; import Checkbox from '@material-ui/core/Checkbox'; import IconButton from '@material-ui/core/IconButton'; import CommentIcon from '@material-ui/icons/Comment'; import '../PupilList.css'; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from '../../Authentication/AuthenticationService'; import CustomAlert from "../utility/Alerts/CustomAlerts"; import CustomAlertWithTwoButtons from "../utility/Alerts/CustomAlertWithTwoButtons"; export default class SelectPupil extends Component { constructor(props) { super(props) this.state = { showError :false, id:this.props.match.params.id, courseName:this.props.match.params.name, showWarning: false, message : null, showSuccess:false, pupils:[], checked : [0] } } //classes = useStyles(); onClose= () => { this.props.history.push(`/admin/courses/${this.state.id}/${this.state.courseName}`) } handleToggle = (value) => () => { //console.log("pressesd check box"); const currentIndex = this.state.checked.indexOf(value); //console.log(currentIndex); const newChecked = [...this.state.checked]; //console.log(newChecked); if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } this.setState({ checked:newChecked }) }; onHide = () => { this.setState({ message:null, showError:false, showWarning:false, showSuccess:false, }) } onSave = () => { console.log(`OnSave - ${this.state.checked}`) this.state.checked.map((item,index)=>{ if(index>0){ if(item.courseId==null){ CourseService.assignPupil(this.state.id,item.pupilId).then( (response)=>{ if(response.status==200){ // setShowSuccess(true); // setMessage(`The Pupil ${item.firstName} ${item.lastName} added to Course (id: ${item.courseId})`) } } ).catch(error=>{ console.log(error); // setShowError(true); //setMessage(`Pupil Could not be added`); }) }else{ //setWarning(true); // setMessage('Pupil already assign to another course,Click agree to deassign from latter and assign to this course') CourseService.assignPupil(this.state.id,item.pupilId).then( (response)=>{ if(response.status==200){ // setShowSuccess(true); // setMessage(`The Pupil ${item.firstName} ${item.lastName} added to Course (id: ${item.courseId})`) } } ).catch(error=>{ console.log(error); // setShowError(true); // setMessage(`Pupil Could not be added`); }) } } }); this.setState({ checked:[0] }) this.onHide(); this.onClose(); } toContinue = () => { this.setAgree(true); } componentDidMount() { this.setState({ checked:[0] }) AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); CourseService.getAllPupils() .then( response => { this.setState({ pupils:response.data }) console.log(this.state.pupils); }); } render(){ return ( <div className="container"> <h1>Select Pupil:</h1> {this.state.showSuccess && <CustomAlert errorMessage={this.state.message} severity='success' onCancel = {this.onHide}/>} {this.state.showError && <CustomAlert errorMessage={this.state.message} severity='error' onCancel = {this.onHide}/>} {this.state.showWarning && <CustomAlertWithTwoButtons errorMessage={this.state.message} severity='warning' onAgree={this.toContinue} onCancel = {this.onHide}/>} <List> { this.state.pupils.map( (pupil,index)=>{ if(pupil.courseId!=this.state.id){ const labelId = `checkbox-list-label-${pupil.pupilId}`; return( <ListItem key={index} role={undefined} dense button onClick={this.handleToggle(pupil)}> <ListItemIcon> <Checkbox edge="start" checked={this.state.checked.indexOf(pupil) != -1} tabIndex={-1} disableRipple inputProps={{ 'aria-labelledby': labelId }} /> </ListItemIcon> <ListItemText id={labelId} primary={` ${pupil.firstName+' '+ pupil.lastName}`} /> </ListItem> ) } } ) } </List> <div style={{display:'inline-block',float:'right',padding:10}}> <Button variant="secondary" style={{marginBottom:10,marginRight:10,padding:10,marginTop:10}} onClick={this.onClose}> Close </Button> <Button variant="primary" style={{marginBottom:10,marginRight:10,padding:10,marginTop:10}} onClick={this.onSave}> Save Changes </Button> </div> </div> ); } }<file_sep>import { Component } from "react"; import TeacherService from "../../api/TeacherService"; import UserService from "../../api/UserService"; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from "../../Authentication/AuthenticationService"; import CustomAlert from "../utility/Alerts/CustomAlerts"; import { Button} from 'react-bootstrap'; import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box' import Grid from '@material-ui/core/Grid'; import { CssBaseline } from '@material-ui/core'; export default class AssignedSubjectsList extends Component{ constructor(props){ super(props) this.state = { activesubjects:[], archivedSubjects:[], courseName:'', message:'', username:this.props.match.params.name, teacherName:'', teacherDetails:{}, error:false, success:false } this.loadTeacherIdByUsername = this.loadTeacherIdByUsername.bind(this); this.loadAssignedSubjects = this.loadAssignedSubjects.bind(this); this.onHide = this.onHide.bind(this); this.showSubject = this.showSubject.bind(this); this.refresh = this.refresh.bind(this); } componentDidMount(){ this.refresh(); // this.loadPupilsWithGrades(); } refresh(){ AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); this.loadTeacherIdByUsername(); } loadTeacherIdByUsername(){ UserService.fetchTeacherIDByUsername(this.state.username).then( response=>{ this.setState({ teacherDetails:response.data, teacherName:`${response.data.firstName} ${response.data.lastName}` }) console.log(this.state.teacherName) this.loadAssignedSubjects(); } ).catch(error=>{ console.log.apply(error) }) } loadAssignedSubjects(){ let teacher_id =this.state.teacherDetails.teacherId; TeacherService.getAllActiveSubjectByTeacherID(teacher_id) .then( response => { this.setState({ activesubjects:response.data }) console.log(this.state.activesubjects) }).catch(error=>console.log(error)) TeacherService.getAllArchivedSubjectsByTeacherId(teacher_id) .then(response=>{ this.setState({ archivedSubjects:response.data }) console.log(this.state.archivedSubjects) }).catch(error=>console.log(error)) } onHide(){ this.setState({ message:'', error:false, success:false }) } showSubject(subjectName){ this.props.history.push(`/teacher/${this.state.teacherName}/subjectDetails/${subjectName}`); } render(){ return ( <div className="root"> <CssBaseline/> <Grid container spacing={3} direction="row" justify="center" alignItems="center" > <Grid item xs={12}> <Paper elevation={2} className="paper"> <Box> <h1>Active Subjects:</h1> {this.state.error && <CustomAlert errorMessage={this.state.message} severity='error' onCancel = {this.onHide}/>} <table className="table"> <thead> <tr> <th>Course Name</th> <th>Subject Name</th> </tr> </thead> <tbody> { this.state.activesubjects.map( subject=> <tr> <td>{subject.courseName}</td> <td>{subject.subjectName}</td> <Button variant="secondary" onClick={()=>{this.showSubject(subject.subjectName)}}> View Details </Button> </tr> ) } </tbody> </table> </Box> </Paper> </Grid> <Grid item xs={12}> <Paper elevation={2} className="paper"> <Box> <h1>Archived Subjects:</h1> {this.state.error && <CustomAlert errorMessage={this.state.message} severity='error' onCancel = {this.onHide}/>} <table className="table"> <thead> <tr> <th>Course Name</th> <th>Subject Name</th> </tr> </thead> <tbody> { this.state.archivedSubjects.length>0? this.state.archivedSubjects.map( subject=> <tr> {subject.courseName!=null &&<td>{subject.courseName}</td>} <td>{subject.subjectName}</td> <Button variant="secondary" onClick={()=>{this.showSubject(subject.subjectName)}}> View Details </Button> </tr> ):'No Archived Subjects!' } </tbody> </table> </Box> </Paper> </Grid> </Grid> </div> ); } }<file_sep>import axios from "axios"; class CourseService{ executeRetrieveAllCoursesService(){ console.log('Executed Retrieved All Courses Service') return axios.get('http://localhost:9000/courses'); } executeCourseById(id){ console.log('Executed Retrieved All Courses Service') return axios.get(`http://localhost:9000/jpa/courses/${id}`); } editCourse(courseId,newCourseName){ let course = { courseName: newCourseName } return axios.put(`http://localhost:9000/course/${courseId}`,course) } executeAddCourse(course){ return axios.post('http://localhost:9000/course',course); } executeDeleteCourseById(id){ return axios.delete(`http://localhost:9000/course/delete/${id}`); } executePupilAndTestCountBySubjectName(subjectName){ return axios.get(`http://localhost:9000/subject/${subjectName}/pupilAndTest/count`) } executeAllPupilByCourseId(id){ return axios.get(`http://localhost:9000/course/${id}/allPupils`) } deAssignPupil(courseId,pupilId){ return axios.put(`http://localhost:9000/course/${courseId}/pupil/${pupilId}`); } assignPupil(courseId,pupilId){ return axios.put(`http://localhost:9000/course/${courseId}/assign/pupil/${pupilId}`); } getAllPupils(){ return axios.get('http://localhost:9000/pupil'); } deleteSubjectbyId(courseId,subjectName){ return axios.delete(`http://localhost:9000/course/${courseId}/subject/${subjectName}`); } } export default new CourseService()<file_sep>import { Component } from "react"; import { Formik, Form, Field, ErrorMessage } from 'formik'; import UserService from "../../api/UserService"; import AuthenticationService, { USER_ID, USER_TOKEN_ATTRIBUTE_NAME } from "../../Authentication/AuthenticationService"; import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box' import Grid from '@material-ui/core/Grid'; import { CssBaseline } from '@material-ui/core'; import Typography from '@material-ui/core/Typography'; import CustomAlert from "./Alerts/CustomAlerts"; export default class UserSettings extends Component{ constructor(props) { super(props) this.state = { id: '', firstName: '', lastName:'', username:'', password:'', role:'', showError:false, showSuccess:false, message:'' } this.onSubmit = this.onSubmit.bind(this) this.validate = this.validate.bind(this) this.retrieveUserDetails = this.retrieveUserDetails.bind(this) } componentDidMount() { AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); let username = sessionStorage.getItem(USER_ID); UserService.executeRetrieveUserIDByUsernameService(username).then( response=>{ console.log('settings: '+response.data) this.setState({ id:response.data.userId },()=>this.retrieveUserDetails()) } ).catch(error=>console.log('error-in retrieving userID'+error)) // let username = AuthenticationService.getLoggedInUserName() } retrieveUserDetails(){ console.log('in retrieve user') UserService.executeRetrieveUserByIdService(this.state.id) .then(response => { console.log(response.data) this.setState({ username: response.data.username, firstName:response.data.firstName, lastName: response.data.lastName, role:response.data.role }) } ) } validate(values) { let errors = {} if (!values.firstName) { errors.firstName = 'Enter the First Name' } if (!values.lastName) { errors.lastName = 'Enter the Last Name' } if(!values.username){ errors.username = 'Enter a User Name' } /** if (!moment(values.targetDate).isValid()) { errors.targetDate = 'Enter a valid Target Date' } */ return errors } onSubmit(values) { // let username = AuthenticationService.getLoggedInUserName() let userDetails = { id: this.state.id, username: values.username, firstName: values.firstName, lastName:values.lastName, role:values.role, password:<PASSWORD>, //targetDate: values.targetDate } console.log(this.state.id); UserService.updateUser(this.state.id, userDetails) .then(() => this.setState({ showSuccess:true, message:'User is updated successfully' }) ).catch((error=>this.setState({ showError:true, message:'User Can not be updated!' }))); console.log(values); } render(){ let { firstName, lastName, role, username, password } = this.state return( <div className="root"> {this.state.showError && <CustomAlert errorMessage={this.state.message} severity='error' onCancel = {()=>{ this.setState({ showError:false, message:'' }) }}/>} {this.state.showSuccess && <CustomAlert errorMessage={this.state.message} severity='success' onCancel = {()=>{ this.setState({ showError:false, message:'' }) }}/>} <CssBaseline/> <Grid container spacing={3} direction="row" justify="center" alignItems="center" > <Grid item xs={8}> <Paper className="paper" elevation={2}> <Box padding='16px'> <Formik initialValues={{ firstName, lastName,role,username,password }} onSubmit={this.onSubmit} validateOnChange={false} validateOnBlur={false} validate={this.validate} enableReinitialize={true} > { (props) => ( <Form> <ErrorMessage name="firstName" component="div" className="alert alert-warning" /> <ErrorMessage name="lastName" component="div" className="alert alert-warning" /> <ErrorMessage name="username" component="div" className="alert alert-warning" /> <ErrorMessage name="role" component="div" className="alert alert-warning" /> <fieldset className="form-group"> <label>First Name</label> <Field className="form-control" type="text" name="firstName" /> </fieldset> <fieldset className="form-group"> <label>Last Name</label> <Field className="form-control" type="text" name="lastName" /> </fieldset> <fieldset className="form-group"> <label>User Name</label> <Field className="form-control" type="text" name="username" /> </fieldset> <fieldset className="form-group"> <label>Role</label> <Field className="form-control" type="text" readonly='true' name="role" /> </fieldset> <fieldset className="form-group"> <label>New Password</label> <Field className="form-control" type="password" name="password" /> </fieldset> <button className="btn btn-success" type="submit">Save</button> </Form> ) } </Formik> </Box> </Paper> </Grid> </Grid> </div> ); } }<file_sep>//import useState hook to create menu collapse state import React, { Component, useState } from "react"; import { Link } from "react-router-dom"; import {FaBars} from "react-icons/fa"; import * as AiIcons from "react-icons/ai"; import { SidebarData,sideBarDataPupil,sideBarDataTeacher } from "./NavBarData"; import './Navbar.css'; import AuthenticationService, { USER_ID, USER_ROLE } from "../../../Authentication/AuthenticationService"; export default class Header extends Component { // const [sidebar, role ,setSidebar,setRole] = useState(false,''); constructor(props){ super(props); this.state={ sidebar:false, role:localStorage.getItem(USER_ROLE), name:sessionStorage.getItem(USER_ID) } } componentDidMount(){ //let extractedRole = AuthenticationService.getRoleFromToken(); this.setState({ role:sessionStorage.getItem(USER_ROLE), name:sessionStorage.getItem(USER_ID) }) } setSidebar = () => { let sidebar = this.state.sidebar this.setState( { sidebar:!sidebar } ) } //showSidebar = () => this.setSidebar(); clickHandler = (item)=>{ this.setSidebar(); if(item.title==='Logout'){ AuthenticationService.logout(); } } render(){ return ( <> <div className="navbar "> <Link to="#" className="nav-bars"> <FaBars onClick={this.setSidebar}/> </Link> <Link to={sessionStorage.getItem(USER_ROLE)=='ADMIN'?`/admin/dashboard/${sessionStorage.getItem(USER_ID)}`: sessionStorage.getItem(USER_ROLE)=='TEACHER'?`/teacher/${sessionStorage.getItem(USER_ID)}/subjects`: `/pupil/welcome/${sessionStorage.getItem(USER_ID)}`} className="nav-link"> Home </Link> </div> <nav className={this.state.sidebar ? 'nav-menu active' : 'nav-menu'}> <ul className='nav-menu-items'> <li className="navbasr-toggle"> <Link to='#' className='menu-bars'> <AiIcons.AiOutlineClose onClick={this.setSidebar}/> </Link> </li> { SidebarData.map((item,index)=>{ if(AuthenticationService.isUserLoggedIn()){ if(item.title!='Login'){ if(item.role==sessionStorage.getItem(USER_ROLE)) { return( <li key={index} className={item.cName}> <Link to= {item.path} onClick={()=>this.clickHandler(item)}> {item.icon} <span>{item.title}</span> </Link> </li> ) }else if(item.title=='Logout'){ return( <li key={index} className={item.cName}> <Link to= {item.path} onClick={()=>this.clickHandler(item)}> {item.icon} <span>{item.title}</span> </Link> </li> ) } else if(item.title=='Settings'){ return( <li key={index} className={item.cName}> <Link to= {item.path} onClick={()=>this.clickHandler(item)}> {item.icon} <span>{item.title}</span> </Link> </li> ) } } }else if(item.title==='Login'){ return( <li key={index} className={item.cName}> <Link to={item.path} onClick={()=>this.clickHandler(item)}> {item.icon} <span>{item.title}</span> </Link> </li> ) } })} </ul> </nav> </> ); } }; <file_sep>package com.lwazir.project.schoolManagementsystem.model.joins.dto; public class GetAllPupilsDTO { private Long pupilId; private Long CourseId; private String firstName; private String lastName; public GetAllPupilsDTO() { } public GetAllPupilsDTO( Long pupilId, Long courseId, String firstName, String lastName) { super(); this.pupilId = pupilId; this.CourseId = courseId; this.firstName = firstName; this.lastName = lastName; } public Long getPupilId() { return pupilId; } public void setPupilId(Long pupilId) { this.pupilId = pupilId; } public Long getCourseId() { return CourseId; } public void setCourseId(Long courseId) { CourseId = courseId; } 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; } @Override public String toString() { return "GetAllPupilsDTO [pupilId=" + pupilId + ", CourseId=" + CourseId + ", firstName=" + firstName + ", lastName=" + lastName + "]"; } } <file_sep>package com.lwazir.project.schoolManagementsystem.model; import java.time.LocalDateTime; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity public class Test { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String testname; private String createdAt; //private Long grade; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="subject_id") //@JsonIgnore private Subject subject; //@OneToMany(mappedBy = "test_id") //Set<PupilTestRecord> grades; public Test() {} public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public Subject getSubject() { return subject; } public void setSubject(Subject subject) { this.subject = subject; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setId(int Long) { this.id = id; } public String getTestname() { return testname; } public void setTestname(String testname) { this.testname = testname; } } <file_sep>package com.lwazir.project.schoolManagementsystem.model.joins.dto; public class isTeacherAssignedSubjectDTO { private Long teacherId; //private String teacher_id; public isTeacherAssignedSubjectDTO() { } public isTeacherAssignedSubjectDTO(Long teacherId) { super(); this.teacherId = teacherId; } public Long getTeacherId() { return teacherId; } public void setTeacherId(Long teacherId) { this.teacherId = teacherId; } } <file_sep>import React,{Component} from 'react' import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box' import Grid from '@material-ui/core/Grid'; import { Button, InputBase, ListItem } from '@material-ui/core'; import { CssBaseline } from '@material-ui/core'; import Typography from '@material-ui/core/Typography'; import TeacherService from '../../api/TeacherService'; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from '../../Authentication/AuthenticationService'; import PageviewSharpIcon from '@material-ui/icons/PageviewSharp'; import DeleteIcon from '@material-ui/icons/Delete'; import { AddOutlined, ArchiveRounded, ArrowRight, EditOutlined, PageviewOutlined, Refresh } from '@material-ui/icons'; import IconButton from '@material-ui/core/IconButton'; import Tooltip from '@material-ui/core/Tooltip'; import PupilService from '../../api/PupilService'; export default class PupilSubjectView extends Component{ constructor(props){ super(props) this.state ={ id:'', tests:[], pupilId:this.props.match.params.pupilId, subjectName:this.props.match.params.subjectName } this.refresh = this.refresh.bind(this); this.loadTestsBySubjectId = this.loadTestsBySubjectId.bind(this); } componentDidMount(){ this.refresh() } refresh(){ AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); this.loadTestsBySubjectId(); } loadTestsBySubjectId(){ PupilService.fetchAllTestsForSelectedSubject(this.state.pupilId,this.state.subjectName).then( response=>{ this.setState({ tests:response.data }) console.log(response.data.pupilId) } ).catch(error=>console.log(error)) } render(){ return ( <div className="root"> <CssBaseline/> <Grid container spacing={1} > <Grid item xs={12}> <Paper elevation={2} className="paper"> <Box> <table className="table"> <thead> <tr> <th>Subject Name</th> <th>Test Id</th> <th>Test Name</th> <th>Grade</th> </tr> </thead> <tbody> { this.state.tests.map( test => <tr> <td>{this.state.subjectName}</td> <td>{test.testId}</td> <td>{test.testName}</td> <td>{test.grade==null?0:test.grade}</td> </tr> ) } </tbody> </table> </Box> </Paper> </Grid> </Grid> </div> ); } }<file_sep>package com.lwazir.project.schoolManagementsystem.model.joins.dto; public class AllAssignedSubjectsWithAvgGradeByPupilIdDTO { private String subjectName; private Double grade; private Long pupilId; public AllAssignedSubjectsWithAvgGradeByPupilIdDTO() { } public AllAssignedSubjectsWithAvgGradeByPupilIdDTO( String subjectName, Double grade, Long pupilId) { super(); this.subjectName = subjectName; this.grade = grade; this.pupilId = pupilId; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public Double getGrade() { return grade; } public void setGrade(Double grade) { this.grade = grade; } public Long getPupilId() { return pupilId; } public void setPupilId(Long pupilId) { this.pupilId = pupilId; } } <file_sep>import { useMediaQuery } from "@material-ui/core"; import React,{ Component } from "react"; import UserService from "../../api/UserService"; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from "../../Authentication/AuthenticationService"; import CustomAlert from "../utility/Alerts/CustomAlerts"; import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box' import Grid from '@material-ui/core/Grid'; import { CssBaseline } from '@material-ui/core'; export default class UsersListComponent extends Component{ constructor(props){ super(props) this.deleteUserById = this.deleteUserById.bind(this) this.refreshUsersList = this.refreshUsersList.bind(this) this.updateUser = this.updateUser.bind(this) this.exportPdf = this.exportPdf.bind(this) this.state={ users:[ //{id:1,name:'Lalit',role:'Admin',createdAt:new Date()}, // {id:2,name:'User 2',role:'Teacher',createdAt:new Date()}, // {id:3,name:'User 3',role:'Pupil',createdAt:new Date()} ], message:null, error:null } this.addUser = this.addUser.bind(this) } updateUser(id){ console.log("update "+id); this.props.history.push(`/editUser/${id}`) } addUser(){ this.props.history.push('/editUser/-1') } deleteUserById(id){ UserService.executedeleteUserByIdService(id) .then( response=>{ console.log(`delete user with id ${id}`) console.log(response) this.setState({ message:`Deleted User With Id : ${id}` }) this.refreshUsersList(); } ).catch(error=>{ // console.log(error) this.setState({ error:'User can not be deleted' }) }); } componentDidMount(){ this.refreshUsersList(); } refreshUsersList(){ AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); UserService.executeRetrieveAllUsersService() .then( response=>{ console.log(response.data) this.setState({ users:response.data }) } ) } exportPdf(){ UserService.executeExportUserToPDFService() .then(response => { console.log(response); const filename = response.headers['content-disposition'].split('filename=')[1]; console.log("FileName: "+filename); const blob = new Blob([response.data],{type:response.data.type}); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.setAttribute('download', filename); //or any other extension document.body.appendChild(link); link.click(); link.remove(); window.URL.revokeObjectURL(url); }); } onHide = () => { this.setState({ error:null, message:null }); } render(){ return ( <div className="root"> <CssBaseline/> <Grid container spacing={3} direction="column" justify="center" alignItems="center" > <Grid item xs={12}> <Paper elevation={3} className="paper"> <Box> <h1>Users:</h1> {this.state.message && <CustomAlert errorMessage={this.state.message} severity='success' onCancel = {this.onHide}/>} {this.state.error && <CustomAlert errorMessage={this.state.error} severity='error' onCancel = {this.onHide}/>} <table className="table"> <thead> <tr> <th>Id</th> <th>User</th> <th>Role</th> <th>Created At</th> <th>Delete</th> <th>Update</th> </tr> </thead> <tbody> { this.state.users.map( user=> <tr> <td>{user.id}</td> <td>{user.name}</td> <td>{user.role}</td> <td>{user.createdAt}</td> <td><button className="btn btn-warning" onClick= {()=>{this.deleteUserById(user.id)}} >Delete</button></td> <td><button className="btn btn-success" onClick= {()=>{this.updateUser(user.id)}} >Update</button></td> </tr> ) } </tbody> </table> <button className="btn btn-success" style={{ position:"relative",left:5 ,marginRight:10}} onClick={this.addUser}>New User</button> <button className="btn btn-success" style={{ position:"relative",right:5, marginLeft:10}} onClick={this.exportPdf}>Export</button> </Box> </Paper> </Grid> </Grid> </div> ); } }<file_sep>package com.lwazir.project.schoolManagementsystem.utility; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import com.lwazir.project.schoolManagementsystem.model.Pupil; import com.lwazir.project.schoolManagementsystem.model.Teacher; import com.lwazir.project.schoolManagementsystem.model.User; import com.lwazir.project.schoolManagementsystem.repository.PupilRepository; import com.lwazir.project.schoolManagementsystem.repository.TeacherRepository; import com.lwazir.project.schoolManagementsystem.repository.UserRepository; @Component public class CustomCommandLineRunner implements CommandLineRunner { @Autowired UserRepository repo; @Autowired TeacherRepository teacherRepo; @Autowired PupilRepository pupilRepo; @Override public void run(String... args) throws Exception { List<User> userList= new ArrayList(); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String encodedPassword =encoder.encode("<PASSWORD>"); User user1= new User( "lwazir", "Lalit", "Wazir", encodedPassword, new Date(), "ADMIN" ); User user2= new User( "pupil1", "anupal", "mishra", encodedPassword, new Date(), "PUPIL" ); User user3= new User( "pupil2", "aman", "khosla", encodedPassword, new Date(), "PUPIL" ); User user4= new User( "pupil3", "susan", "jane", encodedPassword, new Date(), "PUPIL" ); User user5= new User( "pupil4", "aditya", "shukla", encodedPassword, new Date(), "PUPIL" ); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); userList.add(user5); List<User> users=repo.saveAll(userList); List<User> pupils = users .stream() .filter( user -> user.getRole().equals("PUPIL")) .collect(Collectors.toList()); pupils .stream() .forEach ((pupil)->{ Pupil newPupil = new Pupil(); newPupil.setUser(pupil); pupilRepo.save(newPupil); }); } } <file_sep>package com.lwazir.project.schoolManagementsystem.model.compositekeys; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class PupilTestRecordKey implements Serializable { /** * */ private static final long serialVersionUID = 6774242234065941129L; @Column(name = "pupil_id") Long pupilId; @Column(name = "test_id") Long testId; public PupilTestRecordKey() { } public PupilTestRecordKey(Long pupilId, Long testId) { super(); this.pupilId = pupilId; this.testId = testId; } public Long getPupilId() { return pupilId; } public void setPupilId(Long pupilId) { this.pupilId = pupilId; } public Long getTestId() { return testId; } public void setTestId(Long testId) { this.testId = testId; } } <file_sep> import { Modal, ModalBody ,Button} from 'react-bootstrap'; import React,{useState} from 'react'; import TextField from '@material-ui/core/TextField'; import { Alert } from '@material-ui/lab'; import { Component } from 'react'; import TeacherService from '../../api/TeacherService'; export default class EditTest extends Component { constructor(props){ super(props) this.state={ subjectName: props.subjectName, enterredTestName: this.props.testName, showError: false, id: props.testId } this.handleTestNameFieldChanged = this.handleTestNameFieldChanged.bind(this); this.submitHandler = this.submitHandler.bind(this); this.editTest = this.editTest.bind(this); console.log(`Initiial Vallues: ${this.state.enterredTestName} ${this.state.id}`); } editTest(){ console.log(`Props: ${this.props.testName}, ${this.props.testId}`) console.log(`Inside Edit Test : ${this.state.id} ${this.state.enterredTestName} ${this.state.subjectName}`) TeacherService.editTest(this.state.subjectName,this.props.testId,this.state.enterredTestName).then( response=>{ this.props.onHide(); } ).catch(error=>console.log(error)) } handleTestNameFieldChanged(event) { this.setState({ enterredTestName:event.target.value }) } submitHandler(){ if(this.state.enterredTestName.length<4) { this.setState({ showError:true }) console.log(this.state.enterredTestName); this.setState({ enterredTestName:'' }) } else{ this.editTest(); } } render(){ return ( <> <Modal show={this.props.show} onHide={this.props.onHide}> <Modal.Header closeButton> Edit Test</Modal.Header> <Modal.Body> <div className="container"> {this.state.showError && <Alert severity="error">Test Name should contain atleast 4 characters!</Alert>} <TextField variant="outlined" margin="normal" required fullWidth id="testName" label="Test Name" name="testName" value={this.state.enterredTestName} onChange={this.handleTestNameFieldChanged} autoFocus /> </div> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={()=>{ this.setState({ enterredTestName:'' },function(){ this.props.onHide(); }) }}> Close </Button> <Button variant="primary" onClick={this.submitHandler}> Save Changes </Button> </Modal.Footer> </Modal> </> ); } }<file_sep>package com.lwazir.project.schoolManagementsystem.model.joins.dto; public class TestDetailsDTO { private Long id; private String testName; private String createdAt; public TestDetailsDTO() { } public TestDetailsDTO(Long id, String testName, String createdAt) { super(); this.id = id; this.testName = testName; this.createdAt = createdAt; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTestName() { return testName; } public void setTestName(String testName) { this.testName = testName; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } } <file_sep>import React,{Component} from 'react'; import CustomAlert from "../utility/Alerts/CustomAlerts"; import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box' import Grid from '@material-ui/core/Grid'; import { Button, InputBase, ListItem } from '@material-ui/core'; import './css/grid.css'; import { CssBaseline } from '@material-ui/core'; import TeacherService from '../../api/TeacherService'; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from '../../Authentication/AuthenticationService'; import DeleteIcon from '@material-ui/icons/Delete'; import { AddOutlined, ArchiveRounded, EditOutlined, PageviewOutlined, ThreeSixty } from '@material-ui/icons'; import IconButton from '@material-ui/core/IconButton'; import Tooltip from '@material-ui/core/Tooltip'; import UpdateGradeModal from './EditGradeModal'; import SubjectService from '../../api/SubjectService'; export default class TestItemDetailsView extends Component{ constructor(props){ super(props) this.state ={ subjectName:this.props.match.params.subjectName, testRecords:[], isArchived:'', showModal:false, showError:false, message:'', selectedPupilId:'', testId:this.props.match.params.id, testName:this.props.match.params.name } this.addTokentoAuthenticatioHeader = this.addTokentoAuthenticatioHeader.bind(this); this.loadPupilsByTestId = this.loadPupilsByTestId.bind(this); this.refresh = this.refresh.bind(this); this.editGrade = this.editGrade.bind(this); this.onHide = this.onHide.bind(this); this.showEditModal = this.showEditModal.bind(this); } onHide(){ this.setState({ showModal:false, selectedPupilId:'', }) this.refresh(); } editGrade(newValue){ console.log(`Enterred Grade: ${newValue}`) this.addTokentoAuthenticatioHeader(); TeacherService.updateTestRecordGrade(this.state.testId,this.state.selectedPupilId,newValue) .then( response=>{ this.onHide(); this.refresh(); }).catch(error=>{ console.log(error) this.onHide(); this.refresh(); this.setState({ showError:true, message:'Grade Could not be editted' }) }) } componentDidMount(){ this.refresh(); } showEditModal(){ this.setState({ showModal:true }) } refresh(){ this.addTokentoAuthenticatioHeader(); this.loadSubjectDetails(); this.loadPupilsByTestId(); } loadSubjectDetails(){ SubjectService.getSubjectDetailsByName(this.state.subjectName).then( response=>{ this.setState({ isArchived:response.data.is_archived }) console.log(this.state.subjectDetails) } ).catch(error=>console.log(error)) } loadPupilsByTestId(){ TeacherService.fetchAllPupilsWithGradesByTestId(this.state.testId).then( response=>{ this.setState({ testRecords:response.data }) //this.refresh(); } ).catch(error=>console.log(error)) } addTokentoAuthenticatioHeader(){ AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); } render(){ return ( <div className="root"> {this.state.showError && <CustomAlert errorMessage={this.state.message} severity='error' onCancel = {()=>{ this.setState({ showError:false, message:'' }) }}/>} <CssBaseline/> <UpdateGradeModal show={this.state.showModal} onHide ={this.onHide} onSubmit={this.editGrade} /> <Grid container spacing={3} > <Grid item xs={12}> <Paper className="paper" elevation={2}> <Box> <table className="table"> <thead> <tr> <th>Pupil Id</th> <th>Pupil Name</th> <th>Test Id</th> <th>Test Name</th> <th>Grade</th> </tr> </thead> <tbody> { this.state.testRecords.map( testRecords=> <tr> <td>{testRecords.pupilId}</td> <td>{`${testRecords.firstName} ${testRecords.lastName}`}</td> <td>{`${testRecords.testId}`}</td> <td>{`${this.state.testName}`}</td> <td>{`${testRecords.grade==null?0:testRecords.grade}`}</td> {!this.state.isArchived && <td> <IconButton onClick={()=>{ this.setState({ selectedPupilId:testRecords.pupilId }) this.showEditModal(); }}> <Tooltip title="Edit"> <EditOutlined/> </Tooltip> </IconButton> </td>} </tr> ) } </tbody> </table> </Box> </Paper> </Grid> </Grid> </div> ); } }<file_sep>import React from 'react'; import {FaBars} from "react-icons/fa"; import * as AiIcons from "react-icons/ai"; import { USER_ID, USER_ROLE } from '../../../Authentication/AuthenticationService'; import AdminDashboard from '../../AdminView/AdminDashBoard'; const name=sessionStorage.getItem(USER_ID); export const SidebarData =[ { title: 'Home', role:'ADMIN', description:'Dashboard', path:`/admin/dashboard/${sessionStorage.getItem(USER_ID)}`, icon:<AiIcons.AiFillHome/>, cName: 'nav-text' }, { title: 'Home', role:'TEACHER', description:'Dashboard', path:`/teacher/${sessionStorage.getItem(USER_ID)}/subjects`, icon:<AiIcons.AiFillHome/>, cName: 'nav-text' }, { title: 'Home', role:'PUPIL', description:'Dashboard', path:`/pupil/welcome/${sessionStorage.getItem(USER_ID)}`, icon:<AiIcons.AiFillHome/>, cName: 'nav-text' }, { title:'Settings', description:'User Settings', path:`/user/settings`, icon:<AiIcons.AiFillSetting/>, cName: 'nav-text' }, { title: 'Logout', description:'Logout', path:'/logout', icon:<AiIcons.AiOutlineLogout/>, cName: 'nav-text' }, { title: 'Login', description:'Login', path:'/', icon:<AiIcons.AiOutlineLogin/>, cName: 'nav-text' }, ] <file_sep># SchoolManagementSystem Prerequisites: 1. install npm 2. node js, 3. install visual studio code 4. install eclipse IDE 5. install java Please refer to the following video which running frontend and backed app:In this i walk through the entire setup: https://www.youtube.com/watch?v=_HTMtAdfZyo For Deploying the Frontend, Follow the following steps: 1. unzip the schoolManagment.zip folder 2. goto frontend folder --> open terminal/cmd and goto the frontend folder in the unzip folder and run the following commands: a. npm install b. npm start 3. The frontend application will automatically launch in chrome on http://localhost:4500/login For Deploying backend, Follow the following steps: 1. unzip the schoolManagment.zip folder.. if not already done a. you will see the following folder structure -SchoolManagmentSystem -backend -schoolManagementSystem -src -main -java -com.lwazir.project.schoolManagementsystem -controllers -errors -jwt -model -repository -utility -SchoolManagementsystemApplication.java [this is the main file that has to be run after importing the project in Eclipse.. the installation process is explained below] -test -target -pom.xml -frontend -public -src -package.json 2. Install Eclipse IDE and Java 8 3. open eclipse IDE - it will ask for a worksapce ---Just create a blank folder any where on your machine and while selecting workspace give that path of it there. -After selecting and intialization of the workspace .--> goto file in the tool bar menu of eclipse IDE- -->goto import --> window will popup --> select maven --> select existing maven project --> Here you have to browse to the location where you have unzipped the zipped file and select the path upto -Backend/schoolManagementsystem --> please note: that while importing the maven project please select the path upto the folder that is containing the pom.xml file --> After succesfully importing the project go to the SchoolManagementsystemApplication.java file in the com.lwazir.project.schoolManagementsystem package ---> after selecting and opening the file ---> Right Click on the file --> A menu will appear --> select run as --> select Java Application ----The application will launch on Localhost:9000 4. Once the server is running you can login into the front end application using the following credentials: 1. Admin : username: lwazir password: <PASSWORD> 2. Pupil: username:username5 password: <PASSWORD> 3. Teacher username: teacher password: <PASSWORD> 5. Once server is running , you can also access the H2 Database on the following url: --http://localhost:9000/h2-console/login.jsp --if it prompts for username and password or only password --> just leave it blank and login 6. You can also access the api Documentation on the following url: 1.http://localhost:9000/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config. 2.https://bit.ly/3xuIokc <file_sep>package com.lwazir.project.schoolManagementsystem.model.joins.dto; public class SubjectByCourseIdDTO { private String subjectName; public SubjectByCourseIdDTO(String subjectName) { super(); this.subjectName = subjectName; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } } <file_sep>import { PinDropSharp } from '@material-ui/icons'; import React from 'react'; import { Button } from 'react-bootstrap'; import './ListCardItem.css'; export default function ListCardItem(props){ const onClickHandler = () =>{ console.log("OnClickHandler"); props.onDeAssign(); } return ( <li className ="listItem" key={props.key}> <div class="card"> <div class="container"> <h4 className="pupilName"><b>{props.name}</b></h4> <Button className="button" onClick={onClickHandler}>De-Assign</Button> </div> </div> </li> ); } <file_sep>import React,{ Component } from "react"; import moment from 'moment' import { Formik, Form, Field, ErrorMessage } from 'formik'; import UserService from "../../api/UserService"; import AuthenticationService, { USER_TOKEN_ATTRIBUTE_NAME } from "../../Authentication/AuthenticationService"; export default class EditUserComponent extends Component{ constructor(props) { super(props) this.state = { id: this.props.match.params.id, firstName: '', lastName:'', role:'', username:'', password:'' } this.onSubmit = this.onSubmit.bind(this) this.validate = this.validate.bind(this) } componentDidMount() { if (this.state.id === -1) { return } AuthenticationService.setupAxiosInterceptors( AuthenticationService.createJWTToken( localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) ) ); // let username = AuthenticationService.getLoggedInUserName() UserService.executeRetrieveUserByIdService(this.state.id) .then(response => { console.log(response.data) this.setState({ username: response.data.username, firstName:response.data.firstName, lastName: response.data.lastName, role:response.data.role }) } ) } validate(values) { let errors = {} if (!values.firstName) { errors.firstName = 'Enter the First Name' } if (!values.lastName) { errors.lastName = 'Enter the Last Name' } if (!values.role) { errors.role = 'Enter a User Role' } if(!values.username){ errors.username = 'Enter a User Name' } /** if (!moment(values.targetDate).isValid()) { errors.targetDate = 'Enter a valid Target Date' } */ return errors } onSubmit(values) { // let username = AuthenticationService.getLoggedInUserName() let userDetails = { id: this.state.id, username: values.username, firstName: values.firstName, lastName:values.lastName, role:values.role, password:<PASSWORD>, //targetDate: values.targetDate } console.log(this.state.id); if (this.state.id < 0) { UserService.createUser(userDetails) .then(() => this.props.history.push('/users')) } else { UserService.updateUser(this.state.id, userDetails) .then(() => this.props.history.push('/users')) } console.log(values); } render() { let { firstName, lastName, role, username, password } = this.state //let targetDate = this.state.targetDate return ( <div> {this.state.id==-1 && <h1>Add User</h1>} {this.state.id!=-1 && <h1>Edit User</h1>} <div className="container"> <Formik initialValues={{ firstName, lastName,role,username,password }} onSubmit={this.onSubmit} validateOnChange={false} validateOnBlur={false} validate={this.validate} enableReinitialize={true} > { (props) => ( <Form> <ErrorMessage name="firstName" component="div" className="alert alert-warning" /> <ErrorMessage name="lastName" component="div" className="alert alert-warning" /> <ErrorMessage name="username" component="div" className="alert alert-warning" /> <ErrorMessage name="role" component="div" className="alert alert-warning" /> <fieldset className="form-group"> <label>First Name</label> <Field className="form-control" type="text" name="firstName" /> </fieldset> <fieldset className="form-group"> <label>Last Name</label> <Field className="form-control" type="text" name="lastName" /> </fieldset> <fieldset className="form-group"> <label>User Name</label> <Field className="form-control" type="text" name="username" /> </fieldset> <fieldset> <label htmlFor="Roles" style={{ display: 'flex' }}> User Role </label> <Field as="select" className="form-control" name="role" > <option value="" label="Select a Role" /> <option value="TEACHER" label="Teacher" /> <option value="PUPIL" label="PUPIL" /> <option value="ADMIN" label="ADMIN" /> </Field> </fieldset> <fieldset className="form-group"> <label>New Password</label> <Field className="form-control" type="<PASSWORD>" name="password" /> </fieldset> <button className="btn btn-success" type="submit">Save</button> </Form> ) } </Formik> </div> </div> ) } }<file_sep>import axios from "axios"; import jwtDecode from "jwt-decode"; export const USER_TOKEN_ATTRIBUTE_NAME = 'authenticatedUser' export const USER_ROLE = 'USER_ROLE' export const USER_ID = 'USER_ID' export let decodedToken='' class AuthenticationService { executeJWtAuthenticationService(username,password){ return axios.post("http://localhost:9000/authenticate",{ username, password }); } registerSuccesfullLoginForJwt(username,token){ localStorage.setItem(USER_TOKEN_ATTRIBUTE_NAME,token) sessionStorage.setItem(USER_ROLE,this.getRoleFromToken()) sessionStorage.setItem(USER_ID,username) this.setupAxiosInterceptors(this.createJWTToken(token)) } createJWTToken(token) { return 'Bearer ' + token } setupAxiosInterceptors(token) { axios.interceptors.request.use( (config) => { if (this.isUserLoggedIn()) { config.headers.authorization = token } return config } ) } logout() { localStorage.removeItem(USER_TOKEN_ATTRIBUTE_NAME); sessionStorage.removeItem(USER_ID); sessionStorage.removeItem(USER_ROLE) } isUserLoggedIn() { let user = localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME) if (user === null) return false return true } getRoleFromToken(){ let token = localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME); try{ let role = JSON.stringify(jwtDecode(token)).split(",")[1].split(":")[2].split('"')[1] console.log(role) return role; }catch(error){ console.log('Error While Extracting Role from Token: '+error) } } getExpiryDateFromToken(){ let token = localStorage.getItem(USER_TOKEN_ATTRIBUTE_NAME); try{ let expiry_date= JSON.stringify(jwtDecode(token)).split(",")[2].split('"')[2].split(":")[1]; //console.log(expiry_date); return expiry_date; }catch(error){ console.log('Error While Extracting Expiry Time from Token: '+error) } } } export default new AuthenticationService() <file_sep>package com.lwazir.project.schoolManagementsystem.model; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MapsId; import javax.persistence.Id; import com.lwazir.project.schoolManagementsystem.model.compositekeys.PupilTestRecordKey; @Entity public class PupilTestRecord { //@EmbeddedId // PupilTestRecordKey id; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; // @ManyToOne // @MapsId("pupilId") // @JoinColumn(name = "pupil_id") Long pupilId; // @ManyToOne // @MapsId("testId") // @JoinColumn(name = "test_id") Long testId; Long grade; public PupilTestRecord() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getPupilId() { return pupilId; } public void setPupilId(Long pupilId) { this.pupilId = pupilId; } public Long getTestId() { return testId; } public void setTestId(Long testId) { this.testId = testId; } public Long getGrade() { return grade; } public void setGrade(Long grade) { this.grade = grade; } } <file_sep> import { Modal, ModalBody ,Button} from 'react-bootstrap'; import React,{useState} from 'react'; import TextField from '@material-ui/core/TextField'; import { Alert } from '@material-ui/lab'; import { Component } from 'react'; import TeacherService from '../../api/TeacherService'; export default class NewTest extends Component { constructor(props){ super(props) this.state={ subjectName:props.subjectName, enterredTestName:'', showError:false } this.handleTestNameFieldChanged = this.handleTestNameFieldChanged.bind(this); this.submitHandler = this.submitHandler.bind(this); this.addTest = this.addTest.bind(this); console.log(`${this.state.enterredTestName} ${this.state.testId}`); } componentDidMount(){ console.log(`Initial Test Name: ${this.state.enterredTestName}`) this.setState({ enterredTestName:this.props.selectTestName }) } handleTestNameFieldChanged(event) { this.setState({ enterredTestName:event.target.value } ) } submitHandler(){ if(this.state.enterredTestName.length<4) { this.setState({ showError:true }) console.log(this.state.enterredTestName); this.setState({ enterredTestName:'' }) } else{ this.addTest(); } } addTest(){ let test = { testname:this.state.enterredTestName } TeacherService.addTest(this.state.subjectName,test) .then(response=>{ this.setState({ showError:false, enterredTestName:'' }) this.props.onHide(); console.log(response) }) .catch(error=>console.log(error)) } render(){ return ( <> <Modal show={this.props.show} onHide={this.props.onHide} > <Modal.Header closeButton> New Test </Modal.Header> <Modal.Body> <div className="container"> {this.state.showError && <Alert severity="error">Test Name should contain atleast 4 characters!</Alert>} <TextField variant="outlined" margin="normal" required fullWidth id="testName" label="Test Name" name="testName" value={this.state.enterredTestName} onChange={this.handleTestNameFieldChanged} autoFocus /> </div> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={this.props.onHide}> Close </Button> <Button variant="primary" onClick={this.submitHandler}> Save Changes </Button> </Modal.Footer> </Modal> </> ); } } <file_sep>import React , { Component } from "react"; export default class ErrorComponent extends Component{ render(){ return ( <div>Error 404: Page Not Found</div> ); } }
4cb71c3ac6f2b3d0fa214f8041b876d7f47cecf4
[ "JavaScript", "Java", "Markdown", "SQL" ]
45
Java
wazir12/SchoolManagementSystem
47d79453de3964bfa7e552e87b790149d3fd4ced
9aebb1cfd54d68e7e37e7394887448683dedbd62
refs/heads/master
<file_sep>// Brunch automatically concatenates all files in your // watched paths. Those paths can be configured at // config.paths.watched in "brunch-config.js". // // However, those files will only be executed if // explicitly imported. The only exception are files // in vendor, which are never wrapped in imports and // therefore are always executed. // Import dependencies // // If you no longer want to use a dependency, remember // to also remove its path from "config.paths.watched". import "phoenix_html" import React from "react" import ReactDOM from "react-dom" import { BrowserRouter as Router, Route, Link } from 'react-router-dom' class HelloReact extends React.Component { render() { return ( <Router> <div> <Route exact path="/" component={Home}/> <Route exact path="/login" component={Login}/> </div> </Router> ) } } class Home extends React.Component { render() { return ( <div> <h1>Hello React!</h1> <Link to="/login">Login</Link> </div> ) } } class Login extends React.Component { render() { return ( <div> <h1>Hello Boring Login Page!</h1> <Link to="/">Home</Link> </div> ) } } ReactDOM.render( <HelloReact/>, document.getElementById("hello-react") ) // Import local files // // Local files can be imported directly using relative // paths "./socket" or full ones "web/static/js/socket". // import socket from "./socket" <file_sep>import React from "react"; import axios from "axios"; class Form extends React.Component { constructor() { super(); this.state = { title: '', subtitle: '', image: '', link: '', author: '' }; } handleTitle(event) { this.setState({ title: event.target.value }) } handleSubtitle(event) { this.setState({ subtitle: event.target.value }) } handleImage(event) { this.setState({ image: event.target.value }) } handleLink(event) { this.setState({ link: event.target.value }) } handleAuthor(event) { this.setState({ author: event.target.value }) } handleSubmit (event) { event.preventDefault(); axios({ method: 'post', headers: {"Content-Type": "application/json"}, url: 'http://localhost:4000/api/blogs', data: { blogs: { title: this.state.title, subtitle: this.state.subtitle, image: this.state.image, link: this.state.link, author: this.state.author } } }); } render() { return ( <form onSubmit={this.handleSubmit.bind(this)}> <div className="field"> <label className="label">Title</label> <div className="control"> <input className="input" type="text" value = {this.state.title} onChange = {this.handleTitle.bind(this)} /> </div> </div> <div className="field"> <label className="label">Subtitle</label> <div className="control"> <input className="input" type="text" value = {this.state.subtitle} onChange = {this.handleSubtitle.bind(this)} /> </div> </div> <div className="field"> <label className="label">Image</label> <div className="control"> <input className="input" type="text" placeholder="Enter Image URL" onChange = {this.handleImage.bind(this)} /> </div> </div> <div className="field"> <label className="label">Link</label> <div className="control"> <input className="input" type="text" value = {this.state.link} onChange = {this.handleLink.bind(this)} /> </div> </div> <div className="field"> <label className="label">Author</label> <div className="control"> <input className="input" type="text" value = {this.state.author} onChange = {this.handleAuthor.bind(this)} /> </div> </div> <button type="submit" value="Submit" className="button is-primary" > Submit </button> </form> ) } } export default Form <file_sep>import React from "react"; import BlogCard from '../presentationals/BlogCard'; import axios from "axios"; class Blogs extends React.Component { constructor() { super(); this.state = { blogs: [] }; } componentWillMount() { axios.get('http://localhost:4000/blogs') .then(response => { this.setState({ blogs: response.data.blogs }); }) .catch(error => { console.log(error); }); } render() { const posts = this.state.blogs.map((blog, index) => <BlogCard key = { index } title = { blog.title } subtitle = { blog.subtitle } image = { blog.image } link = { blog.link } author = { blog.author } /> ); return ( <div> {posts} </div> ) } } export default Blogs <file_sep>import React from "react"; import BlogCard from '../presentationals/BlogCard'; import axios from "axios"; import { Link } from 'react-router-dom'; class Blogs extends React.Component { constructor() { super(); this.state = { blogs: [] }; } componentWillMount() { axios.get('http://localhost:4000/api/blogs') .then(response => { this.setState({ blogs: response.data.blogs }); }) .catch(error => { console.log(error); }); } render() { const posts = this.state.blogs.map((blog, index) => <BlogCard key = { index } title = { blog.title } subtitle = { blog.subtitle } image = { blog.image } link = { blog.link } author = { blog.author } /> ); return ( <div> <div className="is-primary is-large" style = {{ position: "absolute", top: "10px", right: "10px", padding: "10px 15px", background: "#00D1B2" }} > <Link to="/create" style = {{ color: "white" }} > Create Blog Post </Link> </div> <div className="is-primary is-large" style = {{ position: "absolute", top: "80px", right: "10px", padding: "10px 15px", background: "#00D1B2" }} > <Link to="/update" style = {{ color: "white" }} > Edit Blog Post </Link> </div> {posts} </div> ) } } export default Blogs <file_sep># Full-Stack React With Phoenix Official repo for my ebook, [Full-Stack React With Phoenix](http://bit.ly/2tYrhWp). ![](https://cdn-images-1.medium.com/max/1600/1*LiC2xMlEVIkaDuBwgtKPAg.png) <file_sep>import React from "react"; import {Socket} from "phoenix"; import UserMessage from '../presentationals/UserMessage'; import ServerMessage from '../presentationals/ServerMessage'; class Chat extends React.Component { constructor() { super(); this.state = { inputMessage: "", messages: [] } let socket = new Socket("/socket", {params: {token: window.userToken} }); socket.connect(); this.channel = socket.channel("room:lobby", {}); } componentWillMount() { this.channel.join() .receive("ok", response => { console.log("Joined successfully", response) }) this.channel.on("new_msg", payload => { this.setState({ messages: this.state.messages.concat(payload.body) }) }) } handleInputMessage(event) { this.setState({ inputMessage: event.target.value }) } handleSubmit(event) { event.preventDefault(); this.channel.push("new_msg", {body: this.state.inputMessage}) this.setState({ messages: this.state.messages.concat(this.state.inputMessage), inputMessage: "" }) } render() { const messages = this.state.messages.map((message, index) => { if(index % 2 == 0) { return ( <UserMessage key = { index } username = { "GenericUsername" } message = { message } /> ) } else { return ( <ServerMessage key = { index } username = { "Server" } message = { message } /> ) } }); return ( <div> <form onSubmit={this.handleSubmit.bind(this)} > <div className="field"> <label className="label" style={{ textAlign: "left" }} > Chat With Phoenix: </label> <div className="control"> <input className="input" type="text" style={{ marginTop: "10px" }} value = {this.state.inputMessage} onChange = {this.handleInputMessage.bind(this)} /> </div> </div> <button type="submit" value="Submit" className="button is-primary" style={{ marginTop: "10px" }} > Submit </button> </form> <div className="flex-container" style={{ display: "flex", flexDirection: "column", alignItems: "flexStart", justifyContent: "flexStart", margin: "auto", width: "100%" }} > {messages} </div> </div> ) } } export default Chat <file_sep>import React from "react"; class BlogCard extends React.Component { render() { return ( <div className="card"> <div className="card-image"> <figure className="image is-4by3"> <a href={this.props.link}> <img src={this.props.image} alt="Image" /> </a> </figure> </div> <div className="card-content"> <div className="media"> <div className="media-content"> <p className="title is-4">{this.props.title}</p> <p className="subtitle is-6">{this.props.subtitle}</p> <p className="subtitle is-6">By {this.props.author}</p> </div> </div> </div> </div> ) } } export default BlogCard
085129f843a151044dec47c22890d6352aa5ed6d
[ "JavaScript", "Markdown" ]
7
JavaScript
michaelmang/full-stack-react-phoenix
a157f789b8bcabc4609b580f0ef44279962a0d44
b1ef9ca8a310b6ba6f538bf8f1febc87b6355686
refs/heads/master
<file_sep>package com.practice.mlkitnlp import android.os.Bundle import android.provider.Telephony import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.textclassifier.ConversationActions import android.widget.Toast import androidx.databinding.DataBindingUtil import com.google.mlkit.nl.smartreply.* import com.google.mlkit.nl.smartreply.component.SmartReplyComponentRegistrar import com.practice.mlkitnlp.databinding.FragmentLanguageIdentifierBinding class SmartReplyFragment : Fragment() { private lateinit var binding:FragmentLanguageIdentifierBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding=DataBindingUtil.inflate(layoutInflater,R.layout.fragment_language_identifier,container,false) val conversation=ArrayList<TextMessage>() conversation.add(TextMessage.createForLocalUser("how are you",System.currentTimeMillis())) conversation.add(TextMessage.createForRemoteUser("fine",System.currentTimeMillis(),"recipient1")) //The local user is the user itself, // the remote user is the person who is on the other sie of the conversation, // the userId can be any string that uniquely identifies the person on other side //the userId can be firebase userId in case of firebase conversation.add(TextMessage.createForLocalUser("how are you",System.currentTimeMillis())) conversation.add(TextMessage.createForRemoteUser("fine",System.currentTimeMillis(),"recipient1")) conversation.add(TextMessage.createForLocalUser("how are you",System.currentTimeMillis())) conversation.add(TextMessage.createForRemoteUser("not fine",System.currentTimeMillis(),"recipient1")) conversation.add(TextMessage.createForLocalUser("how are you",System.currentTimeMillis())) conversation.add(TextMessage.createForRemoteUser("fine and you",System.currentTimeMillis(),"recipient1")) conversation.add(TextMessage.createForLocalUser("how are you",System.currentTimeMillis())) conversation.add(TextMessage.createForRemoteUser("sleepy",System.currentTimeMillis(),"recipient1")) conversation.add(TextMessage.createForLocalUser("how are you",System.currentTimeMillis())) conversation.add(TextMessage.createForRemoteUser("unwell",System.currentTimeMillis(),"recipient1")) conversation.add(TextMessage.createForLocalUser("how are you",System.currentTimeMillis())) conversation.add(TextMessage.createForRemoteUser("shut up",System.currentTimeMillis(),"recipient1")) val smartReplyGenerator=SmartReply.getClient() binding.button.setOnClickListener { smartReplyGenerator.suggestReplies(conversation) .addOnCompleteListener { if(it.isSuccessful) { if(it.result!=null) { if (it.result!!.status == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) { Toast.makeText(requireContext(),"Language not supported. Only English",Toast.LENGTH_LONG).show() } else if (it.result!!.status == SmartReplySuggestionResult.STATUS_SUCCESS) { var s="" for(suggestion in it.result!!.suggestions) s="$s${suggestion.text} | " binding.textView.text=s } } else { Toast.makeText(requireContext(),"task result ${it.result}",Toast.LENGTH_LONG).show() Log.d("div","task result ${it.result}") } } else { Toast.makeText(requireContext(),"Task failed ${it.exception}",Toast.LENGTH_LONG).show() Log.d("div", "Task failed ${it.exception}") } } } return binding.root } }<file_sep>package com.practice.mlkitnlp import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.databinding.DataBindingUtil import androidx.navigation.findNavController import com.practice.mlkitnlp.databinding.FragmentChooserBinding class ChooserFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val binding= DataBindingUtil.inflate<FragmentChooserBinding>(layoutInflater,R.layout.fragment_chooser,container,false) val list=ArrayList<String>(); list.add("Language Identifier") list.add("Language Translation") list.add("Smart Reply") val arrayAdapter= ArrayAdapter<String>(requireContext(),R.layout.support_simple_spinner_dropdown_item,list) binding.listView.adapter=arrayAdapter binding.listView.setOnItemClickListener { parent, view, position, id -> when(position) { 0 -> view?.findNavController() ?.navigate(R.id.action_chooserFragment_to_languageIdentifierFragment) 1 -> view?.findNavController() ?.navigate(R.id.action_chooserFragment_to_translationFragment) 2-> view?.findNavController() ?.navigate(R.id.action_chooserFragment_to_smartReplyFragment) } } return binding.root } }<file_sep>package com.practice.mlkitnlp import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.google.mlkit.nl.languageid.LanguageIdentification import com.google.mlkit.nl.languageid.LanguageIdentificationOptions import com.google.mlkit.nl.languageid.LanguageIdentifier import com.practice.mlkitnlp.databinding.FragmentLanguageIdentifierBinding class LanguageIdentifierFragment : Fragment() { lateinit var binding:FragmentLanguageIdentifierBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding= DataBindingUtil.inflate(layoutInflater,R.layout.fragment_language_identifier,container,false) val options=LanguageIdentificationOptions.Builder() .setConfidenceThreshold(0.3f) .build() val languageIdentifier=LanguageIdentification.getClient(options) binding.button.setOnClickListener { languageIdentifier.identifyPossibleLanguages(binding.editText.text.toString()) .addOnCompleteListener { if(it.isSuccessful) { if(it.result!=null) { var s="" for (language in it.result!!) { s+=language.languageTag+"\t"+(language.confidence*100)+"%\n" } binding.textView.text=s } else Log.d("div","result ${it.result}") } else Log.d("div","Task failed ${it.exception}") } } return binding.root } }<file_sep>package com.practice.mlkitnlp import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.Toast import androidx.databinding.DataBindingUtil import com.google.mlkit.common.model.DownloadConditions import com.google.mlkit.nl.languageid.LanguageIdentification import com.google.mlkit.nl.translate.TranslateLanguage import com.google.mlkit.nl.translate.Translation import com.google.mlkit.nl.translate.TranslatorOptions import com.practice.mlkitnlp.databinding.FragmentTranslationBinding class TranslationFragment : Fragment() { private lateinit var binding:FragmentTranslationBinding private var toLang=TranslateLanguage.ENGLISH override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding=DataBindingUtil.inflate(layoutInflater,R.layout.fragment_translation,container,false) var list=ArrayList<String>() list.add("English") list.add("Hindi") list.add("German") list.add("French") list.add("Japanese") val adapter=ArrayAdapter<String>(requireContext(),R.layout.support_simple_spinner_dropdown_item,list) binding.spinner.adapter=adapter binding.spinner.onItemSelectedListener=object: OnItemSelectedListener{ override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { when (position) { 0 -> toLang=TranslateLanguage.ENGLISH 1 -> toLang=TranslateLanguage.HINDI 2 -> toLang=TranslateLanguage.GERMAN 3 -> toLang=TranslateLanguage.FRENCH 4 -> toLang=TranslateLanguage.JAPANESE } } override fun onNothingSelected(parent: AdapterView<*>?) { toLang=TranslateLanguage.ENGLISH } } val languageIdentifier=LanguageIdentification.getClient() binding.button.setOnClickListener { languageIdentifier.identifyLanguage(binding.editText.text.toString()) .addOnCompleteListener { if(it.isSuccessful) { if(it.result!=null) { if(it.result!="und" && TranslateLanguage.fromLanguageTag(it.result!!)!=null) { Log.d("div","Translate L35 ${it.result} ${TranslateLanguage.fromLanguageTag(it.result!!)}") binding.textViewCurrentLanguage.text=it.result translate(binding.editText.text.toString(), TranslateLanguage.fromLanguageTag(it.result!!)!!) } else binding.textViewCurrentLanguage.text="Undefined Language" } else binding.textViewCurrentLanguage.text="null" } else { binding.textViewCurrentLanguage.text="Error ${it.exception}" Log.d("div","Identification Task Failed ${it.exception}") } } } return binding.root } private fun translate(text: String, fromLang: String) { val options=TranslatorOptions.Builder() .setSourceLanguage(fromLang) .setTargetLanguage(toLang) .build() val translator=Translation.getClient(options) val conditions=DownloadConditions.Builder() .build() //You can provide conditions like wifi and charging here translator.downloadModelIfNeeded(conditions) .addOnCompleteListener { it1 -> if(it1.isSuccessful) { Toast.makeText(requireContext(),"Translation model downloaded successfully",Toast.LENGTH_LONG).show() translator.translate(text) .addOnCompleteListener { if(it.isSuccessful) { binding.textView.text=it.result Log.d("div","Translation successful ${it.result}") } else { Toast.makeText(requireContext(),"Translation failed",Toast.LENGTH_LONG).show() Log.d("div","Translation Task failed ${it.exception}") } } } else { Toast.makeText(requireContext(),"Translation model couldn't be downloaded",Toast.LENGTH_LONG).show() Log.d("div","Translation Download Task failed ${it1.exception}") } } } }
a3735643839cbe819a164c3572dd557e56591517
[ "Kotlin" ]
4
Kotlin
divyanshutw/MLKit_NLP
dc4d7e34393727d3b7ee67d7578afd7225742681
4b161b11e5300805ab22e1b8bf61a66b77600937
refs/heads/master
<file_sep>#include <arpa/inet.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // string manipulation #include <sys/socket.h> #include <unistd.h> // read, write #include "strfunc.h" #include "request.h" #define BACKLOG 10 // queue length #define MAX_HEADER_SIZE 65536 #define HTML_FOLDER "html" #define DBG 1 struct client_param { int client_sd; char client_ip[32]; }; int start_socket(int port); void *conn_handler(void *param); void get_response(char *res, char *client_header); int load_file_to_buffer(char *file_name, char *buffer); int main(int argc, char *argv[]) { if (argc != 2) { printf("Port is required\n"); exit(-1); } int port = atoi(argv[1]); int sd = start_socket(port); // Define client variables struct sockaddr_in client; socklen_t client_len = sizeof(struct sockaddr_in); while (1) { // Accept int client_sd = accept(sd, (struct sockaddr *)&client, &client_len); char client_ip[32] = {0}; if (client_sd < 0) { printf("Accept failed\n"); exit(-1); } // Format client ip address and port into client_ip sprintf(client_ip, "%s:%d", inet_ntoa(client.sin_addr), client.sin_port); printf("Connection accepted with client %s\n", client_ip); pthread_t conn_thread; struct client_param param; param.client_sd = client_sd; strcpy(param.client_ip, client_ip); if (pthread_create(&conn_thread, NULL, conn_handler, &param) < 0) { printf("Create thread failed"); exit(-1); } sleep(1); // prevent threading problem } return 0; } /************************************************************ * Function: start_socket * Create a socket, bind and listen * Parameters: * port: listening port * Returns: * sd (socket descriptor) ************************************************************/ int start_socket(int port) { // Create socket int sd = socket(AF_INET, SOCK_STREAM, 0); // SOCK_STREAM for TCP if (sd < 1) { printf("Couldn't create socket\n"); exit(-1); } if (DBG) printf("Socket created, sd = %d\n", sd); // Set server configuration struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; // enable any ip_addr server.sin_port = htons(port); // Bind if (bind(sd, (struct sockaddr *)&server, sizeof(server)) < 0) { printf("Bind failed\n"); exit(-1); } if (DBG) printf("Bind sd(%d) successful\n", sd); // Listen if (listen(sd, BACKLOG) < 0) { printf("Listen failed\n"); exit(-1); } if (DBG) printf("Listen successful\n"); printf("HTTP Server running on port %d\n", port); return sd; } /************************************************************ * Function: conn_handler * Thread executing function, read and write with client by given client_sd * Parameters: * void *param - a client_param structure * Returns: * 0 - successful ************************************************************/ void *conn_handler(void *param) { if (DBG) printf("New thread created\n"); struct client_param *cp = (struct client_param *)param; int client_sd = cp->client_sd; char* client_ip = cp->client_ip; // Read char client_header[MAX_HEADER_SIZE] = {0}; if (DBG) printf("Ready to read from %s\n", client_ip); int read_size = read(client_sd, client_header, MAX_HEADER_SIZE); if (read_size < 0) { printf("Read failed\n"); exit(-1); } if (DBG) { printf("=== Read successful, client header ===\n"); printf("%s", client_header); printf("======================================\n"); } // Write // Define response char res[MAX_HEADER_SIZE] = {0}; get_response(res, client_header); if (write(client_sd, res, strlen(res)) < 0) { printf("Write failed\n"); exit(-1); } if (DBG) { printf("DBG - Write successful, respond to %s\n", client_ip); printf("DBG - Write content: \n%s\n\n", res); } close(client_sd); return 0; } void get_response(char *res, char *client_header) { // Parsing client header char line[32][128]; int i = 0, line_cnt = 0; while (i < strlen(client_header)) { i = get_str_line(client_header, i, line[line_cnt]); line_cnt++; } if (DBG) { printf("Header each line:\n"); for (int j = 0; j < line_cnt; j++) { printf("DBG - Each line: %s\n", line[j]); } } // Determine method int cursor = 0; char method[8], request_route[32]; cursor = get_str_until_space(line[0], cursor, method); printf("Method = %s\n", method); cursor = get_str_until_space(line[0], cursor, request_route); printf("Request Route = %s\n", request_route); // Get UserId char userid[32]; int errcode = get_from_two_str(client_header, COOKIE_USER_ID, "\n", userid); if (errcode != 0) { printf("%s%s\n", COOKIE_USER_ID, userid); } else { printf("Couldn't find %s\n", COOKIE_USER_ID); } // Separate request_route char routes[16][32]; int route_count = get_restful_route(request_route, routes); // Determine response file path if (strcmp(method, "GET") == 0) { printf("GET: %s\n", request_route); if (strcmp(routes[0], "api") == 0) { if (strcmp(routes[1], "member") == 0) { if (strcmp(routes[2], "get") == 0) { if (strcmp(routes[3], "id") == 0) { if (route_count == 5) { // id: fifth param printf("[Action] /api/member/get/id : %s\n", routes[4]); char member_info[1024]; int found = get_member_by_id(routes[4], member_info); if (found) sprintf(res, "HTTP/1.1 200 OK\r\n\r\n%s\r\n", member_info); else sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{}\r\n"); } else { // no id or more param strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else if (strcmp(routes[3], "all") == 0 && route_count == 4) { printf("[Action] /api/member/get/all\n"); char members_info[5120]; get_member_all(members_info); sprintf(res, "HTTP/1.1 200 OK\r\n\r\n%s\r\n", members_info); } else if (strcmp(routes[3], "admin") == 0 && route_count == 4) { printf("[Action] /api/member/get/admin\n"); char members_info[5120]; get_member_admin(members_info); sprintf(res, "HTTP/1.1 200 OK\r\n\r\n%s\r\n", members_info); } else if (strcmp(routes[3], "doctor") == 0 && route_count == 4) { char members_info[5120]; get_member_doctor(members_info); sprintf(res, "HTTP/1.1 200 OK\r\n\r\n%s\r\n", members_info); printf("[Action] /api/member/get/doctor\n"); } else if (strcmp(routes[3], "patient") == 0 && route_count == 4) { char members_info[5120]; get_member_patient(members_info); sprintf(res, "HTTP/1.1 200 OK\r\n\r\n%s\r\n", members_info); printf("[Action] /api/member/get/patient\n"); } } else { // /api/member/? strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else if (strcmp(routes[1], "prescription") == 0) { if (strcmp(routes[2], "get") == 0) { if (strcmp(routes[3], "id") == 0) { if (route_count == 5) { // id: fifth param printf("[Action] /api/prescription/get/id : %s\n", routes[4]); char prescription_info[1024]; int found = get_prescription_by_id(routes[4], prescription_info); if (found) sprintf(res, "HTTP/1.1 200 OK\r\n\r\n%s\r\n", prescription_info); else sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{}\r\n"); } else { // no id or more param strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else if (strcmp(routes[3], "all") == 0 && route_count == 4) { printf("[Action] /api/prescription/get/all\n"); char prescription_info[5120]; get_prescription_all(prescription_info); sprintf(res, "HTTP/1.1 200 OK\r\n\r\n%s\r\n", prescription_info); } else { // /api/prescription/get/? strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else { // /api/prescription/? strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else { // /api/? strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else { // /? strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else if(strcmp(method, "POST") == 0) { printf("POST: %s\n", request_route); if (strcmp(routes[0], "api") == 0) { if (strcmp(routes[1], "member") == 0) { char id[16], passwd[16], name[32], level[4], birthday[16], description[256]; if (strcmp(routes[2], "add") == 0 && route_count == 3) { get_json_val_by_key(client_header, "id", id); printf("[Action] /api/member/add id:%s\n", id); get_json_val_by_key(client_header, "passwd", passwd); get_json_val_by_key(client_header, "name", name); get_json_val_by_key(client_header, "level", level); get_json_val_by_key(client_header, "birthday", birthday); get_json_val_by_key(client_header, "description", description); if (DBG) printf("DBG - member add id(%s) passwd(%s) name(%s) level(%s) birthday(%s) description(%s)\n", id, passwd, name, level, birthday, description); // Fetch data int success = add_member(id, passwd, name, level, birthday, description); if (success) sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": true}\r\n"); else sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": false}\r\n"); } else if (strcmp(routes[2], "edit") == 0 && route_count == 3) { get_json_val_by_key(client_header, "id", id); printf("[Action] /api/member/edit id:%s\n", id); get_json_val_by_key(client_header, "passwd", <PASSWORD>); get_json_val_by_key(client_header, "name", name); get_json_val_by_key(client_header, "level", level); get_json_val_by_key(client_header, "birthday", birthday); get_json_val_by_key(client_header, "description", description); if (DBG) printf("DBG - member edit id(%s) passwd(%s) name(%s) level(%s) birthday(%s) description(%s)\n", id, passwd, name, level, birthday, description); // Fetch data int success = edit_member(id, passwd, name, level, birthday, description); if (success) sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": true}\r\n"); else sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": false}\r\n"); } else if (strcmp(routes[2], "delete") == 0 && route_count == 3) { get_json_val_by_key(client_header, "id", id); printf("[Action] /api/member/delete id:%s\n", id); // Fetch data int success = delete_member(id); if (success) sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": true}\r\n"); else sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": false}\r\n"); } else { // /api/member/? strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else if (strcmp(routes[1], "login") == 0) { char id[32], passwd[32]; get_json_val_by_key(client_header, "id", id); get_json_val_by_key(client_header, "passwd", passwd); printf("[Action] Login id:%s\n", id); login(id, passwd, res); } else if (strcmp(routes[1], "logout") == 0) { printf("[Action] Logout\n"); logout(res); } else if (strcmp(routes[1], "prescription") == 0) { char id[16], doctor_id[16], patient_id[16], date[16], prescription[256]; if (strcmp(routes[2], "add") == 0 && route_count == 3) { printf("[Action] /api/prescription/add\n"); get_json_val_by_key(client_header, "doctor_id", doctor_id); get_json_val_by_key(client_header, "patient_id", patient_id); get_json_val_by_key(client_header, "date", date); get_json_val_by_key(client_header, "prescription", prescription); if (DBG) printf("DBG - prescription add doctor_id(%s) patient_id(%s) date(%s) prescription(%s)\n", doctor_id, patient_id, date, prescription); // Fetch data int success = add_prescription(doctor_id, patient_id, date, prescription); if (success) sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": true}\r\n"); else sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": false}\r\n"); } else if (strcmp(routes[2], "edit") == 0 && route_count == 3) { get_json_val_by_key(client_header, "id", id); printf("[Action] /api/prescription/edit id:%s\n", id); get_json_val_by_key(client_header, "doctor_id", doctor_id); get_json_val_by_key(client_header, "patient_id", patient_id); get_json_val_by_key(client_header, "date", date); get_json_val_by_key(client_header, "prescription", prescription); if (DBG) printf("DBG - prescription edit id(%s) doctor_id(%s) patient_id(%s) date(%s) prescription(%s)\n", id, doctor_id, patient_id, date, prescription); // Fetch data int success = edit_prescription(id, doctor_id, patient_id, date, prescription); if (success) sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": true}\r\n"); else sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": false}\r\n"); } else if (strcmp(routes[2], "delete") == 0 && route_count == 3) { get_json_val_by_key(client_header, "id", id); printf("[Action] /api/prescription/delete id:%s\n", id); // Fetch data int success = delete_prescription(id); if (success) sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": true}\r\n"); else sprintf(res, "HTTP/1.1 200 OK\r\n\r\n{\"success\": false}\r\n"); } else { // /api/prescription/? strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else { // /api/? strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); } } else { // /? strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); return; } } else { printf("Mehtod \"%s\" is unrecognizable\n", method); } // char file_path[64], buffer[1024]; // if (strlen(request_route) == 1 && // compare_str(request_route, 0, "/", 0, 1) == 0) { // root // sprintf(file_path, "%s/index.html", HTML_FOLDER); // } else if (compare_str(request_route, 0, "/login", 0, 6) == 0) { // login // char id[16], passwd[16]; // get_from_two_str(client_header, "id=", "&", id); // get_from_two_str(client_header, "passwd=", "", passwd); // if (DBG) printf("In login, id=%s, passwd=%s\n", id, passwd); // login(id, passwd, res); // return; // } else if (compare_str(request_route, 0, "/logout", 0, 7) == 0) { // logout // logout(res); // return; // } else { // sprintf(file_path, "%s%s", HTML_FOLDER, request_route); // } // // // load file // if (load_file_to_buffer(file_path, buffer) == -1) { // err // strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); // } else { // get file successfully // strcpy(res, "HTTP/1.1 200 OK\r\n"); // strcat(res, buffer); // strcat(res, "\r\n"); // } } <file_sep># Team5 Lab2-Q1 Readme ## Purpose and Introduction This program include the sources of the following Connection-oriented file servers * Iterative server * Concurrent Multiprocessing server with one process per request * Concurrent Multithreading server with one thread per request * Concurrent Pre-forked Multiprocessing server * Concurrent Pre-threaded Multithreading server and two data files size are 900bytes and 1800bytes The client passes an file name to the server as a command line argument. The server receives the message, and check the file then sends it if it is exist. ## Files This folder contains five folders and server files * Iterative_tcp * MultiProcessing_tcp * MultiThreading_tcp * PreForked_tcp * PreThreaded_tcp (Each folder has own makefile to make `server` and `client` folder) * readme.md * 1800bytes.txt * 900bytes.txt ## Compile In each folder, type `make`, it generates two folder `server` and `client`. Use `make clean` to remove generated files ## Execute First, type `./server` to run the TCP server in terminal 1. (For Pre-allocated server type `./server` plus `an Integer` to indicate the number of children to pre_allocated) Second, type `./client ` plus `file name` to run the client in terminal 2. ## Test case and expected result test case1: (none Pre_allocated server) ``` $ ./server # server's terminal $ ./client 900bytes.txt # client's terminal ``` test case2: (Pre_allocated server) ``` $./server 5 # server's terminal $./client 900bytes.txt # client's terminal ``` <file_sep>#ifndef STRFUNC_H #define STRFUNC_H int compare_str(char *str1, int start1, char *str2, int start2, int len); int get_str_until_space(char *src, int src_start, char *dst); int get_restful_route(char *route, char dst[][32]); int get_str_line(char *src, int src_start, char *dst); void strcpy_with_pos_len(char *src, int src_start, int src_len, char *dst); int get_from_two_str(char *src, char *str1, char *str2, char *dst); int get_json_val_by_key(char *header, char *key, char *dst); #endif <file_sep>#ifndef REQUEST_H #define REQUEST_H #define LOGIN_SUCCESS_ADMIN 1 #define LOGIN_SUCCESS_DOCTOR 2 #define LOGIN_SUCCESS_PATIENT 3 #define LOGIN_NOT_EXIST 10 #define LOGIN_INFO_INCORRECT 11 #define COOKIE_USER_ID "HcsUserId=" #define COOKIE_USER_LEVEL "HcsUserLevel=" int get_member_by_id(char *id, char *dst_json); int get_member_all(char *dst_json); int get_member_admin(char *dst_json); int get_member_doctor(char *dst_json); int get_member_patient(char *dst_json); int add_member(char *id, char *passwd, char *name, char *level, char *birthday, char *description); int edit_member(char *id, char *passwd, char *name, char *level, char *birthday, char *description); int delete_member(char *id); int get_prescription_by_id(char *id, char *dst_json); int get_prescription_all(char *dst_json); int add_prescription(char *doctor_id, char *patient_id, char *date, char *prescription); int edit_prescription(char *id, char *doctor_id, char *patient_id, char *date, char *prescription); int delete_prescription(char *id); int login(char *id, char *passwd, char *res); void logout(char *res); int load_file_to_buffer(char *file_name, char *buffer); #endif <file_sep>Check readme.md in Q1 and Q2 folder <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/in.h> #include <math.h> #include <ctype.h> int main(){ //create a socket int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //assign the address and port struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(serv_addr)); //initial server address serv_addr.sin_family = AF_INET; //use IPV4 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //use local host serv_addr.sin_port = htons(2222); //port is 2222 bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); //listen the port listen(serv_sock, 20); //accept the request from client struct sockaddr_in clnt_addr; socklen_t clnt_addr_size = sizeof(clnt_addr); int clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size); //read data from client char buffer[1000000]; read(clnt_sock, buffer, sizeof(buffer)-1); int num = 1; char sym = buffer[0]; int len = strlen(buffer); int valid = 0; //flag //check if the number is negative if (sym == '-') { valid = 2; } //check if the input is a number if (valid != 2) { for (int i = 0; i < len; i++) { //check if the number is decimal if(buffer[i] == '.') { continue; } if(!(isdigit(buffer[i]))) { valid = 1; break; } } } //check if the number is zero if (valid != 1 && valid != 2) { num = atoi(buffer); if (num == 0) { valid = 3; } } switch (valid) { //case 0 the input is appropriate case 0: { int result1 = sqrt(num); char result[1000000]; sprintf(result, "%d", result1); write(clnt_sock, result, sizeof(result)); break; } //case 1 the input is not a number case 1: { char str2[] = "please input a number"; write(clnt_sock, str2, sizeof(str2)); break; } //case 2,3 the input is not bigger than zero case 2: case 3: { char str3[] = "please input a number bigger than zero"; write(clnt_sock, str3, sizeof(str3)); break; } } //close socket memset(buffer, 0, sizeof(buffer)); close(clnt_sock); close(serv_sock); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "strfunc.h" #include "request.h" int main() { char dst[128] = {0}; int new_pos = 0; // get_str_line test char *src1 = " \nabc\r\ndef\r\n"; printf("src1: %s\n", src1); printf("get_str_line test\n"); while (new_pos < strlen(src1)) { new_pos = get_str_line(src1, new_pos, dst); printf("%s, %d\n", dst, new_pos); } // get_str_until_space test char *src2 = " abc def gh"; printf("src2: %s\n", src2); new_pos = 0; printf("get_str_until_space test\n"); while (new_pos < strlen(src2)) { new_pos = get_str_until_space(src2, new_pos, dst); printf("%s, %d\n", dst, new_pos); } // strcpy_with_pos_len test char *src3 = "abcde"; char dst3[32]; printf("strcpy_with_pos_len\n"); strcpy_with_pos_len(src3, 1, 2, dst3); printf("%s\n", dst3); // get_from_two_str test char *src4 = "1234567890"; char dst4[32]; printf("get_from_two_str\n"); printf("find 345 789 from %s\n", src4); int ans = get_from_two_str(src4, "345", "7890", dst4); printf("Ans: %d, %s\n", ans, dst4); printf("find 432 789 from %s\n", src4); ans = get_from_two_str(src4, "543", "789", dst4); printf("Ans: %d, %s\n", ans, dst4); // get_restful_route test char *src5 = "/api/member/add"; char dst5[8][32]; printf("get_restful_route\n"); int count = get_restful_route(src5, dst5); int i; for (i = 0; i < count; i++) { printf("restful_count %d: %s\n", i, dst5[i]); } // dump json char *src6 = "xxxx{\"abc\": \"123\", \"cde\": 2}xxxx"; char dst6[64]; printf("dump json test\n"); get_json_val_by_key(src6, "abc", dst6); printf("Result for abc is - %s\n", dst6); // test request char dst7[2048]; printf("get_member_by_id test\n"); get_member_by_id("001", dst7); printf("json file: %s\n", dst7); return 0; } <file_sep>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <pthread.h> struct sockaddr_in c_addr; char fname[100]; int pid; //preprocessing void reaper(int); //clean up zombie children void reaper(int sig) { int status; while (wait3(&status, WNOHANG, (struct rusage *)0) >= 0) /* empty */; } // send file to client function int SendFileToClient(int fd) { //information from the client int connfd = fd; printf("Connection accepted and id: %d\n",connfd); printf("Connected to Client: %s:%d\n",inet_ntoa(c_addr.sin_addr),ntohs(c_addr.sin_port)); //file which requested by client read(connfd, fname,256); printf("Message form client: %s\n", fname); FILE *fp = fopen(fname,"rb"); if (fp==NULL) { printf("There is no file named: %s\n", fname); } else { //Read data from file and send it while(1) { unsigned char buff[1024]={0}; int nread = fread(buff,1,1024,fp); //If read was success, send data if(nread > 0) { write(connfd, buff, nread); } if (nread < 1024) { if (feof(fp)) { printf("End of file\n"); printf("File transfer completed for id: %d\n",connfd); } if (ferror(fp)) { printf("Error reading\n"); } break; } } } //close the thread printf("Closing Connection for id: %d\n",connfd); close(connfd); shutdown(connfd,SHUT_WR); sleep(2); return 0; } int main(int argc, char *argv[]) { if (argc == 2) { //get the number of pre-allocated children char proc[50]; strcpy(proc,argv[1]); int num = atoi(proc); int connfd = 0; struct sockaddr_in serv_addr; int listenfd = 0,ret; size_t clen=0; //server's information listenfd = socket(AF_INET, SOCK_STREAM, 0); if(listenfd<0) { printf("Error in socket creation\n"); exit(2); } (void)signal(SIGCHLD, reaper); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(2222); ret=bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); if(ret<0) { printf("Error in bind\n"); exit(2); } if(listen(listenfd, 10) == -1) { printf("Failed to listen\n"); return -1; } // preforking process clen = sizeof(c_addr); for (int i = 0; i < num; ++i) { pid = fork(); if (pid == -1) { printf("Error to fork"); } if (pid == 0) { printf("Preforked child %d\n", i + 1); // slave(client) sock connfd = accept(listenfd, (struct sockaddr *)&c_addr, &clen); printf("Preforked child %d connection accept.\n", i + 1); // for child break the for loop break; } } //child if (pid == 0) { (void)close(listenfd); exit(SendFileToClient(connfd)); } //parent while(1) { clen=sizeof(c_addr); printf("Waiting...\n"); connfd = accept(listenfd, (struct sockaddr*)&c_addr,&clen); if(connfd<0) { printf("Error in accept\n"); continue; } switch (fork()) { case 0:{ /* child */ (void)close(listenfd); exit(SendFileToClient(connfd)); } default:{ /* parent */ (void)close(connfd); break; } case -1:{ printf("Error to fork"); } } } } else { printf("Please enter one number\n"); } return 0; } <file_sep># Team5 Lab4-Q1 Readme ## Purpose and Introduction Write a complete connection-oriented client – server program using RPC that performs the file server functionality using different file sizes: 900 and 1800 bytes. The client should record and display the exact number of bytes received. ## Files This folder contains six files * client_get_file.c * get_file.x * remote_procedure.c * readme.md * 1800.txt * 900.txt ## Compile Make sure the system running the service `rpcbind` In command line, Type in `make`. Two executable files `server` and `client` will be compiled and generated Please move `server`, `1800.txt`and `900.txt` into one directory Please move `client` into another directory Use `make clean` to remove generated files ## Execute First, type `./server` to run the TCP server in terminal 1 Second, type `./client ` plus `file name` to run the client in terminal 2 ## Test case and expected result test case1: ``` $ ./server # server's terminal $ ./client 900.txt # client's terminal ``` test case2: ``` $./server # server's terminal $./client 1800.txt # client's terminal ``` test case3:(no this file exist in server side) ``` $./server # server's terminal $./client anything # client's terminal ``` check the file requested has been transferred to client's folder <file_sep>#include <arpa/inet.h> #include <stdio.h> #include <sys/socket.h> #include <unistd.h> #define UDP_DAYTIME_PORT 5678 // Default should be 13, but reserved by OS int main(int argc, char *argv[]) { // Create socket int sd = socket(AF_INET, SOCK_DGRAM, 0); // SOCK_DGRAM for UDP if (sd < 1) { printf("Couldn't create socket\n"); return 1; } printf("UDP socket created\n"); struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr("127.0.0.1"); // only test for localhost server.sin_port = htons(UDP_DAYTIME_PORT); // Send message to server if (sendto(sd, "", 0, 0, (struct sockaddr *)&server, sizeof(server)) < 0) { printf("Sento failed\n"); return 1; } printf("Sent request to server\n"); // Receive response from server char rsp[100]; if (recvfrom(sd, rsp, sizeof(rsp) - 1, 0, NULL, 0) < 0) { printf("Recvfrom failed\n"); return 1; } printf("Receive DAYTIME from server: \"%s\"\n", rsp); return 0; } <file_sep>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <pthread.h> int listenfd; char fname[256]; struct sockaddr_in clnt_addr; socklen_t clen; void *SendFileToClient(void *arg) { FILE *fp = fopen(fname,"rb"); if (fp == NULL) { printf("There is no file named: %s\n", fname); char zero_buff[1] = {0}; sendto(listenfd, zero_buff, 0, 0, (struct sockaddr *)&clnt_addr, clen); } else { // Read data from file and send it unsigned char buff[2048]={0}; int nread = fread(buff,1,2048,fp); sendto(listenfd, buff, nread, 0, (struct sockaddr *)&clnt_addr, clen); printf("File sent!\n"); } } int main() { struct sockaddr_in serv_addr; listenfd = 0; int ret; pthread_t tid; //server's information listenfd = socket(AF_INET, SOCK_DGRAM, 0); if(listenfd<0) { printf("Error in socket creation\n"); exit(2); } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(2222); ret=bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); if(ret<0) { printf("Error in bind\n"); exit(2); } while(1) { clen = sizeof(clnt_addr); printf("Waiting...\n"); recvfrom(listenfd, fname, 256, 0, (struct sockaddr *)&clnt_addr, &clen); int err = pthread_create(&tid, NULL, SendFileToClient, &ret); pthread_join(err, NULL); } return 0; } <file_sep># Project README ## Compile In Project root directory ``` make ``` ## Execute In Project root directory ``` ./server <port> ``` For example ``` ./server 5678 ``` Then use your browser `http://localhost:5678` ## API * Cookies key * `HcsUserId`: user id (string) * `HcsUserLevel`: user level (integer), 3 levels in total * `1`: admin * `2`: doctor * `3`: patient * `/login` User login API * POST Method * Body should be attached * `id`: user id * `passwd`: user <PASSWORD> * The API Set-Cookie: * `HcsUserId` as level id * `HcsUserLevel` as user level * `/logout`: Logout from current user * GET or POST Method * The API Set-Cookie: * `HcsUserId` as "", empty string * Note that, it doesn't change `HcsUserLevel` ## Test example #### Login You can test login by browsing `http://localhost:<Port>/index.html`, there is a form to type in username. For test purpose, three username can be test: * `testadmin`, with any password, it won't check for now * `testdoctor`, with any password, it won't check for now * `testpatient`, with any password, it won't check for now After submit, check `http://localhost:<port>/user.html`, you'll see the username and user level. #### Logout Send request `http://localhost:<port>/logout`, then check `http://localhost:<port>/user.html`, you'll see it shows `User: Not exist` <file_sep>CC = gcc CFLAGS = -Wall all: client server mkdir -p client_folder server_folder mv client client_folder mv server server_folder cp 900bytes.txt server_folder cp 1800bytes.txt server_folder client: client.c ${CC} $< ${CFLAGS} -o $@ server: server.c ${CC} $< ${CFLAGS} -lpthread -o $@ clean: @rm -rf client_folder server_folder <file_sep># Team5 Lab1-Q4 Readme ## Purpose and Introduction This program include the sources of TCP client and server. The client passes an integer to the server as a command line argument. The server receives the message, takes the square root of the integer, and sends the result back to the client. The client then receives the value and prints out both numbers. The sever can handle errors such as the integer is too big, the input is not a number, the input is decimal or the input is less than zero. ## Files This folder contains four files * Makefile * readme.md * client.c * server.c ## Compile In command line, key in `make`. Two executable file `server` and `client` will be compiled and generated. Use `make clean` to remove generated files ## Execute First, type `./server` to run the UDP server in terminal 1. Second, type `./client ` plus an integer to run the client in terminal 2. ## Test case and expected result test case1: (Result: correct output in client's terminal) ``` $ ./server # server's terminal $ ./client 100 # client's terminal Your input is: 100 Message form server: 10 ``` test case2: (Result: 'Message form server: please input a number bigger than zero' in client's terminal) ``` ./server # server's terminal ./client -12 # client's terminal Your input is: -12 Message form server: please input a number bigger than zero ``` test case3: (Result: 'Message form server: please input a number bigger than zero' in client's terminal) ``` ./server # server's terminal ./client 0 # client's terminal Your input is: 0 Message form server: please input a number bigger than zero ``` test case4: (Result: 'Message form server: please input a number' in client's terminal) ``` ./server # server's terminal ./client ab # client's terminal Your input is: ab Message form server: please input a number ``` test case5: (Result: 'Please enter one number' in client's terminal) ``` ./server # server's terminal ./client # client's terminal Please enter one number ``` test case6: (Result: correct output in client's terminal) ``` ./server # server's terminal ./client 1.23 # client's terminal Your input is: 1.23 Message form server: 1 ``` <file_sep>#include <stdio.h> #include <string.h> #include "strfunc.h" #include "jsmn.h" /************************************************************ * Function: compare_str * Compare two string with different start position by given length * EX - compare_str("abc", 1, "bcd", 0, 2) return 0, since "bc" equals to "bc" * Parameters: * str1, str2 - two strings * start1, start2 - start position of the string * len - the length to be compare from two start position * Returns: * 0 - two string are the same, with the given parameters * 1 - two string are not the same, with the given parameters ************************************************************/ int compare_str(char *str1, int start1, char *str2, int start2, int len) { // check corner case if (start1 + len > strlen(str1) || start2 + len > strlen(str2)) return 1; int cnt = 0; while (start1 < strlen(str1) && start2 < strlen(str2) && cnt < len) { if (str1[start1++] != str2[start2++]) { return 1; // not the same } cnt++; } return 0; // the same } /************************************************************ * Function: get_str_until_space * Get substr of src from given position until the first space and put in dst * EX - get_str_until_space("abc def", 0, dst) return 3, dst will be "abc" * Parameters: * src - original string * src_start - the start position (including) of src * dst - the buffer that the substring will be put into * Returns: * the position of next space or the length of src (it traverses to the end) ************************************************************/ int get_str_until_space(char *src, int src_start, char *dst) { // skip space at the beginning while (src[src_start] == ' ') { src_start++; } // start to get string int i; for (i = 0; src_start < strlen(src) && src[src_start] != ' '; i++) { dst[i] = src[src_start]; src_start++; } dst[i] = '\0'; return src_start; } /************************************************************ * Function: get_restful_route * Separate restful route into 2-d array * Ex: route: /api/member/add -> *dst[]: ["api", "member", "add"] and return 3 * Parameters: * route - restful route * dst - 2-d array to be put the result * Returns: * the number of dst array * -1 - error ************************************************************/ int get_restful_route(char *route, char dst[][32]) { if (strlen(route) == 0) { printf("[Error] get_restful_route, no input\n"); return -1; } else if (route[0] != '/') { printf("[Error] get_restful_route, syntax error\n"); return -1; } int i = 1; int count = 0; while (i < strlen(route)) { int j; for (j = 0; i + j < strlen(route) && route[i + j] != '/'; j++) { dst[count][j] = route[i + j]; } dst[count][j] = '\0'; i += j + 1; // skip slash count++; } return count; } /************************************************************ * Function: get_str_line * Get substr of src from given position until end of line and put in dst * EX - get_str_line(" \nabc\r\ndef", 0, dst) return 5, dst will be "abc" * Parameters: * src - original string * src_start - the start position (including) of src * dst - the buffer that the substring will be put into * Returns: * the position of next \n, \r or space or the length or src ************************************************************/ int get_str_line(char *src, int src_start, char *dst) { dst[0] = '\0'; // clean dst // remove \r, \n and space from the beginning int i = src_start; while (i < strlen(src)) { if (src[i] == '\r' || src[i] == '\n' || src[i] == ' ') i++; else break; } int cnt = 0; while (i < strlen(src) && src[i] != '\r' && src[i] != '\n') { dst[cnt++] = src[i++]; } return i; } /************************************************************ * Function: strcpy_with_pos_len * Copy string from src to dst by given start position and length * Parameters: * src - original string * src_start - the start position (including) of src * src_len - the length to be copied * dst - the buffer that the substring will be put into ************************************************************/ void strcpy_with_pos_len(char *src, int src_start, int src_len, char *dst) { int i; for (i = 0; i < strlen(src) && i < src_len; i++) { dst[i] = src[i + src_start]; } dst[i] = '\0'; } /************************************************************ * Function: get_start_from_str * Find the start position of str in src * Parameters: * src - original string * start - the start position (including) of src * str - the string to be found within src * Returns: * the start position of str in src ************************************************************/ int get_start_from_str(char *src, int start, char *str) { int f = start, s = start; // fast, slow pointer, find word between [s, f) // find str while (f++ < strlen(src)) { if (src[f] == str[0]) { s = f; int i; for (i = 0; i < strlen(str) && src[f++] == str[i]; i++); if (i == strlen(str)) { // match str return s; } } } return -1; } /************************************************************ * Function: get_from_two_str * Get the content from two str and put it into dst * Parameters: * src - original string * str1 - first string to be found within src * str2 - second string to be found within src, empty string as input means get the string to the end * dst - the buffer that the content between str1, str2 will be put into * Returns: * 0 - not found * 1 - found ************************************************************/ int get_from_two_str(char *src, char *str1, char *str2, char *dst) { int start1 = get_start_from_str(src, 0, str1); if (start1 == -1) return 0; // not found int content_start = start1 + strlen(str1); int start2 = strlen(src); // special case, get string to the end if (strlen(str2) != 0) { start2 = get_start_from_str(src, content_start, str2); if (start2 == -1) return 0; // not found } // assign string to dst strcpy_with_pos_len(src, content_start, start2 - content_start, dst); return 1; } static int jsoneq(const char *json, jsmntok_t *tok, const char *s) { if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start && strncmp(json + tok->start, s, tok->end - tok->start) == 0) { return 0; } return -1; } /************************************************************ * Function: get_json_val_by_key * Get val by key from a json in a header * Parameters: * header - client header string * key - json key * dst - json val to be put * Returns: * 0 - not found * 1 - found ************************************************************/ int get_json_val_by_key(char *header, char *key, char *dst) { char json_str_buf[1024], json_str[1024]; int errcode = get_from_two_str(header, "{", "}", json_str_buf); if (errcode == 0) return 0; // not found json format string sprintf(json_str, "{%s}", json_str_buf); int i; int r; jsmn_parser p; jsmntok_t t[128]; // We expect no more than 128 tokens jsmn_init(&p); r = jsmn_parse(&p, json_str, strlen(json_str), t, sizeof(t)/sizeof(t[0])); if (r < 0) { printf("Failed to parse JSON: %d\n", r); return 0; } // Assume the top-level element is an object if (r < 1 || t[0].type != JSMN_OBJECT) { printf("Object expected\n"); return 0; } // find key for (i = 1; i < r; i++) { if (jsoneq(json_str, &t[i], key) == 0) { /* We may use strndup() to fetch string value */ sprintf(dst, "%.*s", t[i+1].end-t[i+1].start, json_str + t[i+1].start); return 1; } } return 0; // successful } <file_sep>CC = gcc CFLAGS = -Wall TARGET_1 = udp_client RESOURCE_1 = udp_client.c TARGET_2 = udp_server RESOURCE_2 = udp_server.c all: ${TARGET_1} ${TARGET_2} ${TARGET_1}: ${RESOURCE_1} ${CC} $< ${CFLAGS} -o $@ ${TARGET_2}: ${RESOURCE_2} ${CC} $< ${CFLAGS} -o $@ clean: @rm -rf ${TARGET_1} ${TARGET_2} <file_sep>#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> #include <pthread.h> int main(int argc, char *argv[]) { if (argc == 2) { int sock = socket(AF_INET, SOCK_DGRAM, 0); //sent the request to the assigned host struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(serv_addr)); //initial the address serv_addr.sin_family = AF_INET; //use IPv4 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //use local host serv_addr.sin_port = htons(2222); //port is 2222 //send the name of the file to the server char fname[50]; strcpy(fname,argv[1]); int bytesReceived = 0; char recvBuff[2048] = {0}; printf("requested file name: %s\n", fname); sendto(sock, fname, sizeof(fname), 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); bytesReceived = recvfrom(sock, recvBuff, sizeof(recvBuff) - 1, 0, NULL, 0); printf("bytesReceived = %d\n", bytesReceived); // no file matched if (bytesReceived == 0) { printf("There is no file in server named: %s\n", fname); } else if (bytesReceived < 0) { printf("\n Read Error \n"); } else { //create a file for receiving FILE *fp; printf("Receiving file...\n"); fp = fopen(fname, "ab"); if(NULL == fp) { printf("Error opening file"); return 1; } printf("writing\n"); fflush(stdout); fwrite(recvBuff, 1, bytesReceived, fp); fclose(fp); //check the file printf("File received completely!"); } } else { printf("Please enter the file name\n"); } return 0; } <file_sep>CC = gcc CFLAGS = -Wall TARGET_1 = client TARGET_2 = server all: client server client: client.c ${CC} $< ${CFLAGS} -o $@ server: server.c ${CC} $< ${CFLAGS} -o $@ clean: @rm -rf client server<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "mysql/mysql.h" MYSQL *g_conn; /* mysql connection */ MYSQL_RES *g_res; /* mysql rocord set*/ MYSQL_ROW g_row; /* mysql rocord row*/ #define MAX_BUF_SIZE 1024 /* max buffer */ /*=================================================================*/ /**/ const char *g_host_name = "localhost"; /**/ const char *g_user_name = "root"; /**/ const char *g_password = "<PASSWORD>"; /**/ const char *g_db_name = "project"; /**/ const unsigned int g_db_port = 3306; /*=================================================================*/ char sql[MAX_BUF_SIZE]; char Time[MAX_BUF_SIZE]; int iNum_rows = 0; /* row value aftern execute mysql */ int i = 1; /* system switch */ int id = 0; /* role id of user who is using*/ /* structure for login */ struct Login { char name[24]; char password[20]; } login; /* structure for operation */ struct Operation { char tables[24]; char name[24]; char passwd[20]; int role; char prescription[20]; } ope; /* handle error message */ void print_mysql_error( const char *msg ) { if ( msg ) printf( "%s: %s\n", msg, mysql_error( g_conn ) ); else puts( mysql_error( g_conn ) ); } /* execute mysql,success return 0,fail return -1 */ int executesql( const char * sql ) { if ( mysql_real_query( g_conn, sql, strlen( sql ) ) ) return(-1); return(0); } /* initial mysql */ int init_mysql() { /* init the database connection */ g_conn = mysql_init( NULL ); /* connection the database */ if ( !mysql_real_connect( g_conn, g_host_name, g_user_name, g_password, g_db_name, g_db_port, NULL, 0 ) ) return(-1); /* connection failed */ /* check if is ok to use */ if ( executesql( "set names utf8" ) ) return(-1); return(0); /* success */ } /*select database, if no such a database,create one */ void create_database() { sprintf( sql, "use project" ); if ( executesql( sql ) == -1 ) { puts( "create database" ); executesql( "create database project;" ); print_mysql_error( NULL ); puts( "choice database" ); executesql( "use project;" ); print_mysql_error( NULL ); puts( "!!!Initialize the success!!!" ); }else { executesql( "use project;" ); print_mysql_error( NULL ); } } /* check the table */ void create_table() { /* check/create user table */ sprintf( sql, "show tables;" ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); if ( iNum_rows == 0 ) { puts( "create users table" ); executesql( "create table users(id_ smallint unsigned primary key auto_increment,role_id_ smallint unsigned,name_ varchar(24) not null unique,password_ char(20) not null,prescription_ varchar(200));" ); } mysql_free_result( g_res ); /* free record */ } /* initial admin */ void init_Administrtor() { /* check if there is an admin in user table */ sprintf( sql, "select * from users where id_='1' and name_='root';" ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); if ( iNum_rows == 0 ) { puts( "Init Administrtor User" ); /* insert admin user */ sprintf( sql, "insert into users values(1,1,'admin','123','n/a');" ); executesql( sql ); } mysql_free_result( g_res ); } /* login */ void user_login() { puts( "Init success! Please press any key to continue" ); while ( 1 ) { while ( (getchar() ) != '\n' ) ; system( "clear" ); puts( "!!!Login System!!!" ); /* user name and passwd */ printf( "Name:" ); scanf( "%s", login.name ); printf( "Passwd:" ); scanf( "%s", login.password ); /* check user table if there is the user,login success */ sprintf( sql, "select * from users where name_='%s' and password_='%s';", login.name, login.password ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); if ( iNum_rows != 0 ) { puts( "!!! Login Success !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); break; }else { puts( "!!!Login Failed!!! Check name or password!" ); while ( (getchar() ) != '\n' ) ; } } mysql_free_result( g_res ); } /* get role_id of the user who is using now*/ void role_id() { sprintf( sql, "select role_id_ from users where name_='%s';", login.name ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int iNum_fields = mysql_num_fields( g_res ); while ( (g_row = mysql_fetch_row( g_res ) ) ) { /* 1:admin, 2:doctor, 3:patient */ if ( strcmp( g_row[0], "1" ) == 0 ) id = 1; if ( strcmp( g_row[0], "2" ) == 0 ) id = 2; if ( strcmp( g_row[0], "3" ) == 0 ) id = 3; mysql_free_result( g_res ); } } /* judge target user role_id */ int judge( char u_id[20] ) { int target_id; /* select user from user id */ sprintf( sql, "select role_id_ from users where id_='%s';", u_id ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); if ( iNum_rows == 0 ) { mysql_free_result( g_res ); return(0); }else { int iNum_fields = mysql_num_fields( g_res ); while ( (g_row = mysql_fetch_row( g_res ) ) ) { /* get target user role id */ if ( strcmp( g_row[0], "1" ) == 0 ) target_id = 1; if ( strcmp( g_row[0], "2" ) == 0 ) target_id = 2; if ( strcmp( g_row[0], "3" ) == 0 ) target_id = 3; /* determine the user role id with target user role id */ if ( id < target_id ) { mysql_free_result( g_res ); return(1);//get permission }else { mysql_free_result( g_res ); return(0);// rejected } } } } /* query */ void query_msg() { char u_id[20]; system( "clear" ); puts( "!!! enter id !!! " ); printf( "id:" ); scanf( "%s", u_id ); /* judge the permision */ if ( judge( u_id ) == 0 ) { puts( "!!!Insufficient permissions!!! " ); while ( (getchar() ) != '\n' ) ; getchar(); /* rejected */ return; } sprintf( sql, "select * from users where id_='%s';", u_id ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); system( "clear" ); int iNum_fields = mysql_num_fields( g_res ); puts( "id_|role_id_ | name_ |password_| prescription_ " ); while ( (g_row = mysql_fetch_row( g_res ) ) ) printf( "%s\t%s\t%s\t%s\t\t%s\n", g_row[0], g_row[1], g_row[2], g_row[3], g_row[4] ); mysql_free_result( g_res ); while ( (getchar() ) != '\n' ) ; getchar(); } /* add */ void add_msg() { char u_id[20]; int o; //for admin user if ( id == 1 ) { system( "clear" ); puts( "!!! Add_user !!! " ); /* user id each time puls 1 */ sprintf( sql, "select id_ from users;" ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int i = iNum_rows + 1; /* new id */ /* user name and passwd */ printf( " Name:" ); scanf( "%s", ope.name ); printf( "Password:" ); scanf( "%s", ope.passwd ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int iNum_fields = mysql_num_fields( g_res ); while ( (g_row = mysql_fetch_row( g_res ) ) ) { sprintf( u_id, "%s", g_row[0] ); } /* prescription */ printf( " Prescription:" ); scanf( "%s", ope.prescription ); /* role */ printf( " ROLE:\n1: HEALTHY CARE PROVIDER\n2: PATIENT\n" ); scanf( "%d", &o ); switch ( o ) { case 1: ope.role = 2; break; case 2: ope.role = 3; break; default: puts( "!!! enter right choice !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); } /* insert a new user */ sprintf( sql, "insert into users values(%d,%d,'%s','%s','%s');", i, ope.role, ope.name, ope.passwd, ope.prescription ); executesql( sql ); puts( "!!! success !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); } //for doctor else { system( "clear" ); puts( "!!! Add_user !!! " ); sprintf( sql, "select id_ from users;" ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int i = iNum_rows + 1; printf( " Name:" ); scanf( "%s", ope.name ); printf( "Password:" ); scanf( "%s", ope.passwd ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int iNum_fields = mysql_num_fields( g_res ); while ( (g_row = mysql_fetch_row( g_res ) ) ) { sprintf( u_id, "%s", g_row[0] ); } printf( " Prescription:" ); scanf( "%s", ope.prescription ); /* cannot choose a role, default:add a patient */ ope.role = 3; sprintf( sql, "insert into users values(%d,%d,'%s','%s','%s');", i, ope.role, ope.name, ope.passwd, ope.prescription ); executesql( sql ); puts( "!!! success !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); } } /* alter */ void alter_msg() { int o, op; char p; char ID[20]; char u_id[20]; system( "clear" ); puts( "!!! enter id !!! " ); printf( "id:" ); scanf( "%s", u_id ); /* judge permission */ if ( judge( u_id ) == 0 ) { puts( "!!!Insufficient permissions!!! " ); while ( (getchar() ) != '\n' ) ; getchar(); /* rejected */ return; } sprintf( sql, "select id_ from users where id_='%s';", u_id ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int iNum_fields = mysql_num_fields( g_res ); while ( (g_row = mysql_fetch_row( g_res ) ) ) { sprintf( ID, "%s", g_row[0] ); } //for admin user if ( id == 1 ) { system( "clear" ); puts( "!!! alt_msg !!! " ); puts( "!!! 1:change name !!! " ); puts( "!!! 2:change passwd !!! " ); puts( "!!! 3:change role !!! " ); printf( "!!! choice: !" ); scanf( "%d", &o ); switch ( o ) { case 1: system( "clear" ); puts( "!!! alt_msg !!! " ); printf( "!!! enter name: " ); scanf( "%s", ope.name ); /* renew user name */ sprintf( sql, "update users set name_='%s' where id_=%s;", ope.name, ID ); executesql( sql ); break; case 2: system( "clear" ); puts( "!!! del_alt_msg !!! " ); printf( "!!! enter password: " ); scanf( "%s", ope.passwd ); /* renew paddwd */ sprintf( sql, "update users set password_='%s' where id_=%s;", ope.passwd, ID ); executesql( sql ); break; case 3: system( "clear" ); puts( "!!! alt_msg !!! " ); puts( "!!! 1.HEALTH CARE PROVIDER !!! " ); puts( "!!! 2.PATIENT !!! " ); printf( "!!! choice: !" ); scanf( "%d", &op ); switch ( op ) { case 1: /* set role to be a doctor */ sprintf( sql, "update users set role_id_=2 where id_=%s;", ID ); executesql( sql ); break; case 2: /* set role to be a patient */ sprintf( sql, "update users set role_id_=3 where id_=%s;", ID ); executesql( sql ); break; default: puts( "!!! enter right choice !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); } break; default: puts( "!!! enter right choice !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); } } //for doctor user else { system( "clear" ); puts( "!!! change prescription !!! " ); printf( "!!! enter prescription: " ); scanf( "%s", ope.prescription ); /* renew presecription */ sprintf( sql, "update users set prescription_='%s' where id_=%s;", ope.prescription, ID ); executesql( sql ); } puts( "!!! success !!! " ); mysql_free_result( g_res ); while ( (getchar() ) != '\n' ) ; getchar(); } /*delete */ void delete_msg() { char p; char u_id[20], ID[20]; system( "clear" ); puts( "!!! enter id !!! " ); printf( "id:" ); scanf( "%s", u_id ); /* judge permission */ if ( judge( u_id ) == 0 ) { puts( "!!!Insufficient permissions!!! " ); while ( (getchar() ) != '\n' ) ; getchar(); /* rejected */ return; } sprintf( sql, "select id_ from users where id_='%s';", u_id ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int iNum_fields = mysql_num_fields( g_res ); while ( (g_row = mysql_fetch_row( g_res ) ) ) { sprintf( ID, "%s", g_row[0] ); } system( "clear" ); puts( "!!! delete_msg !!! " ); printf( "!!! sure delete? (Y/N):" ); scanf( "%s", &p ); switch ( p ) { case 'Y': case 'y': /* delete the user by id */ sprintf( sql, "delete from users where id_=%s;", ID ); executesql( sql ); break; case 'N': case 'n': return; } } /* show self information */ void show_self() { /* get self by login name and passwd */ sprintf( sql, "select * from users where name_='%s' and password_='%s';", login.name, login.password ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int iNum_fields = mysql_num_fields( g_res ); system( "clear" ); puts( "!!! personal information !!! \n" ); puts( "id_|role_id_ | name_ |password_| prescription_ " ); while ( (g_row = mysql_fetch_row( g_res ) ) ) printf( "%s\t%s\t%s\t%s\t\t%s\n", g_row[0], g_row[1], g_row[2], g_row[3], g_row[4] ); mysql_free_result( g_res ); while ( (getchar() ) != '\n' ) ; getchar(); } /* alter self information */ void alter_self() { int o; char u_id[20]; sprintf( sql, "select * from users where name_='%s' and password_='%s';", login.name, login.password ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int iNum_fields = mysql_num_fields( g_res ); while ( (g_row = mysql_fetch_row( g_res ) ) ) { sprintf( u_id, "%s", g_row[0] ); } system( "clear" ); puts( "!!! alter_msg !!! " ); puts( "!!! 1:change name !!! " ); puts( "!!! 2:change passwd !!! " ); printf( "!!! choice: !" ); scanf( "%d", &o ); switch ( o ) { case 1: system( "clear" ); puts( "!!! alter_msg !!! " ); printf( "!!! enter name: " ); scanf( "%s", ope.name ); /* renew user name */ sprintf( sql, "update users set name_='%s' where id_=%s;", ope.name, u_id ); executesql( sql ); break; case 2: system( "clear" ); puts( "!!! alter_msg !!! " ); printf( "!!! enter password: " ); scanf( "%s", ope.passwd ); /* renew passwd */ sprintf( sql, "update users set password_='%s' where id_=%s;", ope.passwd, u_id ); executesql( sql ); break; default: puts( "!!! enter right choice !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); } puts( "!!! success !!! " ); mysql_free_result( g_res ); return; } /* display */ void display() { //for admin to get all users'information sprintf( sql, "select * from users;" ); executesql( sql ); g_res = mysql_store_result( g_conn ); iNum_rows = mysql_num_rows( g_res ); int iNum_fields = mysql_num_fields( g_res ); system( "clear" ); puts( "!!! users table !!! \n" ); puts( "id_|role_id_ | name_ |password_| prescription_ " ); while ( (g_row = mysql_fetch_row( g_res ) ) ) printf( "%s\t%s\t%s\t%s\t\t%s\n", g_row[0], g_row[1], g_row[2], g_row[3], g_row[4] ); mysql_free_result( g_res ); while ( (getchar() ) != '\n' ) ; getchar(); } /* menu */ void menu() { role_id(); printf( "id is : %d", id ); switch ( id ) { /* admin */ case 1: { while ( i ) { int choice; system( "clear" ); puts( "!!! choice: !!! " ); puts( "!!! 1:query user !!! " ); puts( "!!! 2:add user !!! " ); puts( "!!! 3:alter user !!! " ); puts( "!!! 4:delete user !!! " ); puts( "!!! 5:display all !!! " ); puts( "!!! 6:show self information !!! " ); puts( "!!! 7:alter self information !!! " ); puts( "!!! 8:exit login !!! " ); puts( "!!! 0:exit system !!! " ); scanf( "%d", &choice ); switch ( choice ) { case 1: query_msg(); break; case 2: add_msg(); break; case 3: alter_msg(); break; case 4: delete_msg(); break; case 5: display(); break; case 6: show_self(); break; case 7: alter_self(); return; case 8: return; case 0: puts( "!!! thank you for using !!! " ); i = 0; break; default: puts( "!!! enter right choice !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); break; } } } /* doctor */ case 2: { while ( i ) { int choice; system( "clear" ); puts( "!!! choice: !!! " ); puts( "!!! 1:query patient !!! " ); puts( "!!! 2:add patient !!! " ); puts( "!!! 3:alter patient's prescription !!! " ); puts( "!!! 4:delete paitent !!! " ); puts( "!!! 5:show self information !!! " ); puts( "!!! 6:alter self information !!! " ); puts( "!!! 7:exit login !!! " ); puts( "!!! 0:exit system !!! " ); scanf( "%d", &choice ); switch ( choice ) { case 1: query_msg(); break; case 2: add_msg(); break; case 3: alter_msg(); break; case 4: delete_msg(); break; case 5: show_self(); break; case 6: alter_self(); return; case 7: return; case 0: puts( "!!! thank you for using !!! " ); i = 0; break; default: puts( "!!! enter right choice !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); break; } } } /* patient */ case 3: { while ( i ) { int choice; system( "clear" ); puts( "!!! choice: !!! " ); puts( "!!! 1:show self information !!! " ); puts( "!!! 2:alter self information !!! " ); puts( "!!! 3:exit login !!! " ); puts( "!!! 0:exit system !!! " ); scanf( "%d", &choice ); switch ( choice ) { case 1: show_self(); break; case 2: alter_self(); return; case 3: return; case 0: puts( "!!! thank you for using !!! " ); i = 0; break; default: puts( "!!! enter right choice !!! " ); while ( (getchar() ) != '\n' ) ; getchar(); break; } } } default: puts( "!!! role id error !!! " ); } } /* main*/ int main( void ) { while ( i ) { puts( "!!!The system is initializing!!!" ); /* initial mysql */ if ( init_mysql() ) print_mysql_error( NULL ); create_database(); create_table(); /* intial admin */ init_Administrtor(); /* login */ user_login(); /* memu */ menu(); } /* close connection */ mysql_close( g_conn ); return(EXIT_SUCCESS); } <file_sep>#include <arpa/inet.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <time.h> #include <unistd.h> #define UDP_DAYTIME_PORT 5678 // Default should be 13, but reserved by OS int main(int argc, char *argv[]) { // Get daytime time_t daytime = time(NULL); char daytime_str[100]; strcpy(daytime_str, ctime(&daytime)); daytime_str[strlen(daytime_str) - 1] = '\0'; // remove \n // Create socket int sd = socket(AF_INET, SOCK_DGRAM, 0); // SOCK_DGRAM for UDP if (sd < 1) { printf("Couldn't create socket\n"); return 1; } printf("UDP socket created\n"); struct sockaddr_in server, client; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; // enable any ip_addr server.sin_port = htons(UDP_DAYTIME_PORT); // Bind if (bind(sd, (struct sockaddr *)&server, sizeof(server)) < 0) { printf("Bind failed\n"); return 1; } printf("Bind successful, listen to port %d\n", UDP_DAYTIME_PORT); // Receive message char msg[100]; socklen_t client_len = sizeof(client); if (recvfrom(sd, msg, sizeof(msg), 0, (struct sockaddr *)&client, &client_len) < 0) { printf("Recvfrom failed\n"); return 1; } printf("Recvfrom successful, get client info\n"); // Send message to client if (sendto(sd, daytime_str, sizeof(daytime_str), 0, (struct sockaddr *)&client, client_len) < 0) { printf("Sento failed\n"); return 1; } printf("Sent message \"%s\" to client\n", daytime_str); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/in.h> #include <math.h> #include <ctype.h> int main(){ //create a socket int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //assign the address and port struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(serv_addr)); //initial server address serv_addr.sin_family = AF_INET; //use IPV4 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //use local host serv_addr.sin_port = htons(2222); //port is 2222 bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); //listen the port listen(serv_sock, 20); char fname[50]; //Iteratively handle each requet while(1) { printf("Waiting...\n"); //accept the request from client struct sockaddr_in clnt_addr; socklen_t clnt_addr_size = sizeof(clnt_addr); int connfd = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size); read(connfd, fname,256); printf("Message form client: %s\n", fname); FILE *fp = fopen(fname,"rb"); if (fp==NULL) { printf("There is no file named: %s\n", fname); } else { //Read data from file and send it while(1) { unsigned char buff[1024]={0}; int nread = fread(buff,1,1024,fp); //If read was success, send data if(nread > 0) { write(connfd, buff, nread); } if (nread < 1024) { if (feof(fp)) { printf("End of file\n"); printf("File transfer completed for id: %d\n",connfd); } if (ferror(fp)) { printf("Error reading\n"); } break; } } } //close the thread printf("Closing Connection for id: %d\n",connfd); close(connfd); sleep(2); } } <file_sep>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <pthread.h> struct sockaddr_in c_addr; char fname[100]; // send file to client function int SendFileToClient(int fd) { //information from the client int connfd = fd; printf("Connection accepted and id: %d\n",connfd); printf("Connected to Client: %s:%d\n",inet_ntoa(c_addr.sin_addr),ntohs(c_addr.sin_port)); //file which requested by client read(connfd, fname,256); printf("Message form client: %s\n", fname); FILE *fp = fopen(fname,"rb"); if (fp==NULL) { printf("There is no file named: %s\n", fname); } else { //Read data from file and send it while(1) { unsigned char buff[1024]={0}; int nread = fread(buff,1,1024,fp); //If read was success, send data if(nread > 0) { write(connfd, buff, nread); } if (nread < 1024) { if (feof(fp)) { printf("End of file\n"); printf("File transfer completed for id: %d\n",connfd); } if (ferror(fp)) { printf("Error reading\n"); } break; } } } //close the thread printf("Closing Connection for id: %d\n",connfd); close(connfd); shutdown(connfd,SHUT_WR); sleep(2); return 0; } int main() { int connfd = 0; struct sockaddr_in serv_addr; int listenfd = 0,ret; size_t clen=0; //server's information listenfd = socket(AF_INET, SOCK_STREAM, 0); if(listenfd<0) { printf("Error in socket creation\n"); exit(2); } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(2222); ret=bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); if(ret<0) { printf("Error in bind\n"); exit(2); } if(listen(listenfd, 10) == -1) { printf("Failed to listen\n"); return -1; } //listen to the port, create one process per request while(1) { clen=sizeof(c_addr); printf("Waiting...\n"); connfd = accept(listenfd, (struct sockaddr*)&c_addr,&clen); if(connfd<0) { printf("Error in accept\n"); continue; } switch (fork()) { case 0:{ /* child */ (void)close(listenfd); exit(SendFileToClient(connfd)); } default:{ /* parent */ (void)close(connfd); break; } case -1:{ printf("Error to fork"); } } } return 0; } <file_sep>#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <assert.h> static off_t file_size(const char* fname); char* content = NULL; char** get_file_3_svc(const char* fname){ if(content != NULL){ free(content); content = NULL; } // open file int fd = open(fname,O_RDWR); if (fd < 0) { printf("There is no file named: %s\n", fname); return &content; } printf("Reading the file: %s\n", fname); off_t fsz = file_size(fname); content = (char*)malloc(fsz); memset(content, 0, sizeof(fsz)); int nread = read(fd,content,fsz); if(nread < 0){ printf("read failed"); free(content); exit(-1); } printf("file tranfered\n"); content[nread] = '\0'; // return a pointer to the space return &content; } static off_t file_size(const char* fname){ struct stat st; if(stat(fname, &st) == 0) return st.st_size; return -1; } <file_sep># Team5 Lab1-Q2 Readme ## Purpose and Introduction Write a UDP client program for DAYTIME service. In this question, we just send the UDP request from client to the server we run by ourselves. We don't exactly follow the Daytime Protocol, what we do is simply send the message and receive the daytime message that we get from our OS. ## Files This folder contains four files * Makefile * readme.md * udp_client.c * This file is the main purpose of this lab * udp_server.c * For test, this file enable client to request DAYTIME. ## Compile In command line, key in `make`. Two executable file `udp_server` and `udp_client` will be compiled and generated. Use `make clean` to remove generated files ## Execute First, type `./udp_server` to run the UDP server in terminal 1. Second, type `./udp_client` to run the client in terminal 2. Here the client send the UDP packet to the server, and the server responds DAYTIME to the client. ## Test case Run `udp_server` and `udp_client` in different terminal windows. ``` $ ./udp_server # terminal 1 UDP socket created Bind successful, listen to port 5678 ``` ``` $ ./udp_client # terminal 2 UDP socket created Sent request to server Receive DAYTIME from server: "Mon Mar 6 01:23:45 2018" ``` <file_sep>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <pthread.h> int main() { struct sockaddr_in serv_addr; int listenfd = 0,ret; //server's information listenfd = socket(AF_INET, SOCK_DGRAM, 0); if(listenfd<0) { printf("Error in socket creation\n"); exit(2); } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(2222); ret=bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); if(ret<0) { printf("Error in bind\n"); exit(2); } while(1) { struct sockaddr_in clnt_addr; socklen_t clen=sizeof(clnt_addr); char fname[256]; printf("Waiting...\n"); recvfrom(listenfd, fname, 256, 0, (struct sockaddr *)&clnt_addr, &clen); int pid = fork(); if (pid == 0) { // child printf("Child %d is forked\n", getpid()); FILE *fp = fopen(fname,"rb"); if (fp==NULL) { printf("There is no file named: %s\n", fname); char zero_buff[1] = {0}; sendto(listenfd, zero_buff, 1, 0, (struct sockaddr *)&clnt_addr, clen); } else { //Read data from file and send it unsigned char buff[2048]={0}; int nread = fread(buff,1,2048,fp); sendto(listenfd, buff, nread, 0, (struct sockaddr *)&clnt_addr, clen printf("File sent!\n"); } } } return 0; } <file_sep> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <pthread.h> int listenfd; char fname[256]; struct sockaddr_in clnt_addr; socklen_t clen; void *SendFileToClient(void *arg) { FILE *fp = fopen(fname,"rb"); if (fp == NULL) { printf("There is no file named: %s\n", fname); char zero_buff[1] = {0}; sendto(listenfd, zero_buff, 0, 0, (struct sockaddr *)&clnt_addr, clen); } else { // Read data from file and send it unsigned char buff[2048]={0}; int nread = fread(buff,1,2048,fp); sendto(listenfd, buff, nread, 0, (struct sockaddr *)&clnt_addr, clen); printf("File sent!\n"); } } int main(int argc, char *argv[]) { if (argc == 2) { char proc[50]; strcpy(proc,argv[1]); int num = atoi(proc); struct sockaddr_in serv_addr; listenfd = 0; int ret; pthread_t tid; //server's information listenfd = socket(AF_INET, SOCK_DGRAM, 0); if(listenfd<0) { printf("Error in socket creation\n"); exit(2); } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(2222); ret=bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); if(ret<0) { printf("Error in bind\n"); exit(2); } // prethreading process for (int i = 0; i < num; ++i) { pthread_t child; int *new_sock = malloc(1); *new_sock = listenfd; if (pthread_create(&child, NULL, SendFileToClient, (void *)new_sock) < 0) printf("Could not creat thread: %s\n"); printf("Prethreaded child %d created.\n", i + 1); // detach the child, parent don't need to wait the child finishing. if (pthread_detach(child) != 0) printf("Could not detach thread: %s\n"); } while(1) { clen = sizeof(clnt_addr); printf("Waiting...\n"); recvfrom(listenfd, fname, 256, 0, (struct sockaddr *)&clnt_addr, &clen); int err = pthread_create(&tid, NULL, SendFileToClient, &ret); pthread_join(err, NULL); } return 0; } else { printf("Please enter one number\n"); } } <file_sep>CC = gcc CFLAGS = -Wall TARGET = tcp_time_client RESOURCE = tcp_time_client.c all: ${TARGET} ${TARGET}: ${RESOURCE} ${CC} $< ${CFLAGS} -o $@ clean: @rm -rf ${TARGET} <file_sep>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <pthread.h> struct sockaddr_in c_addr; char fname[100]; // send file to client function void *SendFileToClient(void *arg) { //information from the client int connfd = *(int*)arg; printf("Connection accepted and id: %d\n",connfd); printf("Connected to client: %s:%d\n",inet_ntoa(c_addr.sin_addr),ntohs(c_addr.sin_port)); //file which requested by client read(connfd, fname,256); printf("Message form client: %s\n", fname); FILE *fp = fopen(fname,"rb"); if (fp==NULL) { printf("There is no file named: %s\n", fname); } else { //Read data from file and send it while(1) { unsigned char buff[1024]={0}; int nread = fread(buff,1,1024,fp); //If read was success, send data if(nread > 0) { write(connfd, buff, nread); } if (nread < 1024) { if (feof(fp)) { printf("End of file\n"); printf("File transfer completed for id: %d\n",connfd); } if (ferror(fp)) { printf("Error reading\n"); } break; } } } //close the thread printf("Closing Connection for id: %d\n",connfd); close(connfd); shutdown(connfd,SHUT_WR); sleep(2); } void *acceptHandleClient(void *sock) { struct sockaddr_in fsin; // the address of a client unsigned int alen; // length of client's address int listenfd = *(int *)sock; int connfd = accept(listenfd, (struct sockaddr *)&fsin, &alen); printf("Prethreaded child connection accepted.\n"); int *new_sock = malloc(1); *new_sock = connfd; SendFileToClient(new_sock); return NULL; } int main(int argc, char *argv[]) { if (argc == 2) { //get the number of pre-allocated children char proc[50]; strcpy(proc,argv[1]); int num = atoi(proc); int connfd = 0,err; pthread_t tid; struct sockaddr_in serv_addr; int listenfd = 0,ret; size_t clen=0; //server's information listenfd = socket(AF_INET, SOCK_STREAM, 0); if(listenfd<0) { printf("Error in socket creation\n"); exit(2); } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(2222); ret=bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); if(ret<0) { printf("Error in bind\n"); exit(2); } if(listen(listenfd, 10) == -1) { printf("Failed to listen\n"); return -1; } // prethreading process for (int i = 0; i < num; ++i) { pthread_t child; int *new_sock = &listenfd; if (pthread_create(&child, NULL, acceptHandleClient, (void *)new_sock) < 0) printf("Could not creat thread"); else printf("Prethreaded child %d\n", i + 1); // detach the child, parent don't need to wait the child finishing. if (pthread_detach(child) != 0) printf("Could not detach thread: %s\n"); } //listen to the port, create one thread per request while(1) { clen=sizeof(c_addr); printf("Waiting...\n"); connfd = accept(listenfd, (struct sockaddr*)&c_addr,&clen); if(connfd<0) { printf("Error in accept\n"); continue; } err = pthread_create(&tid, NULL, SendFileToClient, &connfd); if (err != 0) { printf("\ncan't create thread :[%s]", strerror(err)); } pthread_join(err,NULL); } close(connfd); } else { printf("Please enter one number\n"); } return 0; } <file_sep>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <pthread.h> #include <signal.h> int main(int argc, char *argv[]) { int num = 0; if (argc == 2) { //get the number of pre-allocated children char proc[50]; strcpy(proc,argv[1]); num = atoi(proc); } else { printf("Please enter one number\n"); return -1; } struct sockaddr_in serv_addr; int listenfd = 0,ret; //server's information listenfd = socket(AF_INET, SOCK_DGRAM, 0); if(listenfd<0) { printf("Error in socket creation\n"); exit(2); } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(2222); ret=bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); if(ret<0) { printf("Error in bind\n"); exit(2); } struct sockaddr_in clnt_addr; socklen_t clen=sizeof(clnt_addr); char fname[256]; printf("Waiting...\n"); int pid; for (int i = 0; i < num; i++) { pid = fork(); if (pid == 0) { // child while (1) { printf("child %d is running\n", getpid()); recvfrom(listenfd, fname, 256, 0, (struct sockaddr *)&clnt_addr, &clen); FILE *fp = fopen(fname,"rb"); if (fp==NULL) { printf("There is no file named: %s\n", fname); char zero_buff[1] = {0}; sendto(listenfd, zero_buff, 0, 0, (struct sockaddr *)&clnt_addr, clen); } else { //Read data from file and send it unsigned char buff[2048]={0}; int nread = fread(buff,1,2048,fp); sendto(listenfd, buff, nread, 0, (struct sockaddr *)&clnt_addr, clen); printf("File sent!\n"); } } } } // for killing zombies while (1) { int status; pid_t wait_pid = waitpid(-1, &status, 0); if (wait_pid <= 0) { break; } printf("child_pid: %d dead\n", wait_pid); } return 0; } <file_sep># Team5 Lab3 Readme ## Purpose and Introduction Write basic web Client and Server using BSD sockets. The server can be requested by a browser, so as the client programmed by us. ## Files This folder contains * server.c * client.c * Makefile * readme.md * 1800bytes.txt * 900bytes.txt ## Compile Type `make`, it generates two folder `server_folder` and `client_folder`. Use `make clean` to remove generated files ## Execute First, in `server_folder` type `./server` to run the HTTP server in terminal 1. Second, in `client_folder` type `./client`, you are asked to give a file_name, input either `900bytes.txt` or `1800bytes.txt`. If you give other inputs, server will respond error status. Third, use a browser by typing URL `localhost:5678/900bytes.txt` or `localhost:5678/1800bytes.txt`, you are able to download the two files. If you give other inpus, the server will show the error message. ## Test case and expected result #### Case 1 ``` # Terminal 1 $ make $ cd server_folder $ ./server # Terminal 2 $ cd client_folder $ ./client Please input file name to request: 900bytes.txt ``` #### Case 2 ``` $ make $ cd server_folder $ ./server ``` Use browser, type `localhost:5678/900bytes.txt` <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> int main(int argc, char *argv[]){ //the command line is appropriate if (argc == 2) { char *buffer = argv[1]; int len = strlen(buffer); //check if the input is too big if(len > 7) { printf("The number is too large\n"); } else { //create a socket int sock = socket(AF_INET, SOCK_STREAM, 0); //sent the request to the assigned host struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(serv_addr)); //initial the address serv_addr.sin_family = AF_INET; //use IPv4 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //use local host serv_addr.sin_port = htons(2222); //port is 2222 connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); write(sock, buffer, sizeof(buffer)); //read the data from the server char buffer1[1000000]; read(sock, buffer1, sizeof(buffer1)-1); printf("Your input is: %s\n", buffer); printf("Message form server: %s", buffer1); printf("\n"); //close the socket close(sock); } } // the command line has no input else { printf("Please enter one number\n"); } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "strfunc.h" #include "request.h" #define REQ_DBG 1 #define MAX_FILE_SIZE 2048 #define member_file "member.txt" #define prescription_file "prescription.txt" /* * Member format * 6 lines represents 1 member * Each line in order is id, passwd, name, level, birthday, description * Ex: member.txt * nick0212\n * 123456 * Nick\n * 2\n * 1995/02/12\n * He is a good doctor\n */ // return line_count int get_lines(char member_lines[][128], char *file_name) { FILE *file = fopen(file_name, "r"); if (!file) { printf("Couldn't find %s\n", file_name); return -1; } char *line = NULL; size_t len = 0; int line_count = 0; while (getline(&line, &len, file) != -1) { line[strlen(line) - 1] = '\0'; // remove break line strcpy(member_lines[line_count], line); line_count++; } fclose(file); return line_count; } void save_lines(char member_lines[][128], int member_line_count, char *file_name) { FILE *file = fopen(file_name, "w"); if (!file) { printf("Couldn't find %s\n", file_name); return; } int i; for (i = 0; i < member_line_count; i++) { fprintf(file, "%s\n", member_lines[i]); } fclose(file); } int get_member_by_id(char *id, char *dst_json) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, member_file); int i; for (i = 0; i < member_line_count; i += 6) { if (strcmp(id, member_lines[i]) == 0) { // found sprintf(dst_json, "{\"id\": \"%s\", \"name\": \"%s\", \"level\": %s, \"birthday\": \"%s\", \"description\": \"%s\"}", member_lines[i], member_lines[i+2], member_lines[i+3], member_lines[i+4], member_lines[i+5]); return 1; } } return 0; // not found } int get_member_all(char *dst_json) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, member_file); if (member_line_count < 6) { sprintf(dst_json, "[]"); return 0; } // Add first sprintf(dst_json, "[\n {\"id\": \"%s\", \"name\": \"%s\", \"level\": %s, \"birthday\": \"%s\", \"description\": \"%s\"}", member_lines[0], member_lines[2], member_lines[3], member_lines[4], member_lines[5]); int i; for (i = 6; i < member_line_count; i += 6) { char each_member[1024]; sprintf(each_member, ",\n {\"id\": \"%s\", \"name\": \"%s\", \"level\": %s, \"birthday\": \"%s\", \"description\": \"%s\"}", member_lines[i], member_lines[i+2], member_lines[i+3], member_lines[i+4], member_lines[i+5]); strcat(dst_json, each_member); } strcat(dst_json, "\n]"); return 1; } int get_member_template(char *dst_json, char *level) { char member_lines_all[256][128]; int member_line_count_all = get_lines(member_lines_all, member_file); // Keep level member only char member_lines[256][128]; int member_line_count = 0; int j; for (j = 0; j < member_line_count_all; j += 6) { if (strcmp(member_lines_all[j + 3], level) == 0) { int k; for (k = 0; k < 6; k++) { strcpy(member_lines[member_line_count + k], member_lines_all[j + k]); } member_line_count += 6; } } if (member_line_count < 6) { sprintf(dst_json, "[]"); return 0; } // Add first sprintf(dst_json, "[\n {\"id\": \"%s\", \"name\": \"%s\", \"level\": %s, \"birthday\": \"%s\", \"description\": \"%s\"}", member_lines[0], member_lines[2], member_lines[3], member_lines[4], member_lines[5]); int i; for (i = 6; i < member_line_count; i += 6) { char each_member[256]; sprintf(each_member, ",\n {\"id\": \"%s\", \"name\": \"%s\", \"level\": %s, \"birthday\": \"%s\", \"description\": \"%s\"}", member_lines[i], member_lines[i+2], member_lines[i+3], member_lines[i+4], member_lines[i+5]); strcat(dst_json, each_member); } strcat(dst_json, "\n]"); return 1; } int get_member_admin(char *dst_json) { if (REQ_DBG) printf("get_member_admin\n"); return get_member_template(dst_json, "1"); } int get_member_doctor(char *dst_json) { if (REQ_DBG) printf("get_member_doctor\n"); return get_member_template(dst_json, "2"); } int get_member_patient(char *dst_json) { if (REQ_DBG) printf("get_member_patient\n"); return get_member_template(dst_json, "3"); } int add_member(char *id, char *passwd, char *name, char *level, char *birthday, char *description) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, member_file); // check user exist int exist = 0; int i; for (i = 0; i < member_line_count; i += 6) { if (strcmp(id, member_lines[i]) == 0) exist = 1; } if (!exist) { strcpy(member_lines[member_line_count], id); strcpy(member_lines[member_line_count + 1], passwd); strcpy(member_lines[member_line_count + 2], name); strcpy(member_lines[member_line_count + 3], level); strcpy(member_lines[member_line_count + 4], birthday); strcpy(member_lines[member_line_count + 5], description); member_line_count += 6; save_lines(member_lines, member_line_count, member_file); return 1; } else { return 0; } } int edit_member(char *id, char *passwd, char *name, char *level, char *birthday, char *description) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, member_file); // check user exist int i; for (i = 0; i < member_line_count; i += 6) { if (strcmp(id, member_lines[i]) == 0) { // user exist if (id != NULL && strcmp(id, "") != 0) strcpy(member_lines[i], id); if (id != NULL && strcmp(passwd, "") != 0) strcpy(member_lines[i + 1], passwd); if (id != NULL && strcmp(name, "") != 0) strcpy(member_lines[i + 2], name); if (id != NULL && strcmp(level, "") != 0) strcpy(member_lines[i + 3], level); if (id != NULL && strcmp(birthday, "") != 0) strcpy(member_lines[i + 4], birthday); if (id != NULL && strcmp(description, "") != 0) strcpy(member_lines[i + 5], description); save_lines(member_lines, member_line_count, member_file); return 1; } } return 0; // not found } int delete_member(char *id) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, member_file); // check user exist int i; for (i = 0; i < member_line_count; i += 6) { if (strcmp(id, member_lines[i]) == 0) { // user exist if (i + 6 < member_line_count) { // not the last 6 lines // replace the last 6 lines to these 6 lines strcpy(member_lines[i], member_lines[member_line_count - 6]); strcpy(member_lines[i + 1], member_lines[member_line_count - 5]); strcpy(member_lines[i + 2], member_lines[member_line_count - 4]); strcpy(member_lines[i + 3], member_lines[member_line_count - 3]); strcpy(member_lines[i + 4], member_lines[member_line_count - 2]); strcpy(member_lines[i + 5], member_lines[member_line_count - 1]); } save_lines(member_lines, member_line_count - 6, member_file); return 1; } } return 0; // not found } /* * Prescription format * 5 lines represents 1 member * Each line in order is id, doctor_id, patient_id, date, prescription * Ex: prescription.txt * 1\n * thedoctor\n * thepatient\n * 2018/05/12\n * The disease is ...\n */ int get_prescription_by_id(char *id, char *dst_json) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, prescription_file); int i; for (i = 0; i < member_line_count; i += 5) { if (strcmp(id, member_lines[i]) == 0) { sprintf(dst_json, "{\"id\": \"%s\", \"doctor_id\": \"%s\", \"patient_id\": %s, \"date\": \"%s\", \"prescription\": \"%s\"}", member_lines[i], member_lines[i+1], member_lines[i+2], member_lines[i+3], member_lines[i+4]); return 1; } } return 0; // not found } int get_prescription_all(char *dst_json) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, prescription_file); if (member_line_count < 5) { sprintf(dst_json, "[]"); return 0; } // Add first sprintf(dst_json, "[\n {\"id\": \"%s\", \"doctor_id\": \"%s\", \"patient_id\": %s, \"date\": \"%s\", \"prescription\": \"%s\"}", member_lines[0], member_lines[1], member_lines[2], member_lines[3], member_lines[4]); int i; for (i = 5; i < member_line_count; i += 5) { char each_member[1024]; sprintf(each_member, ",\n {\"id\": \"%s\", \"doctor_id\": \"%s\", \"patient_id\": %s, \"date\": \"%s\", \"prescription\": \"%s\"}", member_lines[i], member_lines[i+1], member_lines[i+2], member_lines[i+3], member_lines[i+4]); strcat(dst_json, each_member); } strcat(dst_json, "\n]"); return 1; } int add_prescription(char *doctor_id, char *patient_id, char *date, char *prescription) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, prescription_file); // find max id int max_id = 1; int i; for (i = 0; i < member_line_count; i += 5) { if (atoi(member_lines[i]) > max_id) max_id = atoi(member_lines[i]); } sprintf(member_lines[member_line_count], "%d", max_id + 1); strcpy(member_lines[member_line_count + 1], doctor_id); strcpy(member_lines[member_line_count + 2], patient_id); strcpy(member_lines[member_line_count + 3], date); strcpy(member_lines[member_line_count + 4], prescription); member_line_count += 5; save_lines(member_lines, member_line_count, prescription_file); return 1; } int edit_prescription(char *id, char *doctor_id, char *patient_id, char *date, char *prescription) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, prescription_file); int i; for (i = 0; i < member_line_count; i += 5) { if (strcmp(id, member_lines[i]) == 0) { strcpy(member_lines[i + 1], doctor_id); strcpy(member_lines[i + 2], patient_id); strcpy(member_lines[i + 3], date); strcpy(member_lines[i + 4], prescription); save_lines(member_lines, member_line_count, prescription_file); return 1; } } return 0; // not found } int delete_prescription(char *id) { char member_lines[256][128]; int member_line_count = get_lines(member_lines, prescription_file); int i; for (i = 0; i < member_line_count; i += 5) { if (strcmp(id, member_lines[i]) == 0) { if (i + 5 < member_line_count) { // not the last 5 lines // replace the last 5 lines to these 5 lines strcpy(member_lines[i], member_lines[member_line_count - 5]); strcpy(member_lines[i + 1], member_lines[member_line_count - 4]); strcpy(member_lines[i + 2], member_lines[member_line_count - 3]); strcpy(member_lines[i + 3], member_lines[member_line_count - 2]); strcpy(member_lines[i + 4], member_lines[member_line_count - 1]); } save_lines(member_lines, member_line_count - 5, prescription_file); return 1; } } return 0; // not found } int login(char *id, char *passwd, char *res) { // validation int valid = LOGIN_NOT_EXIST; char member_lines[256][128]; int member_line_count = get_lines(member_lines, member_file); int i; for (i = 0; i < member_line_count; i += 6) { if (strcmp(id, member_lines[i]) == 0 && strcmp(passwd, member_lines[i + 1]) == 0) { // found and password match if ('1' == member_lines[i + 3][0]) valid = LOGIN_SUCCESS_ADMIN; else if ('2' == member_lines[i + 3][0]) valid = LOGIN_SUCCESS_DOCTOR; else if ('3' == member_lines[i + 3][0]) valid = LOGIN_SUCCESS_PATIENT; break; } } // if (REQ_DBG) { // if (strcmp(id, "testadmin") == 0) { // valid = LOGIN_SUCCESS_ADMIN; // } else if (strcmp(id, "testdoctor") == 0) { // valid = LOGIN_SUCCESS_DOCTOR; // } else if (strcmp(id, "testpatient") == 0) { // valid = LOGIN_SUCCESS_PATIENT; // } // } switch (valid) { case LOGIN_SUCCESS_ADMIN: if (REQ_DBG) printf("LOGIN_SUCCESS_ADMIN\n"); sprintf(res, "HTTP/1.1 200 OK\r\nSet-Cookie: %s%s\r\nSet-Cookie: %s%d\r\n\r\n{\"success\": true}\r\n", COOKIE_USER_ID, id, COOKIE_USER_LEVEL, LOGIN_SUCCESS_ADMIN); break; case LOGIN_SUCCESS_DOCTOR: if (REQ_DBG) printf("LOGIN_SUCCESS_DOCTOR\n"); sprintf(res, "HTTP/1.1 200 OK\r\nSet-Cookie: %s%s\r\nSet-Cookie: %s%d\r\n\r\n{\"success\": true}\r\n", COOKIE_USER_ID, id, COOKIE_USER_LEVEL, LOGIN_SUCCESS_DOCTOR); break; case LOGIN_SUCCESS_PATIENT: if (REQ_DBG) printf("LOGIN_SUCCESS_PATIENT\n"); sprintf(res, "HTTP/1.1 200 OK\r\nSet-Cookie: %s%s\r\nSet-Cookie: %s%d\r\n\r\n{\"success\": true}\r\n", COOKIE_USER_ID, id, COOKIE_USER_LEVEL, LOGIN_SUCCESS_PATIENT); break; case LOGIN_NOT_EXIST: case LOGIN_INFO_INCORRECT: sprintf(res, "HTTP/1.1 403 Forbidden\r\nSet-Cookie: %s\"\"\r\n\r\n{\"success\": false}\r\n", COOKIE_USER_ID); } return valid; } void logout(char *res) { sprintf(res, "HTTP/1.1 200 OK\r\nSet-Cookie: %s\"\"\r\n\r\n{\"success\": true}\r\n", COOKIE_USER_ID); } /************************************************************ * Function: load_file_to_buffer * Read file by a given name * Parameters: * file_name - file name, in the same path that server is executed * buffer - the buffer that file content will put into * Returns: * >= 0 - file size * -1 - error ************************************************************/ int load_file_to_buffer(char *file_name, char *buffer) { FILE *file; file = fopen(file_name, "rb"); if (!file) { printf("Couldn't find %s\n", file_name); return -1; } fread(buffer, MAX_FILE_SIZE, 1, file); fseek(file, 0L, SEEK_END); // in order to find file size int file_size = ftell(file); printf("Server read %s, size %d bytes\n", file_name, file_size); fclose(file); return file_size; } <file_sep>Initial version of database for testing and viewing architechture Testing environment: lunix Configuration: database username:root passwd:<PASSWORD> database name:project please change those information in project.c before compile to compile, use gcc project.c -lmysqlclient -o project before ./project, make sure these is a database named "peoject" exist. <file_sep>CC = gcc CFLAGS = -Wall all: client server mkdir -p client_folder server_folder mv client client_folder mv server server_folder cp 1800bytes.txt 900bytes.txt server_folder client: client.c ${CC} $< ${CFLAGS} -o $@ server: server.c ${CC} $< ${CFLAGS} -o $@ clean: @rm -rf client_folder server_folder <file_sep># Team5 Lab1-Q3 Readme ## Purpose and Introduction Write a TCP client program that contacts two TIME servers and reports the times they return as well as the difference between them. In this question, we create two sockets for two TIME server, and request for the current time. We found the TIME server lists from this websites: https://tf.nist.gov/tf-cgi/servers.cgi ## Files This folder contains four files * Makefile * readme.md * tcp_time_client.c * This file is the main purpose of this lab ## Compile In command line, key in `make`. One executable file `tcp_time_client` will be compiled and generated. Use `make clean` to remove generated files. ## Execute Type `./tcp_time_client [T_SERVER_IP_1] [T_SERVER_IP_2]` to send requests to two TIME server T_SERVER_IP_1 and T_SERVER_IP_2. ## Test case We pick two arbitrary servers for this test case. * 192.168.127.12 * 172.16.58.3 ``` $ ./tcp_time_client 192.168.127.12 172.16.58.3 Send time request to 192.168.127.12... TCP socket created Connection established Send time request to 172.16.58.3... TCP socket created Connection established Receive from server 192.168.127.12: Mon Mar 5 20:41:30 2018 Receive from server 172.16.58.3: Mon Mar 5 20:41:31 2018 The difference between two servers are 1 seconds ``` <file_sep>#include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // string manipulation #include <sys/socket.h> #include <unistd.h> // read, write #define PORT 5678 #define MSG_SIZE 2048 int main() { // User input file_name char file_name[128]; printf("Please input file name to request: "); scanf("%s", file_name); // Create socket int sd = socket(PF_INET, SOCK_STREAM, 0); // PF_INET for BSD if (sd < 1) { printf("Couldn't create socket\n"); return -1; } printf("TCP socket created\n"); struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr("127.0.0.1"); server.sin_port = htons(PORT); // Connect if (connect(sd, (struct sockaddr *)&server, sizeof(server)) < 0) { printf("Connect failed\n"); return -1; } printf("Connect successful\n"); // Write // Define message to be written char client_msg[MSG_SIZE] = {0}; sprintf(client_msg, "GET /%s HTTP/1.1\r\n\r\n", file_name); if (write(sd, client_msg, strlen(client_msg)) < 0) { printf("Write failed\n"); return -1; } printf("Write successful\n"); // Read // Define message buffer from server char server_msg[MSG_SIZE] = {0}; int read_size = read(sd, server_msg, MSG_SIZE); if (read_size < 0) { printf("Read failed\n"); return -1; } printf("Read from server:\n%s\n", server_msg); char file_from_server[MSG_SIZE] = {0}; read_size = read(sd, file_from_server, MSG_SIZE); if (read_size < 0) { printf("Read failed\n"); return -1; } if (strcmp(server_msg, "HTTP/1.1 200 OK\r\n\r\n") == 0) { // write file FILE *file_to_write; file_to_write = fopen(file_name, "wb"); fwrite(file_from_server, read_size, 1, file_to_write); fclose(file_to_write); } else { printf("Fail message from server:\n%s\n", file_from_server); } return 0; } <file_sep>CC=gcc # # Define files generated by rpcgen # GFILES = get_file.h get_file_clnt.c get_file_svc.c get_file_xdr.c # # Define all program files # PROGS = client server # # Define all program files # CFLAGS = -Wall -g -Werror all: ${GFILES} ${PROGS} clean: rm *.o ${PROGS} ${GFILES} ${GFILES}: rpcgen -N get_file.x client: client_get_file.o get_file_clnt.o ${CC} ${CFLAGS} -o client client_get_file.o get_file_clnt.o client_get_file.o: ${CC} ${CFLAGS} -c client_get_file.c get_file_clnt.o: ${CC} ${CFLAGS} -c get_file_clnt.c server: get_file_svc.o remote_procedure.o ${CC} ${CFLAGS} -o server remote_procedure.o get_file_svc.o get_file_svc.o: ${CC} ${CFLAGS} -c get_file_svc.c remote_procedure.o: ${CC} ${CFLAGS} -c remote_procedure.c <file_sep>CC = gcc CFLAGS = -Wall all: server server: server.c jsmn.o request.o strfunc.o ${CC} server.c jsmn.o request.o strfunc.o ${CFLAGS} -lpthread -o $@ teststr: teststr.c strfunc.o jsmn.o request.o request.o: request.c strfunc.o: strfunc.c jsmn.o jsmn.o: jsmn.c clean: @rm -f server teststr *.o <file_sep>#include <stdio.h> #include <rpc/rpc.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include "get_file.h" static void write_to_file(const char* fname, char* buf); unsigned int check_file_size(const char *fname); int main(int argc, char *argv[]) { CLIENT *handle = NULL; char **file_content = NULL; char *server = "localhost"; char *fname = argv[1]; if (argc == 2) { /* create client handle */ if ((handle = clnt_create(server, GETFILEPROG, GETFILEVERS, "udp")) == NULL) { /* couldn't establish connection with server */ printf("Can not access rpc service.\n"); exit(1); } /* first call the remote procedure */ file_content = get_file_3(fname, handle); if (file_content == NULL){ printf("There is no file in server named: %s\n", fname); exit(1); } /* save file*/ write_to_file(fname, *file_content); int size = check_file_size(fname); printf("The size of the file received: %d\n", size); clnt_destroy(handle); /* done with handle */ return 0; } else { printf("Please enter the file name\n"); exit(1); } } static void write_to_file(const char* fname, char* buf){ if(fname != NULL){ // prepare to write int fd = open(fname, O_CREAT|O_RDWR, S_IRUSR|S_IRGRP); if(fd < 0){ printf("error to open file: %s\n", fname); exit(-1); } write(fd, buf, (int)strlen(buf)); } } unsigned int check_file_size(const char *fname) { unsigned int filesize = -1; struct stat statbuff; if(stat(fname, &statbuff) < 0){ return filesize; }else{ filesize = statbuff.st_size; } return filesize; } <file_sep>#include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <time.h> #include <unistd.h> #define TCP_TIME_PORT 37 #define TRANSFORM_OFFSET 2208988800U // transform raw_time (32 bits from server) to a time_t value time_t trans_time_format(unsigned int raw_time) { return ntohl(raw_time) - TRANSFORM_OFFSET; } // save cur_time as a string into time_str void time_to_string(char *time_str, time_t cur_time) { strcpy(time_str, ctime(&cur_time)); time_str[strlen(time_str) - 1] = '\0'; // remove \n } // request time to specific time server and get time_t as return value time_t request_time(char *time_server_ip) { // Create socket int sd = socket(AF_INET, SOCK_STREAM, 0); // SOCK_STREAM for TCP if (sd < 1) { printf("Couldn't create socket\n"); exit(1); } printf("TCP socket created\n"); struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr(time_server_ip); server.sin_port = htons(TCP_TIME_PORT); // Connect to server if (connect(sd, (struct sockaddr *)&server, sizeof(server)) < 0) { printf("Connect failed\n"); exit(1); } printf("Connection established\n"); // Send message to server unsigned int time_buf = 0; if (send(sd, &time_buf, sizeof(time_buf), 0) < 0) { printf("Send failed\n"); exit(1); } // Receive message from server if (recv(sd, &time_buf, sizeof(time_buf), 0) < 0) { printf("Recv failed\n"); exit(1); } // transform time format time_t trans_time = trans_time_format(time_buf); close(sd); return trans_time; } int main(int argc, char *argv[]) { // Check input should contain two ip address if (argc != 3) { printf("Two time server IP Addresses are required\n"); return 1; } // Send requests to two TIME servers printf("Send time request to %s...\n", argv[1]); time_t time1 = request_time(argv[1]); printf("Send time request to %s...\n", argv[2]); time_t time2 = request_time(argv[2]); // Transform time_t to string char time_str1[100], time_str2[100]; time_to_string(time_str1, time1); time_to_string(time_str2, time2); printf("Receive from server %s: %s\n", argv[1], time_str1); printf("Receive from server %s: %s\n", argv[2], time_str2); // Calculate time difference time_t diff = time2 > time1 ? time2 - time1 : time1 - time2; printf("The difference between two servers are %d seconds\n", (int)diff); return 0; } <file_sep>#include <arpa/inet.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // string manipulation #include <sys/socket.h> #include <unistd.h> // read, write #define BACKLOG 10 // queue length #define MAX_HEADER_SIZE 1024 #define MAX_DATA_SIZE 2048 struct client_param { int client_sd; char client_ip[32]; }; int start_socket(int port); void *conn_handler(void *param); int get_str_until_space(char *src, int src_start, char *dst); int load_file_to_buffer(char *file_name, char *buffer); int main() { int sd = start_socket(5678); // Define client variables struct sockaddr_in client; socklen_t client_len = sizeof(struct sockaddr_in); while (1) { // Accept int client_sd = accept(sd, (struct sockaddr *)&client, &client_len); char client_ip[32] = {0}; if (client_sd < 0) { printf("Accept failed\n"); exit(-1); } // Format client ip address and port into client_ip sprintf(client_ip, "%s:%d", inet_ntoa(client.sin_addr), client.sin_port); printf("Connection accepted with client %s\n", client_ip); pthread_t conn_thread; struct client_param param; param.client_sd = client_sd; strcpy(param.client_ip, client_ip); if (pthread_create(&conn_thread, NULL, conn_handler, &param) < 0) { printf("Create thread failed"); exit(-1); } } return 0; } /************************************************************ * Function: start_socket * Create a socket, bind and listen * Parameters: * port: listening port * Returns: * sd (socket descriptor) ************************************************************/ int start_socket(int port) { // Create socket int sd = socket(PF_INET, SOCK_STREAM, 0); // PF_INET for BSD if (sd < 1) { printf("Couldn't create socket\n"); exit(-1); } // Set server configuration struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; // enable any ip_addr server.sin_port = htons(port); // Bind if (bind(sd, (struct sockaddr *)&server, sizeof(server)) < 0) { printf("Bind failed\n"); exit(-1); } // Listen if (listen(sd, BACKLOG) < 0) { printf("Listen failed\n"); exit(-1); } printf("HTTP Server running on port %d\n", port); return sd; } /************************************************************ * Function: conn_handler * Thread executing function, read and write with client by given client_sd * Parameters: * void *param - a client_param structure * Returns: * 0 - successful ************************************************************/ void *conn_handler(void *param) { struct client_param *cp = (struct client_param *)param; int client_sd = cp->client_sd; char* client_ip = cp->client_ip; // Read char client_header[MAX_HEADER_SIZE] = {0}; int read_size = read(client_sd, client_header, MAX_HEADER_SIZE); if (read_size < 0) { printf("Read failed\n"); return (void *) -1; } printf("Client header ================\n"); printf("%s", client_header); printf("==============================\n"); // find out HTTP method and request file char method[8], file_name[32]; int pos = get_str_until_space(client_header, 0, method); // find method pos = get_str_until_space(client_header, pos + 2, file_name); // find file_name printf("Method = %s, File_name = %s\n", method, file_name); // Respond client according given method and file name char res[MAX_HEADER_SIZE] = {0}, buffer[MAX_DATA_SIZE] = {0}; if (strcmp(method, "GET") == 0) { // send file int file_size = load_file_to_buffer(file_name, buffer); if (file_size == -1) { // couldn't find file or other errors // 404 Not Found strcpy(res, "HTTP/1.1 404 Not Found\r\n\r\n"); if (write(client_sd, res, strlen(res)) < 0) { printf("Write failed\n"); return (void *) -1; } // Transfer Error Page if (strcmp(file_name, "") != 0) { sprintf(res, "<!doctype html><html><body>\ <h1>404 Not Found, File %s might not exist</h1>\ </body></html>\r\n\r\n", file_name); } else { sprintf(res, "<!doctype html><html><body>\ <h1>404 Not Found, Please request by given file name</h1>\ </body></html>\r\n\r\n"); } if (write(client_sd, res, strlen(res)) < 0) { printf("Write failed\n"); return (void *) -1; } } else { // 200 OK strcpy(res, "HTTP/1.1 200 OK\r\n\r\n"); if (write(client_sd, res, strlen(res)) < 0) { printf("Write failed\n"); return (void *) -1; } // Transfer data strcpy(res, "The Second Write\r\n\r\n"); if (write(client_sd, buffer, file_size) < 0) { printf("Write failed\n"); return (void *) -1; } } } else if (strcmp(method, "POST") == 0 || strcmp(method, "PUT") == 0) { // 403 Forbidden strcpy(res, "HTTP/1.1 403 Forbidden\r\n\r\n"); if (write(client_sd, res, strlen(res)) < 0) { printf("Write failed\n"); return (void *) -1; } // Transfer Error Page sprintf(res, "<!doctype html><html><body>\ <h1>403 Forbidden</h1>\ </body></html>\r\n\r\n"); if (write(client_sd, res, strlen(res)) < 0) { printf("Write failed\n"); return (void *) -1; } } else { // 400 Bad Request strcpy(res, "HTTP/1.1 400 Bad Request\r\n\r\n"); if (write(client_sd, res, strlen(res)) < 0) { printf("Write failed\n"); return (void *) -1; } // Transfer Error Page sprintf(res, "<!doctype html><html><body>\ <h1>400 Bad Request</h1>\ </body></html>\r\n\r\n"); if (write(client_sd, res, strlen(res)) < 0) { printf("Write failed\n"); return (void *) -1; } } printf("Write Response to %s\n\n", client_ip); close(client_sd); return (void *) 0; } /************************************************************ * Function: get_str_until_space * Get substr of src from given position until the first space and put in dst * EX - get_str_until_space("abc def", 0, dst) return 3, dst will be "abc" * Parameters: * src - original string * src_start - the start position (including) of src * dst - the buffer that the substring will be put into * Returns: * the position of next space or the length of src (it traverses to the end) ************************************************************/ int get_str_until_space(char *src, int src_start, char *dst) { int i; for (i = 0; src_start < strlen(src) && src[src_start] != ' '; i++) { dst[i] = src[src_start]; src_start++; } dst[i] = '\0'; return src_start; } /************************************************************ * Function: load_file_to_buffer * Read file by a given name * Parameters: * file_name - file name, in the same path that server is executed * buffer - the buffer that file content will put into * Returns: * >= 0 - file size * -1 - error ************************************************************/ int load_file_to_buffer(char *file_name, char *buffer) { FILE *file; file = fopen(file_name, "rb"); if (!file) { printf("Couldn't find %s\n", file_name); return -1; } fread(buffer, MAX_DATA_SIZE, 1, file); fseek(file, 0L, SEEK_END); // in order to find file size int file_size = ftell(file); printf("Server read %s, size %d bytes\n", file_name, file_size); fclose(file); return file_size; }
2a2de5ccbf26526ec55b89d4841da4171cc222c2
[ "Markdown", "C", "Makefile" ]
41
C
howarde8/NetProgAndAppl
66365632e417b5124f6f3b59a65132e0d5d12369
0545b6a414d46916e4bec038d8542182ed8618b8
refs/heads/master
<repo_name>sunning97/MusicPlayer<file_sep>/app/src/main/java/com/example/giangnguyen/musicplayer/SongAdapter.java package com.example.giangnguyen.musicplayer; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; /** * Created by <NAME> on 14/11/2017. */ public class SongAdapter extends ArrayAdapter { MediaManager mediaManager; private Context context; private int res; List<Song> list; public SongAdapter(@NonNull Context context, int resource, @NonNull List objects) { super(context, resource, objects); this.context = context; this.list = objects; this.res = resource; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { ViewHolder viewHolder; if(convertView == null) { viewHolder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(R.layout.song_item_layout,parent,false); viewHolder.tv_songName = convertView.findViewById(R.id.tv_songName); viewHolder.tv_songArtist = convertView.findViewById(R.id.tv_songArtist); viewHolder.tv_songDuration = convertView.findViewById(R.id.tv_songDuration); convertView.setTag(viewHolder); } else viewHolder = (ViewHolder) convertView.getTag(); mediaManager = new MediaManager(this.context); Song s = list.get(position); viewHolder.tv_songName.setText(s.getName()); viewHolder.tv_songArtist.setText(s.getArtist()); viewHolder.tv_songDuration.setText(mediaManager.getTimeSong(position)); return convertView; } private class ViewHolder { TextView tv_songName, tv_songDuration, tv_songArtist; } }
818c7a20d47b09570d26aabe0b8d1e743fb02466
[ "Java" ]
1
Java
sunning97/MusicPlayer
d9c4a8bac108c4fb7950f5fc30cbd77d144609bd
4471ed60f83255e395f20810a4659db0e5d4c655
refs/heads/master
<file_sep>/* <NAME> Assignment 1 */ //libraries for the program #include <stdio.h> #include <stdlib.h> #include <string.h> //Linked List Node created with global variable head. struct node { char name [50]; int id; struct node *next; } *head; //Prototypes int deleteId(int num); int deleteName(char *deleteName); void display(struct node *displayNode); void insert(char * insertName, char * insertId); void readDataFile(); //Main Function int main() { //declare all variables char nameDelete[50]; char nameInsert[50]; char id[10]; int idDelete; int i; int num; struct node *DisplayList; //set head equal to NULL head = NULL; //Read the Data File to put the data in the linked list readDataFile(); //prints out the menu of options for the user while(1) { printf("OPTIONS FOR PROGRAM\n\n"); printf("1. Insert a new student\n"); printf("2. Display the list\n"); printf("3. Delete student by Id\n"); printf("4. Delete student by Name\n"); printf("5. Exit program\n"); printf("Enter your choice : "); //if the option entered is not a number, it exits the program and prompts the user to enter a number if(scanf("%d", &i) <= 0) { printf("Enter only a number between 1-5. \n"); exit(0); } //if the option entered is a usable number, then we go to the cases. else { //switch function to read in the options for the cases. switch(i) { //option 1 to insert names and the id as a node into the linked list. case 1: //prompts the user to insert the name of the person and scans it in. printf("Enter the name to insert: "); scanf(" %[^\n]s", nameInsert); //prompts the user to enter the name of the id for the person, and scans it in. printf("What is the id number for %s? ", nameInsert); scanf(" %[^\n]s", id); //then it inserts the name into the linked list as a node at the end and returns. insert(nameInsert, id); break; //option 2 to display the list case 2: //if the head is equal to NULL, that means the list is empty and we tell the user. if(head == NULL) { printf("List is Empty\n"); } else { //if the list is not empty, then we display the list from the file. printf("Element(s) in the list are : \n"); display(DisplayList); } break; //option 3 deletes nodes by id case 3: //if the head is equal to NULL, then the list is empty and then we tell the user it is empty if(head == NULL) printf("List is Empty\n"); else { //prompts the user to enter the ID to be deleted and scans in the data. printf("Enter the ID to delete : "); scanf("%d", &num); //if the id to be deleted exists, then we delete the node that the id is assigned to. //if the id does not exist, then we tell the user and then we return. if(deleteId(num)) printf("%d deleted successfully\n", num); else printf("%d not found in the list\n", num); } break; //option 4 deletes by name case 4: //if the head is equal to NULL, then the list is empty, so we print that out if(head == NULL) printf("List is Empty\n"); else { //prompts user to enter the desired name to be deleted and scans it in. printf("Enter the name to delete : "); scanf(" %[^\n]s", nameDelete); //if the name entered is in the linked list, then we delete it and its id and return //if its not in the list then we print out that it is not in the list and return if(deleteName(nameDelete)) printf("%s deleted successfully\n", nameDelete); else printf("%s not found in the list\n", nameDelete); } break; //exits the program with selection 5. case 5: printf("You have chosen to exit the program, Goodbye!\n\n"); return 0; //the default option when the value given is not an option it prints out that it is invalid. default: printf("Invalid Option\n"); } } } return 0; } //delete the node by Id function int deleteId(int num) { // sets temp and prev struct pointers struct node *temp, *prev; //sets temp equal to head temp = head; //while temp is not equal to NULL while(temp != NULL) { //if the id temp is pointing to is the number entered if(temp->id == num) { //if the temp pointer is at the beginning if(temp == head) { //then that means the id we need to delete is at the beginning //so we set the head of the list to the next node essentially removing it head = temp->next; //then we free the space and return free(temp); return 1; } else { //we set the previous pointer to the temporary pointer and free space prev->next = temp->next; free(temp); return 1; } } else { //if its not the correct id, then we keep traversing the list prev = temp; temp = temp->next; } } return 0; } //deleteName function that deletes nodes by name int deleteName(char *name) { //sets the temp pointer and the pointer to the previous node struct node *temp, *prev; //sets temp pointer equal to head temp = head; //while temp is not equal to NULL while(temp != NULL) { //compare the name the temp pointer is pointing to with the name that name is pointing to. if(strcmp(temp->name, name) ==0) { //if the name is a match, then it prints we found the name printf("found %s!\n", name); if(temp == head) { head = temp->next; free(temp); return 1; } //when we find the name, we set the next part of prev node, to the next portion of the temp node //then we free temp and return with success else { //sets prev next equal to temp next prev->next = temp->next; //frees temp free(temp); return 1; } } else { //the prev pointer goes back to temp, and the temp keeps traversing the list prev = temp; temp = temp->next; } } return 0; } //Display Function to display the list from the file void display(struct node *displayNode) { //set the displayNode equal to head at the beginning displayNode = head; //if the displayNode is equal to NULL, then we return. if(displayNode == NULL) { return; } //if displayNode is not equal to NULL while(displayNode != NULL) { //traverses the linked list and prints out each name and id next to each other printf("Student %s has id %d\n", displayNode->name, displayNode->id); //the part that actually traverses the list, the above part prints each node displayNode = displayNode->next; } //prints a space after each name to make it more readable printf("\n"); } //function for inserting the name and id of the person void insert(char *insertName, char *insertId) { //we set 2 temporary pointers to insert in the list struct node *temp, * temp2; temp = (struct node*)malloc(sizeof(struct node)); //atoi gets rid of the whitespace characters until the first non-whitespace character is found int intId = atoi(insertId); //string copy the name temp pointer is pointing too, to insertName strcpy(temp->name, insertName); temp->id = intId; //since we created a new node, the pointer field for the node is at the end of the list so it points to NULL temp->next = NULL; //if the head pointer is pointing at nothing, then the head pointer is set to the temp pointer if(head == NULL) { head = temp; } //if the head is not pointing to NULL, then set the 2nd temp pointer too head else { temp2 = head; //if the noce after the second temporary pointer is not NULL, we set the second temp pointer to the next node. while(temp2->next != NULL) { temp2 = temp2->next; } //sets the next node from temporary pointer 2 to the new temp which is the new node we inserted. temp2->next = temp; } } //Function to read in the data from the file void readDataFile() { //declare variables //set the constant length const LENGTH = 50; //set the constant character comma const char comma[2] = ","; char * name; char * id; char data[LENGTH]; //sets fileName to the file we need to open which is AssignmentOneInput.txt char fileName[] = "AssignmentOneInput.txt"; //set file pointer FILE *ifp; //opens the file in read mode so we cant change the file ifp = fopen(fileName, "r"); //while the the is there we execute this function while( (fgets(data, LENGTH, ifp) ) != NULL) { //string token splits the string into "tokens" //basically making it easier to remove the comma name = strtok(data, comma); id = strtok(NULL, comma); //inserts the name and id separately to work around the comma insert(name, id); } //we close the file fclose(ifp); } <file_sep># COP-3502-Assignment-One COP 3502 Assignment One
c1baf26615230fbd189e7bb0e3fee9fa92254fba
[ "Markdown", "C" ]
2
C
ChrisKanazeh/COP-3502-Assignment-One
59c8614f9111502871520ce6ce40c6e36cba39b3
7ef0cd71d47bd1bd82c5009640bcb808713c532d
refs/heads/master
<repo_name>uriJuhasz/CXX_benchmarks_5<file_sep>/benchmarks/TimeMeasurement.h #ifndef TIME_MEASUREMENT__CXX #define TIME_MEASUREMENT__CXX #include <string> #include <functional> namespace TimeMeasurement { using std::string; using std::function; void measure(const function<int()>& f,string s); } #endif <file_sep>/benchmarks/CMakeLists.txt set (HEADER_LIST "${HEADER_LIST}" "${CMAKE_CURRENT_SOURCE_DIR}/Benchmarks.h" "${CMAKE_CURRENT_SOURCE_DIR}/TimeMeasurement.h" PARENT_SCOPE ) set (SRC_LIST "${SRC_LIST}" "${CMAKE_CURRENT_SOURCE_DIR}/Benchmark1.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/Benchmark2.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/TimeMeasurement.cpp" PARENT_SCOPE ) <file_sep>/benchmarks/Benchmarks.h #ifndef BENCHMARKS__CXX_ #define BENCHMARKS__CXX_ namespace benchmarks { void test1(); void test2(); } #endif <file_sep>/benchmarks/TimeMeasurement.cpp #include "TimeMeasurement.h" #include <chrono> #include <iostream> #include <iomanip> namespace TimeMeasurement { using namespace std; void measure(const function<int()>& f,string s) { auto startT= chrono::system_clock::now(); f(); auto endT = chrono::system_clock::now(); chrono::duration<double> elapsed_seconds = endT-startT; const int elapsedNS = static_cast<int>(1000000 * elapsed_seconds.count()); cout << s << " time: " << setw(10) << elapsedNS << "ns" << endl; } } <file_sep>/benchmarks/Benchmark2.cpp #include "Benchmarks.h" #include "TimeMeasurement.h" #include <memory> #include <vector> #include <map> #include <unordered_map> #include <optional> #include <cassert> #include <iostream> //#include <optional> namespace benchmarks { using namespace std; // using namespace std::experimental; using std::optional; constexpr int numElements = 100000; constexpr int numReads = 400000; template<class C> class StdMapWrapper { private: C& m; public: inline StdMapWrapper(C& m) : m(m) {} typedef typename C::key_type K; typedef typename C::mapped_type V; inline void insert(const K k, const V v) { m.emplace(k,v); } inline void insert(const pair<K,V>& p) { m.emplace(p.first,p.second); } inline optional<V> lookup(const K k) const { typedef typename C::const_iterator CIT; const CIT it = m.find(k); if (it==m.cend()) return optional<V>(); else return optional<V>(it->second); } }; template<template <class,class> class C>int fMap(const vector<pair<int,int>>& inputs) { typedef C<int,int> M; M m; for (const auto p : inputs) m.insert(p); int x = 0; const auto itEnd = m.cend(); for (int i=0; i<numReads; ++i) { const auto it = m.find(i); if (it != itEnd) x += it->second; } return x; } template<class M>int fMap2(const vector<pair<int,int>>& inputs, M& m) { for (const auto p : inputs) m.insert(p); int x = 0; for (int i=0; i<numReads; ++i) { const auto r = m.lookup(i); if (r) x += *r; } return x; } template <class K, class V> using TreeMap = map<K,V>; template <class K, class V> using HashMap = unordered_map<K,V>; template <class T> class PoolAllocator { private: const size_t m_size; size_t m_cur; T* const m_pool; public: typedef T value_type; inline explicit PoolAllocator(const size_t initial) : m_size(initial) ,m_cur(0) ,m_pool( static_cast<T*>(malloc(initial * sizeof(T)))) { assert(initial>0); } inline ~PoolAllocator(){ delete m_pool; } template<class U>inline constexpr PoolAllocator(const PoolAllocator<U>& other) noexcept : m_size(other.size()) ,m_cur(0) ,m_pool(static_cast<T*>(malloc(m_size * sizeof(T)))) {} inline T* allocate(const std::size_t n) { //if(n > std::size_t(-1) / sizeof(T)) throw std::bad_alloc(); assert(m_cur+n <= m_size); if (m_cur+n>m_size) { cerr << "PA[" << this << "]<" << typeid(*this).name() << ">: " << "Allocation error: " << "size=" << m_size << "cur=" << m_cur << "n=" << n << endl; throw new bad_alloc(); } auto r = m_pool + m_cur; m_cur += n; return r; } inline void deallocate(T*, std::size_t) noexcept { } size_t size() const {return m_size; } size_t cur() const {return m_cur; } }; /*template <class T, class U> bool operator==(const Mallocator<T>&, const Mallocator<U>&) { return true; } template <class T, class U>bool operator!=(const Mallocator<T>&, const Mallocator<U>&) { return false; }*/ void test2() { vector<pair<int,int>> pairs; pairs.reserve(numElements); for (int i=0; i<numElements; ++i) pairs.emplace_back(i,i); TimeMeasurement::measure([pairs]() -> int { return fMap<TreeMap>(pairs); },"std::map [ ]"); TimeMeasurement::measure([pairs]() -> int { return fMap<HashMap>(pairs); },"std::unordered_map[ ]"); TreeMap<int,int> m1; HashMap<int,int> m2; StdMapWrapper<TreeMap<int,int>> m1W( m1 ); StdMapWrapper<HashMap<int,int>> m2W( m2 ); TimeMeasurement::measure([&]() -> int { return fMap2<StdMapWrapper<TreeMap<int,int>>>(pairs,m1W); },"std::map [W ]"); TimeMeasurement::measure([&]() -> int { return fMap2<StdMapWrapper<HashMap<int,int>>>(pairs,m2W); },"std::unordered_map[W ]"); cout << "Eck.0" << endl; typedef pair<const int,int> p; typedef PoolAllocator<p> PA1; typedef map<int,int,less<int>,PA1> TreeMapPA; auto pa1 = PA1(numElements*2); auto m1PA = TreeMapPA(less<int>(),pa1); typedef StdMapWrapper<TreeMapPA> TreeMapPAW; TreeMapPAW m1PAW(m1PA); cout << "Eck.1" << endl; typedef unordered_map<int,int,hash<int>,equal_to<int>,PA1> HashMapPA; auto pa2 = PA1(numElements*2); auto m2PA = HashMapPA(numElements,hash<int>(),equal_to<int>(),pa2); typedef StdMapWrapper<HashMapPA> HashMapPAW; HashMapPAW m2PAW(m2PA); cout << "Eck.2" << endl; TimeMeasurement::measure([&]() -> int { return fMap2<TreeMapPAW>(pairs,m1PAW); },"std::map [PA]"); TimeMeasurement::measure([&]() -> int { return fMap2<HashMapPAW>(pairs,m2PAW); },"std::unordered_map[PA]"); } } <file_sep>/build/Makefile # CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.7 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/bin/cmake # The command to remove a file. RM = /usr/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5 # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/build #============================================================================= # Targets provided globally by CMake. # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." /usr/bin/cmake-gui -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start /home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/build/CMakeFiles /home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/build/CMakeFiles/progress.marks $(MAKE) -f CMakeFiles/Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start /home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/build/CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) -f CMakeFiles/Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named CXX_benchmarks_5 # Build rule for target. CXX_benchmarks_5: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 CXX_benchmarks_5 .PHONY : CXX_benchmarks_5 # fast build rule for target. CXX_benchmarks_5/fast: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/build .PHONY : CXX_benchmarks_5/fast benchmarks/Benchmark1.o: benchmarks/Benchmark1.cpp.o .PHONY : benchmarks/Benchmark1.o # target to build an object file benchmarks/Benchmark1.cpp.o: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark1.cpp.o .PHONY : benchmarks/Benchmark1.cpp.o benchmarks/Benchmark1.i: benchmarks/Benchmark1.cpp.i .PHONY : benchmarks/Benchmark1.i # target to preprocess a source file benchmarks/Benchmark1.cpp.i: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark1.cpp.i .PHONY : benchmarks/Benchmark1.cpp.i benchmarks/Benchmark1.s: benchmarks/Benchmark1.cpp.s .PHONY : benchmarks/Benchmark1.s # target to generate assembly for a file benchmarks/Benchmark1.cpp.s: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark1.cpp.s .PHONY : benchmarks/Benchmark1.cpp.s benchmarks/Benchmark2.o: benchmarks/Benchmark2.cpp.o .PHONY : benchmarks/Benchmark2.o # target to build an object file benchmarks/Benchmark2.cpp.o: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark2.cpp.o .PHONY : benchmarks/Benchmark2.cpp.o benchmarks/Benchmark2.i: benchmarks/Benchmark2.cpp.i .PHONY : benchmarks/Benchmark2.i # target to preprocess a source file benchmarks/Benchmark2.cpp.i: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark2.cpp.i .PHONY : benchmarks/Benchmark2.cpp.i benchmarks/Benchmark2.s: benchmarks/Benchmark2.cpp.s .PHONY : benchmarks/Benchmark2.s # target to generate assembly for a file benchmarks/Benchmark2.cpp.s: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark2.cpp.s .PHONY : benchmarks/Benchmark2.cpp.s benchmarks/TimeMeasurement.o: benchmarks/TimeMeasurement.cpp.o .PHONY : benchmarks/TimeMeasurement.o # target to build an object file benchmarks/TimeMeasurement.cpp.o: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/benchmarks/TimeMeasurement.cpp.o .PHONY : benchmarks/TimeMeasurement.cpp.o benchmarks/TimeMeasurement.i: benchmarks/TimeMeasurement.cpp.i .PHONY : benchmarks/TimeMeasurement.i # target to preprocess a source file benchmarks/TimeMeasurement.cpp.i: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/benchmarks/TimeMeasurement.cpp.i .PHONY : benchmarks/TimeMeasurement.cpp.i benchmarks/TimeMeasurement.s: benchmarks/TimeMeasurement.cpp.s .PHONY : benchmarks/TimeMeasurement.s # target to generate assembly for a file benchmarks/TimeMeasurement.cpp.s: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/benchmarks/TimeMeasurement.cpp.s .PHONY : benchmarks/TimeMeasurement.cpp.s main.o: main.cpp.o .PHONY : main.o # target to build an object file main.cpp.o: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/main.cpp.o .PHONY : main.cpp.o main.i: main.cpp.i .PHONY : main.i # target to preprocess a source file main.cpp.i: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/main.cpp.i .PHONY : main.cpp.i main.s: main.cpp.s .PHONY : main.s # target to generate assembly for a file main.cpp.s: $(MAKE) -f CMakeFiles/CXX_benchmarks_5.dir/build.make CMakeFiles/CXX_benchmarks_5.dir/main.cpp.s .PHONY : main.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... rebuild_cache" @echo "... edit_cache" @echo "... CXX_benchmarks_5" @echo "... benchmarks/Benchmark1.o" @echo "... benchmarks/Benchmark1.i" @echo "... benchmarks/Benchmark1.s" @echo "... benchmarks/Benchmark2.o" @echo "... benchmarks/Benchmark2.i" @echo "... benchmarks/Benchmark2.s" @echo "... benchmarks/TimeMeasurement.o" @echo "... benchmarks/TimeMeasurement.i" @echo "... benchmarks/TimeMeasurement.s" @echo "... main.o" @echo "... main.i" @echo "... main.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>/main.cpp #include <iostream> #include <vector> #include <string> #include "benchmarks/Benchmarks.h" using namespace std; int main(int argc, const char *argv[]) { cout << "===Start" << endl; cout << "Arguments:" << endl; vector<string> args(argv,argv+argc); for (const auto& s : args) cout << " " << s << endl; cout << " Benchmark 1:" << endl; benchmarks::test1(); try { cout << " Benchmark 2:" << endl; benchmarks::test2(); }catch(const exception& e) { cerr << "Error: " << e.what() << endl; } cout << "===End" << endl; return 0; } <file_sep>/benchmarks/Benchmark1.cpp #include "Benchmarks.h" #include "TimeMeasurement.h" #include <memory> namespace benchmarks { using namespace std; constexpr int numIterations = 1000000; int f1() { int x = 0; for (int i=0; i<numIterations; ++i) { x = x*i+(x-1); } return x; } void lll(); void test1() { TimeMeasurement::measure(f1,"additions"); // lll(); } class C{public: int f(); int x;}; // int sa_test1(const C* p __attribute__((nonnull))) int sa_test1(const C* p [[gnu::nonnull]]) { C* const pp = nullptr; pp->x++; return p->x; } int sa_test2(unique_ptr<C> p [[gnu::nonnull]] ) { unique_ptr<C> p2; return p->x + p2->x; } void lll() { sa_test1(nullptr); sa_test2(nullptr); sa_test2(make_unique<C>()); } } <file_sep>/build/CMakeFiles/CXX_benchmarks_5.dir/DependInfo.cmake # The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/benchmarks/Benchmark1.cpp" "/home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/build/CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark1.cpp.o" "/home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/benchmarks/Benchmark2.cpp" "/home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/build/CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark2.cpp.o" "/home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/benchmarks/TimeMeasurement.cpp" "/home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/build/CMakeFiles/CXX_benchmarks_5.dir/benchmarks/TimeMeasurement.cpp.o" "/home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/main.cpp" "/home/uri/projects/CXX_benchmarks_5/CXX_benchmarks_5/build/CMakeFiles/CXX_benchmarks_5.dir/main.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "Clang") # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep>/build/CMakeFiles/CXX_benchmarks_5.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/CXX_benchmarks_5.dir/main.cpp.o" "CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark1.cpp.o" "CMakeFiles/CXX_benchmarks_5.dir/benchmarks/Benchmark2.cpp.o" "CMakeFiles/CXX_benchmarks_5.dir/benchmarks/TimeMeasurement.cpp.o" "CXX_benchmarks_5.pdb" "CXX_benchmarks_5" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/CXX_benchmarks_5.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/CMakeLists.txt project(CXX_benchmarks_5) cmake_minimum_required(VERSION 2.8) aux_source_directory(. SRC_LIST) set(CMAKE_CXX_STANDARD 17) if (LINUX) set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wpedantic -Wall -Wextra -std=c++17" ) endif() if (MSVC) endif() set (SRC_LIST "${SRC_LIST}" "main.cpp" ) add_subdirectory(benchmarks) add_executable(${PROJECT_NAME} ${SRC_LIST})
8ca906cf592b376452b8352ef626363217c16c3f
[ "Makefile", "CMake", "C++" ]
11
C++
uriJuhasz/CXX_benchmarks_5
ec739181af3f7d44bd2da2e91c30a42ba37d8ff6
4b293ba586856f648bc4c9c9ef26c6e8d5e16a9e
refs/heads/master
<repo_name>Roderich25/EmoticonSentiment<file_sep>/scripts/scoreEmoticons.R setwd('C:/etc/Projects/Data/_Ongoing/EmoticonSentiment/') ##################################################### ##Part 0: Acquire Bundle of tweets with emoticons#### tweets <- readLines("data/tweetswithemoticons.txt") #a vector of characterstrings, each element correpsonding to the text part of exactly one tweet ####################################### ######## Part 1: Score Tweets ######### sentiment.file <- "data/AFINN-111.txt" #Initialize sentiment dictionary df.sentiments <- read.table(sentiment.file,header=F,sep="\t",quote="",col.names=c("term","score")) df.sentiments$term <- gsub("[^[:alnum:]]", " ",df.sentiments$term) ScoreTerm <- function(term){ df.sentiments[match(term,df.sentiments[,"term"]),"score"] } ScoreText <- function(text){ text <- tolower(gsub("[^[:alnum:]]", " ",text)) text <- do.call(c,strsplit(text," ")) text <- text[text!=""] length(text) scores <- ScoreTerm(text) scores[is.na(scores)] <- 0 sum(scores) } tweet.scores <- sapply(tweets,ScoreText) ######################################### #### Part 2: Extract the Emoticon(s) #### emoticon.list <- c( "\\:\\-\\)","\\:\\)","\\=\\)", "\\:\\-D","\\:D","8\\-D","8D","x\\-D","xD","X\\-D","XD", "\\:\\-\\(","\\:\\(", "\\:\\-\\|","\\:\\|", "\\:\\'\\-\\(","\\:\\'\\(\\)", "\\:\\'\\-\\)","\\:\\'\\)", "\\:\\-o","\\:\\-O","\\:o","\\:O", "o_O","o\\.O","O_o","O\\.o", "\\:\\*","\\;\\-\\)","\\;\\)", "\\%\\-\\)", "\\<3","\\<\\/3" ) ## oh, oh, oh! Take care that none is a substring of another. ## You can't have ":)" and ":))"; or ">:-)" and ":-)", etc. ## The second kind may actually be a concern ## If you do want them, you'll need to change the matching code somewhat to make sure it only matches the longest one or something ## However, it's perfectly okay to have multiple emoticons in the same text. Like "Oh my! :-) :-O" FindMatches <- function(emoticon,tweets){ #This is a simple function, but I'm separating this out because I might want to replace it with a more complex logic that takes care of substrings, etc. grep(emoticon,tweets) #This will return a vector of elements from <tweets> which contain <emoticon> } emoticon.score.distributions <- sapply(emoticon.list, function(e){ containing.indices <- FindMatches(e,tweets) score.dist <- tweet.scores[containing.indices] as.numeric(score.dist) }) ############################################### ##### Part 3: Post-processing The results ##### ## 1: Mean,sd emoticon.sentiment.means <- sapply(emoticon.score.distributions,mean) emoticon.sentiment.sds <- sapply(emoticon.score.distributions,sd) ##2: Plot clean.scores <- emoticon.score.distributions[sapply(emoticon.score.distributions,length)!=0] emoticon.tags <-do.call(c, sapply(1:length(clean.scores), function(x) rep(names(clean.scores[x]),length(clean.scores[[x]])) ) ) allscores <- do.call(c, clean.scores) df.scores<-data.frame(score=as.numeric(allscores),emoticon=emoticon.tags) row.names(df.scores)<- 1:nrow(df.scores) #The above is a pretty roundabout way to achieve this. If you can think of something better, let me know library(ggplot2) p <- ggplot(data=df.scores,aes( x=score, y=reorder(emoticon,score,mean), color=emoticon, group=emoticon)) p.nonzero <- ggplot(data=df.scores[df.scores$score!=0,],aes( x=score,y=reorder(emoticon,score,mean), color=emoticon, group=emoticon)) p + geom_point(size=2,alpha=0.6, position = position_jitter(height = 0.2)) + geom_errorbarh(stat = "vline", xintercept = "mean", height=0.6, size=1, aes(xmax=..x..,xmin=..x..),color="black") + theme(legend.position="none") + xlab("Score") + ylab("Emoticon") + scale_y_discrete(labels=function(s) { gsub('\\\\','',s) }) #To remove the \\s from the emoticons ## 3: Oddities which(grepl("\\:\\-\\(",tweets) & tweet.scores>5) #################################################### #To Do (2013-09-09): ## Decide how to handle the substring cases, if any #################################################### <file_sep>/scripts/gatherTweets.py import oauth2 as oauth import urllib2 as urllib import json import string access_token_key = "" access_token_secret = "" consumer_key = "" consumer_secret = "" _debug = 0 oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret) oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() http_method = "GET" http_handler = urllib.HTTPHandler(debuglevel=_debug) https_handler = urllib.HTTPSHandler(debuglevel=_debug) ''' Construct, sign, and open a twitter request using the hard-coded credentials above. ''' def twitterreq(url, method, parameters): req = oauth.Request.from_consumer_and_token(oauth_consumer, token=oauth_token, http_method=http_method, http_url=url, parameters=parameters) req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token) headers = req.to_header() if http_method == "POST": encoded_post_data = req.to_postdata() else: encoded_post_data = None url = req.to_url() opener = urllib.OpenerDirector() opener.add_handler(http_handler) opener.add_handler(https_handler) response = opener.open(url, encoded_post_data) return response def hasEmoticon(text): emoticonlist=[':-)', ':)','=)', ':-D',':D','8-D','8D','x-D','xD','X-D','XD', ':-(',':(', ':-|',':|', ":'-(", ":'()", ":'-)",":')", ':-o',':-O',':o',':O', 'o_O','o_0','o.O', ':*',';-)',';)', '%-)','%)', '<3','</3'] for e in emoticonlist: if text.find(e) > -1: return True return False def fetchsamples(): tweetfile = open('C:/etc/Projects/Data/_Ongoing/EmoticonSentiment/data/tweetswithemoticons2.txt', 'a') url = "https://stream.twitter.com/1/statuses/sample.json" parameters = [] response = twitterreq(url, "GET", parameters) ctr=0 for line in response: #extract tweet text from line jtweet=json.loads(line) #print line if "text" in jtweet and "lang" in jtweet and jtweet["lang"]=='en': tweet=(jtweet["text"]).encode('utf-8'),"\n" tweet=' '.join(tweet) if hasEmoticon(tweet): #print tweet tweet=tweet.replace("\n"," ") # basically, so that one line in file correponds to exactly one full tweet tweetfile.write("\n" + tweet) ctr+=1 if ctr%100==0: print ctr tweetfile.close() if __name__ == '__main__': fetchsamples() <file_sep>/README.md Emoticon Sentiments =================== The script gatherTweets.py reads from Twitter's streaming API, and writes any tweet with an emoticon in it to a file. The R script scoreEmoticons.R then reads this file, scores each tweet, and searches for the presence of each emoticon (from a predefined list). The score distributions for each emoticon are then plotted. A more descriptive analysis can be found on my blog [Hot Damn, Data!](http://www.hotdamndata.com/2013/09/the-happiest-emoticons.html) -- The Happiest Emoticons
1cdbaa7a54bb1203cd21154cad5413cd3b279511
[ "Markdown", "Python", "R" ]
3
R
Roderich25/EmoticonSentiment
758b92e40194bd730686ebebc54cdf603d56e0b3
b08123aa8b589cd2dcf2023bee2037c9903d64f0
refs/heads/master
<file_sep># LoopingVideoView [![Version](https://img.shields.io/cocoapods/v/LoopingVideoView.svg?style=flat)](http://cocoapods.org/pods/LoopingVideoView) [![License](https://img.shields.io/cocoapods/l/LoopingVideoView.svg?style=flat)](http://cocoapods.org/pods/LoopingVideoView) [![Platform](https://img.shields.io/cocoapods/p/LoopingVideoView.svg?style=flat)](http://cocoapods.org/pods/LoopingVideoView) ## Usage ## Requirements ## Installation LoopingVideoView is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "LoopingVideoView" ``` ## Author Gustavo ## License LoopingVideoView is available under the MIT license. See the LICENSE file for more info. <file_sep>// // LoopingVideoView2.swift // LoopingVideoView // // Created by <NAME> on 4/12/15. // // import UIKit import AVFoundation @IBDesignable class LoopingVideoView: UIView { @IBInspectable var mainBundleFileName : NSString? var playCount: Int = 100 var playerLayer = AVPlayerLayer() override func layoutSubviews() { super.layoutSubviews() if let fileName = mainBundleFileName { let url = Bundle.main.url(forResource: fileName as String, withExtension: nil) if let url = url { play(url, count: playCount) } else { print("LoopingVideoView: Cannot find video \(fileName)") } } } func play(_ url:URL, count:Int) { guard let asset = try? type(of: self).composedAsset(url, count: count) else { print("LoopingVideoView: Error loading video from url: \(url)") return } let playerLayer = type(of: self).createPlayerLayer(asset) playerLayer.frame = layer.bounds layer.addSublayer(playerLayer) playerLayer.player?.play() self.playerLayer = playerLayer let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self) notificationCenter.addObserver(self, selector: #selector(LoopingVideoView.videoDidFinish), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.playerLayer.player?.currentItem) } func videoDidFinish() { playerLayer.player?.seek(to: CMTimeMake(0, 600)) playerLayer.player?.play() } class func composedAsset(_ url:URL, count:Int) throws -> AVAsset { let videoAsset = AVURLAsset(url: url, options: nil) let videoRange = CMTimeMake(videoAsset.duration.value, videoAsset.duration.timescale) let range = CMTimeRangeMake(CMTimeMake(0, 600), videoRange) let finalAsset = AVMutableComposition() for _ in 0..<count { try finalAsset.insertTimeRange(range, of: videoAsset, at: finalAsset.duration) } return finalAsset; } class func createPlayerLayer(_ asset:AVAsset) -> AVPlayerLayer { let playerItem = AVPlayerItem(asset: asset) let player = AVPlayer(playerItem: playerItem) let playerLayer = AVPlayerLayer(player: player) playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill return playerLayer; } } <file_sep>// // LoopingVideoView.swift // LoopingVideoView // // Created by <NAME> on 4/11/15. // // import UIKit import AVFoundation @IBDesignable class LoopingVideoView2: UIView { @IBInspectable var mainBundleFileName : NSString? var player1: AVPlayer = AVPlayer() var player2: AVPlayer = AVPlayer() var playerLayer : AVPlayerLayer? override func layoutSubviews() { super.layoutSubviews() if let fileName = mainBundleFileName { let url = Bundle.main.url(forResource: fileName as String, withExtension: nil) if let url = url { play(url) } else { print("LoopingVideoView: Cannot find video \(fileName)") } } } func play(_ url:URL) { player1.pause() player2.pause() let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self) let asset = AVURLAsset(url: url, options: nil) let playerLayer = type(of: self).createPlayerLayer(asset) playerLayer.frame = layer.bounds layer.addSublayer(playerLayer) playerLayer.player?.play() player1 = playerLayer.player! registerForFinishedPlayingNotification(player1) self.playerLayer = playerLayer player2 = type(of: self).createPlayer(asset) registerForFinishedPlayingNotification(player2) player2.play() player2.pause() player2.seek(to: CMTimeMake(0, 600)) } func videoDidFinish() { print("Playing Finished \(playerLayer?.player)") let oldPlayer = playerLayer?.player! oldPlayer?.pause() if oldPlayer == player1 { playerLayer?.player = player2 } else { playerLayer?.player = player1 } print("About to play with \(playerLayer?.player)") playerLayer?.player?.play() oldPlayer?.seek(to: CMTimeMake(0, 600)) } class func createPlayer(_ asset:AVAsset) -> AVPlayer { let playerItem = AVPlayerItem(asset: asset) let player = AVPlayer(playerItem: playerItem) return player; } class func createPlayerLayer(_ asset:AVAsset) -> AVPlayerLayer { let player = createPlayer(asset) let playerLayer = AVPlayerLayer(player: player) playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill return playerLayer; } func registerForFinishedPlayingNotification(_ player:AVPlayer) { let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(LoopingVideoView2.videoDidFinish), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem) } }
9a422e977ebae6a6d61d47773a65c4bdf10d4be5
[ "Markdown", "Swift" ]
3
Markdown
gbarcena/LoopingVideoView
b1206ff54b7ff9b725e433c619233687a4e288f3
053ed7ea8a426d69e140d3a1463fe762782a26d4
refs/heads/master
<repo_name>RickyXux/laychat<file_sep>/application/index/controller/Base.php <?php namespace app\index\controller; use app\index\model\UserModel; use think\Controller; class Base extends Controller { public function _initialize() { //检测token是否存在 $token = request()->header('token'); if (!$token) { exit(json_encode(['code' => 0, 'data' => '', 'msg' => '您尚未登录,请登录!'])); } //判断token是否过期 $us = new UserModel(); $check = $us->check_token($token); if ($check['code']==0) { exit(json_encode($check)); } else { $user_id = $check['data']['user_id']; } //获取控制器和方法 $control = lcfirst(request()->controller()); $action = lcfirst(request()->action()); $method = (request()->method()); $user_info = $us->getUserPower($user_id); if ($user_info['code']==0) { exit(json_encode($user_info['msg'])); } $data = $user_info['data']; $action_user = $data['action']; $method_user = $data['method']; $search = array_search($control.'/'.$action, $action_user); if (!is_numeric($search)||$method!=$method_user[$search]) { exit(json_encode(['code' => 0, 'data' => '', 'msg' => '您没有权限访问!'])); } else { //exit(json_encode(['code' => 0, 'data' => '', 'msg' => '您有权访问!'])); } } } <file_sep>/application/index/controller/Login.php <?php namespace app\index\controller; use app\index\model\UserModel; use Lcobucci\JWT\Builder; use Lcobucci\JWT\Signer\Hmac\Sha256; use think\cache\driver\Memcache; use think\Controller; class Login extends Controller { /** * 用户登录 * * @return \think\response\Json */ public function login() { $user_id = input('post.user_id'); $pwd = input('post.pwd'); $us = new UserModel(); $user = $us->where('id', $user_id)->find(); if (!$user) { return json(['code' => 0, 'data' => '', 'msg' => '用户不存在!']); } else if (md5($pwd)!=$user['password']) { return json(['code' => 0, 'data' => '', 'msg' => '密码不正确!']); } $signer = new Sha256(); $token = (string)(new Builder()) ->setIssuer('admin') //设置jwt签发人 ->setAudience($user_id) //设置jwt接受人 ->set('user_id', $user_id) ->setExpiration(time()+3600) //设置jwt过期时间 ->sign($signer, '123456789') //设置jwt密钥 ->getToken(); //将token放入缓存中 $mem = new Memcache(); $mem->set($token, time()+3600, time()+3600); //缓存1个小时 //更新用户登录信息 $data['loginnum'] = $user['loginnum']+1; $data['last_login_ip'] = request()->ip(); $data['last_login_time'] = time(); $us->save($data, ['id' => $user_id]); // $token = (new Parser())->parse((string) $token); // Parses from a string // echo $token->getClaim('user_id').'<br>'; // will print "1" // echo $token->getClaim('pwd'); return json(['code' => 1, 'data' => ['token' => $token], 'msg' => '登录成功!']); } public function loginout() { $token = request()->header('token'); $mem = new Memcache(); $find = $mem->get($token); if ($find) { $destroy = $mem->rm($token); if ($destroy) { return json(['code' => 1, 'data' => '', 'msg' => '退出成功!']); } else { return json(['code' => 1, 'data' => '', 'msg' => '退出失败!']); } } else { return json(['code' => 1, 'data' => '', 'msg' => '退出成功!']); } } } <file_sep>/application/index/model/UserModel.php <?php namespace app\index\model; use app\index\validate\UserValidate; use Lcobucci\JWT\Parser; use think\cache\driver\Memcache; use think\exception\PDOException; use think\Loader; use think\Model; class UserModel extends Model { protected $table = 'tp5_user'; /** * 根据条件获取用户列表 * * @param $where * @param $offset * @param $limit * @return false|\PDOStatement|string|\think\Collection */ public function getUserBywhere($where, $offset, $limit) { return $this->where($where)->limit($offset, $limit)->select(); } /** * 检测新增用户的用户名和密码是否合法 * * @param $username * @param $pwd * @return array */ public function checkNewuser($username, $pwd) { //检测用户名长度是否合法 $name_len = strlen(trim($username)); if ($name_len<6||$name_len>20) { return ['code' => 0, 'data' => '', 'msg' => '用户名长度必须在6~20位!']; } //判断该用户名是否已存在 $unique = $this->where('username', $username)->find(); if ($unique) { return ['code' => 0, 'data' => '', 'msg' => '该用户名已存在!']; } $pwd_len = strlen($pwd); if ($pwd_len<6) { return ['code' => 0, 'data' => '', 'msg' => '密码长度不得小于6位!']; } return ['code' => 1, 'data' => '', 'msg' => '用户名和密码合法!']; } /** * 更新用户信息 * * @param $param * @return array */ public function updateUser($param) { try{ $update = $this->save($param, ['id' => $param['id']]); if (false===$update) { return ['code' => 0, 'data' => '', 'msg' => $this->getError()]; } else { return ['code' => 1, 'data' => '', 'msg' => '用户修改成功']; } }catch (PDOException $e) { return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()]; } } /** * 新增用户 * * @param $param * @return array */ public function addUser($param) { try{ $validate = $this->validate('UserValidate')->save($param); if (false===$validate) { return ['code' => 0, 'data' => '', 'msg' => $this->getError()]; } else { return ['code' => 1, 'data' => '', 'msg' => '用户添加成功']; } }catch (PDOException $e) { return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()]; } } /** * 获取用户权限 * * @param $id * @return array */ public function getUserPower($id) { $user = $this->where('id', $id)->find(); if (!$user) { return ['code' => 0, 'data' => '', 'msg' => '用户不存在']; } else if ($user['username']==='admin') { //超级管理员拥有所有权限 $map_no = ''; } else { $role_ids = db('user_role')->where('user_id', $id)->column('role_id'); $map_node['role_id'] = array('in', $role_ids); $node_ids = db('role_node')->where($map_node)->column('node_id'); $map_no['id'] = array('in', $node_ids); } $nodes = db('node')->where($map_no)->select(); $action = array(); $method = array(); foreach ($nodes as $key => $vo) { if ('#'!=$vo['action_name']) { $action[] = $vo['control_name'].'/'.$vo['action_name']; switch ($vo['type']) { case 1: $method[] = 'GET'; break; case 2: $method[] = 'POST'; break; case 3: $method[] = 'DELETE'; break; case 4: $method[] = 'PUT'; break; default : $method[] = 'GET'; break; } } } return ['code' => 1, 'data' => ['action' => $action, 'method' => $method], 'msg' => '']; } /** * 检测用户token是否有效 * * @param $token * @return array */ public function check_token($token) { $mem = new Memcache(); $limit_time = $mem->get($token); if (!$limit_time) { return ['code' => 0, 'data' => '', 'msg' => 'token已失效,请重新登录!']; } else { if (($limit_time-time())<=300) { //当token失效时间在当前时间的5分钟内时更新token过期时间 $mem->set($token, time()+3600, time()+3600); } $token = (new Parser())->parse((string) $token); // Parses from a string $user_id = $token->getClaim('user_id'); return ['code' => 1, 'data' => ['user_id' => $user_id], 'msg' => 'token有效']; } /* try { $token = (new Parser())->parse((string) $token); } catch (Exception $exception) { return false; } //验证token是否有效 //$check = new ValidationData(); //$re = $token->validate($check); if ($re) { return ['code' => 1, 'data' => '', 'msg' => 'token值有效']; } else { return ['code' => 0, 'data' => '', 'msg' => 'token值无效!']; } */ } } <file_sep>/application/index/job/MultiTask.php <?php /** * 文件路径: \application\index\job\MultiTask.php * 这是一个消费者类,用于处理 multiTaskJobQueue 队列中的任务 */ namespace application\index\job; use think\queue\Job; class MultiTask { public function taskA(Job $job, $data) { $isJobDone = $this->_doTaskA($data); if ($isJobDone) { $job->delete(); print("Info: TaskA of Job MultiTask has been done and deleted" . "\n"); } else { if ($job->attempts() > 3) { $job->delete(); } } } public function taskB(Job $job, $data) { $isJobDone = $this->_doTaskB($data); if ($isJobDone) { $job->delete(); print("Info: TaskB of Job MultiTask has been done and deleted" . "\n"); } else { if ($job->attempts() > 2) { $job->release(); } } } private function _doTaskA($data) { print("Info: doing TaskA of Job MultiTask " . "\n"); return true; } private function _doTaskB($data) { print("Info: doing TaskB of Job MultiTask " . "\n"); return true; } }<file_sep>/application/index/model/UserRoleModel.php <?php namespace app\index\model; use think\Model; class UserRoleModel extends Model { protected $table = 'tp5_user_role'; /** * 获取用户角色 * * @param $id * @return array */ public function getUserRole($id) { $role_id = $this->where('user_id', $id)->column('role_id'); $role = db('role')->where(['id' => ['in', $role_id]])->column('rolename'); return $role; } } <file_sep>/application/index/validate/UserValidate.php <?php /** * Created by PhpStorm. * User: ricky * Date: 17-3-24 * Time: 上午9:45 */ namespace app\index\validate; use think\Validate; class UserValidate extends Validate { protected $rule = [ 'username' => 'require|unique:user', 'password' =>'<PASSWORD>', ]; protected $message = [ 'username.require' => '用户名必须填写', 'username.unique' => '用户名已存在', 'password.require' => '密码必须填写' ]; protected $scene = [ ]; }<file_sep>/application/index/controller/User.php <?php namespace app\index\controller; use app\index\model\UserModel; use app\index\model\UserRoleModel; use think\Controller; use think\Request; class User extends Base { /** * 获取用户列表 * * @return \think\Response */ public function index() { $return = array(); $limit = input('pageSize'); //每页显示多少条 $pageNumber = (input('pageNumber')>0)? input('pageNumber') : 1; $offset = ($pageNumber-1)*$limit; //开始数 //查询条件 $searchText = input('searchText'); if (isset($searchText) &&!empty($searchText)) { $where['username'] = array('like', '%'.$searchText.'%'); } else { $where = ''; } $us = new UserModel(); $return['total_num'] = $us->where($where)->count(); if ($return['total_num']==0) { return json(['code' => 0, 'data' => '', 'msg' => '暂无数据!']); } $return['total_page'] = ceil($return['total_num']/$limit); $return['list'] = $us->getUserBywhere($where, $offset, $limit); if (count($return['list'])==0) { return json(['code' => 0, 'data' => '', 'msg' => '本页没有请求的数据!']); } if ($return['total_num']-count($return['list'])-($pageNumber-1)*$limit>0) { $return['is_has'] = true; } else { $return['is_has'] = false; } return json(['code' => 1, 'data' => $return, 'msg' => '请求数据成功!']); } /** * 显示创建资源表单页. * * @return \think\Response */ public function create() { // } /** * 保存新建的用户 * * @param \think\Request $request * @return \think\Response */ public function save(Request $request) { $param = input('post.'); $username = $param['username']; $pwd = $param['<PASSWORD>']; $us = new UserModel(); //检测 $check_up = $us->checkNewuser($username, $pwd); if ($check_up['code']==0) { return json($check_up); } $param['password'] = md5($pwd); $add = $us->addUser($param); return json($add); } /** * 显示指定的资源 * * @param int $id * @return \think\Response */ public function read($id) { $us = new UserModel(); $user = $us->where('id', $id)->find(); if (!$user) { return json(['code' => 0, 'data' => '', 'msg' => '用户不存在!']); } $ro = new UserRoleModel(); $role = $ro->getUserRole($id); $user['role_name'] = $role; return json(['code' => 1, 'data' => $user, 'msg' => '获取用户成功!']); } /** * 显示编辑资源表单页. * * @param int $id * @return \think\Response */ public function edit($id) { // } /** * 保存更新的资源 * * @return \think\Response */ public function update($id) { $param = input('put.'); $us = new UserModel(); $param['id'] = $id; //判断用户是否存在 $isset = $us->where('id', $id)->find(); if (!$isset) { return json(['code' => 0, 'data' => '', 'msg' => '用户不存在!']); } $username = trim($param['username']); $pwd = trim($param['password']); if ($username!=$isset['username']) { $check = $us->where('username', $username)->find(); if ($check) { return json(['code' => 0, 'data' => '', 'msg' => '用户名已存在!']); } $name_len = strlen($username); if ($name_len<6||$name_len>20) { return json(['code' => 0, 'data' => '', 'msg' => '用户名长度必须在6~20位!']); } } if (!empty($pwd)) { if (strlen($pwd)<6) { return json(['code' => 0, 'data' => '', 'msg' => '密码不得小于6位!']); } $param['password'] = md5($pwd); } else { unset($param['password']); } //更新用户信息 $update = $us->updateUser($param); return json($update); } /** * 删除指定资源 * * @param int $id * @return \think\Response */ public function delete($id) { $us = new UserModel(); $isset = $us->where('id', $id)->find(); if (!$isset) { return json(['code' => 0, 'data' => '', 'msg' => '删除的用户不存在!']); } $delete = $us->where('id', $id)->delete(); if ($delete) { return json(['code' => 1, 'data' => '', 'msg' => '用户删除成功!']); } else { return json(['code' => 0, 'data' => '', 'msg' => '用户删除失败!']); } } } <file_sep>/application/index/controller/Worker.php <?php /** * Created by PhpStorm. * User: ricky * Date: 17-3-24 * Time: 下午3:47 */ namespace app\index\controller; use think\worker\Server; use Workerman\Lib\Timer; class Worker extends Server { protected $socket = 'websocket://www.tp5.com:2346'; protected $processes = 1; protected $uidConnections = array(); /** * 收到信息 * @param $connection * @param $data */ public function onMessage($connection, $data) { //判断当前客户端是否已经验证,即是否设置啦uid if (!isset($connection->uid)) { //没有验证的话把第一个包当作uid $connection->uid = $data; /** * 保存uid到connection的映射,这样科研方便的通过uid 查找connection * 实现对特定uid推送数据 */ $this->uidConnections[$connection->uid] = $connection; return ; } } /** * 当连接建立时触发的回调函数 * @param $connection */ public function onConnect($connection) { echo "new connection from ip ".$connection->getRemoteIp()."\n"; } /** * 当连接断开时触发的回调函数 * @param $connection */ public function onClose($connection) { global $this; if (isset($connection->uid)) { //连接断开是删除映射 unset($this->uidConnections[$connection->uid]); } } /** * 当客户端的连接上发生错误时触发 * @param $connection * @param $code * @param $msg */ public function onError($connection, $code, $msg) { echo "error $code $msg\n"; } /** * 每个进程启动 * @param $worker */ public function onWorkerStart($worker) { /* $timer = new Timer(); $timer->add(10, function ()use($worker){ //遍历当前进程所有的客户的连接,发送但前服务器时间 foreach($worker->connections as $connection) { $connection->send(time()); } }); */ //开启一个内部断开,方便内部系统推送数据,Text协议格式,文本+换行符 $inner_text_worder = new \Workerman\Worker('text://www.tp5.com:5678'); $inner_text_worder->onMessage = function ($connection, $buffer) { echo 'hhh'; //$data数组格式,里面有uid,表示向那个uid的页面推送数据 $data = json_decode($buffer, true); $uid = $data['uid']; //通过workerman向uid的页面推送数据 $ret = $this->sendMessageByUid($uid, $buffer); //返回推送结果 $connection->send($ret? 'ok' : 'fail'); }; //执行监听 $inner_text_worder->listen(); } /** * 连接的应用层发送缓冲区数据全部发送完毕时触发 * * @param $worker */ public function onBufferFull($worker) { } /** * * @param $worker */ public function onWorkerReload($worker) { foreach ($worker->connections as $connection) { $connection->send('worker reloading'); } } //向所有验证的用户推送数据 function broadcast($message) { foreach ($this->uidConnections as $connection) { $connection->send($message); } } //针对uid推送数据 function sendMessageByUid($uid, $message) { if (isset($this->uidConnections[$uid])) { $connection = $this->uidConnections[$uid]; $connection->send($message); return true; } return false; } }<file_sep>/public/server.php <?php /** * Created by PhpStorm. * User: ricky * Date: 17-3-24 * Time: 下午3:45 */ define('APP_PATH', __DIR__ . '/../application/'); define('BIND_MODULE','index/Worker'); // 加载框架引导文件 require __DIR__ . '/../thinkphp/start.php';<file_sep>/application/extra/queue.php <?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: yunwuxin <<EMAIL>> // +---------------------------------------------------------------------- return [ 'connector' => 'Redis', //Redis驱动 'expire' => 60, //任务过期时间,默认为60秒, 'default' => 'default', //默认的队列名称 'host' => '127.0.0.1', //reids 主机ip 'port' => 6379, //reids端口 'password' => '', //<PASSWORD>密码 'select' => 0, //使用哪一个db,默认为db0 'timeout' => 0, //redis链接的超时时间 'persistent' => false, //是否是长连接 ]; <file_sep>/public/index.php <?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <<EMAIL>> // +---------------------------------------------------------------------- //$re = new Redis(); //$res = $re->connect('127.0.0.1', 6379); //var_dump($res);exit; /* $sessionpath = session_save_path(); if (strpos ($sessionpath, ";") !== FALSE) $sessionpath = substr ($sessionpath, strpos ($sessionpath, ";")+1); //获取当前session的保存路径 echo 'session的保存路径:'.$sessionpath.'<br>'; //测试session读取是否正常 session_start(); var_dump($_SESSION); $_SESSION['username'] = "xuxiang"; echo 'session_id:'.session_id().'<br>'; //从Memcache中读取session $m = new Memcache(); $m->connect('127.0.0.1', 11211); $session = $m->get(session_id()); echo 'memcache中的数据:'.$session."<br/>"; //echo $_SESSION['password'].'<br>'; // //$delete = $m->delete(session_id()); //echo $delete; // //var_dump($m->get(session_id())); // // //echo 'session_id:'.session_id()."<br/>"; exit; */ // [ 应用入口文件 ] // 定义应用目录 define('APP_PATH', __DIR__ . '/../application/'); // 加载框架引导文 require __DIR__ . '/../thinkphp/start.php'; <file_sep>/application/index/controller/Hello.php <?php namespace app\index\controller; use think\Controller; use think\queue\Job; use think\Request; class Hello { public function fire(Job $job, $data) { db('test')->insert(['create_at' => date('Y-m-d H:i:s')]); db('tp5_test')->insert(['create_at' => date('Y-m-d H:i:s')]); $isJobDone = $this->doHelloJob($data); if ($isJobDone) { //执行成功 $job->delete(); print("<info>Hello Job has been done and deleted"."</info>\n"); } else { if ($job->attempts()>3) { //通过这个方法可以检查任务已经重复试了几次 print("<warn>Hello Job has been retried more than 3 times!"."</warn>\n"); $job->delete(); } } } /** * 根据消息中的数据进行实际的业务处理 * * @param $data   发布任务时自定义的数据 * @return bool   任务执行的结果 */ private function doHelloJob($data) { print("<info>Hello Job Started. job Data is: ".var_export($data,true)."</info> \n"); print("<info>Hello Job is Fired at " . date('Y-m-d H:i:s') ."</info> \n"); print("<info>Hello Job is Done!"."</info> \n"); return true; } public function failed($data) { echo '任务失败啦'; } }
56d83eb271be58e5ee0ef0fe0882fb43852421e5
[ "PHP" ]
12
PHP
RickyXux/laychat
593964d3a4ca869db24348463d4905910c140178
28d67cecfd61a28af304649e0084011dc5d46400
refs/heads/master
<repo_name>Jbx81/music-library-viz<file_sep>/src/components/BarChart.js import React, { Component } from 'react'; import * as d3 from 'd3'; import { albums } from '../data.json'; const w = 900; const h = 500; export default class BarChart extends Component { constructor() { super(); this.state = { albums: albums.sort((a, b) => { if (a.year < b.year) return -1; if (a.year > b.year) return 1; else return 0; }), }; } componentDidMount() { this.drawChart(); } render() { console.log(albums); return <div />; } drawChart() { function customYAxis(g) { g.call(yAxis); g.select('.domain').remove(); g.selectAll('.tick:not(:first-of-type) line') .attr('stroke', '#777') .attr('stroke-dasharray', '2,2'); g.selectAll('.tick text') .attr('x', 4) .attr('dy', -4); } function customXAxis(g) { g.call(xAxis); g.select('.domain').remove(); } var x = d3 .scaleTime() .domain([ this.state.albums[0].year, this.state.albums[this.state.albums.length - 1].year, ]) .range([0, w]); var y = d3 .scaleLinear() .domain([0, 100]) .range([h, 0]); var xAxis = d3.axisBottom(x).tickFormat(d3.timeYear); var yAxis = d3.axisRight(y).tickSize(w); // var scale = d3 // .scaleTime() // .domain([ // this.state.albums[0].year, // this.state.albums[this.state.albums.length - 1].year, // ]) // .range([0, w - 100]); // var x_axis = d3.axisBottom().scale(scale); const svg = d3 .select('body') .append('svg') .attr('width', w) .attr('height', h) .style('margin-left', 100) .style('margin-bottom', 100); var g = svg .append('g') .attr('transform', 'translate(' + 20 + ',' + 20 + ')'); g.append('g') // .attr('transform', 'translate(0,' + h + ')') .call(customXAxis); g.append('g').call(customYAxis); // x.domain(d3.extent(albums, d => d.year)); // y.domain([0, d3.max(albums, d => d.freq)]); svg.append('g').call(d3.axisBottom(x)); // svg // .selectAll('rect') // .data(this.state.albums) // .enter() // .append('rect') // .attr('x', (d, i) => i * 20) // .attr('y', (d, i) => h - 7.5 * d.freq) // .attr('width', 15) // .attr('height', (d, i) => d.freq * 7.5) // .attr('fill', 'green'); // svg // .selectAll('text') // .data(this.state.albums) // .enter() // .append('text') // .text(d => d.freq) // .attr('x', (d, i) => i * 20) // .attr('y', (d, i) => h - 7.5 * d.freq - 5); } }
0cc14b727343f162802fcc121f3bb72b1b306f90
[ "JavaScript" ]
1
JavaScript
Jbx81/music-library-viz
9f13e37637bd39b0ad8532932620e5124537665a
686c8f2deb6d3b0dfb8f3c28b12e14de0362e55d
refs/heads/master
<repo_name>ChrisMcCat/TerminalCleaner<file_sep>/src/main/java/com/jjdd8_ism/HelloPrinter.java package com.jjdd8_ism; public class HelloPrinter { private static final String printer = "Hello"; public static void helloPrint(){ System.out.println(printer); } } <file_sep>/src/main/java/com/jjdd8_ism/Main.java package com.jjdd8_ism; public class Main { public static void main(String[] args) { HellPrinter.HellPrinter(); TerminalCleaner.cleanConsole(); HelloPrinter.helloPrint(); } }
7fe6959bbdf253cb524432e115dc9fe48ba2a574
[ "Java" ]
2
Java
ChrisMcCat/TerminalCleaner
964d8822c280ca9f00676f0bc163214134bef0da
e3b1c28cda429a44dd03ed185b23fa7cc607f6cc
refs/heads/main
<file_sep>import React from 'react'; const Footer = () => { return ( <div className="p-3 bg-dark text-white text-center mt-3"> <div className="container"> <div className="row"> <div className="col"> <h3>Copyright &copy; 2020 , Ultimate Vacations</h3> <p>All Rights Reserved</p> </div> </div> </div> </div> ); }; export default Footer; <file_sep>import React from 'react'; const About = () => { return( <div className="about"> <div className="container"> <div className="row"> <div className="col-6 p-25"> <h3>About US</h3> <h1>Welcome to <NAME></h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, dolores enim est facere incidunt soluta totam velit. Inventore, odio omnis.</p> <div className="about__btn"> <a href="" className="btn btn-smart">Read More</a> </div> </div> <div className="col-6"> <div className="about__img"> <img src="https://www.recipetineats.com/wp-content/uploads/2020/05/Pizza-Crust-without-yeast_5-SQ.jpg" alt=""/> </div> </div> </div> </div> </div> ) }; export default About;<file_sep>import React from 'react'; import Image from "../Assest/pizza.jpg"; const Menu = () => { return( <div className = "about"> <div className="container"> <div className="row"> <div className="col-6"> <div className="about__img"> <img src={Image} alt=""/> </div> </div> <div className="col-6 p-25"> <h3>The Pizza Menu</h3> <h1>Chicago This Crust</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, dolores enim est facere incidunt soluta totam velit. Inventore, odio omnis.</p> <div className="about__btn"> <a href="" className="btn btn-smart">Read More</a> </div> </div> </div> </div> </div> ) }; export default Menu;
6042ce8605000a7e2e734c940eb9605fed54a105
[ "JavaScript" ]
3
JavaScript
AroojAzhar/Javascript_Learn
a490ea37d07d0c7dc0c03efa324b7bcd2dfff8b7
9d8d9f09733ccc66b021b2dafa2dcac1aaf63696
refs/heads/master
<repo_name>namikingsoft/cloudfront-sandbox<file_sep>/bin/purge.sh #!/bin/sh -e aws configure set preview.cloudfront true aws cloudfront create-invalidation \ --distribution-id ${CLOUDFRONT_DID} \ --paths '/*' <file_sep>/README.md Sandbox of CloudFront [![CircleCI][circle-badge]][circle-url] ======================================== [circle-badge]: https://circleci.com/gh/namikingsoft/cloudfront-sandbox/tree/master.svg?style=svg [circle-url]: https://circleci.com/gh/namikingsoft/cloudfront-sandbox/tree/master <file_sep>/bin/deploy.sh #!/bin/sh -e aws s3 sync html s3://${S3_BUCKET_NAME} --delete
c6a48d80d88dc40058cd163f877ccd8d0a35ac04
[ "Markdown", "Shell" ]
3
Shell
namikingsoft/cloudfront-sandbox
93893a8aeda048a40b6b07d31642faf3cfa87fe8
775d8805991f7d1e1ed09e77b6bf76dcab9456e8
refs/heads/master
<repo_name>birlax/react-learning<file_sep>/first-react-app/app/src/component/bGrid/js/bGridRow.js import React from 'react'; import ReactDOM from 'react-dom'; import '../css/style.css'; import Cell from './bGridCell.js'; class Row extends React.Component { constructor(props) { super(props); this.state = { }; } renderCell(i,className){ return <Cell value={i} className={className}/>; } renderCells(t,className){ var a = []; for (var i = 1; i <= t; i++) { a.push(this.renderCell(i,className)); } return a; } render() { return ( <div> {this.renderCells(13,"cell column")} </div> ); } } export default Row; <file_sep>/first-react-app/app/src/component/bGrid/app.js var React = require('react'); import Cell from './js/bGridCell.js'; import Row from './js/bGridRow.js'; import Grid from './js/bGrid.js'; import GridViewPort from './js/bGridViewPort.js'; <file_sep>/first-react-app/webpack.config.js module.exports = { entry: [ __dirname + '/app/src/component/bGrid/app.js' ], module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'] }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ] }, output: { path: __dirname + '/target', filename: 'bundle.js' }, devServer: { contentBase: __dirname + '/app/src' } };
feba00d26975928b1101cde49d9060b3e6d43579
[ "JavaScript" ]
3
JavaScript
birlax/react-learning
264938522d31dd7cc4493bfcc03339d701e7a97c
dfdb4644b9e614a24e058e83663f7c70aa06b9aa
refs/heads/master
<repo_name>kemalaraz/Weather-prediction-in-Australia-via-Machine-Learning<file_sep>/tables/Info.md ### File for evalutation tables <file_sep>/README.md # Weather-prediction-in-Australia-via-Machine-Learning This repository focusses on the rain prediction over Australia. The dataset was gathered from Kaggle (https://www.kaggle.com/jsphyg/weather-dataset-rattle-package). <br> The features of the dataset introduced below: <br> <br> **Date:** The date of observation <br> **Location:** The common name of the location of the weather station <br> **MinTemp:** The minimum temperature in degrees celsius <br> **MaxTemp:** The maximum temperature in degrees celsius <br> **Rainfall:** The amount of rainfall recorded for the day in mm <br> **Evaporation:** The so-called Class A pan evaporation (mm) in the 24 hours to 9am <br> **Sunshine:** The number of hours of bright sunshine in the day <br> **WindGustDir:** The direction of the strongest wind gust in the 24 hours to midnight <br> **WindGustSpeed:** The speed (km/h) of the strongest wind gust in the 24 hours to midnight <br> **WindDir9am:** Direction of the wind at 9am <br> **WindDir3pm:** Direction of the wind at 3pm <br> **WindSpeed9am:** Wind speed (km/hr) averaged over 10 minutes prior to 9am <br> **WindSpeed3pm:** Wind speed (km/hr) averaged over 10 minutes prior to 3pm <br> **Humidity9am:** Humidity (percent) at 9am <br> **Humidity3pm:** Humidity (percent) at 3pm <br> **Pressure9am:** Atmospheric pressure (hpa) reduced to mean sea level at 9am <br> **Pressure3pm:** Atmospheric pressure (hpa) reduced to mean sea level at 3pm <br> **Cloud9am:** Fraction of sky obscured by cloud at 9am. This is measured in "oktas", which are a unit of eigths. It records how many eigths of the sky are obscured by cloud. A 0 measure indicates completely clear sky whilst an 8 indicates that it is completely overcast <br> **Cloud3pm:** Fraction of sky obscured by cloud (in "oktas": eighths) at 3pm. See Cload9am for a description of the values <br> **Temp9am:** Temperature (degrees C) at 9am <br> **Temp3pm:** Temperature (degrees C) at 3pm <br> **RainTodayBoolean:** 1 if precipitation (mm) in the 24 hours to 9am exceeds 1mm, otherwise 0 <br> **RISK_MM:** The amount of next day rain in mm. Used to create response variable RainTomorrow. A kind of measure of the "risk" <br> **RainTomorrow:** The target variable. Did it rain tomorrow? <br> <br> Most of the kernels made for this dataset introduced bias into their model since they used whole dataset for scaling, imputation of missing values etc. and they included RISK_MM into their model which is a feature for creating the target variable. It has the information of the amount of rain of the next day so if it is some value other than zero it means it will rain tomorrow. So if that feature included in to the model there is no point of rain prediction for the next day. The aspect of multicollinearity studied which also misread in some kernels. Being a classification problem, this work is going to tackle this problem with KNN, Decision Trees, Random Forest and Logistic Regression, and at the end compare their results. As an evaluation method, instead of accuracy, as it was also discussed in the discussions F1_Score can be a good evaluation method to evaluate the models however it is hard to explain that is why balanced accuracy used as an evaluation metric to see the arithmetic mean of sensitivity (true positive rate) and specificity (true negative rate).If classifier does well on both class this metric will be close to the conventional accuracy score however if it does well on one class and does bad in another class it will be much lower than the conventional accuracy metric. Since all the models used accuracy it is also going to be calculated to compare the model with other kernels, but balanced accuracy of the models is going to be used to compare this work’s models. To summarize, for having least possible bias in the model, the plan is to deal with multicollinearity and missing values carefully (impute them rather than deleting the whole column), dividing the dataset into training and testing at the right moment, are some fruitful avenues to pursue. <br> ## Data Understanding ### Data Exploration For data exploration part descriptive statistics were listed to see each attribute's counts, means, standard deviations, min values, max values and percentiles. Then balance for the target RainTomorrow values were checked. 22.42% of the dataset has “Yes” and 77.58% of them has “No”. That balance will be checked again after handling the missing values. After checking the target balance, for the numerical attributes, histograms and probability plots were created to see if they normally distributed or not. From those, it can be seen that some of the distribution does not conform exactly to a normal distribution. Humidity9am, Sunshine are negatively skewed and Evaporation, Rainfall, WindGustSpeed, WindSpeed9am and WindSpeed3pm are positively skewed. After checking distributions, the linear relationship between the attributes were checked with correlation. 0.85 was selected for the threshold and heatmap created for the pairwise correlations. Highly correlated attributes (-0.85 > threshold > 0.85) are Temp3pm and MaxTemp: 0.98, Pressure9am and Pressure3pm: 0.96, Temp9am and MinTemp: 0.9, Temp9am and MaxTemp: 0.89, Temp9am and Temp3pm: 0.86. Those highly correlated attributes will be removed in the data preparation part.<br> ### Data Quality For identifying missing values, each attribute's null percentages were counted. ~48% of the Sunshine values, ~43% of the Evaporation values, ~40% of the Cloud3pm values, ~38% of the Cloud9pm values are missing. <br> ## Data Preparation <br> ### Splitting dataset and excluding target The dataset divided into training and testing datasets 65%and 35% respectively before making any decisions on the preparation section. This is done before the preparation process because doing the decisions about pre-processing on whole data introduces bias to the model. <br> ### Dimensionality reduction (Removing correlated attributes) As mentioned before in the data exploration part, highly correlated attributes were removed. After identifying two highly correlated attributes (Temp3pm – MaxTemp: 0.98), average of their correlation with other attributes were calculated and MaxTemp (attribute with the highest average correlation (MaxTemp average correlation with other attributes: 0.148, Temp3pm average correlation with other attributes: 0.141)) was removed. This process was repeated until there was no correlation remain higher than threshold. After removing MaxTemp, Pressure3pm, MinTemp and Temp9am removed respectively. <br> ### Missing Data Handling Missing values dealt in R programming language since R contains more packages for dealing with missing values. First, the percentage of the missing values shown because even if the attributes with less than 5% missing values are not missing completely at random (MCAR), listwise deletion can be used to delete them (Shafer,1999).Attributes Temp3pm, Rainfall, WindSpeed9am, WindSpeed3pm, Humidity9am and Humidity3pm had less than 5% missing values and their missing values deleted without the need for analyzing MCAR or not. Then for attributes that has more than 5% MCAR test conducted. First, the intention was using Little’s MCAR (Little, 1988) test however, it is computationally expensive and too sensitive for large datasets (Li, 2014), that is why analyzing the graphs gave sufficient information. There is no evidence found that, attributes Cloud3pm, Cloud9am, WindGustSpeed, Pressure9am, Evaporation and Sunshine are not MCAR. Since those attributes have MCAR characteristics MCAR listwise deletion can be used without having the concern of having a biased effect or incorrect variances (Little, 1988) however, one study showed that listwise deletion leads to a decrease in statistical power if more than %10 of data is missing (Raaijmakers, 1999). So listwise deletion applied only Cloud3pm and Cloud9am attributes, others had much more missing values than 10% so another method is needed. Imputation models that can deal with MCAR can easily be implemented for WindGustSpeed, Pressure9am, Evaporation and Sunshine. To deal with missing values of those attributes, bagging ensemble algorithm imputation method chosen because it can deal with both categorical and numerical values also it doesn't need scaling which is going to be the next part in the process. <br> ### Converting categorical attributes into binary The target variable (RainTomorrow) and RainToday variables values are coded as Yes and No. They are changed to 1 and 0 respectively. Since WindGustDir, WindDir9am and WindDir3pm are categorical variables they were encoded to dummy variables. Location had more than 30 distinct categories so in order not to have a lot of columns which will result in a computationally expensive model, they were recoded with label encoding. After converting all variables, feature space increased from 19 to 62. <br> ### Scaling The dataset scaled with z-score. It seems an easy process however if the scaling is done before splitting the model or calculated for both training and test and apply them separately this process may end up leaking information to the model. That is why scaling is calculated on training set and those constants then applied to training and testing sets respectively. <br> ### Oversampling As mentioned in the data understanding part this dataset is highly imbalanced (77.58%-Yes and 22.42%-No). In order to balance it, it is decided to use oversampling because under sampling results in reducing the instances and also it might not take some distinct instances in the under sampled set which may affect the results poorly. There are more than one over sampling techniques present however not all are efficient sampling techniques. This project uses SMOTE as oversampling technique because it introduces new synthetic samples rather than randomly choosing existing samples and increasing their occurrence (Weiss et al., 2007). Regular oversampling techniques tend to overfit since they may learn some specific examples too well, which will result in memorization rather than generalization. SMOTE learns the topological properties of the minority class and creates new classes not same as the originals but similar so it reduces the chance of overfitting. After oversampling dataset instances increased from 77688 to 121398. <br> ## Modelling Since our problem is classification random forest, adaboost, logistic regression and support vector classifier selected as model to do the classification. To fine tune the hyperparameters grid search is used however for SVC even training the model took 2 hours so grid search isn’t used for SVC model, in addition to that to select best features first feature importance examined for random forest and sorted from best to worst. Then, a loop created which tests the model with feature set that started with 1 and increased one by one. <br> ### Random Forest The random forest instance created then for fine tuning grid search used. Grid search model tried 3 different number of trees (50,100,200) with tree depth ranging from 10 to 40. Since this project focuses on balanced accuracy rather than conventional accuracy for grid search the scoring method chosen as balanced accuracy. Lastly, 5-fold cross validation used in order to test the results. Then the model applied to the test set and the balanced accuracy and conventional accuracy found 78.59% and 82.79% respectively and the best hyperparameters for that model was, number of trees=200, max tree depth=15. Then the features sorted according to their importance to prepare a list for feature selection. After that, a for loop is generated to analyse with how many features(from high important to low) the model performs better, and the model gave best results with 53 features leaving 9 out, the graph shown on the right. The results after that operation changed. Test results for balanced accuracy and conventional accuracy increased to 79.07%±0.4 and 84.06%±0.4 respectively with 95% confidence interval. <br> ### Adaboost Two adaboost models created and compared with each other. First model used grid search for tuning the hyperparameters and it used 4 different number of estimations (50,100,200,300) with 3 learning rate options (0.5,1,1.5). Scoring chosen as balanced accuracy; 5-fold cross validation used for training process of grid search. Test results for balanced accuracy and conventional accuracy, 74.96%±0.7 and 84.98%±0.7 respectively with 95% confidence interval. The best parameters was number of estimations=300, learning rate=1.5. In the first model base tree kept as default (DT with max depth=1) but in the second model it changed to random forest with max depth=10 and number of estimators=50 which was proven to give test results (balanced accuracy=78.50% – accuracy=81.50%) similar to the random forest that built before adaboost. Second model haven’t used any model for hyperparamter tuning to save computational time (same gridsearch model applied and after 5 hours it was still runing). The second models balanced accuracy and accuracy results were 76%±0.1 and 86.47%±0.1 respectively with 95% confidence interval. <br> ### Logistic Regression Logistic model created also with grid search to fine tune the hyperparameters of logistic regression. According to the sklearn documentation saga is often the best solver and saga’s capabilities of handling large datasets are the reasons why saga chosen as a solver method. Both lasso and ridge regression regularizations(l1,l2) chosen for grid search with both 0.5 and 1.5 learning rates, max iteration kept as default at first, but the model gave a warning about converging (not converged), so iterations set to 500. Again 5-fold cross validation chosen, and the model is trained with hyperparameters defined above. Test results for balanced accuracy and conventional accuracy were 79.56%±0.1 and 80.32%±0.1 respectively with %95 confidence interval. The best hyperparameters for the model were penalty=l2 and learning rate=1.5. <br> ### SVC Support Vector Classifier built with no hyperparameter tuning to save computational time because only for training svc model took 3 hours 12 minutes. As kernel polynomial chosen to speed up the process since with rbf after 4 hours there was no results. To have 1 / (n_features * X.var()) as gamma scale version of gamma chosen and the model trained. Test results for balanced accuracy and conventional accuracy were 72.88% and 82.45% respectively. <br> ## Evaluation Models trained and tested. All the models have higher accuracy then balanced accuracy. This happened because the models seem to predict one class more accurate than the other. To see which class is favored by the models recall and specificity calculated. It is certain that, sunny days tend to be predicted more accurate than rainy days even with oversampled training data. It seems that when balanced accuracy and conventional accuracy gets closer models equal prediction capacity increases. Since it was one of the fruitful avenues our model is based on, this project has an aim that is better to predict rainy and have sun as a surprise rather than other way around. Although having the highest conventional accuracy, Adaboost-2 model acted poorly on predicting the rainy days. It predicted sunny days with outstanding 94.7% accuracy but when it comes to predict rainy days it only reached 56.6% worst or all models, which is slightly better than flip a coin before going out to decide whether to take an umbrella or not. The model that has highest balanced accuracy also has the highest accuracy on predicting rainy days with a 77.8% accuracy (Specificity), which is logistic regression. When all things taken into consideration for this dataset logistic regression seems to be the best model for this projects cause. It is also useful to inform that, however when all the kernels considered and the overfitted and biased ones excluded Adaboost-2 has the best accuracy score among all kernels. <br> ![](tables/Eval1.JPG) <br> ![](tables/Eval2.JPG) <br> ### REFERENCES Little’s Test of Missing Completely at Random li, 2014 <br><br> Effectiveness of Different Missing Data Treatments in Surveys with Likert-Type Data: Introducing the Relative Mean Substitution Approach, Raaijmakers,1999 Weiss, <NAME>., <NAME>, and <NAME>. "Cost-sensitive learning vs. sampling: Which is best for handling unbalanced classes with unequal error costs?." DMIN 7 (2007): 35-41. <br><br> <NAME>. (1988). A Test of Missing Completely at Random for Multivariate Data with Missing Values. Journal of the American Statistical Association, 83(404), 1198-1202. doi:10.2307/2290157 <br><br> <NAME>L. Multiple imputation: a primer. Stat Methods Med Res. 1999;8:3–15 <br><br> <file_sep>/missing_val_imp.R #####REQUIRED LIBRARIES##### install.packages("VIM") install.packages("caret") install.packages("RANN") library(caret) library(VIM) library(RANN) #####READ TRAIN AND TEST DATASET##### df_train <- read.csv("rain_to_R_train.csv", sep=",", strip.white = TRUE) df_test <- read.csv("rain_to_R_test.csv", sep=",", strip.white = TRUE) df_train <- df_train[,-1] #To drop the index column df_test <- df_test[,-1] #to drop the index column #####PERCENTAGE OF NA##### # To see which attribute has how many missing values in percentage, nans dataframe created nans=as.data.frame(matrix(ncol = 1, nrow = 19), stringsAsFactors = F) for (i in 1:length(df_train)) { nans[i,1] <- sum(is.na(df_train[,i]))/length(df_train[,i]) } colnames(nans) <- "Percentage of NA" # Assigning a column name rownames(nans) <- colnames(df_train) # Assigning row names nans <- nans[order(nans),,drop=F] #Sorted nans #####LISTWISE DELETION OF SOME ATTRIBUTES NA VALUES##### # Since a lot of the attributes has less than %5 of NA values listwise deletion can be used to delete them(Shafer, 1999). na <- nans[which(nans<=0.05 & nans>0),,drop=F] # Attributes that have less than %5 and more than 0 missing values df_train_complete <- df_train[complete.cases(df_train[,c("Temp3pm","Rainfall","WindSpeed9am","WindSpeed3pm","Humidity9am","Humidity3pm")]),] df_train_complete # Missing values of the attributes which has less than %5 missing values, listwise deleted # To check if those attributes still contain missing values or not - nans_complete dataframe created nans_complete=as.data.frame(matrix(ncol = 1, nrow = 19), stringsAsFactors = F) for (i in 1:length(df_train_complete)) { nans_complete[i,1] <- sum(is.na(df_train_complete[,i]))/length(df_train_complete[,i]) } colnames(nans_complete) <- "Percentage of NA" # Assigning a column name rownames(nans_complete) <- colnames(df_train) # Assigning row names nans_complete <- nans_complete[order(nans_complete),,drop=F] #Sorted nans_complete #####MCAR(mising completely at random) CHECK##### #For attributes which still has missing values, graphs created and analyzed below # Continuous attribtues compared with continuous attributes # WindGustSpeed marginplot(df_train_complete[c("WindGustSpeed","Pressure9am")]) marginplot(df_train_complete[c("WindGustSpeed","Evaporation")]) marginplot(df_train_complete[c("WindGustSpeed","Sunshine")]) # It seems WindGustSpeed might be MCAR pbox(df_train_complete,pos=7) # It seems our first opposition is true and WindGustSpeed is MCAR marginplot(df_train_complete[c("Pressure9am","Evaporation")]) marginplot(df_train_complete[c("Pressure9am","Sunshine")]) # It seems Pressure9am might be MCAR pbox(df_train_complete,pos=14) # It seems our first opposition is true and Pressure9am is MCAR marginplot(df_train_complete[c("Evaporation","Sunshine")]) # It seems that Evaporation might be MCAR pbox(df_train_complete,pos=4) # It seems our first opposition is true and Evaporation is MCAR pbox(df_train_complete,pos=5) # Sunshine also seems MCAR # Categorical attribtues compared with categorical attributes marginplot(df_train_complete[c("Cloud3pm","Cloud9am")]) # It seems Cloud9am MCAR but Cloud3pm may be MAR pbox(df_train_complete,pos=15) # It seems our first opposition is true and Cloud9am is MCAR pbox(df_train_complete,pos=16) # It seems our first opposition may be wrong because those instances with missing information for other attributes are not much higher or lower than those of the non-missing instances. # Only differences occured are the comparision with attributes also has missing values and even those differences are not much. # One study showed that listwise # deletion leads to a decrease in statistical power # if more than 10% of the data is missing(Raaijmakers, 1999). # Since WindGustSpeed and Pressure9am is MCAR and missing values are less then %10, listwise deletion is possible. df_train_complete <- df_train_complete[complete.cases(df_train_complete[,c("Pressure9am","WindGustSpeed")]),] #####IMPUTATION##### # Since all the attributes' missing values are MCAR there is no need to dig more and imputation models that can deal with MCAR can easily be implemented # For this dataset bagging ensemble algoritm imputation method chosen because it can deal with both categorical and numerical values also it doesn't need scaling which is going to be the next part in the process. # Since this data is not completely time series data but has some temporal aspects in it and also imputation of Cloud9am, Cloud3pm, Evaporation and Sunshine doesn't need Location and Date attribute to be imputed # they are removed before the imputation process. date_loc <- df_train_complete[,c(1,2)] df_train_complete <- df_train_complete[,-c(1,2)] # Train the imputer df_train_imp <- preProcess(df_train_complete, method = "bagImpute", lev=NULL) # Apply the imputer to the training dataset df_train_imputed <- predict(df_train_imp, newdata = df_train_complete) # To check training dataset if those attributes still contain missing values or not nans_train_imp dataframe created nans_train_imp=as.data.frame(matrix(ncol = 1, nrow = 17), stringsAsFactors = F) for (i in 1:length(df_train_imputed)) { nans_train_imp[i,1] <- sum(is.na(df_train_imputed[,i]))/length(df_train_imputed[,i]) } colnames(nans_train_imp) <- "Percentage of NA" # Assigning a column name rownames(nans_train_imp) <- colnames(df_train_complete) # Assigning row names nans_train_imp <- nans_train_imp[order(nans_train_imp),,drop=F] #Sorted nans_train_imp # Apply listwise deletion (as decided on training dataset) and bagging imputation to test dataset df_test_complete <- df_test[complete.cases(df_test[,c("Temp3pm","Rainfall","WindSpeed9am","WindSpeed3pm","Humidity9am","Humidity3pm","Pressure9am","WindGustSpeed")]),] df_test_imputed <- predict(df_train_imp, newdata = df_test_complete) # To check test dataset if those attributes still contain missing values or not nans_test_imp dataframe created nans_test_imp=as.data.frame(matrix(ncol = 1, nrow = 18), stringsAsFactors = F) for (i in 1:length(df_test_imputed)) { nans_test_imp[i,1] <- sum(is.na(df_test_imputed[,i]))/length(df_test_imputed[,i]) } colnames(nans_test_imp) <- "Percentage of NA" # Assigning a column name rownames(nans_test_imp) <- colnames(df_train) # Assigning row names nans_test_imp <- nans_test_imp[order(nans_test_imp),,drop=F] #Sorted nans_test_imp #####BEFORE AND AFTER IMPUTATION##### summary(df_train_complete) summary(df_train_imputed) summary(df_test_complete) summary(df_test_imputed) #####WRITE RESULTS TO CSV##### df_train_imputed <- cbind(date_loc,df_train_imputed) write.csv(df_train_imputed, file = "rain_from_R_train.csv") write.csv(df_test_imputed, file = "rain_from_R_test.csv") <file_sep>/main_code.py # -*- coding: utf-8 -*- """ Created on Fri Apr 26 03:27:21 2019 @author: kemal """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns; sns.set() #set plot style import missingno as msno #for displaying missing values import scipy.stats as stats #for plotting normality from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn import metrics import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV from sklearn.model_selection import RandomizedSearchCV from sklearn.linear_model import LogisticRegression from imblearn.over_sampling import SMOTE # Importing data rain_data = pd.read_csv("C:\\Users\\kemal\\OneDrive\\Masaüstü\\Data Analytics MSc\\Spec 9270 - Machine Learning\\Assignments\\Task 1\\Rain Prediction\\weatherAUS.csv", engine="python") # Exclude RISK_MM because it leakes information to the model rain_data = rain_data.drop(columns="RISK_MM") #####DATA UNDERSTANDING##### # Descriptive statistics rain_data.describe() rain_data.info() #summary # Yes,No counts for the target (to see if the target variable is imbalanced or not) sns.countplot(rain_data["RainTomorrow"]) # target variable is infact imbalanced, it is going to be taken care of in the preperation section yes=np.count_nonzero(rain_data["RainTomorrow"]=="Yes")*100/len(rain_data) no=np.count_nonzero(rain_data["RainTomorrow"]=="No")*100/len(rain_data) # Noramlity check numeric_cols=rain_data.drop(columns=["Date","Location","WindGustDir","WindDir9am","WindDir3pm","RainToday","RainTomorrow"]) numeric_cols.hist(bins=50, figsize=(25,20)) cols = numeric_cols.columns k = 0 plt.figure("normality") for i in range(2): for j in range(7): ax = plt.subplot2grid((2,7), (i,j)) stats.probplot(numeric_cols[cols[k]], plot=plt) ax.set_title(cols[k]) k = k+1 plt.subplots_adjust(hspace=0.95) plt.show() # Visualisation for categorical attributes sns.countplot(rain_data["WindGustDir"]) sns.countplot(rain_data["WindDir9am"]) sns.countplot(rain_data["WindDir3pm"]) sns.countplot(rain_data["RainToday"]) # Correlation Matrix (to see whether multicollinearity exists in the dataset) corr_rain = rain_data.corr() # Some variables are highly correlated with eachother, it is going to be taken care of in the preperation section sns.heatmap(corr_rain,annot=True,linewidths=0.25) # Exploring missing values null_counts = rain_data.isnull().sum() perc_null = 100*null_counts/len(rain_data) msno.bar(rain_data) #####DATA PREPERATION##### ## Split dataset - Dividing the dataset into training and test dataset X=rain_data.iloc[:,0:22] # predictors y=rain_data.iloc[:,22:23] # target variable X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.35,random_state=5) ## Dimensionality reduction - removing correlated attributes #Correlation matrix corr_rain = X_train.corr() sns.heatmap(corr_rain,annot=True,linewidths=0.25) # Calculating average correlation for highly correlated attributes avg_temp3pm= sum(corr_rain["Temp3pm"])/len(corr_rain) avg_maxtemp = sum(corr_rain["MaxTemp"])/len(corr_rain) # MaxTemp has higher average correlation avg_pressure9am = sum(corr_rain["Pressure9am"])/len(corr_rain) avg_pressure3pm = sum(corr_rain["Pressure3pm"])/len(corr_rain) # Pressure3pm has higher average correlation avg_temp9am= sum(corr_rain["Temp9am"])/len(corr_rain) avg_mintemp= sum(corr_rain["MinTemp"])/len(corr_rain) # MinTemp has higher average correlation avg_temp9am= sum(corr_rain["Temp9am"])/len(corr_rain) avg_temp3pm= sum(corr_rain["Temp3pm"])/len(corr_rain) # Temp9am has higher average correlation # Remove one of the two highly correlated atrribute which has highest average correlation with other attribute X_train=X_train.drop(columns=["MaxTemp","Pressure3pm","MinTemp","Temp9am"]) X_test=X_test.drop(columns=["MaxTemp","Pressure3pm","MinTemp","Temp9am"]) corr_rain = X_train.corr() sns.heatmap(corr_rain,annot=True,linewidths=0.25) ## Handling missing values # Concatenate predictors with target variable - Send them to R for handling missing values rain_to_R_train=pd.concat([X_train,y_train],axis=1,sort=False) rain_to_R_test=pd.concat([X_test,y_test],axis=1,sort=False) rain_to_R_train.to_csv("C:\\Users\\kemal\\OneDrive\\Masaüstü\\Data Analytics MSc\\Spec 9270 - Machine Learning\\Assignments\\Task 1\\Rain Prediction\\rain_to_R_train.csv") rain_to_R_test.to_csv("C:\\Users\\kemal\\OneDrive\\Masaüstü\\Data Analytics MSc\\Spec 9270 - Machine Learning\\Assignments\\Task 1\\Rain Prediction\\rain_to_R_test.csv") ## Read train and test data from R after imputations train_R = pd.read_csv("C:\\Users\\kemal\\OneDrive\\Masaüstü\\Data Analytics MSc\\Spec 9270 - Machine Learning\\Assignments\\Task 1\\Rain Prediction\\Rain_Prediction_R\\rain_from_R_train.csv", engine="python") test_R = pd.read_csv("C:\\Users\\kemal\\OneDrive\\Masaüstü\\Data Analytics MSc\\Spec 9270 - Machine Learning\\Assignments\\Task 1\\Rain Prediction\\Rain_Prediction_R\\rain_from_R_test.csv", engine="python") train_R=train_R.iloc[:,1:20] # remove unnanmed column test_R=test_R.iloc[:,1:20] # remove unnanmed column train_R = train_R.set_index("Date") # assign date as index in training dataset test_R = test_R.set_index("Date") # assign date as index in testing dataset ## Binarization # Change RainToday and RainTomorrow from Yes/No to 1 and 0 train_R["RainToday"].replace({"No":0,"Yes":1},inplace=True) train_R["RainTomorrow"].replace({"No":0,"Yes":1},inplace=True) test_R["RainToday"].replace({"No":0,"Yes":1},inplace=True) test_R["RainTomorrow"].replace({"No":0,"Yes":1},inplace=True) ## Scaling #Seperate predictors from target X_train=train_R[train_R.columns.difference(["RainTomorrow"])] y_train=train_R.iloc[:,17:18] X_test=test_R[test_R.columns.difference(["RainTomorrow"])] y_test=test_R.iloc[:,17:18] # Seperate the categorical variables categorical_train=X_train[["Location","WindGustDir","WindDir9am","WindDir3pm"]] X_train=X_train.drop(columns=["Location","WindGustDir","WindDir9am","WindDir3pm"]) col_names=X_train.columns categorical_test=X_test[["Location","WindGustDir","WindDir9am","WindDir3pm"]] X_test=X_test.drop(columns=["Location","WindGustDir","WindDir9am","WindDir3pm"]) #Label Encoding for Location label_enc=LabelEncoder() categorical_train["Location"]=label_enc.fit_transform(categorical_train["Location"]) categorical_test["Location"]=label_enc.transform(categorical_test["Location"]) scaler=StandardScaler() X_train=scaler.fit_transform(X_train) X_test=scaler.transform(X_test) #Change categorical variable to dummy variables X_train_dummy=pd.get_dummies(categorical_train) X_test_dummy=pd.get_dummies(categorical_test) # Bind categorical and numerical attributes together X_train=pd.DataFrame(X_train, columns = col_names) X_train=X_train.set_index(train_R.index) X_test=pd.DataFrame(X_test, columns = col_names) X_test=X_test.set_index(test_R.index) X_train=pd.concat([X_train,X_train_dummy],axis=1) X_test=pd.concat([X_test,X_test_dummy],axis=1) col_names_all=X_train.columns ## Oversampling sm = SMOTE(random_state=12, ratio = 1.0) X_train_res, y_train_res = sm.fit_sample(X_train, y_train) # Yes,No counts for the target (to see if the target variable is imbalanced or not) #sns.countplot(y_train_res) # target variable is infact imbalanced, it is going to be taken care of in the preperation section # For convention the names changed back to their original X_train,y_train=X_train_res,y_train_res #####MODELING##### ## Random forest # Train Random Forest model and tune it random_forest=RandomForestClassifier(random_state=5) n_estimators_forest=[50,100,200] max_depth=range(10,40) hyperparameters=dict(n_estimators=n_estimators_forest,max_depth=max_depth) random_search_forest=GridSearchCV(random_forest,hyperparameters,scoring="balanced_accuracy",cv=5) random_search_forest.fit(X_train,y_train) best_rand_model=random_search_forest.best_estimator_ #save best model # Test Random forest model pred_test_forest=random_search_forest.predict(X_test) conf_forest=metrics.confusion_matrix(y_test, pred_test_forest) metrics.balanced_accuracy_score(y_test, pred_test_forest) # Train the model again with best estimators and subset of features forest_fea_imp=random_search_forest.best_estimator_.feature_importances_.T forest_fea_imp=forest_fea_imp[:,np.newaxis] forest_fea_imp=pd.DataFrame(forest_fea_imp.T,columns=col_names_all) #convert numpy to pandas to attach the column names to see which attribute is the most important forest_fea_imp=forest_fea_imp.sort_values(ascending=False,by=[0],axis=1) #scale features according to their importance # Try the Random forest model and fine tune feature set from 1 to all(scaled according to their importance) and select the best feature set train_bal_acc = [] test_bal_acc = [] bal_acc= 0 opt_features=0 for i in range(1,63): col_names_forest_imp=forest_fea_imp.columns[0:i] #Columns that will be used to train the model best_random_forest=RandomForestClassifier(max_depth=15,n_estimators=200,random_state=5) X_train=pd.DataFrame(X_train,columns=col_names_all) #convert X_train back to pandas and add columns to select the best columns best_random_forest.fit(X_train[col_names_forest_imp],y_train) print(i,".training finished") pred_train_best_forest=best_random_forest.predict(X_train[col_names_forest_imp]) train_bal_acc.append(metrics.balanced_accuracy_score(y_train, pred_train_best_forest)) #add the accuracy of ith feature set to train array # Test Random forest model X_test=pd.DataFrame(X_test,columns=col_names_all) #convert X_train back to pandas and add columns to select the best columns pred_test_best_forest=best_random_forest.predict(X_test[col_names_forest_imp]) test_bal_acc.append(metrics.balanced_accuracy_score(y_test, pred_test_best_forest)) #add the accuracy of ith depth to test array if bal_acc<metrics.balanced_accuracy_score(y_test, pred_test_best_forest):# Select most accurate(balanced accuracy) feature set bal_acc=metrics.balanced_accuracy_score(y_test, pred_test_best_forest) opt_features = i # To hold the optimum features # Plotting the balanced accuracy and iterations with different depths iterations = np.array(range(i)) plt.plot(iterations, train_bal_acc) plt.plot(iterations, test_bal_acc) plt.xlabel("Features of Random Forest") plt.ylabel("Balanced Accuracy") plt.legend(["Training Bal_Accuracy","Test Bal_Accuracy"]) # Best model with optimum feature set col_names_forest_imp=forest_fea_imp.columns[0:opt_features] #Columns that will be used to train the model best_random_forest=RandomForestClassifier(max_depth=15,n_estimators=200,random_state=5) X_train=pd.DataFrame(X_train,columns=col_names_all) #convert X_train back to pandas and add columns to select the best columns best_random_forest.fit(X_train[col_names_forest_imp],y_train) pred_train_best_forest=best_random_forest.predict(X_train[col_names_forest_imp]) pred_test_best_forest=best_random_forest.predict(X_test[col_names_forest_imp]) conf_forest=metrics.confusion_matrix(y_test, pred_test_best_forest) metrics.balanced_accuracy_score(y_train, pred_train_best_forest) metrics.balanced_accuracy_score(y_test, pred_test_best_forest) metrics.accuracy_score(y_test, pred_test_best_forest) np.mean(random_search_forest.cv_results_["std_test_score"]) ## AdaBoost #Ada boost with gridsearch (Adaboost-1) random_search_ada=AdaBoostClassifier(random_state=5) n_estimators_ada=[100,200,300] learning_rate=[0.7,1.0,1.5] hyperparameters=dict(n_estimators=n_estimators_ada,learning_rate=learning_rate) random_search_ada=GridSearchCV(random_search_ada,hyperparameters,scoring="balanced_accuracy",cv=5) random_search_ada.fit(X_train,y_train) best_ada_model=random_search_ada.best_estimator_ pred_train_random_ada=random_search_ada.predict(X_train) metrics.balanced_accuracy_score(y_train,pred_train_random_ada) metrics.accuracy_score(y_train,pred_train_random_ada) pred_test_random_ada=random_search_ada.predict(X_test) metrics.balanced_accuracy_score(y_test,pred_test_random_ada) metrics.accuracy_score(y_test,pred_test_random_ada) conf_random_ada=metrics.confusion_matrix(y_test, pred_test_random_ada) np.mean(random_search_ada.cv_results_["std_test_score"]) # Adaboost with Random forest model as base model (Adaboost-2) (this random forest model is one # of the best random forest model(for this data - determined with trial and error) that min the risk of overfitting and max balanced accuracy) ada=AdaBoostClassifier(RandomForestClassifier(max_depth=10,n_estimators=50,n_jobs=-1),random_state=5) ada.fit(X_train,y_train) pred_test_ada=ada.predict(X_test) conf_ada=metrics.confusion_matrix(y_test, pred_test_ada) metrics.balanced_accuracy_score(y_test, pred_test_ada) metrics.accuracy_score(y_test, pred_test_ada) # Test Adaboost model pred_test_ada=random_search_ada.predict(X_test) conf_ada=metrics.confusion_matrix(y_test, pred_test_ada) metrics.balanced_accuracy_score(y_test, pred_test_ada) metrics.accuracy_score(y_test, pred_test_ada) ## Logistic Regression # Logistic Regression model with gridsearch logistic=LogisticRegression(solver="saga",max_iter=500,random_state=5) penalty = ['l1', 'l2'] C = [0.5,1.5] hyperparameters = dict(C=C, penalty=penalty) grid_Search_log = GridSearchCV(logistic, hyperparameters, cv=5, verbose=0) grid_Search_log = LogisticRegression(solver="saga",C=1.5,max_iter=500,random_state=5) grid_Search_log.fit(X_train, y_train) # Test the logistic regression model pred_grid_log_test=grid_Search_log.predict(X_test) metrics.balanced_accuracy_score(y_test,pred_grid_log_test) np.mean(grid_Search_log.cv_results_["std_test_score"]) =metrics.confusion_matrix(y_test, pred_grid_log_test) metrics.balanced_accuracy_score(y_test,pred_grid_log_test) metrics.accuracy_score(y_test,pred_grid_log_test) log_best_est=grid_Search_log.best_estimator_ ## SVC #SVC svc=SVC(kernel="poly",gamma="scale",random_state=5) svc.fit(X_train,y_train) svc_train_pred=svc.predict(X_train) metrics.balanced_accuracy_score(y_train,svc_train_pred) svc_test_pred=svc.predict(X_test) metrics.accuracy_score(y_test,svc_test_pred) metrics.balanced_accuracy_score(y_test,svc_test_pred) conf_svc=metrics.confusion_matrix(y_test, svc_test_pred)
feb8b8934dae933797d5b16180bb500dac919cc6
[ "Markdown", "Python", "R" ]
4
Markdown
kemalaraz/Weather-prediction-in-Australia-via-Machine-Learning
412e190dfa5e702fab2d1114eaf0707bd4b3e066
3df682df772deae448f75a0ef85c122949d64d84
refs/heads/master
<repo_name>ArnoldKrumins/angular2<file_sep>/src/app/models/user.ts /** * Created by arnoldkrumins on 10/12/2015. */ export class user{ public name:string; public age:number; public gender:string; constructor(name:string, age:number,gender:string){ this.name = name; this.age = age; this.gender = gender; } }<file_sep>/src/app/directives/textbox.ts /** * Created by arnoldkrumins on 10/12/15. */ import {user} from './../models/user'; import {Component} from 'angular2/angular2'; @Component({ selector: 'my-textbox', template: `<div> <label>{{ person.name }}</label> <input type="text"/><button (click)="">Press Me</button> </div>` }) export class tbox { public person:user = new user('Arnold',48,'male'); }
e69558f6b6d4c2ca3a3169ef20054fadc21ea68e
[ "TypeScript" ]
2
TypeScript
ArnoldKrumins/angular2
055cef33610c72ad842f95e49163f6a1156f8d7d
0073261aa57d68be91befa6c5324195ca7e786b1
refs/heads/master
<repo_name>Offroadcode/umbraco-backoffice-visualization<file_sep>/BackOfficeVisualiser/resources/doctype.api.resource.js angular.module("umbraco.resources").factory("doctypeApiResource", function ($http) { var doctypeApiResource = {}; doctypeApiResource.getViewModel = function () { return $http.get('/umbraco/backoffice/api/DocTypeVisualiser/GetViewModel').then(function(response) { console.log(response.data); return response.data; }); }; return doctypeApiResource; }); <file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/Models/DocTypeAnalyzerResult.cs using System.Collections.Generic; namespace BackOfficeVisualiser.Models { public class DocTypeAnalyzerResult { public DocTypeAnalyzerResult() { DocumentTypes = new List<DocTypeModel>(); Compositions = new List<CompositionModel>(); } public List<DocTypeModel> DocumentTypes { get; set; } public List<CompositionModel> Compositions { get; set; } } }<file_sep>/CHANGELOG.md # Change Log All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## v1.1.1 ### Added * Added this change log. ### Fixed * Fixed bugs in the links to doctypes. ## v1.0.0<file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/API/DocTypeVisualiserController.cs using System.Web.Http; using BackOfficeVisualiser.Api.Attributes; using BackOfficeVisualiser.Models; using Umbraco.Web.Editors; using Umbraco.Web.WebApi; #pragma warning disable 612,618 #pragma warning restore 612,618 namespace BackOfficeVisualiser.Api { [IsBackOffice] [CamelCaseController] public class DocTypeVisualiserController : UmbracoAuthorizedJsonController { [HttpGet] public DocTypeAnalyzerResult GetViewModel() { var dta = new DocTypeAnalyzer(); return dta.Analyze(); } } }<file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/Models/DocTypeModel.cs using System.Collections.Generic; using Umbraco.Core.Models; namespace BackOfficeVisualiser.Models { public class DocTypeModel { public DocTypeModel() { Compositions = new List<int>(); Properties = new List<int>(); } public string Name { get; set; } public string Alias { get; set; } public int Id { get; set; } public int ParentId { get; set; } public List<int> Compositions { get; set; } public List<int> Properties { get; set; } } }<file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/DocTypeAnalyzer.cs using System.Linq; using BackOfficeVisualiser.Models; using Umbraco.Core; using Umbraco.Core.Models; namespace BackOfficeVisualiser { public class DocTypeAnalyzer { public DocTypeAnalyzerResult Analyze() { var model = new DocTypeAnalyzerResult(); var allDoctypes = ApplicationContext.Current.Services.ContentTypeService.GetAllContentTypes(); foreach (var contentType in allDoctypes) { ProcessContentType(contentType, model); } return model; } private void ProcessContentType(IContentType contentType, DocTypeAnalyzerResult model) { var parentIds = contentType.CompositionIds(); var docTypeModel = new DocTypeModel(); docTypeModel.Compositions = parentIds.ToList(); docTypeModel.Alias = contentType.Alias; docTypeModel.Name = contentType.Name; docTypeModel.Id = contentType.Id; docTypeModel.ParentId = contentType.ParentId; model.DocumentTypes.Add(docTypeModel); } } }<file_sep>/BackOfficeVisualiser/resources/propertytype.api.resource.js angular.module("umbraco.resources").factory("propertypeApiResource", function ($http) { var propertytypeApiResource = {}; propertytypeApiResource.getViewModel = function () { return $http.get('/umbraco/backoffice/api/PropertyTypeVisualiser/GetViewModel').then(function(response) { console.log(response.data); return response.data; }); }; return propertytypeApiResource; }); <file_sep>/BackOfficeVisualiser/controllers/doctype.visualiser.controller.js angular.module("umbraco").controller("DocTypeVisualiser.Controller", function ($scope, $http, notificationsService, doctypeApiResource, d3Resource) { /*--- Consts ---*/ var ALL_CHORDS = 0; var TARGET_ONLY = 1; var ALL_EXCEPT_TARGETS = 2; var TARGET_EXCEPT_SELECTED = 3; var FADED = 0.1; var BRIGHT = 0.7; /*--- Init functions ---*/ $scope.init = function() { $scope.setVariables(); $scope.getData().then(function(){ $scope.createGraph(); $scope.listenForTabClick(); }); }; $scope.getData = function() { return doctypeApiResource.getViewModel().then(function (data) { if (data.documentTypes.length) { var sortedDocs = $scope.sortByCompositions(data.documentTypes); $scope.docTypes = sortedDocs; } return true; }); }; $scope.setVariables = function() { $scope.docTypes = []; $scope.hiddenDocTypes = []; $scope.selectedDocType = { id: -1, name: '', breadcrumb: [], compositions: [] }; $scope.showAll = false; $scope.svg = false; }; /*--- Event Handlers ---*/ // Returns an event handler for fading a given chord group. $scope.onHoverOverChord = function () { return function(g, i) { var si = $scope.getIndexByDocTypeId($scope.selectedDocType.id); $scope.toggleChordVisibility(TARGET_ONLY, BRIGHT, i); $scope.toggleChordVisibility(ALL_EXCEPT_TARGETS, FADED, i, si); }; }; $scope.onMouseOutFromChord = function() { return function(g, i) { var si = $scope.getIndexByDocTypeId($scope.selectedDocType.id); if (si != -1) { if (si != i) { $scope.toggleChordVisibility(TARGET_EXCEPT_SELECTED, FADED, i, si); } } else { $scope.toggleChordVisibility(ALL_CHORDS, BRIGHT); } }; } $scope.listenForTabClick = function() { var tabs = document.querySelectorAll('.nav-tabs a.ng-binding'); if (tabs && tabs.length > 0) { for(var i = 0; i < tabs.length; i++) { tabs[i].onclick = function() { if ($('#DocTypeVisualiserPlaceHolder > svg').attr('height') < 101) { window.setTimeout(function() { $scope.refreshGraph(); }, 5); } }; } } window.onresize = function() { $scope.refreshGraph(); }; }; $scope.onDocTypeSelection = function(id) { if (!id) { return function(g, index) { var docTypes = $scope.getDocTypes(); var selected = docTypes[index]; $scope.selectDocType(selected.id); $scope.toggleChordVisibility(ALL_CHORDS, FADED); $scope.toggleChordVisibility(TARGET_ONLY, BRIGHT, index); } } else { var index = $scope.getIndexByDocTypeId(id); var needsRefresh = ($scope.hiddenDocTypes[id]) ? true : false; $scope.selectDocType(id); if (needsRefresh) { // need to refresh graph because unhiding a doctype. $scope.refreshGraph(); // need to refresh index to make new chords appear index = $scope.getIndexByDocTypeId(id); } $scope.toggleChordVisibility(ALL_CHORDS, FADED); $scope.toggleChordVisibility(TARGET_ONLY, BRIGHT, index); } }; $scope.toggleDocTypeVisibility = function(id) { if (!$scope.hiddenDocTypes[id]) { $scope.hiddenDocTypes[id] = true; } else { $scope.hiddenDocTypes[id] = false; } $scope.refreshGraph(); }; /*--- Helper Functions ---*/ $scope.createGraph = function() { var fill = d3.scale.category10(); var data = { labels: $scope.getNames(), matrix: $scope.getMatrix() }; var chord = d3.layout.chord().padding(.05).sortSubgroups(d3.descending).matrix(data.matrix); var width = document.querySelector('#DocTypeVisualiserPlaceHolder').offsetWidth - 200; var height = document.querySelector('#DocTypeVisualiserPlaceHolder').offsetHeight - 200; var r1 = height / 2; var innerRadius = Math.min(width, height) * .41; var outerRadius = innerRadius * 1.1; $scope.svg = d3.select("#DocTypeVisualiserPlaceHolder").append("svg") .attr("width", width + 200) .attr("height", height + 200) .append("g") .attr("transform", "translate(" + (width + 200) / 2 + "," + (height + 200) / 2 + ")"); $scope.svg.append("g") .selectAll("path") .data(chord.groups).enter().append("path") .attr("class", "arc") .style("fill", function(d) { return ($scope.isComposition($scope.getDocTypes()[d.index].id)) ? '#f57020' : fill(d.index); }) .style("stroke", function(d) { return ($scope.isComposition($scope.getDocTypes()[d.index].id)) ? '#f57020' : fill(d.index); }) .attr('stroke-width', 4) .attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius)) .on("click", $scope.onDocTypeSelection()) .on("mouseover", $scope.onHoverOverChord()) .on("mouseout", $scope.onMouseOutFromChord()); $scope.svg.append("g") .attr("class", "chord") .selectAll("path") .data(chord.chords) .enter().append("path") .attr("d", d3.svg.chord().radius(innerRadius - 2)) .style("fill", function(d) { return fill(d.target.index); }) .style("stroke", function(d) { return fill(d.target.index); }) .style("opacity", BRIGHT); $scope.svg.append("g").selectAll(".arc") .data(chord.groups) .enter().append("svg:text") .attr("dy", ".35em") .attr("text-anchor", function(d) { return ((d.startAngle + d.endAngle) / 2) > Math.PI ? "end" : null; }) .attr("transform", function(d) { return "rotate(" + (((d.startAngle + d.endAngle) / 2) * 180 / Math.PI - 90) + ")" + "translate(" + (r1 - 15) + ")" + (((d.startAngle + d.endAngle) / 2) > Math.PI ? "rotate(180)" : ""); }) .text(function(d) { return data.labels[d.index]; }); }; $scope.deleteGraph = function() { $scope.svg = false; $('.doctype-graph').html(''); }; $scope.doesDocTypeHaveConnection = function(docTypes, id) { var hasConnection = false; docTypes.forEach(function(docType) { if (docType.id == id) { if (docType.compositions.length) { hasConnection = true; } } else { var comps = docType.compositions; if (comps && comps.length > 0) { comps.forEach(function(comp) { if (comp === id) { hasConnection = true; } }); } } }); return hasConnection; }; $scope.filterUnconnectedDocTypes = function(docTypes) { var filtered = []; if (docTypes && docTypes.length > 0) { docTypes.forEach(function(docType) { if ($scope.doesDocTypeHaveConnection(docTypes, docType.id)) { filtered.push(docType); } }); } return filtered; }; $scope.getBreadcrumb = function(id) { var breadcrumb = []; if (id) { var docType = $scope.getDocTypeById(id); if (docType) { var hasCrumb = true; while (hasCrumb) { hasCrumb = (docType.parentId > -1) ? true : false; if (hasCrumb) { docType = $scope.getDocTypeById(docType.parentId); var crumb = { name: docType.name, id: docType.id }; breadcrumb.push(crumb); } } } } return breadcrumb; }; $scope.getCompositions = function(id) { var compositions = []; var docType = $scope.getDocTypeById(id); if (docType.compositions && docType.compositions.length > 0) { compositions = docType.compositions.map(function(comp) { return $scope.getDocTypeById(comp); }); } return compositions; }; $scope.getDocTypes = function(shouldNotFilterHidden) { var docTypes = $scope.docTypes; if (!$scope.showAll) { docTypes = $scope.filterUnconnectedDocTypes($scope.docTypes); if (!shouldNotFilterHidden) { if ($scope.hiddenDocTypes && $scope.hiddenDocTypes.length > 0) { $scope.hiddenDocTypes.forEach(function(isHidden, hiddenIndex) { if (isHidden) { docTypes.forEach(function(dt, docTypeIndex) { if (dt.id == hiddenIndex) { docTypes.splice(docTypeIndex, 1); } }); } }); } } } return docTypes; }; $scope.getDocTypeById = function(id) { var result = false; if (id) { if ($scope.docTypes && $scope.docTypes.length > 0) { $scope.docTypes.forEach(function(docType) { if (docType.id === id) { result = docType; } }); } } return result; }; $scope.getIndexByDocTypeId = function(id) { var index = -1; var docTypes = $scope.getDocTypes(); docTypes.forEach(function(dt, i) { if (dt.id === id) { index = i; } }); return index; } $scope.getMatrix = function() { var docTypes = $scope.getDocTypes(); matrix = []; if (docTypes && docTypes.length > 0) { // Loop through each docType docTypes.forEach(function(docType) { var matrixRow = []; var currentComps = docType.comps; var currentId = docType.id; // Loop through each docType to compare against this one. docTypes.forEach(function(otherDocType) { var val = 0; // If other doctype's ID matches one of the compositions for this doctype,then val = 1. if (currentComps && currentComps.length > 0) { currentComps.forEach(function(cc) { if (cc == otherDocType.id) { val = 1; } }); } // Alternatively, if this document's id is a compositionin the other doctype, then val = 1. if (otherDocType.compositions && otherDocType.compositions.length > 0) { otherDocType.compositions.forEach(function(odcc) { if (odcc == currentId) { val = 1; } }); } // Push the val to the row matrixRow.push(val); }); // For each doctype, push a row to the matrix. matrix.push(matrixRow); }); } return matrix; }; $scope.getNames = function() { var names = []; var docTypes = $scope.getDocTypes(); if (docTypes && docTypes.length > 0) { names = docTypes.map(function(docType) { return docType.name; }); } return names; }; $scope.getPagesUsingComp = function(id) { var pages = []; if (id) { $scope.docTypes.forEach(function(dt) { if (dt.compositions && dt.compositions.length > 0) { dt.compositions.forEach(function(comp) { if (comp === id) { pages.push(dt); } }) } }); } return pages; }; $scope.isComposition = function(id) { var docType = $scope.getDocTypeById(id); var isComposition = ($scope.getPagesUsingComp(id).length > 0) ? true : false; return isComposition; }; $scope.refreshGraph = function() { $scope.deleteGraph(); $scope.createGraph(); }; $scope.selectDocType = function(id) { if (id) { var selected = $scope.getDocTypeById(id); $scope.hiddenDocTypes[selected.id] = false; $scope.selectedDocType = { id: selected.id, name: selected.name, breadcrumb: $scope.getBreadcrumb(selected.id), compositions: $scope.getCompositions(selected.id), pagesUsingComp: $scope.getPagesUsingComp(selected.id) }; } }; $scope.sortByCompositions = function(docTypes) { if (docTypes && docTypes.length > 0) { docTypes.sort(function(a, b) { return a.compositions.length - b.compositions.length; }); } return docTypes; }; $scope.toggleChordVisibility = function(filter, opacity, index, selectedIndex) { if (filter === FADED || filter === BRIGHT) { opacity = filter; filter = false; } if (!filter) { filter = ALL_CHORDS; } if (!opacity) { opacity = BRIGHT; } switch (filter) { case ALL_CHORDS: $scope.svg.selectAll(".chord path").transition().style("opacity", opacity); break; case TARGET_ONLY: $scope.svg.selectAll(".chord path").filter(function(d) { return d.source.index == index || d.target.index == index; }).transition().style("opacity", opacity); break; case ALL_EXCEPT_TARGETS: if (selectedIndex == undefined) { $scope.svg.selectAll(".chord path").filter(function(d) { return d.source.index != index && d.target.index != index; }).transition().style("opacity", opacity); } else { $scope.svg.selectAll(".chord path").filter(function(d) { return d.source.index != index && d.target.index != index && d.source.index != selectedIndex && d.target.index != selectedIndex; }).transition().style("opacity", opacity); } break; case TARGET_EXCEPT_SELECTED: $scope.svg.selectAll(".chord path").filter(function(d) { return (d.source.index == index || d.target.index == index) && d.source.index != selectedIndex; }).transition().style("opacity", opacity); break; }; }; /*---- Init ----*/ $scope.init(); }); <file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/API/Attributes/CamelCaseControllerAttribute.cs using System; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http.Controllers; using Newtonsoft.Json.Serialization; namespace BackOfficeVisualiser.Api.Attributes { public class CamelCaseControllerAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { var formatter = controllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single(); controllerSettings.Formatters.Remove(formatter); formatter = new JsonMediaTypeFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() } }; controllerSettings.Formatters.Add(formatter); } } }<file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/Install/PackageActions/BackOfficeVisualiserPackageAction.cs using System.Xml; using umbraco.BusinessLogic; using umbraco.interfaces; using Umbraco.Core; using Umbraco.Core.IO; namespace BackOfficeVisualiser.Install.PackageActions { public class BackOfficeVisualiserPackageAction : IPackageAction { public string Alias() { return "BackOfficeVisualiser"; } public XmlNode SampleXml() { string sample = "<Action runat=\"install\" undo=\"true/false\" alias=\"BackOfficeVisualiser\"/>"; return umbraco.cms.businesslogic.packager.standardPackageActions.helper.parseStringToXmlNode(sample); } public bool Execute(string packageName, XmlNode xmlData) { //If not there, add the dashboards to dashboard.config this.AddSectionDashboard("BackOfficeVisualiser", "settings", "Back Office Visualizer", "/app_plugins/BackOfficeVisualiser/views/DocTypeVisualiser.html"); return true; } public bool Undo(string packageName, XmlNode xmlData) { // Remove the dashboards from Dashboard.config this.RemoveDashboardTab("BackOfficeVisualiser"); return true; } /// <summary> /// Adds the required XML to the dashboard.config file /// </summary> /// <param name="sectionAlias">Alias of the section. a-z, A-z 0-1 and no blank spaces</param> /// <param name="area">Enter the area where you want to show the dashboard</param> /// <param name="tabCaption">Enter the caption to be shown in the dashboard tab</param> /// <param name="src"></param> public void AddSectionDashboard(string sectionAlias, string area, string tabCaption, string src) { bool saveFile = false; //Path to the file resolved var dashboardFilePath = IOHelper.MapPath(SystemFiles.DashboardConfig); Log.Add(LogTypes.Notify, 0, "Adding dashboard section " + sectionAlias + " in: " + dashboardFilePath); //Load settings.config XML file XmlDocument dashboardXml = new XmlDocument(); dashboardXml.Load(dashboardFilePath); // Section Node XmlNode findSection = dashboardXml.SelectSingleNode("//section [@alias='" + sectionAlias + "']"); //Couldn't find it if (findSection == null) { //Let's add the xml var xmlToAdd = "<section alias='" + sectionAlias + "'>" + "<areas>" + "<area>" + area + "</area>" + "</areas>" + "<tab caption='" + tabCaption + "'>" + "<control addPanel='true' panelCaption=''>" + src + "</control>" + "</tab>" + "</section>"; //Get the main root <dashboard> node XmlNode dashboardNode = dashboardXml.SelectSingleNode("//dashBoard"); if (dashboardNode != null) { //Load in the XML string above XmlDocument xmlNodeToAdd = new XmlDocument(); xmlNodeToAdd.LoadXml(xmlToAdd); var toAdd = xmlNodeToAdd.SelectSingleNode("*"); //Prepend the xml above to the dashboard node - so that it will be the first dashboards to show in the backoffice. dashboardNode.PrependChild(dashboardNode.OwnerDocument.ImportNode(toAdd, true)); //Save the file flag to true saveFile = true; } } //If saveFile flag is true then save the file if (saveFile) { //Save the XML file dashboardXml.Save(dashboardFilePath); } } /// <summary> /// Removes a tab from the dashboard configuration. /// </summary> /// <param name="sectionAlias"></param> public void RemoveDashboardTab(string sectionAlias) { string dbConfig = IOHelper.MapPath(SystemFiles.DashboardConfig); XmlDocument dashboardFile = XmlHelper.OpenAsXmlDocument(dbConfig); XmlNode section = dashboardFile.SelectSingleNode("//section [@alias = '" + sectionAlias + "']"); if (section != null) { dashboardFile.SelectSingleNode("/dashBoard").RemoveChild(section); dashboardFile.Save(dbConfig); } } } }<file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/Models/PropertyTypeAnalyzerResult.cs using System.Collections.Generic; namespace BackOfficeVisualiser.Models { public class PropertyTypeAnalyzerResult { public PropertyTypeAnalyzerResult() { DocumentTypes = new List<DocTypeModel>(); Properties = new List<PropertyTypeModel>(); } public List<DocTypeModel> DocumentTypes { get; set; } public List<PropertyTypeModel> Properties { get; set; } } }<file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/Install/PackageActions/RemoveOldInstallation.cs using System.Collections.Generic; using System.Linq; using System.Xml; using umbraco.cms.businesslogic.packager; using umbraco.cms.businesslogic.packager.standardPackageActions; using umbraco.interfaces; namespace BackOfficeVisualiser.Install.PackageActions { /// <summary> /// This action is used for upgrades. It will remove the old icon from the developer-section so that we don't get /// a long list of old packages in the list of installed packages. /// </summary> public class RemoveOldInstallation : IPackageAction { public string Alias() { return "RemoveOldInstallation"; } public bool Execute(string packageName, XmlNode xmlData) { List<InstalledPackage> list = InstalledPackage.GetAllInstalledPackages().Where(x => x.Data.Name.Equals("BackOffice Visualiser")).ToList(); if (list.Count > 1) { list.RemoveAt(list.Count - 1); foreach (InstalledPackage package in list) { package.Delete(); } } return true; } public XmlNode SampleXml() { return helper.parseStringToXmlNode(string.Format("<Action runat=\"install\" alias=\"{0}\"></Action>", this.Alias())); } public bool Undo(string packageName, XmlNode xmlData) { return true; } } }<file_sep>/README.md # Umbraco Backoffice Visualization Package &middot; ![version](https://img.shields.io/badge/version-1.1.1-green.svg) The Umbraco Backoffice Visualization package is a dashboard that displays visual representations of how data in Umbraco intersects. Located in the Settings section, version 1 has the purpose of mapping DocType connections via inheritance and compositions. [You can view the demo here](https://www.youtube.com/watch?v=pmRFipRIfCA). <img src="https://docs.google.com/uc?id=0B1BeRPYxbA_SeE1lNGYtSkszTEk&export=download" width="285" title="DocType Composition Relationships Landing" /> <img src="https://docs.google.com/uc?id=0B1BeRPYxbA_SZDVVZ1oweW55WDg&export=download" width="285" title="DocType Composition Relationships Table" /> <img src="https://docs.google.com/uc?id=0B1BeRPYxbA_SRmV6SjNJQlpFTGc&export=download" width="285" title="DocType Compostion Relationships, Showing All DocTypes" /> ## Download for Umbraco Install the selected release through the Umbraco package installer or [download and install locally from Our](https://our.umbraco.org/projects/backoffice-extensions/umbraco-backoffice-visualization/). ## Contribute Want to contribute to the Backoffice Visualization package? You'll want to use Grunt (our task runner) to help you integrate with a local copy of Umbraco. ### Install Dependencies *Requires Node.js to be installed and in your system path* npm install -g grunt-cli && npm install -g grunt npm install ### Build grunt Builds the project to /dist/. These files can be dropped into an Umbraco 7 site, or you can build directly to a site using: grunt --target="D:\inetpub\mysite" You can also watch for changes using: grunt watch grunt watch --target="D:\inetpub\mysite" To build the actual Umbraco package, use: grunt umbraco <file_sep>/BackOfficeVisualiser/resources/d3.resource.js angular.module("umbraco.resources").factory("d3Resource", function ($http) { var d3Resource = {}; d3Resource.test = function () { console.info('d3resource works'); }; return d3Resource; }); <file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/PropertyTypeAnalyzer.cs using System.Collections.Generic; using System.Linq; using BackOfficeVisualiser.Models; using umbraco.interfaces; using Umbraco.Core; using Umbraco.Core.Models; namespace BackOfficeVisualiser { public class PropertyTypeAnalyzer { public PropertyTypeAnalyzerResult Analyze() { var model = new PropertyTypeAnalyzerResult(); var allDoctypes = ApplicationContext.Current.Services.ContentTypeService.GetAllContentTypes(); var allProperties = ApplicationContext.Current.Services.DataTypeService.GetAllDataTypeDefinitions(); foreach (var contentType in allDoctypes) { ProcessContentType(contentType, model); } foreach (var propertyType in allProperties) { ProcessPropertyType(propertyType, model); } return model; } private void ProcessContentType(IContentType contentType, PropertyTypeAnalyzerResult model) { var parentIds = contentType.CompositionIds(); var docTypeModel = new DocTypeModel(); var propertyList = contentType.PropertyTypes.Select(property => property.DataTypeDefinitionId).ToList(); docTypeModel.Compositions = parentIds.ToList(); docTypeModel.Alias = contentType.Alias; docTypeModel.Name = contentType.Name; docTypeModel.Id = contentType.Id; docTypeModel.ParentId = contentType.ParentId; docTypeModel.Properties = propertyList; model.DocumentTypes.Add(docTypeModel); } private void ProcessPropertyType(IDataTypeDefinition propertyType, PropertyTypeAnalyzerResult model) { var propertyTypeModel = new PropertyTypeModel(); propertyTypeModel.Name = propertyType.Name; propertyTypeModel.Id = propertyType.Id; propertyTypeModel.Alias = propertyType.PropertyEditorAlias; model.Properties.Add(propertyTypeModel); } } }<file_sep>/BackOfficeVisualiser/Umbraco/BackOfficeVisualiser/API/PropertyTypeVisualiserController.cs using System.Web.Http; using BackOfficeVisualiser.Api.Attributes; using BackOfficeVisualiser.Models; using Umbraco.Web.Editors; using Umbraco.Web.WebApi; #pragma warning disable 612,618 #pragma warning restore 612,618 namespace BackOfficeVisualiser.Api { [IsBackOffice] [CamelCaseController] public class PropertyTypeVisualiserController : UmbracoAuthorizedJsonController { [HttpGet] public PropertyTypeAnalyzerResult GetViewModel() { var pta = new PropertyTypeAnalyzer(); return pta.Analyze(); } } }
5466a881488edc583095c01caedd17b4e9dec1c9
[ "JavaScript", "C#", "Markdown" ]
16
JavaScript
Offroadcode/umbraco-backoffice-visualization
71178ce5b3939df653a4173b0396ba7f6aa60474
7f36fbc99ac0914a6e2b07e652ae8cc4af3bf8a9
refs/heads/master
<file_sep>package pe.com.cernafukuzaki.java.mockito.webservice; import static pe.com.cernafukuzaki.java.mockito.webservice.WebServiceComprarLibroResponse.WebServiceComprarLibroResponseMensaje.OK; public class WebServiceComprarLibroService { private WebServiceComprarLibroPort webServiceComprarLibro; public WebServiceComprarLibroService(WebServiceComprarLibroPort webServiceComprarLibro) { this.webServiceComprarLibro = webServiceComprarLibro; } public boolean comprarLibro(Libro libro) { WebServiceComprarLibroResponse response = webServiceComprarLibro.comprarLibro(new WebServiceComprarLibroRequest(libro)); return response.getMensaje() == OK; } } <file_sep>package pe.com.cernafukuzaki.java.arrays; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Tag; @Tag("OperacionesMatematicasTest") @DisplayName("Pruebas de operaciones matemáticas") @TestMethodOrder(OrderAnnotation.class) public class OperacionesMatematicasTest { int[] arregloEnteros = {2,4,6,8,10}; int[] arregloEnterosMCD = {18,24};//Máximo Común Divisor int[] arregloEnterosMCM = {20,38,11,15};//Mínimo Común Múltiplo OperacionesMatematicas operacionesMatematicas = new OperacionesMatematicas(); @Test @DisplayName("Máximo Común Divisor") @Order(1) public void obtenerMaximoComunDivisor() { assertEquals(2, operacionesMatematicas.obtenerMaximoComunDivisor(arregloEnteros)); } @Test @DisplayName("Mínimo Común Múltiplo") @Order(2) public void obtenerMinimoComunMultiplo() { assertEquals(12540, operacionesMatematicas.obtenerMinimoComunMultiplo(arregloEnterosMCM)); } @Test @DisplayName("Factorial de 3 es 6") @Order(3) public void cuandoFactorial3() { assertEquals(6, operacionesMatematicas.factorial(3)); } @Test @DisplayName("Factorial de 13 es 6227020800") @Order(4) public void cuandoFactorial13() { assertEquals(new Long("6227020800"), operacionesMatematicas.factorial(13)); } @Test @DisplayName("Media aritmética de arreglo de 3,7,9") @Order(5) public void cuandoArregloTieneElementosImpar() { int[] arreglo = {3,7,9}; int decimales = 4; assertEquals(6.3333, operacionesMatematicas.mediaAritmetica(arreglo, decimales)); } @Test @DisplayName("Media aritmética de arreglo de 53,87,19,102") @Order(6) public void cuandoArregloTieneElementosPar() { int[] arreglo = {53,87,19,102}; int decimales = 4; assertEquals(65.25, operacionesMatematicas.mediaAritmetica(arreglo, decimales)); } } <file_sep>package pe.com.cernafukuzaki.java.mockito.webservice; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; //import org.mockito.junit.MockitoJUnitRunner;//JUnit 4 import org.mockito.junit.jupiter.MockitoExtension; //@RunWith(MockitoJUnitRunner.class)//JUnit 4 @ExtendWith(MockitoExtension.class)//JUnit 5 class WebServiceComprarLibroServiceTest { /* Inicio Prueba utilizando dependencia de inyección */ @InjectMocks public WebServiceComprarLibroService service; @Mock public WebServiceComprarLibroPort port; @Test void cuando_es_satisfactoria() { service = new WebServiceComprarLibroService(port); Mockito.when(port.comprarLibro(Mockito.any())) .thenReturn(new WebServiceComprarLibroResponse(WebServiceComprarLibroResponse.WebServiceComprarLibroResponseMensaje.OK)); boolean resultado = service.comprarLibro(new Libro("Harry Potter 1")); assertTrue(resultado); } @Test void cuando_no_es_satisfactoria() { service = new WebServiceComprarLibroService(port); Mockito.when(port.comprarLibro(Mockito.any())) .thenReturn(new WebServiceComprarLibroResponse(WebServiceComprarLibroResponse.WebServiceComprarLibroResponseMensaje.ERROR)); boolean resultado = service.comprarLibro(new Libro("Harry Potter 1")); assertFalse(resultado); } /* Fin Prueba utilizando dependencia de inyección */ /* Inicio Prueba instanciando clases */ /* @Test void cuando_es_satisfactoria() { WebServiceComprarLibro port = Mockito.mock(WebServiceComprarLibro.class); Mockito.when(port.comprarLibro(Mockito.any())) .thenReturn(new WebServiceComprarLibroResponse(WebServiceComprarLibroResponse.WebServiceComprarLibroResponseMensaje.OK)); WebServiceComprarLibroService service = new WebServiceComprarLibroService(port); boolean resultado = service.comprarLibro(new Libro("Harry Potter 1")); assertTrue(resultado); } @Test void cuando_no_es_satisfactoria() { WebServiceComprarLibro port = Mockito.mock(WebServiceComprarLibro.class); Mockito.when(port.comprarLibro(Mockito.any())) .thenReturn(new WebServiceComprarLibroResponse(WebServiceComprarLibroResponse.WebServiceComprarLibroResponseMensaje.ERROR)); WebServiceComprarLibroService service = new WebServiceComprarLibroService(port); boolean resultado = service.comprarLibro(new Libro("Harry Potter 1")); assertFalse(resultado); } */ /* Inicio Prueba instanciando clases */ } <file_sep># cernafukuzaki-java Proyecto Java 8 con ejemplos de programación utilizando JUnit y Mockito para test. Librerías utilizadas: - JUnit 5. - Mockito 3. Práticas de Ingeniería de Software utilizada: - Test-driven development (TDD). - Programación Orientada a Objetos (Clase abstracta, Polimorfismo). - Patrones de diseño (Singleton). <file_sep>package pe.com.cernafukuzaki.java.designpattern.singleton; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @DisplayName("Pruebas de clase persona") class PersonaTest { @Test @DisplayName("Todas las personas son iguales") void personaHombreIgualAMujer() { Persona hombre = Persona.getInstance(); Persona mujer = Persona.getInstance(); assertEquals(hombre, mujer); } } <file_sep>package pe.com.cernafukuzaki.java.mockito.webservice; public class WebServiceComprarLibroResponse { enum WebServiceComprarLibroResponseMensaje { OK, ERROR } private WebServiceComprarLibroResponseMensaje mensaje; public WebServiceComprarLibroResponse(WebServiceComprarLibroResponseMensaje mensaje) { this.mensaje = mensaje; } public WebServiceComprarLibroResponseMensaje getMensaje() { return mensaje; } } <file_sep>package pe.com.cernafukuzaki.java.mockito.ejemplo; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.mockito.Mockito; @TestMethodOrder(OrderAnnotation.class) class JugadorTest { @Test @Order(1) void gana_cuando_numero_es_igual() { Dado dado = Mockito.mock(Dado.class); Mockito.when(dado.rodar()).thenReturn(3); Jugador jugador = new Jugador(dado, 3); assertEquals(true, jugador.jugar()); } @Test @Order(2) void gana_cuando_numero_es_mayor() { Dado dado = Mockito.mock(Dado.class); Mockito.when(dado.rodar()).thenReturn(6); Jugador jugador = new Jugador(dado, 3); assertEquals(true, jugador.jugar()); } @Test @Order(3) void pierde_cuando_numero_es_menor() { Dado dado = Mockito.mock(Dado.class); Mockito.when(dado.rodar()).thenReturn(1); Jugador jugador = new Jugador(dado, 3); assertEquals(false, jugador.jugar()); } } <file_sep>package pe.com.cernafukuzaki.java.designpattern.singleton; public class Persona { /* * Instancia estática y final. * Static: Puede ser utilizado sin instanciar la clase. * Final: No es modificable. */ private static final Persona INSTANCE = new Persona(); /* * Constructor privado. */ private Persona() { } /* * Operación que retorna la única instancia */ public static Persona getInstance() { return INSTANCE; } } <file_sep><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>pe.com.cernafukuzaki.java</groupId> <artifactId>cernafukuzaki-java</artifactId> <version>1.0.0</version> <properties> <junit-jupiter-version>5.5.1</junit-jupiter-version> </properties> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>${junit-jupiter-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>3.0.0</version> <scope>test</scope> </dependency> <!-- Mockito Extension --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>2.27.0</version> <scope>test</scope> </dependency> </dependencies> </project>
4804529484657ea89e32ed41822c07cf98997b35
[ "Markdown", "Java", "Maven POM" ]
9
Java
fcernafukuzaki/cernafukuzaki-java
9c24e4131c4da13dc743c68ffcd2d621c2d801a7
8f7ae2b2eefbc30493a4cfc95d8724574580a6dc
refs/heads/master
<repo_name>Lee-App/Stick-Overflow<file_sep>/stickoverflow/templates/registration/login.html <!-- 로그인 --> {% extends 'stickoverflow/base.html' %} {% block content %} {% load static %} <link rel = "stylesheet" type="text/css" href = "{% static 'stickoverflow/style.css/' %}"/> <!-- 로그인 되어있는 경우 --> {% if request.session.user %} <h2> Welcome, {{ request.session.user }} </h2> <a href="{% url 'logout' %}">로그아웃</a> <!-- 로그인 되어있지 않은 경우 --> {% else %} <h2> Login </h2> {% if form.errors %} <!-- 에러발생시 --> <p>ID나 비밀번호가 일치하지 않습니다.</p> {% endif %} <!-- 로그인 폼 --> <form method="post" action="{% url 'login' %}"> {% csrf_token %} {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} <div class="field_label_tag"> {{ field.label_tag }} </div> <div class="field_label"> {{ field }} </div> <!--{{ field.label_tag }} {{ field }}--> </div> {% endfor %} <br> <button type="submit">로그인</button> </form> <br> <p>아이디가 없으신가요? <a href="{% url 'signup' %}" style = "color : skyblue">회원가입</a></p> {% endif %} {% endblock %} <file_sep>/stickoverflow/urls.py from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'stickoverflow' urlpatterns = [ ] <file_sep>/stickoverflow/migrations/0001_initial.py # Generated by Django 2.2.1 on 2019-05-13 08:32 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='File', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user_id', models.CharField(max_length=50)), ('file_no', models.IntegerField()), ('file_name', models.CharField(max_length=260)), ('file_path', models.CharField(max_length=260)), ('file_description', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='Result', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user_id', models.CharField(help_text='Enter User ID', max_length=50)), ('file_no', models.IntegerField()), ('result_no', models.IntegerField()), ('analysis_code', models.IntegerField()), ('save_code', models.IntegerField()), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user_id', models.CharField(help_text='Enter User ID', max_length=50)), ('password', models.CharField(help_text='Enter password', max_length=50)), ('user_name', models.CharField(help_text='Enter user name', max_length=50)), ('email', models.CharField(help_text='Enter email', max_length=100)), ('department', models.CharField(help_text='Enter department', max_length=50, null=True)), ('input_id', models.CharField(max_length=50)), ('input_ip', models.CharField(max_length=15)), ('input_data', models.DateTimeField(auto_now=True)), ('update_id', models.CharField(max_length=50)), ('update_ip', models.CharField(max_length=15)), ('update_data', models.DateTimeField(auto_now=True)), ], ), ] <file_sep>/stickoverflow/apps.py from django.apps import AppConfig class StickoverflowConfig(AppConfig): name = 'stickoverflow' <file_sep>/mysite/urls.py """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from stickoverflow import views as stickoverflow_views # file_upload part from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views urlpatterns = [ # 메인 페이지 path('', stickoverflow_views.IndexView.as_view(), name = 'index'), # 로그인 path('accounts/login/', stickoverflow_views.LoginView.as_view(), name = 'login'), # 회원가입 path('accounts/signup/', stickoverflow_views.CreateUserView.as_view(), name = 'signup'), path('accounts/signup/done/', stickoverflow_views.RegisteredView.as_view(), name = 'create_user_done'), path('accounts/logout/', stickoverflow_views.LogoutView.as_view(), name = 'logout'), # 업로드 path('upload/', stickoverflow_views.UploadView.as_view(), name = 'upload'), # Product 추가 path('aboutus/', stickoverflow_views.AboutUs.as_view(), name = 'aboutus'), path('result_select_view/', stickoverflow_views.ResultSelectView.as_view(), name = 'result_select_view'), path('result_view/', stickoverflow_views.ResultView.as_view(), name = 'result_view'), ] # file_upload part # Serving media files on local machine if settings.DEBUG: # only during development urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) <file_sep>/README.md # Stick-Overflow stick overflow only django project ------------------ Adding Main Page design.(now working) * 메인 페이지 구성 참고사이트(https://www.socialbakers.com/?v=6a&utm_expid=.4c1VR9dJQZmyTzdF5kzbaQ.1&utm_referrer=https%3A%2F%2Fbrunch.co.kr%2F%40okwinus%2F12) ------------------ # 2019-06-09<br> ## 메인 페이지 한글화 및 내용 수정, 구성 변경 ![fixed](https://user-images.githubusercontent.com/39876295/59165228-b400ab80-8b53-11e9-96d4-753550973134.png) ------------------ # 2019-06-04<br> ## 로그인 폼과 회원가입 폼 디자인 완료, 추가사항 있을 시 연락바람. ![캡처](https://user-images.githubusercontent.com/39876295/58828954-8f9f5d80-8681-11e9-9c7b-bc3e779dc79f.JPG) ------------------ # 2019-05-29 ## 깃 충돌체크 및 클론 체크 ![0529](https://user-images.githubusercontent.com/39876295/58512731-c3d5d280-81d8-11e9-95f6-38a2ff6ed763.JPG) ------------------ # 2019-05-21 ## 데이터 분석 결과 확인 페이지 추가 * 분석결과 페이지 추가[O] ## 추가예정 * 분석결과 페이지에 그래프 그리기[O] * 그래프 그리기에 필요한 데이터는 받는대로 제작 착수[O] * 최소한 수요일(05/22)부터 제작 예정[O] * 책 구매 예정(파이썬 웹 프로그래밍:실전편)[X] ------------------ # 2019-05-19 ## 메인 페이지 내용 추가 * 메인 페이지 상단 바 고정[cancel] * About Us페이지 추가(내용 추가예정)[O] ## 추가예정 * 푸터 추가[cancel] * 메인페이지 애니메이션 추가[cancel] * 메인페이지 이미지 추가[undo] <file_sep>/stickoverflow/static/stickoverflow/file_meta_split.js function getCmaFileInfo(obj,stype) { var fileObj, pathHeader , pathMiddle, pathEnd, allFilename, fileName, extName; if(obj == "[object HTMLInputElement]") { fileObj = obj.value } else { fileObj = document.getElementById(obj).value; } if (fileObj != "") { pathHeader = fileObj.lastIndexOf("\\"); pathMiddle = fileObj.lastIndexOf("."); pathEnd = fileObj.length; fileName = fileObj.substring(pathHeader+1, pathMiddle); extName = fileObj.substring(pathMiddle+1, pathEnd); allFilename = fileName+"."+extName; if(stype == "all") { return allFilename; // 확장자 포함 파일명 } else if(stype == "name") { return fileName; // 순수 파일명만(확장자 제외) } else if(stype == "ext") { return extName; // 확장자 } else { return fileName; // 순수 파일명만(확장자 제외) } } else { alert("파일을 선택해주세요"); return false; } // getCmaFileView(this,'name'); // getCmaFileView('upFile','all'); } function getCmaFileView(obj,stype) { var s = getCmaFileInfo(obj,stype); alert(s); } <file_sep>/stickoverflow/forms.py from .models import User from django import forms # 회원가입 폼 class CreateUserForm(forms.ModelForm): user_id = forms.CharField(max_length = 50, label = 'id', required = True) password = forms.CharField(max_length = 50, label = 'password', widget = forms.PasswordInput, required = True) confirm_password = forms.CharField(max_length = 50, label = 'confirm password', widget = forms.PasswordInput, required = True) user_name = forms.CharField(max_length = 50, label = 'name', required = True) email = forms.EmailField(label = 'E-Mail', required = True) department = forms.CharField(max_length = 50, label = 'department') class Meta: model = User fields = ("user_id", "password", "confirm_password", "user_name", "email", "department") class LoginForm(forms.Form): user_id = forms.CharField(max_length = 50, label = 'id', required = True) password = forms.CharField(max_length = 50, label = 'password', widget = forms.PasswordInput, required = True) class UploadForm(forms.Form): file = forms.FileField() description = forms.CharField(max_length = 200, label = 'file description') <file_sep>/stickoverflow/models.py from django.db import models # Create your models here. # User Database class User(models.Model): user_id = models.CharField(max_length = 50, help_text = 'Enter User ID') password = models.CharField(max_length = 50, help_text = 'Enter password') user_name = models.CharField(max_length = 50, help_text = 'Enter user name') email = models.CharField(max_length = 100, help_text = 'Enter email') department = models.CharField(max_length = 50, help_text = 'Enter department', null = True) input_id = models.CharField(max_length = 50) input_ip = models.CharField(max_length = 15) input_data = models.DateTimeField(auto_now=True) update_id = models.CharField(max_length = 50) update_ip = models.CharField(max_length = 15) update_data = models.DateTimeField(auto_now=True) def check_password(self, password): return self.password == password def __str__(self): return self.user_id # FILE Database class File(models.Model): user_id = models.CharField(max_length = 50) file_no = models.IntegerField() file_name = models.CharField(max_length = 260) file_path = models.CharField(max_length = 260) file_description = models.CharField(max_length = 200) # RESULT Database class Result(models.Model): user_id = models.CharField(max_length = 50, help_text = 'Enter User ID') file_no = models.IntegerField() result_no = models.IntegerField() analysis_code = models.IntegerField() save_code = models.IntegerField() <file_sep>/stickoverflow/views.py from django.shortcuts import render from django.views.generic.edit import CreateView from .forms import CreateUserForm #, LoginForm from .models import User from django.urls import reverse_lazy from django.http import HttpResponseRedirect from django.views.generic.edit import View # 회원가입 뷰 class CreateUserView(CreateView): def get(self, request, *args, **kwargs): form = CreateUserForm() context = {'form': form} return render(request, 'registration/signup.html', context) def post(self, request, *args, **kwargs): form = CreateUserForm(data = request.POST) if form.is_valid(): check = self.is_sign_up_done(form.cleaned_data) if check: user = form.save() user.input_id = user.update_id = user.user_id user.input_ip = user.update_ip = self.get_client_ip(request) user.save() return HttpResponseRedirect(reverse_lazy('create_user_done')) return render(request, 'registration/signup.html', {'form': form}) def is_sign_up_done(self, valid_data): rst = True # password != <PASSWORD> if valid_data['password'] != valid_data['confirm_password']: rst = False # exists user id if User.objects.filter(user_id__iexact = valid_data['user_id']): rst = False return rst def get_client_ip(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip from .forms import LoginForm # 로그인 뷰 class LoginView(View): def get(self, request, *args, **kwargs): form = LoginForm() context = {'form': form} return render(request, 'registration/login.html', context) def post(self, request, *args, **kwargs): form = LoginForm(data = request.POST) if form.is_valid(): is_user = self.check_login(form.cleaned_data) if is_user: # Login Success request.session["user"] = is_user.user_id else: # Login Failed form = LoginForm() return render(request, 'registration/login.html', {'form': form}) return render(request, 'registration/login.html', {'form': form}) def check_login(self, valid_data): user = User.objects.filter(user_id__iexact = valid_data['user_id']) check = False if user: check = user[0].check_password(valid_data['password']) if check: return user[0] else: return False class LogoutView(View): def get(self, request, *args, **kwargs): self.logout(request) return render(request, 'registration/logged_out.html') def post(self, request, *args, **kwargs): self.logout(request) return render(request, 'registration/logged_out.html') def logout(self, request): request.session['user'] = '' request.session.modified = True from django.core.files.storage import FileSystemStorage from django.shortcuts import redirect from django.http import HttpResponse from os import mkdir from .forms import UploadForm from .models import File class UploadView(View): def get(self, request, *args, **kwargs): context = self.upload(request) return render(request, 'stickoverflow/upload.html', context) def post(self, request, *args, **kwargs): context = self.upload(request) return render(request, 'stickoverflow/upload.html', context) # file_upload part def upload(self, request): # print(File.objects.all().delete()) fs = FileSystemStorage() form = UploadForm(data = request.POST) context = {'form': form } user_id = '' if "user" in request.session: user_id = request.session['user'] if user_id and not fs.exists(user_id + '/'): mkdir(fs.path(user_id + '/')) if request.method == 'POST' and request.FILES['file']: # File Save uploaded_file = request.FILES['file'] file_full_name = '{}/{}'.format(user_id, uploaded_file) real_name = fs.save(file_full_name, uploaded_file) # DB file_name = real_name[len(user_id) + 1:] file_path = '{}/'.format(user_id) file_description = request.POST['description'] file = File(user_id = user_id, file_no = len(File.objects.all()), file_name = file_name, file_path = file_path, file_description = file_description) file.save() del request.FILES['file'] files = File.objects.filter(user_id__iexact = user_id) if files: file_list = [] for f in files: file_name = '{} <{}>'.format(f.file_name[:-4], f.file_no) file_type = f.file_name[-3:] file_desc = f.file_description file_no = f.file_no tmp = [file_name, file_type, file_desc, file_no] file_list.append(tmp) context['file_list'] = file_list return context from .statistics_model import get_column_names class ResultSelectView(View): def get(self, request, *args, **kwargs): response = "<script>alert('잘못된 접근입니다!');window.history.back();</script>" return HttpResponse(response) def post(self, request, *args, **kwargs): fs = FileSystemStorage() user_id = '' if "user" in request.session: user_id = request.session['user'] file_no = request.POST['file_no'] file = File.objects.filter(file_no__iexact = file_no) file_full_path = file[0].file_path + file[0].file_name if len(file) > 1 or user_id == '': response = "<script>alert('잘못된 접근입니다!');window.history.back();</script>" return HttpResponse(response) real_path = fs.path(file_full_path) columns = get_column_names(real_path) context = {'columns' : columns, 'file_no':file_no} return render(request, 'stickoverflow/result_select_view.html', context) from .statistics_model import result, get_graph_data class ResultView(View): def get(self, request, *args, **kwargs): response = "<script>alert('잘못된 접근입니다!');window.history.back();</script>" return HttpResponse(response) def post(self, request, *args, **kwargs): fs = FileSystemStorage() user_id = '' if "user" in request.session: user_id = request.session['user'] file_no = request.POST['file_no'] file = File.objects.filter(file_no__iexact = file_no) file_full_path = file[0].file_path + file[0].file_name if len(file) > 1: response = "<script>alert('잘못된 접근입니다!');window.history.back();</script>" return HttpResponse(response) option = request.POST['option'] column1 = request.POST['column1'] column2 = request.POST['column2'] real_path = fs.path(file_full_path) graph_data = result(real_path, option, x_label_col = column1, y_label_col = column2) graph_data = get_graph_data(graph_data, options = {'title' : file[0].file_name[:-4]}) context = {'graph_data' : graph_data} return render(request, 'stickoverflow/result_view.html', context) from django.views.generic.base import TemplateView class RegisteredView(TemplateView): template_name = 'registration/signup_done.html' class IndexView(TemplateView): template_name = 'stickoverflow/index.html' class AboutUs(TemplateView): template_name = 'stickoverflow/aboutus.html' <file_sep>/stickoverflow/statistics_model.py from statistics import median, mean from collections import Counter from numpy import bincount from pandas import DataFrame, read_csv from json import dumps option_name = ['Mean', 'Median', 'Max', 'Min', 'Mode'] def get_column_names(file_path): df = read_csv(file_path) return list(df.columns) # return list def result(file_path, option = 0, x_label_col = 1, y_label_col = 2): df = read_csv(file_path) slt_list = list(set(df[x_label_col])) lst = list() lst.append([x_label_col, "{}_{}".format(str(y_label_col), option_name[int(option)])]) for slt in slt_list: data_list = list(df.loc[df[x_label_col] == slt][y_label_col]) lst.append([str(slt), get_data_by_option(data_list, int(option))]) return lst # return numeric def get_data_by_option(data_list, option): rst = 0 if option == 0: rst = round(mean(data_list),3) elif option == 1: rst = median(data_list) elif option == 2: rst = max(data_list) elif option == 3: rst = min(data_list) elif option == 4: rst = int(bincount(data_list).argmax()) return rst # return str def get_graph_data(data_table, chart_type = 'LineChart', options = {'title' : 'Example'}, container_id = 'chart_div'): data = dict() data['chartType'] = chart_type data['dataTable'] = data_table data['options'] = options data['containerId'] = container_id return dumps(data)
35c2ad81696c8e380e49f352b3155d3b150c8add
[ "Markdown", "Python", "JavaScript", "HTML" ]
11
HTML
Lee-App/Stick-Overflow
8ea48ddafd1263a54969d744868f2eefb92c734f
dd82d8682248f5590ad965384027ad383a7f5d55
refs/heads/master
<repo_name>matt-fff/vscode-debug-python-in-docker<file_sep>/requirements.txt ptvsd==3.2.1 <file_sep>/src/config.py """ Container for Config """ import os import logging logger = logging.getLogger(__name__) class Config(object): """ Extracts config information from environmental variables """ def get_value(self, variable: str, default=None): """ Returns the environment variable, if it's defined. Returns the default, otherwise """ if variable in os.environ: return os.environ[variable] return default def get_bool(self, variable: str, default: bool) -> bool: return "{}".format(self.get_value(variable, default)).lower() == "true" def get_int(self, variable: str, default: int) -> int: return int(self.get_value(variable, default)) @property def debug(self) -> bool: return self.get_bool("DEBUG", False) @property def debug_port(self) -> str: return self.get_int("DEBUG_PORT", 3000) @property def debug_secret(self) -> str: return self.get_value("DEBUG_SECRET", None) config = Config() <file_sep>/src/hello_debug.py import ptvsd from config import config def connect_debugger(): if config.debug: address = ("0.0.0.0", config.debug_port) ptvsd.enable_attach(config.debug_secret, address) print("Waiting for debugger...") ptvsd.wait_for_attach() print("Debugger attached") else: print("Not configured for debugging") print("Starting execution") connect_debugger() print("Execution complete") <file_sep>/Dockerfile FROM python:3.6-alpine ENV PYTHONPATH /var/app ENV APPDIR=$PYTHONPATH WORKDIR $APPDIR # Install Pip requirements COPY ./requirements.txt $APPDIR/requirements.txt RUN pip install -U pip && \ pip install -r $APPDIR/requirements.txt CMD ["python", "/var/app/src/hello_debug.py"] <file_sep>/README.md # vscode-debug-python-in-docker [![DUB](https://img.shields.io/dub/l/vibe-d.svg)]() A (soon-to-be) functional Visual Studio Code debug setup for Docker-wrapped Python projects. <file_sep>/Makefile PROJECT_NAME=vscode-debug-python-in-docker REGISTRY_IMAGE=typenil/$(PROJECT_NAME) DOCKER_APPDIR=/var/app ENABLE_DEBUGGING=true EXTERNAL_DEBUG_PORT=4242 DEBUG_SECRET=tadpoles-turn-into-frogs define msg @printf "\033[36m# %s\033[0m\n" $(1) endef build: $(call msg,"Building application Docker image") @docker build --pull -t $(REGISTRY_IMAGE) -f Dockerfile . push: $(call msg,"Pushing application Docker image") @docker push $(REGISTRY_IMAGE) pull: $(call msg,"Pulling application Docker image") @docker push $(REGISTRY_IMAGE) run: rm $(call msg,"Starting application Docker container") @docker run -d \ -p $(EXTERNAL_DEBUG_PORT):3000 \ -e DEBUG_SECRET=$(DEBUG_SECRET) \ -e DEBUG_PORT=3000 \ -e DEBUG=$(ENABLE_DEBUGGING) \ --volume $(PWD)/src:$(DOCKER_APPDIR)/src \ --name $(PROJECT_NAME) \ $(REGISTRY_IMAGE) logs: docker logs -f $(PROJECT_NAME) stop: $(call msg,"Stopping application container") @docker stop $(PROJECT_NAME) rm: $(call msg,"Removing application Docker container") -@docker rm -f $(PROJECT_NAME)
15680da061027df6023e56e4aec57b6d5545a81e
[ "Markdown", "Makefile", "Python", "Text", "Dockerfile" ]
6
Text
matt-fff/vscode-debug-python-in-docker
8d3da7ebfcb4bb13da87ef1a86c3f879b72d5886
5eff139dc5734cbbc7c2ddd4b3187402b40eba79
refs/heads/master
<file_sep>bs4 futures ipywidgets jupyter lxml matplotlib nltk numba git+https://github.com/HazyResearch/numbskull@master numpy>=1.11 pandas requests scipy>=0.18 sklearn sqlalchemy>=1.0.14 tensorflow>=0.12.1 theano>=0.8.2 <file_sep><img src="figs/logo_01.png" width="150"/> **_v0.4.0_** [![Documentation](https://readthedocs.org/projects/snorkel/badge/?version=master)](http://snorkel.readthedocs.io/en/latest/) ## Important Note This is a snapshot of Snorkel on 1/17/2019 only for evaluation and some development of use cases on biomedical literature purposes. For the latest version please go to the main [github](https://github.com/HazyResearch/snorkel), note that a newer version of Snorkel might break our biomedical tutorial and does not yet include the PubAnnotation utilities needed for communication with the service. All original documentation/code remains the same and it is attributed to the original authors. This repo only adds PubAnnotation functionality and the BioMedical literature Jupyter notebook. ## Getting Started * [Data Programming: ML with Weak Supervision](http://hazyresearch.github.io/snorkel/blog/weak_supervision.html) * Installation instructions [below](#installation--dependencies) * Get started with the tutorials [below](#learning-how-to-use-snorkel) * Documentation [here](http://snorkel.readthedocs.io/en/latest/) ## Motivation Snorkel is intended to be a lightweight but powerful framework for developing **structured information extraction applications** for domains in which large labeled training sets are not available or easy to obtain, using the _data programming_ paradigm. In the data programming approach to developing a machine learning system, the developer focuses on writing a set of _labeling functions_, which create a large but noisy training set. Snorkel then learns a generative model of this noise&mdash;learning, essentially, which labeling functions are more accurate than others&mdash;and uses this to train a discriminative classifier. At a high level, the idea is that developers can focus on writing labeling functions&mdash;which are just (Python) functions that provide a label for some subset of data points&mdash;and not think about algorithms _or_ features! **_Snorkel is very much a work in progress_**, but some people have already begun developing applications with it, and initial feedback has been positive... let us know what you think, and how we can improve it, in the [Issues](https://github.com/HazyResearch/snorkel/issues) section! ### References * Data Programming, to appear at NIPS 2016: [https://arxiv.org/abs/1605.07723](https://arxiv.org/abs/1605.07723) * Workshop paper from HILDA 2016 (note Snorkel was previously _DDLite_): [here](http://cs.stanford.edu/people/chrismre/papers/DDL_HILDA_2016.pdf) ## Installation / dependencies Snorkel uses Python 2.7 and requires [a few python packages](python-package-requirement.txt) which can be installed using `pip`: ```bash pip install --requirement python-package-requirement.txt ``` Note that `sudo` can be prepended to install dependencies system wide if this is an option and the above does not work. Snorkel currently relies on `numba`, which occasionally requires a bit more work to install! One option is to use [`conda`](https://www.continuum.io/downloads). If installing manually, you may just need to make sure the right version of `llvmlite` and LLVM is installed and used; for example on Ubuntu, run: ```bash apt-get install llvm-3.8 LLVM_CONFIG=/usr/bin/llvm-config-3.8 pip install llvmlite LLVM_CONFIG=/usr/bin/llvm-config-3.8 pip install numba ``` Finally, enable `ipywidgets`: ```bash jupyter nbextension enable --py widgetsnbextension --sys-prefix ``` _Note: Currently the `Viewer` is supported on the following versions:_ * `jupyter`: 4.1 * `jupyter notebook`: 4.2 By default (e.g. in the tutorials, etc.) we also use [Stanford CoreNLP](http://stanfordnlp.github.io/CoreNLP/) for pre-processing text; you will be prompted to install this when you run `run.sh`. Alternatively, `virtualenv` can be used by starting with: ```bash virtualenv -p python2.7 .virtualenv source .virtualenv/bin/activate ``` ## Running After installing (see below), just run: ``` ./run.sh ``` ## Learning how to use Snorkel The [introductory tutorial](https://github.com/HazyResearch/snorkel/tree/master/tutorials/intro) covers the entire Snorkel workflow, showing how to extract spouse relations from news articles. The tutorial is available in the following directory: ``` tutorials/intro ``` The [biomedical tutorial](https://github.com/jmbanda/snorkelBioMed/blob/master/tutorials/DisGeNET/Snorkel_PubAnnotation.ipynb) it is an adaptation of other tutorials but with the focus on PMID documents as a corpus and using PubAnnotation to derive gold labels for them (using DisGeNET). This is a work in progress, so please report any bugs or issues. The tutorial is available in the following directory: ``` tutorials/DisGeNET ``` ## Issues For issues with the biomedical aspect of this repo, please report them here. For general purpose Snorkel issues please [use](https://github.com/HazyResearch/snorkel/issues) as a place to put bugs, questions, feature requests, etc- don't be shy! If submitting an issue about a bug, however, **please provide a pointer to a notebook (and relevant data) to reproduce it.** *Note: if you have an issue with the matplotlib install related to the module `freetype`, see [this post](http://stackoverflow.com/questions/20533426/ubuntu-running-pip-install-gives-error-the-following-required-packages-can-no); if you have an issue installing ipython, try [upgrading setuptools](http://stackoverflow.com/questions/35943606/error-on-installing-ipython-for-python-3-sys-platform-darwin-and-platform)* ## Jupyter Notebook Best Practices Snorkel is built specifically with usage in **Jupyter/IPython notebooks** in mind; an incomplete set of best practices for the notebooks: It's usually most convenient to write most code in an external `.py` file, and load as a module that's automatically reloaded; use: ```python %load_ext autoreload %autoreload 2 ``` A more convenient option is to add these lines to your IPython config file, in `~/.ipython/profile_default/ipython_config.py`: ``` c.InteractiveShellApp.extensions = ['autoreload'] c.InteractiveShellApp.exec_lines = ['%autoreload 2'] ``` <file_sep>import cPickle import numpy as np import tensorflow as tf from disc_learning import TFNoiseAwareModel from scipy.sparse import issparse from time import time from utils import get_train_idxs class LogisticRegression(TFNoiseAwareModel): def __init__(self, save_file=None, name='LR'): """Noise-aware logistic regression in TensorFlow""" self.d = None self.X = None self.lr = None self.l1_penalty = None self.l2_penalty = None super(LogisticRegression, self).__init__(save_file=save_file, name=name) def _build(self): # TODO: switch to sparse variables self.X = tf.placeholder(tf.float32, (None, self.d)) self.Y = tf.placeholder(tf.float32, (None, 1)) w = tf.Variable(tf.random_normal((self.d, 1), mean=0, stddev=0.01)) b = tf.Variable(tf.random_normal((1, 1), mean=0, stddev=0.01)) h = tf.add(tf.matmul(self.X, w), b) # Build model self.loss = tf.reduce_sum( tf.nn.sigmoid_cross_entropy_with_logits(h, self.Y) ) self.train_fn = tf.train.ProximalGradientDescentOptimizer( learning_rate=tf.cast(self.lr, dtype=tf.float32), l1_regularization_strength=tf.cast(self.l1_penalty, tf.float32), l2_regularization_strength=tf.cast(self.l2_penalty, tf.float32), ).minimize(self.loss) self.prediction = tf.nn.sigmoid(h) self.save_dict = {'w': w, 'b': b} def train(self, X, training_marginals, n_epochs=10, lr=0.01, batch_size=100, l1_penalty=0.0, l2_penalty=0.0, print_freq=5, rebalance=False): """Train elastic net logistic regression model using TensorFlow @X: SciPy or NumPy feature matrix @training_marginals: array of marginals for examples in X @n_epochs: number of training epochs @lr: learning rate @batch_size: batch size for mini-batch SGD @l1_penalty: l1 regularization strength @l2_penalty: l2 regularization strength @print_freq: number of epochs after which to print status @rebalance: rebalance training examples? """ # Build model verbose = print_freq > 0 if verbose: print("[{0}] lr={1} l1={2} l2={3}".format( self.name, lr, l1_penalty, l2_penalty )) print("[{0}] Building model".format(self.name)) self.d = X.shape[1] self.lr = lr self.l1_penalty = l1_penalty self.l2_penalty = l2_penalty self._build() # Get training indices train_idxs = get_train_idxs(training_marginals, rebalance=rebalance) X_train = X[train_idxs, :] y_train = np.ravel(training_marginals)[train_idxs] # Run mini-batch SGD n = X_train.shape[0] batch_size = min(batch_size, n) if verbose: st = time() print("[{0}] Training model #epochs={1} batch={2}".format( self.name, n_epochs, batch_size )) self.session.run(tf.global_variables_initializer()) for t in xrange(n_epochs): epoch_loss = 0.0 for i in range(0, n, batch_size): # Get batch tensors r = min(n-1, i+batch_size) x_batch = X_train[i:r, :].todense() y_batch = y_train[i:r] y_batch = y_batch.reshape((len(y_batch), 1)) # Run training step and evaluate loss function epoch_loss += self.session.run([self.loss, self.train_fn], { self.X: x_batch, self.Y: y_batch, })[0] # Print training stats if verbose and (t % print_freq == 0 or t in [0, (n_epochs-1)]): print("[{0}] Epoch {1} ({2:.2f}s)\tAverage loss={3:.6f}".format( self.name, t, time() - st, epoch_loss / n )) if verbose: print("[{0}] Training done ({1:.2f}s)".format(self.name, time()-st)) def marginals(self, X_test): X = X_test.todense() if issparse(X_test) else X_test return np.ravel(self.session.run([self.prediction], {self.X: X})) def save_info(self, model_name): with open('{0}.info'.format(model_name), 'wb') as f: cPickle.dump((self.d, self.lr, self.l1_penalty, self.l2_penalty), f) def load_info(self, model_name): with open('{0}.info'.format(model_name), 'rb') as f: self.d, self.lr, self.l1_penalty, self.l2_penalty = cPickle.load(f) <file_sep>##################################################### # getFromPubAnnotation file for Snorkel # # This program will allow a file to be passed # # with PMIDs and PubAnnotation project(s) to be # # exported into a Snorkel compatible data tables # # to potentially (or in our case) to be treated as # # gold-labels (as they have been curated by others).# # these tables can be then used for label generation# # or any other usages # ##################################################### import json import sys import string import csv from urllib2 import urlopen def get_jsonparsed_data(url): response = urlopen(url) data = response.read() #.decode("utf-8") return json.loads(data) def getCorpusPubAnnotation(fileWI): ### Read CSV file with list of documents/annotation project to pull from PubAnnotation inputFile=fileWI outFileDeno = open(inputFile[:-4] + "_denotations.txt", "w") outFileRela = open(inputFile[:-4] + "_relations.txt", "w") outFileText = open(inputFile[:-4] + "_text.txt", "w") f = open(inputFile, 'rb') # opens the csv file try: reader = csv.reader(f) # creates the reader object for row in reader: # iterates the rows of the file in orders project = row[1] PMID = str(row[0]) url = ("http://pubannotation.org/projects/"+project+"/docs/sourcedb/PubMed/sourceid/"+PMID+"/annotations.json") annotation = get_jsonparsed_data(url) ##print annotation ## This part generates the denotations - they should be inserted as they appear ## Pull text stuff textTO= annotation["text"].encode('utf-8') textTO = string.replace(textTO, '\r\n', '\\n') textTO = string.replace(textTO, '\n', '\\n') outFileText.write(PMID + "\t" + textTO + "\n") denoSpans = {} #this is a hacky version of getting the spans in a key,value pair for quick search for k in annotation["denotations"]: strID=k["id"] # onto, code = k["obj"].split(":") #get me the annotation_source and the ID it=0 spanV=[] for kp,v in k["span"].iteritems(): spanV.append(v) beginSpan=spanV endSpan=spanV ### This could be fully outputed into Snorkel, but that will come later #print(PMID + "\t" + strID + "\t" + onto + "\t" + code + "\t" + str(spanV[0]) + "\t" + str(spanV[1])) outFileDeno.write(PMID + "\t" + strID + "\t" + onto + "\t" + code + "\t" + str(spanV[0]) + "\t" + str(spanV[1])+"\n") denoSpans[strID]=str(spanV[0]) + "," + str(spanV[1]) ## This part gets the relations and formats them the proper way for kp in annotation["relations"]: for idV, spanVal in denoSpans.items(): if kp["subj"] == idV: sp1, sp2 = spanVal.split(",") outPtVal = PMID + "::span:" + sp1 + ":" + sp2 + "\t" for idV2, spanVal2 in denoSpans.items(): if kp["obj"] == idV2: sp12, sp22 = spanVal2.split(",") outPtVal_F = outPtVal+ PMID + "::span:" + sp12 + ":" + sp22 ### This should be fully outputed into Snorkel, but that will come later outFileRela.write(outPtVal_F + "\t" + kp["subj"] + "\t" + kp["obj"] + "\n") finally: f.close() #closing outFileDeno.close() outFileRela.close() outFileText.close() return 0 #sys.argv[1]
6146a6ab61eec72a262127357672ec8bc0c31e81
[ "Markdown", "Python", "Text" ]
4
Text
jmbanda/snorkelBioMed
db26600326d1ef34129d1c35d2d618b62be2dcf3
4d978920f51e6e2ddf8bfbc59780131b8a00a363
refs/heads/master
<repo_name>kicksapp/kicksapp-wordpress<file_sep>/README.md kicksapp-wordpress ================== > Kickstarter template for wordpress applications Under development ----------------- <file_sep>/index.php <?php // WordPress view bootstrapper define( 'WP_USE_THEMES', true ); set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ . '/vendor/lib'); require_once('./vendor/lib/autoload_52.php'); require('./wp/wp-blog-header.php' ); ?><file_sep>/Gruntfile.js var merge = require("deepmerge"); var path = require('path'); module.exports = function(grunt) { grunt.initConfig({ dist: grunt.option('output') || 'dist', phpbin: '/Applications/MAMP/bin/php/php5.6.2/bin', pkg: grunt.file.readJSON('package.json'), clean: { 'build': "<%= dist %>", 'tmp': ['tmp'] }, copy: { 'dist': { dot: true, expand: true, cwd: '.', src: ['wp/**/*', 'vendor/**/*', 'index.php', '.htaccess'], dest: grunt.option('output') || "<%= dist %>" }, 'broccoli': { dot: true, expand: true, cwd: 'tmp/broccoli_build', src: ['**/*.*'], dest: grunt.option('output') || "<%= dist %>/app" } }, curl: { 'wordpress': { src: 'http://wordpress.org/latest.zip', dest: 'tmp/downloads/wordpress/latest.zip' }, 'composer': { src: 'https://getcomposer.org/installer', dest: 'composer.phar' } }, unzip: { "wordpress": { cwd: 'wordpress', src: "tmp/downloads/wordpress/latest.zip", dest: "tmp/wordpress" } }, template: { 'dist': { options: { data: function() { return merge( grunt.file.readJSON('config/application.json'), grunt.file.readJSON('config/environment/' + ( grunt.option("environment") || 'development' ) + '.json') ); } }, src: 'wp-config.php', dest: ( grunt.option('output') || "<%= dist %>" ) + "/wp-config.php" } }, php: { serve: { options: { bin: "/Applications/MAMP/bin/php/php5.4.34/bin/php", base: 'dist', keepalive: true, open: true } } }, broccoli: { dist: { cwd: 'app', env: ( grunt.option('target') || 'development' ), dest: 'tmp/broccoli_build', config: 'Brocfile.js' } }, rsync: { options: { src: "<%= dist %>/.", //args: ["--verbose"], recursive: true }, development: { options: { dest: "/Applications/MAMP/htdocs/kicksapp/", delete: true } }, test: { options: { dest: "/var/www/site", host: "user@staging-host", delete: true // Careful this option could cause data loss, read the docs! } }, production: { options: { dest: "/var/www/site", host: "user@live-host", delete: true // Careful this option could cause data loss, read the docs! } } } }); grunt.loadNpmTasks('grunt-broccoli'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-template'); grunt.loadNpmTasks('grunt-php'); grunt.loadNpmTasks('grunt-curl'); grunt.loadNpmTasks('grunt-zip'); grunt.loadNpmTasks('grunt-phpdocumentor'); grunt.loadNpmTasks('grunt-wp-i18n'); grunt.loadNpmTasks('grunt-rsync'); /** * This task downloads the latest wordpress to dist */ grunt.registerTask('install', [ 'clean:tmp', 'curl:wordpress', 'unzip:wordpress', 'copy:wordpress', 'clean:tmp' ]); grunt.registerTask('build', [ 'clean:build', 'clean:tmp', 'broccoli:dist:build', 'copy:dist', 'copy:broccoli', 'template:dist', //'clean:tmp' ]); grunt.registerTask('deploy', [ 'build', 'rsync:' + (grunt.option('target') || 'development') ]); grunt.registerTask('serve', [ 'php:serve' ]); };<file_sep>/Brocfile.js // node var fs = require('fs'); var path = require('path'); // broccoli var selectFiles = require('broccoli-select'); var pickFiles = require('broccoli-static-compiler'); var mergeTrees = require('broccoli-merge-trees'); var concat = require('broccoli-concat'); var mince = require('broccoli-mincer'); var env = require('broccoli-env').getEnv(); var root = process.cwd(); var dest = ''; var src = 'app/'; var themesDir = 'themes'; var themesSrcDir = path.join(src, themesDir); var themesDestDir = path.join(dest, themesDir); var themes = fs.readdirSync(themesSrcDir); var resultTree = null; themes.forEach(function(theme) { console.log("Build theme '" + theme + "' with target " + env + "..."); var themeSrcDir = path.join(themesSrcDir, theme); var themeDestDir = path.join(themesDestDir, theme); var assetFiles = ['css/**/*.*', 'js/**/*.*']; var themeAssetsTree = pickFiles(themeSrcDir, { srcDir: '/', files: ['style.*', 'css/**/*.*', 'js/**/*.*'], destDir: "" }); // Select bootstrap assets var bootstrapTree = pickFiles('vendor/assets/components/bootstrap-sass-official/assets/fonts/bootstrap', { srcDir: '/', files: ['**/*.*'], destDir: "bootstrap" }); // Select other files var publicTree = selectFiles(themeSrcDir, { acceptFiles: [ '**/*'], rejectFiles: assetFiles, outputDir: themeDestDir, allowNone: true }); // Setup assets tree var sourceTrees = [themeAssetsTree, bootstrapTree]; var assetsTree = mergeTrees(sourceTrees, { overwrite: true }); // Compile assets assetsTree = mince(assetsTree, { //originalPaths: true, digest: true, allowNone: true, inputFiles: ['**/*.*'], manifest: path.join(themeDestDir, 'assets', 'assets.json'), sourceMaps: true, embedMappingComments: true, compress: false, enable: [ //'autoprefixer' ], engines: { Coffee: { bare: true } }, paths: [ path.join(root, 'vendor/assets/components'), path.join(root, 'vendor/assets/components/bootstrap-sass-official/assets/javascripts'), path.join(root, 'vendor/assets/components/bootstrap-sass-official/assets/stylesheets'), path.join(root, 'vendor/assets/components/bootstrap-sass-official/assets/fonts'), ".", 'css', 'js' ], helpers: { asset_path: function(pathname, options) { var asset = this.environment().findAsset(pathname, options); if (!asset) { throw new Error('File ' + pathname + ' not found'); } return asset.digestPath; } } }); // Merge trees into result var trees = [publicTree, assetsTree]; if (resultTree !== null) { trees.unshift(resultTree); } resultTree = mergeTrees(trees, { overwrite: true }); }); module.exports = resultTree;
e4fd2704462e16bd4976ab34ba4e44a0da45589d
[ "Markdown", "JavaScript", "PHP" ]
4
Markdown
kicksapp/kicksapp-wordpress
3d4c01d4e7baa014b93443ae6c06f991e1f3d006
536329f9b42fd177d92aede8094f2003c4d06153
refs/heads/master
<file_sep>package it.hembik.primatest.view.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.apollographql.apollo.exception.ApolloNetworkException import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import it.hembik.primatest.R import it.hembik.primatest.databinding.FragmentCountryDetailBinding import it.hembik.primatest.repository.models.CountryDetailRepoModel import it.hembik.primatest.viewmodel.CountryDetailViewModel class CountryDetailFragment: Fragment() { private val IMAGE_HOST = "https://www.countryflags.io/" private val IMAGE_LOCATION = "/shiny/64.png" private lateinit var binding: FragmentCountryDetailBinding companion object { val TAG = CountryDetailFragment::class.qualifiedName val COUNTRY_CODE_KEY = "COUNTRY_CODE_KEY" /** Creates project fragment for specific project ID */ fun forCountry(countryCode: String): CountryDetailFragment { val fragment = CountryDetailFragment() val args = Bundle() args.putString(COUNTRY_CODE_KEY, countryCode) fragment.arguments = args return fragment } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_country_detail, container, false) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) activity?.let { activity -> arguments?.let { args -> val factory = CountryDetailViewModel.Factory(activity.application, args.getString(COUNTRY_CODE_KEY)) val viewModel = ViewModelProviders.of(this, factory).get(CountryDetailViewModel::class.java) Glide .with(this) .load(IMAGE_HOST + args.getString(COUNTRY_CODE_KEY) + IMAGE_LOCATION) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(binding.countryLogo) binding.countryViewModel = viewModel binding.isLoading = true observeViewModel(viewModel) } } } private fun observeViewModel(viewModel: CountryDetailViewModel) { // Update the list when the data changes viewModel.getCountryDetailObservable().observe(this, Observer<CountryDetailRepoModel> { countryModel -> countryModel.throwable?.let { if (it.cause is ApolloNetworkException) { Toast.makeText(context, getString(R.string.check_connection), Toast.LENGTH_LONG).show() } } ?: run { countryModel.countryData?.country()?.let { viewModel.setCountryObservable(it) } } binding.isLoading = false }) } }<file_sep>package it.hembik.primatest.repository import androidx.lifecycle.MutableLiveData import com.apollographql.apollo.ApolloCall import com.apollographql.apollo.ApolloClient import com.apollographql.apollo.api.Response import com.apollographql.apollo.exception.ApolloException import com.apollographql.apollo.exception.ApolloNetworkException import it.hembik.primatest.CountriesQuery import it.hembik.primatest.CountryDetailQuery import it.hembik.primatest.repository.models.CountriesRepoModel import it.hembik.primatest.repository.models.CountryDetailRepoModel import okhttp3.OkHttpClient class CountryRepository { private val BASE_URL = "https://countries.trevorblades.com/" private var apolloClient: ApolloClient? = null /** * Apollo client getter. Makes setup if null. */ private fun getApolloClient(): ApolloClient { return apolloClient?.let { it } ?: run { setupClient() } } /** * Gets list of countries. */ fun getCountries(): MutableLiveData<CountriesRepoModel> { val data = MutableLiveData<CountriesRepoModel>() getApolloClient().query( CountriesQuery.builder() .build() )?.enqueue(object: ApolloCall.Callback<CountriesQuery.Data>() { override fun onFailure(e: ApolloException) { data.postValue(CountriesRepoModel(throwable = Throwable(e))) } override fun onResponse(response: Response<CountriesQuery.Data>) { data.postValue(CountriesRepoModel(countriesData = response.data())) } override fun onNetworkError(e: ApolloNetworkException) { data.postValue(CountriesRepoModel(throwable = Throwable(e))) } }) return data } /** * Gets country detail. * @param code country code. */ fun getCountryDetail(code: String?): MutableLiveData<CountryDetailRepoModel> { val data = MutableLiveData<CountryDetailRepoModel>() getApolloClient().query( CountryDetailQuery.builder().code(code) .build() )?.enqueue(object: ApolloCall.Callback<CountryDetailQuery.Data>() { override fun onFailure(e: ApolloException) { data.postValue(CountryDetailRepoModel(throwable = Throwable(e))) } override fun onResponse(response: Response<CountryDetailQuery.Data>) { data.postValue(CountryDetailRepoModel(countryData = response.data())) } override fun onNetworkError(e: ApolloNetworkException) { data.postValue(CountryDetailRepoModel(throwable = Throwable(e))) } }) return data } /** * Setups apollo client */ private fun setupClient(): ApolloClient { val okHttpClient = OkHttpClient.Builder().build() return ApolloClient.builder() .serverUrl(BASE_URL) .okHttpClient(okHttpClient) .build() } }<file_sep>package it.hembik.primatest import android.app.Application import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import it.hembik.primatest.repository.models.CountryDetailRepoModel import it.hembik.primatest.viewmodel.CountryDetailViewModel import junit.framework.Assert import junit.framework.Assert.assertNotNull import org.junit.Rule import org.junit.Test import org.mockito.Mockito import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit class CountryDetailViewModelTest { @get:Rule val rule = InstantTaskExecutorRule() private lateinit var viewModel: CountryDetailViewModel private val observer: Observer<CountryDetailRepoModel> = mock() val latch = CountDownLatch(1) @Test fun fetchCountryDetail_NotNull() { val application = Mockito.mock(Application::class.java) viewModel = CountryDetailViewModel(application, "UA") viewModel.getCountryDetailObservable().observeForever(observer) latch.await(2, TimeUnit.SECONDS) assertNotNull(viewModel.getCountryDetailObservable().value) } @Test fun setCountryObservableTest() { val application = Mockito.mock(Application::class.java) viewModel = CountryDetailViewModel(application, "UA") viewModel.getCountryDetailObservable().observeForever(observer) latch.await(2, TimeUnit.SECONDS) assertNotNull(viewModel.getCountryDetailObservable()) assertNotNull(viewModel.getCountryDetailObservable().value) assertNotNull(viewModel.getCountryDetailObservable().value!!.countryData) assertNotNull(viewModel.getCountryDetailObservable().value!!.countryData!!.country) viewModel.setCountryObservable(viewModel.getCountryDetailObservable().value!!.countryData!!.country!!) assertNotNull(viewModel.country) } }<file_sep>package it.hembik.primatest.repository.models import it.hembik.primatest.CountriesQuery class CountriesRepoModel (val countriesData: CountriesQuery.Data? = null, val throwable: Throwable? = null)<file_sep>package it.hembik.primatest.view.callback import it.hembik.primatest.CountriesQuery interface CountryClickCallback { fun onClick(country: CountriesQuery.Country) }<file_sep>include ':app' rootProject.name='PrimaTest' <file_sep>package it.hembik.primatest.utils import android.widget.Filter import it.hembik.primatest.CountriesQuery import it.hembik.primatest.view.adapter.CountriesAdapter import java.util.* import kotlin.collections.ArrayList open class CountryFilter(private val adapter: CountriesAdapter, private val countries: CountriesQuery.Data?, private var filteredCountries: CountriesQuery.Data?): Filter() { override fun performFiltering(sequence: CharSequence): FilterResults { val sequenceString = sequence.toString() if (sequenceString.isEmpty()) { filteredCountries = countries } else { filterCountries(sequenceString) } val results = FilterResults() results.values = filteredCountries return results } override fun publishResults(sequence: CharSequence?, results: FilterResults?) { results?.values?.let { searchResults -> filteredCountries = searchResults as CountriesQuery.Data filteredCountries?.let { adapter.setFilteredCountries(it) adapter.notifyDataSetChanged() } } } /** * Filters countries. * @param sequenceString searched string. */ fun filterCountries(sequenceString: String) { val filteredList = CountriesQuery.Data(ArrayList<CountriesQuery.Country>()) countries?.countries()?.let { countries -> for (country in countries) { if (continentMatch(country.continent()?.name(), sequenceString) || languageMatch(country.languages() as List<CountriesQuery.Language>, sequenceString)) { filteredList.countries()?.add(country) } filteredCountries = filteredList } } } /** * Checks for continent match. * @param continent current continent. * @param sequence searched sequence. * @return true if match, false otherwise. */ fun continentMatch(continent: String?, sequence: String?): Boolean { continent?.let { sequence?.let { return stringMatch(continent, sequence) } } return false } /** * Checks for language match. * @param language current language. * @param sequence searched sequence. * @return true if match, false otherwise. */ fun languageMatch(languageList: List<CountriesQuery.Language>, sequence: String): Boolean { for (language in languageList) { language.name()?.let { languageName -> sequence.let { return stringMatch(languageName, sequence) } } } return false } /** * Checks for string containing sequence. * @param first first string. * @param second second string. * @return true if first contains second, false otherwise. */ fun stringMatch(first: String, second: String): Boolean { return first.toLowerCase(Locale.getDefault()).contains(second.toLowerCase(Locale.getDefault())) } }<file_sep>package it.hembik.primatest import it.hembik.primatest.utils.CountryFilter import junit.framework.Assert.assertFalse import junit.framework.Assert.assertTrue import org.junit.Before import org.junit.Test import org.mockito.Mockito class CountryFilterTest { private lateinit var filter: CountryFilter @Before fun before() { filter = Mockito.mock(CountryFilter::class.java) } @Test fun testStringMatch() { assertTrue(filter.stringMatch("abcd", "abcd")) } @Test fun testContinentMatch() { assertTrue(filter.continentMatch("abcd", "abcd")) } @Test fun testStringNotMatch() { assertFalse(filter.stringMatch("abcd", "abcde")) } @Test fun testContinentNotMatch() { assertFalse(filter.continentMatch("abcd", "abcde")) } @Test fun testLanguageMatch() { val filter = Mockito.mock(CountryFilter::class.java) val language2 = CountriesQuery.Language("", "ukrainian") assertTrue(filter.languageMatch(listOf(language2), "ukra")) } @Test fun testLanguageNotMatch() { val filter = Mockito.mock(CountryFilter::class.java) val language2 = CountriesQuery.Language("", "ukrainian") assertFalse(filter.languageMatch(listOf(language2), "italian")) } }<file_sep>package it.hembik.primatest.view.ui import android.app.Activity import android.os.Bundle import android.view.inputmethod.InputMethodManager import androidx.appcompat.app.AppCompatActivity import it.hembik.primatest.CountriesQuery import it.hembik.primatest.R class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Add project list fragment if this is first creation savedInstanceState ?: run { val fragment = CountriesFragment() supportFragmentManager.beginTransaction() .add(R.id.fragment_container, fragment, CountriesFragment.TAG).commit() } } /** * Shows country detail fragment. * @param country country instance. */ fun showCountryDetail(country: CountriesQuery.Country) { country.code()?.let { code -> val countryFragment = CountryDetailFragment.forCountry(code) hideSoftKeyboard(this) supportFragmentManager .beginTransaction() .addToBackStack(CountryDetailFragment.TAG) .replace(R.id.fragment_container, countryFragment, null) .commit() } } /** * Hides keyboard. */ fun hideSoftKeyboard(activity: Activity) { val inputMethodManager = activity.getSystemService( Activity.INPUT_METHOD_SERVICE ) as InputMethodManager inputMethodManager.hideSoftInputFromWindow( activity.currentFocus?.windowToken, 0 ) } } <file_sep>package it.hembik.primatest.view.adapter import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import it.hembik.primatest.CountriesQuery import it.hembik.primatest.R import it.hembik.primatest.databinding.CountriesItemBinding import it.hembik.primatest.utils.CountryFilter import it.hembik.primatest.view.callback.CountryClickCallback class CountriesAdapter(private val countryClickCallback: CountryClickCallback): RecyclerView.Adapter<CountriesAdapter.CountryViewHolder>(), Filterable { private val IMAGE_HOST = "https://www.countryflags.io/" private val IMAGE_LOCATION = "/shiny/64.png" private var countriesList: CountriesQuery.Data? = null private var filteredCountriesList: CountriesQuery.Data? = null override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): CountryViewHolder { val binding: CountriesItemBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.countries_item, parent, false) binding.callback = countryClickCallback return CountryViewHolder(binding) } override fun getItemCount(): Int { return filteredCountriesList?.countries()?.size ?: 0 } override fun onBindViewHolder(holder: CountryViewHolder, position: Int) { val code = filteredCountriesList?.countries()!![position]?.code() Glide .with(holder.itemView.context) .load(IMAGE_HOST + code + IMAGE_LOCATION) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(holder.binding.countryLogo) holder.binding.country = filteredCountriesList?.countries()!![position] holder.binding.countryName.text = filteredCountriesList?.countries()!![position]?.name() } fun setCountries(countries: CountriesQuery.Data) { countriesList = countries filteredCountriesList = countriesList notifyDataSetChanged() } fun setFilteredCountries(countries: CountriesQuery.Data) { filteredCountriesList = countries } override fun getFilter(): Filter { return CountryFilter(this, countriesList, filteredCountriesList) } class CountryViewHolder(val binding: CountriesItemBinding): RecyclerView.ViewHolder(binding.root) }<file_sep>package it.hembik.primatest.viewmodel import android.app.Application import androidx.databinding.ObservableField import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import it.hembik.primatest.CountryDetailQuery import it.hembik.primatest.repository.CountryRepository import it.hembik.primatest.repository.models.CountryDetailRepoModel class CountryDetailViewModel(application: Application, countryCode: String?): AndroidViewModel(application) { private val countryObservable: MutableLiveData<CountryDetailRepoModel> = CountryRepository().getCountryDetail(countryCode) var country: ObservableField<CountryDetailQuery.Country> = ObservableField() fun getCountryDetailObservable(): MutableLiveData<CountryDetailRepoModel> { return countryObservable } /** * A factory is used to inject the country code into the ViewModel */ class Factory(private val application: Application, private val countryCode: String?) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return CountryDetailViewModel(application, countryCode) as T } } fun setCountryObservable(country: CountryDetailQuery.Country) { this.country.set(country) } }<file_sep>package it.hembik.primatest.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import it.hembik.primatest.repository.CountryRepository import it.hembik.primatest.repository.models.CountriesRepoModel class CountriesViewModel(application: Application): AndroidViewModel(application) { private val reloadTrigger = MutableLiveData<Boolean>() private val countriesObservable: LiveData<CountriesRepoModel> = Transformations.switchMap(reloadTrigger) { CountryRepository().getCountries() } init { refreshCountries() } fun getCountriesObservable(): LiveData<CountriesRepoModel> { return countriesObservable } fun refreshCountries() { reloadTrigger.value = true } }<file_sep>package it.hembik.primatest.view.adapter import android.view.View import android.widget.TextView import androidx.databinding.BindingAdapter import it.hembik.primatest.CountryDetailQuery const val PLACEHOLDER = "-" /** * CUSTOM BINDING ADAPTERS. */ @BindingAdapter("visibleGone") fun showHide(view: View, show: Boolean) { view.visibility = if (show) View.VISIBLE else View.GONE } @BindingAdapter("languages") fun languages(view: TextView, languages: List<CountryDetailQuery.Language>?) { view.text = languages?.let { languagesList -> if (languagesList.isNotEmpty()) { languagesList.joinToString(separator = ", ") { "${it.name()}"} } else { PLACEHOLDER } } ?: run { PLACEHOLDER } } @BindingAdapter("currency") fun currency(view: TextView, currency: String?) { view.text = currency?.let { if (currency.isNotEmpty()) { currency } else { PLACEHOLDER } } ?: run { PLACEHOLDER } }<file_sep>// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.app_compat_version = "1.1.0" ext.apollo_version = "1.1.3" ext.constraint_layout_version = "1.1.3" ext.core_ktx_version = "1.1.0" ext.espresso_core_version = "3.2.0" ext.glide_version = "4.10.0" ext.junit_version = "4.12" ext.junit_ext_version = "1.1.1" ext.kotlin_version = "1.3.50" ext.lifecycle_version = "2.1.0" ext.runner_version = "1.2.0" ext.recycler_view_version = "1.0.0" ext.core_testing_version = "2.1.0" ext.mockito_version = "3.0.0" repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.5.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath "com.apollographql.apollo:apollo-gradle-plugin:$apollo_version" } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } <file_sep>package it.hembik.primatest.repository.models import it.hembik.primatest.CountryDetailQuery class CountryDetailRepoModel(val countryData: CountryDetailQuery.Data? = null, val throwable: Throwable? = null)<file_sep>package it.hembik.primatest import android.app.Application import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import it.hembik.primatest.repository.models.CountriesRepoModel import it.hembik.primatest.viewmodel.CountriesViewModel import junit.framework.Assert.assertNotNull import org.junit.Rule import org.junit.Test import org.mockito.Mockito import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit class CountriesViewModelTest { @get:Rule val rule = InstantTaskExecutorRule() private lateinit var viewModel: CountriesViewModel private val observer: Observer<CountriesRepoModel> = mock() val latch = CountDownLatch(1) @Test fun fetchCountries_NotNull() { val application = Mockito.mock(Application::class.java) viewModel = CountriesViewModel(application) viewModel.getCountriesObservable().observeForever(observer) latch.await(2, TimeUnit.SECONDS) assertNotNull(viewModel.getCountriesObservable().value) } }<file_sep>package it.hembik.primatest.view.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.SearchView import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.apollographql.apollo.exception.ApolloNetworkException import it.hembik.primatest.CountriesQuery import it.hembik.primatest.R import it.hembik.primatest.databinding.FragmentCountriesBinding import it.hembik.primatest.repository.models.CountriesRepoModel import it.hembik.primatest.view.adapter.CountriesAdapter import it.hembik.primatest.view.callback.CountryClickCallback import it.hembik.primatest.viewmodel.CountriesViewModel class CountriesFragment: Fragment() { companion object { val TAG = CountriesFragment::class.qualifiedName } private lateinit var viewModel: CountriesViewModel var countriesAdapter: CountriesAdapter? = null var searchView: SearchView? = null private lateinit var swipeToRefresh: SwipeRefreshLayout private lateinit var binding: FragmentCountriesBinding private val countryClickCallback = object: CountryClickCallback { override fun onClick(country: CountriesQuery.Country) { if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) { (activity as MainActivity).showCountryDetail(country) } } } private val searchListener = object: SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { countriesAdapter?.filter?.filter(query) return false } override fun onQueryTextChange(newText: String?): Boolean { countriesAdapter?.filter?.filter(newText) return false } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_countries, container, false) countriesAdapter = CountriesAdapter(countryClickCallback) binding.countriesList.adapter = countriesAdapter swipeToRefresh = binding.swipeToRefresh swipeToRefresh.setOnRefreshListener { viewModel.refreshCountries() } searchView = binding.searchField searchView?.setOnQueryTextListener(searchListener) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // View model is not destroyed on configuration changes, api is done only at creation. viewModel = ViewModelProviders.of(this).get(CountriesViewModel::class.java) swipeToRefresh.isRefreshing = true observeViewModel(viewModel) } private fun observeViewModel(viewModel: CountriesViewModel) { // Update the list when the data changes viewModel.getCountriesObservable().observe(this, Observer<CountriesRepoModel> { countriesModel -> swipeToRefresh.isRefreshing = false countriesModel.throwable?.let { if (it.cause is ApolloNetworkException) { Toast.makeText(context, getString(R.string.check_connection), Toast.LENGTH_LONG).show() } } ?: run { countriesModel.countriesData?.let { binding.dataAvailable = it.countries()?.isNotEmpty() ?: false countriesAdapter?.setCountries(it) searchView?.let { searchView -> // Performs query when configuration changes. State is handled by android lifecycle. searchView.setQuery(searchView.query, true) } } } }) } }
9432b5ca5ef96e93bf129a11a939d769469eb61d
[ "Kotlin", "Gradle" ]
17
Kotlin
yaroslav-hembik/TestApp
5c2c530215de4e1e7d4c76e531e8b6b55cd36d4d
a564a5a80e11586e352a4bd72a5bc8b0d47ce635
refs/heads/main
<file_sep>using System.ComponentModel.DataAnnotations; namespace Commander.Dtos { //se usa la notacion de datos para validar //cuando se envia al api la data incompleta //como resultado devolvera un 400 //NOTA PARA MI: NUNCA RETORNES UN 500 public class CommandCreateDto { [Required] [MaxLength(250)] public string HowTo { get; set; } [Required] public string Line { get; set; } [Required] public string Platform { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Mvc; using Commander.Models; using Commander.Data; using Comander.Data; using AutoMapper; using Commander.Dtos; using Microsoft.AspNetCore.JsonPatch; namespace Commander.Controllers { //api/commands [Route("api/[controller]")] [ApiController] public class CommandsController : ControllerBase { private readonly IcommanderRepository _repository; private readonly IMapper _mapper; public CommandsController(IcommanderRepository repository , IMapper mapper) { _repository = repository; _mapper = mapper; } //GET api/commands [HttpGet] public ActionResult <IEnumerable<CommandReadDto>> GetAllCommands() { var commands = _repository.GetAllCommands(); return (commands != null) ? Ok(_mapper.Map<IEnumerable<CommandReadDto>>(commands)) : NotFound(); } //GET api/commands/{id} //GET api/commands/5 [HttpGet("{id}" , Name ="GetCommandById")] public ActionResult <CommandReadDto> GetCommandById(int id) { var command = _repository.GetCommandById(id); return (command != null) ? Ok(_mapper.Map<CommandReadDto>(command)) : NotFound(); } //POST api/commands [HttpPost] public ActionResult <CommandReadDto> CreateCommand(CommandCreateDto commandCreateDto) { var commandModel = _mapper.Map<Command>(commandCreateDto); _repository.CreateCommand(commandModel); _repository.SaveChanges(); var commandReadDto = _mapper.Map<CommandReadDto>(commandModel); //retornar 201 return CreatedAtRoute(nameof(GetCommandById) , new {Id = commandReadDto.Id} , commandReadDto); //asi retorno un 200 y todo a nivel basico //return Ok(commandReadDto); } //PUT api/commands/{id} //PUT api/commands/7 [HttpPut("{id}")] public ActionResult UpdateCommand(int id , CommandUpdateDto commandUpdateDto) { var commandModelFromRepo = _repository.GetCommandById(id); if(commandModelFromRepo == null) return NotFound(); //aqui se asigna la data _mapper.Map(commandUpdateDto , commandModelFromRepo); _repository.UpdateCommand(commandModelFromRepo); _repository.SaveChanges(); return NoContent(); } //PATH api/commands/{id} //PATH api/commands/5 /* [ { "op":"replace", "path":"/howto", "value":"some new value" }, { "op":"replace", "path":"/howto", "value":"some new value" }, ] */ [HttpPatch("{id}")] public ActionResult PartialCommandUpdate(int id , JsonPatchDocument<CommandUpdateDto> patchDoc) { var commandModelFromRepo = _repository.GetCommandById(id); if(commandModelFromRepo == null) return NotFound(); var commandToPatch = _mapper.Map<CommandUpdateDto>(commandModelFromRepo); patchDoc.ApplyTo(commandToPatch , ModelState); if(!TryValidateModel(commandToPatch)){ return ValidationProblem(ModelState); } //aqui se asigna la data _mapper.Map(commandToPatch , commandModelFromRepo); _repository.UpdateCommand(commandModelFromRepo); _repository.SaveChanges(); return NoContent(); } //DELETE api/commands/{id} //DELETE api/commands/3 [HttpDelete("{id}")] public ActionResult DeleteCommand(int id) { var commandModelFromRepo = _repository.GetCommandById(id); if(commandModelFromRepo == null) return NotFound(); _repository.DeleteCommand(commandModelFromRepo); _repository.SaveChanges(); return NoContent(); } } }
fce877ea69d7d01e081ba8c5466559b8ff98475e
[ "C#" ]
2
C#
mrPity28/NetCoreApiRest
ca5037331c46d112ca687fee633cd430d267c5f4
2f5c925284db823d5a087199f212804920f300c3
refs/heads/master
<repo_name>axcs1212/Animation-timer01<file_sep>/Animation timer01/ViewController.swift // // ViewController.swift // Animation timer01 // // Created by D7703_23 on 2018. 4. 5.. // Copyright © 2018년 D7703_23. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var myImageView: UIImageView! @IBOutlet weak var imgCounter: UILabel! var counter = 1 var change = 1 var check = false var mytimer = Timer() override func viewDidLoad() { super.viewDidLoad() imgCounter.text = String(counter) } @IBAction func play(_ sender: Any) { if change == 1{ mytimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(animation), userInfo: nil, repeats: true) change = 0 } else{ mytimer.invalidate() change = 1 } } @IBAction func stop(_ sender: Any) { mytimer.invalidate() } @objc func animation(){ //카운트가 5일때 1로 돌아가면서 타이머가 돌아감 // if counter == 5{ // counter = 1 // } else { // counter = counter + 1 // } //카운트가1일땐 증가하다가 5를만나면 내려가면서 타이머가돌아감 if counter == 5 { check = false } else if counter == 1 { check = true } if check == true { counter = counter + 1 } else if check == false{ counter = counter - 1 } myImageView.image = UIImage(named: "frame\(counter).png") imgCounter.text = String(counter) } }
ff3405b9f46d081c892f2097226a9f1947964ff0
[ "Swift" ]
1
Swift
axcs1212/Animation-timer01
141a28db09217b01811fc5b056ca4988d24af775
6659617164549f4f804ba58ea8da0bb778c61297
refs/heads/master
<file_sep>Parallelel Sorting by Regular Sampling ================================== Implementacion del algoritmo Parallel Sorting by Regular Sampling utilizando MPI. <file_sep>psrs: psrs.c mpicc -o psrs psrs.c -Wall quickSort: quickSort.c gcc -o quickSort quickSort.c -Wall <file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> // Prototipos int *crearVector(int); void quickSort(int*, int, int); int particion(int*, int, int); int main(int argc, char *argv[]) { int tamanioVector; int *punteroVector = NULL; time_t comienzoOrdenamiento, finalOrdenamiento; if (argc == 2) { tamanioVector = atoi(argv[1]); } else { printf("ERROR >> El programa debe ser invocado con un parametro que indique el tamanio del vector.\n"); return 1; } punteroVector = crearVector(tamanioVector); comienzoOrdenamiento = time(NULL); quickSort(punteroVector, 0, tamanioVector - 1); finalOrdenamiento = time(NULL); printf("%d, %f\n", tamanioVector, difftime(finalOrdenamiento, comienzoOrdenamiento)); return 0; } int *crearVector(int tamanio) { int *punteroVector = NULL; int i; if (tamanio <= 0) { printf("ERROR >> El tamanio del vector debe ser mayor a cero.\n"); return NULL; } else { punteroVector = (int*) calloc(tamanio, sizeof (int)); if (punteroVector == NULL) { printf("ERROR >> No se pudo crear el vector.\n"); return NULL; } else { srand(time(NULL)); for (i = 0; i < tamanio; i++) { punteroVector[i] = rand() % (tamanio + 1); } return punteroVector; } } } void quickSort(int *punteroVector, int izq, int der) { int j; if (izq < der) { j = particion(punteroVector, izq, der); quickSort(punteroVector, izq, j - 1); quickSort(punteroVector, j + 1, der); } } int particion(int *punteroVector, int izq, int der) { int pivot, i, j, t; pivot = punteroVector[izq]; i = izq; j = der + 1; while (1) { do ++i; while (punteroVector[i] <= pivot && i <= der); do --j; while (punteroVector[j] > pivot); if (i >= j) break; t = punteroVector[i]; punteroVector[i] = punteroVector[j]; punteroVector[j] = t; } t = punteroVector[izq]; punteroVector[izq] = punteroVector[j]; punteroVector[j] = t; return j; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <time.h> // Prototipos int *crearVector(int); void quickSort(int*, int, int); int particion(int*, int, int); int main(int argc, char *argv[]) { int numeroNodo, numeroProcesos; int tamanioVector; int *punteroVector = NULL; int j; int *sendcounts; int *displs; int *bufferRecepcion; int *localRegularSamples; int *gatheredRegularSamples; int *pivots; int remaining; int sum = 0; int w, p; time_t comienzoOrdenamiento, finalOrdenamiento; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &numeroNodo); MPI_Comm_size(MPI_COMM_WORLD, &numeroProcesos); // Se controla que el programa sea invocado con un argumento que indique la cantidad de elementos a ordenar. // En caso de encontrarlo asigna la variable correspondiente. Si no existe este parametro se muestra un mensaje de error y se termina la ejecucion del programa. if (argc == 2) { tamanioVector = atoi(argv[1]); } else { MPI_Finalize(); printf("ERROR >> El programa debe ser invocado con un parametro que indique el tamanio del vector.\n"); return 1; } // El proceso maestro crea el vector de elementos a ordenar. if (numeroNodo == 0) { punteroVector = crearVector(tamanioVector); } /// -------------------------------------------------------- /// Comienza Fase 1 de Parallel Sorting by Regular Sampling /// -------------------------------------------------------- // Se toma el tiempo en el que comienza efectivamente el algortimo psrs. comienzoOrdenamiento = time(NULL); sendcounts = malloc(sizeof (int)*numeroProcesos); displs = malloc(sizeof (int)*numeroProcesos); localRegularSamples = malloc(sizeof (int)*numeroProcesos); w = (int) (tamanioVector / (numeroProcesos * numeroProcesos)); p = (int) (numeroProcesos / 2); // Realizo el calculo de la cantidad de items que debo distribuir a cada proceso. remaining = tamanioVector % numeroProcesos; for (j = 0; j < numeroProcesos; j++) { sendcounts[j] = tamanioVector / numeroProcesos; if (remaining > 0) { sendcounts[j]++; remaining--; } displs[j] = sum; sum += sendcounts[j]; } bufferRecepcion = (int*) malloc(sizeof (int)*sendcounts[numeroNodo]); // Notar que se utiliza la comunicacion en grupo Scatterv ya que las porciones a distribuir entre los procesos pueden no ser del mismo tamanio. MPI_Scatterv(punteroVector, sendcounts, displs, MPI_INT, bufferRecepcion, sendcounts[numeroNodo], MPI_INT, 0, MPI_COMM_WORLD); if (numeroNodo == 0) { free(punteroVector); } free(displs); quickSort(bufferRecepcion, 0, sendcounts[numeroNodo] - 1); // Notar que comienza en '0' y no en '1' como en el paper debido a que en C los arreglos comienzan en la posicion '0'. int aux = 0; // Cada proceso construye el vector con las muestras regulares locales a enviar al proceso maestro for (j = 0; j < numeroProcesos; j++) { localRegularSamples[j] = bufferRecepcion[aux]; aux += w; } /// -------------------------------------------------------- /// Fin Fase 1 de Parallel Sorting by Regular Sampling /// -------------------------------------------------------- /// -------------------------------------------------------- /// Comienza Fase 2 de Parallel Sorting by Regular Sampling /// -------------------------------------------------------- pivots = malloc(sizeof (int)*(numeroProcesos - 1)); if (numeroNodo == 0) { gatheredRegularSamples = malloc(sizeof (int)*numeroProcesos * numeroProcesos); } MPI_Gather(localRegularSamples, numeroProcesos, MPI_INT, gatheredRegularSamples, numeroProcesos, MPI_INT, 0, MPI_COMM_WORLD); //Recordar que el primer parametro es la direccion al dato a ser enviado, por ello debe ser un parametro por referencia. free(localRegularSamples); if (numeroNodo == 0) { quickSort(gatheredRegularSamples, 0, (numeroProcesos * numeroProcesos) - 1); // Notar que se resta uno a 'p' ya que la primera posicion del arreglo en C no se encuentra en '1' (como se considera en el paper) sino en '0'. aux = p - 1; // El proceso maestro construye el vector con los pivotes a enviar a todos los procesos. for (j = 0; j < (numeroProcesos - 1); j++) { aux += numeroProcesos; pivots[j] = gatheredRegularSamples[aux]; } } if (numeroNodo == 0) { free(gatheredRegularSamples); } MPI_Bcast(pivots, numeroProcesos - 1, MPI_INT, 0, MPI_COMM_WORLD); /// -------------------------------------------------------- /// Fin Fase 2 de Parallel Sorting by Regular Sampling /// -------------------------------------------------------- /// -------------------------------------------------------- /// Comienza Fase 3 de Parallel Sorting by Regular Sampling /// -------------------------------------------------------- int *sendCountsAllToAll = malloc(sizeof (int)*numeroProcesos); int *sendDisplAllToAll = malloc(sizeof (int)*numeroProcesos); int desplazamiento = 0; int cantidadItems = 0; int i = 0; // Cada proceso determina cuantos items debe enviar a cada proceso y el desplazamiento de la tabla. Utilizo los pivotes para ello. for (j = 0; j < (numeroProcesos - 1); j++) { sendDisplAllToAll[j] = desplazamiento; while ((i < sendcounts[numeroNodo]) && (bufferRecepcion[i] <= pivots[j])) { cantidadItems++; i++; } sendCountsAllToAll[j] = cantidadItems; desplazamiento += cantidadItems; cantidadItems = 0; } free(pivots); // Notar que en la iteracion anterior no se consideran los items que son mayores al ultimo pivot. Por ello se calculo aqui. sendDisplAllToAll[j] = desplazamiento; while (i < sendcounts[numeroNodo]) { cantidadItems++; i++; } free(sendcounts); sendCountsAllToAll[j] = cantidadItems; // Como cada proceso conoce cuanto debe enviar a cada proceso pero no conoce cuantos items va a recibir de cada proceso, todos los procesos deben informar cuanto enviaran a cada uno. int *recvCountsAllToAll = malloc(sizeof (int)*numeroProcesos); int *recvDisplAllToAll = malloc(sizeof (int)*numeroProcesos); for (j = 0; j < numeroProcesos; j++) { if (numeroNodo != j) { MPI_Send(&sendCountsAllToAll[j], 1, MPI_INT, j, 1, MPI_COMM_WORLD); } } for (j = 0; j < numeroProcesos; j++) { if (numeroNodo != j) { MPI_Recv(&recvCountsAllToAll[j], 1, MPI_INT, j, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } else { recvCountsAllToAll[j] = sendCountsAllToAll[j]; } } int desplazamientoRecvCount = 0; for (j = 0; j < numeroProcesos; j++) { recvDisplAllToAll[j] = desplazamientoRecvCount; desplazamientoRecvCount += recvCountsAllToAll[j]; } int cantidadFinalRecivida = 0; for (j = 0; j < numeroProcesos; j++) { cantidadFinalRecivida += recvCountsAllToAll[j]; } int *recvFinal = malloc(sizeof (int)*cantidadFinalRecivida); MPI_Alltoallv(bufferRecepcion, sendCountsAllToAll, sendDisplAllToAll, MPI_INT, recvFinal, recvCountsAllToAll, recvDisplAllToAll, MPI_INT, MPI_COMM_WORLD); free(recvDisplAllToAll); free(recvCountsAllToAll); free(sendDisplAllToAll); free(sendCountsAllToAll); free(bufferRecepcion); /// -------------------------------------------------------- /// Fin Fase 3 de Parallel Sorting by Regular Sampling /// -------------------------------------------------------- /// -------------------------------------------------------- /// Comienza Fase 4 de Parallel Sorting by Regular Sampling /// -------------------------------------------------------- quickSort(recvFinal, 0, cantidadFinalRecivida - 1); if (numeroNodo != 0) { MPI_Send(&cantidadFinalRecivida, 1, MPI_INT, 0, 1, MPI_COMM_WORLD); } int *recvCountsGather = malloc(sizeof (int)*numeroProcesos); int *recvDisplGather = malloc(sizeof (int)*numeroProcesos); if (numeroNodo == 0) { int desplazamientoGather = 0; recvCountsGather[0] = cantidadFinalRecivida; recvDisplGather[0] = desplazamientoGather; desplazamientoGather += recvCountsGather[0]; // Notar que la iteracion comienza en 1, ya que el proceso maestro ya tiene la informacion relevante. for (j = 1; j < numeroProcesos; j++) { MPI_Recv(&recvCountsGather[j], 1, MPI_INT, j, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); recvDisplGather[j] = desplazamientoGather; desplazamientoGather += recvCountsGather[j]; } } // Vuelvo a crear espacio para todos los elementos en el proceso maestro. // Notar que para optimizarlo una vez que los elementos se distribuyen con la funcion de comunicacion en grupo Scatterv el espacio del vector con los elementos a ordenar es borrado. // Por ello es necesario crear espacio para recibir los vectores ordenados provenientes de los distintos procesos. if (numeroNodo == 0) { punteroVector = (int*) calloc(tamanioVector, sizeof (int)); if (punteroVector == NULL) { printf("ERROR >> No se pudo crear el vector.\n"); return 1; } } MPI_Gatherv(recvFinal, cantidadFinalRecivida, MPI_INT, punteroVector, recvCountsGather, recvDisplGather, MPI_INT, 0, MPI_COMM_WORLD); free(recvDisplGather); free(recvCountsGather); free(recvFinal); if (numeroNodo == 0) { free(punteroVector); } // Se toma el tiempo en el que termina efectivamente el algortimo psrs. finalOrdenamiento = time(NULL); /// -------------------------------------------------------- /// Fin Fase 4 de Parallel Sorting by Regular Sampling /// -------------------------------------------------------- // Cada proceso realiza el calculo del tiempo transcurrido. double tiempoTranscurrido = difftime(finalOrdenamiento, comienzoOrdenamiento); // Todos los procesos excepto el maestro envian un mensaje al maestro con el tiempo transcurrido. if (numeroNodo != 0) { MPI_Send(&tiempoTranscurrido, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); } // El proceso maestro recibe los tiempos transcurridos de los demas procesos. if (numeroNodo == 0) { double *todosTiemposTranscurridos = malloc(sizeof (double)*numeroProcesos); // El proceso maestro conoce localmente cuanto tardo el mismo. Por ello dicha entrada de la tabla es completada directamente con esta informacion. todosTiemposTranscurridos[0] = tiempoTranscurrido; for (j = 1; j < numeroProcesos; j++) { MPI_Recv(&todosTiemposTranscurridos[j], 1, MPI_DOUBLE, j, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } printf("%d, %d", numeroProcesos, tamanioVector); for (j = 0; j < numeroProcesos; j++) { printf(", %f", todosTiemposTranscurridos[j]); } printf("\n"); } MPI_Finalize(); return 0; } int *crearVector(int tamanio) { int *punteroVector = NULL; int i; if (tamanio <= 0) { printf("ERROR >> El tamanio del vector debe ser mayor a cero.\n"); return NULL; } else { punteroVector = (int*) calloc(tamanio, sizeof (int)); if (punteroVector == NULL) { printf("ERROR >> No se pudo crear el vector.\n"); return NULL; } else { srand(time(NULL)); for (i = 0; i < tamanio; i++) { punteroVector[i] = rand() % (tamanio + 1); } return punteroVector; } } } void quickSort(int *punteroVector, int izq, int der) { int j; if (izq < der) { j = particion(punteroVector, izq, der); quickSort(punteroVector, izq, j - 1); quickSort(punteroVector, j + 1, der); } } int particion(int *punteroVector, int izq, int der) { int pivot, i, j, t; pivot = punteroVector[izq]; i = izq; j = der + 1; while (1) { do ++i; while (punteroVector[i] <= pivot && i <= der); do --j; while (punteroVector[j] > pivot); if (i >= j) break; t = punteroVector[i]; punteroVector[i] = punteroVector[j]; punteroVector[j] = t; } t = punteroVector[izq]; punteroVector[izq] = punteroVector[j]; punteroVector[j] = t; return j; }
a100f8bea9b1b8e331c8593b39c0aa500d2b4913
[ "Markdown", "C", "Makefile" ]
4
Markdown
jmloyola/ParallelelSortingByRegularSampling
0b8ef4af3cd4eb8b11525b3c5abcb1666783d760
fc6c87b43317ce11453e6a8f3888e7f51c217ce9
refs/heads/master
<file_sep>import numpy as np import hyperparameter as hp import preprocess class Batch(object): def __init__(self, preprocess): self.preprocess = preprocess self.batchMatrix = np.zeros((hp.BATCH_SIZE, hp.SEQUENCE_LENGTH), dtype=np.int32) def createBatchMatrix(self, data): indexedData = self.preprocess.indexData(data) self.batchMatrix = np.array(indexedData) print("crated batch matrix") return self.batchMatrix class Batcher(object): def __init__(self,preprocess): self.preprocess = preprocess self.batch = Batch(self.preprocess) self.dataGen = self.preprocess.dataGen self.batchGen = self.batchGenerator() def batchGenerator(self): for i in range(0, hp.DATA_SIZE, hp.BATCH_SIZE): data = next(self.dataGen) indexedBatch = self.batch.createBatchMatrix(data) yield indexedBatch def cevap(matrix): row_length = len(matrix[0]) col_length = len(matrix) coor_to_index = lambda i, j: i * row_length + j index_to_coor = lambda node: (int(node / row_length), node % row_length) adj_list = {} wall_list = [] for i in range(col_length): for j in range(row_length): index = coor_to_index(i, j) if matrix[i][j] == 1: wall_list.append(index) adj_list[index] = neighbours_and_weights(index, matrix) initial_distances = shortest_path(matrix, 1) initial_shortest_path = initial_distances[-1] shortest = initial_shortest_path for wall in wall_list: broken_wall = initial_distances[wall] - 99 if broken_wall > initial_shortest_path: continue wall_i, wall_j = index_to_coor(wall) sliced_matrix = [matrix[i][wall_j:] for i in range(wall_i,col_length)] new_attempt = shortest_path(sliced_matrix, broken_wall)[-1] if new_attempt < shortest: shortest = new_attempt return shortest def shortest_path(matrix, initial_weight): row_length = len(matrix[0]) col_length = len(matrix) size = row_length * col_length # index = lambda i, j: i * row_length + j visited = size * [False] distances = size * [MAX_INT] # min heap (weight,index) pq = [(initial_weight, 0)] distances[0] = initial_weight heapq.heapify(pq) while pq: cur_dist, cur_node = heapq.heappop(pq) if not visited[cur_node]: visited[cur_node] = True adj_list = neighbours_and_weights(cur_node, matrix) for node, weight in adj_list.items(): if visited[node]: continue old_weight = distances[node] new_weight = cur_dist + weight if new_weight < old_weight: distances[node] = new_weight heapq.heappush(pq, (distances[node], node)) return distances def neighbours_and_weights(index, matrix): index_to_coor = lambda node: (int(node / row_length), node % row_length) coor_to_index = lambda i, j: i * row_length + j weight = lambda x: 100 if x == 1 else 1 row_length = len(matrix[0]) col_length = len(matrix) i, j = index_to_coor(index) is_one = matrix[i][j] adj = {} if i > 0: adj[coor_to_index(i - 1, j)] = 100 if is_one else weight(matrix[i - 1][j]) if j > 0: adj[coor_to_index(i, j - 1)] = 100 if is_one else weight(matrix[i][j - 1]) if i + 1 < col_length: adj[coor_to_index(i + 1, j)] = 100 if is_one else weight(matrix[i + 1][j]) if j + 1 < row_length: adj[coor_to_index(i, j + 1)] = 100 if is_one else weight(matrix[i][j + 1]) return adj matrix = [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]] matrx = [[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]] print(cevap(matrix)) # print(shortest_path([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 1, 0], [1, 1, 1, 0]])) <file_sep>import tensorflow as tf import hyperparameter as hp import LSTM import batch import preprocess class Encoder(object): def __init__(self): self.preprocess = preprocess.Preprocess() self.batcher = batch.Batcher(self.preprocess) self.batchGen = self.batcher.batchGen self.embeddingMatrix = self.preprocess.embeddingMatrix def initializeStates(self): prevHiddenState = tf.random_normal(shape=(hp.HIDDEN_SIZE, 1)) prevCellState = tf.random_normal(shape=(hp.HIDDEN_SIZE, 1)) return prevHiddenState, prevCellState def runGraph(self): encoderCell = LSTM.Cell() hiddenState = encoderCell.calculateStates() prevHiddenState, prevCellState = self.initializeStates() sess = tf.Session() init = tf.global_variables_initializer() init = tf. sess.run(init) hasMoreBatch = True while hasMoreBatch: try: currentBatch = next(self.batchGen) embeddedInput = tf.nn.embedding_lookup(self.embeddingMatrix, currentBatch) for sentence in embeddedInput: feedDict = {encoderCell.input: sentence, encoderCell.prevCellState: prevCellState, encoderCell.prevHiddenState: prevHiddenState} prevHiddenStateForSample = sess.run([hiddenState], feed_dict=feedDict) print(prevHiddenStateForSample) hasMoreBatch = False except: hasMoreBatch = False print("Run out of batches !") encoder = Encoder() encoder.runGraph()<file_sep>def run_RNN(self): hidden_state = self.create_RNN() previous_state = np.zeros((self.hidden_size, 1)) cell_state = np.zeros((self.hidden_size, 1)) sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) has_more_batch = True while has_more_batch: try: current_batch = next(self.form_batch) for row_number, row in enumerate(current_batch): embedded_word_vectors = np.zeros((self.max_seq_length, self.embedding_size), dtype=np.float32) for i, index in enumerate(row): embedded_word_vectors[i] = self.embedding_matrix[index] feed_dict = {self.inputs: np.transpose(embedded_word_vectors), self.prev_hidden_state_as_input: previous_state, self.cell_prev_state: cell_state} previous_hidden_state_for_sample = sess.run([hidden_state], feed_dict=feed_dict) print("Row number {}".format(row_number + 1)) print(previous_hidden_state_for_sample) print("==============================\n") has_more_batch = False except: has_more_batch = False logging.info("No more batches")<file_sep>BATCH_SIZE = 32 EMBEDDING_SIZE = 128 VOCAB_PATH = "data/all news.txt" SEQUENCE_LENGTH = 16 HIDDEN_SIZE = 256 DATA_SIZE = 20000 DATA_PATH = "data/all news.txt" import numpy as np # # # temp = [1,2,3,4] # temp = temp + [BATCH_SIZE] * 5 # # print(temp) # for i in range(0, DATA_SIZE, hp.BATCH_SIZE): # yield data[i:i + hp.BATCH_SIZE] # # # def splitAndProcess(DATA_PATH): # gen = readLargeFile(DATA_PATH) # for i in range(0, DATA_SIZE, hp.BATCH_SIZE): # data = preprocess(next(gen), SEQ_LEN) # # TODO : ? # random.shuffle(data) # yield data # list = [[1,2,3],[2,3,4],[5,6,7]] # print(list) # list = np.array(list) # print (list) # # # from batcher import Batcher # from preprocess import Preprocesser # import tensorflow as tf # import json # import numpy as np # # #batch = Batcher().get_batch() # # with open('hyperparams.json') as my_json: # parsed = json.load(my_json) # # SENT_LEN = parsed["preprocesser"]["nn_input_size"] # BATCH_SIZE= parsed["batcher"]["batch_size"] # EYE_SIZE = parsed["preprocesser"]["vocab_size"] # EMBEDDING_SIZE = 128 # HID_SIZE = 256 # ATTENTION = True # BEAMER_ACTIVE = True # BEAM_SIZE = 3 # # CONCAT_SIZE = EMBEDDING_SIZE+HID_SIZE # DECODER_CONCAT_SIZE = EMBEDDING_SIZE+HID_SIZE if ATTENTION is False else EMBEDDING_SIZE+HID_SIZE+SENT_LEN # # class Autoencoder(): # # def __init__(self): # self.batch = Batcher().get_batch() # self.preper= Preprocesser() # self.sess = tf.Session(config=tf.ConfigProto(inter_op_parallelism_threads=1,intra_op_parallelism_threads=1)) # self.input_placeholder, self.loss, self.summary_merge, self.generateds = self.create_graph() # self.train_step = 0 # self.train_writer = tf.summary.FileWriter('./train', self.sess.graph) # self.optimizer = tf.train.AdamOptimizer() # self.gradient_limit = tf.constant(6.0, dtype=tf.float32, name='grad_limit') # grads_and_vars = self.optimizer.compute_gradients(self.loss) # # clipped_grads_and_vars = [] # for grad, var in grads_and_vars: # clipped_grad = tf.clip_by_value(grad, -self.gradient_limit, self.gradient_limit) # clipped_grads_and_vars.append((clipped_grad, var)) # self.apply_grads = self.optimizer.apply_gradients(clipped_grads_and_vars) # self.sess.run(tf.global_variables_initializer()) # @staticmethod # def create_placeholders(): # # input = tf.placeholder(shape=[BATCH_SIZE,SENT_LEN],dtype=tf.int64) # return input # # def create_graph(self): # # input = self.create_placeholders() # # with tf.name_scope("ENCODER"): # W_embedd = tf.Variable(tf.random_normal([EMBEDDING_SIZE,EYE_SIZE]),name="W_embedd") # b_embedd = tf.Variable(tf.random_normal([EMBEDDING_SIZE, 1]), name="b_embedd") # # W_forget = tf.Variable(tf.random_normal([HID_SIZE,CONCAT_SIZE]),name="W_forget") # b_forget = tf.Variable(tf.zeros([HID_SIZE,1]),name="b_forget") # # W_input = tf.Variable(tf.random_normal([HID_SIZE,CONCAT_SIZE]),name="W_input") # b_input = tf.Variable(tf.zeros([HID_SIZE,1]),name="b_input") # # W_Cell = tf.Variable(tf.random_normal([HID_SIZE, CONCAT_SIZE]),name="W_cell") # b_Cell = tf.Variable(tf.zeros([HID_SIZE,1]),name="b_cell") # # W_output = tf.Variable(tf.random_normal([HID_SIZE, CONCAT_SIZE]),name="W_output") # b_output = tf.Variable(tf.zeros([HID_SIZE,1]),name="b_output") # # prev_hidden_st = tf.Variable(tf.zeros([HID_SIZE, BATCH_SIZE]),dtype=tf.float32,name="prev_hidden", trainable=False) # prev_cell_st = tf.Variable(tf.zeros([HID_SIZE, BATCH_SIZE]),dtype=tf.float32,name="prev_cell_stat", trainable=False) # # eh_list = [] # for t,token in enumerate(tf.split(input,SENT_LEN,axis=1)): # loop on words in sentences # # embedded_word = tf.sigmoid(tf.matmul(W_embedd,tf.reshape(tf.one_hot(token,EYE_SIZE),[EYE_SIZE,BATCH_SIZE]))+b_embedd) # Z_conc = tf.concat([embedded_word,prev_hidden_st],0) # Z in diagram # # forget_t = tf.sigmoid(tf.matmul(W_forget,Z_conc)+b_forget) # (256,1) # input_t = tf.sigmoid(tf.matmul(W_input,Z_conc)+b_input) # (256,1) # cell_t = tf.tanh(tf.matmul(W_Cell,Z_conc)+b_Cell) # (256,1) # output_t = tf.sigmoid(tf.matmul(W_output,Z_conc)+b_output) # (256,1) # # cell_state = tf.add(tf.multiply(prev_cell_st,forget_t),tf.multiply(input_t,cell_t)) # hidden_state= tf.multiply(output_t,tf.tanh(cell_state)) # prev_cell_st = cell_state # prev_hidden_st = hidden_state # eh_list.append(hidden_state) # # final_encoded_state = prev_hidden_st # # ### DECODER # with tf.name_scope("DECODER"): # start_seq_embedd = tf.constant(0.0,shape=[EMBEDDING_SIZE,BATCH_SIZE],dtype=tf.float32,name="Start_Sequence") # prev_hidden_st = final_encoded_state #final encoded go there; # prev_cell_st = tf.Variable(tf.zeros([HID_SIZE, BATCH_SIZE]), dtype=tf.float32, name="prev_cell_stat",trainable=False) # # W_embedd_dec = tf.Variable(tf.random_normal([EMBEDDING_SIZE, EYE_SIZE]), name="W_embedd_decoder") # b_embedd_dec = tf.Variable(tf.random_normal([EMBEDDING_SIZE, 1]), name="b_embedd_decoder") # # W_forget_dec = tf.Variable(tf.random_normal([HID_SIZE, DECODER_CONCAT_SIZE]), name="W_forget_decoder") # b_forget_dec = tf.Variable(tf.zeros([HID_SIZE, 1]), name="b_forget_decoder") # # W_input_dec = tf.Variable(tf.random_normal([HID_SIZE, DECODER_CONCAT_SIZE]), name="W_input_decoder") # b_input_dec = tf.Variable(tf.zeros([HID_SIZE, 1]), name="b_input_decoder") # # W_Cell_dec = tf.Variable(tf.random_normal([HID_SIZE, DECODER_CONCAT_SIZE]), name="W_cell_decoder") # b_Cell_dec = tf.Variable(tf.zeros([HID_SIZE, 1]), name="b_cell_decoder") # # W_output_dec = tf.Variable(tf.random_normal([HID_SIZE, DECODER_CONCAT_SIZE]), name="W_output_decoder") # b_output_dec = tf.Variable(tf.zeros([HID_SIZE, 1]), name="b_output_decoder") # # W_prediction = tf.Variable(tf.random_normal([EYE_SIZE,HID_SIZE]),name="W_prediction") # b_prediction = tf.Variable(tf.zeros([EYE_SIZE,1]),name="b_prediction") # # Generated_sentences = [] # #Start with propagating the start word # if ATTENTION is False: # Z_conc = tf.concat([start_seq_embedd, prev_hidden_st], 0) # Z in diagram # else: # context_vector = tf.stack([tf.matmul(tf.transpose(tf.Variable(tf.zeros([HID_SIZE, 1]),dtype=tf.float32)),eh_x) for eh_x in eh_list]) # Z_conc = tf.concat([start_seq_embedd,tf.reshape(context_vector,[SENT_LEN,BATCH_SIZE]),prev_hidden_st],0) # print("sing itt!") # # forget_t = tf.sigmoid(tf.matmul(W_forget_dec, Z_conc) + b_forget_dec) # (256,1) # input_t = tf.sigmoid(tf.matmul(W_input_dec, Z_conc) + b_input_dec) # (256,1) # cell_t = tf.tanh(tf.matmul(W_Cell_dec, Z_conc) + b_Cell_dec) # (256,1) # output_t = tf.sigmoid(tf.matmul(W_output_dec, Z_conc) + b_output_dec) # (256,1) # # cell_state = tf.add(tf.multiply(prev_cell_st, forget_t), tf.multiply(input_t, cell_t)) # hidden_state = tf.multiply(output_t, tf.tanh(cell_state)) # # logits = tf.add(tf.matmul(W_prediction, hidden_state),b_prediction) # normalized_probs = tf.nn.softmax(logits,axis=0) #apply softmax to axis with 250.000 elems # # prev_cell_st = cell_state # prev_hidden_st = hidden_state # #here it comes a loop that generates tokens # for t in range(SENT_LEN): # loop words times in sentences # embedded_word = tf.sigmoid(tf.matmul(W_embedd_dec, tf.reshape(tf.one_hot(tf.argmax(normalized_probs), EYE_SIZE), [EYE_SIZE, BATCH_SIZE])) + b_embedd_dec) # # if ATTENTION is False: # Z_conc = tf.concat([embedded_word, prev_hidden_st], 0) # Z in diagram # else: # context_vector = tf.stack([tf.matmul(tf.transpose(tf.Variable(tf.zeros([HID_SIZE, 1]), dtype=tf.float32)), eh_x) for eh_x in eh_list]) # Z_conc = tf.concat([embedded_word, tf.reshape(context_vector, [SENT_LEN, BATCH_SIZE]), prev_hidden_st], 0) # # forget_t = tf.sigmoid(tf.matmul(W_forget_dec, Z_conc) + b_forget_dec) # (256,1) # input_t = tf.sigmoid(tf.matmul(W_input_dec, Z_conc) + b_input_dec) # (256,1) # cell_t = tf.tanh(tf.matmul(W_Cell_dec, Z_conc) + b_Cell_dec) # (256,1) # output_t = tf.sigmoid(tf.matmul(W_output_dec, Z_conc) + b_output_dec) # (256,1) # # cell_state = tf.add(tf.multiply(prev_cell_st, forget_t), tf.multiply(input_t, cell_t)) # hidden_state = tf.multiply(output_t, tf.tanh(cell_state)) # # logits = tf.add(tf.matmul(W_prediction, hidden_state), b_prediction) # normalized_probs = tf.nn.softmax(logits, axis=0) # apply softmax to axis with vocab_size elems # # Generated_sentences.append(normalized_probs) # prev_cell_st = cell_state # prev_hidden_st = hidden_state # Generated_sentences = tf.stack(Generated_sentences) # # with tf.name_scope("BEAMER"): # prev_hidden_st = final_encoded_state # final encoded go there; # prev_cell_st = tf.Variable(tf.zeros([HID_SIZE, BATCH_SIZE]), dtype=tf.float32, name="prev_cell_stat",trainable=False) # if ATTENTION is False: #update z_conc with start sequence # Z_conc = tf.concat([start_seq_embedd, prev_hidden_st], 0) # Z in diagram # else: # context_vector = tf.stack([tf.matmul(tf.transpose(tf.Variable(tf.zeros([HID_SIZE, 1]),dtype=tf.float32)),eh_x) for eh_x in eh_list]) # Z_conc = tf.concat([start_seq_embedd,tf.reshape(context_vector,[SENT_LEN,BATCH_SIZE]),prev_hidden_st],0) # print("sing itt!") # forget_t = tf.sigmoid(tf.matmul(W_forget_dec, Z_conc) + b_forget_dec) # (256,1) # input_t = tf.sigmoid(tf.matmul(W_input_dec, Z_conc) + b_input_dec) # (256,1) # cell_t = tf.tanh(tf.matmul(W_Cell_dec, Z_conc) + b_Cell_dec) # (256,1) # output_t = tf.sigmoid(tf.matmul(W_output_dec, Z_conc) + b_output_dec) # (256,1) # # cell_state = tf.add(tf.multiply(prev_cell_st, forget_t), tf.multiply(input_t, cell_t)) # hidden_state = tf.multiply(output_t, tf.tanh(cell_state)) # # logits = tf.add(tf.matmul(W_prediction, hidden_state), b_prediction) # normalized_probs = tf.nn.softmax(logits, axis=0) # apply softmax to axis with 250.000 elems # prev_cell_st_list = [cell_state for i in range(BEAM_SIZE)] # every prevs should be kept in list since we'll use them in next step # prev_hidden_st_list = [hidden_state for i in range(BEAM_SIZE)] # top_vals_list = [] # top_indices_list = [] # # top_indices = [0 for i in range(BATCH_SIZE)] # top_vals = [0 for i in range(BATCH_SIZE)] # for cnt, sent_prob_vector in enumerate(tf.split(normalized_probs,BATCH_SIZE,axis=1)): #find top 3 probs for every sentence # top_vals[cnt], top_indices[cnt] = tf.nn.top_k(tf.reshape(sent_prob_vector, [EYE_SIZE]), k=3) # # top_vals_list.append(top_vals) # top_indices_list.append(top_indices) # # top_stacked = tf.stack(top_indices) # 32x3 tensor includes top 3 index of every sentence # for t in range(SENT_LEN): # loop words times in sentences # normalized_probs = [] # for cnt, top_elem in enumerate(tf.split(top_stacked,BEAM_SIZE,1)): # embedded_word = tf.sigmoid(tf.matmul(W_embedd_dec, tf.reshape(tf.one_hot(top_elem, EYE_SIZE), [EYE_SIZE, BATCH_SIZE])) + b_embedd_dec) # # if ATTENTION is False: # Z_conc = tf.concat([embedded_word, prev_hidden_st_list[cnt]], 0) # Z in diagram # else: # context_vector = tf.stack([tf.matmul(tf.transpose(tf.Variable(tf.zeros([HID_SIZE, 1]), dtype=tf.float32)), eh_x) for eh_x in eh_list]) # Z_conc = tf.concat([embedded_word, tf.reshape(context_vector, [SENT_LEN, BATCH_SIZE]), prev_hidden_st_list[cnt]], 0) # # forget_t = tf.sigmoid(tf.matmul(W_forget_dec, Z_conc) + b_forget_dec) # (256,1) # input_t = tf.sigmoid(tf.matmul(W_input_dec, Z_conc) + b_input_dec) # (256,1) # cell_t = tf.tanh(tf.matmul(W_Cell_dec, Z_conc) + b_Cell_dec) # (256,1) # output_t = tf.sigmoid(tf.matmul(W_output_dec, Z_conc) + b_output_dec) # (256,1) # # cell_state = tf.add(tf.multiply(prev_cell_st_list[cnt], forget_t), tf.multiply(input_t, cell_t)) # hidden_state = tf.multiply(output_t, tf.tanh(cell_state)) # # logits = tf.add(tf.matmul(W_prediction, hidden_state), b_prediction) # normalized_probs.append(tf.nn.softmax(logits, axis=0)) #append prob vector of all three candidates # prev_cell_st_list[cnt] = cell_state # prev_hidden_st_list[cnt] = hidden_state # # normalized_probs = tf.concat(normalized_probs,axis=0) # stack them and get a shape(3*V,batch_size) tensor # # for cnt, sent_prob_vector in enumerate(tf.split(normalized_probs, BATCH_SIZE, axis=1)): # find top 3 probs for every sentence # top_vals[cnt], top_indices[cnt] = tf.nn.top_k(tf.reshape(sent_prob_vector, [EYE_SIZE*BEAM_SIZE]), k=3) # top_stacked = tf.stack(top_indices) # 32x3 tensor includes top 3 index of every sentence # top_vals_list.append(tf.stack(top_vals)) # top_indices_list.append(tf.stack(top_indices)) # # # print("la") # # Target_sentences = [] # for t,token in enumerate(tf.split(input,SENT_LEN,axis=1)): # loop on words in sentences # Target_sentences.append(tf.reshape(tf.one_hot(token,EYE_SIZE),[EYE_SIZE,BATCH_SIZE])) # # Target_sentences = tf.stack(Target_sentences) # # Target_sentences = tf.reshape(Target_sentences,[BATCH_SIZE,SENT_LEN,EYE_SIZE]) # Generated_sentences = tf.reshape(Generated_sentences, [BATCH_SIZE, SENT_LEN, EYE_SIZE]) # # loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=Target_sentences, logits=Generated_sentences),axis=1) # tf.summary.scalar('lol_loss',tf.reduce_mean(loss)) # merged = tf.summary.merge_all() # return [input,loss,merged,Generated_sentences] # # def run_graph(self,batch): # input,loss_loses,mergy,_ = self.create_graph() # # with tf.Session() as sess: # writer = tf.summary.FileWriter('./graphs', sess.graph) # init = tf.global_variables_initializer() # sess.run(init) # dicty = {input: batch.reshape(32,30)} # # calced_loss = sess.run(loss_loses,feed_dict=dicty) # print("typeof: ",type(calced_loss)) # print("ov my loss shape: ", calced_loss.shape) # print(calced_loss) # # def train_on_batch(self,batch): # # dicty = {self.input_placeholder: batch.reshape(32,30)} # # my_summary, calced_loss, _, gen = self.sess.run([self.summary_merge, self.loss, self.apply_grads,self.generateds], feed_dict=dicty) # self.train_writer.add_summary(my_summary,self.train_step) # print(np.average(np.array(calced_loss))) # print("Step: ",self.train_step) # deced = np.argmax(gen,axis=2).reshape(BATCH_SIZE,SENT_LEN) # humanic_sent = [self.preper.index2word.get(i) for i in deced[0]] # input_sent = [self.preper.index2word.get(i) for i in batch[0]] # print(humanic_sent) # print(input_sent) # self.train_step += 1 # # def continuous_train(self): # # while True: # self.train_on_batch(next(self.batch)) # #print(next(self.batch)[0]) # if __name__ == '__main__': # # my_neuro = Autoencoder() # my_neuro.continuous_train()<file_sep>import tensorflow as tf import hyperparameter as hp class Cell(object): def __init__(self): self.input = tf.placeholder(shape=[hp.EMBEDDING_SIZE, hp.SEQUENCE_LENGTH], dtype=tf.int32, name='input') self.prevCellState = tf.placeholder(shape=(hp.HIDDEN_SIZE, hp.HIDDEN_SIZE + hp.EMBEDDING_SIZE), dtype=tf.int32) self.prevHiddenState = tf.placeholder(shape=(hp.HIDDEN_SIZE, hp.HIDDEN_SIZE + hp.EMBEDDING_SIZE), dtype=tf.int32) self.bInput, self.bOutput, self.bCell, self.bForget = self.initializeBias() self.wInput, self.wOutput, self.wCell, self.wForget = self.initializeWeight() # self.prevCellState, self.prevHiddenState = self.initializeStates() def initializeBias(self): bInput = tf.random_normal(shape=(hp.HIDDEN_SIZE, 1)) bOutput = tf.random_normal(shape=(hp.HIDDEN_SIZE, 1)) bCell = tf.random_normal(shape=(hp.HIDDEN_SIZE, 1)) bForget = tf.random_normal(shape=(hp.HIDDEN_SIZE, 1)) return bInput, bOutput, bCell, bForget # def initializeStates(self): # prevHiddenState = tf.random_normal(shape=(hp.HIDDEN_SIZE, 1)) # prevCellState = tf.random_normal(shape=(hp.HIDDEN_SIZE, 1)) # return prevCellState, prevHiddenState def initializeWeight(self): wInput = tf.random_normal(shape=(hp.HIDDEN_SIZE, hp.HIDDEN_SIZE + hp.EMBEDDING_SIZE)) wOutput = tf.random_normal(shape=(hp.HIDDEN_SIZE, hp.HIDDEN_SIZE + hp.EMBEDDING_SIZE)) wCell = tf.random_normal(shape=(hp.HIDDEN_SIZE, hp.HIDDEN_SIZE + hp.EMBEDDING_SIZE)) wForget = tf.random_normal(shape=(hp.HIDDEN_SIZE, hp.HIDDEN_SIZE + hp.EMBEDDING_SIZE)) return wInput, wOutput, wCell, wForget #TODO: parametrize et ! def calculateStates(self): for vector in self.input: Z = tf.concat([vector, self.prevHiddenState], axis=0) sForget = tf.sigmoid(tf.math.add(tf.matmul(self.wForget, Z), self.wForget)) sInput = tf.sigmoid(tf.math.add(tf.matmul(self.wInput, Z), self.bForget)) sDCell = tf.tanh(tf.math.add(tf.matmul(self.wCell, Z), self.bCell)) sCell = tf.math.add(tf.tensordot(sForget, self.prevCellState), tf.tensordot(sInput, sDCell)) sOutput = tf.sigmoid(tf.math.add(tf.matmul(self.wOutput, Z), self.bOutput)) sHidden = tf.tensordot(sOutput, tf.tanh(sCell)) self.prevCellState = sCell self.prevHiddenState = sHidden print("calculated states") return sHidden <file_sep>import json import random import re from string import punctuation import tensorflow as tf import numpy as np # from scipy import stats import hyperparameter as hp from tensorflow.contrib.rnn import LSTMCell # all words with frequencies in vocab data # # before batch # Batch size kadar data okuyor # Input must be a matrix indexed # ?? # with tf.Session() as sess: # sess.run(tf.global_variables_initializer()) # average_loss = 0.0 # for index in range(NUM_TRAIN_STEPS): # batch = batch_gen.next() # loss_batch, _ = sess.run([loss, optimizer], # feed_dict={input: batch[0], output: batch[1]}) # average_loss += loss_batch # if (index + 1) % 2000 == 0: # print('Average loss at step {}: {:5.1f}'.format(index + 1, average_loss / (index + 1))) import math def answer(height, nodes): root_node = math.pow(2, height) - 1 parent = -1 return [int(solution_helper(height, node, root_node, parent)) for node in nodes] def solution_helper(height, target_node, current_root, parent): left_most_node = math.pow(2, height) - 1 left_child = current_root - ((left_most_node + 1) / 2) right_child = current_root - 1 if target_node == current_root: return parent elif target_node <= left_child: return solution_helper(height - 1, target_node, left_child, current_root) else: return solution_helper(height - 1, target_node, right_child, current_root) from fractions import Fraction def solution(pegs): is_even = True if len(pegs) % 2 == 0 else False distances = [(-1) * (pegs[i] - pegs[i + 1]) for i in range(len(pegs) - 1)] flip = 1 sum = 0 for dist in distances: sum += (flip * dist) flip *= -1 possible_r = Fraction(2 * (float(sum) / 3 if is_even else sum)).limit_denominator() if is_valid_r(possible_r, distances): return [possible_r.numerator, possible_r.denominator] return [-1, -1] def is_valid_r(cand_r, distances): current_r = cand_r for dist in distances: next_r = dist - current_r if next_r < 1 or current_r < 1: return False current_r = next_r return True import heapq MAX_INT = 1000 def cevap(matrix): row_length = len(matrix[0]) col_length = len(matrix) coor_to_index = lambda i, j: i * row_length + j index_to_coor = lambda node: (int(node / row_length), node % row_length) adj_list = {} wall_list = [] for i in range(col_length): for j in range(row_length): index = coor_to_index(i, j) if matrix[i][j] == 1: wall_list.append(index) adj_list[index] = neighbours_and_weights(index, matrix) initial_distances = shortest_path(matrix, 1) initial_shortest_path = initial_distances[-1] shortest = initial_shortest_path if shortest == row_length + col_length: return shortest for wall in wall_list: broken_wall = initial_distances[wall] - 99 if broken_wall > initial_shortest_path: continue wall_i, wall_j = index_to_coor(wall) sliced_matrix = [matrix[i][wall_j:] for i in range(wall_i, col_length)] sliced_matrix[0][0] = 0 new_attempt = shortest_path(sliced_matrix, broken_wall)[-1] if new_attempt < shortest: shortest = new_attempt return shortest def shortest_path(matrix, initial_weight): row_length = len(matrix[0]) col_length = len(matrix) size = row_length * col_length # index = lambda i, j: i * row_length + j visited = size * [False] distances = size * [MAX_INT] # min heap (weight,index) pq = [(initial_weight, 0)] distances[0] = initial_weight heapq.heapify(pq) while pq: cur_dist, cur_node = heapq.heappop(pq) if not visited[cur_node]: visited[cur_node] = True adj_list = neighbours_and_weights(cur_node, matrix) for node, weight in adj_list.items(): if visited[node]: continue old_weight = distances[node] new_weight = cur_dist + weight if new_weight < old_weight: distances[node] = new_weight heapq.heappush(pq, (distances[node], node)) return distances def neighbours_and_weights(index, matrix): index_to_coor = lambda node: (int(node / row_length), node % row_length) coor_to_index = lambda i, j: i * row_length + j weight = lambda x: 100 if x == 1 else 1 row_length = len(matrix[0]) col_length = len(matrix) i, j = index_to_coor(index) is_one = matrix[i][j] adj = {} if i > 0: adj[coor_to_index(i - 1, j)] = 100 if is_one else weight(matrix[i - 1][j]) if j > 0: adj[coor_to_index(i, j - 1)] = 100 if is_one else weight(matrix[i][j - 1]) if i + 1 < col_length: adj[coor_to_index(i + 1, j)] = 100 if is_one else weight(matrix[i + 1][j]) if j + 1 < row_length: adj[coor_to_index(i, j + 1)] = 100 if is_one else weight(matrix[i][j + 1]) return adj matrix = [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]] matrx = [[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]] print(cevap(matrx)) # print(shortest_path([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 1, 0], [1, 1, 1, 0]])) <file_sep>import re # import scipy import tensorflow as tf import hyperparameter as hp #TODO: blank class Preprocess(object): alphabets = "([A-Za-z])" acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)" PAD_TOKEN = '[PAD]' UNKNOWN_TOKEN = '[UNK]' STOP_TOKEN = '[EOS]' def __init__(self): self.sentenceLengths = [] self.sequenceLength = 0 self.frequencyThreshold = 50 self.dataSize = 0 self.vocab = self.createVocab(hp.VOCAB_PATH) self.vocabToIndex = {word: index for index, word in enumerate(self.vocab)} self.indexToVocab = {index: word for index, word in enumerate(self.vocab)} self.embeddingMatrix = self.createEmbeddingMatrix() self.dataGen = self.readLargeFile(hp.DATA_PATH) def preprocess(self, sentences): #sentences = self.splitSentences(text) # words = re.findall(r"[\w']+", text) processedSentences = [] self.dataSize = len(sentences) # snippet numpy for sentence in sentences: sentence = self.removePunct(sentence) sentence = sentence.split() self.sentenceLengths.append(len(sentence)) temp = [word if word in self.vocabToIndex else self.UNKNOWN_TOKEN for word in sentence] temp.append(self.STOP_TOKEN) padCount = max(0, hp.SEQUENCE_LENGTH - len(temp)) temp = temp + [self.PAD_TOKEN] * padCount temp = temp[:hp.SEQUENCE_LENGTH] temp = " ".join(temp) processedSentences.append(temp) return processedSentences def splitSentences(self, text): text = " " + text + " " text = text.replace("\n", " ") text = re.sub("\s" + self.alphabets + "[.] ", " \\1<prd> ", text) text = re.sub(self.alphabets + "[.]" + self.alphabets + "[.]" + self.alphabets + "[.]", "\\1<prd>\\2<prd>\\3<prd>", text) text = re.sub(self.alphabets + "[.]" + self.alphabets + "[.]", "\\1<prd>\\2<prd>", text) text = re.sub(" " + self.alphabets + "[.]", " \\1<prd>", text) if "”" in text: text = text.replace(".”", "”.") if "\"" in text: text = text.replace(".\"", "\".") if "!" in text: text = text.replace("!\"", "\"!") if "?" in text: text = text.replace("?\"", "\"?") text = text.replace("...", ".") text = text.replace(":", ".") text = text.replace(".", ".<stop>") text = text.replace("?", "?<stop>") text = text.replace("!", "!<stop>") text = text.replace("<prd>", ".") sentences = text.split("<stop>") sentences = sentences[:-1] sentences = [s.strip() for s in sentences] return sentences def createVocab(self, path): dictWithFreq = {} vocab = [] with open(path, "r", encoding="utf-8") as f: text = f.read() text = self.removePunct(text) text = text.lower().split() for i in range(len(text)): dictWithFreq[text[i]] = dictWithFreq.get(text[i], 0) + 1 # with open(VOCAB_PATH, "w", encoding="utf-8") as file: # json.dump(dictWithFreq, file) vocab.append(self.PAD_TOKEN) vocab.append(self.UNKNOWN_TOKEN) vocab.append(self.STOP_TOKEN) for key in dictWithFreq: if dictWithFreq[key] > self.frequencyThreshold: vocab.append(key) print("created vocab") return vocab def removePunct(self, text): text=text.strip("\'") text = re.sub(r'\n', ' ', text) text = re.sub(r'[,{}@_*>()\\#%+=\[\]]', '', text) text = re.sub('a0', '', text) text = re.sub('\'91', ' ', text) text = re.sub('\'92', ' ', text) text = re.sub('\'93', ' ', text) text = re.sub('\'94', ' ', text) text = re.sub('\.', ' ', text) text = re.sub('\!', ' ', text) text = re.sub('-', ' ', text) text = re.sub('\?', ' ', text) text = re.sub(' +', ' ', text) return text def indexData(self, data): data = self.preprocess(data) indexedData = [[self.vocabToIndex[word] for word in sentence.split()] for sentence in data] return indexedData # def getSeqLen(self): # z = np.abs(scipy.stats.zscore(self.sentenceLengths)) # sentenceLengthsO = self.sentenceLengths[(z < 3).all(axis=1)] # self.sequenceLength = sentenceLengthsO.mean() def readLargeFile(self, DATA_PATH): with open(DATA_PATH, "r", encoding="utf-8") as f: while True: data = [] for i in range(hp.BATCH_SIZE): data.append(f.readline()) if not data: break yield data def createEmbeddingMatrix(self): embeddingMatrix = tf.Variable(tf.random_uniform([len(self.vocab), hp.EMBEDDING_SIZE], -1.0, 1.0)) return embeddingMatrix
d47a85102fd56d715698893c18d4a8bef0f5c9c3
[ "Python" ]
7
Python
gulperii/autoencoder
438819de38b5d35cd6be9b8155a0f51b90631ec8
bd05b72ec57ad9b72a5022435883d015122d9a20
refs/heads/master
<repo_name>Zazzy1/24-10-2019<file_sep>/Lab5/Lab5/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; namespace Lab5 { class Program { //comment11bivas static CloudStorageAccount storageAccount; static CloudTableClient tableClient; static CloudTable table; static void Main(string[] args) { try { CreateAzureStorageTable(); AddGuestEntity(); RetrieveGuestEntity(); UpdateGuestEntity(); DeleteGuestEntity(); DeleteAzureStorageTable(); } catch (StorageException ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } //Method to create AzureStorageTable private static void CreateAzureStorageTable() { //RETRIEVE THE STORAGE ACCOUNT FROM THE CONNECTION STRING storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); //CREATE THE TABLE CLIENT tableClient = storageAccount.CreateCloudTableClient(); //CREATE THE CLOUDTABLE OBJECT THAT REPRESENTS THE "guests" table table = tableClient.GetTableReference("guests"); //CREATE THE TABLE IF IT DOES NOT EXIST table.CreateIfNotExists(); Console.WriteLine("Table Created"); } private static void DeleteAzureStorageTable() { table.DeleteIfExists(); Console.WriteLine("Table Deleted"); } private static void DeleteGuestEntity() { TableOperation retrieveOperation = TableOperation.Retrieve<GuestEntity>("IND", "K001"); TableResult retrievedResult = table.Execute(retrieveOperation); if (retrievedResult.Result != null) { var guest = retrievedResult.Result as GuestEntity; TableOperation deleteOperation = TableOperation.Delete(guest); table.Execute(deleteOperation); Console.WriteLine("Entity Deleted"); } else { Console.WriteLine("Details could not be retrieved."); } } private static void UpdateGuestEntity() { TableOperation retrieveOperation = TableOperation.Retrieve<GuestEntity>("IND", "K001"); TableResult retrievedResult = table.Execute(retrieveOperation); if (retrievedResult.Result != null) { var guest = retrievedResult.Result as GuestEntity; guest.ContactNumber = "7894561230"; TableOperation updateOperation = TableOperation.Replace(guest); table.Execute(updateOperation); Console.WriteLine("Entity Updated"); } else { Console.WriteLine("Details could not be retrieved."); } } private static void RetrieveGuestEntity() { TableOperation retrieveOperation = TableOperation.Retrieve<GuestEntity>("IND","K001"); TableResult retrievedResult = table.Execute(retrieveOperation); if (retrievedResult.Result != null) { var guest = retrievedResult.Result as GuestEntity; Console.WriteLine($"Name:{guest.Name} ContactNumber:{guest.ContactNumber}"); } else { Console.WriteLine("Details could not be retrieved."); } } private static void AddGuestEntity() { //Create a new guest Entity GuestEntity guestEntity = new GuestEntity("IND","K001"); guestEntity.Name = "karthik"; guestEntity.ContactNumber = "9874561230"; TableOperation insertOperation = TableOperation.Insert(guestEntity); table.Execute(insertOperation); Console.WriteLine("Entity Added"); } } class GuestEntity:TableEntity { public string Name { get; set; } public string ContactNumber { get; set; } public GuestEntity() { } public GuestEntity(string partitionKey,string rowKey) { this.PartitionKey = partitionKey; this.RowKey = rowKey; } } }
912376401ab871af0b8420e040439a41bea98f95
[ "C#" ]
1
C#
Zazzy1/24-10-2019
ef3fb626125da4c1135f158484db2c9b4b7c23ca
4efd0d196aa41553182fbf6b9453eaf64f90b6c0
refs/heads/master
<file_sep>exports.fixtures = [require('./rooms')] <file_sep>const Joi = require('joi') exports.getFreeRoomsSchema = Joi.object().keys({ city: Joi.string().required(), from: Joi.date().required(), to: Joi.date() .greater(Joi.ref('from')) .required(), }) exports.getRoomsSchema = Joi.object().keys({ city: Joi.string().required(), date: Joi.date(), offset: Joi.number(), limit: Joi.number(), }) <file_sep>const swaggerJSDoc = require('swagger-jsdoc') const { ui } = require('swagger2-koa') exports.moduleFabric = (app, { config }) => { const options = { definition: { servers: [ { url: config.BASE_URL, }, ], info: { title: 'Peregovorki api', version: '1.0.0', description: 'Peregovorki api specification', contact: { name: 'bondiano', email: '<EMAIL>', }, }, openapi: '3.0.1', components: { securitySchemes: { BearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', }, }, }, }, apis: ['./**/*.controller.js', './**/*.model.js', './**/*.validators.js'], } const swaggerDoc = swaggerJSDoc(options) app.use(ui(swaggerDoc, '/doc')) } exports.moduleMeta = { name: 'swagger', baseRoute: '/doc', dependsOn: ['config'], } <file_sep>const AWS = require('aws-sdk') const uuidv4 = require('uuid/v4') const fs = require('fs') module.exports = ({ config }) => { const S3 = new AWS.S3({ params: { Bucket: config.S3_BUCKET, }, accessKeyId: config.S3_ACCESS_KEY_ID, secretAccessKey: config.S3_SECRET_ACCESS_KEY, }) const upload = async (filename = '', file) => { const imageToUpload = { Body: fs.createReadStream(file.path), Key: uuidv4() + '-' + filename + file.name, ACL: 'public-read', } const { Location: url } = await S3.upload(imageToUpload, { ACL: 'public-read', }).promise() return { url } } return { upload, } } <file_sep>export default { sources: ['**/*.{js}'], files: ['**/__test__/*.spec.js'], tap: true, verbose: true, } <file_sep>const rooms = [ { equipment: ['камера', 'микрофон', 'колонки'], events: [], capacity: 11, roomNumber: 101, city: 'Академгородок', }, { capacity: 10, equipment: ['камера', 'микрофон', 'колонки'], events: [], roomNumber: 102, city: 'Академгородок', }, { equipment: ['камера', 'микрофон', 'колонки', 'маркерная доска'], events: [], capacity: 23, roomNumber: 103, city: 'Академгородок', }, { equipment: ['колонки', 'маркерная доска'], events: [], capacity: 6, roomNumber: 104, city: 'Академгородок', }, { equipment: ['камера', 'микрофон', 'колонки', 'маркерная доска'], events: [], capacity: 10, roomNumber: 105, city: 'Академгородок', }, { equipment: ['камера', 'микрофон', 'колонки', 'маркерная доска'], events: [], capacity: 8, roomNumber: 106, city: 'Новосибирск', }, { equipment: ['микрофон', 'колонки', 'маркерная доска'], events: [], capacity: 20, roomNumber: 107, city: 'Новосибирск', }, { equipment: ['микрофон', 'колонки', 'маркерная доска'], events: [], capacity: 14, roomNumber: 108, city: 'Новосибирск', }, { equipment: ['камера'], events: [], capacity: 14, roomNumber: 109, city: 'Новосибирск', }, { equipment: ['микрофон', 'колонки', 'маркерная доска'], events: [], capacity: 10, roomNumber: 110, city: 'Новосибирск', }, { equipment: ['камера', 'маркерная доска'], events: [], capacity: 14, roomNumber: 111, city: 'Новосибирск', }, { equipment: ['камера', 'маркерная доска'], events: [], capacity: 14, roomNumber: 666, city: 'Питер', }, { equipment: ['микрофон', 'камера', 'маркерная доска'], events: [], capacity: 24, roomNumber: 777, city: 'Питер', }, ] exports.model = 'Room' exports.data = rooms <file_sep>const modules = [ require('./core/config'), require('./core/jwt'), require('./core/passport'), require('./core/swagger'), require('./core/media'), require('./users'), require('./events'), require('./rooms'), require('./auth'), ] module.exports = modules <file_sep>const passport = require('passport') const { UnauthorizedError } = require('./errors') exports.authHandler = (ctx, next) => passport.authenticate('jwt', { session: false }, (err, user) => { if (!user) { throw new UnauthorizedError() } ctx.user = user return next() })(ctx, next) <file_sep>const createController = require('./events.controller') const createServices = require('./events.services') exports.moduleFabric = (app, { rooms, users }) => { const externalServices = { roomsServices: rooms.services, usersServices: users.services, } const services = createServices(externalServices) return { controller: createController({ services }), exports: { services, }, } } exports.moduleMeta = { name: 'events', baseRoute: '/events', dependsOn: ['rooms', 'users'], } <file_sep>const BaseError = require('./BaseError') class UnknownError extends BaseError { get errorType() { return BaseError.errorTypes.DEFAULT_ERROR } get httpErrorCode() { return BaseError.httpErrorCodes.unknown } } module.exports = UnknownError <file_sep>const mongoose = require('mongoose') const timeZone = require('mongoose-timezone') const { Schema } = mongoose const { Types } = Schema /** * @swagger * components: * schemas: * Event: * properties: * title: * type: string * description: * type: string * images: * type: [string] * to: * type: string * format: date-time * from: * type: string * format: date-time * room: * $ref: '#/components/schemas/Room' * createdBy: * $ref: '#/components/schemas/User' * createdAt: * type: string */ const eventSchema = new Schema( { title: { type: String, }, description: { type: String, }, images: { type: [String], default: [], }, from: Date, to: Date, room: { type: Types.ObjectId, ref: 'Room', required: true, }, createdBy: { type: Types.ObjectId, ref: 'User', required: true, }, appliedUsers: { type: [ { type: Types.ObjectId, ref: 'User', }, ], default: [], }, }, { timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt', }, }, ) eventSchema.plugin(timeZone, { paths: ['from', 'to'] }) const Event = mongoose.model('Event', eventSchema) module.exports = Event <file_sep>const { pick } = require('lodash') exports.formatCreateEvent = user => pick(user, [ '_id', 'title', 'description', 'images', 'from', 'to', 'createdAt', 'updatedAt', ]) <file_sep>const { sign, verify } = require('jsonwebtoken') module.exports = ({ config }) => { return { sign: payload => sign( { ...payload, expiresIn: payload.expiresIn || config.JWT_EXPIRESIN, }, config.JWT_SECRET, ), verify: payload => verify(payload, config.JWT_SECRET), } } <file_sep>const createController = require('./media.controller') const createServices = require('./media.services') exports.moduleFabric = (app, { config }) => { const services = createServices({ config }) return { controller: createController({ services }), exports: { services, }, } } exports.moduleMeta = { name: 'media', baseRoute: '/media', dependsOn: ['config'], } <file_sep>const { BaseError } = require('@/helpers/errors') class NoRoom extends BaseError { constructor(message) { super() this.message = message } get errorType() { return BaseError.errorTypes.NOT_FOUND } get httpErrorCode() { return BaseError.httpErrorCodes.notFound } get errorMessage() { return this.message } } module.exports = NoRoom <file_sep>const { DepGraph } = require('dependency-graph') /** * @typedef {Object} Module * @property {string} name * @property {Array<string>} dependsOf */ /** * @param {Array<Module>} modules */ const createModulesGraph = modules => { const graph = new DepGraph() for (let module of modules) { if (graph.hasNode(module.name)) { graph.setNodeData(module.name, module) } else { graph.addNode(module.name, module) } if (!module.dependsOn || !module.dependsOn.length) { continue } for (let dependency of module.dependsOn) { if (!graph.hasNode(dependency)) { graph.addNode(dependency) } graph.addDependency(dependency, module.name) } } return graph } /** * @param {Array<Module>} modules */ const resolveDependsToQueue = modules => { const graph = createModulesGraph(modules) const overallOrder = graph.overallOrder().reverse() // It must be a queue as I want :D return overallOrder .map(name => { return modules.find(module => module.name === name) }) .filter(Boolean) } exports.resolveDependsToQueue = resolveDependsToQueue <file_sep>const { DuplicateEntityError, UnknownError } = require('./errors') const mongoErrorsCodesMap = { 11000: DuplicateEntityError, default: UnknownError, } const mongoErrorsHandler = (error, ...rest) => { const handledError = mongoErrorsCodesMap[error.code] || mongoErrorsCodesMap.default return new handledError(error, ...rest) } module.exports = mongoErrorsHandler <file_sep>const mongoose = require('mongoose') const { Schema } = mongoose const { Types } = Schema /** * @swagger * components: * schemas: * Room: * properties: * roomNumber: * type: number * description: * type: string * city: * type: string * images: * type: array * items: * type: string * equipment: * type: array * items: * type: string * events: * type: array * items: * $ref: '#/components/schemas/Event' * createdAt: * type: string * */ const roomSchema = new Schema( { roomNumber: Number, description: { type: String, default: '', }, images: { type: [String], default: [], }, city: String, equipment: { type: [String], default: [], }, capacity: { type: Number, default: 0, }, events: { type: [ { type: Types.ObjectId, ref: 'Event', }, ], default: [], }, }, { timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt', }, }, ) const Room = mongoose.model('Room', roomSchema) module.exports = Room <file_sep>const passport = require('koa-passport') const { registerControllers } = require('@/helpers/registerControllers') const { authHandler } = require('@/helpers/authHandler') const { validatorHandler } = require('@/helpers/validatorHandler') const { loginSchema, createUserSchema } = require('./auth.validators') const createController = registerControllers(module) /** * @swagger * /auth/create: * post: * tags: * - Auth * description: Create new user * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * username: * type: string * password: * type: string * email: * type: string * responses: * 201: * schema: * type: object * properties: * user: * $ref : '#/components/schemas/User' * token: * type: string */ createController( 'post', '/create', validatorHandler(createUserSchema), async (ctx, next, { usersServices, jwtServices }) => { const { username, password, email } = ctx.request.body const user = await usersServices.createUser({ username, password, email }) const token = jwtServices.sign({ id: user._id }) ctx.response.body = { user, token } }, ) /** * @swagger * /auth/login: * post: * tags: * - Auth * description: Login user * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * username: * type: string * password: * type: string * responses: * 200: * schema: * type: object * properties: * user: * $ref : '#/components/schemas/User' * token: * type: string */ createController( 'post', '/login', validatorHandler(loginSchema), async (ctx, next, { jwtServices }) => { await passport.authenticate('local', { session: false }, (err, user) => { if (err) { throw err } const payload = { id: user._id, } const token = jwtServices.sign(payload) ctx.response.body = { user, token } })(ctx, next) }, ) /** * @swagger * /auth/me: * get: * tags: * - Auth * security: * - BearerAuth: [] * description: Returns user data by token * responses: * 200: * schema: * $ref : '#/components/schemas/User' */ createController('get', '/me', authHandler, async ctx => { const { user } = ctx ctx.response.body = user }) <file_sep>const mongoErrorsHandler = require('./mongoErrorsHandler') const createRepository = Model => ({ /** * Get all entities * * @param {Object} conditions * @param {Object|String} projection * @param {Object} options * @return {Promise<any>} */ async getAll(conditions = {}, projection = null, options) { try { const data = await Model.find(conditions, projection, options) return data } catch (e) { throw mongoErrorsHandler(e, Model.modelName) } }, /** * Get entity by id * * @param {string} id - mongo id * @return {Promise<any>} */ getById: id => Model.findById(id), /** * Create new entity * * @param {Object | Array} data - model data to create entity * @return {Promise<any>} */ async create(data) { try { const created = await Model.create(data) return created } catch (e) { throw mongoErrorsHandler(e, Model.modelName) } }, /** * Delete by id * @param {string} id - mongo id * @return {Promise<any>} */ deleteById: id => Model.findByIdAndDelete(id), /** * Find one by conditions * * @param conditions * @param projection * @param options * @return {Promise<any>} */ async findOne(conditions = {}, projection = null, options) { try { const data = await Model.findOne(conditions, projection, options) return data } catch (e) { throw mongoErrorsHandler(e, Model.modelName) } }, /** * Find by id and update * * @param id * @param data * @return {Promise<any>} */ async updateById(id, data) { try { const modelData = await Model.findByIdAndUpdate(id, data, { new: true }) return modelData } catch (e) { throw mongoErrorsHandler(e, Model.modelName) } }, /** * Find several documents and update each * * @param conditions * @param data * @return {Promise<any>} */ async update(conditions = {}, data) { try { const modelData = await Model.update(conditions, data) return modelData } catch (e) { throw mongoErrorsHandler(e, Model.modelName) } }, }) exports.createRepository = createRepository <file_sep>const path = require('path') const moduleAlias = require('module-alias') moduleAlias.addAliases({ '@': path.dirname(__dirname), }) moduleAlias() <file_sep>const createServices = require('./jwt.services') exports.moduleFabric = (app, { config }) => { const services = createServices({ config }) return { exports: { services, }, } } exports.moduleMeta = { name: 'jwt', dependsOn: ['config'], } <file_sep>function registerControllers(controllerModule) { const controllers = [] let dependencies controllerModule.exports = deps => { dependencies = deps return controllers } return function controller(method, path, ...handlers) { const handlersWithDeps = handlers.reduce((acc, handler) => { const handlerWithDeps = (ctx, next) => handler(ctx, next, dependencies) acc.push(handlerWithDeps) return acc }, []) controllers.push({ method, path, handlers: handlersWithDeps, }) } } exports.registerControllers = registerControllers <file_sep>const { startOfDay, endOfDay, parseISO, areIntervalsOverlapping, } = require('date-fns') const { compose } = require('lodash/fp') const { createRepository } = require('@/helpers/mongooseCRUD') const roomModel = require('./rooms.model') const roomRepository = createRepository(roomModel) roomRepository.getAllWithEvents = async function getAllWithEvents({ limit = 10, offset = 0, city, date, }) { const findCondition = { city, } const fromTime = compose(startOfDay, parseISO)(date) const toTime = compose(endOfDay, parseISO)(date) const rooms = await roomModel .find(findCondition, null, { limit: +limit, offset: +offset }) .populate({ path: 'events', match: date && { from: { $gt: fromTime }, to: date && { $lt: toTime } }, }) .exec() const total = await roomModel.countDocuments(findCondition) return { total, offset, limit, rooms } } roomRepository.getAllFreeRooms = async function getAllFreeRoom({ city, from, to, }) { const findCondition = { city, } const rooms = await roomModel .find(findCondition, null) .populate('events') .exec() const userTimeInterval = { start: parseISO(from), end: parseISO(to) } const freeRooms = rooms.filter(room => room.events.length ? room.events.some( event => !areIntervalsOverlapping( { start: parseISO(new Date(event.from).toISOString()), end: parseISO(new Date(event.to).toISOString()), }, userTimeInterval, ), ) : true, ) return freeRooms } roomRepository.getRoomWithEvent = async function getAllWithEvents(id) { const room = await roomModel .findById(id) .populate('events') .exec() return room } exports.roomRepository = roomRepository <file_sep>const { createRepository } = require('@/helpers/mongooseCRUD') const userModel = require('./users.model') const userRepository = createRepository(userModel) userRepository.getUserWithEvent = async function getAllWithEvents(id) { const user = await userModel .findById(id) .populate({ path: 'events', populate: { path: 'room', select: 'roomNumber city equipment images capacity', }, }) .exec() return user } userRepository.findOneWithEvent = async function findOneWithEvent( conditions = {}, projection = null, options, ) { const user = await userModel .findOne(conditions, projection, options) .populate({ path: 'events', populate: { path: 'room', select: 'roomNumber city equipment images capacity', }, }) .exec() return user } exports.userRepository = userRepository <file_sep>require('dotenv').config() exports.PORT = process.env.PORT exports.MONGO_DB_PORT = process.env.MONGO_DB_PORT exports.MONGO_DB_URL = process.env.MONGO_DB_URL exports.JWT_SECRET = process.env.JWT_SECRET exports.JWT_EXPIRESIN = process.env.JWT_EXPIRESIN exports.BASE_URL = process.env.BASE_URL || '' exports.S3_BUCKET = process.env.S3_BUCKET exports.S3_ACCESS_KEY_ID = process.env.S3_ACCESS_KEY_ID exports.S3_SECRET_ACCESS_KEY = process.env.S3_SECRET_ACCESS_KEY <file_sep>const passport = require('koa-passport') const { Strategy: LocalStrategy } = require('passport-local') const { Strategy: JWTStrategy, ExtractJwt } = require('passport-jwt') const { UserNotFound, InvalidCredentials } = require('./exceptions') exports.moduleFabric = (app, { users, config }) => { const optionsJWT = { jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: config.JWT_SECRET, } passport.use( new JWTStrategy(optionsJWT, async (payload, done) => { try { const user = await users.services.getById(payload.id) if (!user) { throw new UserNotFound() } return done(null, user) } catch (error) { return done(error, false) } }), ) passport.use( new LocalStrategy({ session: false }, async (username, password, done) => { try { const isValidPassword = await users.services.verifyPassword( username, password, ) if (!isValidPassword) { throw new InvalidCredentials() } const user = await users.services.findOne({ username }) done(null, user) } catch (error) { return done(error, false) } }), ) } exports.moduleMeta = { name: 'passport', dependsOn: ['users', 'jwt', 'config'], } <file_sep>const Koa = require('koa') const Router = require('koa-router') const logger = require('koa-logger') const cors = require('@koa/cors') const bodyParser = require('koa-body') const helmet = require('koa-helmet') const passport = require('koa-passport') const app = new Koa() const config = require('../config') require('../bootstrap') const { registerModules } = require('../modules') const { errorHandler } = require('../helpers/errorHandler') app.use(helmet()) if (process.env.NODE_ENV === 'development') { app.use(logger()) } app.use(cors()) app.use( bodyParser({ json: true, multipart: true, onerror: (err, ctx) => { ctx.throw('Body parse error', err, 422) }, }), ) app.use(passport.initialize()) registerModules(app, [errorHandler]) app.listen(config.PORT, () => console.log(`PEREGOVORKI API started on ${config.PORT}`), ) <file_sep>const httpErrorCodes = { unprocessableEntity: 422, unknown: 520, notFound: 404, badRequest: 400, forbidden: 403, unauthorized: 401, } module.exports = httpErrorCodes <file_sep>const { NotFoundError } = require('@/helpers/errors') class UserNotFound extends NotFoundError { constructor() { super('User', 'User was not found') } } module.exports = UserNotFound <file_sep>require('./module-aliases') require('./mongo') require('./joi') <file_sep>const BaseError = require('./BaseError') class NotFoundError extends BaseError { constructor(entity, msg) { super() this.entity = entity this.msg = msg } get errorType() { return BaseError.errorTypes.NOT_FOUND } get httpErrorCode() { return BaseError.httpErrorCodes.notFound } get errorMessage() { return this.msg || `${this.entity} not found` } } module.exports = NotFoundError <file_sep>const errorTypes = { DUPLICATED_ENTITY: 'DUPLICATED_ENTITY', DEFAULT_ERROR: 'DEFAULT_ERROR', VALIDATION_ERROR: 'VALIDATION_ERROR', NOT_FOUND: 'NOT_FOUND', BAD_REQUEST: 'BAD_REQUEST', FORBIDDEN: 'FORBIDDEN', UNAUTHORIZED: 'UNAUTHORIZED', } module.exports = errorTypes <file_sep>const Joi = require('joi') const usernameRules = Joi.string() .min(2) .max(20) const passwordRules = Joi.string() .min(8) .max(256) const emailRules = Joi.string().email({ minDomainAtoms: 2 }) exports.updateUserSchema = Joi.object().keys({ username: usernameRules, password: <PASSWORD>, email: emailRules, avatar: Joi.string().uri(), oldPassword: Joi.when('password', { is: Joi.exist(), then: passwordRules.required(), }), about: Joi.string().max(256), firstName: Joi.string().max(256), lastName: Joi.string().max(256), }) <file_sep>const { registerControllers } = require('@/helpers/registerControllers') const { authHandler } = require('@/helpers/authHandler') const { validatorHandler } = require('@/helpers/validatorHandler') const { eventSchema } = require('./events.validators') const createController = registerControllers(module) /** * @swagger * /events: * post: * tags: * - Events * description: Create new event * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * title: * type: string * description: * type: string * images: * type: array * items: * type: string * from: * type: string * format: date-time * to: * type: string * format: date-time * room: * type: string * description: Room id * example: abcd56789012345678901234 * security: * - BearerAuth: [] * responses: * 200: * schema: * $ref: '#/components/schemas/Event' * */ createController( 'post', '/', authHandler, validatorHandler(eventSchema), async (ctx, next, { services }) => { const { user } = ctx const event = await services.createEvent({ ...ctx.request.body, user }) ctx.response.body = event }, ) /** * @swagger * /events: * get: * tags: * - Events * description: Get list of events * responses: * 200: * schema: * type: array * items: * $ref: '#/components/schemas/Event' * */ createController('get', '/', async (ctx, next, { services }) => { const events = await services.getAll() ctx.response.body = events }) /** * @swagger * /events/{id}: * get: * tags: * - Events * description: Get event by id * parameters: * - * name: id * in: path * description: Event id * required: true * responses: * 200: * schema: * $ref: '#/components/schemas/Event' * */ createController('get', '/:id', async (ctx, next, { services }) => { const { id } = ctx.params const event = await services.getById(id) ctx.response.body = event }) /** * @swagger * /events/{id}: * patch: * tags: * - Events * description: Update event by id * parameters: * - * name: id * in: path * description: Event id * required: true * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * title: * type: string * description: * type: string * images: * type: array * items: * type: string * from: * type: string * format: date-time * to: * type: string * format: date-time * room: * type: string * description: Room id * example: abcd56789012345678901234 * security: * - BearerAuth: [] * responses: * 200: * schema: * $ref: '#/components/schemas/Event' * */ createController( 'patch', '/:id', authHandler, validatorHandler(eventSchema), async (ctx, next, { services }) => { const { user } = ctx const { id } = ctx.params const event = await services.updateById({ id, user, data: ctx.request.body, }) ctx.response.body = event }, ) /** * @swagger * /events/{id}/apply: * post: * tags: * - Events * description: Apply to event * parameters: * - * name: id * in: path * description: Event id * required: true * security: * - BearerAuth: [] * responses: * 200: * schema: * $ref: '#/components/schemas/Event' * */ createController( 'post', '/:id/apply', authHandler, async (ctx, next, { services }) => { const { user } = ctx const { id } = ctx.params const event = await services.applyToEvent(id, user._id) ctx.response.body = event }, ) /** * @swagger * /events/{id}/deny: * post: * tags: * - Events * description: Deny from event * parameters: * - * name: id * in: path * description: Event id * required: true * security: * - BearerAuth: [] * responses: * 200: * schema: * $ref: '#/components/schemas/Event' * */ createController( 'post', '/:id/deny', authHandler, async (ctx, next, { services }) => { const { user } = ctx const { id } = ctx.params const event = await services.denyFromEvent(id, user._id) ctx.response.body = event }, ) /** * @swagger * /events/{id}: * delete: * tags: * - Events * description: Apply to event * parameters: * - * name: id * in: path * description: Event id * required: true * security: * - BearerAuth: [] * responses: * 200: * schema: * $ref: '#/components/schemas/Event' * */ createController( 'delete', '/:id', authHandler, async (ctx, next, { services }) => { const { user } = ctx const { id } = ctx.params const event = await services.deleteEvent(id, user._id) ctx.response.body = event }, ) <file_sep>const config = require('@/config') exports.moduleFabric = () => { return { exports: config, } } exports.moduleMeta = { name: 'config', } <file_sep>const Joi = require('joi') const compose = require('koa-compose') const { isEmpty, get } = require('lodash') const { ValidationError } = require('@/helpers/errors') /** * Add validation errors in ctx * * @param {Joi.scheme} scheme * @param {String} path in ctx to object for validate * @return {Promise<void>} koa middleware */ const checkErrors = (scheme, target = 'request.body') => async (ctx, next) => { try { const result = await Joi.validate(get(ctx, target), scheme, { abortEarly: false, allowUnknown: false, }) if (target === 'request.body') { ctx.body = result } } catch (e) { throw new ValidationError(e.details) } await next() } /** * Throw validation error if ctx.validationErrors not empty * * @param ctx * @param next * @return {Promise<void>} */ const returnErrors = async (ctx, next) => { if (!isEmpty(ctx.validationErrors)) { const error = new ValidationError(ctx.validationErrors) throw error } await next() } /** * Composed middleware to check and throw validation error * * @param scheme * @return {Promise<void>} */ const checkAndThrow = (scheme, target) => compose([checkErrors(scheme, target), returnErrors]) exports.validatorHandler = checkAndThrow <file_sep>const createController = require('./users.controller') const createServices = require('./users.services') exports.moduleFabric = app => { const services = createServices() return { controller: createController({ services }), exports: { services, }, } } exports.moduleMeta = { name: 'users', baseRoute: '/users', } <file_sep>const BaseError = require('./BaseError') class ValidationError extends BaseError { constructor(errors) { super() this.errors = errors } get errorType() { return BaseError.errorTypes.VALIDATION_ERROR } get httpErrorCode() { return BaseError.httpErrorCodes.badRequest } } module.exports = ValidationError <file_sep>const { registerControllers } = require('@/helpers/registerControllers') const { validatorHandler } = require('@/helpers/validatorHandler') const roomValidator = require('./room.validators') const createController = registerControllers(module) /** * @swagger * /rooms: * get: * tags: * - Rooms * description: Get list of rooms * parameters: * - in: query * name: city * required: true * schema: * type: string * description: Filter by city name * - in: query * name: date * schema: * type: string * format: date-time * description: Filter by date of events (only events for the date will be sent) * - in: query * name: offset * schema: * type: integer * description: The number of items to skip before starting to collect the result set * - in: query * name: limit * schema: * type: integer * responses: * 200: * schema: * type: array * items: * $ref: '#/components/schemas/Room' * */ createController( 'get', '/', validatorHandler(roomValidator.getRoomsSchema, 'query'), async (ctx, next, { services }) => { const { limit, offset, city, date } = ctx.query const { rooms, ...additional } = await services.getAll({ limit, offset, city, date, }) ctx.additional = additional ctx.response.body = rooms }, ) /** * @swagger * /rooms/free: * get: * tags: * - Rooms * description: Get list of free rooms for time * parameters: * - in: query * name: city * required: true * schema: * type: string * description: Filter by city name * - in: query * name: from * required: true * schema: * type: string * format: date-time * description: User is searching from date * - in: query * name: to * required: true * schema: * type: string * format: date-time * description: User is searching to date * responses: * 200: * schema: * type: array * items: * $ref: '#/components/schemas/Room' * */ createController( 'get', '/free', validatorHandler(roomValidator.getFreeRoomsSchema, 'query'), async (ctx, next, { services }) => { const { city, from, to } = ctx.query const rooms = await services.getAllFreeRooms({ city, from, to }) ctx.response.body = rooms }, ) /** * @swagger * /rooms/{id}: * get: * tags: * - Rooms * description: Room by id * parameters: * - * name: id * in: path * description: Room id * required: true * responses: * 200: * schema: * $ref: '#/components/schemas/Room' * */ createController('get', '/:id', async (ctx, next, { services }) => { const { id } = ctx.params const rooms = await services.getRoomById(id) ctx.response.body = rooms }) <file_sep>exports.UserNotFound = require('./UserNotFound') exports.InvalidCredentials = require('./InvalidCredentials') <file_sep>FROM node:12 RUN mkdir /api WORKDIR /api COPY ./app/package.json ./ COPY ./app/yarn.lock ./ RUN yarn install --no-cache --ignore-optional --frozen-lockfile --network-timeout 100000 COPY ./app . EXPOSE 1488 EXPOSE 9229 ENTRYPOINT ["yarn"] <file_sep>up: docker-compose up -d down: docker-compose down start: docker-compose up --build prod: docker-compose -f ./docker-compose.prod.yaml up --build -d debug: DEBUG_CMD=start:debug docker-compose up build: docker-compose build --no-cache clear-volumes: sudo rm -rf ./data_mongo/* <file_sep>const { parseISO, isSameDay, differenceInHours, areIntervalsOverlapping, } = require('date-fns') const { eventRepository } = require('./events.repository') const { formatCreateEvent } = require('./events.formatter') const { InvalidDate, NoRoom, NotEventCreator } = require('./exceptions') const isValidDateDiff = (from, to) => { const fromISO = parseISO(from) const toISO = parseISO(to) return isSameDay(fromISO, toISO) && differenceInHours(toISO, fromISO) <= 6 } const isTimeInRoomBusy = (events, from, to) => { const userTimeInterval = { start: parseISO(from), end: parseISO(to) } return events.some(event => areIntervalsOverlapping( { start: parseISO(new Date(event.from).toISOString()), end: parseISO(new Date(event.to).toISOString()), }, userTimeInterval, ), ) } // TODO: make all update and delete requests in transaction and move them to repository module.exports = ({ roomsServices, usersServices }) => { const validateEventInfo = async ({ from, to, room }) => { if (!isValidDateDiff(from, to)) { throw new InvalidDate( 'It should be the same day and difference between from and to must be less then 6 hours', ) } const roomInfo = await roomsServices.getRoomById(room) if (!roomInfo) { throw new NoRoom(`Room with id ${room} is not found`) } if (isTimeInRoomBusy(roomInfo.events, from, to)) { throw new InvalidDate('This time in the room is busy') } } const createEvent = async ({ title, description, images, from, to, room, user, }) => { await validateEventInfo({ from, to, room }) const event = await eventRepository.create({ title, description, images, from, to, room, createdBy: user._id, appliedUsers: [user._id], }) const userData = await usersServices.updateUserById(user._id, { $push: { events: event._id }, }) const roomData = await roomsServices.updateRoomById(room, { $push: { events: event._id }, }) return { ...formatCreateEvent(event), createdBy: userData, room: roomData, } } const getAll = conditions => eventRepository.getAllEventsWithData(conditions) const getById = async id => { const event = await eventRepository.getEventWithDataById(id) return event } const updateById = async ({ id, user, data }) => { const event = await eventRepository.getById(id) const isCurrentUserCreator = event.createdBy.equals(user) if (!isCurrentUserCreator) { throw new NotEventCreator() } await validateEventInfo({ ...event, ...data }) const updatedEvent = await eventRepository.updateById(id, data) return updatedEvent } const applyToEvent = async (eventId, userId) => { const user = await usersServices.getById(userId) const isUserHasEvent = user.events.some(({ id }) => id === eventId) if (isUserHasEvent) { // TODO: make special exception throw new Error('User already applied') } await usersServices.updateUserById(userId, { $push: { events: eventId }, }) const event = await eventRepository.updateById(eventId, { $push: { appliedUsers: userId }, }) return event } const denyFromEvent = async (eventId, userId) => { const user = await usersServices.getById(userId) const isUserHasEvent = user.events.some(({ id }) => id === eventId) if (!isUserHasEvent) { // TODO: make special exception throw new Error('User already not applied to event with id: ' + eventId) } await usersServices.updateUserById(userId, { $pull: { events: eventId }, }) const event = await eventRepository.updateById(eventId, { $pull: { appliedUsers: userId }, }) if (!event.appliedUsers.length) { await eventRepository.deleteById(event._id) } return event } const deleteEvent = async (eventId, userId) => { const event = await eventRepository.getById(eventId) if (!event) { throw new Error('No such event') } const isCurrentUserCreator = event.createdBy.equals(userId) if (!isCurrentUserCreator) { throw new NotEventCreator() } await usersServices.update( { events: { $eq: event._id } }, { $pull: { events: { _id: event._id } } }, ) await roomsServices.updateRoomById(event.room, { $pull: { events: { _id: event._id } }, }) await eventRepository.deleteById(event._id) return 'Successfully deleted' } return { getAll, getById, createEvent, updateById, applyToEvent, denyFromEvent, deleteEvent, } } <file_sep>const { roomRepository } = require('./room.repository') module.exports = () => { const getAll = roomRepository.getAllWithEvents const getAllFreeRooms = roomRepository.getAllFreeRooms const updateRoomById = roomRepository.updateById const getRoomById = roomRepository.getRoomWithEvent return { getAll, updateRoomById, getRoomById, getAllFreeRooms, } } <file_sep>const successResponse = (data, additional) => ({ success: true, data, additional, }) const errorResponse = error => ({ success: false, error: { errorCode: error.errorCode, errorMessage: error.errorMessage, errors: error.errors, }, }) const errorHandler = async (ctx, next) => { try { await next() const needWrap = ctx.response.body && typeof ctx.response.body === 'object' if (needWrap) { ctx.response.status = 200 const { additional } = ctx delete ctx.additional ctx.response.body = successResponse(ctx.response.body, additional) } } catch (e) { console.error('Handled error', e) ctx.response.status = typeof e.httpErrorCode === 'number' ? e.httpErrorCode : 500 ctx.response.body = errorResponse(e) } } exports.errorHandler = errorHandler <file_sep>const Joi = require('joi') exports.eventSchema = Joi.object().keys({ title: Joi.string(), description: Joi.string(), images: Joi.array().items(Joi.string()), from: Joi.date() .greater('now') .required(), to: Joi.date() .greater(Joi.ref('from')) .required(), room: Joi.objectId().required(), }) <file_sep>const path = require('path') const classicFs = require('fs') const fs = require('fs').promises const mongoose = require('../bootstrap/mongo') const { fixtures } = require('../fixtures') const hasFile = async filePath => { try { await fs.access(filePath, classicFs.constants.R_OK) return true } catch (e) { return false } } const initModulesModels = async filePath => { if ((await fs.lstat(filePath)).isFile()) { return } const modelFileName = `${filePath}/${path.parse(filePath).name}.model.js` if (await hasFile(modelFileName)) { require(modelFileName) return } const filesInFolder = await fs.readdir(filePath) for (const file of filesInFolder) { const folder = path.resolve(filePath, file) await initModulesModels(folder) } } const insertCollections = async (modelName, data) => { const db = mongoose.connection const Model = db.model(modelName) await Model.deleteMany({}) await Model.create(data) } ;(async () => { try { await initModulesModels(path.resolve(__dirname, '../modules')) for (const fixture of fixtures) { await insertCollections(fixture.model, fixture.data) } console.log('Fixtures were successfully updated') process.exit(0) } catch (e) { console.log(e.message) } })() <file_sep>const { pick } = require('lodash') exports.formatUser = user => pick(user, [ '_id', 'username', 'email', 'createdAt', 'lastName', 'firstName', 'avatar', 'about', 'events', ]) <file_sep>const { createRepository } = require('@/helpers/mongooseCRUD') const eventModel = require('./events.model') const eventRepository = createRepository(eventModel) eventRepository.getAllEventsWithData = async function getAllEventsWithData( conditions, ) { const events = await eventModel .find(conditions) .populate('room') .populate('appliedUsers') .exec() return events } eventRepository.getEventWithDataById = async function getAllWithData(id) { const event = await eventModel .findById(id) .populate('room') .populate('appliedUsers') .exec() return event } exports.eventRepository = eventRepository <file_sep>const errorTypes = require('./errorTypes') const httpErrorCodes = require('./httpErrorCodes') class BaseError extends Error { static get errorTypes() { return errorTypes } static get httpErrorCodes() { return httpErrorCodes } get errorType() { return errorTypes.DEFAULT_ERROR } } module.exports = BaseError <file_sep># Modules ## modules.js You have to require your module to array in `modules.js`. ```javascript const modules = [require('./your-module/path')] ``` ## Module Every module should export `moduleFabric` function for init module and `moduleMeta` object with info. ```javascript exports.moduleFabric = (app, { ...deps }) => { ... return { controller: createController(), exports: {}, } } exports.moduleMeta = { name: 'name', baseRoute: '/', dependsOn: ['depsOn'], } ``` <file_sep>const createController = require('./auth.controller') exports.moduleFabric = (app, { jwt, users }) => { return { controller: createController({ usersServices: users.services, jwtServices: jwt.services, }), } } exports.moduleMeta = { name: 'auth', baseRoute: '/auth', dependsOn: ['jwt', 'users'], } <file_sep>const { resolveDependsToQueue } = require('./resolveDependsToQueue') exports.resolveDependsToQueue = resolveDependsToQueue <file_sep>PORT=1488 MONGO_ADMIN_PORT=8853 MONGO_DB_PORT= MONGO_DB_URL= JWT_SECRET=<PASSWORD> JWT_EXPIRESIN=12h S3_BUCKET= S3_BUCKET= S3_ACCESS_KEY_ID= S3_SECRET_ACCESS_KEY= BASE_URL=http://localhost:1488/
e1620a7aac1ab530b75bd275a1957045697ea053
[ "JavaScript", "Markdown", "Makefile", "Dockerfile", "Shell" ]
55
JavaScript
bondiano/peregovorik-be
c4959f8e534f8cd76e0f6fda9bcd28a5eb49c9b5
a8a9703e5f9b61838367acb15ecf38baaaade45e
refs/heads/main
<file_sep>server.port=9896 spring.jpa.show-sql=true spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl spring.datasource.username=system spring.datasource.password=<PASSWORD> spring.jpa.hibernate.ddl-auto=update <file_sep>package com.example.demo.serviceImp; import com.example.demo.model.Employee; import com.example.demo.repo.EmployeeRepo; import com.example.demo.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeRepo repo; @Override public Integer saveEmp(Employee employee) { Integer employee1id = repo.save(employee).getEmpId(); return employee1id; } @Override public List<Employee> getAllEmp() { return repo.findAll(); } @Override public Optional<Employee> getOneEmp(Integer id) { Optional<Employee> emp=repo.findById(id); return emp; } } <file_sep>package com.example.demo.model; import jdk.jfr.DataAmount; import javax.persistence.*; @Entity @Table public class Employee { @Id @GeneratedValue @Column(name = "empid") private Integer empId; @Column(name = "empname") private String empName; @Column(name = "empadd") private String empAdd; @Column(name = "empsal") private Double empSal; public Employee() { } public Employee(Integer empId, String empName, String empAdd, Double empSal) { this.empId = empId; this.empName = empName; this.empAdd = empAdd; this.empSal = empSal; } public Integer getEmpId() { return empId; } public String getEmpName() { return empName; } public String getEmpAdd() { return empAdd; } public Double getEmpSal() { return empSal; } public void setEmpId(Integer empId) { this.empId = empId; } public void setEmpName(String empName) { this.empName = empName; } public void setEmpAdd(String empAdd) { this.empAdd = empAdd; } public void setEmpSal(Double empSal) { this.empSal = empSal; } }
7662e8c0f9bd452e2b896246f291d0a83710a3f4
[ "Java", "INI" ]
3
INI
rijwan-khan-zensar/masterbranch
76b4dc1b61985779f61ba93b7243352ceafd18af
872f4531c15ab7aa95866e88598d25102701c96c
refs/heads/master
<file_sep>class DictionaryLoader attr_reader :words def initialize @words = [] end def load_words file_lines = File.readlines("5desk.txt") file_lines.each do |word| @words << word.strip end @words end def save(result, filename) File.open(filename,"w") do |file| file.write result end end end <file_sep>=begin 1. class Dictionary - user interaction loop - get word to look up from the command line - should be able to quit and exit the program - once search is complete, ask user to save file or display to screen - if saving to a file - get file name - if it exists, ask whether to overwrite 2. Dictionary loader - reads dictionary file - output: entire dictionary 3. DictionaryAnalyzer - get entire dictionary - provides simple stats: word count, words per letter - perfrom one of 4 search types - exact match - partial match - begins with - ends with - return full word regardless of match type =end require_relative './dictionary_loader.rb' class Dictionary def run analyze = DictionaryAnalyzer.new result = nil puts "What word would you like to search for? " word_to_search = gets.chomp result = search_type(analyze, word_to_search) puts result puts "Save result? [Y/N]" save(result) if gets.chomp.downcase == "y" end def search_type(analyze, word_to_search) puts "What type of search (exact match, partial match, begins with, ends with)? " search_type = gets.chomp case search_type when "exact match" result = analyze.exact_match(word_to_search) when "partial match" result = analyze.partial_match(word_to_search) when "begins with" result = analyze.begins_with(word_to_search) when "ends with" result = analyze.ends_with(word_to_search) else return "Invalid entry" end result end def save(result) puts "What would you like to name your file?" filename = gets.chomp File.open(filename+".txt","w") do |file| file.write result end end end class DictionaryAnalyzer attr_reader :words def initialize dict = DictionaryLoader.new @words = dict.load_words # p @words end # Word Stats def stats(options = {}) @words.length if options[:word_count] if options[:words_per_letter] p "Enter a letter >>" char = gets.chomp.upcase @words.count {|word| word[0].upcase == "#{char}"} end end # def search(word, options = {}) # return exact_match(word) if options[:exact_match] # return partial_match(word) if options[:partial_match] # return begins_with(word) if options[:begins_with] # return ends_with(word) if options[:ends_with] # end def exact_match(word) #/\b"#{word}"\b/ @words.each do |word_from_dict| return word_from_dict if word_from_dict == word end puts "No match" end def partial_match(word) #/#{word}/ result = [] @words.each do |word_from_dict| result << word_from_dict if word_from_dict.include?(word) end result end def begins_with(word) result = [] @words.each do |word_from_dict| result << word_from_dict unless word_from_dict.match(/^#{word}\w+/).nil? end result end def ends_with(word) result = [] @words.each do |word_from_dict| result << word_from_dict unless word_from_dict.match(/\w+#{Regexp.quote(word)}$/).nil? end result end end a = Dictionary.new a.run<file_sep># assignment_file_ops_sprint I can haz spellz Nick and Alok
89142fcc572a9ed0f88142fdfd33cb085a9a86d5
[ "Markdown", "Ruby" ]
3
Ruby
sicknarlo/assignment_file_ops_sprint
a9edc8c4f4cdd8448ba23c1fcb135dab0e4b57fe
08b658c83fdd1d79e57476becdb255b9673cda99
refs/heads/master
<repo_name>DeusAnimaX/SeleniumTestCases<file_sep>/src/utils/Util.java package utils; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class Util { public static String getMacChromeDriver() { String url = "chromedriver"; return url; } public static String getWinChromeDriver() { String url = "chromedriver.exe"; return url; } public static WebDriver getDriver() { System.setProperty("webdriver.chrome.driver", Util.getMacChromeDriver()); WebDriver driver = new ChromeDriver(); return driver; } public static String getFilePath() { return ""; } public static String getFileName() { return "Parametros.xlsx"; } public static String getSheetName() { return "Hoja1"; } } <file_sep>/src/Data/ReadData.java package Data; import utils.Util; import java.io.File; import java.io.FileInputStream; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadData { public static Sheet readExcel() throws Exception { File file = new File(Util.getFilePath()+Util.getFileName()); FileInputStream inputStream = new FileInputStream(file); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheet(Util.getSheetName()); return sheet; } }
f05fffbfc257f51a9310d8a2e549617e0e4b7d8f
[ "Java" ]
2
Java
DeusAnimaX/SeleniumTestCases
e1361a8f40e00d530f637b448c03340133bf44fc
ad3498072cb2ed26fc01fdc8df7bac3c133ea11e
refs/heads/master
<file_sep>![alt-tag](https://img00.deviantart.net/70af/i/2004/341/6/f/ro___chibi_merchant_by_dejichan.jpg) ### Routes `lowest-price`: Input the item id to see its lowest price (`/lowest-price?id={}`) <file_sep>import requests import json import re from bs4 import BeautifulSoup headers = { 'user-agent': 'my-app/0.0.1', 'cookie': '__cfduid=dd2bc98b37a58f03b9074d7a4fd137ea21527513404; _ga=GA1.2.279426244.1527513406; fluxSessionData=6df671d7359a7e03c118711b9ba030d5; _gid=GA1.2.1024025882.1528670382; cookiescriptaccept=visit', } def get_item(item_id): market = requests.get('https://www.novaragnarok.com/?module=vending&action=item&id=%s'% item_id, headers = headers) s = BeautifulSoup(market.text, 'html.parser') name = s.h2.span.a.text img = 'https://www.novaragnarok.com/%s' % s.h2.img['src'] h_table = s.find_all('table', class_='horizontal-table') thead = h_table[1].thead ths = thead.tr.find_all('th') for n in range(len(ths)): if ths[n].a: if 'Price' in ths[n].a.text: index = n break tbody = h_table[1].tbody tr = tbody.find_all('tr')[0] td = tr.find_all('td')[index].span return dict(name = name, price = td.text, image = img) def get_transaction_history(item_id): thistory = [] page = 1 while len(thistory) < 15: market = requests.get('https://www.novaragnarok.com/?module=vending&action=itemhistory&id=%s&p=%s'% (item_id, page), headers = headers) s = BeautifulSoup(market.text, 'html.parser') h2s = s.find_all('h2') for h2 in h2s: if 'Transaction History' in h2.text: hasTransaction = True break else: hasTransaction = False if hasTransaction: tables = s.find_all('table', class_='horizontal-table') if len(tables) <= 1: break trs = tables[1].tbody.find_all("tr") for idx in range(len(trs)): tds = trs[idx].find_all("td") date = re.match('.{8}', tds[0].text.strip()).group(0) price = tds[1].text.strip() thistory.append(dict(data = date, price = price)) page = page + 1 else: break print thistory get_transaction_history(4040) <file_sep>from flask import Flask, jsonify, request, render_template, json, redirect, url_for from flask_sqlalchemy import SQLAlchemy from crawler import get_item, get_transaction_history import os app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') db = SQLAlchemy(app) class Item(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, primary_key=True) item_id = db.Column(db.Integer, unique=True) name = db.Column(db.String(100)) price = db.Column(db.String(100)) image = db.Column(db.String(100)) def __init__(self, item_id, name, price, image): self.item_id = item_id self.name = name self.price = price self.image = image def __repr__(self): return json.dumps(dict( name = self.name, price = self.price, id = self.item_id, image = self.image ) ) @app.route('/') def home(): items = Item.query.paginate().items return render_template('home.html', items=items) @app.route('/transaction-history') def transaction_history(): item_id = request.args.get('id') thistory = get_transaction_history(item_id) return render_template('thistory.html', thistory=thistory) @app.route('/lowest-price') def lowest_price(): item_id = request.args.get('id') item = get_item(item_id) return jsonify(dict(price = item.get('price', ''))) @app.route('/add-item', methods=['POST']) def add_item(): item_id = request.form.get('item', '') item = get_item(item_id) price = item.get('price', '') name = item.get('name', '') image = item.get('image', '') dbcreate = Item(item_id, name, price, image) db.session.add(dbcreate) db.session.commit() return redirect(url_for('home')) if __name__ == '__main__': app.run(debug=True)
dc5b9db559e0a077647daea77db76cb762922587
[ "Markdown", "Python" ]
3
Markdown
murtinha/RO-market
57f801374b9052c31ec14a07afa2c56356d20f5c
45edc35ed2fce5500a3f1a26e499757bc9aa3bdd
refs/heads/master
<file_sep>package com.example.supratik.booklisting; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import java.io.InputStream; import java.lang.reflect.Array; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Currency; import java.util.List; import java.util.Locale; public class BookAdapter extends ArrayAdapter<Book> { //constructors public BookAdapter(Context context, ArrayList<Book> resource) { super(context, 0,resource); } // private ImageView thumbnail; @Override public View getView(int position, View convertView, ViewGroup parent) { View listItemView = convertView; if(listItemView == null){ if (listItemView == null) { listItemView = LayoutInflater.from(getContext()).inflate( R.layout.list_item, parent, false); } Book currentBook = getItem(position); ImageView thumbnail = listItemView.findViewById(R.id.thumbnail); /** download the corresponding thumbnail of the book and hook it to the listItem.*/ if(currentBook != null){ DownloadImageTask task = new DownloadImageTask(thumbnail); task.execute(currentBook.getThumbnailLinkString()); } TextView title = listItemView.findViewById(R.id.title); title.setText(currentBook.getTitle()); if(currentBook.getSale().equals("FOR_SALE")) { TextView amount = listItemView.findViewById(R.id.price); amount.setText(setCurrency(currentBook.getPrice(), currentBook.getCountry().toLowerCase())); } // else{ // TextView amount = listItemView.findViewById(R.id.price); // amount.setText(""); // } TextView authors = listItemView.findViewById(R.id.authors); try { authors.setText(getAuthorName((currentBook.getAuthors()))); } catch (JSONException e) { e.printStackTrace(); } } return listItemView; } public String getAuthorName(JSONArray authors) throws JSONException { StringBuilder AuthorName = new StringBuilder(); int c = 0; for(int i=0; i<authors.length(); i++){ if(i != authors.length()-1) { AuthorName.append(authors.getString(i)+" and "); } else { AuthorName.append(authors.getString(i)); } } return AuthorName.toString(); } public String setCurrency(double price,String country){ String Price = NumberFormat.getCurrencyInstance(new Locale("en",country)).format(price); return Price; } public class DownloadImageTask extends AsyncTask<String,Void,Bitmap>{ ImageView thumbnail; public DownloadImageTask(ImageView bmImage) { thumbnail = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap bmp = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); bmp = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return bmp; } protected void onPostExecute(Bitmap result) { thumbnail.setImageBitmap(result); } } }<file_sep>package com.example.supratik.booklisting; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import java.util.ArrayList; public class BookActivity extends AppCompatActivity { private BookAdapter mAdapter; private ArrayList<Book> booklist; private String BOOKS_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q="; //"https://www.googleapis.com/books/v1/volumes?q="+"&maxResults=20"; private TextView mEmptyView; // private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.booklist); String newString; if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if (extras == null) { newString = null; } else { newString = extras.getString("query"); } } else { newString = (String) savedInstanceState.getSerializable("query"); } ProgressBar progressBar = findViewById(R.id.progressbar); mEmptyView = findViewById(R.id.emptyView); BOOKS_REQUEST_URL = BOOKS_REQUEST_URL + newString + "&maxResults=20"; // booklist = BookUtils.extractBookList(BOOKS_REQUEST_URL); // // ListView listView = findViewById(R.id.list); // // mAdapter = new BookAdapter(this, new ArrayList<Book>()); // // listView.setAdapter(mAdapter); // BookAsyncTask task = new BookAsyncTask(); // task.execute(BOOKS_REQUEST_URL); ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); boolean isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting(); if (isConnected) { BookAsyncTask task = new BookAsyncTask(); task.execute(BOOKS_REQUEST_URL); } else { progressBar.setVisibility(View.GONE); mEmptyView.setText(R.string.no_internet); } } public Void updateUI(ArrayList<Book> booklist) { // booklist = BookUtils.extractBookList(BOOKS_REQUEST_URL); ListView listView = findViewById(R.id.list); mAdapter = new BookAdapter(this, booklist); listView.setAdapter(mAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Book book = mAdapter.getItem(position); Intent i = new Intent(); i.setAction(Intent.ACTION_VIEW); i.setData(Uri.parse(book.getInfoLink())); startActivity(i); } }); return null; } public class BookAsyncTask extends AsyncTask<String, Void, ArrayList<Book>> { @Override protected ArrayList<Book> doInBackground(String... urls) { booklist = BookUtils.extractBookList(urls[0]); return booklist; } @Override protected void onPostExecute(ArrayList<Book> books) { ProgressBar progressBar = findViewById(R.id.progressbar); progressBar.setVisibility(View.GONE); if (books != null && !books.isEmpty()) { updateUI(books); } else { mEmptyView.setText(R.string.no_book); } } } }
7101349d5f970984ec571b908ef73656ec821ca6
[ "Java" ]
2
Java
supratikkoley/Book_Listing
21e614b3d447595f5cd3a83f63cc77fcddd85e25
f0ca199382227dbb0854844b900e62dafb6a66a0
refs/heads/master
<file_sep><?php class TG_Vendor_Model_Action extends Mage_Core_Model_Abstract { function notifyVendors($observer = null) { $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); #$incrementId = '100000091'; $order = Mage::getModel('sales/order')->loadByIncrementId($incrementId); $vendorInfo = array(); if($order && $order->getId()){ foreach($order->getItemsCollection() as $item){ $productId = $item->getProductId(); $qtyOrdered = $item->getQtyOrdered(); if(($vendorId = Mage::helper('vendor')->getVendorId($productId))){ if(!array_key_exists($vendorId, $vendorInfo)){ $vendorInfo[$vendorId] = array(); } $product = Mage::getModel('catalog/product')->load($productId); $vendorInfo[$vendorId][] = $item; } } foreach($vendorInfo as $vendorId => $items ){ if(!($vendor = Mage::getModel('vendor/vendor')->load($vendorId)) || !$vendor->getId()){ continue; //associated vendor not found, skip } $vendorType = $vendor->getVendorType(); $vendorInstance = Mage::helper('vendor')->getVendorInstance($vendorType); $vendorInstance->load($vendorId); $method = 'notifyVendor'; $params = array($order, $items , $vendor); call_user_func_array(array($vendorInstance, $method), $params); } } return $observer; } } ?> <file_sep><?php class TG_Vendor_Model_EmailNotify extends TG_Vendor_Model_Abstract { protected $_vendorType = 'email_notification'; const EMAIL_TEMPLATE_XML_PATH = 'sales/order_notify/vendor_template'; public function _construct() { parent::_construct(); $this->_init('vendor/vendor'); } public function getEmailList() { //$email = $this->getEmail(); $email = $this->getVendorEmail(); $delimiter = ','; return explode( $delimiter , $email ); } public function getCcList() { $ccList = $this->getCcTo(); if(empty($ccList)){ return null; } $delimiter = ','; return explode( $delimiter , $ccList ); } public function notifyVendor($order, $items) { $vendorId = $this->getVendorId(); $orderId = $order->getId(); $mailSubject = 'New Order from Nursing Uniforms'; //Should come from config $sender = Array('name' => '<NAME>', 'email' => '<EMAIL>', ); //Should come from config $email = $this->getEmailList(); $name = '<NAME>'; $vars = Array('items' => $items, 'vendor' => $this, /*'product'=> $product,*/ 'order' => $order, ); $storeId = Mage::app()->getStore()->getId(); $templateId = Mage::getStoreConfig(self::EMAIL_TEMPLATE_XML_PATH); $translate = Mage::getSingleton('core/translate'); $mailTemplate = Mage::getModel('core/email_template') ->setTemplateSubject($mailSubject); if(($ccList = $this->getCcList()) && is_array($ccList)){ foreach($ccList as $cc){ $mailTemplate->addBcc($cc); } } $mailTemplate->sendTransactional($templateId, $sender, $email, $name, $vars, $storeId); $translate->setTranslateInline(true); foreach($items as $item){ $vendorLog = Mage::getModel('vendor/log') ->setProductId($item->getProductId()) ->setVendorId($this->getVendorId()) ->setItemId($item->getId()) ->setOrderId($orderId) ->setStatus(1) ->save(); } return true; } } <file_sep><?php class TG_Vendor_Block_Email_Items extends Mage_Core_Block_Template //Mage_Sales_Block_Items_Abstract { }<file_sep><?php class TG_Vendor_Block_Adminhtml_Vendor_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form { public function initForm() { $form = new Varien_Data_Form(); $form->setHtmlIdPrefix('_vendor'); $form->setFieldNameSuffix('vendor'); $vendorType = $this->getRequest()->getParam('vendor_type', null); if(!$vendorType){ if($vendorData = Mage::registry('vendor_data')){ $vendorType = $vendorData->getVendorType(); } } $vendorList = Mage::getConfig()->getNode('default/vendor')->asArray(); $fieldset = $form->addFieldset('vendor_form', array('legend'=>Mage::helper('vendor')->__('Vendor information'))); $fieldset->addField('name', 'text', array( 'label' => Mage::helper('vendor')->__('Vendor Name'), 'class' => '', 'required' => true, 'name' => 'name', )); foreach($vendorList[$vendorType]['fields'] as $name => $vendor){ $label = (isset($vendor['label'])) ? (string)$vendor['label']: ''; $class = (isset($vendor['class'])) ? (string)$vendor['class']: ''; $type = (isset($vendor['type'])) ? (string)$vendor['type'] : 'text'; $required = (isset($vendor['required']) && $vendor['required'] == 1) ? true: false; $fieldset->addField($name, $type, array( 'label' => Mage::helper('vendor')->__($label), 'class' => $class, 'required' => $required, 'name' => $name, )); } if ( Mage::getSingleton('adminhtml/session')->getVendorData() ){ $form->setValues(Mage::getSingleton('adminhtml/session')->getVendorData()); Mage::getSingleton('adminhtml/session')->setVendorData(null); } elseif ( Mage::registry('vendor_data') ) { $form->setValues(Mage::registry('vendor_data')->getData()); } $fieldset->addField('vendor_type', 'hidden', array( 'name' => 'vendor_type', 'value' => $vendorType, )); $this->setForm($form); return $this; } }<file_sep><?php class TG_Vendor_Model_FtpNotify extends TG_Vendor_Model_Abstract { protected $_vendorType = 'ftp_notification'; public function _construct() { parent::_construct(); $this->_init('vendor/vendor'); } public function notifyVendor($order, $items) { #echo $this->getErrorLogEmail(); $orderId = $order->getId(); $realOrderId = $order->getIncrementId(); $shipping = $order->getShippingAddress(); $vendorItemLog = array(); $filename = $this->getFileName(); $remotePath = $this->getRemotePath(); $localTmpPath = "/var/b2b/orders/"; $localLogPath = "/var/b2b/errors/"; $root = Mage::getBaseDir(); $hFilename = "{$filename}{$realOrderId}h.csv"; $hFilePath = "{$root}{$localTmpPath}$hFilename"; //Drop Shipping $priorityMailCode = 'PS1'; $headerValues = array( 'CustomerID' => $this->getCustomerId(), 'PO' => $realOrderId, //$shipping->getPostcode(), 'ShipMethod' => $priorityMailCode, 'DropShip' => 1, 'FirstName' => $shipping->getFirstname(), 'LastName' => $shipping->getLastname(), 'Address1' => $shipping->getStreet(1), 'Address2' => $shipping->getStreet(2), 'City' => $shipping->getCity(), 'State' => $shipping->getRegionCode(), 'Zip' => $shipping->getCity(), 'Country' => $shipping->getCountry(), ); $headerContent = implode(',', array_keys($headerValues))."\n"; foreach($headerValues as $key => $value){ $headerContent .= '"'.$value.'",'; } try{ if(!is_dir("{$root}{$localTmpPath}")){ mkdir("{$root}{$localTmpPath}", 0777, true); } $fp = fopen($hFilePath, "w"); fputs($fp, $headerContent); fclose($fp); $dFilename = "{$filename}{$realOrderId}d.csv"; $dFilePath = "{$root}{$localTmpPath}$dFilename"; $detailsContent = "PO,UPC,Quantity"."\n"; foreach($items as $item){ $PO = $realOrderId; //$shipping->getPostcode(); $UPC = $item->getSku(); $Quantity = $item->getQtyOrdered(); $detailsContent .= '"'.$PO.'",'; $detailsContent .= '"'.$UPC.'",'; $detailsContent .= '"'.$Quantity.'",' ."\n"; $vendorLog = Mage::getModel('vendor/log') ->setProductId($item->getProductId()) ->setVendorId($this->getVendorId()) ->setItemId($item->getId()) ->setOrderId($orderId) ->setStatus(0); $vendorItemLog [$item->getId()] = $vendorLog; } $fp = fopen($dFilePath, "w"); fputs($fp, $detailsContent); fclose($fp); $ftp_server = $this->getFtpHost(); $ftp_user_name = $this->getFtpUser(); $ftp_user_pass = $this->getFtpPassword(); $con_id = ftp_connect($ftp_server); $login_result = ftp_login($con_id, $ftp_user_name, $ftp_user_pass); if ((!$con_id) || (!$login_result)) { throw new Exception("FTP connection has failed!"); } $upload = ftp_put($con_id, $remotePath.$hFilename, $hFilePath, FTP_BINARY); $upload = ftp_put($con_id, $remotePath.$dFilename, $dFilePath, FTP_BINARY); # $upload = ftp_put($con_id, $remotePath.$remotePath.$hFilename, $hFilePath, FTP_BINARY); # $upload = ftp_put($con_id, $remotePath.$remotePath.$dFilename, $dFilePath, FTP_BINARY); }catch(Exception $e){ foreach($vendorItemLog as $vendorLog){ $vendorLog->setStatus(0)->save(); } if($this->getErrorLogEmail()){ $sendToName = 'Site Admin'; $sendToEmail = $this->getErrorLogEmail(); $sentFromEmail = '<EMAIL>'; $msg = 'Vendor notification can not be sent <br/>'. 'Details:- <br/>'. $e->getMessage() ; $mail = Mage::getModel('core/email'); $mail->setToName($sendToName); $mail->setToEmail($sendToEmail); $mail->setBody($msg); $mail->setSubject("Vendor Notification Error - Order Id {$realOrderId}"); $mail->setFromEmail($sentFromEmail); $mail->setFromName('Site Admin'); $mail->setType('html'); try { $mail->send(); } catch (Exception $e2) { //echo $e2->getMessage(); } } if(!is_dir("{$root}{$localLogPath}")){ mkdir("{$root}{$localLogPath}", 0777, true); } $errorFile = "{$root}{$localLogPath}error_log_{$realOrderId}.txt"; $fp = fopen($errorFile, "w"); fputs($fp, $e->getMessage()); fclose($fp); return false; } foreach($vendorItemLog as $vendorLog){ $vendorLog->setStatus(1)->save(); } } }<file_sep># TG_Vendor - Admin module to manage vendors & their email address, email body, ftp address etc. - Set different vendors to different products - On order placement, product info with customer shipment infor mailed to vendor or ftp uploaded to ftp server <file_sep><?php class TG_Vendor_Model_Log extends Mage_Core_Model_Abstract { public function _construct() { parent::_construct(); $this->_init('vendor/log'); } } <file_sep><?php class TG_Vendor_Model_Mysql4_Vendor extends Mage_Core_Model_Mysql4_Abstract { public function _construct() { // Note that the functionalarea_id refers to the key field in your database table. $this->_init('vendor/vendor', 'vendor_id'); } }<file_sep><?php class TG_Vendor_Model_Abstract extends Mage_Core_Model_Abstract { protected $_vendorType = Null; public function _construct() { parent::_construct(); $this->_init('vendor/vendor'); } public function validate() { return $this; } protected function _beforeSave() { $_fieldValues = array(); if($this->_vendorType){ $vendorConfig = Mage::helper('vendor')->getVendorConfig($this->_vendorType); if(!empty($vendorConfig) && !empty($vendorConfig['fields'])){ foreach($vendorConfig['fields'] as $key => $field){ $_fieldValues[$key] = $this->getData($key); } } } $this->setFieldValues(serialize($_fieldValues)); } public function _afterLoad() { $_fieldValues = unserialize($this->getFieldValues()); if($_fieldValues){ foreach($_fieldValues as $key => $val){ $this->setData($key , $val); } } } } <file_sep> Dear {{htmlescape var=$vendor.getName()}},<br/> You have a new order from NursingUniforms.net <br/> <br/> Customer: {{htmlescape var=$vendor.getClientName()}}<br/> Account Number: {{htmlescape var=$vendor.getClientId()}}<br/> <br/> Payment Method: Please bill our credit card on file for the order. <br/> {{layout handle="vendor_email_items" items=$items}}<br/> =====================================================<br/> Shipping Address: <br/> {{var order.getShippingAddress().format('html')}}<br/> Shipping Method: {{var order.getShippingDescription()}}<br/> Please notify: <EMAIL> when the order is shipped. <br/> If you have any further queries or issues please don't hesitate to contact us. <br/> <br/> <br/> Kind Regards,<br/> <NAME><br/> Nursing Uniforms<br/> tel. 248.626.2129<br/> <file_sep><?php class TG_Vendor_Block_Adminhtml_Vendor_Grid extends Mage_Adminhtml_Block_Widget_Grid { public function __construct() { parent::__construct(); $this->setId('vendorGrid'); $this->setDefaultSort('entity_id'); $this->setDefaultDir('ASC'); $this->setSaveParametersInSession(true); } protected function _prepareCollection() { $collection = Mage::getModel('vendor/vendor')->getCollection(); $this->setCollection($collection); return parent::_prepareCollection(); } protected function _prepareColumns() { $this->addColumn('vendor_id', array( 'header' => Mage::helper('vendor')->__('ID'), 'align' =>'right', 'width' => '50px', 'index' => 'vendor_id', )); $this->addColumn('name', array( 'header' => Mage::helper('vendor')->__('Vendor Info'), 'align' =>'left', 'index' => 'name', )); $vendorList = Mage::getConfig()->getNode('default/vendor')->asArray(); $vendorOptions = array(); foreach($vendorList as $key => $vendor){ $vendorOptions[$key] = $vendor['name']; } $this->addColumn('vendor_type', array( 'header'=> Mage::helper('catalog')->__('Vendor Type'), 'index' => 'vendor_type', 'type' => 'options', 'options' => $vendorOptions, )); $this->addColumn('action', array( 'header' => Mage::helper('vendor')->__('Action'), 'width' => '100', 'type' => 'action', 'getter' => 'getId', 'actions' => array( array( 'caption' => Mage::helper('vendor')->__('Edit'), 'url' => array('base'=> '*/*/edit'), 'field' => 'id' ) ), 'filter' => false, 'sortable' => false, 'index' => 'stores', 'is_system' => true, )); return parent::_prepareColumns(); } public function getRowUrl($row) { return $this->getUrl('*/*/edit', array('id' => $row->getId())); } }<file_sep><?php class TG_Vendor_Block_Adminhtml_Catalog_Product_Edit_Tabs extends Mage_Adminhtml_Block_Catalog_Product_Edit_Tabs { protected function _prepareLayout() { parent::_prepareLayout(); $product = $this->getProduct(); if (!($setId = $product->getAttributeSetId())) { $setId = $this->getRequest()->getParam('set', null); } if ($setId) { //add logic to check if vendor module on and have any vendor information $this->addTab('vendor_information', array( 'label' => Mage::helper('vendor')->__('Vendor Information'), 'content' => $this->getLayout()->createBlock('vendor/adminhtml_catalog_product_edit_tab_vendor')->toHtml(), 'active' => false , )); } //return parent::_prepareLayout(); } } <file_sep><?php class TG_Vendor_Model_Mysql4_Vendor_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract { public function _construct() { parent::_construct(); $this->_init('vendor/vendor'); } }<file_sep><?php class TG_Vendor_Model_Mysql4_Log extends Mage_Core_Model_Mysql4_Abstract { public function _construct() { // Note that the functionalarea_id refers to the key field in your database table. $this->_init('vendor/log', 'entity_id'); } }<file_sep><?php class TG_Vendor_Block_Adminhtml_Catalog_Product_Edit_Tab_Vendor extends Mage_Adminhtml_Block_Template { public function __construct() { parent::__construct(); $this->setTemplate('vendor/catalog/product/vendor.phtml'); } public function getVendorList() { return Mage::getModel('vendor/vendor') ->getCollection(); } public function getProductVendorId() { $product = Mage::registry('product'); //$product = $this->getProduct(); if($product->getId()){ $productId = $product->getId(); $assocVendor = Mage::getModel('vendor/product') ->getCollection() ->addFieldToFilter('product_id',$productId ); if($assocVendor->count()){ return $assocVendor->getFirstItem()->getVendorId (); } } return null; } } <file_sep><?php class TG_Vendor_Block_Adminhtml_Items_Product extends Mage_Adminhtml_Block_Widget_Grid { public function __construct() { parent::__construct(); $this->setId('vendor_product_search_grid'); $this->setDefaultSort('product_id'); $this->setUseAjax(true); } protected function _beforeToHtml() { $this->setId($this->getId().'_'.$this->getIndex()); $this->getChild('reset_filter_button')->setData('onclick', $this->getJsObjectName().'.resetFilter()'); $this->getChild('search_button')->setData('onclick', $this->getJsObjectName().'.doFilter()'); return parent::_beforeToHtml(); } protected function _prepareCollection() { $collection = Mage::getModel('catalog/product')->getCollection() ->setStore($this->_getStore()) ->addAttributeToSelect('name') ->addAttributeToSelect('sku') ->addAttributeToSelect('price') ->addAttributeToSelect('attribute_set_id'); $vendorId = $this->getRequest()->getParam('id', null); $assocProducts = Mage::getModel('vendor/product') ->getCollection() ->addFieldToFilter('vendor_id',$vendorId); $excludeIds = array(); foreach($assocProducts as $item){ $excludeIds[] = $item->getProductId(); } //$collection->addIdFilter($excludeIds, true); $collection->addFieldToFilter('entity_id', array('in'=>$excludeIds)); Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($collection); $this->setCollection($collection); return parent::_prepareCollection(); } protected function _prepareColumns() {/* $this->addColumn('in_vendor', array( 'header_css_class' => 'a-center', 'type' => 'checkbox', 'name' => 'in_vendor', 'values' => $this->_getSelectedProducts(), 'align' => 'center', 'index' => 'in_vendor' ));*/ $this->addColumn('product_id', array( 'header' => Mage::helper('sales')->__('ID'), 'sortable' => true, 'width' => '60px', 'index' => 'entity_id' )); $this->addColumn('name', array( 'header' => Mage::helper('sales')->__('Product Name'), 'index' => 'name', 'column_css_class'=> 'name' )); $sets = Mage::getResourceModel('eav/entity_attribute_set_collection') ->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId()) ->load() ->toOptionHash(); $this->addColumn('set_name', array( 'header'=> Mage::helper('catalog')->__('Attrib. Set Name'), 'width' => '100px', 'index' => 'attribute_set_id', 'type' => 'options', 'options' => $sets, )); $this->addColumn('sku', array( 'header' => Mage::helper('sales')->__('SKU'), 'width' => '80px', 'index' => 'sku', 'column_css_class'=> 'sku' )); $this->addColumn('price', array( 'header' => Mage::helper('sales')->__('Price'), 'align' => 'center', 'type' => 'currency', 'currency_code' => $this->_getStore()->getCurrentCurrencyCode(), 'rate' => $this->_getStore()->getBaseCurrency()->getRate($this->_getStore()->getCurrentCurrencyCode()), 'index' => 'price' )); return parent::_prepareColumns(); } /* protected function _prepareMassaction() { $this->setMassactionIdField('in_vendor'); $this->getMassactionBlock()->setFormFieldName('delete_product'); $this->getMassactionBlock()->addItem('add', array( 'label' => $this->__('Delete Products from Vendor'), 'url' => $this->getUrl('\*//*/massdel', array('_current'=>true)), )); return $this; }*/ protected function _getStore() { return Mage::app()->getStore($this->getRequest()->getParam('store')); } }<file_sep><?php class TG_Vendor_Helper_Data extends Mage_Core_Helper_Abstract { public function getVendorConfig($vendorType = null) { if($vendorType){ $vendorList = Mage::getConfig()->getNode('default/vendor')->asArray(); if(array_key_exists($vendorType, $vendorList)){ return $vendorList[$vendorType]; } } return null; } public function getVendorInstance($vendorType) { $vendorConfig = $this->getVendorConfig($vendorType); $vendorInit = (empty($vendorConfig['class']))? 'vendor/vendor' : $vendorConfig['class']; $vendorInstance = Mage::getModel($vendorInit); if(!$vendorInstance){ throw new Exception("Couldn't load model for vendor type {$vendorType}!"); } return $vendorInstance; } public function getVendorId($productId) { $vendorCollection = Mage::getModel('vendor/product') ->getCollection() ->addFieldToFilter('product_id', $productId) ->load(); if($vendorCollection->count() ) { return $vendorCollection ->getFirstItem()->getVendorId(); } return null; } public function getVendorOptions() { $vendorCollection = Mage::getModel('vendor/vendor') ->getCollection() ->load(); $vendorArray = array(); foreach($vendorCollection->getItems() as $vendor){ $vendorArray[] = array( 'label'=>$vendor->getName(), 'value'=>$vendor->getId()); } return $vendorArray; } }<file_sep><?php class TG_Vendor_Adminhtml_VendorController extends Mage_Adminhtml_Controller_action { protected function _initAction() { $this->loadLayout() ->_setActiveMenu('system/customer_form/functionalarea'); return $this; } public function indexAction() { $this->_initAction() ->renderLayout(); } public function massProductSubscriptionAction() { $productIds = $this->getRequest()->getParam('product'); $vendorId = $this->getRequest()->getParam('vendor_id'); if(isset($vendorId) && is_array($productIds)){ $vendor = Mage::getModel('vendor/vendor')->load($vendorId); if($vendor && $vendor->getId()){ foreach($productIds as $productId){ $assocVendor = Mage::getModel('vendor/product') ->getCollection() ->addFieldToFilter('product_id',$productId) ->load(); $assocId = ($assocVendor->count())? $assocVendor->getFirstItem()->getId():null; $model = Mage::getModel('vendor/product'); if($assocId){ $model->load($assocId); } $model->setProductId($productId) ->setVendorId($vendorId) ->save(); } } } $this->_redirect('adminhtml/catalog_product/'); } public function editAction() { $id = $this->getRequest()->getParam('id'); $model = Mage::getModel('vendor/abstract')->load($id); if ($model->getId() || $id == 0) { $data = Mage::getSingleton('adminhtml/session')->getFormData(true); if (!empty($data)) { $model->setData($data); } Mage::register('vendor_data', $model); $this->loadLayout(); $this->_setActiveMenu('system/customer_form/functionalarea'); $this->getLayout()->getBlock('head')->setCanLoadExtJs(true); $this->_addContent($this->getLayout()->createBlock('vendor/adminhtml_vendor_edit')) ->_addLeft($this->getLayout()->createBlock('vendor/adminhtml_vendor_edit_tabs')); $this->renderLayout(); } else { Mage::getSingleton('adminhtml/session') ->addError(Mage::helper('vendor') ->__('Item does not exist')); $this->_redirect('*/*/'); } } public function newAction() { $this->_forward('edit'); } public function saveAction() { if ($data = $this->getRequest()->getPost('vendor')) { try { $vendorList = Mage::getConfig()->getNode('default/vendor')->asArray(); $vendorType = (empty($data['vendor_type']))? null: $data['vendor_type']; if(!array_key_exists($vendorType, $vendorList)){ throw new Exception('Wrong vendor type!'); } $vendorConfig = $vendorList[$vendorType]; $vendorInit = (empty($vendorConfig['class']))? 'vendor/vendor' : $vendorConfig['class']; $vendorInstance = Mage::getModel($vendorInit); if(!$vendorInstance){ throw new Exception("Couldn't load model for vendor type {$vendorType}!"); } $vendorInstance->setData($data); $vendorInstance->setId($this->getRequest()->getParam('id', null)); $vendorInstance->validate()->save(); Mage::getSingleton('adminhtml/session') ->addSuccess(Mage::helper('vendor') ->__('Vendor Information was successfully saved')); Mage::getSingleton('adminhtml/session')->setFormData(false); if ($this->getRequest()->getParam('back')) { $this->_redirect('*/*/edit', array('id' => $model->getId())); return; } $this->_redirect('*/*/'); return; } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); Mage::getSingleton('adminhtml/session')->setFormData($data); $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id'))); return; } } Mage::getSingleton('adminhtml/session') ->addError(Mage::helper('vendor') ->__('Unable to find item to save')); $this->_redirect('*/*/'); } public function deleteAction() { if( $this->getRequest()->getParam('id') > 0 ) { try { $model = Mage::getModel('vendor/vendor'); $model->setId($this->getRequest()->getParam('id')) ->delete(); Mage::getSingleton('adminhtml/session') ->addSuccess(Mage::helper('adminhtml') ->__('Vendor Information was successfully deleted')); $this->_redirect('*/*/'); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id'))); } } $this->_redirect('*/*/'); } public function massDeleteAction() { $functionalareaIds = $this->getRequest()->getParam('vendor'); if(!is_array($functionalareaIds)) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)')); } else { try { foreach ($functionalareaIds as $functionalareaId) { $functionalarea = Mage::getModel('vendor/vendor')->load($functionalareaId); $functionalarea->delete(); } Mage::getSingleton('adminhtml/session')->addSuccess( Mage::helper('adminhtml')->__( 'Total of %d record(s) were successfully deleted', count($functionalareaIds) ) ); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } } $this->_redirect('*/*/index'); } public function assocGridAction() { $this->loadLayout(); return $this->getResponse()->setBody( $this->getLayout() ->createBlock('vendor/adminhtml_items_product') ->setIndex($this->getRequest()->getParam('index')) ->toHtml() ); } }<file_sep><?php $installer = $this; $installer->startSetup(); $installer->run(" DROP TABLE IF EXISTS {$this->getTable('vendor')}; CREATE TABLE {$this->getTable('vendor')} ( `vendor_id` int(11) NOT NULL auto_increment, `name` varchar(255) NOT NULL, `field_values` text NOT NULL, `vendor_type` varchar(127) NOT NULL, PRIMARY KEY (`vendor_id`) ) ENGINE=MyISAM ; DROP TABLE IF EXISTS {$this->getTable('product_vendor')}; CREATE TABLE {$this->getTable('product_vendor')} ( `entity_id` int(11) NOT NULL AUTO_INCREMENT, `product_id` int(11) NOT NULL, `vendor_id` int(11) NOT NULL, PRIMARY KEY (`entity_id`), UNIQUE KEY `product_id` (`product_id`) ) ENGINE=MyISAM ; DROP TABLE IF EXISTS {$this->getTable('vendor_notification_log')}; CREATE TABLE {$this->getTable('vendor_notification_log')} ( `entity_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `order_id` INT NOT NULL , `item_id` INT NOT NULL , `product_id` INT NOT NULL, `vendor_id` INT NOT NULL , `status` SMALLINT NOT NULL ) ENGINE = MYISAM ; "); $installer->endSetup(); <file_sep><?php class TG_Vendor_Model_Product extends Mage_Core_Model_Abstract { public function _construct() { parent::_construct(); $this->_init('vendor/product'); } }<file_sep><?php class TG_Vendor_Model_Mysql4_Log_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract { public function _construct() { parent::_construct(); $this->_init('vendor/log'); } } <file_sep><?php class TG_Vendor_Model_Vendor extends Mage_Core_Model_Abstract { public function _construct() { parent::_construct(); $this->_init('vendor/vendor'); } } <file_sep><?php class TG_Vendor_Model_FtpNotify extends TG_Vendor_Model_Abstract { protected $_vendorType = 'ftp_notification'; const EMAIL_TEMPLATE_XML_PATH = 'sales/order_notify/vendor_template'; public function _construct() { parent::_construct(); $this->_init('vendor/vendor'); } public function notifyVendor($order, $items) { $lineFeed = "\r\n"; $orderId = $order->getId(); $realOrderId = (string) $order->getIncrementId(); $shipping = $order->getShippingAddress(); $vendorItemLog = array(); $filename = $this->getFileName(); $remotePath = $this->getRemotePath(); $localTmpPath = "/var/b2b/orders/"; $localLogPath = "/var/b2b/errors/"; $root = Mage::getBaseDir(); $hFilename = "{$filename}{$realOrderId}h.csv"; $hFilePath = "{$root}{$localTmpPath}$hFilename"; //Drop Shipping $priorityMailCode = 'PS1'; $headerValues = array( 'CustomerID' => $this->getCustomerId(), 'PO' => $realOrderId, //$shipping->getPostcode(), 'ShipMethod' => $priorityMailCode, 'DropShip' => 1, 'FirstName' => $shipping->getFirstname(), 'LastName' => $shipping->getLastname(), 'Address1' => $shipping->getStreet(1), 'Address2' => $shipping->getStreet(2), 'City' => $shipping->getCity(), 'State' => $shipping->getRegionCode(), 'Zip' => $shipping->getPostcode(), 'Country' => $shipping->getCountry(), ); $headerContent = implode(',', array_keys($headerValues)).$lineFeed; /* foreach($headerValues as $key => $value){ $headerContent .= '"'.$value.'",'; }*/ foreach($headerValues as $key => $value){ $headerContent .= $value. ','; } $headerContent = eregi_replace(',$', '', $headerContent); try{ if(!is_dir("{$root}{$localTmpPath}")){ mkdir("{$root}{$localTmpPath}", 0777, true); } $fp = fopen($hFilePath, "w"); //ftp_pasv($fp, true); fputs($fp, $headerContent); fclose($fp); $dFilename = "{$filename}{$realOrderId}d.csv"; $dFilePath = "{$root}{$localTmpPath}$dFilename"; $detailsContent = "PO,UPC,Quantity".$lineFeed; foreach($items as $item){ $PO = $realOrderId; //$shipping->getPostcode(); $UPC = $item->getSku(); $Quantity = (int)$item->getQtyOrdered(); $detailsContent .= $PO.','; $detailsContent .= $UPC.','; $detailsContent .= $Quantity.$lineFeed; $vendorLog = Mage::getModel('vendor/log') ->setProductId($item->getProductId()) ->setVendorId($this->getVendorId()) ->setItemId($item->getId()) ->setOrderId($orderId) ->setStatus(0); $vendorItemLog [$item->getId()] = $vendorLog; } $fp = fopen($dFilePath, "w"); //ftp_pasv($fp, true); fputs($fp, $detailsContent); fclose($fp); $ftp_server = $this->getFtpHost(); $ftp_user_name = $this->getFtpUser(); $ftp_user_pass = $this->getFtpPassword(); $con_id = ftp_connect($ftp_server); $login_result = ftp_login($con_id, $ftp_user_name, $ftp_user_pass); if ((!$con_id) || (!$login_result)) { throw new Exception("FTP connection has failed!"); } ftp_pasv($con_id, true); $upload = ftp_put($con_id, $remotePath.$hFilename, $hFilePath, FTP_BINARY); $upload = ftp_put($con_id, $remotePath.$dFilename, $dFilePath, FTP_BINARY); # $upload = ftp_put($con_id, $remotePath.$remotePath.$hFilename, $hFilePath, FTP_BINARY); # $upload = ftp_put($con_id, $remotePath.$remotePath.$dFilename, $dFilePath, FTP_BINARY); }catch(Exception $e){ foreach($vendorItemLog as $vendorLog){ $vendorLog->setStatus(0)->save(); } if($this->getErrorLogEmail()){ $sendToName = 'Site Admin'; $sendToEmail = $this->getErrorLogEmail(); $sentFromEmail = '<EMAIL>'; $msg = 'Vendor notification can not be sent <br/>'. 'Details:- <br/>'. $e->getMessage() ; $mail = Mage::getModel('core/email'); $mail->setToName($sendToName); $mail->setToEmail($sendToEmail); $mail->setBody($msg); $mail->setSubject("Vendor Notification Error - Order Id {$realOrderId}"); $mail->setFromEmail($sentFromEmail); $mail->setFromName('Site Admin'); $mail->setType('html'); try { $mail->send(); } catch (Exception $e2) { //echo $e2->getMessage(); } } if(!is_dir("{$root}{$localLogPath}")){ mkdir("{$root}{$localLogPath}", 0777, true); } $errorFile = "{$root}{$localLogPath}error_log_{$realOrderId}.txt"; $fp = fopen($errorFile, "w"); //ftp_pasv($fp, true); fputs($fp, $e->getMessage()); fclose($fp); return false; } if($this->getAdminEmail()){ $mailSubject = 'New Order from Nursing Uniforms'; //Should come from config $sender = Array('name' => '<NAME>', 'email' => '<EMAIL>', ); //Should come from config $email = explode(',', $this->getAdminEmail()); $name = '<NAME>'; $vars = Array('items' => $items, 'vendor' => $this, /*'product'=> $product,*/ 'order' => $order, ); $storeId = Mage::app()->getStore()->getId(); $templateId = Mage::getStoreConfig(self::EMAIL_TEMPLATE_XML_PATH); $translate = Mage::getSingleton('core/translate'); $mailTemplate = Mage::getModel('core/email_template') ->setTemplateSubject($mailSubject); $mailTemplate->sendTransactional($templateId, $sender, $email, $name, $vars, $storeId); $translate->setTranslateInline(true); } foreach($vendorItemLog as $vendorLog){ $vendorLog->setStatus(1)->save(); } } }
b46c08f81575232d4f880c60eca56f102cf05dc7
[ "Markdown", "HTML", "PHP" ]
23
PHP
asad01304/TG_Vendor
25d0bd4b78e5e7a8f4f72f407a13ecb5b5f92891
eaaa7163222f641f9ee289d060325a4a635bb674
refs/heads/master
<repo_name>atereshkin/render.arabica<file_sep>/app.py import os import subprocess import string import random import tempfile import hashlib import re from flask import Flask, request, send_file import svgwrite app = Flask(__name__) def random_string(length): return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(length)) def sanitize_fname(value): return re.sub('[^\w\s-]', '', value) @app.route('/text-to-svg/', methods=['POST']) def hello_world(): if 'text' not in request.form: return #TODO 405 bad request text = request.form['text'] assert len(text) < 10000 download_fname = sanitize_fname(request.form['filename']) assert len(download_fname) <= 16 fname = os.path.join(tempfile.gettempdir(), '{}-{}.svg'.format(hashlib.md5(text.encode('utf-8')).hexdigest(), random_string(5))) dwg = svgwrite.Drawing(fname, size=('100px', '100px'),) txt_el = dwg.text('', font_size='64px', direction='rtl', text_anchor='middle', writing_mode='rl-tb', font_family='Noto Sans Arabic') for idx, line in enumerate(text.split('\n')): tspan = dwg.tspan(line, x='0', dy=['0.6em'] if idx == 0 else ['1.2em']) txt_el.add(tspan) dwg.add(txt_el) dwg.save() subprocess.run(['xvfb-run', 'inkscape', '--with-gui', '--verb', 'EditSelectAll;ObjectToPath;FitCanvasToDrawing;FileSave;FileQuit', fname]) return send_file(fname, mimetype='image/svg+xml', as_attachment=True, download_name='{}.svg'.format(download_fname)) <file_sep>/Dockerfile # syntax=docker/dockerfile:1 FROM debian:bullseye-slim RUN apt-get update RUN apt-get -y install --no-install-recommends inkscape xvfb xauth at-spi2-core python3 python3-pip fonts-noto-core WORKDIR /app COPY . . RUN pip install -r reqs.txt CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 app:app
37f7a68ac23b261be8c7d96b3c33cccb47ae226e
[ "Python", "Dockerfile" ]
2
Python
atereshkin/render.arabica
8642467fdd371a69358f0f4a8e1d1f84f73cb964
8873bd927365a6eb5bae1be52e0917de788a0e12
refs/heads/master
<repo_name>kdgosik/apps<file_sep>/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> # Web applications <img src="http://logo-logos.com/wp-content/uploads/2016/10/Docker_logo_logotype.png" width=100 align="right" /> <img src="https://www.rstudio.com/wp-content/uploads/2014/04/shiny.png" width=100 align="right" /> <img src="http://flask.pocoo.org/static/logo/flask.png" width=100 align="right" /> This repo contains code for building and deploying [web applications](https://en.wikipedia.org/wiki/Web_application) (e.g. [shiny](https://cran.r-project.org/package=shiny), [flask](http://flask.pocoo.org/), [Go](https://golang.org/doc/articles/wiki/) and [node](https://medium.com/@adnanrahic/hello-world-app-with-node-js-and-express-c1eb7cfa8a30)) This repo is heavily borrowed from [here](https://github.com/cpsievert/apps) and adapted for apps that I have created. ## Run an app (as a docker container) Each app has it's own [Docker](https://www.docker.com/) container, as well as a [image tag on DockerHub](https://hub.docker.com/r/kdgosik/apps/builds/), so you can easily run apps on your local machine; for example, this will run the [clifford-attractor (shiny) app](https://github.com/kdgosik/apps/tree/master/shiny/apps/clifford-attractor) on <http://localhost:3838> ### shiny ```shell docker run -p 3838:3838 kdgosik/apps:shiny-clifford-attractor ``` ### flask ```shell docker run -p 3000:80 kdgosik/apps:flask-static-example ``` ### go ```shell docker run -p 8080:8080 kdgosik/apps:goapp-static-example ``` ### node ```shell docker run -p 3000:3000 kdgosik/apps:node-static-example ``` If you'd like to run a particular app in this repo, you can get the relevant image tag from the [`application.yml`](https://github.com/kdgosik/apps/blob/master/application.yml) file. ## Acquire all the app images To run all the applications, you'll need to pull (or build) all the corresponding docker images. A necessary first step is to pull (or build) the corresponding docker images. Either way, I'd suggest cloning this repo: ```shell git clone https://github.com/kdgosik/apps.git cd apps ``` Now you can run the `make` command to *build* all the images or `make pull` to pull them from [my registry](https://hub.docker.com/r/kdgosik/apps/). ## Run all the apps via shinyproxy The [`application.yml`](https://github.com/cpsievert/apps/blob/master/application.yml) can be used/modified to (securely) run all the applications as a service via [shinyproxy](https://www.shinyproxy.io/). See the blog post by the original creator (coming soon). ```shell wget https://www.shinyproxy.io/downloads/shinyproxy-1.0.1.jar java -jar shinyproxy-1.0.1.jar ``` ## Contributing Some guidelines for adding new apps: ### shiny * Run `make shiny app=my-app` (replacing `my-app` with a suitable name). * Place your shiny app under the new `shiny/apps/my-app` directory. * Update install.R file to reflect the necessary packages for R to install. * Add `docker build -t kdgosik/apps:shiny-my-app shiny/apps/my-app` to the [Makefile](https://github.com/kdgosik/apps/blob/Makefile) * Under [apps](https://github.com/kdgosik/apps/blob/master/application.yml) in the `application.yml` file, add your app's name, description, etc. ### flask * Run `make flask app=my-app` (replacing `my-app` with a suitable name). * Place your flask app under the new `flask/apps/my-app` directory. * Update requirements.txt file to reflect the necessary python modules to install. * Add `docker build -t kdgosik/apps:flask-my-app flask/apps/my-app` to the [Makefile](https://github.com/kdgosik/apps/blob/Makefile) * Under [apps](https://github.com/kdgosik/apps/blob/master/application.yml) in the `application.yml` file, add your app's name, description, etc. ### go * Run `make goapp app=my-app` (replacing `my-app` with a suitable name). * Place your go app under the new `goapp/apps/my-app` directory. * Update requirements.txt file to reflect the necessary python modules to install. * Add `docker build -t kdgosik/apps:goapp-my-app goapp/apps/my-app` to the [Makefile](https://github.com/kdgosik/apps/blob/Makefile) * Under [apps](https://github.com/kdgosik/apps/blob/master/application.yml) in the `application.yml` file, add your app's name, description, etc. ### node * Run `make node app=my-app` (replacing `my-app` with a suitable name). * Place your node app under the new `node/apps/my-app` directory. * Update package.json file to reflect the necessary python modules to install. * Add `docker build -t kdgosik/apps:node-my-app node/apps/my-app` to the [Makefile](https://github.com/kdgosik/apps/blob/Makefile) * Under [apps](https://github.com/kdgosik/apps/blob/master/application.yml) in the `application.yml` file, add your app's name, description, etc.<file_sep>/goapp/template/main.go package main import ( "html/template" "log" "net/http" "os/exec" "runtime" "time" ) type PageVariables struct { Date string Time string } // open opens the specified URL in the default browser of the user. func openBrowser(url string) error { var cmd string var args []string switch runtime.GOOS { case "windows": cmd = "cmd" args = []string{"/c", "start"} case "darwin": cmd = "open" default: // "linux", "freebsd", "openbsd", "netbsd" cmd = "xdg-open" } args = append(args, url) return exec.Command(cmd, args...).Start() } func main() { http.HandleFunc("/", HomePage) //http.HandleFunc("/", GithubPage) go func() { for { time.Sleep(time.Second) log.Println("Checking if started...") resp, err := http.Get("http://localhost:8080") if err != nil { log.Println("Failed:", err) continue } resp.Body.Close() if resp.StatusCode != http.StatusOK { log.Println("Not OK:", resp.StatusCode) continue } // Reached this point: server is up and running! break } log.Println("SERVER UP AND RUNNING!") openBrowser("http://localhost:8080/") }() log.Println("Starting server...") log.Fatal(http.ListenAndServe(":8080", nil)) } func HomePage(w http.ResponseWriter, r *http.Request) { now := time.Now() // find the time right now HomePageVars := PageVariables{ //store the date and time in a struct Date: now.Format("02-01-2006"), Time: now.Format("15:04:05"), } t, err := template.ParseFiles("homepage.html") //parse the html file homepage.html if err != nil { // if there is an error log.Print("template parsing error: ", err) // log it } err = t.Execute(w, HomePageVars) //execute the template and pass it the HomePageVars struct to fill in the gaps if err != nil { // if there is an error log.Print("template executing error: ", err) //log it } } <file_sep>/shiny/apps/clifford-attractor/app.R library(Rcpp) library(ggplot2) library(dplyr) library(shiny) opt = theme(legend.position = "none", panel.background = element_rect(fill="white"), axis.ticks = element_blank(), panel.grid = element_blank(), axis.title = element_blank(), axis.text = element_blank()) cppFunction('DataFrame createTrajectory(int n, double x0, double y0, double a, double b, double c, double d) { // create the columns NumericVector x(n); NumericVector y(n); x[0]=x0; y[0]=y0; for(int i = 1; i < n; ++i) { x[i] = sin(a*y[i-1])+c*cos(a*x[i-1]); y[i] = sin(b*x[i-1])+d*cos(b*y[i-1]); } // return a new data frame return DataFrame::create(_["x"]= x, _["y"]= y); } ') # ui section ui = fluidPage( # Title titlePanel("Clifford Attractor"), # Sidebar with slider and controls for animation sidebarLayout( # sidebar with slider sidebarPanel( sliderInput(inputId = "a", label = "a", min = -2, max = 2, value = 0, step = 0.05), sliderInput(inputId = "b", label = "b", min = -2, max = 2, value = 0, step = 0.05), sliderInput(inputId = "c", label = "c", min = -2, max = 2, value = 0, step = 0.05), sliderInput(inputId = "d", label = "d", min = -2, max = 2, value = 0, step = 0.05), actionButton(inputId = "create", "Create Plot") ), # Show the animated graph mainPanel( plotOutput(outputId = "plot1") ) ) ) # server section server = function(input, output, session) { createdf <- eventReactive(input$create, { df <- createTrajectory(1000000, 0, 0, input$a, input$b, input$c, input$d) df }) # Show the graph output$plot1 <- renderPlot({ p <- ggplot(createdf(), aes(x, y)) + geom_point(color = "black", shape = 46, alpha = 0.5) + opt p }) } shinyApp(ui, server) <file_sep>/shiny/apps/clifford-attractor/Dockerfile FROM kdgosik/apps:shiny MAINTAINER <NAME> "<EMAIL>" # copy the app to the image COPY ./ ./ ## install necessary R packages RUN Rscript install.R CMD R -e 'shiny::runApp()' <file_sep>/shiny/template/install.R install.packages(c("Rcpp", "dplyr", "ggplot2"))<file_sep>/node/Dockerfile FROM kdgosik/apps:node WORKDIR /app ADD . /app RUN npm install --production EXPOSE 3000 CMD npm start <file_sep>/README.md --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> # Web applications <img src="http://logo-logos.com/wp-content/uploads/2016/10/Docker_logo_logotype.png" width=100 align="right" /> <img src="https://www.rstudio.com/wp-content/uploads/2014/04/shiny.png" width=100 align="right" /> <img src="http://flask.pocoo.org/static/logo/flask.png" width=100 align="right" /> This repo contains code for building and deploying [web applications](https://en.wikipedia.org/wiki/Web_application) (e.g. [shiny](https://cran.r-project.org/package=shiny), [flask](http://flask.pocoo.org/), [Go](https://golang.org/doc/articles/wiki/) and [node](https://medium.com/@adnanrahic/hello-world-app-with-node-js-and-express-c1eb7cfa8a30)) This repo is heavily borrowed from [here](https://github.com/cpsievert/apps) and adapted for apps that I have created. ## Run an app (as a docker container) Each app has it's own [Docker](https://www.docker.com/) container, as well as a [image tag on DockerHub](https://hub.docker.com/r/kdgosik/apps/builds/), so you can easily run apps on your local machine; for example, this will run the [clifford-attractor (shiny) app](https://github.com/kdgosik/apps/tree/master/shiny/apps/clifford-attractor) on <http://localhost:3838> ### shiny ```shell docker run -p 3838:3838 kdgosik/apps:shiny-clifford-attractor ``` ### flask ```shell docker run -p 3000:80 kdgosik/apps:flask-static-example ``` ### go ```shell docker run -p 8080:8080 kdgosik/apps:goapp-static-example ``` ### node ```shell docker run -p 3000:3000 kdgosik/apps:node-static-example ``` If you'd like to run a particular app in this repo, you can get the relevant image tag from the [`application.yml`](https://github.com/kdgosik/apps/blob/master/application.yml) file. ## Acquire all the app images To run all the applications, you'll need to pull (or build) all the corresponding docker images. A necessary first step is to pull (or build) the corresponding docker images. Either way, I'd suggest cloning this repo: ```shell git clone https://github.com/kdgosik/apps.git cd apps ``` Now you can run the `make` command to *build* all the images or `make pull` to pull them from [my registry](https://hub.docker.com/r/kdgosik/apps/). ## Run all the apps via shinyproxy The [`application.yml`](https://github.com/cpsievert/apps/blob/master/application.yml) can be used/modified to (securely) run all the applications as a service via [shinyproxy](https://www.shinyproxy.io/). See the blog post by the original creator (coming soon). ```shell wget https://www.shinyproxy.io/downloads/shinyproxy-1.0.1.jar java -jar shinyproxy-1.0.1.jar ``` ## Contributing Some guidelines for adding new apps: ### shiny * Run `make shiny app=my-app` (replacing `my-app` with a suitable name). * Place your shiny app under the new `shiny/apps/my-app` directory. * Update install.R file to reflect the necessary packages for R to install. * Add `docker build -t kdgosik/apps:shiny-my-app shiny/apps/my-app` to the [Makefile](https://github.com/kdgosik/apps/blob/Makefile) * Under [apps](https://github.com/kdgosik/apps/blob/master/application.yml) in the `application.yml` file, add your app's name, description, etc. ### flask * Run `make flask app=my-app` (replacing `my-app` with a suitable name). * Place your flask app under the new `flask/apps/my-app` directory. * Update requirements.txt file to reflect the necessary python modules to install. * Add `docker build -t kdgosik/apps:flask-my-app flask/apps/my-app` to the [Makefile](https://github.com/kdgosik/apps/blob/Makefile) * Under [apps](https://github.com/kdgosik/apps/blob/master/application.yml) in the `application.yml` file, add your app's name, description, etc. ### go * Run `make goapp app=my-app` (replacing `my-app` with a suitable name). * Place your go app under the new `goapp/apps/my-app` directory. * Update requirements.txt file to reflect the necessary python modules to install. * Add `docker build -t kdgosik/apps:goapp-my-app goapp/apps/my-app` to the [Makefile](https://github.com/kdgosik/apps/blob/Makefile) * Under [apps](https://github.com/kdgosik/apps/blob/master/application.yml) in the `application.yml` file, add your app's name, description, etc. ### node * Run `make node app=my-app` (replacing `my-app` with a suitable name). * Place your node app under the new `node/apps/my-app` directory. * Update package.json file to reflect the necessary python modules to install. * Add `docker build -t kdgosik/apps:node-my-app node/apps/my-app` to the [Makefile](https://github.com/kdgosik/apps/blob/Makefile) * Under [apps](https://github.com/kdgosik/apps/blob/master/application.yml) in the `application.yml` file, add your app's name, description, etc. <file_sep>/Makefile all: shiny-images flask-images goapp-images node-images shiny-images: docker build -t kdgosik/apps:shiny shiny docker build -t kdgosik/apps:shiny-template shiny/template docker build -t kdgosik/apps:shiny-clifford-attractor shiny/apps/clifford-attractor # build a new shiny app (from a template) # use like `make shiny app=genius` shiny: mkdir shiny/apps/${app} cp shiny/template/* shiny/apps/${app} flask-images: docker build -t kdgosik/apps:flask docker build -t kdgosik/apps:flask-template flask/template docker build -t kdgosik/apps:flask-static-example flask/apps/static-example # build a new flask app (from a template) # use like `make flask app=genius` flask: mkdir flask/apps/${app} cp flask/template/* flask/apps/${app} go-images: docker build -t kdgosik/apps:goapp docker build -t kdgosik/apps:goapp-template goapp/template docker build -t kdgosik/apps:goapp-static-example goapp/apps/static-example # build a new go app (from a template) # use like `make goapp app=genius` goapp: mkdir goapp/apps/${app} cp goapp/template/* goapp/apps/${app} node-images: docker build -t kdgosik/apps:node-images docker build -t kdgosik/apps:node-template node/template docker build -t kdgosik/apps:node-static-example node/apps/static-example # build a new go app (from a template) # use like `make goapp app=genius` node: mkdir node/apps/${app} cp node/template/* node/apps/${app} # publish all the images! # TODO: will this automatically push all tags? push: docker push kdgosik/apps # pull down all the images # http://www.googlinux.com/list-all-tags-of-docker-image/index.html pull: curl 'https://registry.hub.docker.com/v2/repositories/kdgosik/apps/tags/' | jq '."results"[]["name"]' | xargs -I {} echo kdgosik/apps:{} | xargs -L1 sudo docker pull readme: Rscript -e 'knitr::knit("README.Rmd")'
03c1769d18cd504de487ee2187ab0e558b18f128
[ "R", "Markdown", "Makefile", "Dockerfile", "Go", "RMarkdown" ]
8
RMarkdown
kdgosik/apps
102d8fd93ccd69fe754ed432bc1d904cbc40b814
0490ed1908ee7f09be42f75638fd04ac5ab995d2
refs/heads/master
<repo_name>IanHooper613/portfolio<file_sep>/react-portfolio/src/components/ProjectItem/index.js import React from 'react'; import './style.css'; function ProjectItem ({ project }) { console.log('proj ', project); return ( <div className='card mb-3'> <div className='row'> <div className='col-md-4'> <img src={project.thumbnail} className='card-img' alt='jeremiah' /> </div> <div className='col-md-8'> <div className='card-body'> <h5 className='card-title'>{project.name}</h5> <p className='card-text'>{project.description}</p> <small><a href={project.repository} className='left'>Github</a></small> <small><a href={project.deployed} className='right'>Deployed App</a></small> </div> </div> </div> </div> ); }; export default ProjectItem;<file_sep>/react-portfolio/src/components/Footer/index.js import React from 'react'; function Footer (){ return( <footer className='page-footer fixed-bottom'> <div className='container-fluid text-center'> <div className='row'> <div className='col'> <a href='https://github.com/cbrittingham14'>GitHub</a> </div> <div className='col'> <a href='https://www.linkedin.com/in/charlie-brittingham-9877ba1a9/'>LinkedIn</a> </div> </div> </div> </footer> ); }; export default Footer;<file_sep>/react-portfolio/src/pages/Portfolio.js import React from 'react'; import ProjectItem from '../components/ProjectItem'; // import projects from '../utils/projects.json'; import { useStoreContext } from "../utils/GlobalState"; function Portfolio (){ // console.log('projects ', projects); const [state] = useStoreContext(); console.log('state ', state); return( <div> <h1>Portfolio</h1> {state.projects.map(o => ( <ProjectItem key={o.id} project={o} /> ))} </div> ); }; export default Portfolio;<file_sep>/README.md # Portfolio This is a peronal webpage to show some of the work I have done, and allow people to connect with me and get to know me. ## Deployed Page [My Portfolio](https://cbrittingham14.github.io/portfolio/)<file_sep>/react-portfolio/src/pages/Home.js import React from 'react'; function Home (){ return( <div className='container-sm'> <div className='row'> <div className='col-auto'> <h1 className='text-center'>About Me</h1> </div> </div> <div className='row'> <div className='col-sm text-center'> <img src='https://raw.githubusercontent.com/cbrittingham14/portfolio/master/react-portfolio/public/assets/images/portrait.jpg' className='self-portrait' alt='Me' /> </div> <div className='col-sm'> <p> Full stack web developer and electrical engineer knowledgeable about both hardware and software design and troubleshooting, experienced in problem solving, teamwork, and customer service. Known for his ability to get along with everyone, his tenacity and creative thinking in solving complex problems, and his leadership abilities. </p> </div> <div className='col-lg-auto'></div> </div> </div> ); }; export default Home;
87ba7527f79d948338b013b2c409e0e531733d0c
[ "JavaScript", "Markdown" ]
5
JavaScript
IanHooper613/portfolio
5fcebda206cd577f73838d78c9bfad652edae0f0
fe63e999ac7d7161a90e517dc524d9c1d5522f04
refs/heads/master
<repo_name>tommyxst/jdcloud-website<file_sep>/js/shouye1.js /** * Created by win7 on 2016/5/25. */ //$(function(){ // document.body.style.zoom=0.95; //}) function changediv() { var i = 0; document.getElementById("slider" + (i % 4 + 1)).style.display = "none"; i++; document.getElementById("slider" + (i % 4 + 1)).style.display = "block"; setTimeout("changediv()", 15000); } function getBefore() { $(".slider").hide().eq(i).show(); } function getAfter() { //$("#slider1").toggle(); //$("#slider4").toggle(); $(".slider").hide().eq(i).show(); } $(function() { jummper(); setInterval("jummper()", 10000000000); setInterval("after()", 5000); getStatistics() var statisticsData = setInterval(getStatistics, 10000) }); var i = 0; function jummper() { $(".pic3 ul li").eq(i).find("img").css("left", "-1180px"); $(".pic3 ul li").eq(i).find("p").css("width", "0px"); $(".pic3 ul li").eq(i).find("img").animate({ left: "0px" }, 500, function() { //当图片移动完成后再加载进度条 //alert("当图片移动完成后再做操作"); $(".pic3 ul li").eq(i).find("p").animate({ width: "1174px" }, 8000, function() { $(".pic3 ul li").eq(i).find("img").animate({ left: "1180px" }, 500, function() { i++; if (i > 4) i = 0; $(".pic3 ul li").eq(i).fadeIn(100).siblings().fadeOut(100); }); }); }); } function after() { $('#demo-slider-0').flexslider('next') } function before() { $('#demo-slider-0').flexslider('prev') } //$(function(){ $("#tabs-1").select();}) $("#areaSelect").on("change", function() { switch (this.value) { case "shiqu": option.bmap.center = [121.756182, 29.874415]; break; case "cixi": option.bmap.center = [121.249853, 30.22056]; break; case "yuyao": option.bmap.center = [121.160934, 30.042849]; break; case "beijing": option.bmap.center = [116.404068, 39.914776]; break; case "hangzhou": option.bmap.center = [120.175203, 30.291286]; break; } myChart.setOption(option); }); $("#typeSelect").on("change", function() { var temp = []; if(this.value=='全部'){ for (var i in info) { temp.push(dataConverter(info, i)); } }else{ for (var i in info) { if (info[i].type === this.value) { temp.push(dataConverter(info, i)); } } } // console.log(temp); option.series[0].data = temp; // console.log(option); myChart.setOption(option); }); $("#amountSelect").on("change", function() { var temp = []; var v = this.value; switch (v) { case "l100": for (var k in info) { if (info[k].amount < 100) { temp.push(dataConverter(info, k)) } }; break; case "m100": for (var k in info) { if (info[k].amount > 100 && info[k].amount < 200) { temp.push(dataConverter(info, k)) } }; break; case "m200": for (var k in info) { if (info[k].amount > 200 && info[k].amount < 300) { temp.push(dataConverter(info, k)) } }; break; case "m300": for (var k in info) { if (info[k].amount > 300) { temp.push(dataConverter(info, k)) } }; break; } // console.log(temp); option.series[0].data = temp; // console.log(option); myChart.setOption(option); }) option = { title: { text: '', left: 'center' }, tooltip: { trigger: 'item', formatter: function(param) { return param.data.name + '<br>' + param.data.type + '<br>' + param.data.website; } }, bmap: { center: [121.756182, 29.874415], //市区 //center: [121.249853,30.22056], //慈溪 // center: [121.160934,30.042849] //余姚 //center: [116.404068,39.914776] //北京 //center: [120.175203,30.291286] //杭州 zoom: 11, roam: true, mapStyle: { styleJson: [{ "featureType": "water", "elementType": "all", "stylers": { "color": "#021019" } }, { "featureType": "highway", "elementType": "geometry.fill", "stylers": { "color": "#000000" } }, { "featureType": "highway", "elementType": "geometry.stroke", "stylers": { "color": "#147a92" } }, { "featureType": "arterial", "elementType": "geometry.fill", "stylers": { "visibility": "off" } }, { "featureType": "arterial", "elementType": "geometry.stroke", "stylers": { "visibility": "off" } }, { "featureType": "local", "elementType": "geometry", "stylers": { "visibility": "off" } }, { "featureType": "land", "elementType": "all", "stylers": { "color": "#08304b" } }, { "featureType": "railway", "elementType": "geometry.fill", "stylers": { "color": "#000000", "visibility": "off" } }, { "featureType": "railway", "elementType": "geometry.stroke", "stylers": { "visibility": "off" } }, { "featureType": "subway", "elementType": "geometry", "stylers": { "lightness": -70 } }, { "featureType": "building", "elementType": "geometry.fill", "stylers": { "color": "#000000" } }, { "featureType": "all", "elementType": "labels.text.fill", "stylers": { "color": "#857f7f" } }, { "featureType": "all", "elementType": "labels.text.stroke", "stylers": { "color": "#000000" } }, { "featureType": "building", "elementType": "geometry", "stylers": { "visibility": "off" } }, { "featureType": "green", "elementType": "geometry", "stylers": { "color": "#062032" } }, { "featureType": "boundary", "elementType": "all", "stylers": { "color": "#1e1c1c" } }, { "featureType": "manmade", "elementType": "all", "stylers": { "visibility": "off" } }, { "featureType": "poi", "elementType": "labels", "stylers": { "visibility": "off" } }] } }, series: [{ name: 'position', type: 'scatter', coordinateSystem: 'bmap', data: [], symbolSize: function(val) { return val[2] / 10; }, label: { normal: { formatter: '{b}', position: 'right', show: false }, emphasis: { show: false, textStyle: { fontSize: 20, } } }, itemStyle: { normal: { color: 'white' } }, symbol: 'image://img/start.png', symbolSize: 16 }] }; var myChart = echarts.init(document.getElementById("container")); myChart.setOption(option); var bmap = myChart.getModel().getComponent('bmap').getBMap(); // bmap.disableScrollWheelZoom(true); // bmap.disableDragging(true); myChart.on('click', function(param) { // console.log(param); window.open("http://" + param.data.website); }) $(document).ready(function() { $.ajax({ url: "companyInfo.json", dataType: "json", success: function(res) { info = res.data; var temp = []; if (info) { for (var i in info) { temp = dataConverter(info, i); option.series[0].data.push(temp); } }; // console.log(option.series[0].data); myChart.setOption(option); } }) }); function dataConverter(data, index) { return { name: data[index].name, value: [data[index].longitude, data[index].latitude], type: data[index].type + "-" + data[index].category, amount: data[index].amount, website: data[index].homepage }; }; function clearOpt() { $("#areaSelect").val("shiqu"); $("#typeSelect").val(""); $("select").niceSelect("update"); for (var i in info) { temp = dataConverter(info, i); option.bmap.center = [121.756182, 29.874415]; option.series[0].data.push(temp); }; myChart.setOption(option); } function hideAdv() { // $("#advQrCode").toggle("slide", { // direction: "right" // }, 1000); $(".commercial").animate({ right: '-210px', }, 1000); $("#advToggle").hide(); $("#advShow").show(); } function showAdv() { $(".commercial").animate({ right: '0', }, 1000); $("#advToggle").show(); $("#advShow").hide(); } function getStatistics() { $.ajax({ async: true, type: "GET", dataType: 'json', url: "http://iot-expeed.com:8088/v1/platform/statistics", success: function(data) { // console.log(data); if (data.result_code == 0) { $('#allEquipment').html(data.device_sum); $('#onlineEquipment').html(data.device_online_sum); $('#allUserNum').html(data.user_sum); $('#onlineUser').html(data.user_online_sum); } else { alert(data.result_message); } }, error: function() { } }); } $(".sl-banner").on("click", function() { location.href = "solutions.html"; }); (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })();<file_sep>/js/index.js function statuTest(){ $.ajax({ type: "post", url: "http://192.168.3.11:8080/service/syncx.php", datatype: "json", data: { }, success: function (data) { } }) } //创建账号 function creatAccount(){ var accountName=$('#accountName').val(); var username=$('#username').val(); var password=$('#<PASSWORD>').val(); var group=$('#group').val(); var explry_date=$('#explry_date').val(); var email=$('#email').val(); $.ajax({ type: "post", url: "http://192.168.3.11:8181/service/syncx.php", datatype: "json", data: { x:3080, accountName:accountName, username:username, password:<PASSWORD>, group:group, explry_date:explry_date, email:email }, success: function (data) { var toStr= eval('(' + data + ')'); if(toStr.code==0){ alert("创建失败"); return false; }else if(toStr.code==1){ alert("Uesr ID:"+toStr.user_id); alert("Password:"+toStr.password); } } }) } //更改账号 function alterAccount(){ var vmeet_id=$('#vmeet_id').val(); var user_id=$('#user_id').val(); var group2=$('#group2').val(); var username2=$('#username2').val(); var explry_date2=$('#explry_date2').val(); var email2=$('#email2').val(); var service=$('#service').val(); if(vmeet_id==""){ vmeet_id=user_id; } if(user_id==""){ user_id=vmeet_id; } $.ajax({ type: "post", url: "http://192.168.3.11:8181/service/syncx.php", datatype: "json", data: { x:2, json:1, vmeet_id:accountName, user_id:user_id, group:group2, username:username2, explry_date:explry_date2, email:email2, service:service }, success: function (data) { var toStr= eval('(' + data + ')'); if(toStr.code==0){ alert("更改失败"); return false; }else if(toStr.code==1){ alert("更改成功"); } } }) } var conf_id; //创建会议 function makeConf(){ var topic=$('#topic').val(); var time=$('#timeZoom').val(); var timeZoom=time*60*60; var beginTime=$('#beginTime').val(); var endTime=$('#endTime').val(); var chairman=$('#chairman').val(); var userid=$('#userid').val(); var password=$('#password').val(); var part=$('#participant').val(); var array=part.split(","); //var participant=array.join(";0|") var i; var participant=""; for( i=0;i<array.length;i++){ if(i<array.length-1){ participant=participant+array[i]+";0|" }else if(i=array.length-1){ participant=participant+array[i]+";0" } } $.ajax({ type: "post", url: "http://192.168.3.11:8181/service/syncx.php", datatype: "json", data: { x:700, json:1, topic:topic, timezone:timeZoom, begintime:beginTime, endtime:endTime, chairman:chairman, participant:participant }, success: function (data) { var toStr= eval('(' + data + ')'); if(toStr.code==0){ alert(toStr.info); return false; }else if(toStr.code>0){ conf_id=toStr.conf_id; alert("创建成功"); window.location="conference.html"+'?id'+conf_id+'id'+userid+'id'+password } } }) } //取消会议 //function cancelConf(){ // var url=window.location.href; // var a=url.substring(51); // //alert(a) // $.ajax({ // type: "post", // url: "http://192.168.3.11:8181/service/syncx.php", // datatype: "json", // data: { // x:710, // json:1, // conf_id:a // }, // success: function (data) { // var toStr= eval('(' + data + ')'); // if(toStr.code==0){ // alert("取消失败"); // }else if(toStr.code>0){ // alert("取消成功"); // window.location="video.html" // } // } // }) //} //增加与会者 //function addconf(){ // var url=window.location.href; // var a=url.substring(51); // var user=$('#user_list').val(); // var array=user.split(","); // var user_list=""; // for( var i=0;i<array.length;i++){ // if(i<array.length-1){ // user_list=user_list+array[i]+";0|" // }else if(i=array.length-1){ // user_list=user_list+array[i]+";0" // } // } // $.ajax({ // type: "post", // url: "http://192.168.3.11:8181/service/syncx.php", // datatype: "json", // data: { // x:901, // json:1, // user_list:user_list, // conf_id:a // }, // success: function (data) { // var toStr= eval('(' + data + ')'); // if(toStr.code==0){ // alert("添加失败"); // }else if(toStr.code>0){ // alert("添加成功"); // } // } // }) // //} //删除与会者 //function detconf(){ // var url=window.location.href; // var a=url.substring(51); // var user_list2=$('#user_list2').val(); // // $.ajax({ // type: "post", // url: "http://192.168.3.11:8181/service/syncx.php", // datatype: "json", // data: { // x:902, // json:1, // user_list:user_list2, // conf_id:a // }, // success: function (data) { // var toStr= eval('(' + data + ')'); // if(toStr.code==0){ // alert("删除失败"); // }else if(toStr.code>0){ // alert("删除成功"); // } // } // }) // // //} <file_sep>/js/mainIndex.js /** * Created by win7 on 2017/6/22. */ "use strict"; function dataConverter(data, index) { return { name: data[index].name, value: [data[index].longitude, data[index].latitude, Math.floor((Math.random() * 200))], type: data[index].type + "-" + data[index].category, amount: data[index].amount, website: data[index].homepage }; } let myChart = echarts.init(document.getElementById("mapChina")); let myChart2 = echarts.init(document.getElementById("barChart")); let myChart3 = echarts.init(document.getElementById("map2")); let piePatternImg = new Image(); piePatternImg.src = "img/pieBackground.jpg" let option = { tooltip: { trigger: 'item', formatter: function(param) { return param.data.name + '<br>' + param.data.type + '<br>' + param.data.website; } }, legend: { orient: 'vertical', y: 'bottom', x:'right', data:['pm2.5'], textStyle: { color: '#fff' } }, visualMap: { min: 0, max: 200, calculable: true, show: false, inRange: { color: ['#50a3ba', '#eac736', '#d94e5d'] }, textStyle: { color: '#fff' } }, geo: { map: '浙江', label: { emphasis: { show: true, textStyle: { color:"#000" } } }, itemStyle: { normal: { areaColor: '#FFFFFF', borderColor: '#111' }, emphasis: { areaColor: '#0F78F0 ' } } }, series: [ { type: "effectScatter", coordinateSystem: "geo", data: [], symbolSize: 12, effectType: "ripple", showEffectOn: 'render', rippleEffect: { brushType: 'stroke' }, hoverAnimation: true, label: { normal: { show: false }, emphasis: { show: false } }, itemStyle: { emphasis: { borderColor: '#fff', borderWidth: 1 } } } ] }; let itemStyle = { normal: { opacity: 0.7, color: { image: piePatternImg, repeat: 'repeat' }, borderWidth: 1, borderColor: 'rgba(255,255,255,0.5)' } }; let option2 = { tooltip : { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, label : { normal: { textStyle: { color:"#FFFFFF" } } }, series : [ { name:'设备数量', type: 'pie', radius : '55%', center: ['55%', '50%'], data:[], itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }; let option3 = { tooltip: { trigger: 'item', formatter: function(param) { if(param.data.value) { return param.data.name+"<br/>设备数:"+param.data.value } else { return param.data.name+"<br/>设备数:0" } } }, series: [ { name: "设备数", type: 'map', mapType: 'china', selectedMode : 'multiple', label: { normal: { show: true, }, emphasis: { show: true, } }, itemStyle: { emphasis: { areaColor:"#24F4FF" } }, data:[] } ] }; function getData() { $.ajax({ url: "companyInfo.json", dataType: "json", success: function(res) { let info = res.data; let temp = []; if (info) { for (let i in info) { temp = dataConverter(info, i); option.series[0].data.push(temp); } } // console.log(option.series[0].data); myChart.setOption(option); } }); $.ajax({ url: "http://iot-expeed.com:8088/v1/platform/statistics/district", // url: "fuck.json", dataType:"json", success: function(res) { if(res.result_code == 0) { for(let i in res.district_sum) { option2.series[0].data.push({name:res.district_sum[i].district, value:res.district_sum[i].deviceSum}) option3.series[0].data.push({name:res.district_sum[i].district.slice(0,res.district_sum[i].district.indexOf("省")), selected:true, value:res.district_sum[i].deviceSum}) } } myChart2.setOption(option2); myChart3.setOption(option3); console.log(option3.series[0].data) } }) } $(document).ready(function() { getData(); $("#sl-socket-li").hover(); if($(window).width() <= 768) { $("dd").hide(); }; myChart2.setOption(option2); }); myChart.on('click', function(param) { window.open("http://" + param.data.website); }); function createCountUp(id,num) { return new CountUp(id,0,num,0,1,{ useEasing: true, useGrouping : true, separator : ',', decimal : '.' }); } let countDevice; let countDeviceOL; let countMember; let countMemberOL; function getStatistics() { $.ajax({ async: true, type: "GET", dataType: 'json', url: "http://iot-expeed.com:8088/v1/platform/statistics", success: function(data) { // console.log(data); if (data.result_code == 0) { countDevice = createCountUp("device",data.device_sum); countDeviceOL = createCountUp("deviceOL",data.device_online_sum); countMember = createCountUp("member",data.user_sum); countMemberOL = createCountUp("memberOL",data.user_online_sum); } else { alert(data.result_message); } } }); } getStatistics(); $(window).on("scroll",function() { // console.log($("#map").offset().top - $(this).scrollTop()); // if(( $("#map").offset().top - $(this).scrollTop() ) > $(this).height()) { // countUp.start(); // // } if(($(this).scrollTop() ) > 350) { countDevice.start(); countDeviceOL.start(); countMember.start(); countMemberOL.start(); } }); $(function() { let statisticsData = setInterval(function() { $.ajax({ async: true, type: "GET", dataType: 'json', url: "http://iot-expeed.com:8088/v1/platform/statistics", success: function(data) { // console.log(data); if (data.result_code == 0) { countDevice.update(data.device_sum); countDeviceOL.update(data.device_online_sum); countMember.update(data.user_sum); countMemberOL.update(data.user_online_sum); } else { alert(data.result_message); } } }) }, 10000) }); $(".sl-col li").on({ mouseover: function() { $(".sl-col li").removeClass("sl-active"); $(this).addClass("sl-active").siblings("li").removeClass("sl-active"); }, click: function() { $(".sl-mid .sl-mid-div,.sl-mid").hide(); let liId = $(this).attr("id"); $("#"+liId+"-div,.sl-mid").fadeIn(800); } }); function mapChange(area) { $("#"+area).addClass("onSelectArea").siblings("a").removeClass("onSelectArea"); option.geo.map = area; option.series[0].data = []; $.ajax({ url: "companyInfo.json", dataType: "json", success: function(res) { let info = res.data; let temp = []; if (info) { for (let i in info) { if(area === "ningbo" && info[i].city !== "宁波"){ console.log(i); continue; } temp = dataConverter(info, i); option.series[0].data.push(temp); } } // console.log(option.series[0].data); myChart.setOption(option); } }); } $(window).resize(function() { if($(this).width() <= 768) { $("dd").hide(); } else { $("dd").show(); } }); $("dt").on("click",function() { if($(window).width() <= 768) { $(this).siblings("dd").toggle(); $(this).find(".ft-icon").toggleClass("glyphicon-chevron-right").toggleClass("glyphicon-chevron-down"); console.log($(this).find(".ft-icon")); } }); $(".weixin").hover(function () { $(".ft-wechat").toggle(); }); $(".su-img").on("mouseover",function() { let thisId = $(this).attr("id"); $(this).toggle(); $("#"+thisId+"-hover").toggle(); }); $(".su-img-hover").on("mouseout",function() { let thisId = $(this).attr("id"); $(this).toggle(); $("#"+thisId.substring(0,thisId.length-6)).toggle(); });<file_sep>/README.md # jdcloud-website Official website of JiDong cloud
6359879dd08bdfeb2bf8c23981bd3716abe18304
[ "JavaScript", "Markdown" ]
4
JavaScript
tommyxst/jdcloud-website
dee21829a7e2010a32a94e00e316f830fe313117
5f36b8f969a2b89830ca74112248603ff4638d48
refs/heads/master
<repo_name>krlossl87/TP06StrackTracers<file_sep>/Desktop/TrabajoPractico3/src/trabajopractico3/Cliente.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package trabajopractico3; /** * * @author Gonzalo */ public class Cliente { //ATRIBUTOS String ClienteId; String ClienteNom; String ClienteApe; int ClienteEdad; int ClienteDNI; String ClienteCelular; public Cliente(String ClienteNom, String ClienteApe, int ClienteEdad, int ClienteDNI, String ClienteCelular) { this.ClienteNom = ClienteNom; this.ClienteApe = ClienteApe; this.ClienteEdad = ClienteEdad; this.ClienteDNI = ClienteDNI; this.ClienteCelular = ClienteCelular; } public String getClienteId() { return ClienteId; } public String getClienteNom() { return ClienteNom; } public String getClienteApe() { return ClienteApe; } public int getClienteEdad() { return ClienteEdad; } public void setClienteId(String ClienteId) { this.ClienteId = ClienteId; } public void setClienteNom(String ClienteNom) { this.ClienteNom = ClienteNom; } public void setClienteApe(String ClienteApe) { this.ClienteApe = ClienteApe; } public void setClienteEdad(int ClienteEdad) { this.ClienteEdad = ClienteEdad; } public static boolean valida_dni_no_sea_vacio(Cliente c){ return c.ClienteDNI > 0; } public static boolean valida_celular_no_sea_vacio(Cliente c){ return !c.ClienteCelular.equals(""); } } <file_sep>/Documents/NetBeansProjects/TP06/src/test/java/com/mycompany/tp06/SeleniumConfig.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.tp06; //import java.io.File; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; //import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.DesiredCapabilities; /** * * @author Charly */ public class SeleniumConfig { private WebDriver driver; public SeleniumConfig() { Capabilities capabilities = DesiredCapabilities.chrome(); driver = new ChromeDriver(capabilities); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } static { System.setProperty("webdriver.gecko.driver", "./src/test/drivers/geckodriver.exe"); System.setProperty("webdriver.chrome.driver", "./src/test/drivers/chromedriver.exe"); } public WebDriver getDriver() { return driver; } public void setDriver(WebDriver driver) { this.driver = driver; } }
8ef1f9ce39de3230ec0b5259ce533036c1df9c78
[ "Java" ]
2
Java
krlossl87/TP06StrackTracers
ffc7b510156383eeabd0d19c5755c84dfd9fb8bd
b06ec814a2dcb1d3ce580d8d5d0c9cee65617619
refs/heads/master
<repo_name>Thomas-de-Brouwer/eet_nu-ios<file_sep>/eet.nu/ResultViewController.swift // // ResultViewController.swift // eet.nu // // Created by User on 12/04/15. // Copyright (c) 2015 User. All rights reserved. // import UIKit class ResultViewController: UITableViewController { @IBOutlet weak var textview: UITextView! var searchword = String() var tableData:[Venue] = []; override func viewDidLoad() { super.viewDidLoad() println(searchword) let url = NSURL(string: "https://api.eet.nu/venues?query="+searchword+"&geolocation=51.525508,5.079604&max_distance=5") let request = NSURLRequest(URL: url!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in var error: NSError? let jsonData: NSData = data let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary var resultsArr: NSArray = jsonDict["results"] as NSArray for( var i = 0 ; i < resultsArr.count ;i++){ var result: NSDictionary = resultsArr[i] as NSDictionary self.tableData.append(Venue(name: result["name"] as String,id: result["id"] as Int)) } println(jsonDict) for (var i=0; i < self.tableData.count; i++){ println(self.tableData[i].name) } //println(NSString(data: data, encoding: NSUTF8StringEncoding)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }<file_sep>/eet.nu/ViewController.swift // // ViewController.swift // eet.nu // // Created by User on 08/04/15. // Copyright (c) 2015 User. All rights reserved. // import UIKit class ViewController: UIKit.UIViewController { @IBOutlet weak var searchfield: UITextField! @IBOutlet weak var tableView: UITableView! var resultjson = NSData() override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destViewController : ResultViewController = segue.destinationViewController as ResultViewController destViewController.searchword = searchfield.text } } <file_sep>/eet.nu/Venue.swift // // Venue.swift // eet.nu // // Created by User on 30/06/15. // Copyright (c) 2015 User. All rights reserved. // import Foundation class Venue { var name:String var id:Int init(name:String, id:Int){ self.name = name self.id = id } }
de51236f453e9108e67ad1dce133e1917c2474e1
[ "Swift" ]
3
Swift
Thomas-de-Brouwer/eet_nu-ios
83d584afb3a7963e00b3d418db85fb23cb1e5bb7
1472f2c9f445b56fb06fe994cf37868ed1b35445
refs/heads/master
<file_sep>// Assignment Code var generateBtn = document.querySelector("#generate"); function randomizer(arr){ var randoIdx = Math.floor(Math.random() * arr.length); var randoEl = arr[randoIdx]; return randoEl; } function generatePassword(){ var select = [] var newChars = [] var newpassword = [] var pLength = prompt("What is the desired length of the password?") if (pLength < 8 || pLength > 128){ alert("Must choose between 8 and 128 characters."); } else { var pLower = confirm("Would you like lowercase characters included in the password") var pUpper = confirm("Would you like uppercase characters included in the password?") var pNumber = confirm("Would you like numeric characters included in the password?") var pSpecial = confirm("Would you like special characters included in the password?") lowers = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; uppers = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; specials = ["!", "#", "$", "%", "&", "*", "+", "-", ".", "/", ":", ";", "<", "=", ">", "?", "@"]; if (!pLower && !pUpper && !pNumber && !pSpecial){ alert("Must choose atleast one character type."); } if (pLower){ select.push(lowers.join("")); } if (pUpper){ select.push(uppers.join("")); } if (pNumber){ select.push(numbers.join("")); } if (pSpecial){ select.push(specials.join("")); } for (var i = 0; i < select.length; i++) { newChars.push(randomizer(select)); } for (var i = 0; i < pLength; i++) { newpassword[i] = newChars[i]; } } return newpassword } // Add event listener to generate button generateBtn.addEventListener("click", writePassword); // Write password to the #password input function writePassword(){ var password = generatePassword(); var passwordText = document.querySelector("#password"); passwordText.value = password; } // // Assignment Code // var generateBtn = document.querySelector("#generate"); // function randomizer(){ // var randoIdx = Math.floor(Math.random() * arr.length); // var randoEl = arr[randoIdx]; // console.log(randoEl) // } // function generatePassword(){ // var selected = [] // var newChars = [] // var newPword = [] // // var newpassword = [] // var pLength = prompt("What is the desired length of the password?") // if (pLength < 8 || pLength > 128){ // alert("Must choose between 8 and 128 characters."); // } // else { // var pLower = confirm("Would you like lowercase characters included in the password") // var pUpper = confirm("Would you like uppercase characters included in the password?") // var pNumber = confirm("Would you like numeric characters included in the password?") // var pSpecial = confirm("Would you like special characters included in the password?") // lowers = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; // uppers = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; // numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; // specials = ["!", "#", "$", "%", "&", "*", "+", "-", ".", "/", ":", ";", "<", "=", ">", "?", "@"]; // if (!pLower && !pUpper && !pNumber && !pSpecial){ // alert("Must choose atleast one character type."); // } // if (pLower){ // selected.push(...lowers); // } // if (pUpper){ // selected.push(...uppers); // } // if (pNumber){ // selected.push(...numbers); // } // if (pSpecial){ // selected.push(...specials); // } // } // for (var i = 0; i < 79; i++){ // var selected = randomizer(selected); // } // for (var i = 0; i < pLength; i++){ // newChars.push(selected); // } // for (var i = 0; i < pLength; i++){ // newPword.push(newChars); // console.log(newPword); // } // // newPword.push(newchars); // // newpword[i] = selected[i] // } // // for (var i = 0; i < pLength; i++) { // // var randos = randomizer(randos); // // newpassword.push(randos); // // } // // for (var i = 0; i < selected.length; i++) { // // newpassword[i] = selected[i]; // // } // // return newpassword.join("") // // Add event listener to generate button // generateBtn.addEventListener("click", writePassword); // // Write password to the #password input // function writePassword(){ // var password = generatePassword(); // var passwordText = document.querySelector("#password"); // passwordText.value = password; // } // // Assignment Code // var generateBtn = document.querySelector("#generate"); // // Write password to the #password input // function writePassword(){ // var password = generatePassword(); // var passwordText = document.querySelector("#password"); // passwordText.value = password; // } // // Add event listener to generate button // generateBtn.addEventListener("click", writePassword); // function generatePassword(){ // var randos = [] // var selected = [] // var newpassword = [] // var pLength = prompt("What is the desired length of the password?") // if (pLength < 8 || pLength > 128){ // alert("Must choose between 8 and 128 characters."); // } // else { // var pLower = confirm("Would you like lowercase characters included in the password") // var pUpper = confirm("Would you like uppercase characters included in the password?") // var pNumber = confirm("Would you like numeric characters included in the password?") // var pSpecial = confirm("Would you like special characters included in the password?") // lowers = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; // uppers = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; // numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; // specials = ["!", "#", "$", "%", "&", "*", "+", "-", ".", "/", ":", ";", "<", "=", ">", "?", "@"]; // if (!pLower && !pUpper && !pNumber && !pSpecial){ // alert("Must choose atleast one character type."); // } // if (pLower){ // for (var i = 0; i <= pLength; i++) { // randos.push(...lowers) // } // } // if (pUpper){ // for (var i = 0; i <= pLength; i++) { // randos.push(...uppers) // } // } // if (pNumber){ // for (var i = 0; i <= pLength; i++) { // randos.push(...numbers) // } // } // if (pSpecial){ // for (var i = 0; i <= pLength; i++) { // randos.push(...specials); // } // } // } // return newpassword.join("")<file_sep># Password=Generator A password creator that provides randomized passwords within the users perinmeters. While I wasn't able to produce a fully functional generator, I learned several lessons and had a lot of practice debugging issues. ![password1](Capture.JPG) ## Table of Contents * [Tech Used](#tech_used) * [Usage](#usage) * [Features](#features) * [Deployed_Link](#deployed_link) * [Author](#author) * [Credits](#credits) * [License](#license) ---- ## Tech Used * [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) * [Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) ## Usage This generator would be ideal for selecting passwords with different perimeters determined by the user. ## Features - Conditional logic restricts password to users requirements. ![code.1](logic1.JPG) - "Randomizer" code produces randon characters from an array. ![code.2](logic2.JPG) ## Deployed Link * [See Live Site](https://ajhuff7.github.io/password-generator/) --- ## Author **<NAME>** - [Portfolio Site](#) - [Github](https://github.com/ajhuff7) - [LinkedIn](https://www.linkedin.com/in/aj-huff-7696b14b/) ## License ![License](https://img.shields.io/badge/License-MIT-brightgreen)
532a882084e22a67d2838422cec786749d198efe
[ "JavaScript", "Markdown" ]
2
JavaScript
ajhuff7/password-generator
e697c7a790354f44120011376d5da5b9d2a258b6
61192035c941bf3a19d32df2ec0be50dc02618ff
refs/heads/master
<file_sep>this is a read me file this is project to explore git hub features from gireesh <file_sep>#include<stdio.h> int main() { printf("this is my first text file.this is created for the testing git"); printf("\nhello world.."); return 0; }
be936df11ca5b5a2001603a01776faeec6ee2f79
[ "Markdown", "C" ]
2
Markdown
gireeshcse/testgit
5b3a2c4d085e97a369e3dcaacdf5aa7e11a65265
a831244607eea6c62ea2c5b4821903943c4328a8
refs/heads/master
<file_sep>#include <iostream> #include <time.h> using namespace std; int main() { // initialize random seed srand(time(NULL)); // generate a random number btw 1 and 100 int secretNumber = rand() % 100 + 1; int userInput = 0; // enter the loop. notifies if number is not numeric // also notifies if the guessed number is too high or too low // if the number is correct it leaves the loop cout << "Hi Player. Please guess the Secret Number" << endl; do { if(!(cin >> userInput)) { cout << "Only enter numeric numbers" << endl; } else { // if its to high notify to highg if(userInput > secretNumber) cout << "You guessed wrong and too high, try again!" << endl; // if its to low notify to low if(userInput < secretNumber) cout << "You guessed wrong and too low, try again!" << endl; } } while (userInput != secretNumber); // prints the final message cout << "You guessed write! The Secret Number was " << secretNumber << endl; return 0; }<file_sep>var express = require("express"); var app = express(); var path = require("path"); var HTTP_PORT = process.env.PORT || 8080; // call this function after the http server starts listening for requests function onHttpStart() { console.log("Express http server listening on: " + HTTP_PORT); } // setup a 'route' to listen on the default url path (http://localhost) app.get("/", function(req,res){ res.send("Hello World<br /><a href='/about'>Go to the about page</a>"); }); // setup another route to listen on /about app.get("/about", function(req,res){ res.sendFile(path.join(__dirname, "/week2-assets/about.html")); }); //==================================================== app.get("/viewData", function(req,res){ var someData = { name: "John", age: 23, occupation: "developer", company: "Scotiabank" }; var htmlString = "<!doctype html>" + "<html>" + "<head>" + "<title>" + "View Data" + "</title>" + "</head>" + "<body>" + "<table border='10'>" + "<tr>" + "<th>" + "Name" + "</th>" + "<th>" + "Age" + "</th>" + "<th>" + "Occupation" + "</th>" + "<th>" + "Company" + "</th>" + "</tr>" + "<tr>" + "<td>" + someData.name + "</td>" + "<td>" + someData.age + "</td>" + "<td>" + someData.occupation + "</td>" + "<td>" + someData.company + "</td>" + "</tr>" + "</table>" + "</body>" + "</html>"; res.send(htmlString); }); //==================================================== // setup http server to listen on HTTP_PORT app.listen(HTTP_PORT, onHttpStart);<file_sep>var express = require("express"); var exphbs = require('express-handlebars'); var path = require("path"); var app = express(); var HTTP_PORT = process.env.PORT || 3000; // call this function after the http server starts listening for requests function onHttpStart() { console.log("Express http server listening on: " + HTTP_PORT); } //////////////////// // Register express-handlebars as the rendering engine for views app.engine('.hbs', exphbs({ extname: 'hbs' })); app.set('view engine', '.hbs'); //==================================================== app.get("/viewData", function (req, res) { var someData = { name: "John", age: 23, occupation: "developer", company: "Scotiabank", visible: true, contract: false }; // Call res.render() and pass name of hbs view file res.render('viewData', {data : someData}); }); //==================================================== // setup http server to listen on HTTP_PORT app.listen(HTTP_PORT, onHttpStart);<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <mysql.h> #include <iostream> #include <iomanip> #include <string> using namespace std; #define HOST "********************" #define USER "*****************" #define PASS "*****************" #define DB "*************" #define PORT **** template<typename T> void printElement(T t, const int& width) { cout << left << setw(width) << setfill(' ') << t; } void Clear(); ostream& line(const int len, const char ch); int menu(); int getIntInRange(int min, int max); int getInt(); bool yes(); int findEmployee(MYSQL* conn, int employeeNumber, struct Employee* emp); void displayEmployee(MYSQL* conn, struct Employee* emp); void displayAllEmployees(MYSQL* conn); void insertEmployee(MYSQL* conn, struct Employee* emp); void updateEmployee(MYSQL* conn, const int no); void deleteEmployee(MYSQL* conn, const int no); struct Employee { int employeeNumber; char lastName[50]; char firstName[50]; char email[100]; char phone[50]; char extension[10]; char reportsTo[100]; char jobTitle[50]; char city[50]; }; int main() { bool exit = false; int option; Employee* emp = nullptr; MYSQL* conn = mysql_init(0); conn = mysql_real_connect(conn, HOST, USER, PASS, DB, PORT, nullptr, 0); if (conn) { cout << "Successful connection to Database" << endl << endl; int ok = mysql_set_server_option(conn, MYSQL_OPTION_MULTI_STATEMENTS_ON); mysql_autocommit(conn, false); do { option = menu(); switch (option) { case 1: emp = new Employee(); system("CLS"); displayEmployee(conn, emp); cout << endl; delete emp; system("PAUSE"); system("CLS"); break; case 2: system("CLS"); displayAllEmployees(conn); cout << endl; system("PAUSE"); system("CLS"); break; case 3: emp = new Employee(); system("CLS"); insertEmployee(conn, emp); cout << endl; delete emp; system("PAUSE"); system("CLS"); break; case 4: system("CLS"); int no; cout << "Enter Employee Number: "; no = getInt(); updateEmployee(conn, no); cout << endl; system("PAUSE"); system("CLS"); break; case 5: system("CLS"); cout << "Enter Employee Number: "; no = getInt(); deleteEmployee(conn, no); cout << endl; system("PAUSE"); system("CLS"); break; case 0: cout << "Exit the program? (Y)es/(N)o: "; exit = yes(); cout << endl; system("CLS"); break; } } while (!exit); mysql_rollback(conn); mysql_close(conn); } else { cout << "Connection Failed. Error: " << mysql_error(conn) << endl; } } void Clear() { while (getchar() != '\n') { ; } } ostream& line(const int len, const char* ch) { for (int i = 0; i < len; i++, cout << ch); return cout; } int menu() { line(21, ""); cout << " HR Menu "; line(21, ""); cout << endl; cout << "1) Find Employee" << endl; cout << "2) Employees Report" << endl; cout << "3) Add Employee" << endl; cout << "4) Update Employee" << endl; cout << "5) Remove Employee" << endl; cout << "0) Exit" << endl << endl; cout << "Select an option:> "; return getIntInRange(0, 5); } int getIntInRange(int min, int max) { bool done = false; int value; do { value = getInt(); if (value > max || value < min) { cout << "* OUT OF RANGE * <Enter a number between " << min << " and " << max << ">: "; } else { done = true; } } while (!done); return value; } int getInt() { bool done = false; int first, value; char after; do { first = scanf("%d%c", &value, &after); if (first == 0) { cout << "* INVALID INTEGER * <Please enter an integer>: "; Clear(); } else if (after != '\n') { cout << "* INVALID INTEGER * <Please enter an integer>: "; Clear(); } else if (first < INT_MIN || first > INT_MAX) { cout << "* INVALID INTEGER * <Please enter an integer>: "; Clear(); } else { done = true; } } while (!done); return value; } bool yes() { char answer, after; bool value = false; do { scanf(" %c%c", &answer, &after); if (after != '\n') answer = '1'; switch (answer) { case 'n': case 'N': value = false; break; case 'y': case 'Y': value = true; break; default: printf("* INVALID ENTRY * <Only (Y)es or (N)o are acceptable>: "); Clear(); break; } } while (answer != 'n' && answer != 'y' && answer != 'N' && answer != 'Y'); answer = ' '; return value; } int findEmployee(MYSQL* conn, int employeeNumber, struct Employee* emp) { int exit_code = 0; string query = "SELECT emp.employeeNumber, emp.lastName, emp.firstName, emp.email, of.phone, emp.extension, emp.reportsTo, emp.jobTitle, of.city " "FROM employees emp JOIN offices of ON emp.officeCode = of.officeCode " "WHERE emp.employeeNumber = " + std::to_string(employeeNumber); if (!mysql_query(conn, query.c_str())) { MYSQL_RES* result = mysql_store_result(conn); if (result) { MYSQL_ROW row = mysql_fetch_row(result); if (row != nullptr) { if (emp != nullptr) { emp->employeeNumber = std::atoi(row[0]); strcpy(emp->lastName, row[1]); strcpy(emp->firstName, row[2]); strcpy(emp->email, row[3]); strcpy(emp->phone, row[4]); strcpy(emp->extension, row[5]); if (row[6] != nullptr) { strcpy(emp->reportsTo, row[6]); } strcpy(emp->jobTitle, row[7]); strcpy(emp->city, row[8]); } exit_code = 1; } else { cout << "invalid data" << endl; } } else { cout << "Error message: " << mysql_error(conn) << ": " << mysql_errno(conn) << endl; } } else { cout << "Error message: " << mysql_error(conn) << ": " << mysql_errno(conn) << endl; } return exit_code; } void displayEmployee(MYSQL* conn, Employee* emp) { int number; cout << "Enter Employee Number: "; number = getInt(); if (findEmployee(conn, number, emp)) { cout << endl; cout << "employeeNumber = " << emp->employeeNumber << endl; cout << "lastName = " << emp->lastName << endl; cout << "firstName = " << emp->firstName << endl; cout << "email = " << emp->email << endl; cout << "phone = " << emp->phone << endl; cout << "extension = " << emp->extension << endl; cout << "reportsTo = " << emp->reportsTo << endl; cout << "jobTitle = " << emp->jobTitle << endl; cout << "city = " << emp->city << endl; } else { cout << "Employee " << number << " does not exist." << endl;} } void displayAllEmployees(MYSQL* conn) { string query = "SELECT emp.employeeNumber, emp.firstName, emp.lastName, emp.email, of.phone, emp.extension, mng.firstName, mng.lastName " "FROM(employees emp LEFT JOIN employees mng ON emp.reportsTo = mng.employeeNumber " "JOIN offices of ON emp.officeCode = of.officeCode);"; if (!mysql_query(conn, query.c_str())) { MYSQL_RES* result = mysql_store_result(conn); if (result) { printElement("E", 6); printElement("Employee Name", 20); printElement("Email", 35); printElement("Phone", 20); printElement("Ext", 10); printElement("Manager", 20); cout << endl; line(111, "-"); cout << endl; while (MYSQL_ROW row = mysql_fetch_row(result)) { if (row != nullptr) { std::string emp_frst(row[1]); std::string emp_lst(row[2]); string emp_name = emp_frst + " " + emp_lst; string mng_name; if (row[6] && row[7]) { std::string mng_frst(row[6]); std::string mng_lst(row[7]); mng_name = mng_frst + " " + mng_lst; } else { mng_name = ""; } printElement(row[0], 6); printElement(emp_name, 20); printElement(row[3], 35); printElement(row[4], 20); printElement(row[5], 10); printElement(mng_name, 20); cout<<endl;} else { cout << "Invalid data" << endl;} } } else { cout << "Error message: " << mysql_error(conn) << ": " << mysql_errno(conn) << endl;} } else { cout << "Error message: " << mysql_error(conn) << ": " << mysql_errno(conn) << endl;} } void insertEmployee(MYSQL* conn, Employee* emp) { cout << "Employee Number: "; emp->employeeNumber = getInt(); if (!findEmployee(conn, emp->employeeNumber, nullptr)) { cout << "Last Name: "; cin.get(emp->lastName, 51, '\n'); Clear(); cout << "First Name: "; cin.get(emp->firstName, 51, '\n'); Clear(); cout << "Email: "; cin.get(emp->email, 101, '\n'); Clear(); cout << "Extension: "; cin.get(emp->extension, 11, '\n'); Clear(); cout << "Job Title: "; cin.get(emp->jobTitle, 51, '\n'); Clear(); cout << "City: "; cin.get(emp->city, 51, '\n'); Clear(); string query = "INSERT INTO employees VALUES (" + std::to_string(emp->employeeNumber) + ",'" + std::string(emp->lastName) + "','" + std::string(emp->firstName) + "','" + std::string(emp->extension) + "','" + std::string(emp->email) + "'," + "1" + "," + "1002" + ",'" + std::string(emp->jobTitle) + "');"; if (mysql_query(conn, query.c_str())) { cout << "Error message: " << mysql_error(conn) << ": " << mysql_errno(conn) << endl; } else { cout << endl << "Employee " << emp->employeeNumber << " was successfully added." << endl; } } else { cout << "An employee with the same employee number exists." << endl; } } void updateEmployee(MYSQL* conn, const int number) { if (findEmployee(conn, number, nullptr)) { char ext[11]; cout << "New Extension: "; cin.get(ext, 11, '\n'); Clear(); string query = "UPDATE employees SET extension = '" + std::string(ext) + "' WHERE employeeNumber = " + std::to_string(number) + ";"; if (mysql_query(conn, query.c_str())) { cout << "Error message: " << mysql_error(conn) << ": " << mysql_errno(conn) << endl; } else { cout << endl << "Employee " << number << " was successfully updated." << endl; } } else { cout << "Employee " << number << " does not exist." << endl; } } void deleteEmployee(MYSQL* conn, const int number) { if (findEmployee(conn, number, nullptr)) { string query = "DELETE FROM employees WHERE employeeNumber = " + std::to_string(number) + ";"; if (mysql_query(conn, query.c_str())) { cout << "Error message: " << mysql_error(conn) << ": " << mysql_errno(conn) << endl;} else { cout << "The employee has been deleted." << endl;} } else { cout << "The employee does not exist." << endl;} } <file_sep>npm init express and handlebars <file_sep>var nummath = require('./sourcelib.js'); nummath.addints(12,12); nummath.prodints(12,12); nummath.divints(72,12);<file_sep>var patient = { pid: 1001, name: 'Keith', ward: 'HDU', //getters getpid: function(){return this.pid;}, getname: function(){return this.name;}, getward: function(){return this.ward;}, //setters setpid: function(newpid){this.pid = newpid}, setname: function(newname){this.name = newname}, setward: function(newward){this.ward = newward} }; patient.setpid(1002); patient.setname('Smith'); patient.setward('ICU'); console.log(patient.getpid()); console.log(patient.getname()); console.log(patient.getward()); /* console.log(patient.pid); console.log(patient.name); console.log(patient.ward); */ var patient2 = Object.create(patient); console.log(patient2.getpid()); console.log(patient2.getname()); console.log(patient2.getward()); <file_sep> /* var divints = (num1,num2) => { var divofints = num1 / num2; console.log(divints(24,4)); }; */ //======================================== var divints = function(num1,num2){ return num1 / num2; }; console.log(divints(24,4)); //======================================= var divints = (num1,num2) => num1 / num2; console.log(divints(24,4)); <file_sep>//Blocking Code Service var fs = require('fs'); var data = fs.readFileSync('web322.txt'); console.log(data.toString()); console.log('Dense Webdev course'); console.log('Really nice WebDev course'); console.log('A little tough web course'); console.log('Blocking Program Ended'); console.log('************************************************'); //Non Blocking Code Example var fs = require('fs'); fs.readFile('web322.txt' , function(err , data ){ if(err){ return console.error(err); } console.log(data.toString()); }); console.log('Dense Webdev course'); console.log('Really nice WebDev course'); console.log('A little tough web course'); console.log('Non Blocking Program Ended'); <file_sep> var BitStuffing = function () { var counter = 0; var BITS = ['0','1','1','1','1','1','1','0','1','1','1','1','1','1','0']; var flag = "01111110"; var stuffedBits = ""; var c; var charCounterNormal; var charCounterStuffed; for (charCounterNormal = 0; charCounterNormal < BITS.length; charCounterNormal++ ){ }; //console.log(charCounterNormal); for (var i = 0; i<BITS.length; i++) { c = BITS[i]; stuffedBits = stuffedBits + c; if (BITS[i] == 1) { counter++; } if (counter == 5) { stuffedBits = stuffedBits + "0"; } if (counter == 11) { stuffedBits = stuffedBits + "0"; } } for (charCounterStuffed = 0; charCounterStuffed < stuffedBits.length; charCounterStuffed++){{} } //console.log(stuffedBits); //console.log(charCounterStuffed); var framing = flag + stuffedBits + flag; var framedAsString = framing.split('').join(' '); var BITSAsString = BITS.join(' '); var stuffedBitsAsModifiedString = stuffedBits.split('').join(' '); //console.log(stuffedBitsAsModifiedString); console.log('Before Stuffing: ' + BITSAsString + ' -- ' + charCounterNormal + ' charachters'); console.log('After Stuffing: ' + stuffedBitsAsModifiedString + ' -- ' + charCounterStuffed + ' charachters'); console.log('After framing:' + framedAsString); } BitStuffing(); <file_sep># Store-Room Repository has exactly what the name says. It has garbage and random bits and pieces of code. <file_sep> (function(){ exports.addints = (num1,num2)=> { var sumofnums = num1 + num2; console.log('num1 + num2 = ' + sumofnums); }; exports.prodints = (num1,num2)=>{ var prodofnums = num1 * num2; console.log('num1 * num2 = ' + prodofnums); }; exports.divints = (num1,num2) => { var divofnums = num1 / num2; console.log('num1 / num2 = ' + divofnums); }; }());<file_sep>//series won't work after first two digits and too frustrated too solve it #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> float altSum(int); int main() { int ans; while (1) { printf("Enter a number: "); scanf("%d", &ans); if (ans <= 0) continue; // change to break and see the impact printf("Sum of the first %d alternate terms is %f \n", ans, altSum(ans)); } } // Returns the sum of alternating series: 1 - 1/2 + 1/3 - 1/4 + …. (+/-) 1/n float altSum(int n) { double i = 0; double number = 0; double sum = 0; double k = 0; double sum2 = 0; for ( i = 1; i <= n ; i++){ sum += 1 / (sum + 1); sum2 = fabs(sum); } if( n % 2 == 0) for ( k = 1; k <= n ; k++){ sum += -(1 / (n)) + -1; sum2 = fabs(sum); } return sum2; }
bb455a409ed9c2542bd4343b5d2d2707a2fb111d
[ "JavaScript", "C", "C++", "Markdown" ]
13
C++
NamraOnPC/Scrap
a4645566bc9162032534043d8ea1e8e444ffa802
a515612a587d7c05e4ad03dfb3711bd5c857b8a2
refs/heads/main
<repo_name>emersong2112/bubowlQr<file_sep>/app/Services/UtilsService.php <?php namespace App\Services; /** * Class utilsService * @package App\Services */ class UtilsService { /** * utilsService constructor. */ public function __construct() { #call your models, repositories and another things here } public static function removeSpecialChar($text){ $text = preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/"),explode(" ","a A e E i I o O u U n N"),$text); $text = iconv('UTF-8', 'ASCII//TRANSLIT', $text); $text = str_replace(' ', '-', $text); $text = str_replace('"', '', $text); $text = strtolower($text); return str_replace('/', '-', $text); } }<file_sep>/app/Models/Segment.php <?php /** * Created by Reliese Model. */ namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; /** * Class Segment * * @property int $id * @property int $id_rest * @property string $name * @property string $desc * @property string $status * @property string|null $remember_token * @property Carbon|null $created_at * @property Carbon|null $updated_at * @property string|null $deleted_at * * @property Rest $rest * @property Collection|Food[] $food * * @package App\Models */ class Segment extends Model { use SoftDeletes; protected $table = 'segments'; protected $casts = [ 'id_rest' => 'int' ]; protected $hidden = [ 'remember_token' ]; protected $fillable = [ 'id_rest', 'name', 'desc', 'status', 'remember_token' ]; public function rest() { return $this->belongsTo(Rest::class, 'id_rest'); } public function food() { return $this->hasMany(Food::class, 'id_segment'); } } <file_sep>/app/Http/Controllers/Admin/FoodsController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Requests\Admin\FoodsRequest; use App\Models\Foods; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; class FoodsController extends Controller { /** * @var array */ protected $breadcrumbs; /** * FoodsController constructor. */ public function __construct() { $this->breadcrumbs = [ route('admin.foods.index') => __('global.titles.foods_index'), ]; } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { /** @var Foods $foods */ $foods = Foods::orderBy('id', 'ASC'); if ($param = $request->search) { $foods->where('id', 'LIKE', "%{$param}%"); } return view('admin.foods.index', [ 'foods' => $foods->paginate(20) ]); } /** * @param FoodsRequest $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View */ public function create(FoodsRequest $request) { if ($request->isMethod('post')) { DB::beginTransaction(); try { /** @var Foods $foods */ $foods = Foods::create($request->all()); DB::commit(); messages(__('global.titles.success'), __('messages.success_store'), 'success'); return redirect()->route('admin.foods.index'); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_store'), 'danger', 5000); return redirect()->back(); } } return view('admin.foods.create', [ 'breadcrumbs' => $this->breadcrumbs, ]); } /** * @param $id * @param FoodsRequest $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View */ public function edit($id, FoodsRequest $request) { /** @var Foods $foods */ $foods = Foods::find($id); if ($request->isMethod('post')) { DB::beginTransaction(); try { $foods->update($request->all()); DB::commit(); messages(__('global.titles.success'), __('messages.success_update'), 'success'); return redirect()->route('admin.foods.index'); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_update'), 'danger', 5000); return redirect()->route('admin.foods.edit', $id); } } return view('admin.foods.edit', [ 'foods' => $foods, 'breadcrumbs' => $this->breadcrumbs, ]); } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function destroy($id) { DB::beginTransaction(); try { Foods::find($id)->delete(); DB::commit(); messages(__('global.titles.success'), __('messages.success_trashed'), 'success', 6000); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_trashed'), 'danger', 6000); return redirect()->back(); } } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function trashed(Request $request) { $foods = Foods::orderBy('deleted_at', 'DESC')->onlyTrashed(); if ($param = $request->search) { $foods->where('id', 'LIKE', "%{$param}%"); } return view('admin.foods.trashed', [ 'foods' => $foods->paginate(20) ]); } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function restore($id) { DB::beginTransaction(); try { /** @var Foods $foods */ $foods = Foods::where('id', $id)->onlyTrashed()->first(); $foods->restore(); DB::commit(); messages(__('global.titles.success'), __('messages.success_restore'), 'success'); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_retore'), 'danger'); return redirect()->back(); } } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function forceDelete($id) { DB::beginTransaction(); try { /** @var Foods $foods */ $foods = Foods::where('id', $id)->onlyTrashed()->first(); $foods->forceDelete(); DB::commit(); messages(__('global.titles.success'), __('messages.success_destroy'), 'success'); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_destroy'), 'danger'); return redirect()->back(); } } } <file_sep>/app/Http/Controllers/Admin/FoodController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Requests\Admin\FoodRequest; use App\Models\Food; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; class FoodController extends Controller { /** * @var array */ protected $breadcrumbs; /** * FoodController constructor. */ public function __construct() { $this->breadcrumbs = [ route('admin.food.index') => __('global.titles.food_index'), ]; } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { /** @var Food $food */ $food = Food::orderBy('id', 'ASC'); if ($param = $request->search) { $food->where('id', 'LIKE', "%{$param}%"); } return view('admin.food.index', [ 'food' => $food->paginate(20) ]); } /** * @param FoodRequest $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View */ public function create(FoodRequest $request) { if ($request->isMethod('post')) { DB::beginTransaction(); try { /** @var Food $food */ $food = Food::create($request->all()); DB::commit(); messages(__('global.titles.success'), __('messages.success_store'), 'success'); return redirect()->route('admin.food.index'); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_store'), 'danger', 5000); return redirect()->back(); } } return view('admin.food.create', [ 'breadcrumbs' => $this->breadcrumbs, ]); } /** * @param $id * @param FoodRequest $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View */ public function edit($id, FoodRequest $request) { /** @var Food $food */ $food = Food::find($id); if ($request->isMethod('post')) { DB::beginTransaction(); try { $food->update($request->all()); DB::commit(); messages(__('global.titles.success'), __('messages.success_update'), 'success'); return redirect()->route('admin.food.index'); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_update'), 'danger', 5000); return redirect()->route('admin.food.edit', $id); } } return view('admin.food.edit', [ 'food' => $food, 'breadcrumbs' => $this->breadcrumbs, ]); } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function destroy($id) { DB::beginTransaction(); try { Food::find($id)->delete(); DB::commit(); messages(__('global.titles.success'), __('messages.success_trashed'), 'success', 6000); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_trashed'), 'danger', 6000); return redirect()->back(); } } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function trashed(Request $request) { $food = Food::orderBy('deleted_at', 'DESC')->onlyTrashed(); if ($param = $request->search) { $food->where('id', 'LIKE', "%{$param}%"); } return view('admin.food.trashed', [ 'food' => $food->paginate(20) ]); } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function restore($id) { DB::beginTransaction(); try { /** @var Food $food */ $food = Food::where('id', $id)->onlyTrashed()->first(); $food->restore(); DB::commit(); messages(__('global.titles.success'), __('messages.success_restore'), 'success'); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_retore'), 'danger'); return redirect()->back(); } } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function forceDelete($id) { DB::beginTransaction(); try { /** @var Food $food */ $food = Food::where('id', $id)->onlyTrashed()->first(); $food->forceDelete(); DB::commit(); messages(__('global.titles.success'), __('messages.success_destroy'), 'success'); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_destroy'), 'danger'); return redirect()->back(); } } } <file_sep>/app/Models/Rest.php <?php /** * Created by Reliese Model. */ namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; /** * Class Rest * * @property int $id * @property string $name * @property string $desc * @property string $end * @property string $tel * @property string $color * @property string $logo_path * @property string $status * @property string|null $remember_token * @property Carbon|null $created_at * @property Carbon|null $updated_at * @property string|null $deleted_at * * @property Collection|Segment[] $segments * * @package App\Models */ class Rest extends Model { use SoftDeletes; protected $table = 'rests'; protected $hidden = [ 'remember_token' ]; protected $fillable = [ 'name', 'desc', 'end', 'tel', 'color', 'logo_path', 'status', 'remember_token' ]; public function segments() { return $this->hasMany(Segment::class, 'id_rest'); } } <file_sep>/app/Http/Controllers/site/HomeController.php <?php namespace App\Http\Controllers\site; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\RestRequest; use App\Models\Post; use App\Models\Rest; use Illuminate\Http\Request; class HomeController extends Controller { /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index($url,RestRequest $request) { /** @var Rest $rests */ $rest = Rest::where('url', $url)->first(); return view('home.index', [ 'rest' => $rest, ]); } public function print($url,RestRequest $request) { /** @var Rest $rests */ $rest = Rest::where('url', $url)->first(); return view('home.print', [ 'rest' => $rest, ]); } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; use App\Http\Controllers\site\HomeController; Auth::routes(); Route::get('/home', function () { return redirect("/admin"); }); Route::get('/admin', 'Admin\AdminController@index')->name('domains.index'); Route::group([ 'prefix' => env('APP_PREFIX', 'admin'), 'namespace' => 'Admin', 'middleware' => 'auth', 'as' => 'admin.' ], function () { // Rest Route::prefix('/rests')->group(function () { Route::get('/', 'RestController@index')->name('rests.index'); Route::get('/trashed', 'RestController@trashed')->name('rests.trashed'); Route::delete('/destroy/{id}', 'RestController@destroy')->name('rests.destroy'); Route::get('/{id}/restore', 'RestController@restore')->name('rests.restore'); Route::delete('/{id}/forceDelete', 'RestController@forceDelete')->name('rests.forceDelete'); Route::match(['post', 'get'], '/{id}/edit', 'RestController@edit')->name('rests.edit'); Route::match(['post', 'get'], '/create', 'RestController@create')->name('rests.create'); }); // Segment Route::prefix('/segments')->group(function () { Route::get('/', 'SegmentController@index')->name('segments.index'); Route::get('/trashed', 'SegmentController@trashed')->name('segments.trashed'); Route::delete('/destroy/{id}', 'SegmentController@destroy')->name('segments.destroy'); Route::get('/{id}/restore', 'SegmentController@restore')->name('segments.restore'); Route::delete('/{id}/forceDelete', 'SegmentController@forceDelete')->name('segments.forceDelete'); Route::match(['post', 'get'], '/{id}/edit', 'SegmentController@edit')->name('segments.edit'); Route::match(['post', 'get'], '/create', 'SegmentController@create')->name('segments.create'); }); // Food Route::prefix('/food')->group(function () { Route::get('/', 'FoodController@index')->name('food.index'); Route::get('/trashed', 'FoodController@trashed')->name('food.trashed'); Route::delete('/destroy/{id}', 'FoodController@destroy')->name('food.destroy'); Route::get('/{id}/restore', 'FoodController@restore')->name('food.restore'); Route::delete('/{id}/forceDelete', 'FoodController@forceDelete')->name('food.forceDelete'); Route::match(['post', 'get'], '/{id}/edit', 'FoodController@edit')->name('food.edit'); Route::match(['post', 'get'], '/create', 'FoodController@create')->name('food.create'); }); // Foods Route::prefix('/foods')->group(function () { Route::get('/', 'FoodsController@index')->name('foods.index'); Route::get('/trashed', 'FoodsController@trashed')->name('foods.trashed'); Route::delete('/destroy/{id}', 'FoodsController@destroy')->name('foods.destroy'); Route::get('/{id}/restore', 'FoodsController@restore')->name('foods.restore'); Route::delete('/{id}/forceDelete', 'FoodsController@forceDelete')->name('foods.forceDelete'); Route::match(['post', 'get'], '/{id}/edit', 'FoodsController@edit')->name('foods.edit'); Route::match(['post', 'get'], '/create', 'FoodsController@create')->name('foods.create'); }); }); Route::namespace('site')->group(function(){ // Route::get('/', 'HomeController')->name('home.index'); Route::get('/{url}/imprimir', 'HomeController@print')->name('home.print'); Route::get('/{url}', 'HomeController@index')->name('home.menu'); }); /*Rota da API */ Route::namespace('api')->group(function(){ Route::get('/api', 'ApiController@index'); Route::get('/api/asd', 'ArticleController@index'); Route::get('/api/asdd', 'CategoryController@index'); Route::get('/api/{slug}', 'CategoryController@show'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); <file_sep>/database/migrations/2020_10_14_210038_segments.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class Segments extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('segments', function (Blueprint $table) { $table->integer('id')->autoIncrement(); $table->integer('id_rest'); $table->string('name'); $table->string('desc'); $table->enum('status', ['on', 'off'])->default('on'); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); $table->foreign('id_rest')->references('id')->on('rests')->onDelete('CASCADE'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('segments'); } } <file_sep>/app/Http/Controllers/Admin/SegmentController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Requests\Admin\SegmentRequest; use App\Models\Segment; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; class SegmentController extends Controller { /** * @var array */ protected $breadcrumbs; /** * SegmentController constructor. */ public function __construct() { $this->breadcrumbs = [ route('admin.segments.index') => __('global.titles.segments_index'), ]; } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { /** @var Segment $segments */ $segments = Segment::orderBy('id', 'ASC'); if ($param = $request->search) { $segments->where('id', 'LIKE', "%{$param}%"); } return view('admin.segments.index', [ 'segments' => $segments->paginate(20) ]); } /** * @param SegmentRequest $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View */ public function create(SegmentRequest $request) { if ($request->isMethod('post')) { DB::beginTransaction(); try { /** @var Segment $segment */ $segment = Segment::create($request->all()); DB::commit(); messages(__('global.titles.success'), __('messages.success_store'), 'success'); return redirect()->route('admin.segments.index'); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_store'), 'danger', 5000); return redirect()->back(); } } return view('admin.segments.create', [ 'breadcrumbs' => $this->breadcrumbs, ]); } /** * @param $id * @param SegmentRequest $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View */ public function edit($id, SegmentRequest $request) { /** @var Segment $segment */ $segment = Segment::find($id); if ($request->isMethod('post')) { DB::beginTransaction(); try { $segment->update($request->all()); DB::commit(); messages(__('global.titles.success'), __('messages.success_update'), 'success'); return redirect()->route('admin.segments.index'); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_update'), 'danger', 5000); return redirect()->route('admin.segments.edit', $id); } } return view('admin.segments.edit', [ 'segment' => $segment, 'breadcrumbs' => $this->breadcrumbs, ]); } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function destroy($id) { DB::beginTransaction(); try { Segment::find($id)->delete(); DB::commit(); messages(__('global.titles.success'), __('messages.success_trashed'), 'success', 6000); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_trashed'), 'danger', 6000); return redirect()->back(); } } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function trashed(Request $request) { $segments = Segment::orderBy('deleted_at', 'DESC')->onlyTrashed(); if ($param = $request->search) { $segments->where('id', 'LIKE', "%{$param}%"); } return view('admin.segments.trashed', [ 'segments' => $segments->paginate(20) ]); } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function restore($id) { DB::beginTransaction(); try { /** @var Segment $segment */ $segment = Segment::where('id', $id)->onlyTrashed()->first(); $segment->restore(); DB::commit(); messages(__('global.titles.success'), __('messages.success_restore'), 'success'); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_retore'), 'danger'); return redirect()->back(); } } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function forceDelete($id) { DB::beginTransaction(); try { /** @var Segment $segment */ $segment = Segment::where('id', $id)->onlyTrashed()->first(); $segment->forceDelete(); DB::commit(); messages(__('global.titles.success'), __('messages.success_destroy'), 'success'); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_destroy'), 'danger'); return redirect()->back(); } } } <file_sep>/routes/admin.php <?php use \Illuminate\Support\Facades\Route; Route::prefix('/publish')->group(function () { Route::get('/', 'PublishController@index')->name('publish.index'); }); // Rest Route::prefix('/rests')->group(function () { Route::get('/', 'RestController@index')->name('rests.index'); Route::get('/trashed', 'RestController@trashed')->name('rests.trashed'); Route::delete('/destroy/{id}', 'RestController@destroy')->name('rests.destroy'); Route::get('/{id}/restore', 'RestController@restore')->name('rests.restore'); Route::delete('/{id}/forceDelete', 'RestController@forceDelete')->name('rests.forceDelete'); Route::match(['post', 'get'], '/{id}/edit', 'RestController@edit')->name('rests.edit'); Route::match(['post', 'get'], '/create', 'RestController@create')->name('rests.create'); }); // Segment Route::prefix('/segments')->group(function () { Route::get('/', 'SegmentController@index')->name('segments.index'); Route::get('/trashed', 'SegmentController@trashed')->name('segments.trashed'); Route::delete('/destroy/{id}', 'SegmentController@destroy')->name('segments.destroy'); Route::get('/{id}/restore', 'SegmentController@restore')->name('segments.restore'); Route::delete('/{id}/forceDelete', 'SegmentController@forceDelete')->name('segments.forceDelete'); Route::match(['post', 'get'], '/{id}/edit', 'SegmentController@edit')->name('segments.edit'); Route::match(['post', 'get'], '/create', 'SegmentController@create')->name('segments.create'); }); // Food Route::prefix('/food')->group(function () { Route::get('/', 'FoodController@index')->name('food.index'); Route::get('/trashed', 'FoodController@trashed')->name('food.trashed'); Route::delete('/destroy/{id}', 'FoodController@destroy')->name('food.destroy'); Route::get('/{id}/restore', 'FoodController@restore')->name('food.restore'); Route::delete('/{id}/forceDelete', 'FoodController@forceDelete')->name('food.forceDelete'); Route::match(['post', 'get'], '/{id}/edit', 'FoodController@edit')->name('food.edit'); Route::match(['post', 'get'], '/create', 'FoodController@create')->name('food.create'); }); // Foods Route::prefix('/foods')->group(function () { Route::get('/', 'FoodsController@index')->name('foods.index'); Route::get('/trashed', 'FoodsController@trashed')->name('foods.trashed'); Route::delete('/destroy/{id}', 'FoodsController@destroy')->name('foods.destroy'); Route::get('/{id}/restore', 'FoodsController@restore')->name('foods.restore'); Route::delete('/{id}/forceDelete', 'FoodsController@forceDelete')->name('foods.forceDelete'); Route::match(['post', 'get'], '/{id}/edit', 'FoodsController@edit')->name('foods.edit'); Route::match(['post', 'get'], '/create', 'FoodsController@create')->name('foods.create'); }); <file_sep>/database/migrations/2020_10_14_204632_rests.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class Rests extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('rests', function (Blueprint $table) { $table->integer('id')->autoIncrement(); $table->integer('id_user'); $table->string('name'); $table->string('url'); $table->text('desc'); $table->string('end'); $table->string('horFunc'); $table->string('tel'); $table->string('color'); $table->string('logo_path'); $table->enum('status', ['on', 'off'])->default('on'); $table->foreign('id_user')->references('id')->on('users')->onDelete('CASCADE'); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('rests'); } } <file_sep>/app/Http/Controllers/Admin/RestController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Requests\Admin\RestRequest; use App\Models\Rest; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; class RestController extends Controller { /** * @var array */ protected $breadcrumbs; /** * RestController constructor. */ public function __construct() { $this->breadcrumbs = [ route('admin.rests.index') => __('global.titles.rests_index'), ]; } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { /** @var Rest $rests */ $rests = Rest::orderBy('id', 'ASC'); if ($param = $request->search) { $rests->where('id', 'LIKE', "%{$param}%"); } return view('admin.rests.index', [ 'rests' => $rests->paginate(20) ]); } /** * @param RestRequest $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View */ public function create(RestRequest $request) { if ($request->isMethod('post')) { DB::beginTransaction(); try { /** @var Rest $rest */ $rest = Rest::create($request->all()); DB::commit(); messages(__('global.titles.success'), __('messages.success_store'), 'success'); return redirect()->route('admin.rests.index'); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_store'), 'danger', 5000); return redirect()->back(); } } return view('admin.rests.create', [ 'breadcrumbs' => $this->breadcrumbs, ]); } /** * @param $id * @param RestRequest $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View */ public function edit($id, RestRequest $request) { /** @var Rest $rest */ $rest = Rest::find($id); if ($request->isMethod('post')) { DB::beginTransaction(); try { $rest->update($request->all()); DB::commit(); messages(__('global.titles.success'), __('messages.success_update'), 'success'); return redirect()->route('admin.rests.index'); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_update'), 'danger', 5000); return redirect()->route('admin.rests.edit', $id); } } return view('admin.rests.edit', [ 'rest' => $rest, 'breadcrumbs' => $this->breadcrumbs, ]); } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function destroy($id) { DB::beginTransaction(); try { Rest::find($id)->delete(); DB::commit(); messages(__('global.titles.success'), __('messages.success_trashed'), 'success', 6000); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_trashed'), 'danger', 6000); return redirect()->back(); } } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function trashed(Request $request) { $rests = Rest::orderBy('deleted_at', 'DESC')->onlyTrashed(); if ($param = $request->search) { $rests->where('id', 'LIKE', "%{$param}%"); } return view('admin.rests.trashed', [ 'rests' => $rests->paginate(20) ]); } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function restore($id) { DB::beginTransaction(); try { /** @var Rest $rest */ $rest = Rest::where('id', $id)->onlyTrashed()->first(); $rest->restore(); DB::commit(); messages(__('global.titles.success'), __('messages.success_restore'), 'success'); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_retore'), 'danger'); return redirect()->back(); } } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function forceDelete($id) { DB::beginTransaction(); try { /** @var Rest $rest */ $rest = Rest::where('id', $id)->onlyTrashed()->first(); $rest->forceDelete(); DB::commit(); messages(__('global.titles.success'), __('messages.success_destroy'), 'success'); return redirect()->back(); } catch (\Exception $exception) { DB::rollBack(); messages(__('global.titles.danger'), __('messages.error_destroy'), 'danger'); return redirect()->back(); } } } <file_sep>/app/Http/Controllers/api/ApiController.php <?php namespace App\Http\Controllers\api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\Post; class ApiController extends Controller { /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { $total = Post::get(); for($x = 0; $x < count($total); $x ++){ $post[$x]['id'] = $total[$x]['id']; $post[$x]['title'] = $total[$x]['title']; // $post[$x]['content'] = $total[$x]['content']; // $post[$x]['idUser'] = $total[$x]['idUser']; $post[$x]['img'] = "http://localhost:8000/img/logo_bubowl_small.png"; } return $post; } } <file_sep>/app/Console/Commands/MakeService.php <?php namespace App\Console\Commands; use Illuminate\Console\Command; class MakeService extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'make:service {service} {--reset}'; /** * The console command description. * * @var string */ protected $description = 'Services create'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * Command create a new service * @return mixed|void */ public function handle() { $service = $this->argument('service'); $options = $this->options(); if (!is_dir(app_path('Services'))) { mkdir(app_path('Services')); $this->info('Directory app/Services created'); } if (file_exists(app_path("Services/{$service}Service.php"))) { if ($options['reset']) { $this->make($service); return; } $this->error('This service already exists, if you want to redo it, add option --reset'); return; } $this->make($service); } /** * @param string $service * @return void */ protected function make(string $service) { $estrutura = '<?php namespace App\Services; /** * Class %1$sService * @package App\Services */ class %1$sService { /** * %1$sService constructor. */ public function __construct() { #call your models, repositories and another things here } }'; file_put_contents(app_path("Services/{$service}Service.php"), sprintf($estrutura, $service)); $this->info("Service {$service} created"); } } <file_sep>/app/Console/Commands/ResourceGenerator.php <?php namespace App\Console\Commands; use Doctrine\DBAL\Driver\PDOException; use Illuminate\Console\Command; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; class ResourceGenerator extends Command { protected $signature = 'resource:generator {name : Class (singular) for example User} {path="" : Path (singular) for example Admin}'; protected $description = 'Create CRUD operations'; public function __construct() { parent::__construct(); } public function handle() { $name = $this->argument('name'); $path = $this->argument('path'); $this->route($name, $path); $this->controller($name, $path); $this->model($name); $this->request($name, $path); $this->view($name, Str::lower($path)); } protected function controller($name, $path) { $nameSpace = ($path == '""') ? "" : "\\$path"; $path = ($path == '""') ? "" : "$path/"; $controllerTemplate = str_replace([ '{{modelName}}', '{{modelNamePlural}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}', '{{modelNameSingularCamelCase}}', '{{modelNamePluralCamelCase}}', '{{nameSpace}}', ], [ $name, Str::plural($name), Str::lower(Str::plural($name)), Str::lower($name), lcfirst($name), Str::plural(lcfirst($name)), $nameSpace, ], $this->getStub('Controller', $path) ); try { file_put_contents(app_path("/Http/Controllers/{$path}{$name}Controller.php"), $controllerTemplate); $this->info("Controller {$name}Controller.php generated"); } catch (\Exception $exception) { $this->error("Error: {$exception->getMessage()} Row: {$exception->getLine()}"); } } protected function view(string $name, string $prefix) { $types = [ "index", "trashed", "create", "edit", "blocks/form", ]; foreach ($types as $type) { $template = str_replace([ '{{modelName}}', '{{modelNamePlural}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}', '{{modelNameSingularCamelCase}}', '{{modelNamePluralCamelCase}}', ], [ $name, Str::plural($name), strtolower(Str::plural($name)), strtolower($name), lcfirst($name), Str::plural(lcfirst($name)), ], file_get_contents(resource_path("stubs/{$prefix}/views/{$type}.stub"))); try { $folder = strtolower(Str::plural($name)); if (!Storage::disk('resource')->exists($path = "views/{$prefix}/{$folder}")) { Storage::disk('resource')->makeDirectory($path); } if (!Storage::disk('resource')->exists($path = "views/{$prefix}/{$folder}/blocks")) { Storage::disk('resource')->makeDirectory($path); } if (Storage::disk('resource')->put("views/{$prefix}/{$folder}/{$type}.blade.php", $template)) { $this->info("View {$prefix}.{$folder}.{$type} generated"); } } catch (\Exception $exception) { $this->error("Error: {$exception->getMessage()} Row: {$exception->getLine()}"); } } } protected function model(string $name) { try { try { $table = Str::lower(Str::plural($name)); Artisan::call("code:models --table={$table}"); } catch (\Exception $argumentException) { Artisan::call("make:model Models/{$name}"); } $this->info("Model {$name} generated"); } catch (PDOException $PDOException) { $this->error("Error: {$PDOException->getMessage()}"); } } protected function request(string $name, string $path) { try { Artisan::call("make:request {$path}/{$name}Request"); $this->info("{$name}Request generated, do you need change authorize method for true or rules access control"); } catch (\InvalidArgumentException $argumentException) { $this->error("Error: {$argumentException->getMessage()} Row: {$argumentException->getLine()}"); } } protected function route(string $name, string $prefix) { $namePlural = strtolower(Str::plural($name)); preg_match_all("/[A-Z]/", $name, $matche); $routeName = $name; if (!empty($matche[0])) { foreach ($matche[0] as $key => $value) { if ($key > 0) { $routeName = str_replace($value, "-{$value}", $routeName); } } } $routeName = trim(Str::lower(Str::plural($routeName)), '-'); $route = " // {$name} Route::prefix('/{$routeName}')->group(function () { Route::get('/', '{$name}Controller@index')->name('{$namePlural}.index'); Route::get('/trashed', '{$name}Controller@trashed')->name('{$namePlural}.trashed'); Route::delete('/destroy/{id}', '{$name}Controller@destroy')->name('{$namePlural}.destroy'); Route::get('/{id}/restore', '{$name}Controller@restore')->name('{$namePlural}.restore'); Route::delete('/{id}/forceDelete', '{$name}Controller@forceDelete')->name('{$namePlural}.forceDelete'); Route::match(['post', 'get'], '/{id}/edit', '{$name}Controller@edit')->name('{$namePlural}.edit'); Route::match(['post', 'get'], '/create', '{$name}Controller@create')->name('{$namePlural}.create'); }); "; if (file_put_contents(base_path('routes/' . Str::lower($prefix) . '.php'), $route, FILE_APPEND)) { $this->info("Routes from {$name} generated, do you need agruped now"); return; } $this->error('Error: Route not generated.'); } protected function getStub(string $type, string $path) { return file_get_contents(resource_path("stubs/" . Str::lower($path) . "/{$type}.stub")); } } <file_sep>/app/Models/Food.php <?php /** * Created by Reliese Model. */ namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; /** * Class Food * * @property int $id * @property int $id_segment * @property string $name * @property string $desc * @property float $price * @property string $status * @property string|null $remember_token * @property Carbon|null $created_at * @property Carbon|null $updated_at * @property string|null $deleted_at * * @property Segment $segment * * @package App\Models */ class Food extends Model { use SoftDeletes; protected $table = 'foods'; protected $casts = [ 'id_segment' => 'int', 'price' => 'float' ]; protected $hidden = [ 'remember_token' ]; protected $fillable = [ 'id_segment', 'name', 'desc', 'price', 'status', 'remember_token' ]; public function segment() { return $this->belongsTo(Segment::class, 'id_segment'); } }
c1d7fed983bd3109703d038d236c9133182c3253
[ "PHP" ]
16
PHP
emersong2112/bubowlQr
5ba21b38f714cf47556d003d7ed1ecd17fa3ea12
c4681b2ef3ff7e9fe86ff762746c024528c3d299
refs/heads/master
<repo_name>Menachem35/Recent-post-plugin<file_sep>/plugin-menachem-adweek.php <?php /* Plugin Name: Menachem ADWEEK Code assessment Plugin URI: http://www.glikdesign.com/ Description: a plugin assignment for the Adweek WordPress Developer Role. Version: 1.0 Author: <NAME> Author URI: http://www.glikdesign.com/ License: GPL2 */ wp_register_style ( 'AW-style', plugins_url ( 'style.css', __FILE__ ) ); wp_enqueue_style('AW-style'); /** * Displays the timestamp * */ function time_ago( $type = 'post' ) { $d = 'posted' == $type ? 'get_comment_time' : 'get_post_time'; return human_time_diff($d('U'), current_time('timestamp')) . " " . __('ago'); } /** * Displays the latest post * */ function display_most_recent_post($content) { global $post; $html = ""; $my_query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 1 )); $html .="<div class=\"AW-container\">" . "\n"; if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post(); $img_url = wp_get_attachment_image_src(get_post_thumbnail_id(),'single-post-thumbnail'); $recent_post_img_url = $img_url [0]; $awcategory = get_the_category(); $html .="<div class=\"AW-item\">" . "<img src=\"" . $recent_post_img_url . "\" class=\"AW-postImg\">" . "</div>" . "\n"; $html .="<div class=\"AW-item-1\">". "\n"; $html .= "<p class=\"AW-category\">" . $awcategory[0]->cat_name . "<span class=\"AW-TimestampMobile\">" . "|" . time_ago(). "</span></p>". "\n"; $html .= "<a href=\"" . get_permalink() . "\" class=\"AW-postLink\">" . get_the_title() . "</a>". "\n"; $html .= "<br />". "\n"; $html .= "<p class=\"AW-text\">By <span id=\"AW-Author\">" . ' ' . the_author() . "</span>" . "<span class=\"AW-Timestamp\">" . time_ago(). "</span></p>". "\n"; endwhile; endif; $html .="</div>\n"; $content .= $html; return $content; } add_action( 'the_content', 'display_most_recent_post'); ?> <file_sep>/README.md # Recent-post-plugin Wordpress plugin to display the most recent post Plugin written by <NAME> Feel free to use.
32e63961ce52642eaa1c694a7642db56a397fa4b
[ "Markdown", "PHP" ]
2
PHP
Menachem35/Recent-post-plugin
36b70ea166075c387ba6b15f6e62d00e78db0d9a
14b883d30a179a7600c21d36aa77a54786fdbae1
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, HttpResponse, redirect import random from datetime import datetime # Create your views here. def index(request): if 'total' not in request.session: #request.session['updated'] = False request.session['total'] = 0 request.session['log'] = [] return render (request, 'gold/index.html') #helper function to update total & build log entry def helper(request, earn, where, when): request.session['total'] += earn log = {'event': "Earned " + str(earn) + " gold from the " + where + "! " + "(" + when + ")", 'class': 'earn'} request.session['log'].append(log) request.session['updated'] = True def process(request): # store event time when = datetime.now().strftime( "%x, %X") # collect appropriate value & location then process w/ helper() if request.POST['building'] == 'farm': earn = random.randint(10,21) where = 'farm' helper(request, earn, where, when) if request.POST['building'] == 'cave': earn = random.randint(5,11) where = 'cave' helper(request, earn, where, when) if request.POST['building'] == 'cave': earn = random.randint(2,6) where = 'house' helper(request, earn, where, when) if request.POST['building'] == 'casino' : earn = random.randint(1,101) - 50 where = 'casino' helper(request, earn, where, when) # build log entry for casion case if earn < 0: log = {'event': "Entered a casino and lost " + str(earn) + " gold... Ouch! (" + when +")", 'class': 'loss' } request.session['log'].append(log) request.session['updated'] = True #prevent break-even case (benefit of the doubt:) elif earn == 0: earn += 1 helper(request, earn, where, when) # return HttpResponse (request.session['log']) return redirect ('/')
2275c9cf7ba5ad3146a3286725d10eae7c60153f
[ "Python" ]
1
Python
Unknonymous/Ninja_Gold
4ae573acf21a84637be11d5cc574e7fb4dd15fb2
a4778040fe6f29aaf3ad3133f7a9600ba08d31aa
refs/heads/master
<repo_name>jeffersonjuliano/advpl<file_sep>/Aulas/Relatorio/RelSimples/SQLQuery3.sql SELECT A1_COD, A1_NOME, C5_NUM, C6_QTDVEN, C6_PRCVEN,B1_DESC FROM SA1990 SA1, SC5990 SC5, SC6990 SC6, SB1990 SB1 WHERE SA1.D_E_L_E_T_= '' AND C5_FILIAL = '01' AND SC5.D_E_L_E_T_ = '' AND C5_CLIENTE = A1_COD AND C6_FILIAL = '01' AND SC6.D_E_L_E_T_= '' AND C6_NUM = C5_NUM AND B1_FILIAL = '' AND SB1.D_E_L_E_T_ = '' AND B1_COD = C6_PRODUTO ORDER BY A1_FILIAL, A1_COD, C5_FILIAL,C5_NUM, C6_FILIAL, C6_ITEM
8f26bfc6df7372a6a35a5e292a0f8aeef86ad76d
[ "SQL" ]
1
SQL
jeffersonjuliano/advpl
5e3b265330e1a7a476877b0d75ad7a79561bb2f4
8cb6bcecea8b9e7d652accc45e3e29c07a59a07b
refs/heads/master
<file_sep>module.exports = { plugins: { "posthtml-extend": { root: './' }, "posthtml-include": { root: './' }, "posthtml-expressions": { "locals": { "mainMenuItems": { "playground": { title: "Playground", link: "/", activeMenuItemLink: "/" }, }, } }, }, };
92d8bbd40fce3f6fb0c05b1e803545492fe46664
[ "JavaScript" ]
1
JavaScript
int0x33/phpstan
12e0a1db53a08562b9405bf72c428e7e46bc402f
ea5d525cbce4f3cecfa8062b6606e4ce4fb318b2
refs/heads/master
<file_sep>var addToBasket = document.getElementsByClassName('buy'); Array.from(addToBasket).forEach(function(el) { el.addEventListener('click', function(){ changeButton(el); changeOpacity(el); }); }); function changeButton(el){ el.innerText = 'تم الطلب'; el.style.backgroundColor = '#1dd1a1'; } function changeOpacity(el){ var mealCard = el.closest('.meal-card'); mealCard.style.opacity = '0.5'; }<file_sep>from flask import Flask, request, jsonify, Response from flask_cors import CORS app = Flask(__name__) CORS(app) meals_list = [] class Meal(): def __init__(self, name, description, image, price): self.name = name self.description = description self.image = image self.price = price def get_all_meals(): all_meals = [meal.__dict__ for meal in meals_list] return jsonify(all_meals) def add_new_meal(meal_data): new_meal = Meal( name=meal_data['name'], description=meal_data['description'], image=meal_data['image'], price=meal_data['price'], ) meals_list.append(new_meal) @app.route('/meals', methods=['GET', 'POST']) def meals(): if request.method == 'GET': return get_all_meals() elif request.method == 'POST': meal_data = request.get_json() add_new_meal(meal_data) return Response(status=201) if __name__ == '__main__': app.run(host='0.0.0.0', port=8080)
a730cd459605bf8162279cf4cdf844aa6d067911
[ "JavaScript", "Python" ]
2
JavaScript
bibaflower1/frontend-backend-difference-workshop
04a1543b6c9aa95624850699ea7509e8eac859db
e281ea44a4381e3ff8e9d266d5050d59a1408c49
refs/heads/main
<file_sep>import me.tongfei.progressbar.ProgressBar; import me.tongfei.progressbar.ProgressBarBuilder; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import static java.nio.charset.StandardCharsets.UTF_8; public class Statements { ArrayList<Statement> statementList = new ArrayList<>(); public void generateAudienceReport (Path inputPath){ try { statementList.clear(); readStatements(inputPath); } catch (IOException e) { e.printStackTrace(); } Calendar c1 =Calendar.getInstance(); Collections.sort(statementList); Calendar c2 =Calendar.getInstance(); System.out.println(c2.getTimeInMillis()-c1.getTimeInMillis()); calculateOutput(statementList); } private void calculateOutput(ArrayList<Statement> list){ ProgressBarBuilder pbb = new ProgressBarBuilder(); Path outputPath = Paths.get("src\\main\\java\\resources\\output.txt"); Integer homeNumber = null; long duration=0; LocalDateTime endTime; // StringBuilder stringBuilder = new StringBuilder(); try (ProgressBar pb = new ProgressBar("Calculate", list.size())) { FileOutputStream fileOutputStream = new FileOutputStream("output2.txt"); PrintWriter printWriter = new PrintWriter(fileOutputStream); printWriter.println("HomeNo|Channel|StartTime|Activity|EndTime|Duration"); for (int i = 0; i < list.size(); i++) { Statement statement1 = list.get(i); if (i < list.size() - 1) { endTime = list.get(i + 1).getStartTime(); homeNumber = list.get(i + 1).getHomeNumber(); } else { endTime = statement1.getStartTime().plusDays(1).withHour(0).withMinute(0).withSecond(0); homeNumber = statement1.getHomeNumber(); } if (statement1.getHomeNumber().equals(homeNumber)) { if (isSameDay(statement1.getStartTime(), endTime)) { duration = ChronoUnit.SECONDS.between(statement1.getStartTime(), endTime); OutputStatement outputStatement = new OutputStatement(homeNumber, statement1.getChannel(), statement1.getStartTime(), endTime, statement1.getActivity(), duration); printWriter.println(outputStatement); } else { endTime = statement1.getStartTime().plusDays(1).withHour(0).withMinute(0).withSecond(0); duration = ChronoUnit.SECONDS.between(statement1.getStartTime(), endTime); OutputStatement outputStatement = new OutputStatement(homeNumber, statement1.getChannel(), statement1.getStartTime(), endTime, statement1.getActivity(), duration); printWriter.println(outputStatement); } } else { endTime = statement1.getStartTime().plusDays(1).withHour(0).withMinute(0).withSecond(0); duration = ChronoUnit.SECONDS.between(statement1.getStartTime(), endTime); OutputStatement outputStatement = new OutputStatement(statement1.getHomeNumber(), statement1.getChannel(), statement1.getStartTime(), endTime, statement1.getActivity(), duration); printWriter.println(outputStatement); } pb.step(); } printWriter.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println("finish"); } private boolean isSameDay(LocalDateTime date1, LocalDateTime date2) { return date1.toLocalDate().equals(date2.toLocalDate()); } private void readStatements(Path inputPath) throws IOException { Calendar c1 =Calendar.getInstance(); List<String> lines = Files.readAllLines(inputPath.toAbsolutePath(), UTF_8); // List<Statement> statements = new ArrayList<Statement>(); lines.stream().skip(1).forEach( line->{ String[] fields = line.split("\\|"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); LocalDateTime dateTime = LocalDateTime.parse(fields[2], formatter); statementList.add(new Statement(Integer.parseInt(fields[0]), Integer.parseInt(fields[1]), dateTime, fields[3])); } ); Calendar c3 =Calendar.getInstance(); System.out.println(c3.getTimeInMillis()-c1.getTimeInMillis()); } }
00e23ab14a1ae1fd38d146b951daec559af03579
[ "Java" ]
1
Java
dhampir1/Audience_v1
009ee57b913e06c5cdc19ec3ac3b006850dd71b6
37a54135716f9e3f2cba72f397fd60cfc168c394
refs/heads/master
<repo_name>eiffelqiu/ass<file_sep>/README.md ass ======= ####Apple Service Server was written with Ruby/Sinatra and Sequel(Sqlite3), it provides push notification with web admin interface #### Feature: ======= 1. 'ass' is a rubygem, simple to install. 2. only need to provide pem file. 3. no need to setup database(using sqlite3). 4. provide default config file(ass.yml) with default value. Sqlite3 Installation ======= CentOS/Redhat: $ yum install sqlite3 Debian/Ubuntu: $ apt-get install sqlite3 FreeBSD: $ cd /usr/ports/databases/sqlite34 $ sudo make install clean Mac: $ brew install sqlite # Homebrew $ port install sqlite # Macport Installation * Method 1: with OS X builtin Ruby(AKA 'system ruby'), need to run with 'sudo', no extra step ```bash $ sudo gem install ass ``` * Method 2: Install Ruby 1.9 (via RVM or natively) first, no need to run with 'sudo' ```bash $ gem install rvm $ rvm install 1.9.3 $ rvm use 1.9.3 ``` * Install ass: ```bash $ gem install ass ``` Usage ======= under the current directory, provide single pem file combined with certificate and key(name pattern: appid_mode.pem), HOWTO ([Check this link](http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12)) How to make development pem file ------- dev_cert.pem: $ openssl x509 -in aps_development.cer -inform der -out dev_cert.pem dev_key.pem: $ openssl pkcs12 -nocerts -in Certificates.p12 -out dev_key.pem $ Enter Import Password: $ MAC verified OK $ Enter PEM pass phrase: $ Verifying - Enter PEM pass phrase: Development Pem: $ cat dev_cert.pem dev_key.pem > appid_development.pem How to make produce production pem file ------- prod_cert.pem: $ openssl x509 -in aps_production.cer -inform der -out prod_cert.pem prod_key.pem: $ openssl pkcs12 -nocerts -in Certificates.p12 -out prod_key.pem $ Enter Import Password: $ MAC verified OK $ Enter PEM pass phrase: $ Verifying - Enter PEM pass phrase: Production Pem: $ cat prod_cert.pem prod_key.pem > appid_production.pem Start Ass server(default port is 4567) ------- $ ass ![ass usage](https://raw.github.com/eiffelqiu/ass/master/doc/capture1.png) ![ass usage](https://raw.github.com/eiffelqiu/ass/master/doc/capture2.png) ![ass usage](https://raw.github.com/eiffelqiu/ass/master/doc/capture3.png) ![ass usage](https://raw.github.com/eiffelqiu/ass/master/doc/capture4.png) Configuration (ass.yml) ======= when you run 'ass' first time, it will generate 'ass.yml' config file under current directory. ([Check this link](https://raw.github.com/eiffelqiu/ass/master/ass.yml)) port: 4567 ## ASS server port, default is sinatra's port number: 4567 mode: development ## 'development' or 'production' mode, you should provide pem file ({appid}_{mode}.pem) accordingly(such as, app1_development.pem, app1_production.pem). cron: cron ## cron job file name, ASS server will generate a demo 'cron' file for demostration only under current directory. timer: 0 # how often you run the cron job, unit: minute. when set with 0, means no cron job execute. user: admin # admin username pass: <PASSWORD> # admin password flood: 1 # request time from same ip every one minute as Flood Attack pempass: <PASSWORD> # pem password loglevel: info # logger level apps: - app1 ## appid you want to supprt APNS, ASS Server can give push notification support for many iOS apps, just list the appid here. FAQ: ======= 1. How to register notification? (Client Side) ------- In AppDelegate file, add methods below to register device token #pragma mark - push notification methods - (void)sendToken:(NSString *)token { NSString *tokenUrl = [NSString stringWithFormat:@"http://serverIP:4567/v1/apps/app1/%@", token]; NSLog(@"tokenUrl: %@", tokenUrl); //prepare NSURL with newly created string NSURL *url = [NSURL URLWithString:tokenUrl]; //AsynchronousRequest to grab the data NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if ([data length] > 0 && error == nil) { // NSLog(@"send data successfully"); } else if ([data length] == 0 && error == nil) { // NSLog(@"No data"); } else if (error != nil && error.code == NSURLErrorTimedOut) { //used this NSURLErrorTimedOut from // NSLog(@"Token Time out"); } else if (error != nil) { // NSLog(@"Error is: [%@]", [error description]); } }]; } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSString *tokenAsString = [[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]] stringByReplacingOccurrencesOfString:@" " withString:@""]; NSLog(@"My token is: [%@]", tokenAsString); [self sendToken:tokenAsString]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"Failed to get token, error: %@", error); } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { NSString *message = nil; NSString *sound = nil; NSString *extra = nil; id aps = [userInfo objectForKey:@"aps"]; extra = [userInfo objectForKey:@"extra"]; if ([aps isKindOfClass:[NSString class]]) { message = aps; } else if ([aps isKindOfClass:[NSDictionary class]]) { message = [aps objectForKey:@"alert"]; sound = [aps objectForKey:@"sound"]; // badge } if (aps) { DLog(@"extra %@",[NSString stringWithFormat:@"sound %@ extra %@", sound, extra ]); } } 2. How to send push notification? (Server Side) ------- run **curl** command to send push notification message on server' shell. $ curl http://localhost:4567/v1/apps/app1/push/{message}/{pid} Note: param1 (message): push notification message you want to send, remember the message should be html escaped param2 (pid ): unique string to mark the message, for example current timestamp or md5/sha1 digest 3. How to send test push notification on web? ------- open your web browser and access http://localhost:4567/ (localhost should be changed to your server IP address accordingly), click "admin" on top navbar, you will see the Test Sending textbox on the top page, select your app , input your message and click 'send' button to send push notification. ![ass usage](https://raw.github.com/eiffelqiu/ass/master/doc/capture5.png) 4. How to run ass in background? ------- $ nohup ass control + z to return to shell prompt $ bg now ass is running as a background service . Contributing to ass ======= * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet. * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it. * Fork the project. * Start a feature/bugfix branch. * Commit and push until you are happy with your contribution. * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally. * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it. Copyright ======= #####Copyright (c) 2013 <NAME>. See LICENSE.txt for further details.##### <file_sep>/lib/ass.rb #encoding: utf-8 require 'ass/conf' require 'ass/app'<file_sep>/lib/ass/conf.rb #encoding: utf-8 require 'rubygems' require 'yaml' require 'logger' require 'sequel' require 'socket' require 'openssl' require 'cgi' require 'rufus/scheduler' require 'uri' require 'uri-handler' require 'net/http' require 'active_support' require 'json' require 'digest/sha2' require 'will_paginate' require 'will_paginate/sequel' ############################################################ ## Initilization Setup ############################################################ LIBDIR = File.expand_path(File.join(File.dirname(__FILE__), '../..', 'lib')) ROOTDIR = File.expand_path(File.join(File.dirname(__FILE__), '../..')) unless $LOAD_PATH.include?(LIBDIR) $LOAD_PATH << LIBDIR end unless File.exist?("#{Dir.pwd}/ass.yml") then puts 'create config file: ass.yml' system "cp #{ROOTDIR}/ass.yml #{Dir.pwd}/ass.yml" end unless File.exist?("#{Dir.pwd}/cron") then puts "create a demo 'cron' script" system "cp #{ROOTDIR}/cron #{Dir.pwd}/cron" end ############################################################ ## Configuration Setup ############################################################ env = ENV['SINATRA_ENV'] || "development" config = YAML.load_file("#{Dir.pwd}/ass.yml") $timer = "#{config['timer']}".to_i $cron = config['cron'] || 'cron' $port = "#{config['port']}".to_i || 4567 $mode = config['mode'] || env $VERSION = File.open("#{ROOTDIR}/VERSION", "rb").read $apps = config['apps'] || [] $log = config['log'] || 'off' $user = config['user'] || 'admin' $pass = config['pass'] || '<PASSWORD>' $pempass = config['pempass'] || '' $loglevel = config['loglevel'] || 'info' $flood = "#{config['flood']}".to_i || 1 # default 1 minute $client_ip = '1172.16.17.32' $last_access = 0 ############################################################ ## Certificate Key Setup ############################################################ $certkey = {} def check_cert $apps.each { |app| unless File.exist?("#{Dir.pwd}/#{app}_#{$mode}.pem") then puts "Please provide #{app}_#{$mode}.pem under '#{Dir.pwd}/' directory" return false; else puts "'#{app}'s #{$mode} PEM: (#{app}_#{$mode}.pem)" certfile = File.read("#{Dir.pwd}/#{app}_#{$mode}.pem") openSSLContext = OpenSSL::SSL::SSLContext.new openSSLContext.cert = OpenSSL::X509::Certificate.new(certfile) if $pempass == '' then openSSLContext.key = OpenSSL::PKey::RSA.new(certfile) else openSSLContext.key = OpenSSL::PKey::RSA.new(certfile,"#{$pempass}") end $certkey["#{app}"] = openSSLContext end } return true end unless check_cert then html = <<-END 1: please provide certificate key pem file under current directory, name should be: appid_development.pem for development and appid_production.pem for production 2: edit your ass.yml under current directory 3: run ass 4: iOS Client: in AppDelegate file, didRegisterForRemoteNotificationsWithDeviceToken method should access url below: END $apps.each { |app| html << "'#{app}'s registration url: http://serverIP:#{$port}/v1/apps/#{app}/DeviceToken" } html << "5: Server: cron should access 'curl http://localhost:#{$port}/v1/app/push/{messages}/{pid}' to send push message" puts html exit else html = <<-END #{'*'*80} Apple Service Server(#{$VERSION}) is Running ... Push Notification Service: Enabled Mode: #{$mode} Port: #{$port} END html << "#{'*'*80}" html << "Cron Job: '#{Dir.pwd}/#{$cron}' script is running every #{$timer} #{($timer == 1) ? 'minute' : 'minutes'} " unless "#{$timer}".to_i == 0 html << "\n" html << "access http://localhost:#{$port}/ for more information" html << "\n" html << "#{'*'*80}" puts html end ############################################################ ## Sequel Database Setup ############################################################ unless File.exist?("#{Dir.pwd}/ass-#{$mode}.db") then $DB = Sequel.connect("sqlite://#{Dir.pwd}/ass-#{$mode}.db") $DB.create_table :tokens do primary_key :id String :app, :unique => false, :null => false String :token, :unique => false, :null => false, :size => 100 Time :created_at index [:app, :token] end $DB.create_table :pushes do primary_key :id String :pid, :unique => false, :null => false, :size => 100 String :app, :unique => false, :null => false, :size => 30 String :message, :unique => false, :null => false, :size => 107 String :ip, :unique => false, :null => false, :size => 20 Time :created_at index [:pid, :app, :message] end else $DB = Sequel.connect("sqlite://#{Dir.pwd}/ass-#{$mode}.db") end class Token < Sequel::Model #Sequel.extension :pagination end class Push < Sequel::Model #Sequel.extension :pagination end ############################################################ ## Timer Job Setup ############################################################ scheduler = Rufus::Scheduler.new unless $timer == 0 then scheduler.every "#{$timer}m" do puts "running job: '#{Dir.pwd}/#{$cron}' every #{$timer} #{($timer == 1) ? 'minute' : 'minutes'}" system "./#{$cron}" end end<file_sep>/bin/ass #!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'rubygems' unless defined?(Gem) require 'sinatra/base' require 'thread' class Object alias sh system end require 'ass' App.run! <file_sep>/lib/ass/app.rb #encoding: utf-8 require 'rubygems' require 'yaml' require 'logger' require 'sequel' require 'socket' require 'openssl' require 'cgi' require 'rufus/scheduler' require 'eventmachine' require 'sinatra' require 'sinatra/base' require 'sinatra/synchrony' require 'rack/mobile-detect' require 'uri' require 'uri-handler' require 'net/http' require 'active_support' require 'json' require 'digest/sha2' require 'will_paginate' require 'will_paginate/sequel' ############################################################ ## Apple Service Server based on Sinatra ############################################################ class App < Sinatra::Base register Sinatra::Synchrony use Rack::MobileDetect LOGGER = Logger.new("ass-#{$mode}.log", 'a+') case $loglevel.upcase when 'FATAL' set :logging, Logger::FATAL when 'ERROR' set :logging, Logger::ERROR when 'WARN' set :logging, Logger::WARN when 'INFO' set :logging, Logger::INFO when 'DEBUG' set :logging, Logger::DEBUG else set :logging, Logger::DEBUG end if "#{$mode}".strip == 'production' then set :environment, :production set :raise_errors, false set :dump_errors, false set :show_exceptions, false set :logging, false set :reload, false else set :environment, :development set :raise_errors, true set :dump_errors, true set :show_exceptions, true set :logging, true set :reload, true end set :root, File.expand_path('../../../', __FILE__) set :port, "#{$port}".to_i set :public_folder, File.dirname(__FILE__) + '/../../public' set :views, File.dirname(__FILE__) + '/../../views' helpers do include Rack::Utils alias_method :h, :escape_html def connect_socket(app) openSSLContext = $certkey["#{app}"] sock = nil sslSocket = nil; if $mode == 'production' then sock = TCPSocket.new('gateway.push.apple.com', 2195) else sock = TCPSocket.new('gateway.sandbox.push.apple.com', 2195) end sslSocket = OpenSSL::SSL::SSLSocket.new(sock, openSSLContext) sslSocket.connect [sock, sslSocket] end def logger LOGGER end def checkFlood?(req) if $client_ip != "#{req.ip}" then $client_ip = "#{req.ip}" return false else if $last_access == 0 then return false else return isFlood? end end end def isFlood? result = (Time.now - $last_access) < $flood * 60 $last_access = Time.now return result end def iOS? result = case request.env['X_MOBILE_DEVICE'] when /iPhone|iPod|iPad/ then true else false end return result end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ["#{$user}", "#{$pass}"] end def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Restricted Area") throw(:halt, [401, "Oops... we need your login name & password\n"]) end end def push(parameter) message = CGI::unescape(parameter[:alert].encode("UTF-8") || "")[0..107] pid = "#{parameter[:pid]}" badge = 1 badge = parameter[:badge].to_i if parameter[:badge] and parameter[:badge] != '' sound = CGI::unescape(parameter[:sound] || "") extra = CGI::unescape(parameter[:extra] || "") @tokens = Token.where(:app => "#{app}").reverse_order(:id) @exist = Push.first(:pid => "#{pid}", :app => "#{app}") unless @exist Push.insert(:pid => pid, :message => message, :created_at => Time.now, :app => "#{app}", :ip => "#{parameter.ip}" ) sock, sslSocket = connect_socket("#{app}") # write our packet to the stream @tokens.each do |o| begin tokenText = "#{o[:token]}" tokenData = [tokenText].pack('H*') aps = {'aps'=> {}} aps['aps']['alert'] = message aps['aps']['badge'] = badge aps['aps']['sound'] = sound aps['aps']['extra'] = extra pm = aps.to_json packet = [0,0,32,devData,0,pm.bytesize,pm].pack("ccca*cca*") sslSocket.write(packet) rescue Errno::EPIPE, OpenSSL::SSL::SSLError => e puts "e: #{e} from id:#{o[:id]}" sleep 3 sock, sslSocket = connect_socket("#{app}") next #retry end end # cleanup sslSocket.close sock.close end end def localonly(req) protected! unless req.host == 'localhost' end end before do end get '/' do erb :index end get '/about' do erb :about end not_found do erb :not_found end error do @error = ""; @error = params['captures'].first.inspect if development? end post '/v1/send' do app = params[:app] message = CGI::escape(params[:message] || "").encode("UTF-8") pid = "#{Time.now.to_i}" # begin # url = URI.parse("http://localhost:#{$port}/v1/apps/#{app}/push") # post_args1 = { :alert => "#{message}".encode('UTF-8'), :pid => "#{pid}" } # Net::HTTP.post_form(url, post_args1) # rescue =>err # puts "#{err.class} ##{err}" # end system "curl http://localhost:#{$port}/v1/apps/#{app}/push/#{message}/#{pid}" redirect '/v1/admin/push' if (params[:app] and params[:message]) end get "/v1/admin/:db" do protected! db = params[:db] || 'token' page = 1 page = params[:page].to_i if params[:page] if (db == 'token') then @o = [] $apps.each_with_index { |app, index| @o << Token.where(:app => app).order(:id).reverse.limit(20) } erb :token elsif (db == 'push') then @p = [] $apps.each_with_index { |app, index| @p << Push.where(:app => app).order(:id).reverse.limit(20) } erb :push else erb :not_found end end $apps.each { |app| ## register token api get "/v1/apps/#{app}/:token" do if (("#{params[:token]}".length == 64) and iOS? and checkFlood?(request) ) then o = Token.first(:app => app, :token => params[:token]) unless o Token.insert( :app => app, :token => params[:token], :created_at => Time.now ) end end end ## http POST method push api post "/v1/apps/#{app}/push" do localonly(request) push(params) end ## http GET method push api ## POST method get more options get "/v1/apps/#{app}/push/:message/:pid" do localonly(request) push(params) end } end<file_sep>/ass.gemspec # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: ass 0.0.24 ruby lib Gem::Specification.new do |s| s.name = "ass" s.version = "0.0.24" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["<NAME>"] s.date = "2013-10-23" s.description = "Apple Service Server written with Sinatra and Sequel(Sqlite3)" s.email = "<EMAIL>" s.executables = ["ass"] s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ "LICENSE.txt", "README.md", "VERSION", "ass.yml", "cron", "lib/ass.rb", "lib/ass/app.rb", "lib/ass/conf.rb", "public/css/bootstrap-responsive.css", "public/css/bootstrap-responsive.min.css", "public/css/bootstrap.css", "public/css/bootstrap.min.css", "public/favicon.ico", "public/img/glyphicons-halflings-white.png", "public/img/glyphicons-halflings.png", "public/js/bootstrap.js", "public/js/bootstrap.min.js", "views/about.erb", "views/error.erb", "views/index.erb", "views/layout.erb", "views/not_found.erb", "views/push.erb", "views/token.erb" ] s.homepage = "http://github.com/eiffelqiu/ass" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubyforge_project = "ass" s.rubygems_version = "2.1.9" s.summary = "Apple Service Server" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<sqlite3>, [">= 0"]) s.add_runtime_dependency(%q<thin>, [">= 0"]) s.add_runtime_dependency(%q<json>, [">= 0"]) s.add_runtime_dependency(%q<sinatra>, [">= 0"]) s.add_runtime_dependency(%q<sequel>, [">= 0"]) s.add_runtime_dependency(%q<rufus-scheduler>, [">= 0"]) s.add_runtime_dependency(%q<eventmachine>, [">= 0"]) s.add_runtime_dependency(%q<activesupport>, [">= 0"]) s.add_runtime_dependency(%q<uri-handler>, [">= 0"]) s.add_runtime_dependency(%q<will_paginate>, [">= 0"]) s.add_runtime_dependency(%q<sinatra-contrib>, [">= 0"]) s.add_runtime_dependency(%q<rack-mobile-detect>, [">= 0"]) s.add_runtime_dependency(%q<sinatra-synchrony>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, [">= 0"]) s.add_development_dependency(%q<bundler>, [">= 0"]) s.add_development_dependency(%q<jeweler>, [">= 0"]) s.add_runtime_dependency(%q<sqlite3>, [">= 0"]) s.add_runtime_dependency(%q<thin>, [">= 0"]) s.add_runtime_dependency(%q<sinatra>, [">= 0"]) s.add_runtime_dependency(%q<sequel>, [">= 0"]) s.add_runtime_dependency(%q<rufus-scheduler>, [">= 0"]) s.add_runtime_dependency(%q<eventmachine>, [">= 0"]) s.add_runtime_dependency(%q<activesupport>, [">= 3.2.8"]) s.add_runtime_dependency(%q<uri-handler>, [">= 0"]) s.add_runtime_dependency(%q<will_paginate>, ["~> 3.0"]) s.add_runtime_dependency(%q<sinatra-contrib>, [">= 0"]) s.add_runtime_dependency(%q<rack-mobile-detect>, [">= 0"]) s.add_runtime_dependency(%q<sinatra-synchrony>, [">= 0"]) else s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<thin>, [">= 0"]) s.add_dependency(%q<json>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sequel>, [">= 0"]) s.add_dependency(%q<rufus-scheduler>, [">= 0"]) s.add_dependency(%q<eventmachine>, [">= 0"]) s.add_dependency(%q<activesupport>, [">= 0"]) s.add_dependency(%q<uri-handler>, [">= 0"]) s.add_dependency(%q<will_paginate>, [">= 0"]) s.add_dependency(%q<sinatra-contrib>, [">= 0"]) s.add_dependency(%q<rack-mobile-detect>, [">= 0"]) s.add_dependency(%q<sinatra-synchrony>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, [">= 0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<thin>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sequel>, [">= 0"]) s.add_dependency(%q<rufus-scheduler>, [">= 0"]) s.add_dependency(%q<eventmachine>, [">= 0"]) s.add_dependency(%q<activesupport>, [">= 3.2.8"]) s.add_dependency(%q<uri-handler>, [">= 0"]) s.add_dependency(%q<will_paginate>, ["~> 3.0"]) s.add_dependency(%q<sinatra-contrib>, [">= 0"]) s.add_dependency(%q<rack-mobile-detect>, [">= 0"]) s.add_dependency(%q<sinatra-synchrony>, [">= 0"]) end else s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<thin>, [">= 0"]) s.add_dependency(%q<json>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sequel>, [">= 0"]) s.add_dependency(%q<rufus-scheduler>, [">= 0"]) s.add_dependency(%q<eventmachine>, [">= 0"]) s.add_dependency(%q<activesupport>, [">= 0"]) s.add_dependency(%q<uri-handler>, [">= 0"]) s.add_dependency(%q<will_paginate>, [">= 0"]) s.add_dependency(%q<sinatra-contrib>, [">= 0"]) s.add_dependency(%q<rack-mobile-detect>, [">= 0"]) s.add_dependency(%q<sinatra-synchrony>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, [">= 0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<thin>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sequel>, [">= 0"]) s.add_dependency(%q<rufus-scheduler>, [">= 0"]) s.add_dependency(%q<eventmachine>, [">= 0"]) s.add_dependency(%q<activesupport>, [">= 3.2.8"]) s.add_dependency(%q<uri-handler>, [">= 0"]) s.add_dependency(%q<will_paginate>, ["~> 3.0"]) s.add_dependency(%q<sinatra-contrib>, [">= 0"]) s.add_dependency(%q<rack-mobile-detect>, [">= 0"]) s.add_dependency(%q<sinatra-synchrony>, [">= 0"]) end end <file_sep>/Gemfile source "http://rubygems.org" #source "http://ruby.taobao.org" #source "http://gems.github.com" # Add dependencies to develop your gem here. # Include everything needed to run rake, tests, features, etc. group :development do gem "shoulda" gem "rdoc" gem "bundler" gem "jeweler" end gem 'sqlite3' gem 'thin' gem 'json' gem 'sinatra' gem 'sequel' gem 'rufus-scheduler' gem 'eventmachine' gem 'activesupport' gem 'uri-handler' gem 'will_paginate' gem 'sinatra-contrib' gem 'rack-mobile-detect' gem 'sinatra-synchrony'
7bdb85856247044e9f145b7c62cab0358c4bdaac
[ "Markdown", "Ruby" ]
7
Markdown
eiffelqiu/ass
bf1dedb95677ae666879a494fb02a323baaf4981
859bb5188ba517e404a0bb508f70f72030d8330a
refs/heads/master
<file_sep>/// <reference path="../node_modules/angular/angular.js" /> // Module - same thing as a namespace // Each namesace has a classe (controller) // Each Controller has methods and properties // Directives connect HMTL and Angular > Module > Controller(anything starts with 'ng-' //Expresions (anthing inbetween the {{ and }} // So --- // Modules have Controllers, Controllers have methods & properties // Namespaces have Classes, clases have methods and properties (function () { var app = angular.module("store", ['store-directives', 'ngRoute']); //var app = angular.module("store", ['store-directives', 'ngRoute', 'Product']) // Provider // .config(function (ProductProvider) { // ProductProvider.setId(1); // }); //app.controller('StoreController', function (Product) { // Controller - is a class, the $http is baked in to angular, to use it use [] app.controller('StoreController', function ($http, Product) { this.products = []; this.overviewProduct = {}; var that = this; var request = $http.get('scripts/products.json'); request.then(function (response) { that.products = response.data; console.log(response.data); console.log(that.products[0].imageURL); }); this.overviewClick = function (product) { this.overviewProduct = product; var popup = document.getElementById('popup'); popup.style.display = 'block'; // console.dir(this.overviewProduct); } this.closePopup = function () { var popup = document.getElementById('popup'); popup.style.display = "none"; } }); app.controller("PanelController", function () { this.tab = 1; this.selectTab = function (tabNum) { this.tab = tabNum; }; this.isSelected = function (tabNum) { return this.tab === tabNum; }; this.getIndex = function (array, value) { var index = 0; for (var i = 0; i < array.length; i++) { if (array[i] === value) { index = i; break; } } return index; }; }); app.controller("FilterController", function () { this.filters = { shirtSize: 0, colors: [], priceRange: '' }; this.filterColors = ["white", "black", "grey", "pink"]; this.filterSize = ["small", "medium", "large"]; //Radio Button var rbShirtSize = document.getElementsByName("rbSize"); //Grabs element by input name //Checkboxes var chx = document.getElementsByName('cbColors'); //Price Rang var ddlPriceRange = document.getElementById('ddlPriceRange'); this.shirtSzeClick = function (sortSiz) { //var products = getVisibleProducts(); //only var products = document.getElementsByClassName('product'); // var value = this.value; var value = sortSiz; for (var x = 0; x < products.length; x++) { var shirtSizes = products[x].children[4].textContent.replace(/"/g, '').replace('[', '').replace(']', '').split(","); console.log(shirtSizes); var yes = false; //sets the value to false so that we can check if one of the values match, and make true later for (var y = 0; y < shirtSizes.length; y++) { if (shirtSizes[y] == value) { // check if 1 of the values are true console.log(value); yes = true; //if it is - then the yes is true } } if (yes == true) { // if yes is true - then the one of the values for the innerText for shirtSize is true products[x].style.display = "block"; } else { products[x].style.display = "none"; } } this.filters.shirtSize = value; } this.colorsClick = function () { var products = document.getElementsByClassName('product'); var colors = []; for (var y = 0; y < chx.length; y++) { if (chx[y].checked == true) { colors.push(chx[y].value) } } if (colors.length > 0) { for (var z = 0; z < products.length; z++) { var shirtColors = products[z].children[0].children[3].innerText.replace(/\"|\[|\]/g, '').split(','); console.log(shirtColors); var either = false; //Has to be reset for each product for (var c = 0; c < shirtColors.length; c++) { for (var v = 0; v < colors.length; v++) { if (shirtColors[c] == colors[v]) { either = true; console.log(shirtColors[c] + ' ' + colors[v]); } } } if (either == true) { // if yes is true - then the one of the values for the innerText for shirtSize is true products[z].style.display = "block"; } else { products[z].style.display = "none"; } } } else { for (var d = 0; d < products.length; d++) { products[d].style.display = "inline"; } } this.filters.colors = colors; } this.priceRangeChange = function () { if (ddlPriceRange.value != '') { var products = document.getElementsByClassName('product'); var min = parseFloat(ddlPriceRange.value.split('-')[0]); var max = parseFloat(ddlPriceRange.value.split('-')[1]); for (var i = 0; i < products.length; i++) { var price = products[i].children[2].children[0].innerText; price = parseFloat(price.substring(1, price.length)); //if the price returns '$4.99' => that value is an string array, substring start at the value after the $ so 1 if (price >= min && price <= max) { products[i].style.display = "block"; } else { products[i].style.display = "none"; } } } //else { // for (var d = 0; d < products.length; d++) { // products[d].style.display = "block"; // } //} this.filters.priceRange = ddlPriceRange.value; } }); //var shirts = [ // { // imageurl: "img/shirt.jpg", // productname: "nice shirt", // price: 8, // color: ["grey", "black"], // shirtsize: ["small", "large"], // canoverview: false, // colortab: 1, // shirtsizetab: 1, // reviews: [ // { // stars: 5, // body: "best show", // author: "<EMAIL>" // } // ] // }, // { // imageurl: "img/shirt1.jpg", // productname: "my shirt", // price: 18, // color: ["white", "pink"], // shirtsize: ["medium", "large"], // canoverview: false, // colortab: 1, // shirtsizetab: 1, // reviews: [] // }, // { // imageurl: "img/shirt3.jpg", // productname: "ice shirt", // price: 8, // color: ["pink", "black"], // shirtsize: ["large"], // canoverview: false, // colortab: 1, // shirtsizetab: 1, // reviews: [] // }, // { // imageurl: "img/shirt4.jpg", // productname: "price shirt", // price: 80, // color: ["grey", "pink"], // shirtsize: ["medium"], // canoverview: false, // colortab: 1, // shirtsizetab: 1, // reviews: [] // }, // { // imageurl: "img/shirt5.jpg", // productname: "cool shirt", // price: 120, // color: ["black"], // shirtsize: ["large"], // canoverview: false, // colortab: 1, // shirtsizetab: 1, // reviews: [] // }, // { // imageurl: "img/shirt6.jpg", // productname: "<NAME>", // price: 176, // color: ["white"], // shirtsize: ["small"], // canoverview: false, // colortab: 1, // shirtsizetab: 1, // reviews: [] // } //]; // console.log(JSON.stringify(shirts)); })(); <file_sep>/// <reference path="angular.js" /> (function () { //Factory angular.module("store").factory("Product", function ProductFactory($http) { // .factory (nameOfTable, function return { all: function () { return $http({ method: "GET", url: 'http://localhost:51737/Api/products/getall/' }); }, find: function (id) { return $http({ method: "GET", url: 'http://localhost:51737/Api/products/findbyid/' + id }); }, findByName: function(name){ return $http({ method: "Get", url: 'http://localhost:51737/Api/products/FindByName?name=' + name }); }, create: function (productInfo) { return $http({ method: "POST", url: 'http://localhost:51737/Api/products/create/', data: JSON.stringify(productInfo) }); }, findByCategoryId: function (id, categoryId){ return $http({ method: "GET", url: 'http://localhost:51737/FindByCategoryId?id=' +id + "&categoryId=" + categoryId }); }, delete: function (id) { return $http({ method: "DELETE", url: 'http://localhost:51737/Api/products/deletebyId/' + id }); }, update: function (prod, id) { return $http({ method: "PUT", url: 'http://localhost:51737/Api/products/updatebyId/' + id, data:prod }); } }; }); //Provider //angular.module("store").provider("Product", function ProductProvider() { // this.id = 1 // this.setId = function (newId) { // id = newId; // } // this.$get = function($http) { // return { // setId: function (newId) { // id = newId; // }, // all: function () { // return $http({ method: "GET", url: 'http://localhost:51737/Api/products/' }); // }, // find: function (id) { // return $http({ method: "Get", url: 'http://localhost:51737/Api/products/' + id }); // } // }; // }; //}); })();<file_sep>/// <reference path="../node_modules/angular/angular-route.js" /> /// <reference path="../node_modules/angular/angular.js" /> (function () { angular.module('store').config(function ($routeProvider) { $routeProvider.when('/filterColors', { templateUrl: '/templates/filters/productColor.html' }); //when (variable name--add the forward slash, {object}) $routeProvider.when('/filterSize', { templateUrl: '/templates/filters/productSize.html' }); $routeProvider.when('/productReview', { templateUrl: '/templates/products/productReview.html' }); $routeProvider.when('/productTemple', { templateUrl: '/templates/products/productTemplate.html' }); }); })();
312d7eb4a5396f82f9c6c8e7d8361323b7b5451a
[ "JavaScript" ]
3
JavaScript
micwhit/Angular-Ecommerce
4dbd77099e0d76c931e7c572f854573c53f98f36
39ba9532ba9cdd37d2d4b4811a8d56cf5590f3f7
refs/heads/master
<repo_name>rocketmobile/cassandra_migrations<file_sep>/README.md [![Gem Version](https://badge.fury.io/rb/cassandra_migrations.png)](http://badge.fury.io/rb/cassandra_migrations) [![Code Climate](https://codeclimate.com/github/hsgubert/cassandra_migrations.png)](https://codeclimate.com/github/hsgubert/cassandra_migrations) Cassandra Migrations ==================== **Cassandra schema management for a multi-environment development.** A gem to manage Cassandra database schema for Rails. This gem offers migrations and environment specific databases out-of-the-box for Rails users. This enables you to use Cassandra in an organized way, combined with your ActiveRecord relational database. # Requirements - Cassandra 1.2 or higher with the native_transport_protocol turned on ([Instructions to install cassandra locally](https://github.com/hsgubert/cassandra_migrations/wiki/Preparing-standalone-Cassandra-in-local-machine)) - Ruby 1.9 - Rails > 3.2 # Installation gem install cassandra_migrations # Quick start ### Configure Cassandra The native transport protocol (sometimes called binary protocol, or CQL protocol) is not on by default on all version of Cassandra. If it is not you can enable by editing the `CASSANDRA_DIR/conf/cassandra.yaml` file on all nodes in your cluster and set `start_native_transport` to `true`. You need to restart the nodes for this to have effect. ### Prepare Project In your rails root directory run: prepare_for_cassandra . Which create the `config/cassandra.yml` ### Configuring cassandra access Open the newly-created `config/cassandra.yml` and configure the database name for each of the environments, just like you would do for your regular database. The other options defaults should be enough for now. ```ruby development: hosts: ['127.0.0.1'] port: 9042 keyspace: 'my_keyspace_name' replication: class: 'SimpleStrategy' replication_factor: 1 ``` >> *SUPPORTED CONFIGURATION OPTIONS*: For a list of supported options see the docs for [Cassandra module, connect method](http://datastax.github.io/ruby-driver/api/) in the [DataStax Ruby Driver](https://github.com/datastax/ruby-driver) ### Create your database There are a collection of rake tasks to help you manage the cassandra database (`rake cassandra:create`, `rake cassandra:migrate`, `rake cassandra:drop`, etc.). For now this one does the trick: rake cassandra:reset ### Creating a C* Table rails generate cassandra_migration create_posts In your migration file, make it create a table and drop it on its way back: ```ruby class CreatePosts < CassandraMigrations::Migration def up create_table :posts do |p| p.integer :id, :primary_key => true p.timestamp :created_at p.string :title p.text :text end end def self.down drop_table :posts end end ``` And now run: rake cassandra:migrate To create a table with compound primary key just specify the primary keys on table creation, i.e.: ```ruby class CreatePosts < CassandraMigrations::Migration def up create_table :posts, :primary_keys => [:id, :created_at] do |p| p.integer :id p.timestamp :created_at p.string :title p.text :text end end def self.down drop_table :posts end end ``` To create a table with a compound partition key specify the partition keys on table creation, i.e.: ```ruby class CreatePosts < CassandraMigrations::Migration def up create_table :posts, :partition_keys => [:id, :created_month], :primary_keys => [:created_at] do |p| p.integer :id p.string :created_month p.timestamp :created_at p.string :title p.text :text end end def self.down drop_table :posts end end ``` To create a table with a secondary index you add it similar to regular rails indexes, i.e.: ```ruby class CreatePosts < CassandraMigrations::Migration def up create_table :posts, :primary_keys => [:id, :created_at] do |p| p.integer :id p.timestamp :created_at p.string :title p.text :text end create_index :posts, :title, :name => 'by_title' end def self.down drop_index 'by_title' drop_table :posts end end ``` #### Passing options to create_table The create_table method allow do pass a hash of options for: * Clustering Order (clustering_order): A string such as 'a_decimal DESC' * Compact Storage (compact_storage): Boolean, true or false * Wait before GC (gc_grace_seconds): Default: 864000 [10 days] * Others: See [CQL Table Properties](http://www.datastax.com/documentation/cql/3.1/cql/cql_reference/tabProp.html) Cassandra Migration will attempt to pass through the properties to the CREATE TABLE command. Examples: ```ruby class WithClusteringOrderMigration < CassandraMigrations::Migration def up create_table :collection_lists, options: { clustering_order: 'a_decimal DESC', compact_storage: true, gc_grace_seconds: 43200 } do |t| t.uuid :id, :primary_key => true t.decimal :a_decimal end end end ``` #### Using Alternate/Additional Keyspaces The using_keyspace method in a migration allows to execute that migration in the context of a specific keyspace: ```ruby class WithAlternateKeyspaceMigration < CassandraMigrations::Migration def up using_keyspace('alternative') do create_table :collection_lists, options: {compact_storage: true} do |t| t.uuid :id, :primary_key => true t.decimal :a_decimal end end end end ``` The overall workflow for a multiple keyspace env: - define all of your keyspaces/environment combinations as separate environments in `cassandra.yml`. You probably want to keep your main or default keyspace as just plain `development` or 'production`, especially if you're using the queries stuff (so as to confuse Rails as little as possible) - make sure to run `rake cassandra:create` for all of them - if you use `using_keyspace` in all your migrations for keyspaces defined in environments other than the standard Rails ones, you won't have to run them for each 'special' environment. > *Side Note*: If you're going to be using multiple keyspaces in one application > (specially with cql-rb), you probably want to just fully qualify your table names > in your queries rather than having to call `USE <keyspace>` all over the place. > Specially since cql-rb encourages you to only have one client object per application. There are some other helpers like `add_column` too.. take a look inside! ### Migrations for Cassandra Collections Support for C* collections is provided via the list, set and map column types. ```ruby class CollectionsListMigration < CassandraMigrations::Migration def up create_table :collection_lists do |t| t.uuid :id, :primary_key => true t.list :my_list, :type => :string t.set :my_set, :type => :float t.map :my_map, :key_type => :uuid, :value_type => :float end end end ``` ### Querying cassandra There are two ways to use the cassandra interface provided by this gem #### 1. Accessing through query helpers ```ruby # selects all posts CassandraMigrations::Cassandra.select(:posts) # more complex select query CassandraMigrations::Cassandra.select(:posts, :projection => 'title, created_at', :selection => 'id > 1234', :order_by => 'created_at DESC', :limit => 10 ) # selects single row by uuid CassandraMigrations::Cassandra.select(:posts, :projection => 'title, created_at', :selection => 'id = 6bc939c2-838e-11e3-9706-4f2824f98172', :allow_filtering => true # needed for potentially expensive queries ) # secondary options If using gem version 0.2.3+, you can also select based on secondary options listed [here](http://datastax.github.io/ruby-driver/api/session/#execute_async-instance_method). For instance, for the above query you might want your results to be paginated with 50 results on each page with a timeout of 200 seconds: CassandraMigrations::Cassandra.select(:posts, :projection => 'title, created_at', :selection => 'id > 1234', :order_by => 'created_at DESC', :limit => 10, :page_size => 50, :timeout => 200 ) All listed options in the linked page above are supported though you can also pass in any secondary options using a "secondary_options" hash as shown below: CassandraMigrations::Cassandra.select(:posts, :projection => 'title, created_at', :selection => 'id > 1234', :order_by => 'created_at DESC', :limit => 10, {:secondary_options => {:page_size => 50, {:timeout => 200}} ) # adding a new post CassandraMigrations::Cassandra.write!(:posts, { :id => 9999, :created_at => Time.current, :title => 'My new post', :text => 'lorem ipsum dolor sit amet.' }) # adding a new post with TTL CassandraMigrations::Cassandra.write!(:posts, { :id => 9999, :created_at => Time.current, :title => 'My new post', :text => 'lorem ipsum dolor sit amet.' }, :ttl => 3600 ) # updating a post CassandraMigrations::Cassandra.update!(:posts, 'id = 9999', :title => 'Updated title' ) # updating a post with TTL CassandraMigrations::Cassandra.update!(:posts, 'id = 9999', { :title => 'Updated title' }, :ttl => 3600 ) # deleting a post CassandraMigrations::Cassandra.delete!(:posts, 'id = 1234') # deleting a post title CassandraMigrations::Cassandra.delete!(:posts, 'id = 1234', :projection => 'title' ) # deleting all posts CassandraMigrations::Cassandra.truncate!(:posts) ``` #### 4. Manipulating Collections Given a migration that generates a set type column as shown next: ```ruby class CreatePeople < CassandraMigrations::Migration def up create_table :people, :primary_keys => :id do |t| t.uuid :id t.string :ssn ... t.set :emails, :type => :string end end ... end ``` You can add new emails to the existing collection: ```ruby CassandraMigrations::Cassandra.update!(:people, "ssn = '867530900'", {emails: ['<EMAIL>', '<EMAIL>']}, {operations: {emails: :+}}) ``` You can remove emails from the collection: ```ruby CassandraMigrations::Cassandra.update!(:people, "ssn = '867530900'", {emails: ['<EMAIL>']}, {operations: {emails: :-}}) ``` Or, completely replace the existing values in the collection: ```ruby CassandraMigrations::Cassandra.update!(:people, "ssn = '867530900'", {emails: ['<EMAIL>', '<EMAIL>']}) ``` The same operations (addition `:+` and subtraction `:-`) are supported by all collection types. Read more about C* collections at http://cassandra.apache.org/doc/cql3/CQL.html#collections #### 3. Using raw CQL3 ```ruby CassandraMigrations::Cassandra.execute('SELECT * FROM posts') ``` ### Reading query results Select queries will return an enumerable object over which you can iterate. All other query types return `nil`. ```ruby CassandraMigrations::Cassandra.select(:posts).each |post_attributes| puts post_attributes end # => {'id' => 9999, 'created_at' => 2013-05-20 18:43:23 -0300, 'title' => 'My new post', 'text' => 'lorem ipsum dolor sit amet.'} ``` If your want some info about the table metadata just call it on a query result: ```ruby CassandraMigrations::Cassandra.select(:posts).metadata # => {'id' => :integer, 'created_at' => :timestamp, 'title' => :varchar, 'text' => :varchar} ``` ### Using uuid data type Please refer to the wiki: [Using uuid data type](https://github.com/hsgubert/cassandra_migrations/wiki/Using-uuid-data-type) ### Deploy integration with Capistrano This gem comes with built-in compatibility with Passenger and its smart spawning functionality, so if you're using Passenger all you have to do is deploy and be happy! To add cassandra database creation and migrations steps to your Capistrano recipe, just add the following line to you deploy.rb: `require 'cassandra_migrations/capistrano'` # Acknowledgements This gem is built upon the official [Ruby Driver for Apache Cassandra](https://github.com/datastax/ruby-driver) by DataStax. Which supersedes the [cql-rb](https://github.com/iconara/cql-rb) gem (thank you Theo for doing an awesome job). <file_sep>/bin/prepare_for_cassandra #!/usr/bin/env ruby require 'optparse' require 'fileutils' require 'colorize' OptionParser.new do |opts| opts.banner = "Usage: #{File.basename($0)} [path]" opts.on("-h", "--help", "Displays this help info") do puts opts exit 0 end begin opts.parse!(ARGV) rescue OptionParser::ParseError => e warn e.message puts opts exit 1 end end if ARGV.empty? abort "Please specify the directory of a rails appilcation, e.g. `#{File.basename($0)} .'" elsif !File.directory?(ARGV.first) abort "`#{ARGV.first}' is not a directory." elsif ARGV.length > 1 abort "Too many arguments; please specify only the directory of the rails application." end rails_root = ARGV.first # create cassandra.yaml if File.exists?(File.expand_path('config/cassandra.yml', rails_root)) puts "[skip] 'config/cassandra.yml' already exists".yellow else puts "[new] creating 'config/cassandra.yml' (please update with your own configurations!)".green FileUtils.cp( File.expand_path('../template/cassandra.yml', File.dirname(__FILE__)), File.expand_path('config/cassandra.yml', rails_root) ) end # create db/cassandra_migrations if File.exists?(File.expand_path('db/cassandra_migrate', rails_root)) puts "[skip] 'db/cassandra_migrate' already exists".yellow else puts "[new] creating 'db/cassandra_migrate' directory".green FileUtils.mkdir(File.expand_path('db/cassandra_migrate', rails_root)) end puts '[done] prepared for cassandra!'.green puts '' puts 'Your steps from here are:'.green puts ' 1. configure '.green + 'config/cassandra.yml'.red puts ' 2. run '.green + 'rake cassandra:reset'.red + ' and try starting your application'.green puts ' 3. create your first migration with '.green + 'rails g cassandra_migration'.red puts ' 4. apply your migration with '.green + 'rake cassandra:migrate'.red puts ' 5. run '.green + 'rake cassandra:test:prepare'.red + ' and start testing'.green puts ' 6. have lots of fun!'.green.blink <file_sep>/lib/cassandra_migrations/cassandra/keyspace_operations.rb # encoding: utf-8 require 'cassandra' module CassandraMigrations module Cassandra module KeyspaceOperations def create_keyspace!(env) config = Config.configurations[env] begin execute( "CREATE KEYSPACE #{config.keyspace} \ WITH replication = { \ 'class':'#{config.replication['class']}', \ 'replication_factor': #{config.replication['replication_factor']} \ }" ) use(config.keyspace) rescue Exception => exception drop_keyspace!(env) raise exception end end def drop_keyspace!(env) config = Config.configurations[env] begin execute("DROP KEYSPACE #{config.keyspace}") rescue ::Cassandra::Errors::ConfigurationError raise Errors::UnexistingKeyspaceError, config.keyspace end end end end end
c51d9e54a584e2a3a3990bebac7a7731ab1675e0
[ "Markdown", "Ruby" ]
3
Markdown
rocketmobile/cassandra_migrations
c4ff2f97e95debb65e093cfa1e8a244f5c427b5d
ae1efcfa82d072b2ea8055c43a429c73240253a6
refs/heads/master
<file_sep>#!/usr/bin/env ruby def is_prime(n) # anything over n/2 won't divide into n half_n = n / 2 (2..half_n).each do |d| if(n % d == 0) return false end end return true end def get_nth_prime(n) primes = [2] i = 3 while (primes.count < n) primes.push(i) if (is_prime(i)) # Count by two to skip checking evens i += 2 end primes.pop end n = 10001 print "The #" + n.to_s + " prime is " + get_nth_prime(n).to_s <file_sep>#!/usr/bin/env ruby def decipher_file(encoded_file) words = Hash.new print "Loading dictionary..." File.new("words").each().each do |line| words[line.chop] = nil end puts "done!" text = File.new(encoded_file).read() tokens = text.split(",") decoded_message = "" ("aaa".."zzz").each do |key| decoded_message = "" i = 0 tokens.each do |token| decoded_token = key[i].ord ^ token.to_i decoded_message += decoded_token.chr i = (i + 1) % key.length() end if (is_english(decoded_message, words, 90)) return decoded_message end end return nil end def is_english(text, english_dictionary, threshold) n_words = 0 n_english_words = 0 # Strip anything that's not a letter text = text.downcase.gsub(/[^a-z'\s]/i, '') text.split(" ").each do |token| n_words += 1 if (english_dictionary.has_key?(token)) n_english_words += 1 end end percent_english = 100 * n_english_words / n_words.to_f if (percent_english > threshold) return true end return false end def sum_string(text) sum = 0 text.each_char do |c| sum += c.ord end return sum end file_name = ARGV[0] if (file_name.nil?) abort "Usage: #{$0} FILENAME" elsif (!File.exist?(file_name)) abort "#{file_name} does not exist" end start_time = Time.now decoded_message = decipher_file(file_name) decoded_message_sum = sum_string(decoded_message) end_time = Time.now puts "Decoded message: #{decoded_message}" puts "Decoded message sum: #{decoded_message_sum}" puts "Elapsed time: #{end_time - start_time} s" <file_sep>#!/usr/bin/env ruby # Gets the sum of all multiples up to a given limit of numbers in a given array # * *Args* : # - +numbers+ -> # - +limit+ -> # * *Returns* : # - The sum of all multiples of the numbers of the given array def sum_multiples(numbers, limit) sum = 0 (numbers[0]..limit-1).each { |potential_multiple| i = 0 has_been_counted = false while (i < numbers.length && !has_been_counted) do if (potential_multiple % numbers[i] == 0) has_been_counted = true sum += potential_multiple end i += 1 end } return sum end numbers = [3, 5] limit = 1000 print "Sum of all multiples of " + numbers.join(", ") + " below " + limit.to_s + " is " + sum_multiples(numbers, limit).to_s + "\n" <file_sep>#!/usr/bin/env ruby sum = 0 sum_of_squares = 0 (1..100).each do |n| sum += n sum_of_squares += n * n end square_of_sum = sum * sum diff = square_of_sum - sum_of_squares print diff <file_sep>#!/usr/bin/env ruby # Gets the total number of routes on an n by n grid from the top left corner to # the bottom right corner by being only able to make right or downward moves. # * *Args* : # - +n+ -> Dimension of the grid in number of squares # * *Returns* : # - The total number of routes def count_routes(n) return 0 end n = ARGV[0] if (n.nil?) abort "Usage: #{$0} INTEGER" elsif (false if (Integer(n)) rescue true) abort "#{n} is not an Integer" end n = n.to_i puts "The total number of routes on an #{n} by #{n} grid: #{count_routes(n)}" <file_sep>#!/usr/bin/env ruby def sum_even_fibonacci(limit) last = 1 fib = 2 sum = 0 while (fib < limit) do print "fib: " + fib.to_s + "\n" if ( fib % 2 == 0 ) sum += fib end temp = fib fib += last last = temp end return sum end limit = 4000000 print "Sum of even Fibonacci sequence values less than " + limit.to_s + ": " + sum_even_fibonacci(limit).to_s <file_sep>#!/usr/bin/env ruby # Gets the sum of all the digits in the result of n! # * *Args* : # - +n+ -> # * *Returns* : # - The sum of all the digits in the result of n! def sum_factorial_digits(n) n_factorial = factorial(n) sum = 0 while (n_factorial > 0) do sum += n_factorial % 10 n_factorial /= 10 end return sum end def factorial(n) if (n <= 1) return 1 else return factorial(n - 1) * n end end n = ARGV[0] if (n.nil?) abort "Usage: #{$0} INTEGER\n" elsif (false if (Integer(n)) rescue true) abort "#{n} is not an Integer\n" end n = n.to_i print "Sum of digits in #{n}!: #{sum_factorial_digits(n)}\n" <file_sep>#!/usr/bin/env ruby # Gets the smallest common multiple of all numbers from 1 up to n # * *Args* : # - +n+ -> # * *Returns* : # - The smallest common multiple of all numbers from 1 up to n def smallest_common_multiple(n) return 0 end n = ARGV[0] if (n.nil?) abort "Usage: #{$0} INTEGER\n" elsif (false if (Integer(n)) rescue true) abort "#{n} is not an Integer\n" end n = n.to_i print "Smallest common multiple of all numbers from 1 to #{n}: " + \ "#{smallest_common_multiple(n)}\n" <file_sep>#!/usr/bin/env ruby # Gets the sum of all primes less than a given number # * *Args* : # - +n+ -> # * *Returns* : # - The sum of all primes less than n def is_prime(n) if ( n <= 1 ) return false end (2..(Math.sqrt(n).floor)).each do |divisor| if ( n % divisor == 0 ) return false end end return true end def sum_of_primes(n) sum = 0 (1..n).each do |x| sum += x if (is_prime(x)) print "x=#{x}, sum=#{sum}\n" if (x % 100000 == 0) end return sum end n = ARGV[0] if (n.nil?) abort "Usage: #{$0} INTEGER\n" elsif (false if (Integer(n)) rescue true) abort "#{n} is not an Integer\n" end n = n.to_i start_time = Time.now sum = sum_of_primes(n) end_time = Time.now print "Sum of all primes less than #{n}: #{sum}\nElapsed time: " + \ "#{end_time - start_time} s" <file_sep>#!/usr/bin/env ruby def is_palindrome(n) n_array = [] while (n > 0) do #print "n=#{n}\n" n_array.push(n % 10) n /= 10 end i = 0 until (i >= (n_array.count - i)) do #print "i=#{i}, -i=#{-i}\n" if (n_array[i] != n_array[-i - 1]) return false end i += 1 end return true end def get_largest_palindrome_product(digits) max = 10 ** digits - 1 min = 10 ** (digits - 1) palindrome_products = [] max.downto(min) do |n| n.downto(min).each do |m| product = n * m palindrome_products.push(product) if (is_palindrome(product)) end end if (palindrome_products.count <= 0) then return -1 else return palindrome_products.sort.pop end end n_digits = 3 largest_palindrome_product = get_largest_palindrome_product(n_digits) if (largest_palindrome_product >= 0) then print "Largest palindrome product for " + n_digits.to_s + " digit multiples" + " is " + largest_palindrome_product.to_s else # We should never get here print "Could not find a palindrome product for " + n_digits.to_s + " digit " + "multipliers!" end <file_sep>#!/usr/bin/env ruby def is_prime(n) if ( n <= 2 ) return true end (2..(n/2)).each do |divisor| if ( n % divisor == 0 ) return false end end return true end def largest_prime_factor(n) # Check if n itself is prime return n if (is_prime(n)) lower_factors = [] upper_factors = [] # Iterate over the lower factors and calculate their partner factor Math.sqrt(n).floor.downto(1).each do |lower_factor| if (n % lower_factor == 0) # Keep both arrays in descending order lower_factors << lower_factor upper_factors.insert(0, n / lower_factor) end end (upper_factors + lower_factors).each do |factor| return factor if (is_prime(factor)) end return 1 end n = ARGV[0] if (n.nil?) abort "Usage: largest_prime_factor INTEGER\n" elsif (false if (Integer(n)) rescue true) abort "#{n} is not an Integer\n" end n = n.to_i print "The largest prime factor of #{n} is #{largest_prime_factor(n)}" <file_sep>#!/usr/bin/env ruby def last_ten_digits_of_self_power(n) product = 1 (1..n).each do product = product * n if (product > 10000000000) product = product % 10000000000 end end return product end def last_ten_digits_of_series(n) sum = 0 (1..n).each do |x| sum += self_power(x) end sum = sum % 10000000000 return sum end n = 1000 start_time = Time.now result = last_ten_digits_of_series(n) end_time = Time.now print "Last ten digits of series up to #{n}: #{result}\nElapsed time: " + \ "#{end_time - start_time} s\n"
1d8940d3169a8a2640e70ea374f260161b723785
[ "Ruby" ]
12
Ruby
tomwatts/project_euler
10751783aca006b7ca37cb85640b14e7b8143d50
47d7aeac724df1ab02b75a6f31b254213ed7eed5
refs/heads/master
<repo_name>EwaldJa/polymovies-client<file_sep>/README.md # Client VueJS Poly'Movies ### <NAME> & <NAME> - WebServices 2020/2021 Ce repository est un client [VueJS](https://vuejs.org) réalisé dans le cadre de notre cours de WebServices à Polytech Lyon. Ce client est utilisé pour consommer les données d'une base de données de films, d'acteurs, de personnages, et de réalisateurs, mises à disposition à l'aide d'un webserver Spring Boot disponible sur [ce repository](https://github.com/felixMartelin/WebService) Trois vues principales servent à afficher les trois principaux types de données (films, acteurs et personnages), et deux autres vues secondaires sont utilisées pour modifier/ajouter des données. Nous avons utilisé et adapté un composant de tableau disponible en ligne, de même pour un formulaire. Ce serveur peut être installé avec la commande `npm install`, à effectuer dans le dossier dans lequel se situe le projet. Il pourra ensuite être lancé APRES le webserver avec `npm run serve`. Le client sera ainsi accessible à [cette adresse](http://localhost:8081/). <file_sep>/src/main.js import Vue from 'vue' import App from './Cinema.vue' import "vue-good-table/dist/vue-good-table.css"; import VueGoodTable from 'vue-good-table' import VueRouter from 'vue-router' import Films from './components/Films.vue' import Acteurs from './components/Acteurs.vue' import Roles from './components/Roles.vue' import AjoutRole from './components/AjoutRole.vue' import ModifierRole from './components/ModifierRole.vue' Vue.use(VueRouter) Vue.config.productionTip = false Vue.use(VueGoodTable) const routes = [ { path: '/films', name: "films", component: Films }, { path: '/ajoutRole/:idActor',name :"ajoutRole" , component: AjoutRole}, { path: '/modifierRole',name :"modifierRole" , component: ModifierRole}, { path: '/roles', name :"roles" , component: Roles}, { path: '/acteurs', name: "acteurs", component: Acteurs} ] const router = new VueRouter({ routes }) new Vue({ router, render: h => h(App), }).$mount('#app')
aa898246ba086521ba44057a2200a1af37f95ff0
[ "Markdown", "JavaScript" ]
2
Markdown
EwaldJa/polymovies-client
3168428be5cab1f416357b3e8d8000b69d15eb02
16598094175c5ab9e1d2930a2f8b229867ae6502
refs/heads/master
<repo_name>panzi/mathfun<file_sep>/src/mathfun.c #include <string.h> #include <errno.h> #include <stdlib.h> #include <ctype.h> #include <assert.h> #include "mathfun_intern.h" bool mathfun_context_init(mathfun_context *ctx, bool define_default, mathfun_error_p *error) { ctx->decl_capacity = 256; ctx->decl_used = 0; ctx->decls = calloc(ctx->decl_capacity, sizeof(mathfun_decl)); if (!ctx->decls) { ctx->decl_capacity = 0; mathfun_raise_error(error, MATHFUN_OUT_OF_MEMORY); return false; } if (define_default) { return mathfun_context_define_default(ctx, error); } return true; } void mathfun_context_cleanup(mathfun_context *ctx) { free(ctx->decls); ctx->decls = NULL; ctx->decl_capacity = 0; ctx->decl_used = 0; } bool mathfun_context_ensure(mathfun_context *ctx, size_t n, mathfun_error_p *error) { size_t size = ctx->decl_capacity + n; size_t rem = size % 256; if (rem) size += 256 - rem; mathfun_decl *decls = realloc(ctx->decls, size * sizeof(mathfun_decl)); if (!decls) { mathfun_raise_error(error, MATHFUN_OUT_OF_MEMORY); return false; } ctx->decls = decls; ctx->decl_capacity = size; return true; } // first string is NUL terminated, second string has a defined length static int strn2cmp(const char *s1, const char *s2, size_t n2) { const char *s2end = s2 + n2; for (; *s1 == (s2 == s2end ? 0 : *s2); ++ s1, ++ s2) { if (*s1 == 0) { return 0; } } return (*(const unsigned char *)s1 < (s2 == s2end ? 0 : *(const unsigned char *)s2)) ? -1 : +1; } static bool mathfun_context_find(const mathfun_context *ctx, const char *name, size_t n, size_t *index) { // binary search // exclusive range: [lower, upper) size_t lower = 0; size_t upper = ctx->decl_used; const mathfun_decl *decls = ctx->decls; while (lower < upper) { const size_t mid = lower + (upper - lower) / 2; const mathfun_decl *decl = decls + mid; int cmp = strn2cmp(decl->name, name, n); if (cmp < 0) { lower = mid + 1; } else if (cmp > 0) { upper = mid; } else { *index = mid; return true; } } *index = lower; return false; } const mathfun_decl *mathfun_context_get(const mathfun_context *ctx, const char *name) { size_t index = 0; if (mathfun_context_find(ctx, name, strlen(name), &index)) { return ctx->decls + index; } return NULL; } const mathfun_decl *mathfun_context_getn(const mathfun_context *ctx, const char *name, size_t n) { size_t index = 0; if (mathfun_context_find(ctx, name, n, &index)) { return ctx->decls + index; } return NULL; } const char *mathfun_context_funct_name(const mathfun_context *ctx, mathfun_binding_funct funct) { for (size_t i = 0; i < ctx->decl_used; ++ i) { const mathfun_decl *decl = &ctx->decls[i]; if (decl->type == MATHFUN_DECL_FUNCT && decl->decl.funct.funct == funct) { return decl->name; } } return NULL; } bool mathfun_valid_name(const char *name) { const char *ptr = name; if (!isalpha(*ptr) && *ptr != '_') { return false; } ++ ptr; while (*ptr) { if (!isalnum(*ptr) && *ptr != '_') { return false; } ++ ptr; } return strcasecmp(name, "inf") != 0 && strcasecmp(name, "nan") != 0 && strcasecmp(name, "true") != 0 && strcasecmp(name, "false") != 0 && strcasecmp(name, "in") != 0; } bool mathfun_validate_argnames(const char *argnames[], size_t argc, mathfun_error_p *error) { for (size_t i = 0; i < argc; ++ i) { const char *argname = argnames[i]; if (!mathfun_valid_name(argname)) { mathfun_raise_name_error(error, MATHFUN_ILLEGAL_NAME, argname); return false; } for (size_t j = 0; j < i; ++ j) { if (strcmp(argname, argnames[j]) == 0) { mathfun_raise_name_error(error, MATHFUN_DUPLICATE_ARGUMENT, argname); return false; } } } return true; } static int mathfun_decl_cmp(const void *a, const void *b) { return strcmp(((const mathfun_decl*)a)->name, ((const mathfun_decl*)b)->name); } bool mathfun_context_define(mathfun_context *ctx, const mathfun_decl decls[], mathfun_error_p *error) { size_t new_count = 0; const mathfun_decl *ptr = decls; while (ptr->name) { if (mathfun_context_get(ctx, ptr->name)) { mathfun_raise_name_error(error, MATHFUN_NAME_EXISTS, ptr->name); return false; } ++ ptr; ++ new_count; } size_t old_count = ctx->decl_used; size_t size = old_count + new_count; size_t rem = size % 256; if (rem) size += 256 - rem; mathfun_decl *merged = calloc(size, sizeof(mathfun_decl)); if (!merged) { mathfun_raise_error(error, MATHFUN_OUT_OF_MEMORY); return false; } mathfun_decl *old_decls = ctx->decls; mathfun_decl *new_decls = merged + old_count; // copy new list to new buffer where I can sort it memcpy(new_decls, decls, new_count * sizeof(mathfun_decl)); qsort(new_decls, new_count, sizeof(mathfun_decl), mathfun_decl_cmp); // merge old and new lists size_t i = 0, j = 0, index = 0; while (i < old_count && j < new_count) { int cmp = strcmp(old_decls[i].name, new_decls[j].name); if (cmp < 0) { merged[index] = old_decls[i ++]; } else if (cmp > 0) { merged[index] = new_decls[j ++]; } else { mathfun_raise_name_error(error, MATHFUN_NAME_EXISTS, old_decls[i].name); free(merged); return false; } if (index > 0 && strcmp(merged[index].name, merged[index - 1].name) == 0) { mathfun_raise_name_error(error, MATHFUN_NAME_EXISTS, merged[index].name); free(merged); return false; } ++ index; } // add rest of old list while (i < old_count) { merged[index] = old_decls[i]; if (index > 0 && strcmp(merged[index].name, merged[index - 1].name) == 0) { mathfun_raise_name_error(error, MATHFUN_NAME_EXISTS, merged[index].name); free(merged); return false; } ++ i; ++ index; } // new list should be in place, just validate uniquness of names assert(merged + index == new_decls + j); while (j < new_count) { if (index > 0 && strcmp(merged[index].name, merged[index - 1].name) == 0) { mathfun_raise_name_error(error, MATHFUN_NAME_EXISTS, merged[index].name); free(merged); return false; } ++ j; ++ index; } // use merged lists free(ctx->decls); ctx->decls = merged; ctx->decl_used = old_count + new_count; ctx->decl_capacity = size; return true; } bool mathfun_context_define_const(mathfun_context *ctx, const char *name, double value, mathfun_error_p *error) { if (!mathfun_valid_name(name)) { mathfun_raise_name_error(error, MATHFUN_ILLEGAL_NAME, name); return false; } size_t index = 0; if (mathfun_context_find(ctx, name, strlen(name), &index)) { mathfun_raise_name_error(error, MATHFUN_NAME_EXISTS, name); return false; } if (ctx->decl_used == ctx->decl_capacity && !mathfun_context_ensure(ctx, 1, error)) { return false; } memmove(ctx->decls + index + 1, ctx->decls + index, (ctx->decl_used - index) * sizeof(mathfun_decl)); mathfun_decl *decl = ctx->decls + index; decl->type = MATHFUN_DECL_CONST; decl->name = name; decl->decl.value = value; ++ ctx->decl_used; return true; } bool mathfun_context_define_funct(mathfun_context *ctx, const char *name, mathfun_binding_funct funct, const mathfun_sig *sig, mathfun_error_p *error) { if (!mathfun_valid_name(name)) { mathfun_raise_name_error(error, MATHFUN_ILLEGAL_NAME, name); return false; } if (sig->argc > MATHFUN_REGS_MAX) { mathfun_raise_error(error, MATHFUN_TOO_MANY_ARGUMENTS); return false; } size_t index = 0; if (mathfun_context_find(ctx, name, strlen(name), &index)) { mathfun_raise_name_error(error, MATHFUN_NAME_EXISTS, name); return false; } if (ctx->decl_used == ctx->decl_capacity && !mathfun_context_ensure(ctx, 1, error)) { return false; } memmove(ctx->decls + index + 1, ctx->decls + index, (ctx->decl_used - index) * sizeof(mathfun_decl)); mathfun_decl *decl = ctx->decls + index; decl->type = MATHFUN_DECL_FUNCT; decl->name = name; decl->decl.funct.funct = funct; decl->decl.funct.sig = sig; ++ ctx->decl_used; return true; } bool mathfun_context_undefine(mathfun_context *ctx, const char *name, mathfun_error_p *error) { size_t index = 0; if (!mathfun_context_find(ctx, name, strlen(name), &index)) { mathfun_raise_name_error(error, MATHFUN_NO_SUCH_NAME, name); return false; } memmove(ctx->decls + index, ctx->decls + index + 1, (ctx->decl_used - index - 1) * sizeof(mathfun_decl)); -- ctx->decl_used; return true; } void mathfun_cleanup(mathfun *fun) { free(fun->code); fun->code = NULL; fun->argc = 0; fun->framesize = 0; } double mathfun_call(const mathfun *fun, mathfun_error_p *error, ...) { va_list ap; va_start(ap, error); double value = mathfun_vcall(fun, ap, error); va_end(ap); return value; } double mathfun_acall(const mathfun *fun, const double args[], mathfun_error_p *error) { mathfun_value *regs = calloc(fun->framesize, sizeof(mathfun_value)); if (!regs) { mathfun_raise_error(error, MATHFUN_OUT_OF_MEMORY); return NAN; } for (size_t i = 0; i < fun->argc; ++ i) { regs[i].number = args[i]; } errno = 0; double value = mathfun_exec(fun, regs); free(regs); if (errno != 0) { mathfun_raise_c_error(error); } return value; } double mathfun_vcall(const mathfun *fun, va_list ap, mathfun_error_p *error) { mathfun_value *regs = calloc(fun->framesize, sizeof(mathfun_value)); if (!regs) { mathfun_raise_error(error, MATHFUN_OUT_OF_MEMORY); return NAN; } for (size_t i = 0; i < fun->argc; ++ i) { regs[i].number = va_arg(ap, double); } errno = 0; double value = mathfun_exec(fun, regs); free(regs); if (errno != 0) { mathfun_raise_c_error(error); } return value; } double mathfun_run(const char *code, mathfun_error_p *error, ...) { va_list ap; va_start(ap, error); size_t argc = 0; while (va_arg(ap, const char *)) { va_arg(ap, double); ++ argc; } va_end(ap); const char **argnames = NULL; double *args = NULL; if (argc > 0) { argnames = calloc(argc, sizeof(char*)); if (!argnames) { mathfun_raise_error(error, MATHFUN_OUT_OF_MEMORY); return NAN; } args = calloc(argc, sizeof(double)); if (!args) { mathfun_raise_error(error, MATHFUN_OUT_OF_MEMORY); free(argnames); return NAN; } } va_start(ap, error); for (size_t i = 0; i < argc; ++ i) { argnames[i] = va_arg(ap, const char *); args[i] = va_arg(ap, double); } va_end(ap); double value = mathfun_arun(argnames, argc, code, args, error); free(args); free(argnames); return value; } double mathfun_arun(const char *argnames[], size_t argc, const char *code, const double args[], mathfun_error_p *error) { mathfun_context ctx; if (!mathfun_validate_argnames(argnames, argc, error)) return NAN; if (!mathfun_context_init(&ctx, true, error)) return NAN; mathfun_expr *expr = mathfun_context_parse(&ctx, argnames, argc, code, error); if (!expr) { mathfun_context_cleanup(&ctx); return NAN; } // it's only executed once, so any optimizations and byte code // compilations would only add overhead errno = 0; double value = mathfun_expr_exec(expr, args).number; if (errno != 0) { mathfun_raise_c_error(error); mathfun_expr_free(expr); mathfun_context_cleanup(&ctx); return NAN; } mathfun_expr_free(expr); mathfun_context_cleanup(&ctx); return value; } bool mathfun_context_compile(const mathfun_context *ctx, const char *argnames[], size_t argc, const char *code, mathfun *fun, mathfun_error_p *error) { if (!mathfun_validate_argnames(argnames, argc, error)) return false; mathfun_expr *expr = mathfun_context_parse(ctx, argnames, argc, code, error); memset(fun, 0, sizeof(struct mathfun)); if (!expr) return false; mathfun_expr *opt = mathfun_expr_optimize(expr, error); if (!opt) { // expr is freed by mathfun_expr_optimize on error return false; } fun->argc = argc; bool ok = mathfun_expr_codegen(opt, fun, error); // mathfun_expr_optimize reuses expr and frees discarded things, // so only opt has to be freed: mathfun_expr_free(opt); return ok; } bool mathfun_compile(mathfun *fun, const char *argnames[], size_t argc, const char *code, mathfun_error_p *error) { mathfun_context ctx; memset(fun, 0, sizeof(struct mathfun)); if (!mathfun_context_init(&ctx, true, error)) return false; bool ok = mathfun_context_compile(&ctx, argnames, argc, code, fun, error); mathfun_context_cleanup(&ctx); return ok; } mathfun_expr *mathfun_expr_alloc(enum mathfun_expr_type type, mathfun_error_p *error) { mathfun_expr *expr = calloc(1, sizeof(mathfun_expr)); if (!expr) { mathfun_raise_error(error, MATHFUN_OUT_OF_MEMORY); return NULL; } expr->type = type; return expr; } void mathfun_expr_free(mathfun_expr *expr) { if (!expr) return; switch (expr->type) { case EX_CONST: case EX_ARG: break; case EX_CALL: if (expr->ex.funct.args) { const size_t argc = expr->ex.funct.sig->argc; for (size_t i = 0; i < argc; ++ i) { mathfun_expr_free(expr->ex.funct.args[i]); } free(expr->ex.funct.args); expr->ex.funct.args = NULL; } break; case EX_NEG: case EX_NOT: mathfun_expr_free(expr->ex.unary.expr); expr->ex.unary.expr = NULL; break; case EX_ADD: case EX_SUB: case EX_MUL: case EX_DIV: case EX_MOD: case EX_POW: case EX_EQ: case EX_NE: case EX_LT: case EX_GT: case EX_LE: case EX_GE: case EX_BEQ: case EX_BNE: case EX_AND: case EX_OR: case EX_IN: case EX_RNG_INCL: case EX_RNG_EXCL: mathfun_expr_free(expr->ex.binary.left); mathfun_expr_free(expr->ex.binary.right); expr->ex.binary.left = NULL; expr->ex.binary.right = NULL; break; case EX_IIF: mathfun_expr_free(expr->ex.iif.cond); mathfun_expr_free(expr->ex.iif.then_expr); mathfun_expr_free(expr->ex.iif.else_expr); expr->ex.iif.cond = NULL; expr->ex.iif.then_expr = NULL; expr->ex.iif.else_expr = NULL; break; } free(expr); } mathfun_type mathfun_expr_type(const mathfun_expr *expr) { switch (expr->type) { case EX_CONST: return expr->ex.value.type; case EX_CALL: return expr->ex.funct.sig->rettype; case EX_IIF: return mathfun_expr_type(expr->ex.iif.then_expr); case EX_ARG: case EX_NEG: case EX_ADD: case EX_SUB: case EX_MUL: case EX_DIV: case EX_MOD: case EX_POW: return MATHFUN_NUMBER; case EX_NOT: case EX_EQ: case EX_NE: case EX_LT: case EX_GT: case EX_LE: case EX_GE: case EX_BEQ: case EX_BNE: case EX_AND: case EX_OR: case EX_IN: return MATHFUN_BOOLEAN; case EX_RNG_INCL: case EX_RNG_EXCL: return -1; default: assert(false); return -1; } } const char *mathfun_type_name(mathfun_type type) { switch (type) { case MATHFUN_NUMBER: return "number"; case MATHFUN_BOOLEAN: return "boolean"; default: fprintf(stderr, "illegal type: %d\n", type); return NULL; } } double mathfun_mod(double x, double y) { if (y == 0.0) { errno = EDOM; return NAN; } double mod = fmod(x, y); if (mod) { if ((y < 0.0) != (mod < 0.0)) { mod += y; } } else { mod = copysign(0.0, y); } return mod; } <file_sep>/src/mathfun_intern.h #ifndef MATHFUN_INTERN_H__ #define MATHFUN_INTERN_H__ // This is an internal header so there might be no MATHFUN_/mathfun_ prefixes. #include "mathfun.h" #include <stdbool.h> #include <stdlib.h> #include <inttypes.h> #include <stdarg.h> #ifdef __cplusplus extern "C" { #endif // assumtions: // sizeof(x) == 2 ** n and sizeof(x) == __alignof__(x) // for x in {mathfun_value, mathfun_binding_funct} #define MATHFUN_REGS_MAX UINTPTR_MAX #define MATHFUN_FUNCT_CODES (1 + ((sizeof(mathfun_binding_funct) - 1) / sizeof(mathfun_code))) #define MATHFUN_VALUE_CODES (1 + ((sizeof(mathfun_value) - 1) / sizeof(mathfun_code))) #ifndef M_TAU # define M_TAU (2*M_PI) #endif #ifndef __GNUC__ # define __attribute__(X) #endif #if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__CYGWIN__) # if defined(_WIN64) # define PRIzu PRIu64 # define PRIzx PRIx64 # elif defined(_WIN32) # define PRIzu PRIu32 # define PRIzx PRIx32 # elif defined(_WIN16) # define PRIzu PRIu16 # define PRIzx PRIx16 # endif #else # define PRIzu "zu" # define PRIzx "zx" #endif typedef uintptr_t mathfun_code; typedef struct mathfun_expr mathfun_expr; typedef struct mathfun_error mathfun_error; typedef struct mathfun_parser mathfun_parser; typedef struct mathfun_codegen mathfun_codegen; enum mathfun_expr_type { EX_CONST, EX_ARG, EX_CALL, EX_NEG, EX_ADD, EX_SUB, EX_MUL, EX_DIV, EX_MOD, EX_POW, EX_NOT, EX_EQ, EX_NE, EX_LT, EX_GT, EX_LE, EX_GE, EX_IN, EX_RNG_INCL, EX_RNG_EXCL, EX_BEQ, EX_BNE, EX_AND, EX_OR, EX_IIF }; struct mathfun_expr { enum mathfun_expr_type type; union { struct { mathfun_type type; mathfun_value value; } value; mathfun_code arg; struct { mathfun_binding_funct funct; const mathfun_sig *sig; mathfun_expr **args; } funct; struct { mathfun_expr *expr; } unary; struct { mathfun_expr *left; mathfun_expr *right; } binary; struct { mathfun_expr *cond; mathfun_expr *then_expr; mathfun_expr *else_expr; } iif; } ex; }; enum mathfun_bytecode { // arguments description NOP = 0, // do nothing. used to align VAL and CALL RET = 1, // reg return MOV = 2, // reg, reg copy value VAL = 3, // val, reg load an immediate value CALL = 4, // ptr, reg, reg call a function. parameters: // * C function pointer // * register of first argument // * register for the return value NEG = 5, // reg, reg negate ADD = 6, // reg, reg, reg add SUB = 7, // reg, reg, reg substract MUL = 8, // reg, reg, reg multiply DIV = 9, // reg, reg, reg divide MOD = 10, // reg, reg, reg modulo division POW = 11, // reg, reg, reg power NOT = 12, // reg, reg logically negate EQ = 13, // reg, reg, reg equals NE = 14, // reg, reg, reg not equals LT = 15, // reg, reg, reg lower than GT = 16, // reg, reg, reg greater than LE = 17, // reg, reg, reg lower or equal than GE = 18, // reg, reg, reg greater or equal than BEQ = 19, // reg, reg, reg boolean equals BNE = 20, // reg, reg, reg boolean not equals JMP = 21, // adr jumo to adr JMPT = 22, // reg, adr jump to adr if reg contains true JMPF = 23, // reg, adr jump to adr if reg contains false SETT = 24, // reg set reg to true SETF = 25, // reg set reg to false END = 26 // pseudo instruction. marks end of code. }; struct mathfun_error { enum mathfun_error_type type; int errnum; size_t lineno; size_t column; const char *str; const char *errpos; size_t errlen; union { struct { size_t got; size_t expected; } argc; struct { mathfun_type got; mathfun_type expected; } type; } err; }; struct mathfun_parser { const struct mathfun_context *ctx; const char **argnames; size_t argc; const char *code; const char *ptr; mathfun_error_p *error; }; struct mathfun_codegen { size_t argc; size_t maxstack; size_t currstack; size_t code_size; size_t code_used; mathfun_code *code; mathfun_error_p *error; }; MATHFUN_LOCAL bool mathfun_context_ensure(mathfun_context *ctx, size_t n, mathfun_error_p *error); MATHFUN_LOCAL const mathfun_decl *mathfun_context_getn(const mathfun_context *ctx, const char *name, size_t n); MATHFUN_LOCAL mathfun_expr *mathfun_context_parse(const mathfun_context *ctx, const char *argnames[], size_t argc, const char *code, mathfun_error_p *error); MATHFUN_LOCAL bool mathfun_expr_codegen(mathfun_expr *expr, mathfun *mathfun, mathfun_error_p *error); MATHFUN_LOCAL bool mathfun_codegen_expr(mathfun_codegen *codegen, mathfun_expr *expr, mathfun_code *ret); MATHFUN_LOCAL bool mathfun_codegen_val(mathfun_codegen *codegen, mathfun_value value, mathfun_code target); MATHFUN_LOCAL bool mathfun_codegen_call(mathfun_codegen *codegen, mathfun_binding_funct funct, mathfun_code firstarg, mathfun_code target); MATHFUN_LOCAL bool mathfun_codegen_ins0(mathfun_codegen *codegen, enum mathfun_bytecode code); MATHFUN_LOCAL bool mathfun_codegen_ins1(mathfun_codegen *codegen, enum mathfun_bytecode code, mathfun_code arg1); MATHFUN_LOCAL bool mathfun_codegen_ins2(mathfun_codegen *codegen, enum mathfun_bytecode code, mathfun_code arg1, mathfun_code arg2); MATHFUN_LOCAL bool mathfun_codegen_ins3(mathfun_codegen *codegen, enum mathfun_bytecode code, mathfun_code arg1, mathfun_code arg2, mathfun_code arg3); MATHFUN_LOCAL bool mathfun_codegen_binary(mathfun_codegen *codegen, mathfun_expr *expr, enum mathfun_bytecode code, mathfun_code *ret); MATHFUN_LOCAL bool mathfun_codegen_unary(mathfun_codegen *codegen, mathfun_expr *expr, enum mathfun_bytecode code, mathfun_code *ret); MATHFUN_LOCAL mathfun_expr *mathfun_expr_alloc(enum mathfun_expr_type type, mathfun_error_p *error); MATHFUN_LOCAL void mathfun_expr_free(mathfun_expr *expr); MATHFUN_LOCAL mathfun_expr *mathfun_expr_optimize(mathfun_expr *expr, mathfun_error_p *error); MATHFUN_LOCAL mathfun_type mathfun_expr_type(const mathfun_expr *expr); MATHFUN_LOCAL mathfun_value mathfun_expr_exec(const mathfun_expr *expr, const double args[]); MATHFUN_LOCAL const char *mathfun_find_identifier_end(const char *str); MATHFUN_LOCAL mathfun_error *mathfun_error_alloc(enum mathfun_error_type type); MATHFUN_LOCAL void mathfun_raise_error(mathfun_error_p *error, enum mathfun_error_type type); MATHFUN_LOCAL void mathfun_raise_name_error(mathfun_error_p *error, enum mathfun_error_type type, const char *name); MATHFUN_LOCAL void mathfun_raise_math_error(mathfun_error_p *error, int errnum); MATHFUN_LOCAL void mathfun_raise_c_error(mathfun_error_p *error); MATHFUN_LOCAL void mathfun_raise_parser_error(const mathfun_parser *parser, enum mathfun_error_type type, const char *errpos); MATHFUN_LOCAL void mathfun_raise_parser_argc_error(const mathfun_parser *parser, const char *errpos, size_t expected, size_t got); MATHFUN_LOCAL void mathfun_raise_parser_type_error(const mathfun_parser *parser, const char *errpos, mathfun_type expected, mathfun_type got); MATHFUN_LOCAL bool mathfun_validate_argnames(const char *argnames[], size_t argc, mathfun_error_p *error); MATHFUN_LOCAL const char *mathfun_type_name(mathfun_type type); #ifdef __cplusplus } #endif #endif <file_sep>/src/exec.c #include <errno.h> #include "mathfun_intern.h" // tree interpreter, for one time execution and debugging mathfun_value mathfun_expr_exec(const mathfun_expr *expr, const double args[]) { switch (expr->type) { case EX_CONST: return expr->ex.value.value; case EX_ARG: return (mathfun_value){ .number = args[expr->ex.arg] }; case EX_CALL: { const size_t argc = expr->ex.funct.sig->argc; mathfun_value *funct_args = malloc(argc * sizeof(mathfun_value)); if (!funct_args) { if (errno == 0) errno = ENOMEM; return (mathfun_value){ .number = NAN }; } for (size_t i = 0; i < argc; ++ i) { funct_args[i] = mathfun_expr_exec(expr->ex.funct.args[i], args); } mathfun_value value = expr->ex.funct.funct(funct_args); free(funct_args); return value; } case EX_NEG: return (mathfun_value){ .number = -mathfun_expr_exec(expr->ex.unary.expr, args).number }; case EX_ADD: return (mathfun_value){ .number = mathfun_expr_exec(expr->ex.binary.left, args).number + mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_SUB: return (mathfun_value){ .number = mathfun_expr_exec(expr->ex.binary.left, args).number - mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_MUL: return (mathfun_value){ .number = mathfun_expr_exec(expr->ex.binary.left, args).number * mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_DIV: return (mathfun_value){ .number = mathfun_expr_exec(expr->ex.binary.left, args).number / mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_MOD: return (mathfun_value){ .number = mathfun_mod( mathfun_expr_exec(expr->ex.binary.left, args).number, mathfun_expr_exec(expr->ex.binary.right, args).number) }; case EX_POW: return (mathfun_value){ .number = pow( mathfun_expr_exec(expr->ex.binary.left, args).number, mathfun_expr_exec(expr->ex.binary.right, args).number) }; case EX_NOT: return (mathfun_value){ .boolean = !mathfun_expr_exec(expr->ex.unary.expr, args).boolean }; case EX_EQ: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).number == mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_NE: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).number != mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_LT: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).number < mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_GT: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).number > mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_LE: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).number <= mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_GE: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).number >= mathfun_expr_exec(expr->ex.binary.right, args).number }; case EX_BEQ: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).boolean == mathfun_expr_exec(expr->ex.binary.right, args).boolean }; case EX_BNE: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).boolean != mathfun_expr_exec(expr->ex.binary.right, args).boolean }; case EX_AND: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).boolean && mathfun_expr_exec(expr->ex.binary.right, args).boolean }; case EX_OR: return (mathfun_value){ .boolean = mathfun_expr_exec(expr->ex.binary.left, args).boolean || mathfun_expr_exec(expr->ex.binary.right, args).boolean }; case EX_IIF: return mathfun_expr_exec(expr->ex.iif.cond, args).boolean ? mathfun_expr_exec(expr->ex.iif.then_expr, args) : mathfun_expr_exec(expr->ex.iif.else_expr, args); case EX_IN: { double value = mathfun_expr_exec(expr->ex.binary.left, args).number; mathfun_expr *range = expr->ex.binary.right; return (mathfun_value){ .boolean = range->type == EX_RNG_INCL ? value >= mathfun_expr_exec(range->ex.binary.left, args).number && value <= mathfun_expr_exec(range->ex.binary.right, args).number : value >= mathfun_expr_exec(range->ex.binary.left, args).number && value < mathfun_expr_exec(range->ex.binary.right, args).number}; } case EX_RNG_INCL: case EX_RNG_EXCL: break; } errno = EINVAL; return (mathfun_value){ .number = NAN }; } double mathfun_exec(const mathfun *fun, mathfun_value regs[]) { const mathfun_code *start = fun->code; const mathfun_code *code = fun->code; #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" #pragma GCC diagnostic ignored "-Wunused-label" #pragma GCC diagnostic ignored "-Wpointer-arith" // http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html // use offsets instead of absolute addresses to reduce the number of // dynamic relocations for code in shared libraries // // TODO: same for llvm clang // http://blog.llvm.org/2010/01/address-of-label-and-indirect-branches.html static const intptr_t jump_table[] = { /* NOP */ &&do_nop - &&do_add, /* RET */ &&do_ret - &&do_add, /* MOV */ &&do_mov - &&do_add, /* VAL */ &&do_val - &&do_add, /* CALL */ &&do_call - &&do_add, /* NEG */ &&do_neg - &&do_add, /* ADD */ &&do_add - &&do_add, /* SUB */ &&do_sub - &&do_add, /* MUL */ &&do_mul - &&do_add, /* DIV */ &&do_div - &&do_add, /* MOD */ &&do_mod - &&do_add, /* POW */ &&do_pow - &&do_add, /* NOT */ &&do_not - &&do_add, /* EQ */ &&do_eq - &&do_add, /* NE */ &&do_ne - &&do_add, /* LT */ &&do_lt - &&do_add, /* GT */ &&do_gt - &&do_add, /* LE */ &&do_le - &&do_add, /* GE */ &&do_ge - &&do_add, /* BEQ */ &&do_beq - &&do_add, /* BNE */ &&do_bne - &&do_add, /* JMP */ &&do_jmp - &&do_add, /* JMPT */ &&do_jmpt - &&do_add, /* JMPF */ &&do_jmpf - &&do_add, /* SETT */ &&do_sett - &&do_add, /* SETF */ &&do_setf - &&do_add }; # define DISPATCH goto *(&&do_add + jump_table[*code]); DISPATCH; #else # define DISPATCH break; #endif for (;;) { switch (*code) { case ADD: do_add: regs[code[3]].number = regs[code[1]].number + regs[code[2]].number; code += 4; DISPATCH; case SUB: do_sub: regs[code[3]].number = regs[code[1]].number - regs[code[2]].number; code += 4; DISPATCH; case MUL: do_mul: regs[code[3]].number = regs[code[1]].number * regs[code[2]].number; code += 4; DISPATCH; case DIV: do_div: regs[code[3]].number = regs[code[1]].number / regs[code[2]].number; code += 4; DISPATCH; case MOD: do_mod: regs[code[3]].number = mathfun_mod(regs[code[1]].number, regs[code[2]].number); code += 4; DISPATCH; case POW: do_pow: regs[code[3]].number = pow(regs[code[1]].number, regs[code[2]].number); code += 4; DISPATCH; case NEG: do_neg: regs[code[2]].number = -regs[code[1]].number; code += 3; DISPATCH; case VAL: do_val: regs[code[1 + MATHFUN_VALUE_CODES]] = *(mathfun_value*)(code + 1); code += 2 + MATHFUN_VALUE_CODES; DISPATCH; case CALL: do_call: { mathfun_binding_funct funct = *(mathfun_binding_funct*)(code + 1); code += 1 + MATHFUN_FUNCT_CODES; mathfun_code firstarg = *(code ++); mathfun_code ret = *(code ++); regs[ret] = funct(regs + firstarg); DISPATCH; } case MOV: do_mov: regs[code[2]] = regs[code[1]]; code += 3; DISPATCH; case NOT: do_not: regs[code[2]].boolean = !regs[code[1]].boolean; code += 3; DISPATCH; case EQ: do_eq: regs[code[3]].boolean = regs[code[1]].number == regs[code[2]].number; code += 4; DISPATCH; case NE: do_ne: regs[code[3]].boolean = regs[code[1]].number != regs[code[2]].number; code += 4; DISPATCH; case LT: do_lt: regs[code[3]].boolean = regs[code[1]].number < regs[code[2]].number; code += 4; DISPATCH; case GT: do_gt: regs[code[3]].boolean = regs[code[1]].number > regs[code[2]].number; code += 4; DISPATCH; case LE: do_le: regs[code[3]].boolean = regs[code[1]].number <= regs[code[2]].number; code += 4; DISPATCH; case GE: do_ge: regs[code[3]].boolean = regs[code[1]].number >= regs[code[2]].number; code += 4; DISPATCH; case BEQ: do_beq: regs[code[3]].boolean = regs[code[1]].boolean == regs[code[2]].boolean; code += 4; DISPATCH; case BNE: do_bne: regs[code[3]].boolean = regs[code[1]].boolean != regs[code[2]].boolean; code += 4; DISPATCH; case JMP: do_jmp: code = start + code[1]; DISPATCH; case JMPT: do_jmpt: if (regs[code[1]].boolean) { code = start + code[2]; } else { code += 3; } DISPATCH; case JMPF: do_jmpf: if (regs[code[1]].boolean) { code += 3; } else { code = start + code[2]; } DISPATCH; case SETT: do_sett: regs[code[1]].boolean = true; code += 2; DISPATCH; case SETF: do_setf: regs[code[1]].boolean = false; code += 2; DISPATCH; case RET: do_ret: return regs[code[1]].number; case NOP: do_nop: ++ code; DISPATCH; default: errno = EINVAL; return NAN; } } } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif <file_sep>/src/CMakeLists.txt include(GenerateExportHeader) configure_file(config.h.in "${CMAKE_CURRENT_BINARY_DIR}/config.h" @ONLY) set(MATHFUN_SRCS bindings.c optimize.c codegen.c exec.c mathfun.c parser.c error.c mathfun.h mathfun_intern.h config.h.in) add_compiler_export_flags() add_library(${MATHFUN_LIB_NAME} ${MATHFUN_SRCS}) generate_export_header(${MATHFUN_LIB_NAME} EXPORT_MACRO_NAME MATHFUN_EXPORT EXPORT_FILE_NAME export.h STATIC_DEFINE MATHFUN_STATIC_LIB) target_link_libraries(${MATHFUN_LIB_NAME} ${M_LIBRARY}) install(TARGETS ${MATHFUN_LIB_NAME} DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(FILES mathfun.h "${CMAKE_CURRENT_BINARY_DIR}/config.h" "${CMAKE_CURRENT_BINARY_DIR}/export.h" DESTINATION "include/${MATHFUN_NAME}") <file_sep>/src/error.c #include <string.h> #include <errno.h> #include "mathfun_intern.h" // special error info in case of ENOMEM, because then it's unlikely that allocating a new // error object will work and this is also the only way to signal a proper error in case // there is an ENOMEM when allocating an error object. static const mathfun_error mathfun_memory_error = { MATHFUN_OUT_OF_MEMORY, ENOMEM, 0, 0, NULL, NULL, 0, { .argc = { 0, 0 } } }; enum mathfun_error_type mathfun_error_type(mathfun_error_p error) { if (error) return error->type; switch (errno) { case 0: return MATHFUN_OK; case EDOM: case ERANGE: return MATHFUN_MATH_ERROR; case ENOMEM: return MATHFUN_OUT_OF_MEMORY; default: return MATHFUN_C_ERROR; } } int mathfun_error_errno(mathfun_error_p error) { return error ? error->errnum : errno; } size_t mathfun_error_lineno(mathfun_error_p error) { return error ? error->lineno : 0; } size_t mathfun_error_column(mathfun_error_p error) { return error ? error->column : 0; } size_t mathfun_error_errpos(mathfun_error_p error) { return error ? error->errpos - error->str : 0; } size_t mathfun_error_errlen(mathfun_error_p error) { return error ? error->errlen : 0; } void mathfun_error_log_and_cleanup(mathfun_error_p *errptr, FILE *stream) { mathfun_error_log(errptr ? *errptr : NULL, stream); mathfun_error_cleanup(errptr); } void mathfun_error_cleanup(mathfun_error_p *errptr) { if (errptr) { if (*errptr != &mathfun_memory_error) { free((mathfun_error*)*errptr); } *errptr = NULL; } } mathfun_error *mathfun_error_alloc(enum mathfun_error_type type) { mathfun_error *error = calloc(1, sizeof(mathfun_error)); if (error) { error->type = type; switch (type) { case MATHFUN_OK: // probably I should assert(false) here break; case MATHFUN_IO_ERROR: case MATHFUN_MATH_ERROR: case MATHFUN_OUT_OF_MEMORY: case MATHFUN_C_ERROR: error->errnum = errno; break; default: error->errnum = errno = EINVAL; break; } } return error; } void mathfun_raise_error(mathfun_error_p *errptr, enum mathfun_error_type type) { if (!errptr) return; if (type == MATHFUN_OUT_OF_MEMORY || (type == MATHFUN_C_ERROR && errno == ENOMEM)) { *errptr = &mathfun_memory_error; } else { *errptr = mathfun_error_alloc(type); } } void mathfun_raise_name_error(mathfun_error_p *errptr, enum mathfun_error_type type, const char *name) { if (errptr) { mathfun_error *error = mathfun_error_alloc(type); if (error) { error->str = name; *errptr = error; } else { *errptr = &mathfun_memory_error; } } } static mathfun_error *mathfun_alloc_parse_error( const mathfun_parser *parser, enum mathfun_error_type type, const char *errpos) { mathfun_error *error = mathfun_error_alloc(type); if (error) { error->type = type; error->errnum = errno = EINVAL; error->str = parser->code; error->errpos = errpos ? errpos : parser->ptr; switch (type) { case MATHFUN_PARSER_UNDEFINED_REFERENCE: case MATHFUN_PARSER_NOT_A_FUNCTION: case MATHFUN_PARSER_NOT_A_VARIABLE: error->errlen = mathfun_find_identifier_end(error->errpos) - error->errpos; break; default: error->errlen = errpos ? parser->ptr - errpos : 1; } size_t lineno = 1; size_t column = 1; const char *ptr = parser->code; for (; ptr < error->errpos; ++ ptr) { if (*ptr == '\n') { ++ lineno; column = 1; } else { ++ column; } } error->lineno = lineno; error->column = column; } return error; } void mathfun_raise_parser_error(const mathfun_parser *parser, enum mathfun_error_type type, const char *errpos) { if (parser->error) { mathfun_error *error = mathfun_alloc_parse_error(parser, type, errpos); if (error) { *parser->error = error; } else { *parser->error = &mathfun_memory_error; } } } void mathfun_raise_parser_argc_error(const mathfun_parser *parser, const char *errpos, size_t expected, size_t got) { if (parser->error) { mathfun_error *error = mathfun_alloc_parse_error(parser, MATHFUN_PARSER_ILLEGAL_NUMBER_OF_ARGUMENTS, errpos); if (error) { error->err.argc.expected = expected; error->err.argc.got = got; *parser->error = error; } else { *parser->error = &mathfun_memory_error; } } } void mathfun_raise_parser_type_error(const mathfun_parser *parser, const char *errpos, mathfun_type expected, mathfun_type got) { if (parser->error) { mathfun_error *error = mathfun_alloc_parse_error(parser, MATHFUN_PARSER_TYPE_ERROR, errpos); if (error) { error->err.type.expected = expected; error->err.type.got = got; *parser->error = error; } else { *parser->error = &mathfun_memory_error; } } } void mathfun_raise_c_error(mathfun_error_p *errptr) { if (errptr) { switch (errno) { case 0: *errptr = NULL; break; case ERANGE: case EDOM: mathfun_raise_math_error(errptr, errno); break; default: mathfun_raise_error(errptr, MATHFUN_C_ERROR); break; } } } void mathfun_raise_math_error(mathfun_error_p *errptr, int errnum) { errno = errnum; mathfun_raise_error(errptr, MATHFUN_MATH_ERROR); } static void mathfun_log_parser_error(mathfun_error_p error, FILE *stream, const char *fmt, ...) { va_list ap; const char *endl = strchr(error->errpos, '\n'); int n = endl ? endl - error->str : (int)strlen(error->str); fprintf(stream, "%"PRIzu":%"PRIzu": parser error: ", error->lineno, error->column); va_start(ap, fmt); vfprintf(stream, fmt, ap); va_end(ap); fprintf(stream, "\n%.*s\n", n, error->str); if (error->column > 0) { for (size_t column = error->column - 1; column > 0; -- column) { fputc('-', stream); } } fprintf(stream, "^\n"); } void mathfun_error_log(mathfun_error_p error, FILE *stream) { enum mathfun_error_type type = MATHFUN_OK; int errnum = 0; if (error) { type = error->type; errnum = error->errnum; } else { errnum = errno; if (errnum != 0) { type = MATHFUN_C_ERROR; } } switch (type) { case MATHFUN_OK: fprintf(stream, "no error\n"); return; case MATHFUN_OUT_OF_MEMORY: case MATHFUN_IO_ERROR: case MATHFUN_MATH_ERROR: case MATHFUN_C_ERROR: fprintf(stream, "error: %s\n", strerror(errnum)); return; case MATHFUN_ILLEGAL_NAME: fprintf(stream, "error: illegal name: '%s'\n", error->str); return; case MATHFUN_DUPLICATE_ARGUMENT: fprintf(stream, "error: duplicate argument: '%s'\n", error->str); return; case MATHFUN_NAME_EXISTS: fprintf(stream, "error: name already exists: '%s'\n", error->str); return; case MATHFUN_NO_SUCH_NAME: fprintf(stream, "error: no such constant or function: '%s'\n", error->str); return; case MATHFUN_TOO_MANY_ARGUMENTS: fprintf(stream, "error: too many arguments\n"); return; case MATHFUN_EXCEEDS_MAX_FRAME_SIZE: fprintf(stream, "error: expression would exceed maximum frame size\n"); return; case MATHFUN_INTERNAL_ERROR: fprintf(stream, "error: internal error\n"); return; case MATHFUN_PARSER_EXPECTED_CLOSE_PARENTHESIS: mathfun_log_parser_error(error, stream, "expected ')'"); return; case MATHFUN_PARSER_UNDEFINED_REFERENCE: mathfun_log_parser_error(error, stream, "undefined reference: '%.*s'", error->errlen, error->errpos); return; case MATHFUN_PARSER_NOT_A_FUNCTION: mathfun_log_parser_error(error, stream, "reference is not a function: '%.*s'", error->errlen, error->errpos); return; case MATHFUN_PARSER_NOT_A_VARIABLE: mathfun_log_parser_error(error, stream, "reference is not an argument or constant: '%.*s'", error->errlen, error->errpos); return; case MATHFUN_PARSER_ILLEGAL_NUMBER_OF_ARGUMENTS: mathfun_log_parser_error(error, stream, "illegal number of arguments: expected %"PRIzu" but got %"PRIzu, error->err.argc.expected, error->err.argc.got); return; case MATHFUN_PARSER_EXPECTED_NUMBER: mathfun_log_parser_error(error, stream, "expected a number"); return; case MATHFUN_PARSER_EXPECTED_IDENTIFIER: mathfun_log_parser_error(error, stream, "expected an identifier"); return; case MATHFUN_PARSER_EXPECTED_COLON: mathfun_log_parser_error(error, stream, "expected ':'"); return; case MATHFUN_PARSER_EXPECTED_DOTS: mathfun_log_parser_error(error, stream, "expected '..' or '...'"); return; case MATHFUN_PARSER_TYPE_ERROR: mathfun_log_parser_error(error, stream, "expression has illegal type for this position: expected %s but got %s", mathfun_type_name(error->err.type.expected), mathfun_type_name(error->err.type.got)); return; case MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT: mathfun_log_parser_error(error, stream, "unexpected end of input"); return; case MATHFUN_PARSER_TRAILING_GARBAGE: mathfun_log_parser_error(error, stream, "trailing garbage"); return; } fprintf(stream, "error: unknown error: %d\n", type); } <file_sep>/src/optimize.c #include <errno.h> #include "mathfun_intern.h" typedef double (*mathfun_binary_op)(double a, double b); typedef bool (*mathfun_cmp)(double a, double b); static double mathfun_add(double a, double b) { return a + b; } static double mathfun_sub(double a, double b) { return a - b; } static double mathfun_mul(double a, double b) { return a * b; } static double mathfun_div(double a, double b) { return a / b; } static bool mathfun_eq(double a, double b) { return a == b; } static bool mathfun_ne(double a, double b) { return a != b; } static bool mathfun_gt(double a, double b) { return a > b; } static bool mathfun_lt(double a, double b) { return a < b; } static bool mathfun_ge(double a, double b) { return a >= b; } static bool mathfun_le(double a, double b) { return a <= b; } static mathfun_expr *mathfun_expr_optimize_binary(mathfun_expr *expr, mathfun_binary_op op, bool has_neutral, double neutral, bool commutative, mathfun_error_p *error) { expr->ex.binary.left = mathfun_expr_optimize(expr->ex.binary.left, error); if (!expr->ex.binary.left) { mathfun_expr_free(expr); return NULL; } expr->ex.binary.right = mathfun_expr_optimize(expr->ex.binary.right, error); if (!expr->ex.binary.right) { mathfun_expr_free(expr); return NULL; } if (expr->ex.binary.left->type == EX_CONST && expr->ex.binary.right->type == EX_CONST) { errno = 0; double value = op(expr->ex.binary.left->ex.value.value.number, expr->ex.binary.right->ex.value.value.number); if (errno != 0) { mathfun_raise_c_error(error); mathfun_expr_free(expr); return NULL; } mathfun_expr_free(expr->ex.binary.left); mathfun_expr_free(expr->ex.binary.right); expr->type = EX_CONST; expr->ex.value.type = MATHFUN_NUMBER; expr->ex.value.value.number = value; } else if (has_neutral) { if (expr->ex.binary.right->type == EX_CONST && expr->ex.binary.right->ex.value.value.number == neutral) { mathfun_expr *left = expr->ex.binary.left; expr->ex.binary.left = NULL; mathfun_expr_free(expr); expr = left; } else if (commutative && expr->ex.binary.left->type == EX_CONST && expr->ex.binary.left->ex.value.value.number == neutral) { mathfun_expr *right = expr->ex.binary.right; expr->ex.binary.right = NULL; mathfun_expr_free(expr); expr = right; } } return expr; } static mathfun_expr *mathfun_expr_optimize_comparison(mathfun_expr *expr, mathfun_cmp cmp, mathfun_error_p *error) { expr->ex.binary.left = mathfun_expr_optimize(expr->ex.binary.left, error); if (!expr->ex.binary.left) { mathfun_expr_free(expr); return NULL; } expr->ex.binary.right = mathfun_expr_optimize(expr->ex.binary.right, error); if (!expr->ex.binary.right) { mathfun_expr_free(expr); return NULL; } if (expr->ex.binary.left->type == EX_CONST && expr->ex.binary.right->type == EX_CONST) { bool value = cmp(expr->ex.binary.left->ex.value.value.number, expr->ex.binary.right->ex.value.value.number); mathfun_expr_free(expr->ex.binary.left); mathfun_expr_free(expr->ex.binary.right); expr->type = EX_CONST; expr->ex.value.type = MATHFUN_BOOLEAN; expr->ex.value.value.boolean = value; } return expr; } static mathfun_expr *mathfun_expr_optimize_boolean_comparison(mathfun_expr *expr, mathfun_error_p *error) { expr->ex.binary.left = mathfun_expr_optimize(expr->ex.binary.left, error); if (!expr->ex.binary.left) { mathfun_expr_free(expr); return NULL; } expr->ex.binary.right = mathfun_expr_optimize(expr->ex.binary.right, error); if (!expr->ex.binary.right) { mathfun_expr_free(expr); return NULL; } mathfun_expr *const_expr; mathfun_expr *other_expr; if (expr->ex.binary.left->type == EX_CONST && expr->ex.binary.right->type == EX_CONST) { bool value = expr->type == EX_BEQ ? expr->ex.binary.left->ex.value.value.boolean == expr->ex.binary.right->ex.value.value.boolean : expr->ex.binary.left->ex.value.value.boolean != expr->ex.binary.right->ex.value.value.boolean; mathfun_expr_free(expr->ex.binary.left); mathfun_expr_free(expr->ex.binary.right); expr->type = EX_CONST; expr->ex.value.type = MATHFUN_BOOLEAN; expr->ex.value.value.boolean = value; return expr; } else if (expr->ex.binary.left->type == EX_CONST) { const_expr = expr->ex.binary.left; other_expr = expr->ex.binary.right; } else if (expr->ex.binary.right->type == EX_CONST) { const_expr = expr->ex.binary.right; other_expr = expr->ex.binary.left; } else { return expr; } bool value = const_expr->ex.value.value.boolean; if ((expr->type == EX_BEQ && value) || (expr->type == EX_BNE && !value)) { expr->ex.binary.left = NULL; expr->ex.binary.right = NULL; mathfun_expr_free(const_expr); mathfun_expr_free(expr); return other_expr; } else { mathfun_expr_free(const_expr); expr->type = EX_NOT; expr->ex.unary.expr = other_expr; return mathfun_expr_optimize(expr, error); } } static mathfun_expr *mathfun_expr_optimize_not(mathfun_expr *expr, mathfun_error_p *error) { expr->ex.unary.expr = mathfun_expr_optimize(expr->ex.unary.expr, error); if (!expr->ex.unary.expr) { mathfun_expr_free(expr); return NULL; } switch (expr->ex.unary.expr->type) { case EX_NOT: { mathfun_expr *child = expr->ex.unary.expr->ex.unary.expr; expr->ex.unary.expr->ex.unary.expr = NULL; mathfun_expr_free(expr); return child; } case EX_CONST: { mathfun_expr *child = expr->ex.unary.expr; expr->ex.unary.expr = NULL; mathfun_expr_free(expr); child->ex.value.value.boolean = !child->ex.value.value.boolean; return child; } // can't do this for <, >, <=, >= and in because !(1 < NAN) != (1 >= NAN) case EX_EQ: { mathfun_expr *child = expr->ex.unary.expr; expr->ex.unary.expr = NULL; mathfun_expr_free(expr); child->type = EX_NE; return child; } case EX_NE: { mathfun_expr *child = expr->ex.unary.expr; expr->ex.unary.expr = NULL; mathfun_expr_free(expr); child->type = EX_EQ; return child; } case EX_BEQ: { mathfun_expr *child = expr->ex.unary.expr; expr->ex.unary.expr = NULL; mathfun_expr_free(expr); child->type = EX_BNE; return child; } case EX_BNE: { mathfun_expr *child = expr->ex.unary.expr; expr->ex.unary.expr = NULL; mathfun_expr_free(expr); child->type = EX_BEQ; return child; } default: return expr; } } mathfun_expr *mathfun_expr_optimize(mathfun_expr *expr, mathfun_error_p *error) { switch (expr->type) { case EX_CONST: case EX_ARG: return expr; case EX_CALL: { bool allconst = true; const size_t argc = expr->ex.funct.sig->argc; for (size_t i = 0; i < argc; ++ i) { mathfun_expr *child = expr->ex.funct.args[i] = mathfun_expr_optimize(expr->ex.funct.args[i], error); if (!child) { mathfun_expr_free(expr); return NULL; } else if (child->type != EX_CONST) { allconst = false; } } if (allconst) { mathfun_value *args = calloc(argc, sizeof(mathfun_value)); if (!args) return NULL; for (size_t i = 0; i < argc; ++ i) { mathfun_expr *arg = expr->ex.funct.args[i]; args[i] = arg->ex.value.value; mathfun_expr_free(arg); } free(expr->ex.funct.args); // math errors are communicated via errno // XXX: buggy. see NOTES in man math_error errno = 0; mathfun_value value = expr->ex.funct.funct(args); free(args); expr->type = EX_CONST; expr->ex.value.type = expr->ex.funct.sig->rettype; expr->ex.value.value = value; if (errno != 0) { mathfun_raise_c_error(error); mathfun_expr_free(expr); return NULL; } } return expr; } case EX_NEG: expr->ex.unary.expr = mathfun_expr_optimize(expr->ex.unary.expr, error); if (!expr->ex.unary.expr) { mathfun_expr_free(expr); return NULL; } else if (expr->ex.unary.expr->type == EX_NEG) { mathfun_expr *child = expr->ex.unary.expr->ex.unary.expr; expr->ex.unary.expr->ex.unary.expr = NULL; mathfun_expr_free(expr); return child; } else if (expr->ex.unary.expr->type == EX_CONST) { mathfun_expr *child = expr->ex.unary.expr; expr->ex.unary.expr = NULL; mathfun_expr_free(expr); child->ex.value.value.number = -child->ex.value.value.number; return child; } return expr; case EX_ADD: return mathfun_expr_optimize_binary(expr, mathfun_add, true, 0, true, error); case EX_SUB: return mathfun_expr_optimize_binary(expr, mathfun_sub, true, 0, false, error); case EX_MUL: return mathfun_expr_optimize_binary(expr, mathfun_mul, true, 1, true, error); case EX_DIV: return mathfun_expr_optimize_binary(expr, mathfun_div, true, 1, false, error); case EX_MOD: return mathfun_expr_optimize_binary(expr, mathfun_mod, false, NAN, false, error); case EX_POW: return mathfun_expr_optimize_binary(expr, pow, true, 1, false, error); case EX_NOT: return mathfun_expr_optimize_not(expr, error); case EX_EQ: return mathfun_expr_optimize_comparison(expr, mathfun_eq, error); case EX_NE: return mathfun_expr_optimize_comparison(expr, mathfun_ne, error); case EX_LT: return mathfun_expr_optimize_comparison(expr, mathfun_lt, error); case EX_GT: return mathfun_expr_optimize_comparison(expr, mathfun_gt, error); case EX_LE: return mathfun_expr_optimize_comparison(expr, mathfun_le, error); case EX_GE: return mathfun_expr_optimize_comparison(expr, mathfun_ge, error); case EX_IN: { mathfun_expr *value = expr->ex.binary.left = mathfun_expr_optimize(expr->ex.binary.left, error); if (!value) { mathfun_expr_free(expr); return NULL; } mathfun_expr *range = expr->ex.binary.right = mathfun_expr_optimize(expr->ex.binary.right, error); if (!range) { mathfun_expr_free(expr); return NULL; } if (value->type == EX_CONST) { mathfun_expr *lower = range->ex.binary.left; mathfun_expr *upper = range->ex.binary.right; if (lower->type == EX_CONST && upper->type == EX_CONST) { bool res = range->type == EX_RNG_INCL ? value->ex.value.value.number >= lower->ex.value.value.number && value->ex.value.value.number <= lower->ex.value.value.number : value->ex.value.value.number >= lower->ex.value.value.number && value->ex.value.value.number < lower->ex.value.value.number; expr->ex.binary.left = NULL; mathfun_expr_free(expr); value->ex.value.type = MATHFUN_BOOLEAN; value->ex.value.value.boolean = res; return value; } else if (lower->type == EX_CONST) { if (value->ex.value.value.number >= lower->ex.value.value.number) { expr->ex.binary.left = NULL; expr->ex.binary.right = NULL; mathfun_expr_free(expr); mathfun_expr_free(lower); range->type = range->type == EX_RNG_INCL ? EX_LE : EX_LT; range->ex.binary.left = value; return range; } else { expr->ex.binary.left = NULL; mathfun_expr_free(expr); value->ex.value.type = MATHFUN_BOOLEAN; value->ex.value.value.boolean = false; return value; } } else if (upper->type == EX_CONST) { if (range->type == EX_RNG_INCL ? value->ex.value.value.number <= upper->ex.value.value.number : value->ex.value.value.number < upper->ex.value.value.number) { expr->ex.binary.left = NULL; expr->ex.binary.right = NULL; mathfun_expr_free(expr); mathfun_expr_free(upper); range->type = EX_GE; range->ex.binary.left = value; range->ex.binary.right = lower; return range; } else { expr->ex.binary.left = NULL; mathfun_expr_free(expr); value->ex.value.type = MATHFUN_BOOLEAN; value->ex.value.value.boolean = false; return value; } } } return expr; } case EX_RNG_INCL: case EX_RNG_EXCL: { expr->ex.binary.left = mathfun_expr_optimize(expr->ex.binary.left, error); if (!expr->ex.binary.left) { mathfun_expr_free(expr); return NULL; } expr->ex.binary.right = mathfun_expr_optimize(expr->ex.binary.right, error); if (!expr->ex.binary.right) { mathfun_expr_free(expr); return NULL; } return expr; } case EX_BEQ: case EX_BNE: return mathfun_expr_optimize_boolean_comparison(expr, error); case EX_AND: { expr->ex.binary.left = mathfun_expr_optimize(expr->ex.binary.left, error); if (!expr->ex.binary.left) { mathfun_expr_free(expr); return NULL; } expr->ex.binary.right = mathfun_expr_optimize(expr->ex.binary.right, error); if (!expr->ex.binary.right) { mathfun_expr_free(expr); return NULL; } mathfun_expr *const_expr; mathfun_expr *other_expr; if (expr->ex.binary.left->type == EX_CONST && expr->ex.binary.right->type == EX_CONST) { bool value = expr->ex.binary.left->ex.value.value.boolean && expr->ex.binary.right->ex.value.value.boolean; mathfun_expr_free(expr->ex.binary.left); mathfun_expr_free(expr->ex.binary.right); expr->type = EX_CONST; expr->ex.value.type = MATHFUN_BOOLEAN; expr->ex.value.value.boolean = value; return expr; } else if (expr->ex.binary.left->type == EX_CONST) { const_expr = expr->ex.binary.left; other_expr = expr->ex.binary.right; } else if (expr->ex.binary.right->type == EX_CONST) { other_expr = expr->ex.binary.left; const_expr = expr->ex.binary.right; } else { return expr; } if (const_expr->ex.value.value.boolean) { expr->ex.binary.left = NULL; expr->ex.binary.right = NULL; mathfun_expr_free(const_expr); mathfun_expr_free(expr); return other_expr; } else { mathfun_expr_free(expr->ex.binary.left); mathfun_expr_free(expr->ex.binary.right); expr->type = EX_CONST; expr->ex.value.type = MATHFUN_BOOLEAN; expr->ex.value.value.boolean = false; return expr; } } case EX_OR: { expr->ex.binary.left = mathfun_expr_optimize(expr->ex.binary.left, error); if (!expr->ex.binary.left) { mathfun_expr_free(expr); return NULL; } expr->ex.binary.right = mathfun_expr_optimize(expr->ex.binary.right, error); if (!expr->ex.binary.right) { mathfun_expr_free(expr); return NULL; } mathfun_expr *const_expr; mathfun_expr *other_expr; if (expr->ex.binary.left->type == EX_CONST && expr->ex.binary.right->type == EX_CONST) { bool value = expr->ex.binary.left->ex.value.value.boolean || expr->ex.binary.right->ex.value.value.boolean; mathfun_expr_free(expr->ex.binary.left); mathfun_expr_free(expr->ex.binary.right); expr->type = EX_CONST; expr->ex.value.type = MATHFUN_BOOLEAN; expr->ex.value.value.boolean = value; return expr; } else if (expr->ex.binary.left->type == EX_CONST) { const_expr = expr->ex.binary.left; other_expr = expr->ex.binary.right; } else if (expr->ex.binary.right->type == EX_CONST) { other_expr = expr->ex.binary.left; const_expr = expr->ex.binary.right; } else { return expr; } if (const_expr->ex.value.value.boolean) { mathfun_expr_free(expr->ex.binary.left); mathfun_expr_free(expr->ex.binary.right); expr->type = EX_CONST; expr->ex.value.type = MATHFUN_BOOLEAN; expr->ex.value.value.boolean = true; return expr; } else { expr->ex.binary.left = NULL; expr->ex.binary.right = NULL; mathfun_expr_free(const_expr); mathfun_expr_free(expr); return other_expr; } } case EX_IIF: { expr->ex.iif.cond = mathfun_expr_optimize(expr->ex.iif.cond, error); if (!expr->ex.iif.cond) { mathfun_expr_free(expr); return NULL; } expr->ex.iif.then_expr = mathfun_expr_optimize(expr->ex.iif.then_expr, error); if (!expr->ex.iif.then_expr) { mathfun_expr_free(expr); return NULL; } expr->ex.iif.else_expr = mathfun_expr_optimize(expr->ex.iif.else_expr, error); if (!expr->ex.iif.else_expr) { mathfun_expr_free(expr); return NULL; } if (expr->ex.iif.cond->type == EX_CONST) { mathfun_expr *child; if (expr->ex.iif.cond->ex.value.value.boolean) { child = expr->ex.iif.then_expr; expr->ex.iif.then_expr = NULL; } else { child = expr->ex.iif.else_expr; expr->ex.iif.else_expr = NULL; } mathfun_expr_free(expr); return child; } return expr; } } return expr; } <file_sep>/examples/wavegen.c #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <math.h> #include <mathfun.h> #include "portable_endian.h" #ifndef M_TAU # define M_TAU (2*M_PI) #endif static mathfun_value square_wave(const mathfun_value args[]) { return (mathfun_value){ .number = fmod(args[0].number, M_TAU) < M_PI ? 1 : -1 }; } static mathfun_value triangle_wave(const mathfun_value args[]) { const double x = fmod((args[0].number + M_PI_2), M_TAU); return (mathfun_value){ .number = x < M_PI ? x * M_2_PI - 1 : 3 - x * M_2_PI }; } static mathfun_value sawtooth_wave(const mathfun_value args[]) { return (mathfun_value){ .number = fmod(args[0].number, M_TAU) * M_1_PI - 1 }; } static mathfun_value fadein(const mathfun_value args[]) { const double t = args[0].number; if (t < 0) return (mathfun_value){ .number = 0.0 }; const double duration = args[1].number; if (duration < t) return (mathfun_value){ .number = 1.0 }; const double x = t / duration; return (mathfun_value){ .number = x*x }; } static mathfun_value fadeout(const mathfun_value args[]) { double t = args[0].number; const double duration = args[1].number; if (t > duration) return (mathfun_value){ .number = 0.0 }; if (t < 0.0) return (mathfun_value){ .number = 1.0 }; const double x = (t - duration) / duration; return (mathfun_value){ .number = x*x }; } static mathfun_value mask(const mathfun_value args[]) { const double t = args[0].number; return (mathfun_value){ .number = t >= 0 && t < args[1].number ? 1.0 : 0.0 }; } static mathfun_value clamp(const mathfun_value args[]) { const double x = args[0].number; const double min = args[1].number; const double max = args[2].number; return (mathfun_value){ .number = x < min ? min : x > max ? max : x }; } static mathfun_value pop(const mathfun_value args[]) { const double t = args[0].number; const double wavelength = args[1].number; const double half_wavelength = wavelength * 0.5; const double amplitude = args[2].number; return (mathfun_value){ .number = t >= 0.0 && t < half_wavelength ? amplitude : t >= half_wavelength && t < wavelength ? -amplitude : 0.0 }; } static mathfun_value drop(const mathfun_value args[]) { return (mathfun_value){ .number = args[0].number == 0.0 ? 0.0 : 1.0 }; } #define RIFF_WAVE_HEADER_SIZE 44 #pragma pack(push, 1) struct riff_wave_header { uint8_t id[4]; uint32_t size; uint8_t format[4]; uint8_t fmt_chunk_id[4]; uint32_t fmt_chunk_size; uint16_t audio_format; uint16_t channels; uint32_t sample_rate; uint32_t byte_rate; uint16_t block_align; uint16_t bits_per_sample; uint8_t data_chunk_id[4]; uint32_t data_chunk_size; }; #pragma pack(pop) static unsigned int to_full_byte(int bits) { int rem = bits % 8; return rem == 0 ? bits : bits + (8 - rem); } bool mathfun_wavegen(const char *filename, FILE *stream, uint32_t sample_rate, uint16_t bits_per_sample, uint16_t channels, uint32_t samples, const mathfun channel_functs[], bool write_header) { if (sample_rate == 0) { fprintf(stderr, "illegal sample rate: %u\n", sample_rate); return false; } if (bits_per_sample == 0) { fprintf(stderr, "illegal number of bits per sample: %u\n", bits_per_sample); return false; } if (channels == 0) { fprintf(stderr, "illegal number of channels: %u\n", channels); return false; } const int mid = 1 << (bits_per_sample - 1); const int max_volume = ~(~((uint32_t)0) << (bits_per_sample - 1)); const unsigned int ceil_bits_per_sample = to_full_byte(bits_per_sample); const unsigned int shift = ceil_bits_per_sample - bits_per_sample; const unsigned int bytes_per_sample = ceil_bits_per_sample / 8; uint8_t *sample_buf = malloc(bytes_per_sample); if (!sample_buf) { perror("allocating sample buffer"); return false; } // to boost performance even more pre-allocate a big enough frame instead of // allocating a new frame on each function call size_t maxframesize = 0; for (uint16_t channel = 0; channel < channels; ++ channel) { size_t framesize = channel_functs[channel].framesize; if (framesize > maxframesize) { maxframesize = framesize; } } mathfun_value *frame = calloc(maxframesize, sizeof(mathfun_value)); if (!frame) { perror("allocating frame"); free(sample_buf); return false; } if (write_header) { const uint16_t block_align = channels * bytes_per_sample; const uint32_t data_size = block_align * samples; const struct riff_wave_header header = { .id = "RIFF", .size = htole32(36 + data_size), .format = "WAVE", .fmt_chunk_id = "fmt ", .fmt_chunk_size = htole32(16), .audio_format = htole16(1), // PCM .channels = htole16(channels), .sample_rate = htole32(sample_rate), .byte_rate = htole32(sample_rate * block_align), .block_align = htole16(block_align), .bits_per_sample = htole16(bits_per_sample), .data_chunk_id = "data", .data_chunk_size = htole32(data_size) }; if (fwrite(&header, RIFF_WAVE_HEADER_SIZE, 1, stream) != 1) { perror(filename); free(frame); free(sample_buf); return false; } } for (size_t sample = 0; sample < samples; ++ sample) { const double t = (double)sample / (double)sample_rate; const double r = t * M_TAU; for (size_t channel = 0; channel < channels; ++ channel) { const mathfun *funct = channel_functs + channel; // arguments are the first cells in frame: frame[0].number = t; frame[1].number = r; frame[2].number = sample; frame[3].number = channel; // ignore math errors here (would be in errno) double value = mathfun_exec(funct, frame); if (value > 1.0) value = 1.0; else if (value < -1.0) value = -1.0; int vol = (int)(max_volume * value) << shift; if (bits_per_sample <= 8) { vol += mid; } for (size_t byte = 0; byte < bytes_per_sample; ++ byte) { sample_buf[byte] = (vol >> (byte * 8)) & 0xFF; } if (fwrite(sample_buf, bytes_per_sample, 1, stream) != 1) { perror(filename); free(frame); free(sample_buf); return false; } } } free(frame); free(sample_buf); return true; } bool wavegen(const char *filename, FILE *stream, uint32_t sample_rate, uint16_t bits_per_sample, uint16_t channels, uint32_t samples, const char *channel_functs[], bool write_header) { const mathfun_sig sig1 = {1, (mathfun_type[]){MATHFUN_NUMBER}, MATHFUN_NUMBER}; const mathfun_sig sig2 = {2, (mathfun_type[]){MATHFUN_NUMBER, MATHFUN_NUMBER}, MATHFUN_NUMBER}; const mathfun_sig sig3 = {3, (mathfun_type[]){MATHFUN_NUMBER, MATHFUN_NUMBER, MATHFUN_NUMBER}, MATHFUN_NUMBER}; mathfun_context ctx; mathfun_error_p error = NULL; if (!mathfun_context_init(&ctx, true, &error) || !mathfun_context_define_const(&ctx, "C0", 16.35, &error) || !mathfun_context_define_const(&ctx, "Cs0", 17.32, &error) || !mathfun_context_define_const(&ctx, "D0", 18.35, &error) || !mathfun_context_define_const(&ctx, "Ds0", 19.45, &error) || !mathfun_context_define_const(&ctx, "E0", 20.60, &error) || !mathfun_context_define_const(&ctx, "F0", 21.83, &error) || !mathfun_context_define_const(&ctx, "Fs0", 23.12, &error) || !mathfun_context_define_const(&ctx, "G0", 24.50, &error) || !mathfun_context_define_const(&ctx, "Gs0", 25.96, &error) || !mathfun_context_define_const(&ctx, "A0", 27.50, &error) || !mathfun_context_define_const(&ctx, "As0", 29.14, &error) || !mathfun_context_define_const(&ctx, "B0", 30.87, &error) || !mathfun_context_define_const(&ctx, "C1", 32.70, &error) || !mathfun_context_define_const(&ctx, "Cs1", 34.65, &error) || !mathfun_context_define_const(&ctx, "D1", 36.71, &error) || !mathfun_context_define_const(&ctx, "Ds1", 38.89, &error) || !mathfun_context_define_const(&ctx, "E1", 41.20, &error) || !mathfun_context_define_const(&ctx, "F1", 43.65, &error) || !mathfun_context_define_const(&ctx, "Fs1", 46.25, &error) || !mathfun_context_define_const(&ctx, "G1", 49.00, &error) || !mathfun_context_define_const(&ctx, "Gs1", 51.91, &error) || !mathfun_context_define_const(&ctx, "A1", 55.00, &error) || !mathfun_context_define_const(&ctx, "As1", 58.27, &error) || !mathfun_context_define_const(&ctx, "B1", 61.74, &error) || !mathfun_context_define_const(&ctx, "C2", 65.41, &error) || !mathfun_context_define_const(&ctx, "Cs2", 69.30, &error) || !mathfun_context_define_const(&ctx, "D2", 73.42, &error) || !mathfun_context_define_const(&ctx, "Ds2", 77.78, &error) || !mathfun_context_define_const(&ctx, "E2", 82.41, &error) || !mathfun_context_define_const(&ctx, "F2", 87.31, &error) || !mathfun_context_define_const(&ctx, "Fs2", 92.50, &error) || !mathfun_context_define_const(&ctx, "G2", 98.00, &error) || !mathfun_context_define_const(&ctx, "Gs2", 103.83, &error) || !mathfun_context_define_const(&ctx, "A2", 110.00, &error) || !mathfun_context_define_const(&ctx, "As2", 116.54, &error) || !mathfun_context_define_const(&ctx, "B2", 123.47, &error) || !mathfun_context_define_const(&ctx, "C3", 130.81, &error) || !mathfun_context_define_const(&ctx, "Cs3", 138.59, &error) || !mathfun_context_define_const(&ctx, "D3", 146.83, &error) || !mathfun_context_define_const(&ctx, "Ds3", 155.56, &error) || !mathfun_context_define_const(&ctx, "E3", 164.81, &error) || !mathfun_context_define_const(&ctx, "F3", 174.61, &error) || !mathfun_context_define_const(&ctx, "Fs3", 185.00, &error) || !mathfun_context_define_const(&ctx, "G3", 196.00, &error) || !mathfun_context_define_const(&ctx, "Gs3", 207.65, &error) || !mathfun_context_define_const(&ctx, "A3", 220.00, &error) || !mathfun_context_define_const(&ctx, "As3", 233.08, &error) || !mathfun_context_define_const(&ctx, "B3", 246.94, &error) || !mathfun_context_define_const(&ctx, "C4", 261.63, &error) || !mathfun_context_define_const(&ctx, "Cs4", 277.18, &error) || !mathfun_context_define_const(&ctx, "D4", 293.66, &error) || !mathfun_context_define_const(&ctx, "Ds4", 311.13, &error) || !mathfun_context_define_const(&ctx, "E4", 329.63, &error) || !mathfun_context_define_const(&ctx, "F4", 349.23, &error) || !mathfun_context_define_const(&ctx, "Fs4", 369.99, &error) || !mathfun_context_define_const(&ctx, "G4", 392.00, &error) || !mathfun_context_define_const(&ctx, "Gs4", 415.30, &error) || !mathfun_context_define_const(&ctx, "A4", 440.00, &error) || !mathfun_context_define_const(&ctx, "As4", 466.16, &error) || !mathfun_context_define_const(&ctx, "B4", 493.88, &error) || !mathfun_context_define_const(&ctx, "C5", 523.25, &error) || !mathfun_context_define_const(&ctx, "Cs5", 554.37, &error) || !mathfun_context_define_const(&ctx, "D5", 587.33, &error) || !mathfun_context_define_const(&ctx, "Ds5", 622.25, &error) || !mathfun_context_define_const(&ctx, "E5", 659.25, &error) || !mathfun_context_define_const(&ctx, "F5", 698.46, &error) || !mathfun_context_define_const(&ctx, "Fs5", 739.99, &error) || !mathfun_context_define_const(&ctx, "G5", 783.99, &error) || !mathfun_context_define_const(&ctx, "Gs5", 830.61, &error) || !mathfun_context_define_const(&ctx, "A5", 880.00, &error) || !mathfun_context_define_const(&ctx, "As5", 932.33, &error) || !mathfun_context_define_const(&ctx, "B5", 987.77, &error) || !mathfun_context_define_const(&ctx, "C6", 1046.50, &error) || !mathfun_context_define_const(&ctx, "Cs6", 1108.73, &error) || !mathfun_context_define_const(&ctx, "D6", 1174.66, &error) || !mathfun_context_define_const(&ctx, "Ds6", 1244.51, &error) || !mathfun_context_define_const(&ctx, "E6", 1318.51, &error) || !mathfun_context_define_const(&ctx, "F6", 1396.91, &error) || !mathfun_context_define_const(&ctx, "Fs6", 1479.98, &error) || !mathfun_context_define_const(&ctx, "G6", 1567.98, &error) || !mathfun_context_define_const(&ctx, "Gs6", 1661.22, &error) || !mathfun_context_define_const(&ctx, "A6", 1760.00, &error) || !mathfun_context_define_const(&ctx, "As6", 1864.66, &error) || !mathfun_context_define_const(&ctx, "B6", 1975.53, &error) || !mathfun_context_define_const(&ctx, "C7", 2093.00, &error) || !mathfun_context_define_const(&ctx, "Cs7", 2217.46, &error) || !mathfun_context_define_const(&ctx, "D7", 2349.32, &error) || !mathfun_context_define_const(&ctx, "Ds7", 2489.02, &error) || !mathfun_context_define_const(&ctx, "E7", 2637.02, &error) || !mathfun_context_define_const(&ctx, "F7", 2793.83, &error) || !mathfun_context_define_const(&ctx, "Fs7", 2959.96, &error) || !mathfun_context_define_const(&ctx, "G7", 3135.96, &error) || !mathfun_context_define_const(&ctx, "Gs7", 3322.44, &error) || !mathfun_context_define_const(&ctx, "A7", 3520.00, &error) || !mathfun_context_define_const(&ctx, "As7", 3729.31, &error) || !mathfun_context_define_const(&ctx, "B7", 3951.07, &error) || !mathfun_context_define_const(&ctx, "C8", 4186.01, &error) || !mathfun_context_define_const(&ctx, "Cs8", 4434.92, &error) || !mathfun_context_define_const(&ctx, "D8", 4698.63, &error) || !mathfun_context_define_const(&ctx, "Ds8", 4978.03, &error) || !mathfun_context_define_const(&ctx, "E8", 5274.04, &error) || !mathfun_context_define_const(&ctx, "F8", 5587.65, &error) || !mathfun_context_define_const(&ctx, "Fs8", 5919.91, &error) || !mathfun_context_define_const(&ctx, "G8", 6271.93, &error) || !mathfun_context_define_const(&ctx, "Gs8", 6644.88, &error) || !mathfun_context_define_const(&ctx, "A8", 7040.00, &error) || !mathfun_context_define_const(&ctx, "As8", 7458.62, &error) || !mathfun_context_define_const(&ctx, "B8", 7902.13, &error) || !mathfun_context_define_funct(&ctx, "sq", square_wave, &sig1, &error) || !mathfun_context_define_funct(&ctx, "tri", triangle_wave, &sig1, &error) || !mathfun_context_define_funct(&ctx, "saw", sawtooth_wave, &sig1, &error) || !mathfun_context_define_funct(&ctx, "fadein", fadein, &sig2, &error) || !mathfun_context_define_funct(&ctx, "fadeout", fadeout, &sig2, &error) || !mathfun_context_define_funct(&ctx, "mask", mask, &sig2, &error) || !mathfun_context_define_funct(&ctx, "clamp", clamp, &sig3, &error) || !mathfun_context_define_funct(&ctx, "pop", pop, &sig3, &error) || !mathfun_context_define_funct(&ctx, "drop", drop, &sig1, &error)) { mathfun_error_log_and_cleanup(&error, stderr); return false; } mathfun *functs = calloc(channels, sizeof(mathfun)); if (!functs) { perror("allocating function buffer"); return false; } // t ... time in seconds // r ... t * 2 * pi // s ... sample // c ... channel const char *argnames[] = { "t", "r", "s", "c" }; for (size_t i = 0; i < channels; ++ i) { if (!mathfun_context_compile(&ctx, argnames, 4, channel_functs[i], functs + i, &error)) { mathfun_error_log_and_cleanup(&error, stderr); for (; i > 0; -- i) { mathfun_cleanup(functs + i - 1); } free(functs); mathfun_context_cleanup(&ctx); return false; } } bool ok = mathfun_wavegen(filename, stream, sample_rate, bits_per_sample, channels, samples, functs, write_header); for (size_t i = channels; i > 0; -- i) { mathfun_cleanup(functs + i - 1); } free(functs); mathfun_context_cleanup(&ctx); return ok; } static void usage(int argc, const char *argv[]) { printf( "Usage: %s <wave-filename> <sample-rate> <bits-per-sample> <samples> <wave-function>...\n", argc > 0 ? argv[0] : "wavegen"); } static bool parse_uint16(const char *str, uint16_t *valueptr) { char *endptr = NULL; unsigned long int value = strtoul(str, &endptr, 10); if (endptr == str || value > UINT16_MAX) return false; while (isspace(*endptr)) ++ endptr; if (*endptr) return false; *valueptr = value; return true; } static bool parse_uint32(const char *str, uint32_t *valueptr) { char *endptr = NULL; unsigned long int value = strtoul(str, &endptr, 10); if (endptr == str || value > UINT32_MAX) return false; while (isspace(*endptr)) ++ endptr; if (*endptr) return false; *valueptr = value; return true; } static bool parse_samples(const char *str, uint32_t sample_rate, uint32_t *samplesptr) { if (!*str) return false; const char *ptr = strrchr(str,':'); const char *endptr = NULL; if (ptr) { const double sec = strtod(++ptr, (char**)&endptr); unsigned long int min = 0; unsigned long int hours = 0; if (ptr == endptr) return false; while (isspace(*endptr)) ++ endptr; if (*endptr) return false; ptr -= 2; while (ptr > str && *ptr != ':') -- ptr; if (ptr >= str) { min = strtoul(*ptr == ':' ? ptr+1 : ptr, (char**)&endptr, 10); if (endptr == ptr || *endptr != ':') return false; if (ptr > str) { hours = strtoul(str, (char**)&endptr, 10); if (str == endptr || endptr != ptr) return false; } } unsigned long int samples = (((hours * 60 + min) * 60) + sec) * sample_rate; if (samples > UINT32_MAX) return false; *samplesptr = samples; return true; } endptr = str + strlen(str) - 1; while (endptr > str && isspace(*endptr)) -- endptr; ptr = endptr; ++ endptr; while (ptr > str && isalpha(*ptr)) -- ptr; ++ ptr; size_t sufflen = endptr - ptr; if ((sufflen == 2 && strncmp("ms",ptr,sufflen) == 0) || (sufflen == 4 && strncmp("msec",ptr,sufflen) == 0)) { const double msec = strtod(str, (char**)&endptr); if (endptr == str || msec < 0) return false; while (isspace(*endptr)) ++ endptr; if (endptr != ptr) return false; const double samples = sample_rate * msec / 1000.0; if (samples > UINT32_MAX) return false; *samplesptr = (uint32_t)samples; } else if ((sufflen == 1 && strncmp("s",ptr,sufflen) == 0) || (sufflen == 3 && strncmp("sec",ptr,sufflen) == 0)) { const double sec = strtod(str, (char**)&endptr); if (endptr == str || sec < 0) return false; while (isspace(*endptr)) ++ endptr; if (endptr != ptr) return false; const double samples = sample_rate * sec; if (samples > UINT32_MAX) return false; *samplesptr = (uint32_t)samples; } else if ((sufflen == 1 && strncmp("m",ptr,sufflen) == 0) || (sufflen == 3 && strncmp("min",ptr,sufflen) == 0)) { const double min = strtod(str, (char**)&endptr); if (endptr == str || min < 0) return false; while (isspace(*endptr)) ++ endptr; if (endptr != ptr) return false; const double samples = sample_rate * min * 60; if (samples > UINT32_MAX) return false; *samplesptr = (uint32_t)samples; } else { return parse_uint32(str, samplesptr); } return true; } int main(int argc, const char *argv[]) { if (argc < 6) { fprintf(stderr, "error: too few arguments\n"); usage(argc, argv); return 1; } const char *filename = argv[1]; uint32_t sample_rate = 0; if (!parse_uint32(argv[2], &sample_rate) || sample_rate == 0) { fprintf(stderr, "illegal value for sample rate: %s\n", argv[2]); return 1; } uint16_t bits_per_sample = 0; if (!parse_uint16(argv[3], &bits_per_sample) || bits_per_sample == 0) { fprintf(stderr, "illegal value for bits per sample: %s\n", argv[3]); return 1; } uint32_t samples = 0; if (!parse_samples(argv[4], sample_rate, &samples)) { fprintf(stderr, "illegal value for samples: %s\n", argv[4]); return 1; } const char **functs = argv + 5; int channels = argc - 5; if (channels > UINT16_MAX) { fprintf(stderr, "too many channels: %d\n", channels); return 1; } bool ok; if (strcmp(filename, "-") == 0) { ok = wavegen("<stdout>", stdout, sample_rate, bits_per_sample, channels, samples, functs, true); } else { FILE *stream = fopen(filename, "wb"); if (!stream) { perror(filename); return 1; } ok = wavegen(filename, stream, sample_rate, bits_per_sample, channels, samples, functs, true); fclose(stream); } return ok ? 0 : 1; } <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8.8) project(mathfun) option(BUILD_EXAMPLES "Build examples" OFF) option(INSTALL_WAVEGEN "Install wavegen binary (from examples)" OFF) option(BUILD_SHARED_LIBS "Build Shared Libraries" OFF) option(BUILD_DOCS "Build doxygen documentation" OFF) option(BUILD_TESTS "Build tests" OFF) set(MATHFUN_MAJOR_VERSION 1) set(MATHFUN_MINOR_VERSION 0) set(MATHFUN_PATCH_VERSION 0) set(MATHFUN_NAME mathfun${MATHFUN_MAJOR_VERSION}${MATHFUN_MINOR_VERSION}) set(MATHFUN_VERSION ${MATHFUN_MAJOR_VERSION}.${MATHFUN_MINOR_VERSION}.${MATHFUN_PATCH_VERSION}) if(BUILD_SHARED_LIBS) set(MATHFUN_LIB_NAME ${MATHFUN_NAME}) else() set(MATHFUN_LIB_NAME ${MATHFUN_NAME}_static) endif() if(NOT DEFINED CMAKE_INSTALL_LIBDIR) set(CMAKE_INSTALL_LIBDIR "lib") endif() if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Werror -std=gnu99") if(NOT(CMAKE_BUILD_TYPE STREQUAL "Debug")) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3") endif() if(NOT(CMAKE_COMPILER_IS_MINGW64)) # can't be pedantic for mingw64 because of format strings set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pedantic") endif() endif() if(NOT WIN32) find_library(M_LIBRARY NAMES m PATHS /usr/lib /usr/local/lib) if(M_LIBRARY) set(MATHFUN_PRIVATE_LIBS -l${M_LIBRARY}) else() message(STATUS "math library 'libm' not found") endif() else() # not needed on windows set(M_LIBRARY "") endif() # from libpng # Set a variable with CMake code which: # Creates a symlink from src to dest (if possible) or alternatively # copies if different. macro(mathfun_generate_symlink_code CODE SRC DEST) if(WIN32 AND NOT CYGWIN) set(_mathfun_gsc_message "Copying ${SRC} to ${DEST} if needed") set(_mathfun_gsc_operation "copy_if_different") else() set(_mathfun_gsc_message "Symlinking ${SRC} to ${DEST}") set(_mathfun_gsc_operation "create_symlink") endif() set(${CODE} " message(STATUS \"${_mathfun_gsc_message}\") execute_process(COMMAND \${CMAKE_COMMAND} -E ${_mathfun_gsc_operation} \"${SRC}\" \"${DEST}\") ") endmacro() configure_file(${CMAKE_CURRENT_SOURCE_DIR}/mathfun.pc.in ${CMAKE_CURRENT_BINARY_DIR}/${MATHFUN_NAME}.pc @ONLY) mathfun_generate_symlink_code(MATHFUN_PC_INSTALL_CODE ${CMAKE_CURRENT_BINARY_DIR}/${MATHFUN_NAME}.pc ${CMAKE_CURRENT_BINARY_DIR}/mathfun.pc) install(CODE ${MATHFUN_PC_INSTALL_CODE}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/mathfun.pc ${CMAKE_CURRENT_BINARY_DIR}/${MATHFUN_NAME}.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) # for config.h include_directories("${PROJECT_BINARY_DIR}/src") add_subdirectory(src) if(BUILD_EXAMPLES) add_subdirectory(examples) endif() if(BUILD_TESTS) include(CTest) enable_testing() set(CTEST_MEMORYCHECK_COMMAND "valgrind") set(CTEST_MEMORYCHECK_COMMAND_OPTIONS "-v --leak-check=full") add_subdirectory(test) endif() if(BUILD_DOCS) find_package(Doxygen) if(NOT DOXYGEN_FOUND) message(FATAL_ERROR "Doxygen is needed to build the documentation.") endif() configure_file(Doxyfile.in "${PROJECT_BINARY_DIR}/Doxyfile" @ONLY) add_custom_target(docs ALL COMMAND ${DOXYGEN_EXECUTABLE} ${PROJECT_BINARY_DIR}/Doxyfile SOURCES ${PROJECT_BINARY_DIR}/Doxyfile) endif() # uninstall target configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_BINARY_DIR}/cmake/cmake_uninstall.cmake") <file_sep>/test/test_mathfun.c #include <CUnit/Basic.h> #include <CUnit/TestRun.h> #include <mathfun.h> #include <stdlib.h> #define STRINGIFY(arg) STRINGIFY1(arg) #define STRINGIFY1(arg) STRINGIFY2(arg) #define STRINGIFY2(arg) #arg #define CONCATENATE(arg1, arg2) CONCATENATE1(arg1, arg2) #define CONCATENATE1(arg1, arg2) CONCATENATE2(arg1, arg2) #define CONCATENATE2(arg1, arg2) arg1##arg2 #define STRINGIFY_LIST_0() #define STRINGIFY_LIST_1(x) STRINGIFY(x) #define STRINGIFY_LIST_2(x, ...) STRINGIFY(x), STRINGIFY_LIST_1(__VA_ARGS__) #define STRINGIFY_LIST_3(x, ...) STRINGIFY(x), STRINGIFY_LIST_2(__VA_ARGS__) #define STRINGIFY_LIST_4(x, ...) STRINGIFY(x), STRINGIFY_LIST_3(__VA_ARGS__) #define STRINGIFY_LIST_5(x, ...) STRINGIFY(x), STRINGIFY_LIST_4(__VA_ARGS__) #define STRINGIFY_LIST_6(x, ...) STRINGIFY(x), STRINGIFY_LIST_5(__VA_ARGS__) #define STRINGIFY_LIST_7(x, ...) STRINGIFY(x), STRINGIFY_LIST_6(__VA_ARGS__) #define STRINGIFY_LIST_8(x, ...) STRINGIFY(x), STRINGIFY_LIST_7(__VA_ARGS__) #define STRINGIFY_LIST_(N, ...) CONCATENATE(STRINGIFY_LIST_, N)(__VA_ARGS__) #define STRINGIFY_LIST(...) STRINGIFY_LIST_(PP_NARG(__VA_ARGS__), __VA_ARGS__) #define MATHFUN_RUN_VARARGS_0() #define MATHFUN_RUN_VARARGS_1(x) STRINGIFY(x), x #define MATHFUN_RUN_VARARGS_2(x, ...) STRINGIFY(x), x, MATHFUN_RUN_VARARGS_1(__VA_ARGS__) #define MATHFUN_RUN_VARARGS_3(x, ...) STRINGIFY(x), x, MATHFUN_RUN_VARARGS_2(__VA_ARGS__) #define MATHFUN_RUN_VARARGS_4(x, ...) STRINGIFY(x), x, MATHFUN_RUN_VARARGS_3(__VA_ARGS__) #define MATHFUN_RUN_VARARGS_5(x, ...) STRINGIFY(x), x, MATHFUN_RUN_VARARGS_4(__VA_ARGS__) #define MATHFUN_RUN_VARARGS_6(x, ...) STRINGIFY(x), x, MATHFUN_RUN_VARARGS_5(__VA_ARGS__) #define MATHFUN_RUN_VARARGS_7(x, ...) STRINGIFY(x), x, MATHFUN_RUN_VARARGS_6(__VA_ARGS__) #define MATHFUN_RUN_VARARGS_8(x, ...) STRINGIFY(x), x, MATHFUN_RUN_VARARGS_7(__VA_ARGS__) #define MATHFUN_RUN_VARARGS_(N, ...) CONCATENATE(MATHFUN_RUN_VARARGS_, N)(__VA_ARGS__) #define MATHFUN_RUN_VARARGS(...) MATHFUN_RUN_VARARGS_(PP_NARG(__VA_ARGS__), __VA_ARGS__) #define PP_NARG(...) PP_NARG_(__VA_ARGS__,PP_RSEQ_N()) #define PP_NARG_(...) PP_ARG_N(__VA_ARGS__) #define PP_ARG_N(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N #define PP_RSEQ_N() 8,7,6,5,4,3,2,1,0 #define ASSERT_COMPILE_ERROR(expected, code, ...) \ const size_t argc = sizeof((const char *[]){__VA_ARGS__}) / sizeof(const char *); \ CU_ASSERT_EQUAL(test_compile_error((const char *[]){__VA_ARGS__}, argc, code), expected); #define ASSERT_COMPILE_ERROR_NOARGS(expected, code) \ CU_ASSERT_EQUAL(test_compile_error(NULL, 0, code), expected); #define ASSERT_EXEC(expr, cexpr, ...) \ { \ mathfun_error_p error = NULL; \ CU_ASSERT(issame(cexpr, MATHFUN_RUN(expr, &error, MATHFUN_RUN_VARARGS(__VA_ARGS__)))); \ CU_ASSERT(error == NULL); \ if (error) mathfun_error_log_and_cleanup(&error, stderr); \ mathfun fun; \ const char *argnames[] = {STRINGIFY_LIST(__VA_ARGS__)}; \ mathfun_compile(&fun, argnames, PP_NARG(__VA_ARGS__), expr, &error); \ CU_ASSERT(error == NULL); \ if (error) { \ mathfun_error_log_and_cleanup(&error, stderr); \ } \ else { \ CU_ASSERT(issame(cexpr, mathfun_call(&fun, &error, __VA_ARGS__))); \ CU_ASSERT(error == NULL); \ if (error) mathfun_error_log_and_cleanup(&error, stderr); \ const double args[] = {__VA_ARGS__}; \ CU_ASSERT(issame(cexpr, mathfun_acall(&fun, args, &error))); \ CU_ASSERT(error == NULL); \ if (error) mathfun_error_log_and_cleanup(&error, stderr); \ mathfun_cleanup(&fun); \ }\ } #define ASSERT_EXEC_DIRECT(expr, ...) ASSERT_EXEC(STRINGIFY(expr), expr, __VA_ARGS__) static bool issame(double x, double y) { return isnan(x) ? isnan(y) : x == y; } static bool test_compile_success(const char *argnames[], size_t argc, const char *code) { mathfun fun; mathfun_error_p error = NULL; bool compile_success = mathfun_compile(&fun, argnames, argc, code, &error); if (!compile_success) { mathfun_error_log_and_cleanup(&error, stderr); } mathfun_cleanup(&fun); return compile_success; } static enum mathfun_error_type test_compile_error(const char *argnames[], size_t argc, const char *code) { mathfun fun; mathfun_error_p error = NULL; enum mathfun_error_type error_type = mathfun_compile(&fun, argnames, argc, code, &error) ? MATHFUN_OK : mathfun_error_type(error); mathfun_error_cleanup(&error); mathfun_cleanup(&fun); return error_type; } static void test_compile() { const char *argnames[] = { "x" }; CU_ASSERT(test_compile_success(argnames, 1, "sin(x)")); } static void test_empty_argument_name() { ASSERT_COMPILE_ERROR(MATHFUN_ILLEGAL_NAME, "pi", ""); } static void test_empty_argument_name_with_spaces() { ASSERT_COMPILE_ERROR(MATHFUN_ILLEGAL_NAME, "pi", "foo "); } static void test_illegal_argument_name_true() { ASSERT_COMPILE_ERROR(MATHFUN_ILLEGAL_NAME, "pi", "true"); } static void test_illegal_argument_name_FalSE() { ASSERT_COMPILE_ERROR(MATHFUN_ILLEGAL_NAME, "pi", "FalSE"); } static void test_illegal_argument_name_Inf() { ASSERT_COMPILE_ERROR(MATHFUN_ILLEGAL_NAME, "pi", "Inf"); } static void test_illegal_argument_name_nan() { ASSERT_COMPILE_ERROR(MATHFUN_ILLEGAL_NAME, "pi", "nan"); } static void test_illegal_argument_name_number() { ASSERT_COMPILE_ERROR(MATHFUN_ILLEGAL_NAME, "pi", "123"); } static void test_illegal_argument_name_minus() { ASSERT_COMPILE_ERROR(MATHFUN_ILLEGAL_NAME, "pi", "-"); } static void test_duplicate_argument_name() { ASSERT_COMPILE_ERROR(MATHFUN_DUPLICATE_ARGUMENT, "bar", "foo", "bar", "foo"); } static void test_empty_expr() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, ""); } static void test_parser_expected_close_parenthesis_but_got_eof() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, "(5 + 2"); } static void test_parser_expected_close_parenthesis_but_got_something_else() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_EXPECTED_CLOSE_PARENTHESIS, "(5 + 2 3"); } static void test_parser_funct_expected_close_parenthesis_but_got_eof() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, "sin(5 + 2"); } static void test_parser_funct_expected_close_parenthesis_but_got_something_else() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_EXPECTED_CLOSE_PARENTHESIS, "sin(5 + 2 3"); } static void test_parser_undefined_reference_funct() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_UNDEFINED_REFERENCE, "foo()"); } static void test_parser_undefined_reference_var() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_UNDEFINED_REFERENCE, "bar"); } static void test_parser_not_a_function_but_an_argument() { ASSERT_COMPILE_ERROR(MATHFUN_PARSER_NOT_A_FUNCTION, "x()", "x"); } static void test_parser_not_a_function_but_a_const() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_NOT_A_FUNCTION, "pi()"); } static void test_parser_not_a_variable() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_NOT_A_VARIABLE, "sin"); } static void test_parser_illegal_number_of_arguments() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_ILLEGAL_NUMBER_OF_ARGUMENTS, "sin(pi,e)"); } static void test_parser_expected_number_but_got_something_else() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_EXPECTED_NUMBER, ".x"); } static void test_parser_expected_identifier_but_got_something_else() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_EXPECTED_IDENTIFIER, "$"); } static void test_parser_expected_colon_but_got_eof() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, "true ? pi "); } static void test_parser_expected_colon_but_got_something_else() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_PARSER_EXPECTED_COLON, "true ? pi e"); } static void test_parser_expected_dots_but_got_eof() { ASSERT_COMPILE_ERROR(MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, "x in 5", "x"); } static void test_parser_expected_dots_but_got_something_else() { ASSERT_COMPILE_ERROR(MATHFUN_PARSER_EXPECTED_DOTS, "x in 5 5", "x"); } static void test_parser_type_error_expected_number() { ASSERT_COMPILE_ERROR(MATHFUN_PARSER_TYPE_ERROR, "x in 1...5", "x"); } static void test_parser_type_error_expected_boolean() { ASSERT_COMPILE_ERROR(MATHFUN_PARSER_TYPE_ERROR, "x ? pi : e", "x"); } static void test_parser_trailing_garbage() { ASSERT_COMPILE_ERROR(MATHFUN_PARSER_TRAILING_GARBAGE, "x 5", "x"); } static void test_math_error_in_const_folding() { ASSERT_COMPILE_ERROR_NOARGS(MATHFUN_MATH_ERROR, "5 % 0"); } static void test_mod() { errno = 0; CU_ASSERT(issame(mathfun_mod(5.0, 0.0), NAN)); CU_ASSERT_EQUAL(errno, EDOM); errno = 0; CU_ASSERT(issame(mathfun_mod(9.0, 5.0), 4.0)); CU_ASSERT_EQUAL(errno, 0); errno = 0; CU_ASSERT(issame(mathfun_mod(-2.1, 5.2), 3.1)); CU_ASSERT_EQUAL(errno, 0); errno = 0; CU_ASSERT(issame(mathfun_mod(-8.0, -5.2), -2.8)); CU_ASSERT_EQUAL(errno, 0); errno = 0; CU_ASSERT(issame(mathfun_mod(9.0, -5.0), -1.0)); CU_ASSERT_EQUAL(errno, 0); errno = 0; CU_ASSERT(issame(mathfun_mod(INFINITY, 1.0), NAN)); CU_ASSERT_EQUAL(errno, EDOM); errno = 0; CU_ASSERT(issame(mathfun_mod(INFINITY, -1.0), -NAN)); CU_ASSERT_EQUAL(errno, EDOM); errno = 0; CU_ASSERT(issame(mathfun_mod(-INFINITY, 1.0), -NAN)); CU_ASSERT_EQUAL(errno, EDOM); } static void test_exec_sin_x() { const double x = M_PI_2; ASSERT_EXEC_DIRECT(sin(x), x); } static void test_exec_all() { const double x = M_PI_2; const double y = 1.0; const double z = 2.0; ASSERT_EXEC( "x in (-3e2 * y)...Inf && y == 1 || !(x <= pi_2 ? z >= 2 || x > NaN || y in -10..10 : z != -2 && z < x) ? x % z / 3 : -x ** y - z + +cos(5.5)", ((x >= (-3e2 * y) && x < INFINITY) && y == 1) || !(x <= M_PI_2 ? z >= 2 || x > NAN || (y >= -10 && y <= 10) : z != -2 && z < x) ? mathfun_mod(x, z) / 3 : pow(-x, y) - z + +cos(5.5), x, y, z); } static mathfun_value test_funct1(const mathfun_value args[]) { return (mathfun_value){ .number = args[0].number + args[1].number }; } static mathfun_value test_funct2(const mathfun_value args[]) { return (mathfun_value){ .number = args[0].number - args[1].number }; } static mathfun_value test_funct3(const mathfun_value args[]) { return (mathfun_value){ .number = args[0].number * args[1].number }; } #define TEST_CONTEXT \ mathfun_context ctx; \ mathfun_error_p error = NULL; \ CU_ASSERT(mathfun_context_init(&ctx, false, &error)); \ if (error) { \ mathfun_error_log_and_cleanup(&error, stderr); \ return; \ } #define TEST_CONTEXT_DEFAULTS \ mathfun_context ctx; \ mathfun_error_p error = NULL; \ CU_ASSERT(mathfun_context_init(&ctx, true, &error)); \ if (error) { \ mathfun_error_log_and_cleanup(&error, stderr); \ return; \ } static void test_define_funct() { TEST_CONTEXT; const mathfun_sig sig = {2, (mathfun_type[]){MATHFUN_NUMBER, MATHFUN_NUMBER}, MATHFUN_NUMBER}; CU_ASSERT(mathfun_context_define_funct(&ctx, "funct1", test_funct1, &sig, &error)); if (error) mathfun_error_log_and_cleanup(&error, stderr); mathfun_context_cleanup(&ctx); } static void test_define_const() { TEST_CONTEXT; CU_ASSERT(mathfun_context_define_const(&ctx, "const", 1.0, &error)); if (error) mathfun_error_log_and_cleanup(&error, stderr); mathfun_context_cleanup(&ctx); } static void test_define_multiple() { TEST_CONTEXT; const mathfun_sig sig = {2, (mathfun_type[]){MATHFUN_NUMBER, MATHFUN_NUMBER}, MATHFUN_NUMBER}; const mathfun_decl decls1[] = { { MATHFUN_DECL_CONST, "b", { .value = 2.0 } }, { MATHFUN_DECL_CONST, "a", { .value = 1.0 } }, { MATHFUN_DECL_FUNCT, "funct1", { .funct = { test_funct1, &sig } } }, { MATHFUN_DECL_FUNCT, "funct2", { .funct = { test_funct2, &sig } } }, { -1, NULL, { .value = 0 } } }; const mathfun_decl decls2[] = { { MATHFUN_DECL_CONST, "c", { .value = 3.0 } }, { MATHFUN_DECL_FUNCT, "funct3", { .funct = { test_funct3, &sig } } }, { -1, NULL, { .value = 0 } } }; CU_ASSERT(mathfun_context_define(&ctx, decls1, &error)); if (error) mathfun_error_log_and_cleanup(&error, stderr); CU_ASSERT(mathfun_context_define(&ctx, decls2, &error)); if (error) mathfun_error_log_and_cleanup(&error, stderr); mathfun_context_cleanup(&ctx); } static void test_define_defaults() { TEST_CONTEXT_DEFAULTS; mathfun_context_cleanup(&ctx); } static void test_get_funct() { TEST_CONTEXT_DEFAULTS; const mathfun_decl *decl = mathfun_context_get(&ctx, "sin"); CU_ASSERT(decl != NULL && decl->type == MATHFUN_DECL_FUNCT); mathfun_context_cleanup(&ctx); } static void test_get_const() { TEST_CONTEXT_DEFAULTS; const mathfun_decl *decl = mathfun_context_get(&ctx, "e"); CU_ASSERT(decl != NULL && decl->type == MATHFUN_DECL_CONST); mathfun_context_cleanup(&ctx); } static void test_get_funct_name() { TEST_CONTEXT; const mathfun_sig sig = {2, (mathfun_type[]){MATHFUN_NUMBER, MATHFUN_NUMBER}, MATHFUN_NUMBER}; CU_ASSERT(mathfun_context_define_funct(&ctx, "funct1", test_funct1, &sig, &error)); if (error) mathfun_error_log_and_cleanup(&error, stderr); const char *name = mathfun_context_funct_name(&ctx, test_funct1); CU_ASSERT(name != NULL && strcmp(name, "funct1") == 0); mathfun_context_cleanup(&ctx); } static void test_undefine() { TEST_CONTEXT_DEFAULTS; CU_ASSERT(mathfun_context_undefine(&ctx, "sin", &error)); if (error) mathfun_error_log_and_cleanup(&error, stderr); CU_ASSERT(mathfun_context_get(&ctx, "sin") == NULL); mathfun_context_cleanup(&ctx); } static void test_define_existing() { TEST_CONTEXT_DEFAULTS; const mathfun_sig sig = {2, (mathfun_type[]){MATHFUN_NUMBER, MATHFUN_NUMBER}, MATHFUN_NUMBER}; CU_ASSERT(!mathfun_context_define_funct(&ctx, "sin", test_funct1, &sig, &error)); CU_ASSERT_EQUAL(mathfun_error_type(error), MATHFUN_NAME_EXISTS); mathfun_error_cleanup(&error); CU_ASSERT(!mathfun_context_define_const(&ctx, "e", M_E, &error)); CU_ASSERT_EQUAL(mathfun_error_type(error), MATHFUN_NAME_EXISTS); mathfun_error_cleanup(&error); mathfun_context_cleanup(&ctx); } static void test_undefine_none_existing() { TEST_CONTEXT_DEFAULTS; CU_ASSERT(!mathfun_context_undefine(&ctx, "blargh", &error)); CU_ASSERT_EQUAL(mathfun_error_type(error), MATHFUN_NO_SUCH_NAME); mathfun_error_cleanup(&error); mathfun_context_cleanup(&ctx); } static void test_get_none_existing() { TEST_CONTEXT_DEFAULTS; CU_ASSERT(mathfun_context_get(&ctx, "blargh") == NULL); mathfun_context_cleanup(&ctx); } static void test_get_funct_name_none_existing() { TEST_CONTEXT_DEFAULTS; CU_ASSERT(mathfun_context_funct_name(&ctx, test_funct1) == NULL); mathfun_context_cleanup(&ctx); } CU_TestInfo compile_test_infos[] = { {"compile", test_compile}, {"empty argument name", test_empty_argument_name}, {"argument name with spaces",test_empty_argument_name_with_spaces}, {"illegal argument name: true", test_illegal_argument_name_true}, {"illegal argument name: FalSE", test_illegal_argument_name_FalSE}, {"illegal argument name: Inf", test_illegal_argument_name_Inf}, {"illegal argument name: nan", test_illegal_argument_name_nan}, {"illegal argument name: 123", test_illegal_argument_name_number}, {"illegal argument name: -", test_illegal_argument_name_minus}, {"duplicate argument name", test_duplicate_argument_name}, {"empty expression", test_empty_expr}, {"eof instead of )", test_parser_expected_close_parenthesis_but_got_eof}, {"missing )", test_parser_expected_close_parenthesis_but_got_something_else}, {"eof instead of ) in function call", test_parser_funct_expected_close_parenthesis_but_got_eof}, {"missing ) in function call", test_parser_funct_expected_close_parenthesis_but_got_something_else}, {"undefined reference (function)", test_parser_undefined_reference_funct}, {"undefined reference (const/argument)", test_parser_undefined_reference_var}, {"argument is not a function", test_parser_not_a_function_but_an_argument}, {"const is not a function", test_parser_not_a_function_but_a_const}, {"function is not a variable", test_parser_not_a_variable}, {"illegal number of arguments", test_parser_illegal_number_of_arguments}, {"illegal number", test_parser_expected_number_but_got_something_else}, {"not an identifier", test_parser_expected_identifier_but_got_something_else}, {"eof instead of :", test_parser_expected_colon_but_got_eof}, {"missing :", test_parser_expected_colon_but_got_something_else}, {"eof instead of ... (dots)", test_parser_expected_dots_but_got_eof}, {"missing ... (dots)", test_parser_expected_dots_but_got_something_else}, {"type error: expected number", test_parser_type_error_expected_number}, {"type error: expected boolean", test_parser_type_error_expected_boolean}, {"trailing garbage", test_parser_trailing_garbage}, {"math error in const folding", test_math_error_in_const_folding}, {NULL, NULL} }; CU_TestInfo exec_test_infos[] = { {"mathfun_mod", test_mod}, {"sin(x)", test_exec_sin_x}, {"expression with all operators", test_exec_all}, {NULL, NULL} }; CU_TestInfo context_test_infos[] = { {"define a function", test_define_funct}, {"define a constant", test_define_const}, {"define multiple references", test_define_multiple}, {"define defaults", test_define_defaults}, {"get declaration a function", test_get_funct}, {"get declaration a constant", test_get_const}, {"get name of a function", test_get_funct_name}, {"undefine a reference", test_undefine}, {"define same reference twice", test_define_existing}, {"undefine not existing reference", test_undefine_none_existing}, {"get declaration of not existing reference", test_get_none_existing}, {"get name of not existing function", test_get_funct_name_none_existing}, {NULL, NULL} }; CU_SuiteInfo test_suite_infos[] = { {"context", NULL, NULL, context_test_infos}, {"compile", NULL, NULL, compile_test_infos}, {"execute", NULL, NULL, exec_test_infos}, {NULL, NULL, NULL, NULL} }; int main() { if (CUE_SUCCESS != CU_initialize_registry()) { return CU_get_error(); } if (CUE_SUCCESS != CU_register_suites(test_suite_infos)) { CU_cleanup_registry(); return CU_get_error(); } CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); CU_ErrorCode error_code = CU_get_error(); unsigned int failures = CU_get_number_of_failures(); CU_cleanup_registry(); return error_code || failures; } <file_sep>/examples/dump.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <mathfun.h> int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "invalid number of arguments\n"); return 1; } const size_t funct_argc = argc - 2; mathfun_context ctx; mathfun fun; mathfun_error_p error = NULL; if (!mathfun_context_init(&ctx, true, &error)) { mathfun_error_log_and_cleanup(&error, stderr); return 1; } if (!mathfun_context_compile(&ctx, (const char**)argv + 1, funct_argc, argv[argc - 1], &fun, &error)) { mathfun_error_log_and_cleanup(&error, stderr); mathfun_context_cleanup(&ctx); return 1; } if (!mathfun_dump(&fun, stdout, &ctx, &error)) { mathfun_error_log_and_cleanup(&error, stderr); mathfun_cleanup(&fun); mathfun_context_cleanup(&ctx); return 1; } mathfun_cleanup(&fun); mathfun_context_cleanup(&ctx); return 0; } <file_sep>/test/CMakeLists.txt find_package(PkgConfig) pkg_check_modules(CUNIT REQUIRED cunit) include_directories("${PROJECT_SOURCE_DIR}/src") add_executable(test_mathfun test_mathfun.c) target_link_libraries(test_mathfun ${MATHFUN_LIB_NAME} ${CUNIT_LIBRARIES}) add_test(test_mathfun ${CMAKE_CURRENT_BINARY_DIR}/test_mathfun) add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND} DEPENDS test_mathfun) <file_sep>/src/mathfun.h /** * @file mathfun.h * @author <NAME> * @date October, 2013 * @brief Evaluate simple mathematical functions. */ #ifndef MATHFUN_H__ #define MATHFUN_H__ #pragma once #include <stdint.h> #include <stdio.h> #include <stdarg.h> #include <stdbool.h> #include <math.h> #include "config.h" #include "export.h" #if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) # define MATHFUN_LOCAL #else # if __GNUC__ >= 4 # define MATHFUN_LOCAL __attribute__ ((visibility ("hidden"))) # else # define MATHFUN_LOCAL # endif #endif /** Test if given mathfun_error_type is a parser error. * * @param ERROR The #error_type. * @return true if ERROR is a parser error type, false otherwise. */ #define MATHFUN_IS_PARSER_ERROR(ERROR) ( \ (ERROR) >= MATHFUN_PARSER_EXPECTED_CLOSE_PARENTHESIS && \ (ERROR) <= MATHFUN_PARSER_TRAILING_GARBAGE) /** Parse and run a function expression. * * Macro wrapper for mathfun_run() that ensures the existence of the terminating NULL. * * @param code The function expression. * @param error A pointer to an error handle. * @return The result of the execution. */ #ifdef __GNUC__ # define MATHFUN_RUN(code, error, ...) mathfun_run(code, error, ##__VA_ARGS__, NULL) #else # define MATHFUN_RUN(code, error, ...) mathfun_run(code, error, __VA_ARGS__, NULL) #endif #ifdef __cplusplus extern "C" { #endif /** Type used for the "registers" of the interpreter. */ typedef union mathfun_value { double number; ///< numeric value bool boolean; ///< boolean value } mathfun_value; /** Type enum. * * E.g. used in #mathfun_sig. */ typedef enum mathfun_type { MATHFUN_NUMBER, ///< value is number (double) MATHFUN_BOOLEAN ///< value is boolean (bool) } mathfun_type; /** Function signature. * * @see mathfun_context_define_funct() */ typedef struct mathfun_sig { size_t argc; ///< number of arguments mathfun_type *argtypes; ///< array of argument types mathfun_type rettype; ///< return type } mathfun_sig; /** Function type for functions to be registered with a #mathfun_context. */ typedef mathfun_value (*mathfun_binding_funct)(const mathfun_value args[]); /** Error code as returned by mathfun_error_type(mathfun_error_p error) */ enum mathfun_error_type { MATHFUN_OK = 0, ///< no error occured MATHFUN_IO_ERROR, ///< error while writing to file MATHFUN_OUT_OF_MEMORY, ///< memory allocation failed MATHFUN_MATH_ERROR, ///< a math error occured, like x % 0 MATHFUN_C_ERROR, ///< a C error occured (errno is set) MATHFUN_ILLEGAL_NAME, ///< a illegal argument/function/constant name was used MATHFUN_DUPLICATE_ARGUMENT, ///< a argument name occured more than once in the list of arguments MATHFUN_NAME_EXISTS, ///< a constant/function with given name already exists MATHFUN_NO_SUCH_NAME, ///< no constant/function with given name exists MATHFUN_TOO_MANY_ARGUMENTS, ///< number of arguments to big MATHFUN_EXCEEDS_MAX_FRAME_SIZE, ///< frame size of compiled function exceeds maximum MATHFUN_INTERNAL_ERROR, ///< internal error (e.g. unknown bytecode) MATHFUN_PARSER_EXPECTED_CLOSE_PARENTHESIS, ///< expected ')' but got something else MATHFUN_PARSER_UNDEFINED_REFERENCE, ///< undefined reference MATHFUN_PARSER_NOT_A_FUNCTION, ///< reference does not define a function (but a constant or argument) MATHFUN_PARSER_NOT_A_VARIABLE, ///< reference does not define a constant or argument (but a function) MATHFUN_PARSER_ILLEGAL_NUMBER_OF_ARGUMENTS, ///< function called with an illegal number of arguments MATHFUN_PARSER_EXPECTED_NUMBER, ///< expected a number but got something else MATHFUN_PARSER_EXPECTED_IDENTIFIER, ///< expected an identifier but got something else MATHFUN_PARSER_EXPECTED_COLON, ///< expected ':' but got something else MATHFUN_PARSER_EXPECTED_DOTS, ///< expected '..' or '...' but got something else MATHFUN_PARSER_TYPE_ERROR, ///< expression with wrong type for this position MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, ///< unexpected end of input MATHFUN_PARSER_TRAILING_GARBAGE ///< garbage at the end of input }; /** Declaration type enum. * @see #mathfun_decl */ enum mathfun_decl_type { MATHFUN_DECL_CONST, ///< reference declares a constant MATHFUN_DECL_FUNCT ///< reference declares a function }; struct mathfun_decl { enum mathfun_decl_type type; ///< type of the declared reference const char *name; ///< name of the declared reference union { double value; ///< numeric value struct { mathfun_binding_funct funct; ///< function pointer const mathfun_sig *sig; ///< function signature } funct; ///< function info } decl; ///< declaration info }; struct mathfun_error; /** Function/constant declaration. * @see mathfun_context_define() */ typedef struct mathfun_decl mathfun_decl; /** Object that holds function and constant definitions. */ typedef struct mathfun_context mathfun_context; /** Compiled matfun function expression. */ typedef struct mathfun mathfun; /** Error handle. * * A pointer to this type (so a pointer to a pointer) is used as argument type of * every function that can cause an error. If the function failes the refered pointer * will be set to an error object, describing the error. This object might be newly * allocated or a constant global object (e.g. in case of #MATHFUN_OUT_OF_MEMORY). * In case you don't care about errors you can alyways pass NULL instead. * * Pelase initialize error handles with NULL. * * To free the object use mathfun_error_cleanup() or mathfun_error_log_and_cleanup(), * which also sets the refered error handle to NULL again. * @code mathfun_error_p error = NULL; double value = mathfun_run("sin(x) + cos(y)", &error, "x", 1.2, "y", 3.4, NULL); if (error) { mathfun_error_log_and_cleanup(&error, stderr); } @endcode */ typedef const struct mathfun_error *mathfun_error_p; struct mathfun_context { mathfun_decl *decls; size_t decl_capacity; size_t decl_used; }; #define MATHFUN_CONTEXT_INIT { .decls = NULL, .decl_capacity = 0, .decl_used = 0 } struct mathfun { size_t argc; size_t framesize; void *code; }; #define MATHFUN_INIT { .argc = 0, .framesize = 0, .code = NULL } /** Initialize a mathfun_context. * * @param ctx A pointer to a #mathfun_context * @param define_default If true then a lot of default functions (mainly from <math.h>) and * constans will be defined in the math_context. See mathfun_context_define_default() for more details. * @param error A pointer to an error handle. * @return true on success, false if an error occured. */ MATHFUN_EXPORT bool mathfun_context_init(mathfun_context *ctx, bool define_default, mathfun_error_p *error); /** Frees allocated resources. * @param ctx A pointer to a #mathfun_context */ MATHFUN_EXPORT void mathfun_context_cleanup(mathfun_context *ctx); /** Define default set of functions and constants. * * <strong>Functions:</strong> * * - bool isnan(double x) * - bool isfinite(double x) * - bool isnormal(double x) * - bool isinf(double x) * - bool isgreater(double x, double y) * - bool isgreaterequal(double x, double y) * - bool isless(double x, double y) * - bool islessequal(double x, double y) * - bool islessgreater(double x, double y) * - bool isunordered(double x, double y) * - bool signbit(double x) * - double acos(double x) * - double acosh(double x) * - double asin(double x) * - double asinh(double x) * - double atan(double x) * - double atan2(double y, double x) * - double atanh(double x) * - double cbrt(double x) * - double ceil(double x) * - double copysign(double x, double y) * - double cos(double x) * - double cosh(double x) * - double erf(double x) * - double erfc(double x) * - double exp(double x) * - double exp2(double x) * - double expm1(double x) * - double abs(double x) unsing fabs(double x) * - double fdim(double x, double y) * - double floor(double x) * - double fma(double x, double y, double z) * - double fmod(double x, double y) * - double max(double x, double y) equivalent to fmax(double x, double y) * - double min(double x, double y) equivalent to fmin(double x, double y) * - double hypot(double x, double y) * - double j0(double x) * - double j1(double x) * - double jn(int n, double x) * - double ldexp(double x, int exp) * - double log(double x) * - double log10(double x) * - double log1p(double x) * - double log2(double x) * - double logb(double x) * - double nearbyint(double x) * - double nextafter(double x, double y) * - double nexttoward(double x, double y) * - double remainder(double x, double y) * - double round(double x) * - double scalbln(double x, long int exp) * - double sin(double x) * - double sinh(double x) * - double sqrt(double x) * - double tan(double x) * - double tanh(double x) * - double gamma(double x) using tgamma(double x) * - double trunc(double x) * - double y0(double x) * - double y1(double x) * - double yn(int n, double x) * - double sign(double x) * * See man <math.h> for a documentation on these functions, except for sign(). * * <strong>double sign(double x)</strong> * * Returns sign of x, idecating whether x is positive, negative or zero. * * - If x is +NaN, the result is +NaN. * - If x is -NaN, the result is -NaN. * - If x is +0, the result is +0. * - If x is -0, the result is -0. * - If x is negative and not -0 or -NaN, the result is -1. * - If x is positive and not +0 or +NaN, the result is +1. * * <strong>Constants:</strong> * * - e = 2.7182818284590452354 * - log2e = log2(e) * - log10e = log10(e) * - ln2 = log(2) * - ln10 = log(10) * - pi = 3.14159265358979323846 * - tau = pi * 2 * - pi_2 = pi / 2 * - pi_4 = pi / 4 * - _1_pi = 1 / pi * - _2_pi = 2 / pi * - _2_sqrtpi = 2 / sqrt(pi) * - sqrt2 = sqrt(2) * - sqrt1_2 = 1 / sqrt(2) * * @param ctx A pointer to a #mathfun_context * @param error A pointer to an error handle. Possible errors: #MATHFUN_OUT_OF_MEMORY and #MATHFUN_NAME_EXISTS * @return true on success, false if an error occured. */ MATHFUN_EXPORT bool mathfun_context_define_default(mathfun_context *ctx, mathfun_error_p *error); /** Define multiple functions and constants at once. * @param ctx A pointer to a #mathfun_context * @param decls A array of declarations. The array is terminated by a declaration with a NULL pointer for it's name. * @param error A pointer to an error handle. Possible errors: #MATHFUN_OUT_OF_MEMORY and #MATHFUN_NAME_EXISTS * @return true on success, false if an error occured. */ MATHFUN_EXPORT bool mathfun_context_define(mathfun_context *ctx, const mathfun_decl decls[], mathfun_error_p *error); /** Define a constant value. * @param ctx A pointer to a #mathfun_context * @param name The name of the constant. * @param value The value of the constant. * @param error A pointer to an error handle. Possible errors: #MATHFUN_OUT_OF_MEMORY and #MATHFUN_NAME_EXISTS * @return true on success, false if an error occured. */ MATHFUN_EXPORT bool mathfun_context_define_const(mathfun_context *ctx, const char *name, double value, mathfun_error_p *error); /** Define a constant function. * @param ctx A pointer to a #mathfun_context * @param name The name of the function. * @param funct A function pointer. * @param sig The function signature. sig has to have a lifetime of at least as long as ctx. * @param error A pointer to an error handle. Possible errors: #MATHFUN_OUT_OF_MEMORY and #MATHFUN_NAME_EXISTS * @return true on success, false if an error occured. */ MATHFUN_EXPORT bool mathfun_context_define_funct(mathfun_context *ctx, const char *name, mathfun_binding_funct funct, const mathfun_sig *sig, mathfun_error_p *error); /** Find the name of a given function. * @param ctx A pointer to a #mathfun_context * @param funct Function pointer to the function that shall be found. * @return The name of the function or NULL if not found. */ MATHFUN_EXPORT const char *mathfun_context_funct_name(const mathfun_context *ctx, mathfun_binding_funct funct); /** Get declaration of a reference by name. * @param ctx A pointer to a #mathfun_context * @param name The name of the function/constant. * @return Pointer to the #mathfun_decl or NULL if no such reference exists. */ MATHFUN_EXPORT const mathfun_decl *mathfun_context_get(const mathfun_context *ctx, const char *name); /** Removes a function/constant from the context. * @param ctx A pointer to a #mathfun_context * @param name The name of the function/constant. * @param error A pointer to an error handle. Possible errors: #MATHFUN_NO_SUCH_NAME * @return true on success, false if an error occured. */ MATHFUN_EXPORT bool mathfun_context_undefine(mathfun_context *ctx, const char *name, mathfun_error_p *error); /** Compile a function expression to byte code. * * @param ctx A pointer to a #mathfun_context * @param argnames Array of argument names of the function expression * @param argc Number of arguments * @param code The function expression * @param fun Target byte code object (will be initialized in any case) * @param error A pointer to an error handle. Possible errors: #MATHFUN_ILLEGAL_NAME, #MATHFUN_DUPLICATE_ARGUMENT, * #MATHFUN_OUT_OF_MEMORY, #MATHFUN_MATH_ERROR, #MATHFUN_TOO_MANY_ARGUMENTS, #MATHFUN_EXCEEDS_MAX_FRAME_SIZE, * MATHFUN_PARSER_* * @return true on success, false if an error occured. */ MATHFUN_EXPORT bool mathfun_context_compile(const mathfun_context *ctx, const char *argnames[], size_t argc, const char *code, mathfun *fun, mathfun_error_p *error); /** Frees allocated resources. * * @param fun A pointer to a #mathfun object */ MATHFUN_EXPORT void mathfun_cleanup(mathfun *fun); /** Compile function expression to byte code using default function/constant definitions. * * @param fun Target byte code object (will be initialized in any case) * @param argnames Array of argument names of the function expression * @param argc Number of arguments * @param code The function expression * @param error A pointer to an error handle. Possible errors: #MATHFUN_ILLEGAL_NAME, #MATHFUN_DUPLICATE_ARGUMENT, * #MATHFUN_OUT_OF_MEMORY, #MATHFUN_MATH_ERROR, #MATHFUN_TOO_MANY_ARGUMENTS, #MATHFUN_EXCEEDS_MAX_FRAME_SIZE, * MATHFUN_PARSER_* * @return true on success, false if an error occured. */ MATHFUN_EXPORT bool mathfun_compile(mathfun *fun, const char *argnames[], size_t argc, const char *code, mathfun_error_p *error); /** Execute a compiled function expression. * * @param fun Byte code object to execute * @param error A pointer to an error handle. Possible errors: #MATHFUN_OUT_OF_MEMORY, #MATHFUN_MATH_ERROR, * #MATHFUN_C_ERROR (depending on the functions called by the expression) * @return The result of the evaluation. */ MATHFUN_EXPORT double mathfun_call(const mathfun *fun, mathfun_error_p *error, ...); /** Execute a compiled function expression. * * @param fun Byte code object to execute * @param args Array of argument values * @param error A pointer to an error handle. Possible errors: #MATHFUN_OUT_OF_MEMORY, #MATHFUN_MATH_ERROR, * #MATHFUN_C_ERROR (depending on the functions called by the expression) * @return The result of the evaluation. */ MATHFUN_EXPORT double mathfun_acall(const mathfun *fun, const double args[], mathfun_error_p *error); /** Execute a compiled function expression. * * @param fun Byte code object to execute * @param ap Variable argument list pointer * @param error A pointer to an error handle. Possible errors: #MATHFUN_OUT_OF_MEMORY, #MATHFUN_MATH_ERROR, * #MATHFUN_C_ERROR (depending on the functions called by the expression) * @return The result of the evaluation */ MATHFUN_EXPORT double mathfun_vcall(const mathfun *fun, va_list ap, mathfun_error_p *error); /** Execute a compiled function expression. * * This is a low-level function used by mathfun_call(), mathfun_acall() and mathfun_vcall(). Use it if you need * high speed and allocate the execution frame yourself (e.g. to re-use it over many calls). * * The frame has to have mathfun->framesize elements. The first mathfun->argc elements shall be initialized * with the arguments of the function expression. There are no guarantees about what elements will be overwritten * after the execution. * * Sets errno when a math error occurs. * * @param fun The compiled function expression * @param frame The functions execution frame * @return The result of the execution */ MATHFUN_EXPORT double mathfun_exec(const mathfun *fun, mathfun_value frame[]) __attribute__((__noinline__,__noclone__)); /** Dump text representation of byte code. * * @param fun The compiled function expression * @param stream The output FILE * @param ctx A pointer to a #mathfun_context. Can be NULL. * @param error A pointer to an error handle. Possible errors: #MATHFUN_IO_ERROR * @return true on success, false if an error occured. */ MATHFUN_EXPORT bool mathfun_dump(const mathfun *fun, FILE *stream, const mathfun_context *ctx, mathfun_error_p *error); /** Parse and run a function expression. * * This doesn't optimize or compile the expression but instead directly runs on the abstract syntax tree. * Use this for one-time executions. * @code double mathfun_run(const char *code, mathfun_error_p *error, [const char *argname, double argvalue]..., NULL); @endcode * * @param code The function expression. * @param error A pointer to an error handle. * @return The result of the execution. */ MATHFUN_EXPORT double mathfun_run(const char *code, mathfun_error_p *error, ...); /** Parse and run function expression. * * This doesn't optimize or compile the expression but instead directly runs on the abstract syntax tree. * Use this for one-time executions. * * @param argnames Array of argument names. * @param argc Number of arguments. * @param code The function expression. * @param args The argument values. * @param error A pointer to an error handle. Possible errors: #MATHFUN_ILLEGAL_NAME, #MATHFUN_DUPLICATE_ARGUMENT, * #MATHFUN_OUT_OF_MEMORY, #MATHFUN_MATH_ERROR, #MATHFUN_TOO_MANY_ARGUMENTS, #MATHFUN_EXCEEDS_MAX_FRAME_SIZE, * MATHFUN_PARSER_* * @return The result of the execution. */ MATHFUN_EXPORT double mathfun_arun(const char *argnames[], size_t argc, const char *code, const double args[], mathfun_error_p *error); /** Get mathfun_error_type of error. * * If error is NULL, derive mathfun_error_type from errno. * * @param error Error handle * @return a mathfun_error_type */ MATHFUN_EXPORT enum mathfun_error_type mathfun_error_type(mathfun_error_p error); /** Get C error number of error. * * If error is NULL, return errno. * * @param error Error handle * @return a C error number */ MATHFUN_EXPORT int mathfun_error_errno(mathfun_error_p error); /** Get line number of a parser error. * * @param error Error handle * @return line number of parser error or 0 if error isn't a parser error. */ MATHFUN_EXPORT size_t mathfun_error_lineno(mathfun_error_p error); /** Get column of a parser error. * * @param error Error handle * @return column of parser error or 0 if error isn't a parser error. */ MATHFUN_EXPORT size_t mathfun_error_column(mathfun_error_p error); /** Get index of parser error in function expression code string. * * @param error Error handle * @return index of parser error or 0 if error isn't a parser error. */ MATHFUN_EXPORT size_t mathfun_error_errpos(mathfun_error_p error); /** Get length of erroneous area in function expression code string. * * @param error Error handle * @return length of error or 0 if error isn't a parser error. */ MATHFUN_EXPORT size_t mathfun_error_errlen(mathfun_error_p error); /** Print error message. * * @param error Error handle * @param stream Output stream */ MATHFUN_EXPORT void mathfun_error_log(mathfun_error_p error, FILE *stream); /** Print error message and free error object. * * @param error Error handle * @param stream Output stream */ MATHFUN_EXPORT void mathfun_error_log_and_cleanup(mathfun_error_p *error, FILE *stream); /** Free error object and set error handle to NULL. * * @param error Error handle */ MATHFUN_EXPORT void mathfun_error_cleanup(mathfun_error_p *error); /** Test if argument is a valid name. * * Valid names start with a letter or '_' and then have an arbitrary number of more * letters, numbers or '_'. To test for letters isalpha() is used, to test for letters or * numbers isalnum() is used. * * @return true if argument is a valid name, false otherwise */ MATHFUN_EXPORT bool mathfun_valid_name(const char *name); /** Modulo division using the Euclidean definition. * * The remainder is always positive or 0. This is the way the % operator works * in the mathfun expression language. * * If y is 0, a NaN is returned and errno is set to EDOM (domain error). * * @param x The dividend * @param y The divisor * @return The remainder */ MATHFUN_EXPORT double mathfun_mod(double x, double y); #ifdef __cplusplus } #endif #endif <file_sep>/src/bindings.c #include "mathfun_intern.h" static const mathfun_sig mathfun_bsig1 = { 1, (mathfun_type[]){MATHFUN_NUMBER}, MATHFUN_BOOLEAN }; static const mathfun_sig mathfun_bsig2 = { 2, (mathfun_type[]){MATHFUN_NUMBER, MATHFUN_NUMBER}, MATHFUN_BOOLEAN }; static const mathfun_sig mathfun_sig1 = { 1, (mathfun_type[]){MATHFUN_NUMBER}, MATHFUN_NUMBER }; static const mathfun_sig mathfun_sig2 = { 2, (mathfun_type[]){MATHFUN_NUMBER, MATHFUN_NUMBER}, MATHFUN_NUMBER }; static const mathfun_sig mathfun_sig3 = { 3, (mathfun_type[]){MATHFUN_NUMBER, MATHFUN_NUMBER, MATHFUN_NUMBER}, MATHFUN_NUMBER }; static mathfun_value mathfun_funct_isnan(const mathfun_value args[]) { return (mathfun_value){ .boolean = isnan(args[0].number) }; } static mathfun_value mathfun_funct_isfinite(const mathfun_value args[]) { return (mathfun_value){ .boolean = isfinite(args[0].number) }; } static mathfun_value mathfun_funct_isnormal(const mathfun_value args[]) { return (mathfun_value){ .boolean = isnormal(args[0].number) }; } static mathfun_value mathfun_funct_isinf(const mathfun_value args[]) { return (mathfun_value){ .boolean = isinf(args[0].number) }; } static mathfun_value mathfun_funct_isgreater(const mathfun_value args[]) { return (mathfun_value){ .boolean = isgreater(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_isgreaterequal(const mathfun_value args[]) { return (mathfun_value){ .boolean = isgreaterequal(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_isless(const mathfun_value args[]) { return (mathfun_value){ .boolean = isless(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_islessequal(const mathfun_value args[]) { return (mathfun_value){ .boolean = islessequal(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_islessgreater(const mathfun_value args[]) { return (mathfun_value){ .boolean = islessgreater(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_isunordered(const mathfun_value args[]) { return (mathfun_value){ .boolean = isunordered(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_signbit(const mathfun_value args[]) { return (mathfun_value){ .boolean = signbit(args[0].number) != 0 }; } static mathfun_value mathfun_funct_acos(const mathfun_value args[]) { return (mathfun_value){ .number = acos(args[0].number) }; } static mathfun_value mathfun_funct_acosh(const mathfun_value args[]) { return (mathfun_value){ .number = acosh(args[0].number) }; } static mathfun_value mathfun_funct_asin(const mathfun_value args[]) { return (mathfun_value){ .number = asin(args[0].number) }; } static mathfun_value mathfun_funct_asinh(const mathfun_value args[]) { return (mathfun_value){ .number = asinh(args[0].number) }; } static mathfun_value mathfun_funct_atan(const mathfun_value args[]) { return (mathfun_value){ .number = atan(args[0].number) }; } static mathfun_value mathfun_funct_atan2(const mathfun_value args[]) { return (mathfun_value){ .number = atan2(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_atanh(const mathfun_value args[]) { return (mathfun_value){ .number = atanh(args[0].number) }; } static mathfun_value mathfun_funct_cbrt(const mathfun_value args[]) { return (mathfun_value){ .number = cbrt(args[0].number) }; } static mathfun_value mathfun_funct_ceil(const mathfun_value args[]) { return (mathfun_value){ .number = ceil(args[0].number) }; } static mathfun_value mathfun_funct_copysign(const mathfun_value args[]) { return (mathfun_value){ .number = copysign(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_cos(const mathfun_value args[]) { return (mathfun_value){ .number = cos(args[0].number) }; } static mathfun_value mathfun_funct_cosh(const mathfun_value args[]) { return (mathfun_value){ .number = cosh(args[0].number) }; } static mathfun_value mathfun_funct_erf(const mathfun_value args[]) { return (mathfun_value){ .number = erf(args[0].number) }; } static mathfun_value mathfun_funct_erfc(const mathfun_value args[]) { return (mathfun_value){ .number = erfc(args[0].number) }; } static mathfun_value mathfun_funct_exp(const mathfun_value args[]) { return (mathfun_value){ .number = exp(args[0].number) }; } static mathfun_value mathfun_funct_exp2(const mathfun_value args[]) { return (mathfun_value){ .number = exp2(args[0].number) }; } static mathfun_value mathfun_funct_expm1(const mathfun_value args[]) { return (mathfun_value){ .number = expm1(args[0].number) }; } static mathfun_value mathfun_funct_abs(const mathfun_value args[]) { return (mathfun_value){ .number = fabs(args[0].number) }; } static mathfun_value mathfun_funct_fdim(const mathfun_value args[]) { return (mathfun_value){ .number = fdim(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_floor(const mathfun_value args[]) { return (mathfun_value){ .number = floor(args[0].number) }; } static mathfun_value mathfun_funct_fma(const mathfun_value args[]) { return (mathfun_value){ .number = fma(args[0].number, args[1].number, args[2].number) }; } static mathfun_value mathfun_funct_fmod(const mathfun_value args[]) { return (mathfun_value){ .number = fmod(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_max(const mathfun_value args[]) { double x = args[0].number; double y = args[1].number; return (mathfun_value){ .number = (x >= y || isnan(x)) ? x : y }; // return (mathfun_value){ .number = fmax(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_min(const mathfun_value args[]) { double x = args[0].number; double y = args[1].number; return (mathfun_value){ .number = (x <= y || isnan(y)) ? x : y }; // return (mathfun_value){ .number = fmin(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_hypot(const mathfun_value args[]) { return (mathfun_value){ .number = hypot(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_j0(const mathfun_value args[]) { return (mathfun_value){ .number = j0(args[0].number) }; } static mathfun_value mathfun_funct_j1(const mathfun_value args[]) { return (mathfun_value){ .number = j1(args[0].number) }; } static mathfun_value mathfun_funct_jn(const mathfun_value args[]) { return (mathfun_value){ .number = jn((int)args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_ldexp(const mathfun_value args[]) { return (mathfun_value){ .number = ldexp(args[0].number, (int)args[1].number) }; } static mathfun_value mathfun_funct_log(const mathfun_value args[]) { return (mathfun_value){ .number = log(args[0].number) }; } static mathfun_value mathfun_funct_log10(const mathfun_value args[]) { return (mathfun_value){ .number = log10(args[0].number) }; } static mathfun_value mathfun_funct_log1p(const mathfun_value args[]) { return (mathfun_value){ .number = log1p(args[0].number) }; } static mathfun_value mathfun_funct_log2(const mathfun_value args[]) { return (mathfun_value){ .number = log2(args[0].number) }; } static mathfun_value mathfun_funct_logb(const mathfun_value args[]) { return (mathfun_value){ .number = logb(args[0].number) }; } static mathfun_value mathfun_funct_nearbyint(const mathfun_value args[]) { return (mathfun_value){ .number = nearbyint(args[0].number) }; } static mathfun_value mathfun_funct_nextafter(const mathfun_value args[]) { return (mathfun_value){ .number = nextafter(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_nexttoward(const mathfun_value args[]) { return (mathfun_value){ .number = nexttoward(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_remainder(const mathfun_value args[]) { return (mathfun_value){ .number = remainder(args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_round(const mathfun_value args[]) { return (mathfun_value){ .number = round(args[0].number) }; } static mathfun_value mathfun_funct_scalbln(const mathfun_value args[]) { return (mathfun_value){ .number = scalbln(args[0].number, (long)args[1].number) }; } static mathfun_value mathfun_funct_sin(const mathfun_value args[]) { return (mathfun_value){ .number = sin(args[0].number) }; } static mathfun_value mathfun_funct_sinh(const mathfun_value args[]) { return (mathfun_value){ .number = sinh(args[0].number) }; } static mathfun_value mathfun_funct_sqrt(const mathfun_value args[]) { return (mathfun_value){ .number = sqrt(args[0].number) }; } static mathfun_value mathfun_funct_tan(const mathfun_value args[]) { return (mathfun_value){ .number = tan(args[0].number) }; } static mathfun_value mathfun_funct_tanh(const mathfun_value args[]) { return (mathfun_value){ .number = tanh(args[0].number) }; } static mathfun_value mathfun_funct_gamma(const mathfun_value args[]) { return (mathfun_value){ .number = tgamma(args[0].number) }; } static mathfun_value mathfun_funct_trunc(const mathfun_value args[]) { return (mathfun_value){ .number = trunc(args[0].number) }; } static mathfun_value mathfun_funct_y0(const mathfun_value args[]) { return (mathfun_value){ .number = y0(args[0].number) }; } static mathfun_value mathfun_funct_y1(const mathfun_value args[]) { return (mathfun_value){ .number = y1(args[0].number) }; } static mathfun_value mathfun_funct_yn(const mathfun_value args[]) { return (mathfun_value){ .number = yn((int)args[0].number, args[1].number) }; } static mathfun_value mathfun_funct_sign(const mathfun_value args[]) { const double x = args[0].number; return (mathfun_value){ .number = isnan(x) || x == 0.0 ? x : copysign(1.0, x) }; } bool mathfun_context_define_default(mathfun_context *ctx, mathfun_error_p *error) { const mathfun_decl decls[] = { // Constants { MATHFUN_DECL_CONST, "e", { .value = M_E } }, { MATHFUN_DECL_CONST, "log2e", { .value = M_LOG2E } }, { MATHFUN_DECL_CONST, "log10e", { .value = M_LOG10E } }, { MATHFUN_DECL_CONST, "ln2", { .value = M_LN2 } }, { MATHFUN_DECL_CONST, "ln10", { .value = M_LN10 } }, { MATHFUN_DECL_CONST, "pi", { .value = M_PI } }, { MATHFUN_DECL_CONST, "tau", { .value = M_TAU } }, { MATHFUN_DECL_CONST, "pi_2", { .value = M_PI_2 } }, { MATHFUN_DECL_CONST, "pi_4", { .value = M_PI_4 } }, { MATHFUN_DECL_CONST, "_1_pi", { .value = M_1_PI } }, { MATHFUN_DECL_CONST, "_2_pi", { .value = M_2_PI } }, { MATHFUN_DECL_CONST, "_2_sqrtpi", { .value = M_2_SQRTPI } }, { MATHFUN_DECL_CONST, "sqrt2", { .value = M_SQRT2 } }, { MATHFUN_DECL_CONST, "sqrt1_2", { .value = M_SQRT1_2 } }, // Functions { MATHFUN_DECL_FUNCT, "isnan", { .funct = { mathfun_funct_isnan, &mathfun_bsig1 } } }, { MATHFUN_DECL_FUNCT, "isfinite", { .funct = { mathfun_funct_isfinite, &mathfun_bsig1 } } }, { MATHFUN_DECL_FUNCT, "isnormal", { .funct = { mathfun_funct_isnormal, &mathfun_bsig1 } } }, { MATHFUN_DECL_FUNCT, "isinf", { .funct = { mathfun_funct_isinf, &mathfun_bsig1 } } }, { MATHFUN_DECL_FUNCT, "isgreater", { .funct = { mathfun_funct_isgreater, &mathfun_bsig2 } } }, { MATHFUN_DECL_FUNCT, "isgreaterequal", { .funct = { mathfun_funct_isgreaterequal, &mathfun_bsig2 } } }, { MATHFUN_DECL_FUNCT, "isless", { .funct = { mathfun_funct_isless, &mathfun_bsig2 } } }, { MATHFUN_DECL_FUNCT, "islessequal", { .funct = { mathfun_funct_islessequal, &mathfun_bsig2 } } }, { MATHFUN_DECL_FUNCT, "islessgreater", { .funct = { mathfun_funct_islessgreater, &mathfun_bsig2 } } }, { MATHFUN_DECL_FUNCT, "isunordered", { .funct = { mathfun_funct_isunordered, &mathfun_bsig2 } } }, { MATHFUN_DECL_FUNCT, "signbit", { .funct = { mathfun_funct_signbit, &mathfun_bsig2 } } }, { MATHFUN_DECL_FUNCT, "acos", { .funct = { mathfun_funct_acos, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "acosh", { .funct = { mathfun_funct_acosh, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "asin", { .funct = { mathfun_funct_asin, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "asinh", { .funct = { mathfun_funct_asinh, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "atan", { .funct = { mathfun_funct_atan, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "atan2", { .funct = { mathfun_funct_atan2, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "atanh", { .funct = { mathfun_funct_atanh, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "cbrt", { .funct = { mathfun_funct_cbrt, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "ceil", { .funct = { mathfun_funct_ceil, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "copysign", { .funct = { mathfun_funct_copysign, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "cos", { .funct = { mathfun_funct_cos, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "cosh", { .funct = { mathfun_funct_cosh, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "erf", { .funct = { mathfun_funct_erf, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "erfc", { .funct = { mathfun_funct_erfc, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "exp", { .funct = { mathfun_funct_exp, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "exp2", { .funct = { mathfun_funct_exp2, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "expm1", { .funct = { mathfun_funct_expm1, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "abs", { .funct = { mathfun_funct_abs, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "fdim", { .funct = { mathfun_funct_fdim, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "floor", { .funct = { mathfun_funct_floor, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "fma", { .funct = { mathfun_funct_fma, &mathfun_sig3 } } }, { MATHFUN_DECL_FUNCT, "fmod", { .funct = { mathfun_funct_fmod, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "max", { .funct = { mathfun_funct_max, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "min", { .funct = { mathfun_funct_min, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "hypot", { .funct = { mathfun_funct_hypot, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "j0", { .funct = { mathfun_funct_j0, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "j1", { .funct = { mathfun_funct_j1, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "jn", { .funct = { mathfun_funct_jn, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "ldexp", { .funct = { mathfun_funct_ldexp, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "log", { .funct = { mathfun_funct_log, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "log10", { .funct = { mathfun_funct_log10, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "log1p", { .funct = { mathfun_funct_log1p, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "log2", { .funct = { mathfun_funct_log2, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "logb", { .funct = { mathfun_funct_logb, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "nearbyint", { .funct = { mathfun_funct_nearbyint, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "nextafter", { .funct = { mathfun_funct_nextafter, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "nexttoward", { .funct = { mathfun_funct_nexttoward, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "remainder", { .funct = { mathfun_funct_remainder, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "round", { .funct = { mathfun_funct_round, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "scalbln", { .funct = { mathfun_funct_scalbln, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "sin", { .funct = { mathfun_funct_sin, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "sinh", { .funct = { mathfun_funct_sinh, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "sqrt", { .funct = { mathfun_funct_sqrt, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "tan", { .funct = { mathfun_funct_tan, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "tanh", { .funct = { mathfun_funct_tanh, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "gamma", { .funct = { mathfun_funct_gamma, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "trunc", { .funct = { mathfun_funct_trunc, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "y0", { .funct = { mathfun_funct_y0, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "y1", { .funct = { mathfun_funct_y1, &mathfun_sig1 } } }, { MATHFUN_DECL_FUNCT, "yn", { .funct = { mathfun_funct_yn, &mathfun_sig2 } } }, { MATHFUN_DECL_FUNCT, "sign", { .funct = { mathfun_funct_sign, &mathfun_sig1 } } }, { -1, NULL, { .value = 0 } } }; return mathfun_context_define(ctx, decls, error); } <file_sep>/src/codegen.c #include <string.h> #include "mathfun_intern.h" void mathfun_codegen_cleanup(mathfun_codegen *codegen) { free(codegen->code); codegen->code = NULL; } bool mathfun_codegen_ensure(mathfun_codegen *codegen, size_t n) { const size_t size = codegen->code_used + n; if (size > codegen->code_size) { mathfun_code *code = realloc(codegen->code, size * sizeof(mathfun_code)); if (!code) { mathfun_raise_error(codegen->error, MATHFUN_OUT_OF_MEMORY); return false; } codegen->code = code; codegen->code_size = size; } return true; } bool mathfun_codegen_align(mathfun_codegen *codegen, size_t offset, size_t align) { const uintptr_t mask = ~(align - 1); for (;;) { uintptr_t ptr = (uintptr_t)(codegen->code + codegen->code_used + offset); uintptr_t aligned = ptr & mask; if (aligned == ptr) break; if (!mathfun_codegen_ensure(codegen, 1)) return false; codegen->code[codegen->code_used ++] = NOP; } return true; } bool mathfun_codegen_val(mathfun_codegen *codegen, mathfun_value value, mathfun_code target) { if (!mathfun_codegen_align(codegen, 1, sizeof(mathfun_value))) return false; if (!mathfun_codegen_ensure(codegen, MATHFUN_VALUE_CODES + 2)) return false; codegen->code[codegen->code_used ++] = VAL; *(mathfun_value*)(codegen->code + codegen->code_used) = value; codegen->code_used += MATHFUN_VALUE_CODES; codegen->code[codegen->code_used ++] = target; return true; } bool mathfun_codegen_call(mathfun_codegen *codegen, mathfun_binding_funct funct, mathfun_code firstarg, mathfun_code target) { if (!mathfun_codegen_align(codegen, 1, sizeof(mathfun_binding_funct))) return false; if (!mathfun_codegen_ensure(codegen, MATHFUN_FUNCT_CODES + 3)) return false; codegen->code[codegen->code_used ++] = CALL; *(mathfun_binding_funct*)(codegen->code + codegen->code_used) = funct; codegen->code_used += MATHFUN_FUNCT_CODES; codegen->code[codegen->code_used ++] = firstarg; codegen->code[codegen->code_used ++] = target; return true; } bool mathfun_codegen_ins0(mathfun_codegen *codegen, enum mathfun_bytecode code) { if (!mathfun_codegen_ensure(codegen, 1)) return false; codegen->code[codegen->code_used ++] = code; return true; } bool mathfun_codegen_ins1(mathfun_codegen *codegen, enum mathfun_bytecode code, mathfun_code arg1) { if (!mathfun_codegen_ensure(codegen, 2)) return false; codegen->code[codegen->code_used ++] = code; codegen->code[codegen->code_used ++] = arg1; return true; } bool mathfun_codegen_ins2(mathfun_codegen *codegen, enum mathfun_bytecode code, mathfun_code arg1, mathfun_code arg2) { if (!mathfun_codegen_ensure(codegen, 3)) return false; codegen->code[codegen->code_used ++] = code; codegen->code[codegen->code_used ++] = arg1; codegen->code[codegen->code_used ++] = arg2; return true; } bool mathfun_codegen_ins3(mathfun_codegen *codegen, enum mathfun_bytecode code, mathfun_code arg1, mathfun_code arg2, mathfun_code arg3) { if (!mathfun_codegen_ensure(codegen, 4)) return false; codegen->code[codegen->code_used ++] = code; codegen->code[codegen->code_used ++] = arg1; codegen->code[codegen->code_used ++] = arg2; codegen->code[codegen->code_used ++] = arg3; return true; } bool mathfun_codegen_binary( mathfun_codegen *codegen, mathfun_expr *expr, enum mathfun_bytecode code, mathfun_code *ret) { mathfun_code leftret = codegen->currstack; mathfun_code rightret; if (!mathfun_codegen_expr(codegen, expr->ex.binary.left, &leftret)) return false; if (leftret < codegen->currstack) { // returned an argument, can use unchanged currstack for right expression rightret = codegen->currstack; if (!mathfun_codegen_expr(codegen, expr->ex.binary.right, &rightret)) return false; } else { rightret = ++ codegen->currstack; if (!mathfun_codegen_expr(codegen, expr->ex.binary.right, &rightret)) return false; // doing this *after* the codegen for the right expression // optimizes the case where no extra register is needed (e.g. it // just accesses an argument register) if (codegen->maxstack < rightret) { codegen->maxstack = rightret; } -- codegen->currstack; } return mathfun_codegen_ins3(codegen, code, leftret, rightret, *ret); } static bool mathfun_codegen_range( mathfun_codegen *codegen, mathfun_expr *expr, mathfun_code valuereg, mathfun_code *ret) { mathfun_code rngret = codegen->currstack; if (!mathfun_codegen_expr(codegen, expr->ex.binary.left, &rngret)) return false; const mathfun_code lowerret = codegen->currstack; if (!mathfun_codegen_ins3(codegen, GE, valuereg, rngret, lowerret)) return false; size_t adr = codegen->code_used + 2; if (!mathfun_codegen_ins2(codegen, JMPF, lowerret, 0)) return false; rngret = codegen->currstack; if (!mathfun_codegen_expr(codegen, expr->ex.binary.right, &rngret)) return false; const mathfun_code upperret = codegen->currstack; if (!mathfun_codegen_ins3(codegen, expr->type == EX_RNG_INCL ? LE : LT, valuereg, rngret, upperret)) return false; if (upperret != *ret) { if (!mathfun_codegen_ins2(codegen, MOV, upperret, *ret)) return false; } codegen->code[adr] = codegen->code_used; if (lowerret != *ret) { return mathfun_codegen_ins1(codegen, SETF, *ret); } return true; } static bool mathfun_codegen_in( mathfun_codegen *codegen, mathfun_expr *expr, mathfun_code *ret) { mathfun_code valueret = codegen->currstack; if (!mathfun_codegen_expr(codegen, expr->ex.binary.left, &valueret)) return false; if (valueret < codegen->currstack) { return mathfun_codegen_range(codegen, expr->ex.binary.right, valueret, ret); } else { ++ codegen->currstack; if (!mathfun_codegen_range(codegen, expr->ex.binary.right, valueret, ret)) return false; // doing this *after* the codegen for the range expression // optimizes the case where no extra register is needed (e.g. it // just accesses an argument registers) if (codegen->maxstack < codegen->currstack) { codegen->maxstack = codegen->currstack; } -- codegen->currstack; return true; } } bool mathfun_codegen_unary(mathfun_codegen *codegen, mathfun_expr *expr, enum mathfun_bytecode code, mathfun_code *ret) { mathfun_code unret = *ret; if (!mathfun_codegen_expr(codegen, expr->ex.unary.expr, &unret)) return false; return mathfun_codegen_ins2(codegen, code, unret, *ret); } bool mathfun_codegen_expr(mathfun_codegen *codegen, mathfun_expr *expr, mathfun_code *ret) { switch (expr->type) { case EX_CONST: if (expr->ex.value.type == MATHFUN_BOOLEAN) { return mathfun_codegen_ins1(codegen, expr->ex.value.value.boolean ? SETT : SETF, *ret); } else { return mathfun_codegen_val(codegen, expr->ex.value.value, *ret); } case EX_ARG: *ret = expr->ex.arg; return true; case EX_CALL: { mathfun_code oldstack = codegen->currstack; mathfun_code firstarg = oldstack; size_t i = 0; const size_t argc = expr->ex.funct.sig->argc; // check if args happen to be on the "stack" // This removes mov instructions when all arguments are already in the // correct order in registers or the leading arguments are in registers // directly before the current "stack pointer". if (argc > 0 && expr->ex.funct.args[0]->type == EX_ARG) { firstarg = expr->ex.funct.args[0]->ex.arg; for (i = 1; i < argc; ++ i) { mathfun_expr *arg = expr->ex.funct.args[i]; if (arg->type != EX_ARG || arg->ex.arg != firstarg + i) { break; } } if (firstarg + i != codegen->currstack && i != argc) { // didn't work out firstarg = oldstack; i = 0; } } // codegen for the rest of the arguments for (; i < argc; ++ i) { mathfun_expr *arg = expr->ex.funct.args[i]; mathfun_code argret = codegen->currstack; if (!mathfun_codegen_expr(codegen, arg, &argret)) return false; if (argret != codegen->currstack && !mathfun_codegen_ins2(codegen, MOV, argret, codegen->currstack)) { return false; } if (i + 1 < argc) { ++ codegen->currstack; if (codegen->currstack > codegen->maxstack) { codegen->maxstack = codegen->currstack; } } } codegen->currstack = oldstack; return mathfun_codegen_call(codegen, expr->ex.funct.funct, firstarg, *ret); } case EX_NEG: return mathfun_codegen_unary(codegen, expr, NEG, ret); case EX_ADD: return mathfun_codegen_binary(codegen, expr, ADD, ret); case EX_SUB: return mathfun_codegen_binary(codegen, expr, SUB, ret); case EX_MUL: return mathfun_codegen_binary(codegen, expr, MUL, ret); case EX_DIV: return mathfun_codegen_binary(codegen, expr, DIV, ret); case EX_MOD: return mathfun_codegen_binary(codegen, expr, MOD, ret); case EX_POW: return mathfun_codegen_binary(codegen, expr, POW, ret); case EX_NOT: return mathfun_codegen_unary(codegen, expr, NOT, ret); case EX_EQ: return mathfun_codegen_binary(codegen, expr, EQ, ret); case EX_NE: return mathfun_codegen_binary(codegen, expr, NE, ret); case EX_LT: return mathfun_codegen_binary(codegen, expr, LT, ret); case EX_GT: return mathfun_codegen_binary(codegen, expr, GT, ret); case EX_LE: return mathfun_codegen_binary(codegen, expr, LE, ret); case EX_GE: return mathfun_codegen_binary(codegen, expr, GE, ret); case EX_IN: return mathfun_codegen_in(codegen, expr, ret); case EX_RNG_INCL: case EX_RNG_EXCL: mathfun_raise_error(codegen->error, MATHFUN_INTERNAL_ERROR); return false; case EX_BEQ: return mathfun_codegen_binary(codegen, expr, BEQ, ret); case EX_BNE: return mathfun_codegen_binary(codegen, expr, BNE, ret); case EX_AND: { mathfun_code leftret = *ret; if (!mathfun_codegen_expr(codegen, expr->ex.binary.left, &leftret)) return false; size_t adr = codegen->code_used + 2; if (!mathfun_codegen_ins2(codegen, JMPF, leftret, 0)) return false; mathfun_code rightret = *ret; if (!mathfun_codegen_expr(codegen, expr->ex.binary.right, &rightret)) return false; if (rightret != *ret) { if (!mathfun_codegen_ins2(codegen, MOV, rightret, *ret)) return false; } codegen->code[adr] = codegen->code_used; if (leftret != *ret) { return mathfun_codegen_ins1(codegen, SETF, *ret); } return true; } case EX_OR: { mathfun_code leftret = *ret; if (!mathfun_codegen_expr(codegen, expr->ex.binary.left, &leftret)) return false; size_t adr = codegen->code_used + 2; if (!mathfun_codegen_ins2(codegen, JMPT, leftret, 0)) return false; mathfun_code rightret = *ret; if (!mathfun_codegen_expr(codegen, expr->ex.binary.right, &rightret)) return false; if (rightret != *ret) { if (!mathfun_codegen_ins2(codegen, MOV, rightret, *ret)) return false; } codegen->code[adr] = codegen->code_used; if (leftret != *ret) { return mathfun_codegen_ins1(codegen, SETT, *ret); } return true; } case EX_IIF: { mathfun_code childret = *ret; if (!mathfun_codegen_expr(codegen, expr->ex.iif.cond, &childret)) return false; size_t adr1 = codegen->code_used + 2; if (!mathfun_codegen_ins2(codegen, JMPF, childret, 0)) return false; childret = *ret; if (!mathfun_codegen_expr(codegen, expr->ex.iif.then_expr, &childret)) return false; if (childret != *ret) { if (!mathfun_codegen_ins2(codegen, MOV, childret, *ret)) return false; } size_t adr2 = codegen->code_used + 1; if (!mathfun_codegen_ins1(codegen, JMP, 0)) return false; codegen->code[adr1] = codegen->code_used; childret = *ret; if (!mathfun_codegen_expr(codegen, expr->ex.iif.else_expr, &childret)) return false; if (childret != *ret) { if (!mathfun_codegen_ins2(codegen, MOV, childret, *ret)) return false; } codegen->code[adr2] = codegen->code_used; return true; } } mathfun_raise_error(codegen->error, MATHFUN_INTERNAL_ERROR); return false; } // shortcut unconditional jump chain to RET static bool mathfun_code_shortcut_jmp_to_ret(mathfun_code *code, mathfun_code *ptr, mathfun_code *retptr) { switch (ptr[0]) { case RET: if (retptr) *retptr = ptr[1]; return true; case JMP: { mathfun_code ret = 0; bool shortcut = mathfun_code_shortcut_jmp_to_ret(code, code + ptr[1], &ret); if (shortcut) { ptr[0] = RET; ptr[1] = ret; if (retptr) *retptr = ret; } return shortcut; } default: return false; } } // shortcut unconditional jump chain static mathfun_code mathfun_code_shortcut_jmp(mathfun_code *code, mathfun_code *ptr) { if (ptr[0] == JMP) { return (ptr[1] = mathfun_code_shortcut_jmp(code, code + ptr[1])); } else { return ptr - code; } } // shortcut conditional jump chain on same condition register static mathfun_code mathfun_code_shortcut_jmptf(mathfun_code *code, mathfun_code *ptr, enum mathfun_bytecode instr, mathfun_code reg) { if (ptr[0] == instr && ptr[1] == reg) { return (ptr[2] = mathfun_code_shortcut_jmptf(code, code + ptr[2], instr, reg)); } else { return ptr - code; } } bool mathfun_expr_codegen(mathfun_expr *expr, mathfun *fun, mathfun_error_p *error) { if (fun->argc > MATHFUN_REGS_MAX) { mathfun_raise_error(error, MATHFUN_TOO_MANY_ARGUMENTS); return false; } mathfun_codegen codegen; memset(&codegen, 0, sizeof(struct mathfun_codegen)); codegen.argc = codegen.currstack = codegen.maxstack = fun->argc; codegen.code_size = 16; codegen.code = calloc(codegen.code_size, sizeof(mathfun_code)); codegen.error = error; if (!codegen.code) { mathfun_raise_error(error, MATHFUN_OUT_OF_MEMORY); mathfun_codegen_cleanup(&codegen); return false; } mathfun_code ret = fun->argc; if (!mathfun_codegen_expr(&codegen, expr, &ret) || !mathfun_codegen_ins1(&codegen, RET, ret) || !mathfun_codegen_ins0(&codegen, END)) { mathfun_codegen_cleanup(&codegen); return false; } if (codegen.maxstack >= MATHFUN_REGS_MAX) { mathfun_raise_error(error, MATHFUN_EXCEEDS_MAX_FRAME_SIZE); mathfun_codegen_cleanup(&codegen); return false; } // shortcut everything that just jumps to RET mathfun_code *ptr = codegen.code; while (*ptr != END) { switch (*ptr) { case JMP: if (!mathfun_code_shortcut_jmp_to_ret(codegen.code, ptr, NULL)) { mathfun_code_shortcut_jmp(codegen.code, ptr); } ptr += 2; break; case NOP: ptr += 1; break; case MOV: case NEG: case NOT: ptr += 3; break; case JMPF: case JMPT: mathfun_code_shortcut_jmptf(codegen.code, ptr, ptr[0], ptr[1]); ptr += 3; break; case VAL: ptr += 2 + MATHFUN_VALUE_CODES; break; case CALL: ptr += 3 + MATHFUN_FUNCT_CODES; break; case ADD: case SUB: case MUL: case DIV: case MOD: case POW: case EQ: case NE: case LT: case GT: case LE: case GE: case BEQ: case BNE: ptr += 4; break; case SETF: case SETT: ptr += 2; break; case RET: ptr += 2; break; default: mathfun_raise_error(error, MATHFUN_INTERNAL_ERROR); mathfun_codegen_cleanup(&codegen); return false; } } fun->framesize = codegen.maxstack + 1; fun->code = codegen.code; codegen.code = NULL; mathfun_codegen_cleanup(&codegen); return true; } #define MATHFUN_DUMP(ARGS) \ if (fprintf ARGS < 0) { \ mathfun_raise_error(error, MATHFUN_IO_ERROR); \ return false; \ } bool mathfun_dump(const mathfun *fun, FILE *stream, const mathfun_context *ctx, mathfun_error_p *error) { const mathfun_code *start = fun->code; const mathfun_code *code = start; MATHFUN_DUMP((stream, "argc = %"PRIzu", framesize = %"PRIzu"\n\n", fun->argc, fun->framesize)); while (*code != END) { MATHFUN_DUMP((stream, "0x%08"PRIXPTR": ", code - start)); switch (*code) { case NOP: MATHFUN_DUMP((stream, "nop\n")); ++ code; break; case RET: MATHFUN_DUMP((stream, "ret %"PRIuPTR"\n", code[1])); code += 2; break; case MOV: MATHFUN_DUMP((stream, "mov %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2])); code += 3; break; case VAL: MATHFUN_DUMP((stream, "val %a, %"PRIuPTR"\n", *(double*)(code + 1), code[1 + MATHFUN_VALUE_CODES])); code += 2 + MATHFUN_VALUE_CODES; break; case CALL: { mathfun_binding_funct funct = *(mathfun_binding_funct*)(code + 1); mathfun_code firstarg = code[MATHFUN_FUNCT_CODES + 1]; mathfun_code ret = code[MATHFUN_FUNCT_CODES + 2]; code += 3 + MATHFUN_FUNCT_CODES; if (ctx) { const char *name = mathfun_context_funct_name(ctx, funct); if (name) { MATHFUN_DUMP((stream, "call %s, %"PRIuPTR", %"PRIuPTR"\n", name, firstarg, ret)); break; } } MATHFUN_DUMP((stream, "call 0x%"PRIxPTR", %"PRIuPTR", %"PRIuPTR"\n", (uintptr_t)funct, firstarg, ret)); break; } case NEG: MATHFUN_DUMP((stream, "neg %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2])); code += 3; break; case ADD: MATHFUN_DUMP((stream, "add %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case SUB: MATHFUN_DUMP((stream, "sub %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case MUL: MATHFUN_DUMP((stream, "mul %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case DIV: MATHFUN_DUMP((stream, "div %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case MOD: MATHFUN_DUMP((stream, "mod %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case POW: MATHFUN_DUMP((stream, "pow %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case NOT: MATHFUN_DUMP((stream, "not %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2])); code += 3; break; case EQ: MATHFUN_DUMP((stream, "eq %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case NE: MATHFUN_DUMP((stream, "ne %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case LT: MATHFUN_DUMP((stream, "lt %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case GT: MATHFUN_DUMP((stream, "gt %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case LE: MATHFUN_DUMP((stream, "le %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case GE: MATHFUN_DUMP((stream, "ge %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case BEQ: MATHFUN_DUMP((stream, "beq %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case BNE: MATHFUN_DUMP((stream, "bne %"PRIuPTR", %"PRIuPTR", %"PRIuPTR"\n", code[1], code[2], code[3])); code += 4; break; case JMP: MATHFUN_DUMP((stream, "jmp 0x%"PRIXPTR"\n", code[1])); code += 2; break; case JMPT: MATHFUN_DUMP((stream, "jmpt %"PRIuPTR", 0x%"PRIXPTR"\n", code[1], code[2])); code += 3; break; case JMPF: MATHFUN_DUMP((stream, "jmpf %"PRIuPTR", 0x%"PRIXPTR"\n", code[1], code[2])); code += 3; break; case SETT: MATHFUN_DUMP((stream, "sett %"PRIuPTR"\n", code[1])); code += 2; break; case SETF: MATHFUN_DUMP((stream, "setf %"PRIuPTR"\n", code[1])); code += 2; break; default: // assert? mathfun_raise_error(error, MATHFUN_INTERNAL_ERROR); return false; } } return true; } <file_sep>/src/parser.c #include <string.h> #include <errno.h> #include <ctype.h> #include "mathfun_intern.h" #define skipws(parser) { \ const char *ptr = (parser)->ptr; \ while (isspace(*ptr)) ++ ptr; \ (parser)->ptr = ptr; \ } // BNF // Note: The parser also does type checks. Arithmetic and comparison operations only work on numbers // and boolean operations only on boolean values. // // test ::= or_test ["?" or_test ":" test] // or_test ::= and_test ("||" and_test)* // and_test ::= not_test ("&&" not_test)* // not_test ::= "!" not_test | comparison // comparison ::= arith_expr (comp_op arith_expr | "in" range)* // comp_op ::= "==" | "!=" | "<" | ">" | "<=" | ">=" // range ::= arith_expr (".."|"...") factor // arith_expr ::= term (("+"|"-") term)* // term ::= factor (("*"|"/"|"%") factor)* // factor ::= ("+"|"-") factor | power // power ::= atom ["**" factor] // atom ::= identifier ("(" [test ("," test)*] ")")? | number | "true" | "false" | "(" test ")" // number ::= "Inf" | "NaN" | ["-"]("0"|"1"..."9"digit*)["."digit*][("e"|"E")["+"|"-"]digit+] // identifier ::= (alpha|"_")(alnum|"_")* // // strtod is used for number // isalpha is used for alpha // isalnum is used for alnum // isspace is used for whitespace static mathfun_expr *mathfun_parse_test(mathfun_parser *parser); static mathfun_expr *mathfun_parse_or_test(mathfun_parser *parser); static mathfun_expr *mathfun_parse_and_test(mathfun_parser *parser); static mathfun_expr *mathfun_parse_not_test(mathfun_parser *parser); static mathfun_expr *mathfun_parse_comparison(mathfun_parser *parser); static mathfun_expr *mathfun_parse_arith_expr(mathfun_parser *parser); static mathfun_expr *mathfun_parse_range(mathfun_parser *parser); static mathfun_expr *mathfun_parse_term(mathfun_parser *parser); static mathfun_expr *mathfun_parse_factor(mathfun_parser *parser); static mathfun_expr *mathfun_parse_power(mathfun_parser *parser); static mathfun_expr *mathfun_parse_atom(mathfun_parser *parser); static mathfun_expr *mathfun_parse_number(mathfun_parser *parser); static size_t mathfun_parse_identifier(mathfun_parser *parser); mathfun_expr *mathfun_parse_test(mathfun_parser *parser) { const char *errptr = parser->ptr; mathfun_expr *expr = mathfun_parse_or_test(parser); if (!expr) return NULL; if (*parser->ptr == '?') { mathfun_expr *cond = expr; if (mathfun_expr_type(cond) != MATHFUN_BOOLEAN) { // not a boolean expression for condition mathfun_raise_parser_type_error(parser, errptr, MATHFUN_BOOLEAN, mathfun_expr_type(cond)); mathfun_expr_free(cond); return NULL; } ++ parser->ptr; skipws(parser); errptr = parser->ptr; mathfun_expr *then_expr = mathfun_parse_or_test(parser); if (!then_expr) { mathfun_expr_free(cond); return NULL; } skipws(parser); if (*parser->ptr != ':') { mathfun_raise_parser_error(parser, *parser->ptr ? MATHFUN_PARSER_EXPECTED_COLON : MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, NULL); mathfun_expr_free(then_expr); mathfun_expr_free(cond); return NULL; } ++ parser->ptr; skipws(parser); mathfun_expr *else_expr = mathfun_parse_test(parser); if (!else_expr) { mathfun_expr_free(then_expr); mathfun_expr_free(cond); return NULL; } if (mathfun_expr_type(then_expr) != mathfun_expr_type(else_expr)) { // type missmatch of the two branches mathfun_raise_parser_type_error(parser, errptr, mathfun_expr_type(else_expr), mathfun_expr_type(then_expr)); mathfun_expr_free(then_expr); mathfun_expr_free(else_expr); mathfun_expr_free(cond); return NULL; } expr = mathfun_expr_alloc(EX_IIF, parser->error); if (!expr) { mathfun_expr_free(then_expr); mathfun_expr_free(else_expr); mathfun_expr_free(cond); return NULL; } expr->ex.iif.cond = cond; expr->ex.iif.then_expr = then_expr; expr->ex.iif.else_expr = else_expr; } return expr; } mathfun_expr *mathfun_parse_or_test(mathfun_parser *parser) { const char *errptr = parser->ptr; mathfun_expr *expr = mathfun_parse_and_test(parser); if (!expr) return NULL; if (parser->ptr[0] == '|' && parser->ptr[1] == '|') { if (mathfun_expr_type(expr) != MATHFUN_BOOLEAN) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_BOOLEAN, mathfun_expr_type(expr)); mathfun_expr_free(expr); return NULL; } do { parser->ptr += 2; skipws(parser); errptr = parser->ptr; mathfun_expr *left = expr; mathfun_expr *right = mathfun_parse_and_test(parser); if (!right) { mathfun_expr_free(left); return NULL; } if (mathfun_expr_type(right) != MATHFUN_BOOLEAN) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_BOOLEAN, mathfun_expr_type(right)); mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr = mathfun_expr_alloc(EX_OR, parser->error); if (!expr) { mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr->ex.binary.left = left; expr->ex.binary.right = right; } while (parser->ptr[0] == '|' && parser->ptr[1] == '|'); } return expr; } mathfun_expr *mathfun_parse_and_test(mathfun_parser *parser) { const char *errptr = parser->ptr; mathfun_expr *expr = mathfun_parse_not_test(parser); if (!expr) return NULL; if (parser->ptr[0] == '&' && parser->ptr[1] == '&') { if (mathfun_expr_type(expr) != MATHFUN_BOOLEAN) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_BOOLEAN, mathfun_expr_type(expr)); mathfun_expr_free(expr); return NULL; } do { parser->ptr += 2; skipws(parser); errptr = parser->ptr; mathfun_expr *left = expr; mathfun_expr *right = mathfun_parse_not_test(parser); if (!right) { mathfun_expr_free(left); return NULL; } if (mathfun_expr_type(right) != MATHFUN_BOOLEAN) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_BOOLEAN, mathfun_expr_type(right)); mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr = mathfun_expr_alloc(EX_AND, parser->error); if (!expr) { mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr->ex.binary.left = left; expr->ex.binary.right = right; } while (parser->ptr[0] == '&' && parser->ptr[1] == '&'); } return expr; } mathfun_expr *mathfun_parse_not_test(mathfun_parser *parser) { const char *errptr = parser->ptr; mathfun_expr *expr = NULL; mathfun_expr **exprptr = &expr; while (*parser->ptr == '!') { ++ parser->ptr; skipws(parser); errptr = parser->ptr; mathfun_expr *not_expr = mathfun_expr_alloc(EX_NOT, parser->error); if (!not_expr) { mathfun_expr_free(expr); return NULL; } *exprptr = not_expr; exprptr = &not_expr->ex.unary.expr; if (mathfun_expr_type(not_expr) != MATHFUN_BOOLEAN) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_BOOLEAN, mathfun_expr_type(not_expr)); mathfun_expr_free(expr); return NULL; } } errptr = parser->ptr; mathfun_expr *comparison_expr = mathfun_parse_comparison(parser); if (!comparison_expr) { mathfun_expr_free(expr); return NULL; } if (expr && mathfun_expr_type(comparison_expr) != MATHFUN_BOOLEAN) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_BOOLEAN, mathfun_expr_type(comparison_expr)); mathfun_expr_free(comparison_expr); mathfun_expr_free(expr); return NULL; } *exprptr = comparison_expr; return expr; } mathfun_expr *mathfun_parse_range(mathfun_parser *parser) { const char *errptr = parser->ptr; mathfun_expr *left = mathfun_parse_arith_expr(parser); if (!left) return NULL; if (mathfun_expr_type(left) != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_NUMBER, mathfun_expr_type(left)); mathfun_expr_free(left); return NULL; } if (parser->ptr[-1] == '.') { // got something like 5...6 and the dot after the 5 was eaten by the number. -- parser->ptr; } if (parser->ptr[0] == '.' && parser->ptr[1] == '.') { enum mathfun_expr_type type; if (parser->ptr[2] == '.') { type = EX_RNG_EXCL; parser->ptr += 3; } else { type = EX_RNG_INCL; parser->ptr += 2; } skipws(parser); mathfun_expr *right = mathfun_parse_factor(parser); if (!right) { mathfun_expr_free(left); return NULL; } if (mathfun_expr_type(right) != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_NUMBER, mathfun_expr_type(right)); mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } mathfun_expr *expr = mathfun_expr_alloc(type, parser->error); if (!expr) { mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr->ex.binary.left = left; expr->ex.binary.right = right; return expr; } mathfun_expr_free(left); mathfun_raise_parser_error(parser, *parser->ptr ? MATHFUN_PARSER_EXPECTED_DOTS : MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, NULL); return NULL; } mathfun_expr *mathfun_parse_comparison(mathfun_parser *parser) { const char *errptr = parser->ptr; mathfun_expr *expr = mathfun_parse_arith_expr(parser); if (!expr) return NULL; while (((parser->ptr[0] == '=' || parser->ptr[0] == '!') && parser->ptr[1] == '=') || parser->ptr[0] == '<' || parser->ptr[0] == '>' || (strncasecmp("in", parser->ptr, 2) == 0 && !isalnum(parser->ptr[2]))) { enum mathfun_expr_type type; mathfun_type left_type = mathfun_expr_type(expr); if (parser->ptr[0] == '=' && parser->ptr[1] == '=') { parser->ptr += 2; type = left_type == MATHFUN_BOOLEAN ? EX_BEQ : EX_EQ; } else if (parser->ptr[0] == '!' && parser->ptr[1] == '=') { parser->ptr += 2; type = left_type == MATHFUN_BOOLEAN ? EX_BNE : EX_NE; } else if (parser->ptr[0] == '<') { if (parser->ptr[1] == '=') { parser->ptr += 2; type = EX_LE; } else { ++ parser->ptr; type = EX_LT; } } else if (parser->ptr[0] == '>') { if (parser->ptr[1] == '=') { parser->ptr += 2; type = EX_GE; } else { ++ parser->ptr; type = EX_GT; } } else if (strncasecmp("in", parser->ptr, 2) == 0 && !isalnum(parser->ptr[2])) { parser->ptr += 3; type = EX_IN; } else { mathfun_raise_error(parser->error, MATHFUN_INTERNAL_ERROR); mathfun_expr_free(expr); return NULL; } skipws(parser); const char *lefterrptr = errptr; errptr = parser->ptr; mathfun_expr *left = expr; mathfun_expr *right = NULL; if (type == EX_IN) { if (left_type != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, lefterrptr, MATHFUN_NUMBER, left_type); mathfun_expr_free(expr); return NULL; } right = mathfun_parse_range(parser); if (!right) { mathfun_expr_free(left); return NULL; } } else { right = mathfun_parse_arith_expr(parser); if (!right) { mathfun_expr_free(left); return NULL; } mathfun_type right_type = mathfun_expr_type(right); if (type == EX_BEQ || type == EX_BNE) { // left_type was used to generate EX_BEQ/EX_BNE, so it is MATHFUN_BOOLEAN here if (right_type != MATHFUN_BOOLEAN) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_BOOLEAN, right_type); mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } } else if (left_type != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, lefterrptr, MATHFUN_NUMBER, left_type); mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } else if (right_type != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_NUMBER, right_type); mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } } expr = mathfun_expr_alloc(type, parser->error); if (!expr) { mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr->ex.binary.left = left; expr->ex.binary.right = right; } return expr; } mathfun_expr *mathfun_parse_arith_expr(mathfun_parser *parser) { const char *errptr = parser->ptr; mathfun_expr *expr = mathfun_parse_term(parser); if (!expr) return NULL; char ch = *parser->ptr; if (ch == '+' || ch == '-') { if (mathfun_expr_type(expr) != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_NUMBER, mathfun_expr_type(expr)); mathfun_expr_free(expr); return NULL; } do { ++ parser->ptr; skipws(parser); errptr = parser->ptr; mathfun_expr *left = expr; mathfun_expr *right = mathfun_parse_term(parser); if (!right) { mathfun_expr_free(left); return NULL; } if (mathfun_expr_type(right) != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_NUMBER, mathfun_expr_type(right)); mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr = mathfun_expr_alloc(ch == '+' ? EX_ADD : EX_SUB, parser->error); if (!expr) { mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr->ex.binary.left = left; expr->ex.binary.right = right; ch = *parser->ptr; } while (ch == '+' || ch == '-'); } return expr; } mathfun_expr *mathfun_parse_term(mathfun_parser *parser) { const char *errptr = parser->ptr; mathfun_expr *expr = mathfun_parse_factor(parser); if (!expr) return NULL; char ch = *parser->ptr; if (ch == '*' || ch == '/' || ch == '%') { if (mathfun_expr_type(expr) != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_NUMBER, mathfun_expr_type(expr)); mathfun_expr_free(expr); return NULL; } do { ++ parser->ptr; skipws(parser); errptr = parser->ptr; mathfun_expr *left = expr; mathfun_expr *right = mathfun_parse_factor(parser); if (!right) { mathfun_expr_free(left); return NULL; } if (mathfun_expr_type(right) != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_NUMBER, mathfun_expr_type(right)); mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr = mathfun_expr_alloc(ch == '*' ? EX_MUL : ch == '/' ? EX_DIV : EX_MOD, parser->error); if (!expr) { mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr->ex.binary.left = left; expr->ex.binary.right = right; ch = *parser->ptr; } while (ch == '*' || ch == '/' || ch == '%'); } return expr; } mathfun_expr *mathfun_parse_factor(mathfun_parser *parser) { const char ch = *parser->ptr; if (ch == '+' || ch == '-') { ++ parser->ptr; skipws(parser); const char *errptr = parser->ptr; mathfun_expr *expr = mathfun_parse_factor(parser); if (!expr) return NULL; if (mathfun_expr_type(expr) != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_NUMBER, mathfun_expr_type(expr)); mathfun_expr_free(expr); return NULL; } if (ch == '-') { mathfun_expr *child = expr; expr = mathfun_expr_alloc(EX_NEG, parser->error); if (!expr) { mathfun_expr_free(child); return NULL; } expr->ex.unary.expr = child; } return expr; } else { return mathfun_parse_power(parser); } } mathfun_expr *mathfun_parse_power(mathfun_parser *parser) { mathfun_expr *expr = mathfun_parse_atom(parser); if (!expr) return NULL; if (parser->ptr[0] == '*' && parser->ptr[1] == '*') { parser->ptr += 2; skipws(parser); const char *errptr = parser->ptr; mathfun_expr *left = expr; mathfun_expr *right = mathfun_parse_factor(parser); if (!right) { mathfun_expr_free(left); return NULL; } if (mathfun_expr_type(right) != MATHFUN_NUMBER) { mathfun_raise_parser_type_error(parser, errptr, MATHFUN_NUMBER, mathfun_expr_type(right)); mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr = mathfun_expr_alloc(EX_POW, parser->error); if (!expr) { mathfun_expr_free(left); mathfun_expr_free(right); return NULL; } expr->ex.binary.left = left; expr->ex.binary.right = right; } return expr; } mathfun_expr *mathfun_parse_atom(mathfun_parser *parser) { char ch = *parser->ptr; if (ch == '(') { ++ parser->ptr; skipws(parser); mathfun_expr *expr = mathfun_parse_test(parser); if (!expr) return NULL; if (*parser->ptr != ')') { // missing ')' mathfun_raise_parser_error(parser, *parser->ptr ? MATHFUN_PARSER_EXPECTED_CLOSE_PARENTHESIS : MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, NULL); mathfun_expr_free(expr); return NULL; } ++ parser->ptr; skipws(parser); return expr; } else if (isdigit(ch) || ch == '.') { return mathfun_parse_number(parser); } else { const char *idstart = parser->ptr; const size_t idlen = mathfun_parse_identifier(parser); if (idlen == 0) return NULL; if (idlen == 3 && strncasecmp(idstart, "nan", idlen) == 0) { mathfun_expr *expr = mathfun_expr_alloc(EX_CONST, parser->error); if (!expr) return NULL; expr->ex.value.type = MATHFUN_NUMBER; expr->ex.value.value.number = NAN; return expr; } else if (idlen == 3 && strncasecmp(idstart, "inf", idlen) == 0) { mathfun_expr *expr = mathfun_expr_alloc(EX_CONST, parser->error); if (!expr) return NULL; expr->ex.value.type = MATHFUN_NUMBER; expr->ex.value.value.number = INFINITY; return expr; } else if (idlen == 4 && strncasecmp(idstart, "true", idlen) == 0) { mathfun_expr *expr = mathfun_expr_alloc(EX_CONST, parser->error); if (!expr) return NULL; expr->ex.value.type = MATHFUN_BOOLEAN; expr->ex.value.value.boolean = true; return expr; } else if (idlen == 5 && strncasecmp(idstart, "false", idlen) == 0) { mathfun_expr *expr = mathfun_expr_alloc(EX_CONST, parser->error); if (!expr) return NULL; expr->ex.value.type = MATHFUN_BOOLEAN; expr->ex.value.value.boolean = false; return expr; } size_t argind = 0; for (; argind < parser->argc; ++ argind) { const char *argname = parser->argnames[argind]; if (strncmp(argname, idstart, idlen) == 0 && !argname[idlen]) { break; } } if (*parser->ptr != '(') { if (argind < parser->argc) { mathfun_expr *expr = mathfun_expr_alloc(EX_ARG, parser->error); if (!expr) return NULL; expr->ex.arg = argind; return expr; } const mathfun_decl *decl = mathfun_context_getn(parser->ctx, idstart, idlen); if (!decl) { mathfun_raise_parser_error(parser, MATHFUN_PARSER_UNDEFINED_REFERENCE, idstart); return NULL; } if (decl->type != MATHFUN_DECL_CONST) { mathfun_raise_parser_error(parser, MATHFUN_PARSER_NOT_A_VARIABLE, idstart); return NULL; } mathfun_expr *expr = mathfun_expr_alloc(EX_CONST, parser->error); if (!expr) return NULL; expr->ex.value.type = MATHFUN_NUMBER; expr->ex.value.value.number = decl->decl.value; return expr; } else if (argind < parser->argc) { mathfun_raise_parser_error(parser, MATHFUN_PARSER_NOT_A_FUNCTION, idstart); return NULL; } else { const mathfun_decl *decl = mathfun_context_getn(parser->ctx, idstart, idlen); if (!decl) { mathfun_raise_parser_error(parser, MATHFUN_PARSER_UNDEFINED_REFERENCE, idstart); return NULL; } if (decl->type != MATHFUN_DECL_FUNCT) { mathfun_raise_parser_error(parser, MATHFUN_PARSER_NOT_A_FUNCTION, idstart); return NULL; } mathfun_expr *expr = mathfun_expr_alloc(EX_CALL, parser->error); if (!expr) { return NULL; } expr->ex.funct.funct = decl->decl.funct.funct; expr->ex.funct.sig = decl->decl.funct.sig; if (expr->ex.funct.sig->argc > 0) { expr->ex.funct.args = calloc(expr->ex.funct.sig->argc, sizeof(mathfun_expr*)); if (!expr->ex.funct.args) { mathfun_expr_free(expr); return NULL; } } ++ parser->ptr; skipws(parser); size_t argc = 0; const char *lastarg = parser->ptr; for (;;) { ch = *parser->ptr; if (!ch || ch == ')') break; lastarg = parser->ptr; mathfun_expr *arg = mathfun_parse_test(parser); if (!arg) { mathfun_expr_free(expr); return NULL; } if (argc >= expr->ex.funct.sig->argc) { mathfun_expr_free(arg); } else { expr->ex.funct.args[argc] = arg; if (expr->ex.funct.sig->argtypes[argc] != mathfun_expr_type(arg)) { mathfun_raise_parser_type_error(parser, lastarg, expr->ex.funct.sig->argtypes[argc], mathfun_expr_type(arg)); mathfun_expr_free(expr); return NULL; } } ++ argc; if (*parser->ptr != ',') break; ++ parser->ptr; skipws(parser); } if (*parser->ptr != ')') { mathfun_raise_parser_error(parser, *parser->ptr ? MATHFUN_PARSER_EXPECTED_CLOSE_PARENTHESIS : MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, NULL); mathfun_expr_free(expr); return NULL; } ++ parser->ptr; skipws(parser); if (argc != decl->decl.funct.sig->argc) { mathfun_raise_parser_argc_error(parser, lastarg, decl->decl.funct.sig->argc, argc); mathfun_expr_free(expr); return NULL; } return expr; } } } mathfun_expr *mathfun_parse_number(mathfun_parser *parser) { char *endptr = NULL; double value = strtod(parser->ptr, &endptr); if (parser->ptr == endptr) { // can't have MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT here because this function is only called // if there is at least one character that can be at the start of a number literal. mathfun_raise_parser_error(parser, MATHFUN_PARSER_EXPECTED_NUMBER, NULL); return NULL; } parser->ptr = endptr; skipws(parser); mathfun_expr *expr = mathfun_expr_alloc(EX_CONST, parser->error); if (!expr) return NULL; expr->ex.value.type = MATHFUN_NUMBER; expr->ex.value.value.number = value; return expr; } const char *mathfun_find_identifier_end(const char *str) { if (!isalpha(*str) && *str != '_') { return str; } ++ str; while (isalnum(*str) || *str == '_') { ++ str; } return str; } size_t mathfun_parse_identifier(mathfun_parser *parser) { const char *from = parser->ptr; parser->ptr = mathfun_find_identifier_end(from); if (from == parser->ptr) { mathfun_raise_parser_error(parser, *from ? MATHFUN_PARSER_EXPECTED_IDENTIFIER : MATHFUN_PARSER_UNEXPECTED_END_OF_INPUT, from); return 0; } size_t n = parser->ptr - from; skipws(parser); return n; } mathfun_expr *mathfun_context_parse(const mathfun_context *ctx, const char *argnames[], size_t argc, const char *code, mathfun_error_p *error) { if (!mathfun_validate_argnames(argnames, argc, error)) return NULL; mathfun_parser parser = { ctx, argnames, argc, code, code, error }; skipws(&parser); mathfun_expr *expr = mathfun_parse_test(&parser); if (expr) { skipws(&parser); if (*parser.ptr) { mathfun_raise_parser_error(&parser, MATHFUN_PARSER_TRAILING_GARBAGE, NULL); mathfun_expr_free(expr); return NULL; } if (mathfun_expr_type(expr) != MATHFUN_NUMBER) { const char *ptr = code; while (isspace(*ptr)) ++ ptr; mathfun_raise_parser_type_error(&parser, ptr, MATHFUN_NUMBER, mathfun_expr_type(expr)); mathfun_expr_free(expr); return NULL; } } return expr; } <file_sep>/examples/evaltree.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <mathfun.h> #include <math.h> int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "invalid number of arguments\n"); return 1; } char **argnames = argv + 1; const size_t funct_argc = argc - 2; double *funct_args = calloc(funct_argc, sizeof(double)); if (!funct_args) { perror("error allocating arguments"); return 1; } for (size_t i = 0; i < funct_argc; ++ i) { char *argname = argnames[i]; char *assign = strchr(argname, '='); if (!assign) { fprintf(stderr, "invalid argument: %s\n", argname); free(funct_args); return 1; } char *arg = assign + 1; char *endptr = NULL; funct_args[i] = strtod(arg, &endptr); if (arg == endptr) { fprintf(stderr, "invalid argument: %s\n", argname); free(funct_args); return 1; } *assign = 0; } mathfun_error_p error = NULL; double value = mathfun_arun((const char **)argnames, funct_argc, argv[argc - 1], funct_args, &error); free(funct_args); if (error) { mathfun_error_log_and_cleanup(&error, stderr); return 1; } printf("%.22g\n", value); return 0; } <file_sep>/examples/CMakeLists.txt include_directories("${PROJECT_SOURCE_DIR}/src") set(MATHFUN_EXAMPLES dump eval evaltree wavegen livewave) foreach(example ${MATHFUN_EXAMPLES}) add_executable(${example} ${example}.c) target_link_libraries(${example} ${MATHFUN_LIB_NAME}) endforeach() if(INSTALL_WAVEGEN) install(TARGETS wavegen RUNTIME DESTINATION "bin") endif()
5842e969bc7b7ff65c34690ba260e1295c885ad6
[ "C", "CMake" ]
17
C
panzi/mathfun
001c1b4a5be4693c976008ae76027a8727fa560f
9282210cd0cb848acf8d62d3bd92b8739506d83a
refs/heads/exo1
<repo_name>MarieJoss/Simpson_work<file_sep>/src/components/Avatar.jsx import React from 'react'; const Avatar = ({image, firstName, lastName})=>{ return <div> <img src={image}/> <h1>{firstName}</h1> <h2>{lastName}</h2> </div> } export default Avatar;
45536d15abe04c819f42eebfa28dc20aaf1634e7
[ "JavaScript" ]
1
JavaScript
MarieJoss/Simpson_work
f76491e8111c14a25c7a5bd21e43dc19b3443c81
d7ad192c699d128e7aeddf03e44a6330ad0dd7dc
refs/heads/master
<file_sep>package com.my.package; /** * * About * ----- * * A utility class for dynamically setting the height and width of screen objects in android, * based on the current screen dimensions. * * Also has some methods for grabbing screen data, such as the height and width in pixels. * * Android devices come in all shapes and sizes, so this class has helped me make my android * applications more "responsive" based on the device they are running on. * * Hopefully this will help you set up your screen objects across devices too. * * I wouldn't recommend using this utility class for bigger devices like tablets, as the objects * just end up looking gigantic if you're only using a few of them on screen at a time. * * Legal stuff * ----------- * * Copyright (c) <NAME> 2012 * * 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/> * * @author <NAME> www.phalt.co.uk */ import android.app.Activity; import android.content.ActivityNotFoundException; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.ViewGroup.LayoutParams; public class ScreenUtility { private Activity _activity; private int _height; private int _width; /** * Default constructor * @param activity * The activity the objects are in. */ public ScreenUtility(Activity activity) { try { setActivity(activity); discoverActivityScreenSize(); } catch (Exception e) { Log.e("ScreenUtility.java", e.getMessage()); } } /* * ======================================================================== * Public functions * ======================================================================== */ /** * Sets a view object height and width to a supplied percentage of the device screen. * @param heightPercentage * The desired height in percentage (between 1 and 100). * @param widthPercentage * The desired width in percentage (between 1 and 100). * @param viewObject * The view object that you are setting the dimensions for. */ public void setViewObjectDimensionsAsPercentage(int heightPercentage, int widthPercentage, View viewObject) { LayoutParams layout = viewObject.getLayoutParams(); setDynamicDimensions(layout, heightPercentage, widthPercentage); } /* * ======================================================================== * Getters and setters for activity, screen height and screen width * ======================================================================== */ private void setActivity(Activity activity) { if(activity == null) { throw new ActivityNotFoundException(); } else { this._activity = activity; } } private Activity getActivity() { return this._activity; } private void setHeight(int height) { this._height = height; } /** * Get the screen height * @return The screen height. */ public int getScreenHeight() { return this._height; } /** * Get the screen height * @return The screen height as a double. */ public Double getScreenHeightAsDouble() { return Double.valueOf(this._height); } private void setWidth(int width) { this._width = width; } /** * Get the screen width * @return The screen width. */ public int getScreenWidth() { return this._width; } /** * Get the screen width * @return The screen width as a double. */ public Double getScreenWidthAsDouble() { return Double.valueOf(this._width); } /* * ======================================================================== * Private functions for use internally * ======================================================================== */ /** * Sets the view object to it's dynamic height and width * @param layout * @param height * @param width */ private void setDynamicDimensions(LayoutParams layout, int height, int width) { double[] dimensions = setDimensions(height, width); layout.height= (int)dimensions[0]; layout.width = (int)dimensions[1]; } /** * Set the dimensions needed for view objects * @param heightPercentage * @param widthPercentage * @return */ private double[] setDimensions(int heightPercentage, int widthPercentage) { double[] dimensions = new double[2]; dimensions[0] = ((double)heightPercentage * getScreenHeight()) / 100; dimensions[1] = ((double)widthPercentage * getScreenWidth()) / 100; return dimensions; } /** * Discover the screen height and width */ private void discoverActivityScreenSize() { DisplayMetrics displaymetrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); setHeight(displaymetrics.heightPixels); setWidth(displaymetrics.widthPixels); } } <file_sep>##Android Screen Utility = A utility class for dynamically setting view object height and width based on percentages of the total screen height and width. This has saved me a lot of time creating layouts that look good across different screen sizes, but it doesn't look very good on larger devices such as tablets. ##Using this class 1. Add the class to your package and change the package line at the top: ```Java package com.my.package; ``` 2. Create an instance of this class: ```Java ScreenUtility utility = new ScreenUtility(this); ``` (We need to pass the current activity to it in the constructor) 3. Declare your view objects, for example a button: ```Java Button myButton = (Button)findViewById(R.id.mybutton); ``` 4. Set its dimensions! ```Java int width = 100; int height = 20; utility.setViewObjectDimensionsAsPercentage(height, width, myButton); ``` The view object will now be the size you gave it, in percentage, of the total height and width of the screen size.
1570c3723ea48cab7a838e9a4c3e7ba8f7456148
[ "Markdown", "Java" ]
2
Java
skumar2998/ScreenUtility
8f6d9186d7fb006077a1085738e0cd7f461188aa
eed64e97adf330c1c9964495a8f7a0978e371001
refs/heads/master
<repo_name>bnguyen14/StockCharts<file_sep>/stock-chart-angular/src/app/charts/charttimeseries.ts import { Charttime } from './charttime'; import { Chartdata } from './chartdata'; export interface Charttimeseries{ list: Charttime[]; } <file_sep>/stock-chart-angular/src/app/charts/charts.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CandlestickComponent } from './candlestick/candlestick.component'; import * as CanvasJS from '../../assets/canvasjs.min.js'; @NgModule({ declarations: [CandlestickComponent], imports: [ CommonModule ] }) export class ChartsModule { } <file_sep>/stock-chart-spring/src/main/java/pyramid/controllers/ChartController.java package pyramid.controllers; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.List; import org.json.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import pyramid.models.ChartData; import pyramid.models.RespModel; @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/chart") public class ChartController { @Value("${api.key}") private String apiKey; @GetMapping(value = "/intraday/{symbol}/{interval}") public ResponseEntity<RespModel> getIntradayChartData(@PathVariable String symbol, @PathVariable String interval) { String url = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo"; // String url = "https://www.alphavantage.co/query?" // + "function=TIME_SERIES_INTRADAY" // + "&symbol="+symbol // + "&interval="+interval // + "&apikey="+apiKey; return constructRespEntity("intraday", url); } @GetMapping(value = "/swing/{symbol}/{interval}") public ResponseEntity<RespModel> getLongChartData(@PathVariable String symbol, @PathVariable String interval) { String url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo"; // String url = "https://www.alphavantage.co/query?" // + "function=TIME_SERIES_"+interval.toUpperCase() // + "&symbol="+symbol // + "&apikey="+apiKey; return constructRespEntity("swing", url); } private ResponseEntity<RespModel> constructRespEntity(String format, String url) { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); ObjectMapper mapper = new ObjectMapper(); RespModel rm = null; try { rm = mapper.readValue(response.getBody(), RespModel.class); JSONObject obj = new JSONObject(response.getBody()); JSONObject timeseries = obj.getJSONObject(JSONObject.getNames(obj)[0]); String[] series = JSONObject.getNames(timeseries); Arrays.sort(series); for(int i = 0; i< series.length; i++) { rm.getTimeSeries().addToSeries(format.equals("intraday")?dateToUnix(series[i]):series[i], mapper.readValue(timeseries.getJSONObject(series[i]).toString(), ChartData.class)); } } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ResponseEntity<RespModel>(rm, HttpStatus.OK); } private String dateToUnix(String date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return String.valueOf(sdf.parse(date).getTime()/1000); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "conversion error"; } } <file_sep>/stock-chart-angular/src/app/charts/candlestick/candlestick.component.ts import { Component, OnInit, HostListener } from '@angular/core'; import { ChartserviceService } from '../chartservice.service'; import { createChart } from 'lightweight-charts'; import { Chartdata } from '../chartdata'; @Component({ selector: 'app-candlestick', templateUrl: './candlestick.component.html', styleUrls: ['./candlestick.component.css'] }) export class CandlestickComponent implements OnInit { ticker = "aapl"; dataPoints = []; chartdata:Chartdata; chart; candlestickSeries; constructor(private ChartService:ChartserviceService) { } ngOnInit() { this.ChartService.getSwingChartData().subscribe( data => { console.log(data); this.chartdata=data; // console.log(this.chartdata.MetaData); // console.log(this.chartdata.TimeSeries.list); this.ticker=this.chartdata.MetaData.Symbol; this.chartdata.TimeSeries.list.forEach(element => { if(this.chartdata.MetaData.Interval){ this.dataPoints.push({ time: +element.time, open: element.open, high: element.high, low: element.low, close: element.close }); }else{ this.dataPoints.push({ time: element.time, open: element.open, high: element.high, low: element.low, close: element.close }); } }); this.setChart(); } ); } @HostListener('window:resize', ['$event']) onResize(event) { this.chart.resize(300,window.innerWidth); } setChart(){ this.chart = createChart(document.body, { width: window.innerWidth, height: 300 }); this.candlestickSeries = this.chart.addCandlestickSeries(); this.candlestickSeries.setData(this.dataPoints); } } <file_sep>/stock-chart-angular/src/app/charts/chartmetadata.ts export interface Chartmetadata { Information:string; Symbol:string; LastRefreshed:string; Interval:string; OutputSize:string; TimeZone:string; } <file_sep>/stock-chart-angular/src/app/charts/charttime.spec.ts import { Charttime } from './charttime'; describe('Charttime', () => { it('should create an instance', () => { expect(new Charttime()).toBeTruthy(); }); }); <file_sep>/stock-chart-angular/src/app/charts/chartmetadata.spec.ts import { Chartmetadata } from './chartmetadata'; describe('Chartmetadata', () => { it('should create an instance', () => { expect(new Chartmetadata()).toBeTruthy(); }); }); <file_sep>/stock-chart-angular/src/app/charts/chartservice.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Chartdata } from './chartdata'; @Injectable({ providedIn: 'root' }) export class ChartserviceService { constructor(private httpClient : HttpClient) { } //https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo getIntraChartData(){ return this.httpClient.get<Chartdata>("http://localhost:8080/chart/intraday/TSLA/1min"); } getSwingChartData(){ return this.httpClient.get<Chartdata>("http://localhost:8080/chart/swing/TSLA/Daily"); } } <file_sep>/stock-chart-spring/src/main/java/pyramid/models/ChartData.java package pyramid.models; import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class ChartData { @JsonProperty("time") private String time; @JsonProperty("open") @JsonAlias("1. open") private float open; @JsonProperty("high") @JsonAlias("2. high") private float high; @JsonProperty("low") @JsonAlias("3. low") private float low; @JsonProperty("close") @JsonAlias("4. close") private float close; @JsonProperty("volume") @JsonAlias("5. volume") private float volume; public ChartData() {} public ChartData(String time, float open, float high, float low, float close, float volume) { super(); this.time = time; this.open = open; this.high = high; this.low = low; this.close = close; this.volume = volume; } public void setTime(String time) { this.time = time; } @Override public String toString() { return "ChartData [time=" + time + ", open=" + open + ", high=" + high + ", low=" + low + ", close=" + close + ", volume=" + volume + "]"; } } <file_sep>/stock-chart-angular/src/app/charts/charttime.ts export class Charttime { time:string; open:number; high:number; low:number; close:number; volume:number; } <file_sep>/stock-chart-spring/target/classes/application.properties api.key = <KEY><file_sep>/stock-chart-angular/src/app/charts/charttimeseries.spec.ts import { Charttimeseries } from './charttimeseries'; describe('Charttimeseries', () => { it('should create an instance', () => { expect(new Charttimeseries()).toBeTruthy(); }); }); <file_sep>/stock-chart-angular/src/app/charts/chartdata.ts import { Chartmetadata } from './chartmetadata'; import { Charttimeseries } from './charttimeseries'; export interface Chartdata { MetaData:Chartmetadata; TimeSeries:Charttimeseries; }
8b561d81eb0a7d9d3ffeb3d6548ef73d9377d919
[ "Java", "TypeScript", "INI" ]
13
TypeScript
bnguyen14/StockCharts
65aba0d2a8b90da934531df79476a3d67de555f0
e0e20f6aba8e760993207f5be51aca52cd9fbfb0
refs/heads/master
<repo_name>Sheynckes/Seader<file_sep>/README.md # Seader 本项目开发一个txt阅读器,主要实现以下功能: - 生成全书的词频统计(简单的计数); - 给出选中单词的释义(关联本地词典); - 通过next按钮顺序查询其在文中出现的位置,并高亮显示该单词;<file_sep>/Seader.py # -*- coding: utf-8 -*- import os import tkinter as tk from tkinter import filedialog import string import urllib from bs4 import BeautifulSoup YOUDAO = 'http://youdao.com/w/%s/#keyfrom=dict2.top' class Application(object): def __init__(self): self.root = tk.Tk() self.root.title('Seader') self.root.geometry('+800+400') self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.create_frm_tools() self.create_frm_txt() self.create_frm_words() self.create_paras() self.root.mainloop() def create_frm_tools(self): self.frm_tools = tk.Frame(self.root) self.frm_tools.pack(fill=tk.X) self.btn_open = tk.Button(self.frm_tools, text='Open Book', command=self.open_book) self.btn_open.pack(padx=10, side=tk.LEFT) self.btn_count = tk.Button(self.frm_tools, text='Count Word', command=self.count_word) self.btn_count.pack(padx=10, side=tk.LEFT) def create_frm_txt(self): self.frm_txt = tk.Frame(self.root) self.frm_txt.pack(side=tk.LEFT, fill=tk.BOTH) self.scrl_novel = tk.Scrollbar(self.frm_txt) self.scrl_novel.pack(side=tk.RIGHT, fill=tk.Y) self.txt_novel = tk.Text(self.frm_txt, height=40, yscrollcommand=self.scrl_novel.set) self.txt_novel.pack(side=tk.LEFT, fill=tk.BOTH) self.scrl_novel.config(command=self.txt_novel.yview) def create_frm_words(self): self.frm_words = tk.Frame(self.root, width=30) self.frm_words.pack(side=tk.LEFT, fill=tk.Y) self.frm_search = tk.Frame(self.frm_words) self.frm_search.pack(fill=tk.X) self.entry_search = tk.Entry(self.frm_search, width=10, borderwidth=0, background='LightGrey') self.entry_search.pack(padx=5, side=tk.LEFT) self.label_result = tk.Label(self.frm_search) self.label_result.pack(padx=5, side=tk.LEFT) self.frm_btns = tk.Frame(self.frm_words) self.frm_btns.pack(fill=tk.X) self.btn_define = tk.Button(self.frm_btns, text='Define', command=self.define_word) self.btn_define.pack(padx=5, side=tk.LEFT) self.btn_previous = tk.Button(self.frm_btns, text='Previous', command=self.previous_word, state=tk.DISABLED) self.btn_previous.pack(padx=5, side=tk.LEFT) self.btn_next = tk.Button(self.frm_btns, text='Next', command=self.next_word) self.btn_next.pack(padx=5, side=tk.LEFT) self.frm_definition = tk.Frame(self.frm_words) self.frm_definition.pack(fill=tk.X) self.scrl_definition = tk.Scrollbar(self.frm_definition) self.scrl_definition.pack(side=tk.RIGHT, fill=tk.Y) self.txt_definition = tk.Text(self.frm_definition, width=25, height=20, yscrollcommand=self.scrl_definition.set) self.txt_definition.pack(side=tk.LEFT, fill=tk.BOTH) self.scrl_definition.config(command=self.txt_definition.yview) self.label_count = tk.Label(self.frm_words, text='Word Counts: ', anchor=tk.W, background='Gainsboro') self.label_count.pack(fill=tk.X) self.frm_count = tk.Frame(self.frm_words) self.frm_count.pack(fill=tk.BOTH) self.scrl_count = tk.Scrollbar(self.frm_count) self.scrl_count.pack(side=tk.RIGHT, fill=tk.Y) self.lb_count = tk.Listbox(self.frm_count, height=18, yscrollcommand=self.scrl_count.set) self.lb_count.pack(side=tk.LEFT, fill=tk.BOTH) self.scrl_count.config(command=self.lb_count.yview) self.lb_count.bind('<Double-Button-1>', self.define_word_from_lb) def create_paras(self): self.idx = 1.0 self.word_temp = '' self.word_num = 0 def open_book(self): filename = filedialog.askopenfile() with open(filename.name, 'r') as filetxt: self.txt_novel.delete(1.0, tk.END) self.txt_novel.insert(tk.END, filetxt.read()) # self.count_word() def not_stop_words(self, word): stop_words_file = open("stop_words.txt", "r") stop_words_list = stop_words_file.read().split(",") stop_words_file.close() if not (word in stop_words_list): return word def word_cleaning(self, word): word = word.strip(string.punctuation+"""!?,.'“”-…""") if word.isalpha(): return word.lower() def count_word(self): txt = self.txt_novel.get(1.0, tk.END) self.wc_dict = {} for word in txt.split(): word = self.word_cleaning(word) word = self.not_stop_words(word) if word in self.wc_dict: self.wc_dict[word] += 1 else: self.wc_dict[word] = 1 word_counts = [] for word, count in self.wc_dict.items(): if word: word_counts.append({"word": word, "count": count}) self.word_by_counts = sorted(word_counts, key=lambda d: (d['count'], d['word']), reverse=True) for d in self.word_by_counts: self.lb_count.insert(tk.END, '(%03d) %s' %(d["count"], d["word"])) def define_word(self): self.txt_definition.delete(1.0, tk.END) url = YOUDAO % self.entry_search.get() resp = urllib.request.urlopen(url) html = resp.read() soup = BeautifulSoup(html, 'lxml') pronunciation = soup.find('div', attrs={'class': 'baav'}).get_text() p_list = pronunciation.split() self.txt_definition.insert(tk.END, ' '.join(p_list)) definition = soup.find('div', attrs={'class': 'trans-container'}) self.txt_definition.insert(tk.END, os.linesep + definition.ul.get_text()) if definition.p: additional = definition.p.get_text() a_list = additional.split() self.txt_definition.insert(tk.END, os.linesep*2 + ' '.join(a_list)) def define_word_from_lb(self, btn_obj): self.entry_search.delete(0, tk.END) self.word_search = self.lb_count.selection_get().split()[-1] self.entry_search.insert(tk.END, self.word_search) self.define_word() def previous_word(self): self.word_num -= 1 self.label_result.config(text='%d of %d' % (self.word_num, self.word_total)) self.word_start = self.txt_novel.search(' %s ' % self.word_search, self.word_start, backwards=True) idx_dot = self.word_start.index('.') line = int(self.word_start[0: idx_dot]) column = int(self.word_start[idx_dot+1: ]) self.word_end = str(line) + '.' + str(column + self.word_len + 1) self.txt_novel.tag_delete('bg') self.txt_novel.tag_add('bg', self.word_start, self.word_end) self.txt_novel.tag_config('bg', background='yellow') self.txt_novel.see(self.word_start) if self.word_num == self.word_total - 1: self.btn_next.config(state=tk.NORMAL) if self.word_num == 1: self.btn_previous.config(state=tk.DISABLED) def next_word(self): self.word_search = self.entry_search.get() if self.word_search and (self.word_search != self.word_temp): self.word_end = '1.0' self.word_num = 0 self.word_temp = self.word_search self.txt_novel.tag_delete('bg') elif self.word_search == self.word_temp: self.txt_novel.tag_delete('bg') self.word_len = len(self.word_search) self.word_start = self.txt_novel.search(' %s ' % self.word_search, self.word_end) if self.word_start: self.word_num += 1 self.word_total = self.wc_dict[self.word_search] self.label_result.config(text='%d of %d' % (self.word_num, self.word_total)) idx_dot = self.word_start.index('.') line = int(self.word_start[0: idx_dot]) column = int(self.word_start[idx_dot+1: ]) self.word_end = str(line) + '.' + str(column + self.word_len + 1) self.txt_novel.tag_add('bg', self.word_start, self.word_end) self.txt_novel.tag_config('bg', background='yellow') self.txt_novel.see(self.word_start) self.btn_previous.config(state=tk.NORMAL) if self.word_num == self.word_total: self.btn_next.config(state=tk.DISABLED) else: self.label_result.config(text='0') if __name__ == '__main__': app = Application()
4a42335c3d8232e758d94113a557ae7de5510d3c
[ "Markdown", "Python" ]
2
Markdown
Sheynckes/Seader
8b703a875a64e2a01ec0e3f04577a763599d0f34
309125a5ef09271a14a0d75dbbf71980a8f60d90
refs/heads/master
<file_sep>require "e1505to_okamura/version" require "bigdecimal" module E1505toOkamura # Your code goes here... print 'Please set price(without tax) : ' price = gets.chomp.to_i print 'Please set sales_date : ' date = gets.chomp.to_i #日付を元に消費税率を設定 if date < 19890401 then taxrt = BigDecimal("1.00") elsif date < 19970401 then taxrt = BigDecimal("1.03") elsif date < 20140401 then taxrt = BigDecimal("1.05") elsif date < 20170401 then taxrt = BigDecimal("1.08") else taxrt = BigDecimal("1.10") end #価格*(1+税率) price_wt = ( (BigDecimal( price ) * taxrt).floor ) print "Price with tax is " print price_wt print " at " print date puts "." end <file_sep>#!/usr/bin/env ruby require "e1505to_okamura" if ARGV.size != 2 STDERR.print "Usage: ruby#{$0} price shipping_date(YYYYMMDD)\n" exit end #puts "PRICE:" + ARGV[0] #puts "SHIPPING DATE:" + ARGV[1] price = ARGV[0].to_i date = ARGV[1].to_i puts E1505toOkamura.new_method(price,date)
5698e9cd8d5a71bd8e468aa3bc9937fc4c1a9f63
[ "Ruby" ]
2
Ruby
okamuratakeshi/e1505to_okamura
64b2104da10a62214e47ec6e7f099ecbf7ab0728
26c25a65c9f8318835461372d2a4850701bac088
refs/heads/main
<file_sep>#define IR_SENSOR_RIGHT 11 #define IR_SENSOR_LEFT 12 #define MOTOR_SPEED 180 //Right motor int enableRightMotor=6; int rightMotorPin1=7; int rightMotorPin2=8; //Left motor int enableLeftMotor=5; int leftMotorPin1=9; int leftMotorPin2=10; void setup() { //The problem with TT gear motors is that, at very low pwm value it does not even rotate. //If we increase the PWM value then it rotates faster and our robot is not controlled in that speed and goes out of line. //For that we need to increase the frequency of analogWrite. //Below line is important to change the frequency of PWM signal on pin D5 and D6 //Because of this, motor runs in controlled manner (lower speed) at high PWM value. //This sets frequecny as 7812.5 hz. TCCR0B = TCCR0B & B11111000 | B00000010 ; // put your setup code here, to run once: pinMode(enableRightMotor, OUTPUT); pinMode(rightMotorPin1, OUTPUT); pinMode(rightMotorPin2, OUTPUT); pinMode(enableLeftMotor, OUTPUT); pinMode(leftMotorPin1, OUTPUT); pinMode(leftMotorPin2, OUTPUT); pinMode(IR_SENSOR_RIGHT, INPUT); pinMode(IR_SENSOR_LEFT, INPUT); rotateMotor(0,0); } void loop() { int rightIRSensorValue = digitalRead(IR_SENSOR_RIGHT); int leftIRSensorValue = digitalRead(IR_SENSOR_LEFT); //If none of the sensors detects black line, then go straight if (rightIRSensorValue == LOW && leftIRSensorValue == LOW) { rotateMotor(MOTOR_SPEED, MOTOR_SPEED); } //If right sensor detects black line, then turn right else if (rightIRSensorValue == HIGH && leftIRSensorValue == LOW ) { rotateMotor(-MOTOR_SPEED, MOTOR_SPEED); } //If left sensor detects black line, then turn left else if (rightIRSensorValue == LOW && leftIRSensorValue == HIGH ) { rotateMotor(MOTOR_SPEED, -MOTOR_SPEED); } //If both the sensors detect black line, then stop else { rotateMotor(0, 0); } } void rotateMotor(int rightMotorSpeed, int leftMotorSpeed) { if (rightMotorSpeed < 0) { digitalWrite(rightMotorPin1,LOW); digitalWrite(rightMotorPin2,HIGH); } else if (rightMotorSpeed > 0) { digitalWrite(rightMotorPin1,HIGH); digitalWrite(rightMotorPin2,LOW); } else { digitalWrite(rightMotorPin1,LOW); digitalWrite(rightMotorPin2,LOW); } if (leftMotorSpeed < 0) { digitalWrite(leftMotorPin1,LOW); digitalWrite(leftMotorPin2,HIGH); } else if (leftMotorSpeed > 0) { digitalWrite(leftMotorPin1,HIGH); digitalWrite(leftMotorPin2,LOW); } else { digitalWrite(leftMotorPin1,LOW); digitalWrite(leftMotorPin2,LOW); } analogWrite(enableRightMotor, abs(rightMotorSpeed)); analogWrite(enableLeftMotor, abs(leftMotorSpeed)); } <file_sep># LineFollowerRobot This repository contains code and diagram for Line Follower Robot using Arduino
a5d0be7cc3161925cf2ff61f08d5f9f806e5700d
[ "Markdown", "C++" ]
2
C++
Rhevathi/LineFollowerRobot-
ed1202f7e7e88c642b585218aa7c5e14ea0653f8
e32da51363243f119420e97321b1127c6b1be53e
refs/heads/master
<repo_name>koslibpro/python-web-crawler<file_sep>/modules/frontier.py __author__ = 'koslib' import logging class Frontier: FRONTIER = [] INDEXED = [] def __init__(self): link = "http://stanford.edu" self.FRONTIER.append(link) # initialize frontier list def load_frontier(self): return self.FRONTIER def update_frontier(self, new_list): try: del new_list[0] self.FRONTIER = new_list self.remove_duplicates() return True except Exception, e: logging.error(e) return False def next_frontier_url(self): try: return self.FRONTIER[0] except Exception, e: logging.error(e) return None def remove_duplicates(self): seen = set() seen_add = seen.add return [x for x in self.FRONTIER if not (x in seen or seen_add(x))] def remove_url(self, url_to_be_removed): self.FRONTIER.remove(url_to_be_removed) def add_to_indexed(self, checksum): try: self.INDEXED.append(checksum) except Exception, e: logging.error(e) def load_indexed(self): return self.INDEXED <file_sep>/modules/parse.py __author__ = 'koslib' from bs4 import BeautifulSoup import re import hashlib import logging import robotparser from modules.frontier import Frontier class Parser: def __init__(self, current_url, content): self.current_url = current_url self.content = content def parse(self): # main parsing method to be called from Fetcher hashed = self.fingerprint() frontier_obj = Frontier() indexed_list = frontier_obj.load_indexed() if hashed not in indexed_list: frontier_obj.add_to_indexed(hashed) links = self.extract_links() self.update_frontier(links) else: links = self.extract_links() self.update_frontier(links) def extract_links(self): links_temp = [] # temporary links list links = [] # normalized links list soup = BeautifulSoup(self.content) for link in soup.findAll('a'): # for links_temp starting with "http://", # we should use soup.findAll('a', attrs={'href': re.compile("^http://")}) link = link.get('href') links_temp.append(link) # normalize urls and make relative paths absolute links_temp = self.normalize_links(links_temp) for link in links_temp: try: if link not in links: # do not insert duplicate links.append(link) except Exception, e: logging.warning(e) pass return links def normalize_links(self, links): normalized_links = [] try: for link in links: if link == "/" or link == "#": continue if "http://" not in link and "https://" not in link: link = "%s%s" % (self.current_url, link) normalized_links.append(link) elif link is "http:///" or link is "https:///" \ or link is "http://#" or link is "https://#": continue else: normalized_links.append(link) except Exception, e: logging.warning(e) return normalized_links def update_frontier(self, links): frontier_obj = Frontier() frontier = frontier_obj.load_frontier() del frontier[0] # remove item just indexed from frontier list # parse and respect robots rp = robotparser.RobotFileParser() rp.set_url("%s/robots.txt" % self.current_url) rp.read() for link in links: if link not in frontier: # be polite & respect robots if rp.can_fetch("*", link): frontier.append(link) # finally update the frontier of this thread frontier_obj.update_frontier(frontier) def fingerprint(self): m = hashlib.md5() m.update(self.striped_html_content()) print "Checksum: %s" % m.hexdigest() return m.hexdigest() def striped_html_content(self): p = re.compile(r'<.*?>') return str(p.sub('', self.content)) <file_sep>/main.py __author__ = 'koslib' <file_sep>/modules/fetch.py __author__ = 'koslib' import requests import logging from modules.parse import Parser from modules.frontier import Frontier class Fetcher: def __init__(self, url): self.url = url self.get_content() def dns_check(self): try: r = requests.get(self.url) if r.status_code == requests.codes.ok: return True else: frontier = Frontier() logging.error("Could not fetch url %s" % self.url) frontier.remove_url(self.url) pass except Exception, e: logging.error("Exception occurred: %s" % e) pass return False def fetch(self): try: r = requests.get(self.url) r.links.viewitems() content = r.text except Exception, e: logging.error(e) content = None return content def fetch_html(self): try: r = requests.get(self.url) html = r.content except Exception, e: logging.error(e) html = None return html def get_content(self): try: if self.dns_check(): content = self.fetch() html = self.fetch_html() # fire up the parser after exiting fetching module parser = Parser(self.url, html) parser.parse() # return content, html else: # return None, None logging.warning("DNS Check failed in get_content() method on url %s" % self.url) pass except Exception, e: logging.warning(e) <file_sep>/README.md # python-web-crawler Minimal web crawler in Python, for research (university task) reasons <file_sep>/requirements.txt pbr==0.10.8 requests==2.7.0 six==1.9.0 stevedore==1.3.0 virtualenv==12.1.1 virtualenv-clone==0.2.5 virtualenvwrapper==4.5.0 <file_sep>/modules/utils.py __author__ = 'koslib' def clean_url(url): return str(url).replace("http://", "").replace("https://", "")<file_sep>/crawler.py __author__ = 'koslib' #TODO: complete the crawling process description """ The crawling process: to be completed """ from modules.fetch import Fetcher from modules.frontier import Frontier class Crawler: def __init__(self): pass def crawl(self): frontier = Frontier() loop = 0 while len(frontier.load_frontier()) >= 1: loop += 1 url = frontier.next_frontier_url() fetch = Fetcher(url) print "Loop: %s \nFRONTIER length: %s\nURL to occupy: %s\n============" % (loop, len(frontier.FRONTIER), url) if __name__ == '__main__': crawler = Crawler() crawler.crawl() <file_sep>/modules/housekeeping.py __author__ = 'koslib' def crawl_progress(): pass def frontier_size(): pass def checkpoint(): """ In checkpointing, a snapshot of the crawler's state (say, the URL frontier) is committed to disk. In the event of a catastrophic crawler failure, the crawl is restarted from the most recent checkpoint. """ pass
87ccdee96ea2901bf3932082ec9a35548f78dfac
[ "Markdown", "Python", "Text" ]
9
Python
koslibpro/python-web-crawler
c1812dc552c36358d3bc61b83230c3a097298a6f
2737a553ceadbb625d913671adb3d08a0254938c
refs/heads/master
<repo_name>sayan711/Fahrenheit2Celsius<file_sep>/src/com/company/Main.java package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("What is today's temperature in fahrenheit?"); Scanner scan = new Scanner(System.in); int temp = input.nextInt(); System.out.println("Today's temperature in celsius is " + (temp-32)/1.8 ); } }
046bab4101d9816ed5d3d12c6b800b6974877f52
[ "Java" ]
1
Java
sayan711/Fahrenheit2Celsius
b32e785a2e6050261e04519ab1a8302116885676
b76ba1b647010d8639aa52d9d9ce86110056dd14
refs/heads/master
<repo_name>egovaflavia/Training-CIShop-Codepolitan<file_sep>/application/views/layouts/app.php <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="<NAME>, <NAME>, and Bootstrap contributors"> <meta name="generator" content="Jekyll v3.8.5"> <title><?= isset($title) ? $title : 'CIShop' ?> - Codeigniter E-Commerce</title> <link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/navbar-fixed/"> <!-- Bootstrap core CSS --> <link href="assets/libs/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- fontawesome css --> <link rel="stylesheet" href="assets/libs/fontawesome/css/all.min.css"> <link href="assets/css/up.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-expand-md navbar-light fixed-top bg-light"> <div class="container"> <a class="navbar-brand" href="#">CIShop</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item dropdown"> <a href="#" class="nav-link dropdown-toggle" id="dropdown-1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Manage</a> <div class="dropdown-menu" aria-labelledby="dropdown-1"> <a href="/admin-category.html" class="dropdown-item">Kategori</a> <a href="/admin-product.html" class="dropdown-item">Produk</a> <a href="/admin-order.html" class="dropdown-item">Order</a> <a href="/admin-users.html" class="dropdown-item">Pengguna</a> </div> </li> </ul> <ul class="navbar-nav"> <li class="nav-item"> <a href="/cart.html" class="nav-link"><i class="fas fa-shopping-cart"></i> Cart(0)</a> </li> <li class="nav-item"> <a href="/login.html" class="nav-link">Login</a> </li> <li class="nav-item"> <a href="/register.html" class="nav-link">Register</a> </li> <li class="nav-item dropdown"> <a href="#" class="nav-link dropdown-toggle" id="dropdown-2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Admin</a> <div class="dropdown-menu" aria-labelledby="dropdown-2"> <a href="/profile.html" class="dropdown-item">Profile</a> <a href="/orders.html" class="dropdown-item">Orders</a> <a href="#" class="dropdown-item">Logout</a> </div> </li> </ul> </div> </div> </nav> <!-- Content --> <?php $this->load->view($page); ?> <!-- EndContent --> <script src="assets/libs/jquery/jquery-3.5.1.min.js"></script> <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="assets/js/up.js"></script> </body> </html>
c7ccfd50012252b0f63285da961780f61ba446cd
[ "PHP" ]
1
PHP
egovaflavia/Training-CIShop-Codepolitan
c298b2a1e613c6e55fcc023a401ede9e283516da
986f55d200462643f6589a8102ff6b8d37db3884
refs/heads/master
<repo_name>cubejs/raptor-dust<file_sep>/lib/widgets-helpers.js exports.addHelpers = function(dust) { var InitWidgetsTag = require('raptor/templating/taglibs/widgets/InitWidgetsTag'); dust.helpers.initWidgets = function(chunk, context, bodies, params) { return dust.invokeRenderer(InitWidgetsTag, chunk, context, bodies, params); }; };<file_sep>/lib/index.js var path = require('path'); var fs = require('fs'); function write(str) { this._dustChunk.write(str); return this; } var chunkToRenderContext; function beginAsyncFragment(callback, timeout) { var raptorContext = this._raptorContext; this._dustChunk = this._dustChunk.map(function(asyncChunk) { var newChunkContext = chunkToRenderContext(asyncChunk, raptorContext); callback(newChunkContext, { end: function() { newChunkContext._dustChunk.end(); } }); }); } function renderDustBody(body, context) { var newChunk = this._dustChunk.render(body, context); this._dustChunk = newChunk; } chunkToRenderContext = function(chunk, raptorContext) { var newContext = Object.create(raptorContext); newContext._raptorContext = raptorContext; newContext._dustChunk = chunk; newContext.write = write; newContext.w = write; newContext.beginAsyncFragment = beginAsyncFragment; newContext.renderDustBody = renderDustBody; return newContext; }; function invokeRenderer(tag, chunk, context, bodies, params) { var request = context.get('request'); var raptorContext = request.raptorContext; var renderContext = chunkToRenderContext(chunk, raptorContext); var render = tag.render || tag.process; params = params || {}; if (!render) { var proto = tag.prototype; if (proto) { render = proto.render || proto.process; } } render.call(tag, params, renderContext); return renderContext._dustChunk; } function configureDust(dust, srcDir) { dust.onLoad = function(path, callback){ if (!path.endsWith('.dust')) { path += '.dust'; } if (!path.startsWith('/')) { path = srcDir + '/' + path; } else { path = srcDir + path; } fs.readFile(path, 'UTF-8', callback); }; dust.invokeRenderer = invokeRenderer; dust.helpers.component = function(chunk, context, bodies, params) { var renderer = params.renderer; for (var k in params) { if (params.hasOwnProperty(k)) { if (k === 'true') { params[k] = true; } else if (k === 'false') { params[k] = false; } } } return invokeRenderer(require(renderer), chunk, context, bodies, params); }; require('./optimizer-helpers').addHelpers(dust); require('./async-helpers').addHelpers(dust); require('./widgets-helpers').addHelpers(dust); } exports.configureDust = configureDust;<file_sep>/README.md raptor-dust =========== Support module for integrating Dust and RaptorJS
27ded0dc6b163e8d320697f8507c82be7e4fa07d
[ "JavaScript", "Markdown" ]
3
JavaScript
cubejs/raptor-dust
3d1fab6ef4407d48b8e88a4ad9be9ee0b30bbd57
aa94ebfbb92ccfbd8621bfaa9bd89e5409197d03
refs/heads/master
<file_sep>import React from 'react'; import { Link } from 'react-router-dom'; const PageNotFound = () => { return ( <div> <h1>Page Not Found</h1> <p>Woops! Looks like you're a little lost? <Link to={HomePage}>Go Home</Link></p> </div> ) } export default PageNotFound <file_sep>import React from 'react' const Footer = () => { return ( <footer> <div className="main-wrapper"> <p>All Rights Reversed! {new Date().getFullYear()}</p> <div className="crane-kudos"><p>Crane Icon made by <a href="https://www.flaticon.com/authors/mynamepong" title="mynamepong">mynamepong</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a></p></div> </div> </footer> ) } export default Footer <file_sep>import React, { useState } from 'react' const SelectService = ({addClass, options, onChange, value}) => { return ( <> <select className={addClass} onChange={onChange} value={value} > {options.map((option) => { return <option key={option.optionValue} value={option.optionValue}>{option.textContent}</option> })} </select> </> ) } export default SelectService <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; // ReactDOM.createPortal(child, container) const appRoot = document.getElementById('root'); const modalRoot = document.getElementById('modal-root') class Modal extends React.Component { constructor(props) { super(props); this.el = document.createElement('div'); } componentDidMount() { modalRoot.appendChild(this.el) } componentWilUnmount() { modalRoot.removeChild(this.el) } render() { return ReactDOM.createPortal( this.props.children, this.el ) } } class Parent extends React.Component { constructor(props) { super(props) this.state = { clicks: 0 }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState((prevState) => { return { clicks: prevState.clicks + 1 } }) } render () { return ( <div onClick={this.handleClick}> <p>Number of clicks: {this.state.clicks}</p> <p> Open up the browser DevTools to observe that the button is not a child of the div with the onclick handler. </p> <Modal> <Child /> </Modal> </div> ) } } function Child() { return ( <div className="modal"> <button>Click</button> </div> ) } ReactDOM.render(<Parent />, appRoot)<file_sep>import React, { useContext, useState, useEffect } from 'react'; import moment from 'moment'; import { BlogsContext } from '../contexts/BlogsContext'; import { getVisibleItems } from '../selectors/global'; import GridService from './services/GridService/GridService'; import PaginationService from './services/PaginationService/PaginationService'; import SelectService from './services/SelectService/SelectService'; import { DateRangePicker } from 'react-dates'; const ArticlesPage = () => { const { blogs } = useContext(BlogsContext); // filtered items will hold an array of the remaining blogs, once they've been passed through the filters. // the state before filtering starts off as just a copy of blogs const [ filteredItems, setfilteredItems ] = useState([...blogs]); const [ filters, setFilters ] = useState({ show: 'all', sortBy: 'desc', startOfRangeDate: moment().subtract(180, 'days'), endOfRangeDate: moment() }); // paginatedItems takes the filtered items and tracks the current page of projects const [ paginatedItems, setPaginatedItems ] = useState([...filteredItems]) const [ paginationSettings, setPaginationSettings ] = useState({ onPage: 1, itemsPerPage: 6 }); // For react-dates date-picker const [ focusedInput, setFocusedInput ] = useState(null) const onDatesChange = ({startDate, endDate}) => { setfilteredItems([...blogs]) setFilters({ ...filters, startOfRangeDate: startDate, endOfRangeDate: endDate }) } const onFocusChange = (focusedInput) => { setFocusedInput(focusedInput) } const falseFunc = () => false; const getArticlesByTag = (show) => { // As done in other functions first need to reset the subset back to all blogs (clean slate), then set the new filters, which in turn will cause useEffect to run which will pass the blogs through the filters using getVissibleItems selector function. setfilteredItems([...blogs]) setFilters({ ...filters, show }) } const articlesFilterOptions = [{ optionValue: 'all', textContent: 'All', },{ optionValue: 'the web', textContent: 'The Web' },{ optionValue: 'javascript', textContent: 'Javascript' },{ optionValue: 'nodeJS', textContent: 'NodeJS' },{ optionValue: 'css', textContent: 'CSS' },{ optionValue: 'reactJS', textContent: 'ReactJS' },{ optionValue: 'angular', textContent: 'Angular' },{ optionValue: 'web components', textContent: 'Web Components' },{ optionValue: 'expressJS', textContent: 'ExpressJS' }]; const articlesSortOptions = [{ optionValue: 'desc', textContent: 'Latest Top', },{ optionValue: 'asc', textContent: 'Oldest Top', }]; const onSortChange = (e) => { setFilters({ ...filters, sortBy: e.target.value }) } const onFilterChange = (e) => { // reset the data setfilteredItems([...blogs]) setFilters({ ...filters, show: e.target.value }) } const onPageClicked = (e) => { console.log(`Page number ${parseInt(e.target.textContent)} was clicked....`); setPaginationSettings({ ...paginationSettings, onPage: parseInt(e.target.textContent) }) } useEffect(() => { setfilteredItems(getVisibleItems('blogs', filteredItems, filters)); setPaginationSettings({ ...paginationSettings, onPage: 1 }) }, [filters]) useEffect(() => { getPageItems() }, [filteredItems, paginationSettings]) const getPageItems = () => { const skip = (paginationSettings.onPage - 1) * paginationSettings.itemsPerPage; const paginated = [...filteredItems].splice(skip, paginationSettings.itemsPerPage); setPaginatedItems(paginated) } return ( <> <section className="sect blogs-page"> <h1>All Articles</h1> <p>Some of my latest, usually troubled musings :)</p> <div className="select-filters blogs-filters"> Showing <SelectService addClass="select-css" options={articlesFilterOptions} onChange={onFilterChange} value={filters.show} /> related entries with the <SelectService addClass="select-css" options={articlesSortOptions} onChange={onSortChange} /> </div> that were created between <DateRangePicker startDate={filters.startOfRangeDate} // momentPropTypes.momentObj or null, startDateId="startDateRange" // PropTypes.string.isRequired, endDate={filters.endOfRangeDate} // momentPropTypes.momentObj or null,` endDateId="endDateRange" // PropTypes.string.isRequired, onDatesChange={onDatesChange} focusedInput={focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null, onFocusChange={onFocusChange} // PropTypes.func.isRequired, numberOfMonths={1} isOutsideRange={falseFunc} showClearDates={false} /> </section> <section className="sect blogs-page"> <PaginationService listLength={filteredItems.length} onPageClicked={onPageClicked} paginationSettings={paginationSettings} /> <GridService list={paginatedItems} imgOverlay={true} serviceType={"blogsThumb"} staticOverlay={true} getArticlesByTag={getArticlesByTag} /> </section> </> ) } export default ArticlesPage <file_sep>import React from 'react' import { Link } from 'react-router-dom'; import moment from 'moment'; const BlogsThumbOverlay = ({item, getArticlesByTag}) => { const getDate = (stamp) => { return moment(stamp).format('MMMM Do, YYYY'); } const onClick = (e) => { const content = e.target.textContent; console.log(content) getArticlesByTag(content) } return ( <> <p className="blogs-thumb-date">Posted:{getDate(item.createdAt)}</p> <div className="thumb-center"> <h1>{item.title} <hr /></h1> <div> <Link to={`/articles/${item.id}`}> Read Article </Link> </div> </div> <ul className="blogs-thumb-tags"> {item.tags.map((tag) => { return <li key={tag} onClick={onClick}><i className="fas fa-tags"></i>{tag}</li> })} </ul> </> ) } export default BlogsThumbOverlay <file_sep>import React, { useContext } from 'react' import ArticlePortal from './ArticlePortal'; import { BlogsContext } from '../contexts/BlogsContext' import GridService from './services/GridService/GridService'; const ArticlePage = (props) => { const { blogs } = useContext(BlogsContext) const article = blogs.find((blog) => { return blog.id === parseInt(props.match.params.id); }) return ( <ArticlePortal> <section className="sect blog-banner"> <GridService list={[article]} imgOverlay={true} serviceType="blogPostBanner" staticOverlay={true} /> </section> <section className="sect article-page"> {article.article} </section> </ArticlePortal> ) } export default ArticlePage <file_sep>import React from 'react' import { useHistory } from 'react-router-dom'; import BlogPostBannerOverlay from'./custom/BlogPostBannerOverlay'; import BlogsThumbOverlay from './custom/BlogsThumbOverlay'; import ProjectsOverlay from './custom/ProjectsOverlay'; const GridImgOverlay = ({item, serviceType, staticOverlay, getArticlesByTag}) => { // Refactor this to employ state to track the adding / removing of classes instead of the below dom manipulations. let history = useHistory(); const onMouseEnter = (e) => { e.target.classList.add('show-overlay') }; const onMouseLeave = (e) => { e.target.classList.remove('show-overlay'); } const redir = () => { history.push(`/projects/${item.id}`) } const getServiceType = () => { switch (serviceType) { case 'projects': return <ProjectsOverlay item={item}/> case 'blogsThumb': return <BlogsThumbOverlay item={item} getArticlesByTag={getArticlesByTag}/> case 'blogPostBanner': return <BlogPostBannerOverlay item={item} /> } } return ( <div className={`grid-thumb-overlay ${serviceType}`} onMouseLeave={!staticOverlay ? onMouseLeave : undefined} onMouseEnter={!staticOverlay ? onMouseEnter : undefined} onClick={!staticOverlay ? redir : undefined}> <div className="off-edges"> {getServiceType()} </div> </div> ) } export default GridImgOverlay <file_sep>import React, { useState, useEffect } from 'react'; import ReactDOM from 'react-dom'; import { useTransition, animated, config } from 'react-spring' const SlideBox = ({show, toggleSlideBox, children}) => { const transitions = useTransition(show, null, { from: {transform: 'translateX(-100%)'}, enter: {transform: 'translateX(0%)'}, leave: {transform: 'translateX(-100%)'}, config: { mass: 1, tension: 200, friction: 30 } }) const renderSlideBox = () => { return ( <div> {transitions.map(({ item, key, props }) => item && <animated.div key={key} style={props} className="slide-box"> {children} </animated.div> ) } </div> ) } return ReactDOM.createPortal(renderSlideBox(), document.querySelector('body')) } export default SlideBox <file_sep>import React from 'react' const LearningPage = () => { return ( <section className="sect"> <h1>Learning Page</h1> <p> Below are projects based on Udemy, YouTube etc, after building them out I always spend time going back over the code and analysing it, it just helps the dust settle. There's a lot of dust up there. </p> </section> ) } export default LearningPage <file_sep>import React, { useContext, useState } from 'react' import { Link, useHistory } from 'react-router-dom'; import { ProjectsContext } from '../contexts/ProjectsContext'; import { getLastXListItems, getFeaturedItem } from '../selectors/global'; import GridService from './services/GridService/GridService'; import { BlogsContext } from '../contexts/BlogsContext'; const HomePage = () => { const { projects } = useContext(ProjectsContext) const { blogs } = useContext(BlogsContext) const [ latestProjects, setLatestProjects ] = useState(getLastXListItems(projects, 3, false)); const [ latestBlogs, setLatestBlogs ] = useState(getLastXListItems(blogs, 3, false)); const featuredProject = projects.find((project) => { return project.featured; }) const featuredBlog = blogs.find((blog) => { return blog.featured; }) return ( <> <section className="sect home-page-feature-project"> <h1 className="contains-icon">{featuredProject.name}<img src="https://dmvie1.s3.us-east-2.amazonaws.com/crane.png" alt="Crane Image"></img></h1> <p>{featuredProject.featuredSpiel}</p> <div className="featured-item-wrapper"> <div className="img-featured-item-wrapper"> <img className="img-featured-item" src={featuredProject.thumbPic}/> </div> <div className="home-page-feature-details"> <p>{featuredProject.shortDescription}</p> <p>Built With: {featuredProject.tools.map((tool) => { return `${tool}, ` })} </p> <div className="center-wrapper"> <Link to={`/projects/${featuredProject.id}`} className="button button--btn1">More Info</Link> </div> </div> </div> </section> <section className="sect home-page-projects"> <h1 className="section-title contains-icon"> Other Works: <i className="fas fa-project-diagram"></i></h1> <p>Or have a look through some of my other work, in various states of completion!</p> <GridService list={latestProjects} imgOverlay={true} serviceType={"projects"} staticOverlay={false}/> <Link to="/all-projects" className="button button--btn1">See All Projects</Link> </section> <section className="sect home-page-feature-blog"> <h1 className="contains-icon">{featuredBlog.title}<img src="https://dmvie1.s3.us-east-2.amazonaws.com/crane.png" alt="Crane Image"></img></h1> <p>{featuredBlog.shortDescription}</p> {/* list needs an array, so create an array literal and into it add the featured blog object so there's now a list with 1 item.. */} <GridService list={[featuredBlog]} imgOverlay={true} serviceType="blogsThumb" staticOverlay={true} /> </section> <section className="sect home-page-blogs"> <h1 className="section-title contains-icon">Articles <i className="far fa-newspaper"></i></h1> <GridService list={latestBlogs} imgOverlay={true} serviceType={"blogsThumb"} staticOverlay={true}/> </section> </> ) } export default HomePage <file_sep>import React from 'react' import { Link } from 'react-router-dom'; const ProjectsOverlay = ({item}) => { return ( <Link to="/projects/ENTER_ID/project"> <h2>{item.name}</h2> <hr /> <p>{item.shortDescription}</p> <p>Built With: {item.tools.map((tool) => { return (` ${tool}, `) })}</p> </Link> ) } export default ProjectsOverlay <file_sep>import React, { createContext, useReducer } from 'react'; import moment from 'moment'; import ProjectsReducer from '../reducers/ProjectsReducer'; // initial state const initialProjectsState = { projects: [ { id: 1, name: '<NAME>', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/thedarkfund.jpg', shortDescription: 'Client Site, blogging platform', longDescription: 'A Blogging platform designed to clients requested layout, with admin area to manage posts. ', tools: ['HTML', 'CSS', 'PHP', 'Javascript', 'MYSQL'], features: [ 'Design and Color Schemed to client request', 'PHP running Mysql Storage', 'Site Authentication', 'Controlled access to admin area' ], featuredSpiel: null, githubLink: '', liveSiteLink: null, featured: false, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(2, 'days').valueOf(), completed: false, completedAt: null }, { id: 2, name: 'ShutterBlink', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/shutterblink.jpg', shortDescription: 'Client Photography Website', longDescription: 'Photography showcase with E-Commerce delivered via stripe, and MYSQL data store. NodeJS Server side', tools: ['HTML', 'CSS', 'Javascript', 'ES6', 'NodeJS', 'MySQL'], features: [ 'Mobile First with Flexbox Design', 'Express Server side with Handlebars templating', 'Multer image uploading with Sharp editing', 'Site authentication using Bcrypt and JWT' ], githubLink: '', liveSiteLink: null, featured: false, featuredSpiel: null, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(1, 'days').valueOf(), completed: false, completedAt: null }, { id: 3, name: 'PRJMan', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/prjman.jpg', shortDescription: 'Designed to track project, RAG status, key milestones, resource allocation and more..', longDescription: 'A project managment API end point, allowing for storing and retrieving projects and their data. Functionality allows for creating new projects and their sub tasks, monitoring progress against milestones, and features RAG flag notifications on deadlines.', tools: ['HTML', 'CSS', 'ReactJS', 'Javascript', 'ES6', 'NodeJS', 'MongoDB', 'Mongoose'], features: [ 'NodeJS Express Server Routing', 'Multer image uploading with Sharp editing', 'Site Admin authentication', 'Data Store By MongoDB and Mongoose' ], githubLink: '', liveSiteLink: null, featured: true, featuredSpiel: null, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(3, 'days').valueOf(), completed: false, completedAt: null },{ id: 4, name: '<NAME>', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/thedarkfund.jpg', shortDescription: 'Client Site, blogging platform', longDescription: 'A Blogging platform designed to clients requested layout, with admin area to manage posts. ', tools: ['HTML', 'CSS', 'PHP', 'Javascript', 'MYSQL'], features: [ 'Design and Color Schemed to client request', 'PHP running Mysql Storage', 'Site Authentication', 'Controlled access to admin area' ], featuredSpiel: null, githubLink: '', liveSiteLink: null, featured: false, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(300, 'days').valueOf(), completed: false, completedAt: null },{ id: 5, name: '<NAME>', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/thedarkfund.jpg', shortDescription: 'Client Site, blogging platform', longDescription: 'A Blogging platform designed to clients requested layout, with admin area to manage posts. ', tools: ['HTML', 'CSS', 'PHP', 'Javascript', 'MYSQL'], features: [ 'Design and Color Schemed to client request', 'PHP running Mysql Storage', 'Site Authentication', 'Controlled access to admin area' ], featuredSpiel: null, githubLink: '', liveSiteLink: null, featured: false, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(111, 'days').valueOf(), completed: false, completedAt: null },{ id: 6, name: '<NAME>', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/thedarkfund.jpg', shortDescription: 'Client Site, blogging platform', longDescription: 'A Blogging platform designed to clients requested layout, with admin area to manage posts. ', tools: ['HTML', 'CSS', 'PHP', 'Javascript', 'MYSQL'], features: [ 'Design and Color Schemed to client request', 'PHP running Mysql Storage', 'Site Authentication', 'Controlled access to admin area' ], featuredSpiel: null, githubLink: '', liveSiteLink: null, featured: false, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(26, 'days').valueOf(), completed: false, completedAt: null },{ id: 7, name: '<NAME>', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/thedarkfund.jpg', shortDescription: 'Client Site, blogging platform', longDescription: 'A Blogging platform designed to clients requested layout, with admin area to manage posts. ', tools: ['HTML', 'CSS', 'PHP', 'Javascript', 'MYSQL'], features: [ 'Design and Color Schemed to client request', 'PHP running Mysql Storage', 'Site Authentication', 'Controlled access to admin area' ], featuredSpiel: null, githubLink: '', liveSiteLink: null, featured: false, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(4, 'days').valueOf(), completed: false, completedAt: null },{ id: 8, name: '<NAME>', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/thedarkfund.jpg', shortDescription: 'Client Site, blogging platform', longDescription: 'A Blogging platform designed to clients requested layout, with admin area to manage posts. ', tools: ['HTML', 'CSS', 'PHP', 'Javascript', 'MYSQL'], features: [ 'Design and Color Schemed to client request', 'PHP running Mysql Storage', 'Site Authentication', 'Controlled access to admin area' ], featuredSpiel: null, githubLink: '', liveSiteLink: null, featured: false, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(78, 'days').valueOf(), completed: true, completedAt: moment().subtract(70, 'days').valueOf() },{ id: 9, name: '<NAME>', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/thedarkfund.jpg', shortDescription: 'Client Site, blogging platform', longDescription: 'A Blogging platform designed to clients requested layout, with admin area to manage posts. ', tools: ['HTML', 'CSS', 'PHP', 'Javascript', 'MYSQL'], features: [ 'Design and Color Schemed to client request', 'PHP running Mysql Storage', 'Site Authentication', 'Controlled access to admin area' ], featuredSpiel: null, githubLink: '', liveSiteLink: null, featured: false, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(114, 'days').valueOf(), completed: false, completedAt: null }, { id: 10, name: '<NAME>', thumbPic: 'https://dmvie1.s3.us-east-2.amazonaws.com/thedarkfund.jpg', shortDescription: 'Client Site, blogging platform', longDescription: 'A Blogging platform designed to clients requested layout, with admin area to manage posts. ', tools: ['HTML', 'CSS', 'PHP', 'Javascript', 'MYSQL'], features: [ 'Design and Color Schemed to client request', 'PHP running Mysql Storage', 'Site Authentication', 'Controlled access to admin area' ], featuredSpiel: null, githubLink: '', liveSiteLink: null, featured: false, progress: 0, buildTime: 0, progressStatement: '', createdAt: moment().subtract(305, 'days').valueOf(), completed: true, completedAt: moment().subtract(305, 'days').valueOf() } ], error: null } // Create context: export const ProjectsContext = createContext(initialProjectsState); export const ProjectsProvider = ({ children }) => { // UseReducer Hook, gives us back state, and means of changing it over time. const [state, dispatch] = useReducer(ProjectsReducer, initialProjectsState); // Actions; return ( <ProjectsContext.Provider value={{ projects: state.projects, error: state.error }}> {children} </ProjectsContext.Provider> ) } <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; export default class ArticlePortal extends React.Component { constructor(props) { super(props) this.el = document.createElement('div'); this.el.id = 'banner'; } componentDidMount() { document.getElementById('root').insertBefore(this.el, document.querySelector('footer')) } render() { return ReactDOM.createPortal(this.props.children, this.el) } } <file_sep>import React from 'react' import moment from 'moment' const BlogPostBannerOverlay = ({item}) => { return ( <> <h1>{item.title} </h1> <p>Posted: {moment(item.createdAt).format("MMM, Do, YYYY")}</p> </> ) } export default BlogPostBannerOverlay <file_sep>import React, { useContext, useState, useEffect } from 'react'; import moment from 'moment'; import { DateRangePicker } from 'react-dates'; import { ProjectsContext } from '../contexts/ProjectsContext'; import GridService from './services/GridService/GridService'; import SelectService from './services/SelectService/SelectService'; import { getVisibleItems } from '../selectors/global'; import PaginationService from './services/PaginationService/PaginationService'; const falseFunc = () => false; const ProjectsPage = () => { const { projects, error } = useContext(ProjectsContext); // filteredItems is local copy of all of the projects, this get's updated via filtering and sorting const [ filteredItems, setfilteredItems ] = useState([...projects]); // paginatedItems takes the filtered items and tracks the current page of projects const [ paginatedItems, setPaginatedItems ] = useState([...filteredItems]) const [ paginationSettings, setPaginationSettings ] = useState({ onPage: 1, itemsPerPage: 3 }); const [ filters, setFilters ] = useState({ show: 'all', sortBy: 'asc', startOfRangeDate: moment().subtract(90, 'days'), endOfRangeDate: moment() }) // For react-dates date-picker const [ focusedInput, setFocusedInput ] = useState(null) // Pass an array to the SelectService, it holds the options fields value and textContent values. const projectFilterOptions = [{ optionValue: 'completed', textContent: 'Completed', },{ optionValue: 'incomplete', textContent: 'Incomplete' },{ optionValue: 'all', textContent: 'All' }] const projectSortOptions = [{ optionValue: 'desc', textContent: 'Latest Top' },{ optionValue: 'asc', textContent: 'Oldest Top' }] const onCompleteStatusChange = (e) => { setfilteredItems([...projects]) // reset local list to all projects setFilters({ // change the filters (which causes useEffect to re-render) ...filters, show: e.target.value }) } const onSortChange = (e) => { setfilteredItems([...projects]) // need to reset filteredItems setFilters({ ...filters, sortBy: e.target.value }) } const onDatesChange = ({startDate, endDate}) => { setfilteredItems([...projects]) setFilters({ ...filters, startOfRangeDate: startDate, endOfRangeDate: endDate }) } const onFocusChange = (focusedInput) => { setFocusedInput(focusedInput) } const onPageClicked = (e) => { console.log(`Page number ${parseInt(e.target.textContent)} was clicked....`); setPaginationSettings({ ...paginationSettings, onPage: parseInt(e.target.textContent) }) } const getPageItems = () => { const skip = (paginationSettings.onPage - 1) * paginationSettings.itemsPerPage; const paginated = [...filteredItems].splice(skip, paginationSettings.itemsPerPage); setPaginatedItems(paginated) } useEffect(() => { setfilteredItems(getVisibleItems('projects', filteredItems, filters)); setPaginationSettings({ ...paginationSettings, onPage: 1 }) }, [filters]) // Hook to call pagination every time the list changes, say for example, by user changing sorting / filtering, the display results need to reflect this across all pages... useEffect(() => { getPageItems() }, [filteredItems, paginationSettings]) return ( <section className="sect projects-page"> <h1>All Projects</h1> <p>Listed projects that I've been working on:</p> <div className="select-filters projects-filters"> Showing <SelectService addClass='select-css' options={projectFilterOptions} onChange={onCompleteStatusChange} value={filters.show} /> projects from between <DateRangePicker startDate={filters.startOfRangeDate} // momentPropTypes.momentObj or null, startDateId="startOfRangeDate" // PropTypes.string.isRequired, endDate={filters.endOfRangeDate} // momentPropTypes.momentObj or null, endDateId="endOfRangeDate" // PropTypes.string.isRequired, onDatesChange={onDatesChange} focusedInput={focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null, onFocusChange={onFocusChange} // PropTypes.func.isRequired, numberOfMonths={1} isOutsideRange={falseFunc} showClearDates={false} /> sorted by: <SelectService addClass="select-css" options={projectSortOptions} onChange={onSortChange} value={filters.sortBy} /> </div> <PaginationService listLength={filteredItems.length} onPageClicked={onPageClicked} paginationSettings={paginationSettings} /> <GridService list={paginatedItems} imgOverlay={true} serviceType={"projects"} staticOverlay={false} /> </section> ) } export default ProjectsPage <file_sep>import React, { useState, useEffect } from 'react' import { NavLink } from 'react-router-dom'; import SlideBox from './services/SlideBox/SlideBox'; const Header = () => { const [show, set] = useState(false) const toggleSlideBox = () => { set(!show) } return ( <header> <div className="main-wrapper"> <a href="/" className="home"> <img src="https://dmvie1.s3.us-east-2.amazonaws.com/profilepic.jpg" alt="DmVie"/> </a> <h1>Vie</h1> <i className="fas fa-bars" onClick={toggleSlideBox}>X</i> <SlideBox show={show} toggleSlideBox={toggleSlideBox}> <nav className="mob-nav"> <li><NavLink to="/" onClick={toggleSlideBox} activeClassName="is-active-link" exact={true}>Home</NavLink></li> <li><NavLink to="/all-projects" onClick={toggleSlideBox} activeClassName="is-active-link">Projects</NavLink></li> <li><NavLink to="/articles" onClick={toggleSlideBox} activeClassName="is-active-link">Articles</NavLink></li> <li><NavLink to="/learning" onClick={toggleSlideBox} activeClassName="is-active-link">Learning</NavLink></li> <li><NavLink to="/contact" onClick={toggleSlideBox} activeClassName="is-active-link">Contact</NavLink></li> </nav> </SlideBox> <nav className="noMob"> <li><NavLink to="/" activeClassName="is-active-link" exact={true}>Home</NavLink></li> <li><NavLink to="/all-projects" activeClassName="is-active-link">Projects</NavLink></li> <li><NavLink to="/articles" activeClassName="is-active-link">Articles</NavLink></li> <li><NavLink to="/learning" activeClassName="is-active-link">Learning</NavLink></li> <li><NavLink to="/contact" activeClassName="is-active-link">Contact</NavLink></li> </nav> </div> </header> ) } export default Header <file_sep>import React from 'react' const PageContent = ({children}) => { return ( <> <div className="page-content"> <div className="main-wrapper"> {children} </div> </div> </> ) } export default PageContent <file_sep>import React, { useState } from 'react' const PaginationService = ( { listLength = 0, onPageClicked, paginationSettings } ) => { const paginationLinks = () => { let links; if(listLength > 0) { links = Math.ceil(listLength / paginationSettings.itemsPerPage) }else { links = 1 } let i = 1; const arr = []; while(i <= links) { arr.push(i) i++ } return arr; } return ( <div className="links-bar"> <span>Results: <span className="results-count"> {listLength} </span> </span> <ul> <span className="pagination-bar-pages">Pages: </span> {paginationLinks().map((pageNumber) => { return ( <li key={pageNumber} className={`paginate-li ${paginationSettings.onPage === pageNumber ? "current-page" : ""}`} onClick={onPageClicked} > {pageNumber} </li>) })} </ul> </div> ) } export default PaginationService <file_sep>import React from 'react' const ContactPage = () => { return ( <> <section className="sect"> <h1 className="contains-icon">Contact Me <i className="fas fa-envelope-open-text"></i></h1> <p>To get in touch, fill out the form below along with your preferred means of contact, and I'll get right back to you :)</p> </section> <section className="sect contact-page"> <form> <div className="contact-name"> <div className="center-el"> <label htmlFor="name">Your Name:</label><br /> <input type="text" id="name" name="name" aria-required="true" /> </div> </div> <div className="contact-email"> <div className="center-el"> <label htmlFor="email">Email</label><br /> <input type="email" id="email" name="email" /> </div> </div> <div className="contact-last-name"> <div className="center-el"> <input type="text" name="last-name" id="last-name" tabIndex="-1" autoComplete="off" style={thisStyle}/> </div> </div> <div className="contact-message"> <div className="center-el"> <label htmlFor="message">Message</label><br /> <textarea name="message" id="message" cols="30" rows="10" aria-required="true"></textarea> </div> </div> <div className="contact-button"> <div className="center-el"> <button className="button button--btn1">Send Message</button> </div> </div> </form> </section> </> ) } const thisStyle = { display: 'none' } export default ContactPage
25dcc99b4a38acafb3592f08ddc961a378df166a
[ "JavaScript" ]
20
JavaScript
DavidMVie/dmvie-site
1764045bceabb477eb2775036873cffe308a7217
a177c828b217cf9028e85631bd246e57bb7c42db
refs/heads/master
<file_sep>require("webduino-js"); require("webduino-blockly"); //variable about webduino var myFirebase; var dht; var mTemp=0,mHum=0,bRain=0,uid=0,i=0,flag=0; //variable about linebot var linebot = require('linebot'); var express = require('express'); var bot = linebot({ channelId: '1519721522', channelSecret: '<KEY>', channelAccessToken: '<KEY> }); const app = express(); const linebotParser = bot.parser(); app.post('/', linebotParser); //因為 express 預設走 port 3000,而 heroku 上預設卻不是,要透過下列程式轉換 var server = app.listen(process.env.PORT || 8080, function() { var port = server.address().port; console.log("App now running on port", port); }); // Initialize Firebase var firebase = require("firebase"); var config = { apiKey: "<KEY>", authDomain: "webduino-23015.firebaseapp.com", databaseURL: "https://webduino-23015.firebaseio.com", projectId: "webduino-23015", storageBucket: "webduino-23015.appspot.com", messagingSenderId: "927229253803" }; firebase.initializeApp(config); //firebase connect var db = firebase.database(); var myFirebase = db.ref(); function get_date(t) { var varDay = new Date(), varYear = varDay.getFullYear(), varMonth = varDay.getMonth() + 1, varDate = varDay.getDate(); var varNow; if (t == "ymd") { varNow = varYear + "/" + varMonth + "/" + varDate; } else if (t == "mdy") { varNow = varMonth + "/" + varDate + "/" + varYear; } else if (t == "dmy") { varNow = varDate + "/" + varMonth + "/" + varYear; } else if (t == "y") { varNow = varYear; } else if (t == "m") { varNow = varMonth; } else if (t == "d") { varNow = varDate; } return varNow; } function get_time(t) { var varTime = new Date(), varHours = varTime.getHours(), varMinutes = varTime.getMinutes(), varSeconds = varTime.getSeconds(); var varNow; if (t == "hms") { varNow = varHours + ":" + varMinutes + ":" + varSeconds; } else if (t == "h") { varNow = varHours; } else if (t == "m") { varNow = varMinutes; } else if (t == "s") { varNow = varSeconds; } return varNow; } //linebot function _bot(){ console.log("bot",bRain); if(bRain==1){//如果判斷可能會下雨 bot.push('U29c716493f690891169338083c3599ca', '家裡附近可能會下雨,回家收衣服喔!! '); bot.push('U08fdb11d718b720f728c620a3a749139', '家裡附近可能會下雨,回家收衣服喔!! '); bRain=0; } bot.on('message', function(event) { uid = event.source.userId; console.log(uid); if (event.message.type = 'text') { var msg = event.message.text; if(flag == 0){ if(msg.indexOf('濕度') != -1) msg = "現在濕度為 " + mHum + " %"; if(msg.indexOf('溫度') != -1) msg = "現在溫度為 " + mTemp + " °C"; if(msg == '桂一'){ event.reply({ type: 'image', originalContentUrl: 'https://firebasestorage.googleapis.com/v0/b/webduino-23015.appspot.com/o/S__47710348.jpg?alt=media&token=5cf5bba7-d860-4328-8e89-26a8a4f83a9c', previewImageUrl: 'https://firebasestorage.googleapis.com/v0/b/webduino-23015.appspot.com/o/S__47710348.jpg?alt=media&token=5cf5bba7-d860-4328-8e89-26a8a4f83a9c' }); } if(msg == '呼叫工具人') msg = '就知道你想我了吧~'; if(msg == '工具人閉嘴'){ flag = 1; msg = '掰掰~ 再次呼叫請輸入\"呼叫工具人\"'; } event.reply(msg).then(function(data) { // success console.log(msg); }).catch(function(error) { // error console.log('error'); }); }else if(flag == 1){ if(msg == '呼叫工具人') flag = 0; } } }); } function rain(temperature,humidity){ switch (temperature){ case 20: if(humidity>80) bRain=1; break; case 21: if(humidity>78) bRain=1; break; case 22: if(humidity>78) bRain=1; break; case 23: if(humidity>72) bRain=1; break; case 24: if(humidity>78) bRain=1; break; case 25: if(humidity>76) bRain=1; break; case 26: if(humidity>77) bRain=1; break; case 27: if(humidity>70) bRain=1; break; case 28: if(humidity>71) bRain=1; break; case 29: if(humidity>78) bRain=1; break; default: if(humidity>70) bRain=1; break; } } boardReady({device: 'YWgg'}, function (board) { var temp = 0, humidity = 0; board.systemReset(); board.samplingInterval = 250; //myFirebase = new Firebase("https://webduino-23015.firebaseio.com/"); dht = getDht(board, 11); //myFirebase.set({}); //clear data //console.log("clear ok"); //每十秒檢測一次,且記錄每半小之平均值 dht.read(function(evt){ mHum = dht.humidity; mTemp = dht.temperature; i++; if(i > 180){//每半小時檢查一次有沒有可能會下雨 bRain = i = 0; rain(mTemp,mHum); } _bot();//call linebot myFirebase.push({ date:get_date("ymd"), time:get_time("hms"), temp:dht.temperature, humidity:dht.humidity }); }, 10000); });
c473108a2e83075f2fbf30adaaf18487fbae3daa
[ "JavaScript" ]
1
JavaScript
lixingxing41/linebot
5016b2761db6993cee9916c34587f90c4a1ef599
6f909517de8558c24b1f29219de3976b52f4a1a0
refs/heads/master
<repo_name>g360codes/stark<file_sep>/R/hello.R #' time_to_got #' #' #' @return #' @export #' #' @examples #' time_to_got() #' for(i in seq_along(1:100)){ #' time_to_got() #' print('----------') #' } time_to_got <- function(sound = 1) { td <- as.numeric(as.POSIXct('2019-04-14 21:00:00', tz = 'EST')) - as.numeric((Sys.time())) print(paste(td/(86400*7), 'weeks')) print(paste(td/86400, 'days')) print(paste(td/3600, 'hours')) print(paste(td/24, 'minutes')) print(paste(td, 'seconds')) for (i in c(0.5, 1, 0.1, 0.1, 0.5, 1, 0.1, 0.1, 0.1)){ beepr::beep(sound = sound) Sys.sleep(i) } invisible() }
37e60f5472aa80fc5f5b00e679eb883f798c7a3f
[ "R" ]
1
R
g360codes/stark
bc83a319b83b12ccc354de891514169fb605cfda
c846f299fc7196328683d54d31891d542538f929
refs/heads/master
<repo_name>iFreeForAll/Glitch-Garden<file_sep>/Assets/Scripts/MusicManager.cs using UnityEngine; using UnityEngine.SceneManagement; [RequireComponent(typeof(AudioSource))] public class MusicManager : MonoBehaviour { public AudioClip[] levelMusicChange; private AudioSource audioSource; private int activeSceneIndex; void OnEnable() { SceneManager.activeSceneChanged += OnSceneLoaded; } void OnDisable() { SceneManager.activeSceneChanged -= OnSceneLoaded; } void Awake () { DontDestroyOnLoad (gameObject); } void Start() { audioSource = GetComponent<AudioSource>(); audioSource.volume = PlayerPrefsManager.GetMasterVolume(); } void OnSceneLoaded(Scene lastScene, Scene newScene) { AudioClip thisLevelMusic = levelMusicChange[newScene.buildIndex]; if(!thisLevelMusic) return; audioSource.clip = thisLevelMusic; audioSource.Play(); } public void SetVolume (float volume) { audioSource.volume = volume; } } <file_sep>/README.md # Glitch Garden Simple Plants vs. Zombie clone https://www.udemy.com/unitycourse/learn/v4/overview
148cf713c6e38d3f0e68a3e2dc8a3e8809f65368
[ "Markdown", "C#" ]
2
C#
iFreeForAll/Glitch-Garden
1a47af90b9b32c77dcf316389b0b8526239dd4eb
ab94b786588afc2a3f8dc64d54189821657e1115
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; // importamos el servicio de translate para usarlo @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { // utilizarlo de manera dinamica // creamos el array (lista de lenguajes a utilizar) langs: string[] = []; title = 'Traduce tu app'; name = 'brayan'; constructor(private translate: TranslateService) { // le damos la instrucccion de que empieze en ingles por defecto this.translate.setDefaultLang('en'); this.translate.use('en'); // usamos addlangs para llenar la lista con los lenguajes que soporta la applicacion this.translate.addLangs(['en', 'es']); // que nos entregue el array que le configuramos y lo guardamos en el array langs this.langs = this.translate.getLangs(); // forma estatica 2 de uso - por medio del componente this.translate.stream('HELLO') .subscribe((res: string) => { console.log(res); }); this.translate.stream('GREETING', {name:this.name}) .subscribe((res: string) => { console.log(res); }); } // ahora cambiamos el lenguaje dinamicamente changeLang(lang: string) { //ahora que use el lenguaje que le pasamos this.translate.use(lang); } }
9be15690c102419800b8d03341a2258bcce60d3d
[ "TypeScript" ]
1
TypeScript
brayanhdz5/translate-with-angular
2799cdab017fb3580842960dc33250fa501acd8a
65606722f759d947a4854aa87073e275c1253420
refs/heads/master
<repo_name>developer-ranavishal/searchPost<file_sep>/app/src/main/java/com/example/searchpost/network/PostOfficeInfo.kt package com.example.searchpost.network class PostOfficeInfo<T> : ArrayList<PostOfficeInfoItem>()<file_sep>/app/src/main/java/com/example/searchpost/view/PostOfficeListScreen.kt package com.example.searchpost.view import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.example.searchpost.R import com.example.searchpost.databinding.FragmentPostOfficeListScreenBinding import com.example.searchpost.list.OnItemClickListener import com.example.searchpost.list.PostOfficeAdapter import com.example.searchpost.network.PostOffice import com.example.searchpost.viewmodel.PostOfficeViewModel class PostOfficeListScreen : Fragment(), OnItemClickListener { private lateinit var binding : FragmentPostOfficeListScreenBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentPostOfficeListScreenBinding.inflate(layoutInflater) val postOfficeViewModel= ViewModelProvider(this).get(PostOfficeViewModel::class.java) val adapter = PostOfficeAdapter(this) binding.recyclerView.adapter = adapter postOfficeViewModel.listOfPostOffice.observe(viewLifecycleOwner , {list -> if(list!=null) adapter.refreshPostOfficeList(list) }) return binding.root } override fun onClick(postOffice: PostOffice, position: Int) { Toast.makeText(context, "clicked on ${postOffice.Name}", Toast.LENGTH_SHORT).show() } }<file_sep>/app/src/main/java/com/example/searchpost/view/EnterPincodeScreen.kt package com.example.searchpost.view import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.example.searchpost.databinding.FragmentEnterPincodeScreenBinding import com.example.searchpost.list.OnItemClickListener import com.example.searchpost.list.PostOfficeAdapter import com.example.searchpost.network.PostOffice import com.example.searchpost.viewmodel.PostOfficeViewModel class EnterPincodeScreen : Fragment() { private lateinit var binding: FragmentEnterPincodeScreenBinding private var pinCode: Int = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentEnterPincodeScreenBinding.inflate(layoutInflater) val viewModel = ViewModelProvider(this).get(PostOfficeViewModel::class.java) binding.searchButton.setOnClickListener { pinCode = binding.enterPinEdittext.text.toString().toIntOrNull() ?: 0 if (pinCode <= 99999) Toast.makeText(context, "please enter correct pin!", Toast.LENGTH_SHORT).show() else { viewModel.getPostByPin(pinCode) val action = EnterPincodeScreenDirections.actionEnterPincodeScreenToPostOfficeListScreen() findNavController().navigate(action) Toast.makeText(context, "done it!", Toast.LENGTH_SHORT).show() } } viewModel.listOfPostOffice.observe(viewLifecycleOwner, { }) return binding.root } } <file_sep>/app/src/main/java/com/example/searchpost/list/PostOfficeAdapter.kt package com.example.searchpost.list import android.annotation.SuppressLint import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.searchpost.databinding.PostOfficeItemBinding import com.example.searchpost.network.PostOffice import com.example.searchpost.view.EnterPincodeScreen class PostOfficeAdapter(private val listener: OnItemClickListener) : RecyclerView.Adapter<PostOfficeAdapter.PostOfficeViewHolder>() { private var postOfficeList = listOf<PostOffice>() class PostOfficeViewHolder(private val binding : PostOfficeItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bindingPostOffice(postOffice : PostOffice){ binding.postOffice = postOffice binding.executePendingBindings() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = PostOfficeViewHolder(PostOfficeItemBinding.inflate(LayoutInflater.from(parent.context))) override fun onBindViewHolder(holder: PostOfficeViewHolder, position: Int) { Log.d("onbind", "onBindViewHolder: called()") val currentItem= postOfficeList[position] holder.bindingPostOffice(currentItem) holder.itemView.setOnClickListener { listener.onClick(currentItem,position) } } override fun getItemCount() = postOfficeList.size @SuppressLint("NotifyDataSetChanged") fun refreshPostOfficeList(newPostOfficeList : List<PostOffice>){ postOfficeList = newPostOfficeList notifyDataSetChanged() // imp line to refresh new data in recyclerview } } interface OnItemClickListener { fun onClick(postOffice : PostOffice,position: Int) }<file_sep>/app/src/main/java/com/example/searchpost/adapters/Adapters.kt package com.example.searchpost.adapters import android.util.Log import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView import com.example.searchpost.list.PostOfficeAdapter import com.example.searchpost.network.PostOffice //@BindingAdapter("loadPostOfficeList") //fun bindRecyclerView(recyclerView: RecyclerView , postOfficeList : List<PostOffice>?){ // val adapter = recyclerView.adapter as PostOfficeAdapter // if (postOfficeList!=null) { // adapter.refreshPostOfficeList(postOfficeList) // } //} <file_sep>/app/src/main/java/com/example/searchpost/MainActivity.kt package com.example.searchpost import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.findNavController import com.example.searchpost.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) navController=findNavController(R.id.fragment_navhost) } override fun onNavigateUp(): Boolean { return super.onNavigateUp() || navController.navigateUp() } }<file_sep>/app/src/main/java/com/example/searchpost/network/PostOfficeApiService.kt package com.example.searchpost.network import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query //https://api.postalpincode.in/pincode/{PINCODE} //https://newsapi.org/v2/top-headlines?country=in&apiKey=<KEY> interface PostOfficeApi{ @GET("pincode/{PINCODE}") suspend fun getPostByPinCode( @Path("PINCODE")pinCode : Int ) : Response<PostOfficeInfo<ArrayList<PostOfficeInfoItem>>> } //object PostOfficeApiService { //// make singleton retrofit object // private val retrofit = Retrofit.Builder(). // addConverterFactory(GsonConverterFactory.create()). // baseUrl(BASE_URL).build() // val retrofitService: PostOfficeApi by lazy { // retrofit.create(PostOfficeApi::class.java) // } //}<file_sep>/app/src/main/java/com/example/searchpost/network/ServiceBuilder.kt package com.example.searchpost.network import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory private const val BASE_URL="https://api.postalpincode.in/" object ServiceBuilder { //create okhttp client private val okHttp = OkHttpClient.Builder() //create Retrofit Builder private val builder = Retrofit.Builder().baseUrl(BASE_URL). addConverterFactory(GsonConverterFactory.create()). client(okHttp.build()) //create Retrofit Instance private val retrofit = builder.build() fun <T> buildService(serviceType : Class<T>) : T{ return retrofit.create(serviceType) } }<file_sep>/app/src/main/java/com/example/searchpost/network/PostOfficeInfoItem.kt package com.example.searchpost.network data class PostOfficeInfoItem( val Message: String, val PostOffice: List<PostOffice>, val Status: String )<file_sep>/app/src/main/java/com/example/searchpost/SplashScreen.kt package com.example.searchpost import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.bumptech.glide.Glide import com.example.searchpost.databinding.ActivitySplashScreenBinding class SplashScreen : AppCompatActivity() { private lateinit var binding: ActivitySplashScreenBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySplashScreenBinding.inflate(layoutInflater) setContentView(binding.root) showSplashImg() } private fun showSplashImg() { Glide.with(this).load(R.drawable.posta).into(binding.splashImg) binding.splashImg.alpha = 0f binding.splashImg.animate().setDuration(3000).alpha(1f).withEndAction { val intent = Intent() intent.apply { setClass(this@SplashScreen, MainActivity::class.java) } startActivity(intent) overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) } } } <file_sep>/app/src/main/java/com/example/searchpost/viewmodel/PostOfficeViewModel.kt package com.example.searchpost.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.searchpost.network.PostOffice import com.example.searchpost.network.PostOfficeApi import com.example.searchpost.network.ServiceBuilder import kotlinx.coroutines.CompletableJob import kotlinx.coroutines.Job import kotlinx.coroutines.launch class PostOfficeViewModel : ViewModel() { private var _listOfPostOffice: MutableLiveData<List<PostOffice>> = MutableLiveData() val listOfPostOffice: LiveData<List<PostOffice>> get() = _listOfPostOffice fun getPostByPin(pinCode: Int) { viewModelScope.launch { val response = ServiceBuilder.buildService(PostOfficeApi::class.java).getPostByPinCode(pinCode) val postResponseBody = response.body() if (postResponseBody != null) { Log.d("post", "${postResponseBody[0].PostOffice}") _listOfPostOffice.value = postResponseBody[0].PostOffice } else Log.d("post", "empty body") } } }
0e2aa2f4a6125b0febbc1e133539f7cd3d1c8d81
[ "Kotlin" ]
11
Kotlin
developer-ranavishal/searchPost
fe34852c0f3e403a0ace9a4a08b16a4fd9e78b50
332585d8e45358fa4fd01a2f2171371f54bceb53
refs/heads/master
<file_sep> import requests import time import ujson as json from instagram_network import settings def get_response(endpoint, params={}): if params != {}: r = requests.get(endpoint, params=params) else: r = requests.get(endpoint) tries = 0 max_tries = 5 while tries < max_tries: try: if r.status_code == 400: return json.loads(r.content) if r.status_code == 404: return json.loads(r.content) r.raise_for_status() break except: print(r) print(endpoint) print(params) print('Received bad status_code. Sleeping \ for 5 seconds.') time.sleep(5) if params: r = requests.get(endpoint, params=params) else: r = requests.get(endpoint) tries += 1 time.sleep(settings.MAX_REQUESTS_PER_HOUR/3600.0) return json.loads(r.content) def get_next_page_data(response): try: return response['pagination'] except: print('No pagination data!') return None def get_followers(user_id, access_token): endpoint = settings.BASE_ENDPOINT + '/users/' + str(user_id) + '/followed-by' args = {'access_token': access_token} resp = get_response(endpoint, args) next_page = get_next_page_data(resp) users = resp.get('data', []) while next_page and next_page.get('next_url'): resp = get_response(next_page['next_url'], {}) next_page = get_next_page_data(resp) users += resp.get('data', []) print("Found %d followers of user %s" % (len(users), user_id)) return list(users) def get_follows(user_id, access_token): endpoint = settings.BASE_ENDPOINT + '/users/' + str(user_id) + '/follows' args = {'access_token': access_token} resp = get_response(endpoint, args) next_page = get_next_page_data(resp) users = resp.get('data', []) while next_page and next_page.get('next_url'): resp = get_response(next_page['next_url'], {}) next_page = get_next_page_data(resp) users += resp.get('data', []) return list(users) def search_users(query, access_token): endpoint = settings.BASE_ENDPOINT + '/users/search' args = {'access_token': access_token, 'q': query} resp = get_response(endpoint, args) next_page = get_next_page_data(resp) users = resp.get('data', []) while next_page and next_page.get('next_url'): resp = get_response(next_page['next_url'], {}) next_page = get_next_page_data(resp) users += resp.get('data', []) return list(users) <file_sep>BASE_ENDPOINT = 'https://api.instagram.com/v1' MAX_REQUESTS_PER_HOUR = 5000<file_sep>ACCESS_TOKEN = '<PASSWORD>'<file_sep># instagram-network Python tools for getting data from the Instagram API ## Setting up access key Clone the repository. Copy the file `conf_template.py` to a new file `conf.py`. Obtain an access key and add it to `conf.py`. Do not add `conf.py` to git - it's not good practice. ## Installation ``` cd instagram-network pip install -U . ``` This will also install the dependencies `networkx` and `ujson` See the demo Jupyter notebook for more details on how to use. <file_sep>import networkx import copy from instagram_network import utils, conf def add_node(G, user_data): G.add_node(user_data['id'], attr_dict = user_data) def prune_graph(G): out_degree = G.out_degree() G_pruned = copy.deepcopy(G) for node in G_pruned.nodes(): if out_degree[node]: G_pruned.node[node]['out_degree'] = out_degree[node] else: G_pruned.remove_node(node) return G_pruned def get_follower_graph(user_id, access_token = conf.ACCESS_TOKEN, pruned=True): G = networkx.DiGraph() for follower in utils.get_followers(user_id, access_token): add_node(G, follower) G.add_edge(user_id, follower['id']) for _follower in utils.get_followers(follower['id'], access_token): add_node(G, _follower) G.add_edge(follower['id'], _follower['id']) if pruned: return prune_graph(G) return G<file_sep>from setuptools import setup setup(name='instagram-network', version='0.0.1', description='Retrieve instagram data for graph visualizations', url='https://gite.brandwatch.com/benj/instagram-network', author='<NAME>', author_email='<EMAIL>', packages=['instagram_network'], install_requires=[ 'ujson', 'networkx==1.10' ], zip_safe=False)
125de275673978ebc2a3d1b1304eb840066a1cd2
[ "Markdown", "Python" ]
6
Python
BrandwatchLtd/benj-instagram-network
f67313969f52eaeb1ce8d75f34a9e92b6de724b3
51e7e6f3b748f3fc1ab1a70761594e3b89193d9b
refs/heads/master
<file_sep>var fernando = { Nome: "<NAME>", CPF: "83547098", Nascimento: "22/02/1990", poster:"https://remax.azureedge.net/userimages/12/A_2514de4f9b1c4845be3eb22dddb0c999_iList.jpg" }; var tbody = document.getElementById("tbodyPessoas"); var btnSalvar = document.getElementById("btnSalvar"); var txfNome = document.getElementById("txfNome"); var txfCpf = document.getElementById("txfCpf"); var txfImagem = document.getElementById("txfImagem"); var txfData = document.getElementById("txfData"); var txfId = document.getElementById("txfId"); var pessoas = []; function init() { localStorage.removeItem("pessoas"); addEventListener(); loadPessoas(); }; var loadPessoas = () => { tbody.innerHTML = ""; pessoas = loalStorage.getItem("pessoas"); pessoas = JSON.parse(pessoas); var cidadao = [fernando] pessoas = pessoas ? pessoas: cidadao; pessoas.forEach((p, i) => addPessoaParaTabela(p, i)); }; var addEventListeners = () => { btnSalvar.addEventListener("click", getAndSavePessoa); }; var addPessoaParaTabela = function(pessoas, index) { if(!pessoa) return; var row = "<tr>" + "<td>"+pessoa.nome+"</td>"+ "<td>"+pessoa.cpf+"</td>"+ "<td>"+pessoa.nascimento+"</td>"+ "<td>"<img src=\""+pessoa.imagem+"\" width=\"30px\"></td>"+ "<td>" + " <input type=\"button\" value=\"apagar\" onclick=\"removePessoa("+index+")\"/>" + " <input type=\"button\" value=\"editar\" onclick=\"editaPessoa("+index+")\"/>" + "</td>" + "</tr>"; tbody.innerHTML += row; }; var removePessoa = (index) => { console.log("removendo pessoa "+pessoas[index].title); delete pessoas[index]; localStorage.setItem("pessoas", JSON.stringify(pessoas)); loadPessoas(); }; var editPessoa = (index) => { console.log("editando pessoa"+pessoas[index].nome); var pessoa = pessoas[index]; txfNome.value = pessoa.nome; txfCpf.value = pessoa.cpf; txfData.value = pessoa.data; txfImagem.value = pessoa.imagem; txfId.value = index; }; var getAndSavePessoa = function(e) { if (e) e.preventDefault(); var title = txtNome.value; var cpf = txtCpf.value; var data = txtData.value; var imagem = txfImagem.value; var isNew = id == "-1"; id = isNew? pessoas.length: id; var pessoa = {id: id, nome: nome, cpf: cpf, data: data, "imagem": imagem}; if (isNew){ pessoas.push(pessoa); }else{ pessoas[id] = pessoa; } localStorage.setItem("pessoas", JSON.stringify(pessoas)); loadPessoas(); } window.onload = init();
f4230d68abebde56d487d77ffc489fadc39a94af
[ "JavaScript" ]
1
JavaScript
Aron201/javawebpratico2018
a9b235c0a16b0459999ae8807e530b7ca89e7cf1
07101b45bdac08572b0f73f5a1fd42a43f3d5c00
refs/heads/master
<repo_name>ob0420/odoo.hospital<file_sep>/patient.py # -*- coding: utf-8 -*- from odoo import models, fields, api, _ from odoo.exceptions import ValidationError class SaleOrderInherit(models.Model): _inherit = 'sale.order' patient_name = fields.Char(string='Name') class HospitalPatient(models.Model): _name = 'hospital.patient' _inherit = ['mail.thread', 'mail.activity.mixin'] _description = 'Patient Record' _rec_name = 'patient_name' patient_name = fields.Char(string='Name', required=True, track_visibility="always") patient_age = fields.Integer('Age', track_visibility="always") notes = fields.Text(string="Registration Note") image = fields.Binary(string="Image", attachment=True) name = fields.Char(string="Test") name_seq = fields.Char(string='Patient ID', required=True, copy=False, readonly=True, index=True, default=lambda self: _('New')) @api.model def create(self, vals): if vals.get('name_seq', _('New')) == _('New'): vals['name_seq'] = self.env['ir.sequence'].next_by_code('hospital.patient.sequence') or _('New') result = super(HospitalPatient, self).create(vals) return result<file_sep>/__init__.py from . import patient from . import security from . import static from . import data<file_sep>/README.md # odoo.hospital Module for Hospital Management
f3bbaf9164693ff6d584349eb9546ec70e128c63
[ "Markdown", "Python" ]
3
Python
ob0420/odoo.hospital
73df6ccb86a4c4e5f276ac21658bea1c33f4a953
027858421d0204b1911e213c6779cd97ae558304
refs/heads/main
<file_sep>package com.gfg.article.sharedviewmodel import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider class MessageReceiverFragment : Fragment() { //to contain and display shared message lateinit var displayMsg: TextView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { //inflate the fragment layout return inflater.inflate(R.layout.fragment_message_receiver, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //reference for the container declared above displayMsg = view.findViewById(R.id.textViewReceiver) //create object of SharedViewModel val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java) //observing the change in the message declared in SharedViewModel model.message.observe(viewLifecycleOwner, Observer { //updating data in displayMsg displayMsg.text = it }) } }<file_sep># Blogathon-GFG <h3><a href="https://www.geeksforgeeks.org/shared-viewmodel-in-android/#">Detailed Explanation</a> <hr> Output: https://user-images.githubusercontent.com/42924677/133922339-989804e6-5793-4b38-a4c3-77d4c0e15289.mp4 <file_sep>package com.gfg.article.sharedviewmodel import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import androidx.appcompat.widget.AppCompatButton import androidx.lifecycle.ViewModelProvider class MessageSenderFragment : Fragment() { lateinit var btn: Button //to send message lateinit var writeMSg: EditText //to write message override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_message_sender, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //reference for button and EditText btn = view.findViewById(R.id.button) writeMSg = view.findViewById(R.id.writeMessage) //create object of SharedViewModel val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java) //call function "sendMessage" defined in SharedVieModel to store the value in message. btn.setOnClickListener { model.sendMessage(writeMSg.text.toString()) } } }<file_sep>package com.gfg.article.sharedviewmodel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class SharedViewModel : ViewModel() { //variable to contain message whenever it gets changed/modified(mutable) val message = MutableLiveData<String>() //function to send message fun sendMessage(text: String) { message.value = text } }
24b12449ea7b10f0385c4c7740183efa3704e6f5
[ "Markdown", "Kotlin" ]
4
Kotlin
Anju1415/Blogathon-GFG
4347b8d750fccf5d65b7e42bd748c9df6458413c
1105b946fb9b7510e6041c8e5156967c8f358d25
refs/heads/master
<repo_name>osyun0101/SampleEmpty<file_sep>/SampleEmptyApp/Data.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleEmptyApp { class Data { // Dataオブジェクトの数 private static int num = 0; // データの値 private int id; // コンストラクタ(引数つき) public Data(int id) { this.id = id; num++; Console.WriteLine("値:{0} 数:{1}", this.id, num); } // オブジェクトの数を取得 public static void ShowNumber() { Console.WriteLine("Dataオブジェクトの数:{0}", num); } } } <file_sep>/SampleEmptyApp/IPhone.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleEmptyApp { // 電話インターフェース interface IPhone { // 指定した番号に電話をかける void Call(string number); } }<file_sep>/SampleEmptyApp/Startup.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace SampleEmptyApp { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // 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.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { context.Response.ContentType = "text/html"; await context.Response.WriteAsync("<html><title>Hello</title></head>"); await context.Response.WriteAsync("<body><h1>Hello!</h1>"); await context.Response.WriteAsync("<p>This is sample page.</p>"); await context.Response.WriteAsync("<p>neko</p>"); await context.Response.WriteAsync("<p>犬</p>"); await context.Response.WriteAsync("<p>鈴木</p>"); await context.Response.WriteAsync("<p>洵輔</p>"); await context.Response.WriteAsync("</body></html>"); }); }); } } } <file_sep>/SampleEmptyApp/IFuncs1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleEmptyApp { interface IFuncs1 { void Func1(); void Func2(); } }<file_sep>/SampleEmptyApp/Sample.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleEmptyApp { class Sample { // コンストラクタ public Sample() { Console.WriteLine("コンストラクタ"); } // デストラクタ ~Sample() { Console.WriteLine("デストラクタ"); } } } <file_sep>/SampleEmptyApp/IEmail.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleEmptyApp { // 電子メール interface IEmail { // メールを送る void SendMail(string address); } }<file_sep>/SampleEmptyApp/CellPhone.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleEmptyApp { // 携帯電話クラス(IPhone、IEmailクラスを実装 class CellPhone : IPhone, IEmail { // メールアドレス private string mailAddress; // 電話番号 private string number; // コンストラクタ(メールアドレスと電話番号を設定 public CellPhone(string mailAddress, string number) { this.mailAddress = mailAddress; this.number = number; } // 指定したメールアドレスにメールを送信する public void SendMail(string address) { Console.WriteLine(address + "に、" + this.mailAddress + "からメールを出します。"); } // 指定した番号に電話をかける public void Call(string number) { Console.WriteLine(number + "に、" + this.number + "から電話をかけます。"); } } }
d5ac3f246fc51b9e2dab956858a476b6d78837e2
[ "C#" ]
7
C#
osyun0101/SampleEmpty
6adbc3a571d49cb37704a53a2b828010a1e936ec
9d9cece4daf1c8ff06b1c5a0f4d31265ae7968b3
refs/heads/master
<file_sep>class About < ActiveRecord::Base validates :bio, presence: true end <file_sep>class WelcomeController < ApplicationController def home if About.last @bio = About.last.bio else @bio = "Emily is the best" end @list = Composer.all.sort_by{|x| x[:name]} end def calendar @performances = Performance.all end end <file_sep>Personal website for friend <NAME> live at: senturia.herokuapp.com <file_sep>require 'pp' class AnalyticsController < ApplicationController http_basic_authenticate_with name: "Emilarr", password: "<PASSWORD>" def home @total_visits = Visitor.all.count @chrome = Browser.where(name:"Google Chrome").count @firefox = Browser.where(name:"Mozilla Firefox").count @safari = Browser.where(name:"Safari").count @ie = Browser.where(name:"Internet Explorer").count @other = Browser.where(name:"Other").count end def new_performance @performance = Performance.new end def create_performance @performance = Performance.new(performance_params) if @performance.save redirect_to calendar_path else render :new_performance end end def edit_bio @about = About.new end def update_bio @about = About.new(about_params) if @about.save redirect_to root_path else render :edit_bio end end private def performance_params params.require(:performance).permit(:date, :venue, :program) end def about_params params.require(:about).permit(:bio) end end <file_sep>class Composer < ActiveRecord::Base has_many :operas validates :name, presence: true end <file_sep>Emilarr::Application.routes.draw do get "/operas/new" => 'operas#new' post '/operas' => 'operas#create', as: :operas get "operas/:id/edit" => 'operas#edit' patch '/operas/:id' => 'operas#update', as: :opera delete 'operas/:id' => 'operas#delete' get "public/resume.pdf" => "application#serve" get "/calendar" => "welcome#calendar" get "/analytics" => "analytics#home" get "/new_performance" => "analytics#new_performance" post "/new_performance" => "analytics#create_performance" get "/edit_bio" => "analytics#edit_bio" post "/edit_bio" => "analytics#update_bio" # get "/update_rep" => "analytics#add_rep", as: :opera root 'welcome#home' end
e4223c3956e5da90ad2c63ab16f0d682c8bce31b
[ "RDoc", "Ruby" ]
6
Ruby
jefflembeck/Senturia
6a952b9ee29e954b5c602d2a2976cc2314535eab
156249863215a0968be869cb9a3303dd04001836
refs/heads/master
<file_sep># miyanky elflmai <file_sep><?php echo 'hello world'; ecoh "other"; dpfjfmf skfhdfrpgkwk qk baboyam bbbbabo<file_sep><?php echo '<div> hello</div>';
6eac010d54ce372756063c568b62c1d6344e9d10
[ "Markdown", "PHP" ]
3
Markdown
kimmg12/miyanky
f1d8ae54e996310b44cd5c846f1189f6d21d0758
918be15b1c4c44e8e7106f47347582fe943a8fce
refs/heads/master
<repo_name>rita08113/arcademakecodewhacamole<file_sep>/main.ts namespace SpriteKind { export const background = SpriteKind.create() export const 按鈕 = SpriteKind.create() export const 道具 = SpriteKind.create() export const 人物 = SpriteKind.create() } function 遊戲內容 () { if (game_1 == 2) { scene.setBackgroundImage(assets.image`場景1`) scene.cameraShake(3, 1000) 土壤1 = sprites.create(assets.image`坑洞1`, SpriteKind.background) 土壤2 = sprites.create(assets.image`坑洞1`, SpriteKind.background) 土壤3 = sprites.create(assets.image`坑洞1`, SpriteKind.background) 土壤4 = sprites.create(assets.image`坑洞1`, SpriteKind.background) 土壤5 = sprites.create(assets.image`坑洞1`, SpriteKind.background) 土壤6 = sprites.create(assets.image`坑洞1`, SpriteKind.background) 土壤7 = sprites.create(assets.image`坑洞1`, SpriteKind.background) 土壤8 = sprites.create(assets.image`坑洞1`, SpriteKind.background) 土壤9 = sprites.create(assets.image`坑洞1`, SpriteKind.background) 土壤1.setPosition(40, 40) 土壤2.setPosition(80, 40) 土壤3.setPosition(120, 40) 土壤4.setPosition(40, 60) 土壤5.setPosition(80, 60) 土壤6.setPosition(120, 60) 土壤7.setPosition(40, 80) 土壤8.setPosition(80, 80) 土壤9.setPosition(120, 80) 槌子 = sprites.create(assets.image`槌子`, SpriteKind.道具) controller.moveSprite(槌子) 槌子.setStayInScreen(true) game.splash("控制方向鍵打擊地鼠") } } sprites.onOverlap(SpriteKind.道具, SpriteKind.按鈕, function (sprite, otherSprite) { if (otherSprite == 開始按鍵 && controller.A.isPressed()) { 一開始 = 1 遊戲頁面() } if (otherSprite == 繼續按鍵 && controller.A.isPressed()) { 一開始 = 2 遊戲頁面() 遊戲內容() } if (otherSprite == 介紹按鍵 && controller.A.isPressed()) { 一開始 = 3 遊戲介紹() } }) function 遊戲介紹 () { if (一開始 == 3) { scene.setBackgroundImage(assets.image`場景1`) 介紹按鍵.destroy() 開始按鍵.destroy() 槌子.destroy() 村民2 = sprites.create(img` . . . . . f f 4 4 f f . . . . . . . . . f 5 4 5 5 4 5 f . . . . . . . f e 4 5 5 5 5 4 e f . . . . . f b 3 e 4 4 4 4 e 3 b f . . . . f 3 3 3 3 3 3 3 3 3 3 f . . . f 3 3 e b 3 e e 3 b e 3 3 f . . f 3 3 f f e e e e f f 3 3 f . . f b b f b f e e f b f b b f . . f b b e 1 f 4 4 f 1 e b b f . f f b b f 4 4 4 4 4 4 f b b f f f b b f f f e e e e f f f b b f . f e e f b d d d d b f e e f . . . e 4 c d d d d d d c 4 e . . . . e f b d b d b d b b f e . . . . . f f 1 d 1 d 1 d f f . . . . . . . . f f b b f f . . . . . `, SpriteKind.人物) 村民2.say("你好" + "這裡是遊戲介紹" + ("移動鍵盤" + "就可以打擊地鼠" + "並且打死20 40 60地鼠就會跳到下張地圖,並且更換道具" + "打死隻至100時遊戲結束")) 槌子 = sprites.create(assets.image`槌子`, SpriteKind.道具) controller.moveSprite(槌子) } } function 遊戲頁面 () { if (一開始 == 0) { scene.setBackgroundImage(assets.image`22222`) 開始按鍵 = sprites.create(assets.image`myImage3`, SpriteKind.按鈕) 槌子 = sprites.create(assets.image`槌子`, SpriteKind.道具) 開始按鍵.setPosition(80, 72) controller.moveSprite(槌子) 槌子.setStayInScreen(true) 介紹按鍵 = sprites.create(assets.image`myImage4`, SpriteKind.按鈕) 介紹按鍵.setPosition(139, 15) } if (一開始 == 1) { 槌子.destroy() 開始按鍵.destroy() 介紹按鍵.destroy() scene.setBackgroundImage(assets.image`場景1`) 村民 = sprites.create(img` . . . . . . 5 . 5 . . . . . . . . . . . . f 5 5 5 f f . . . . . . . . . f 1 5 2 5 1 6 f . . . . . . . f 1 6 6 6 6 6 1 6 f . . . . . . f 6 6 f f f f 6 1 f . . . . . . f 6 f f d d f f 6 f . . . . . f 6 f d f d d f d f 6 f . . . . f 6 f d 3 d d 3 d f 6 f . . . . f 6 6 f d d d d f 6 6 f . . . f 6 6 f 3 f f f f 3 f 6 6 f . . . f f d 3 5 3 3 5 3 3 f f . . . . f d f f 3 5 5 3 f d f . . . . . . f f 3 3 3 3 3 f d f . . . . . . f 3 3 5 3 3 5 3 f f . . . . . . f f f f f f f f f . . . . . . . . . f f . . f f . . . . . `, SpriteKind.人物) 繼續按鍵 = sprites.create(assets.image`myImage2`, SpriteKind.按鈕) 槌子 = sprites.create(assets.image`槌子`, SpriteKind.道具) controller.moveSprite(槌子) 槌子.setStayInScreen(true) 村民.say("你好" + "勇者" + ("我們的村莊,因為在做實驗的時候病毒不小心外洩了" + "導致有一隻地鼠感染變異,之後就陸續擴散" + "現在我們需要你" + "請幫我們消滅地鼠吧" + "事成後我會答謝你的")) } if (一開始 == 2) { 槌子.destroy() 繼續按鍵.destroy() 村民.destroy() scene.setBackgroundImage(assets.image`場景1`) game_1 = 2 } } controller.menu.onEvent(ControllerButtonEvent.Pressed, function () { if (game_1 == 2) { scene.setBackgroundImage(assets.image`3`) } }) sprites.onOverlap(SpriteKind.道具, SpriteKind.Enemy, function (sprite, otherSprite) { if (true) { animation.runImageAnimation( 槌子, assets.animation`會動的槌子`, 200, false ) if (info.score() >= 20) { animation.runImageAnimation( 雲朵槌子, assets.animation`會動的雲朵垂`, 200, false ) } if (info.score() >= 40) { animation.runImageAnimation( 鐮刀, assets.animation`myAnim`, 200, false ) } otherSprite.destroy(effects.ashes, 200) info.changeScoreBy(1) } if (info.score() == 20) { 槌子.destroy() scene.setBackgroundImage(assets.image`藍藍的天`) 雲朵槌子 = sprites.create(assets.image`雲朵武器`, SpriteKind.道具) 雲朵槌子.setVelocity(150, 150) controller.moveSprite(雲朵槌子) 雲朵槌子.setStayInScreen(true) } if (info.score() == 40) { 雲朵槌子.destroy() scene.setBackgroundImage(assets.image`3`) 土壤1.destroy() 土壤2.destroy() 土壤3.destroy() 土壤4.destroy() 土壤5.destroy() 土壤6.destroy() 土壤7.destroy() 土壤8.destroy() 土壤9.destroy() 土壤21 = sprites.create(assets.image`火1`, SpriteKind.background) 土壤20 = sprites.create(assets.image`myImage0`, SpriteKind.background) 土壤19 = sprites.create(assets.image`火1`, SpriteKind.background) 土壤10 = sprites.create(assets.image`坑洞2`, SpriteKind.background) 土壤11 = sprites.create(assets.image`坑洞2`, SpriteKind.background) 土壤12 = sprites.create(assets.image`坑洞2`, SpriteKind.background) 土壤13 = sprites.create(assets.image`坑洞2`, SpriteKind.background) 土壤14 = sprites.create(assets.image`坑洞2`, SpriteKind.background) 土壤15 = sprites.create(assets.image`坑洞2`, SpriteKind.background) 土壤16 = sprites.create(assets.image`坑洞2`, SpriteKind.background) 土壤17 = sprites.create(assets.image`坑洞2`, SpriteKind.background) 土壤18 = sprites.create(assets.image`坑洞2`, SpriteKind.background) 土壤21.setPosition(141, 33) 土壤19.setPosition(17, 21) 土壤20.setPosition(93, 15) 土壤10.setPosition(40, 40) 土壤11.setPosition(80, 40) 土壤12.setPosition(120, 40) 土壤13.setPosition(40, 60) 土壤14.setPosition(80, 60) 土壤15.setPosition(120, 60) 土壤16.setPosition(40, 80) 土壤17.setPosition(80, 80) 土壤18.setPosition(120, 80) 鐮刀 = sprites.create(assets.image`鐮刀`, SpriteKind.道具) controller.moveSprite(鐮刀) 鐮刀.setVelocity(200, 200) 鐮刀.setStayInScreen(true) } if (info.score() == 100) { color.FadeToBlack.startScreenEffect() pause(3000) color.clearFadeEffect() game.over(true) } }) let 芋頭: Sprite = null let 粉粉: Sprite = null let 小辣椒: Sprite = null let 基本款: Sprite = null let 水噹噹: Sprite = null let random = 0 let pos9: number[] = [] let pos8: number[] = [] let pos7: number[] = [] let pos6: number[] = [] let pos5: number[] = [] let pos4: number[] = [] let pos3: number[] = [] let pos2: number[] = [] let pos1: number[] = [] let 殭屍: Sprite = null let 土壤18: Sprite = null let 土壤17: Sprite = null let 土壤16: Sprite = null let 土壤15: Sprite = null let 土壤14: Sprite = null let 土壤13: Sprite = null let 土壤12: Sprite = null let 土壤11: Sprite = null let 土壤10: Sprite = null let 土壤19: Sprite = null let 土壤20: Sprite = null let 土壤21: Sprite = null let 鐮刀: Sprite = null let 雲朵槌子: Sprite = null let 村民: Sprite = null let 村民2: Sprite = null let 介紹按鍵: Sprite = null let 繼續按鍵: Sprite = null let 開始按鍵: Sprite = null let 槌子: Sprite = null let 土壤9: Sprite = null let 土壤8: Sprite = null let 土壤7: Sprite = null let 土壤6: Sprite = null let 土壤5: Sprite = null let 土壤4: Sprite = null let 土壤3: Sprite = null let 土壤2: Sprite = null let 土壤1: Sprite = null let game_1 = 0 let 一開始 = 0 一開始 = 0 遊戲頁面() 遊戲內容() 遊戲介紹() game.onUpdateInterval(5000, function () { if (info.score() >= 20) { 殭屍 = sprites.create(assets.image`殭屍`, SpriteKind.Enemy) pos1 = [40, 36] pos2 = [80, 36] pos3 = [120, 36] pos4 = [40, 56] pos5 = [80, 56] pos6 = [120, 56] pos7 = [40, 76] pos8 = [80, 76] pos9 = [120, 76] random = randint(0, 8) if (random == 0) { 殭屍.setPosition(pos1[0], pos1[1]) } else if (random == 1) { 殭屍.setPosition(pos2[0], pos2[1]) } else if (random == 2) { 殭屍.setPosition(pos3[0], pos3[1]) } else if (random == 3) { 殭屍.setPosition(pos4[0], pos4[1]) } else if (random == 4) { 殭屍.setPosition(pos5[0], pos5[1]) } else if (random == 5) { 殭屍.setPosition(pos6[0], pos6[1]) } else if (random == 6) { 殭屍.setPosition(pos7[0], pos7[1]) } else if (random == 7) { 殭屍.setPosition(pos8[0], pos8[1]) } else if (random == 8) { 殭屍.setPosition(pos9[0], pos9[1]) } } }) game.onUpdateInterval(7000, function () { if (info.score() >= 50) { 水噹噹 = sprites.create(assets.image`水噹噹`, SpriteKind.Enemy) pos1 = [40, 36] pos2 = [80, 36] pos3 = [120, 36] pos4 = [40, 56] pos5 = [80, 56] pos6 = [120, 56] pos7 = [40, 76] pos8 = [80, 76] pos9 = [120, 76] random = randint(0, 8) if (random == 0) { 水噹噹.setPosition(pos1[0], pos1[1]) } else if (random == 1) { 水噹噹.setPosition(pos2[0], pos2[1]) } else if (random == 2) { 水噹噹.setPosition(pos3[0], pos3[1]) } else if (random == 3) { 水噹噹.setPosition(pos4[0], pos4[1]) } else if (random == 4) { 水噹噹.setPosition(pos5[0], pos5[1]) } else if (random == 5) { 水噹噹.setPosition(pos6[0], pos6[1]) } else if (random == 6) { 水噹噹.setPosition(pos7[0], pos7[1]) } else if (random == 7) { 水噹噹.setPosition(pos8[0], pos8[1]) } else if (random == 8) { 水噹噹.setPosition(pos9[0], pos9[1]) } } }) game.onUpdateInterval(2000, function () { if (game_1 == 2) { 基本款 = sprites.create(assets.image`基本款`, SpriteKind.Enemy) pos1 = [40, 36] pos2 = [80, 36] pos3 = [120, 36] pos4 = [40, 56] pos5 = [80, 56] pos6 = [120, 56] pos7 = [40, 76] pos8 = [80, 76] pos9 = [120, 76] random = randint(0, 8) if (random == 0) { 基本款.setPosition(pos1[0], pos1[1]) } else if (random == 1) { 基本款.setPosition(pos2[0], pos2[1]) } else if (random == 2) { 基本款.setPosition(pos3[0], pos3[1]) } else if (random == 3) { 基本款.setPosition(pos4[0], pos4[1]) } else if (random == 4) { 基本款.setPosition(pos5[0], pos5[1]) } else if (random == 5) { 基本款.setPosition(pos6[0], pos6[1]) } else if (random == 6) { 基本款.setPosition(pos7[0], pos7[1]) } else if (random == 7) { 基本款.setPosition(pos8[0], pos8[1]) } else if (random == 8) { 基本款.setPosition(pos9[0], pos9[1]) } } }) game.onUpdateInterval(4000, function () { if (info.score() >= 35) { 小辣椒 = sprites.create(assets.image`小辣椒`, SpriteKind.Enemy) pos1 = [40, 36] pos2 = [80, 36] pos3 = [120, 36] pos4 = [40, 56] pos5 = [80, 56] pos6 = [120, 56] pos7 = [40, 76] pos8 = [80, 76] pos9 = [120, 76] random = randint(0, 8) if (random == 0) { 小辣椒.setPosition(pos1[0], pos1[1]) } else if (random == 1) { 小辣椒.setPosition(pos2[0], pos2[1]) } else if (random == 2) { 小辣椒.setPosition(pos3[0], pos3[1]) } else if (random == 3) { 小辣椒.setPosition(pos4[0], pos4[1]) } else if (random == 4) { 小辣椒.setPosition(pos5[0], pos5[1]) } else if (random == 5) { 小辣椒.setPosition(pos6[0], pos6[1]) } else if (random == 6) { 小辣椒.setPosition(pos7[0], pos7[1]) } else if (random == 7) { 小辣椒.setPosition(pos8[0], pos8[1]) } else if (random == 8) { 小辣椒.setPosition(pos9[0], pos9[1]) } } }) forever(function () { music.setTempo(126) for (let index = 0; index < 2; index++) { music.playTone(370, music.beat(BeatFraction.Whole)) music.playTone(370, music.beat(BeatFraction.Half)) music.playTone(554, music.beat(BeatFraction.Half)) music.playTone(494, music.beat(BeatFraction.Whole)) music.playTone(440, music.beat(BeatFraction.Whole)) music.playTone(415, music.beat(BeatFraction.Whole)) music.playTone(415, music.beat(BeatFraction.Half)) music.playTone(415, music.beat(BeatFraction.Half)) music.playTone(494, music.beat(BeatFraction.Whole)) music.playTone(440, music.beat(BeatFraction.Half)) music.playTone(415, music.beat(BeatFraction.Half)) music.playTone(370, music.beat(BeatFraction.Whole)) music.playTone(370, music.beat(BeatFraction.Half)) music.playTone(880, music.beat(BeatFraction.Half)) music.playTone(831, music.beat(BeatFraction.Half)) music.playTone(880, music.beat(BeatFraction.Half)) music.playTone(831, music.beat(BeatFraction.Half)) music.playTone(880, music.beat(BeatFraction.Half)) music.playTone(370, music.beat(BeatFraction.Whole)) music.playTone(370, music.beat(BeatFraction.Half)) music.playTone(880, music.beat(BeatFraction.Half)) music.playTone(831, music.beat(BeatFraction.Half)) music.playTone(880, music.beat(BeatFraction.Half)) music.playTone(831, music.beat(BeatFraction.Half)) music.playTone(880, music.beat(BeatFraction.Half)) } music.playTone(440, music.beat(BeatFraction.Half)) music.playTone(440, music.beat(BeatFraction.Half)) music.playTone(440, music.beat(BeatFraction.Half)) music.playTone(440, music.beat(BeatFraction.Half)) music.playTone(554, music.beat(BeatFraction.Half)) music.playTone(554, music.beat(BeatFraction.Half)) music.playTone(554, music.beat(BeatFraction.Half)) music.playTone(554, music.beat(BeatFraction.Half)) music.playTone(494, music.beat(BeatFraction.Half)) music.playTone(494, music.beat(BeatFraction.Half)) music.playTone(494, music.beat(BeatFraction.Half)) music.playTone(494, music.beat(BeatFraction.Half)) music.playTone(659, music.beat(BeatFraction.Half)) music.playTone(659, music.beat(BeatFraction.Half)) music.playTone(659, music.beat(BeatFraction.Half)) music.playTone(659, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(740, music.beat(BeatFraction.Half)) music.playTone(494, music.beat(BeatFraction.Half)) music.playTone(440, music.beat(BeatFraction.Half)) music.playTone(415, music.beat(BeatFraction.Half)) music.playTone(330, music.beat(BeatFraction.Half)) }) forever(function () { music.setTempo(126) for (let index = 0; index < 2; index++) { music.playTone(294, music.beat(BeatFraction.Double)) music.playTone(294, music.beat(BeatFraction.Double)) music.playTone(494, music.beat(BeatFraction.Double)) music.playTone(494, music.beat(BeatFraction.Double)) music.playTone(277, music.beat(BeatFraction.Double)) music.playTone(277, music.beat(BeatFraction.Double)) music.playTone(277, music.beat(BeatFraction.Double)) music.playTone(277, music.beat(BeatFraction.Double)) } music.playTone(294, music.beat(BeatFraction.Whole)) music.playTone(294, music.beat(BeatFraction.Whole)) music.playTone(294, music.beat(BeatFraction.Whole)) music.playTone(294, music.beat(BeatFraction.Whole)) music.playTone(330, music.beat(BeatFraction.Whole)) music.playTone(330, music.beat(BeatFraction.Whole)) music.playTone(330, music.beat(BeatFraction.Whole)) music.playTone(330, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) music.playTone(277, music.beat(BeatFraction.Whole)) }) forever(function () { music.setTempo(126) for (let index = 0; index < 2; index++) { music.playTone(147, music.beat(BeatFraction.Breve)) music.playTone(247, music.beat(BeatFraction.Breve)) music.playTone(139, music.beat(BeatFraction.Breve)) music.playTone(139, music.beat(BeatFraction.Breve)) } music.playTone(147, music.beat(BeatFraction.Breve)) music.playTone(165, music.beat(BeatFraction.Breve)) music.playTone(139, music.beat(BeatFraction.Breve)) music.playTone(139, music.beat(BeatFraction.Breve)) }) game.onUpdateInterval(8000, function () { if (info.score() >= 50) { 粉粉 = sprites.create(assets.image`粉`, SpriteKind.Enemy) pos1 = [40, 36] pos2 = [80, 36] pos3 = [120, 36] pos4 = [40, 56] pos5 = [80, 56] pos6 = [120, 56] pos7 = [40, 76] pos8 = [80, 76] pos9 = [120, 76] random = randint(0, 8) if (random == 0) { 粉粉.setPosition(pos1[0], pos1[1]) } else if (random == 1) { 粉粉.setPosition(pos2[0], pos2[1]) } else if (random == 2) { 粉粉.setPosition(pos3[0], pos3[1]) } else if (random == 3) { 粉粉.setPosition(pos4[0], pos4[1]) } else if (random == 4) { 粉粉.setPosition(pos5[0], pos5[1]) } else if (random == 5) { 粉粉.setPosition(pos6[0], pos6[1]) } else if (random == 6) { 粉粉.setPosition(pos7[0], pos7[1]) } else if (random == 7) { 粉粉.setPosition(pos8[0], pos8[1]) } else if (random == 8) { 粉粉.setPosition(pos9[0], pos9[1]) } } }) game.onUpdateInterval(10000, function () { if (info.score() >= 50) { 芋頭 = sprites.create(assets.image`芋頭`, SpriteKind.Enemy) pos1 = [40, 36] pos2 = [80, 36] pos3 = [120, 36] pos4 = [40, 56] pos5 = [80, 56] pos6 = [120, 56] pos7 = [40, 76] pos8 = [80, 76] pos9 = [120, 76] 一開始 = randint(0, 8) if (random == 0) { 芋頭.setPosition(pos1[0], pos1[1]) } else if (random == 1) { 芋頭.setPosition(pos2[0], pos2[1]) } else if (random == 2) { 芋頭.setPosition(pos3[0], pos3[1]) } else if (random == 3) { 芋頭.setPosition(pos4[0], pos4[1]) } else if (random == 4) { 芋頭.setPosition(pos5[0], pos5[1]) } else if (random == 5) { 芋頭.setPosition(pos6[0], pos6[1]) } else if (random == 6) { 芋頭.setPosition(pos7[0], pos7[1]) } else if (random == 7) { 芋頭.setPosition(pos8[0], pos8[1]) } else if (random == 8) { 芋頭.setPosition(pos9[0], pos9[1]) } } })
61ab26cccd2fbcf8ca19581db3cb4bf57c8e600c
[ "TypeScript" ]
1
TypeScript
rita08113/arcademakecodewhacamole
0c1277fe0b04c536fe36cfa70c0d03d468096f2f
5fdfb6efa2f87a3f1f33a23de7f56bac8d7568a5
refs/heads/master
<repo_name>emersonbnp/health-monitoring-api<file_sep>/src/main/java/com/healthmonitoringapi/controller/UserController.java package com.healthmonitoringapi.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.healthmonitoringapi.dto.UserDTO; import com.healthmonitoringapi.entity.User; import com.healthmonitoringapi.service.UserService; import com.healthmonitoringapi.util.Response; @RestController @RequestMapping("/user") public class UserController extends BasicController<UserDTO> { @Autowired private UserService userService; @PostMapping public ResponseEntity<Response<UserDTO>> save(@Valid @RequestBody UserDTO userDTO, BindingResult result) { if (result.getAllErrors().isEmpty()) { User user= new User(); user.parse(userDTO); userDTO = new UserDTO(); userDTO.parse(userService.save(user)); return new ResponseEntity<Response<UserDTO>>(new Response<UserDTO>(userDTO), HttpStatus.CREATED); } else { return error(result); } } } <file_sep>/src/main/java/com/healthmonitoringapi/dto/AddressDTO.java package com.healthmonitoringapi.dto; import java.io.Serializable; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.healthmonitoringapi.entity.Address; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) public class AddressDTO implements Serializable { /** * */ private static final long serialVersionUID = -5271055302648034381L; private Integer id; @NotNull(message = "Street name should not be empty") private String street; @NotNull(message = "City name should not be empty") private String city; @NotNull(message = "District name should not be empty") private String district; @NotNull(message = "State name should not be empty") private String state; @NotNull(message = "Street number should not be empty") private String number; @NotNull(message = "Zipcode should not be empty") private String zipcode; @JsonInclude(Include.NON_NULL) private String description; void parse(Address entity) { this.id = entity.getId(); this.street = entity.getStreet(); this.city = entity.getCity(); this.district = entity.getDistrict(); this.state = entity.getState(); this.number = entity.getNumber(); this.zipcode = entity.getZipcode(); this.description = entity.getDescription(); } } <file_sep>/Dockerfile # Step : Package image FROM openjdk:8-jre-alpine CMD exec java $JAVA_OPTS -jar /app/my-app.jar WORKDIR /build COPY target/*.jar /app/my-app.jar<file_sep>/src/main/java/com/healthmonitoringapi/service/impl/UserServiceImpl.java package com.healthmonitoringapi.service.impl; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.healthmonitoringapi.entity.User; import com.healthmonitoringapi.exception.EntityNotFoundException; import com.healthmonitoringapi.repository.UserRepository; import com.healthmonitoringapi.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override public User save(User user) { return userRepository.save(user); } @Override public User update(User user) throws EntityNotFoundException { if (userRepository.existsById(user.getId())) { return userRepository.save(user); } else { throw new EntityNotFoundException("Entity not found."); } } @Override public User findById(Integer id) throws EntityNotFoundException { return userRepository.findById(id).orElseThrow(() -> new EntityNotFoundException()); } @Override public User findByEmailAndPassword(String username, String password) throws EntityNotFoundException { return userRepository.findByUsernameAndPassword(username, password) .orElseThrow(() -> new EntityNotFoundException()); } @Override public Optional<User> findByEmail(String email) { return userRepository.findByEmail(email); } } <file_sep>/src/main/java/com/healthmonitoringapi/exception/CustomException.java package com.healthmonitoringapi.exception; public class CustomException extends Throwable { /** * */ private static final long serialVersionUID = -1758607852534983331L; public CustomException(String message) { super(message); } } <file_sep>/src/main/java/com/healthmonitoringapi/util/Response.java package com.healthmonitoringapi.util; import java.util.ArrayList; import java.util.List; import lombok.Data; @Data public class Response <T> { public Response(T data) { super(); this.data = data; } public Response(List<String> errors) { this.errors = errors; } public Response() { } private T data; private List<String> errors = new ArrayList<>(); } <file_sep>/src/main/java/com/healthmonitoringapi/service/ParentService.java package com.healthmonitoringapi.service; import com.healthmonitoringapi.entity.Parent; public interface ParentService { Parent save(Parent parent); Parent update(Parent parent); Parent findById(Integer id); }<file_sep>/src/main/java/com/healthmonitoringapi/repository/InfantRepository.java package com.healthmonitoringapi.repository; import java.util.List; import java.util.Optional; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.healthmonitoringapi.entity.Infant; import com.healthmonitoringapi.entity.Parent; @Repository public interface InfantRepository extends JpaRepository<Infant, Long> { public Optional<Infant> findById(Integer id); public Optional<Infant> findByDevice(String device); public Optional<List<Infant>> findByParent(Parent parent, Pageable pageable); public Optional<Infant> findByIdAndParent(Integer id, Parent parent); } <file_sep>/src/main/java/com/healthmonitoringapi/repository/ParentRepository.java package com.healthmonitoringapi.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.healthmonitoringapi.entity.Parent; public interface ParentRepository extends JpaRepository<Parent, Integer>{ } <file_sep>/src/main/java/com/healthmonitoringapi/dto/UserDTO.java package com.healthmonitoringapi.dto; import java.io.Serializable; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.healthmonitoringapi.entity.User; import lombok.Data; @Data public class UserDTO implements Serializable { /** * */ private static final long serialVersionUID = 3063009554101058648L; private Integer id; @NotNull(message = "Email can't be empty") @Email(message = "Email can't be empty") private String email; @NotNull(message = "Username can't be empty") @Length(min = 3, max = 32, message = "Username should contain between 3 and 32 characters") private String username; @NotNull(message = "Password can't be empty") @Length(min = 6, max = 32, message = "Password should contain between 6 and 32 characters") @JsonInclude(Include.NON_NULL) private String password; @NotNull(message = "Parent info is necessary") private ParentDTO parent; public void parse(User entity) { this.id = entity.getId(); this.email = entity.getEmail(); this.username = entity.getUsername(); this.parent = new ParentDTO(); this.parent.parse(entity.getParent()); } } <file_sep>/src/test/java/com/healthmonitoringapi/controller/UserControllerTest.java package com.healthmonitoringapi.controller; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.BDDMockito; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.healthmonitoringapi.dto.ParentDTO; import com.healthmonitoringapi.dto.UserDTO; import com.healthmonitoringapi.entity.Parent; import com.healthmonitoringapi.entity.User; import com.healthmonitoringapi.service.UserService; @ActiveProfiles("test") @SpringBootTest @RunWith(SpringRunner.class) @AutoConfigureMockMvc public class UserControllerTest { private final String URL = "/user"; private final Integer ID = 1; private final String USER = "user"; private final String EMAIL = "<EMAIL>"; private final String INVALID_EMAIL = "user"; private final String PASSWORD = "<PASSWORD>"; private final String PARENT_FIRST_NAME = "João"; private final String PARENT_LAST_NAME = "Silva"; private final String PARENT_USERID = "1234651561816"; private final String PARENT_PHONE = "83999998888"; private final String INVALID_EMAIL_MSG = "Email can't be empty"; @MockBean private UserService userService; @Autowired private MockMvc mvc; @Test public void saveUser() throws Exception { BDDMockito.given(userService.save(Mockito.any(User.class))) .willReturn(getMockUser()); mvc.perform(MockMvcRequestBuilders.post(URL) .content(getJsonPayload(ID, USER, EMAIL, PASSWORD)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(jsonPath("$.data.id").value(ID)) .andExpect(jsonPath("$.data.username").value(USER)) .andExpect(jsonPath("$.data.email").value(EMAIL)) .andExpect(jsonPath("$.data.password").doesNotExist()); } @Test public void saveInvalidUser() throws Exception { BDDMockito.given(userService.save(Mockito.any(User.class))) .willReturn(getMockUser()); mvc.perform(MockMvcRequestBuilders.post(URL) .content(getJsonPayload(ID, USER, INVALID_EMAIL, PASSWORD)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors[0]").value(INVALID_EMAIL_MSG)); } private String getJsonPayload(Integer id, String username, String email, String password) throws JsonProcessingException { UserDTO dto = new UserDTO(); dto.setId(id); dto.setUsername(username); dto.setEmail(email); dto.setPassword(<PASSWORD>); ParentDTO parentDTO = new ParentDTO(); parentDTO.setFirstName(PARENT_FIRST_NAME); parentDTO.setLastName(PARENT_LAST_NAME); parentDTO.setPhone(PARENT_PHONE); parentDTO.setUserID(PARENT_USERID); dto.setParent(parentDTO); return (new ObjectMapper()).writeValueAsString(dto); } public User getMockUser() { Parent parent = new Parent(); parent.setId(ID); parent.setFirstName(PARENT_FIRST_NAME); parent.setLastName(PARENT_LAST_NAME); parent.setPhone(PARENT_PHONE); parent.setUserID(PARENT_USERID); User user = new User(); user.setId(ID); user.setEmail(EMAIL); user.setUsername(USER); user.setPassword(<PASSWORD>); user.setParent(parent); return user; } } <file_sep>/src/main/java/com/healthmonitoringapi/service/InfantService.java package com.healthmonitoringapi.service; import java.util.List; import org.springframework.data.domain.Pageable; import com.healthmonitoringapi.entity.Infant; import com.healthmonitoringapi.entity.Parent; import com.healthmonitoringapi.exception.EntityNotFoundException; public interface InfantService { Infant findById(Integer id) throws EntityNotFoundException; Infant save(Infant infant) throws EntityNotFoundException; List<Infant> findByParent(Parent parent, Pageable pageable); Infant findByIdAndParent(Integer id, Parent parent) throws EntityNotFoundException; }<file_sep>/src/test/java/com/healthmonitoringapi/repository/UserRepositoryTest.java package com.healthmonitoringapi.repository; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.healthmonitoringapi.entity.Parent; import com.healthmonitoringapi.entity.User; import com.healthmonitoringapi.repository.ParentRepository; import com.healthmonitoringapi.repository.UserRepository; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public class UserRepositoryTest { private final String USER = "user"; private final String EMAIL = "<EMAIL>"; private final String PASSWORD = "<PASSWORD>"; private final String PARENT_FIRST_NAME = "João"; private final String PARENT_LAST_NAME = "Silva"; private final String PARENT_USERID = "1234651561816"; private final String PARENT_PHONE = "83999998888"; @Autowired private UserRepository userRepository; @Autowired private ParentRepository parentRepository; @Before public void before () { Parent parent = new Parent(); parent.setFirstName(PARENT_FIRST_NAME); parent.setLastName(PARENT_LAST_NAME); parent.setPhone(PARENT_PHONE); parent.setUserID(PARENT_USERID); parentRepository.save(parent); User user = new User(); user.setUsername(USER); user.setPassword(<PASSWORD>); user.setEmail(EMAIL); user.setParent(parent); userRepository.save(user); } @Test public void userWasSaved() { Optional<User> savedUser = userRepository.findByUsernameAndPassword(USER, PASSWORD); assertTrue(savedUser.isPresent()); User user = savedUser.get(); assertNotNull(user.getParent()); assertEquals(user.getParent().getFirstName(), PARENT_FIRST_NAME); assertEquals(user.getParent().getLastName(), PARENT_LAST_NAME); assertEquals(user.getParent().getPhone(), PARENT_PHONE); assertEquals(user.getParent().getUserID(), PARENT_USERID); } } <file_sep>/src/main/java/com/healthmonitoringapi/entity/Address.java package com.healthmonitoringapi.entity; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import com.healthmonitoringapi.dto.AddressDTO; import lombok.Data; import lombok.EqualsAndHashCode; @Entity @Table(name = "address") @Data @EqualsAndHashCode(callSuper = false) public class Address implements Serializable { /** * */ private static final long serialVersionUID = 1501434443126913173L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "idaddress") private Integer id; @Column(name = "latitude") private BigDecimal latitude; @Column(name = "longitude") private BigDecimal longitude; @Column(name = "city") private String city; @Column(name = "state") private String state; @Column(name = "street") private String street; @Column(name = "district") private String district; @Column(name = "zipcode") private String zipcode; @Column(name = "number") private String number; @Column(name = "description") private String description; @JoinColumn(name = "idinfant", referencedColumnName = "idinfant") @OneToOne(fetch = FetchType.LAZY) private Infant infant; public void parse(AddressDTO addressDTO, Infant infant) { this.setInfant(infant); this.parse(addressDTO); } public void parse(AddressDTO addressDTO) { this.setCity(addressDTO.getCity()); this.setDescription(addressDTO.getDescription()); this.setDistrict(addressDTO.getDistrict()); this.setNumber(addressDTO.getNumber()); this.setState(addressDTO.getState()); this.setStreet(addressDTO.getStreet()); this.setZipcode(addressDTO.getZipcode()); } } <file_sep>/src/main/java/com/healthmonitoringapi/service/impl/ParentServiceImpl.java package com.healthmonitoringapi.service.impl; import javax.persistence.EntityNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.healthmonitoringapi.entity.Parent; import com.healthmonitoringapi.entity.User; import com.healthmonitoringapi.repository.ParentRepository; import com.healthmonitoringapi.service.ParentService; import com.healthmonitoringapi.service.UserService; @Service public class ParentServiceImpl implements ParentService { @Autowired private ParentRepository parentRepository; @Autowired private UserService userService; public Parent save(Parent parent) { User user = parent.getUser(); userService.save(user); return parentRepository.save(parent); } public Parent update(Parent parent) { return parentRepository.save(parent); } @Override public Parent findById(Integer id) throws EntityNotFoundException { return parentRepository.findById(id).orElseThrow(() -> new EntityNotFoundException()); } }<file_sep>/src/main/java/com/healthmonitoringapi/service/impl/InfantServiceImpl.java package com.healthmonitoringapi.service.impl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.healthmonitoringapi.entity.Infant; import com.healthmonitoringapi.entity.Parent; import com.healthmonitoringapi.exception.EntityNotFoundException; import com.healthmonitoringapi.repository.InfantRepository; import com.healthmonitoringapi.service.InfantService; @Service public class InfantServiceImpl implements InfantService { @Autowired private InfantRepository infantRepository; @Override public Infant findById(Integer id) throws EntityNotFoundException { return this.infantRepository.findById(id).get(); } @Override @CacheEvict(value = "findByParent", allEntries = true) public Infant save(Infant infant) throws EntityNotFoundException { return this.infantRepository.save(infant); } @Override @Cacheable(value = "findByParent") public List<Infant> findByParent(Parent parent, Pageable pageable) { return this.infantRepository.findByParent(parent, pageable).orElse(new ArrayList<Infant>()); } @Override public Infant findByIdAndParent(Integer id, Parent parent) throws EntityNotFoundException { return this.infantRepository.findByIdAndParent(id, parent).orElseThrow(() -> new EntityNotFoundException()); } }<file_sep>/src/main/java/com/healthmonitoringapi/entity/Parent.java package com.healthmonitoringapi.entity; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import com.healthmonitoringapi.dto.ParentDTO; import lombok.Data; @Entity @Table(name = "parent") @Data public class Parent implements Serializable { /** * */ private static final long serialVersionUID = 6255620678102218300L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "idparent") private Integer id; @Column(name = "firstname") private String firstName; @Column(name = "lastname") private String lastName; @Column(name = "userid") private String userID; @Column(name = "phone") private String phone; @OneToMany(mappedBy = "parent") private List<Infant> infants; @OneToOne(mappedBy = "parent") private User user; public Parent() { } public Parent(Integer id) { this.id = id; } public void parse(ParentDTO parentDTO) { this.firstName = parentDTO.getFirstName(); this.lastName = parentDTO.getLastName(); this.phone = parentDTO.getPhone(); this.userID = parentDTO.getUserID(); } } <file_sep>/src/main/java/com/healthmonitoringapi/exception/handler/GlobalExceptionHandler.java package com.healthmonitoringapi.exception.handler; import java.util.Arrays; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.healthmonitoringapi.exception.CustomException; import com.healthmonitoringapi.util.Response; @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(value = { CustomException.class }) protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) { String error = ex.getCause().getMessage(); Response<Object> response = new Response<Object>(); response.setErrors(Arrays.asList(new String [] {error})); return handleExceptionInternal(ex, response, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); } @ExceptionHandler(Exception.class) protected ResponseEntity<Object> handleGenericConflict(Exception ex, WebRequest request) { String error = ex.getMessage(); Response<Object> response = new Response<Object>(); response.setErrors(Arrays.asList(new String [] {error})); return handleExceptionInternal(ex, response, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request); } }<file_sep>/src/main/resources/db/migration/postgresql/V1__init.sql CREATE TABLE healthmonitoringapi.parent ( idparent int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY, firstname varchar(255) NULL, lastname varchar(255) NULL, phone varchar(255) NULL, userid varchar(255) NULL, CONSTRAINT parent_pkey PRIMARY KEY (idparent) ); CREATE TABLE healthmonitoringapi."user" ( iduser int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY, email varchar(255) NULL, "password" varchar(255) NULL, username varchar(255) NULL, idparent int4 NULL, CONSTRAINT user_pkey PRIMARY KEY (iduser) ); ALTER TABLE healthmonitoringapi."user" ADD CONSTRAINT fk_user_parent FOREIGN KEY (idparent) REFERENCES healthmonitoringapi.parent(idparent); CREATE TABLE healthmonitoringapi.infant ( idinfant int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY, birthday date NULL, device varchar(255) NULL, firstname varchar(255) NULL, lastname varchar(255) NULL, weight numeric(19,2) NULL, idparent int4 NULL, CONSTRAINT infant_pkey PRIMARY KEY (idinfant) ); ALTER TABLE healthmonitoringapi.infant ADD CONSTRAINT fk_infant_parent FOREIGN KEY (idparent) REFERENCES healthmonitoringapi.parent(idparent); CREATE TABLE healthmonitoringapi.address ( idaddress int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY, city varchar(255) NULL, description varchar(255) NULL, district varchar(255) NULL, latitude numeric(19,2) NULL, longitude numeric(19,2) NULL, "number" varchar(255) NULL, state varchar(255) NULL, street varchar(255) NULL, zipcode varchar(255) NULL, idinfant int4 NULL, CONSTRAINT address_pkey PRIMARY KEY (idaddress) ); ALTER TABLE healthmonitoringapi.address ADD CONSTRAINT fk_address_infant FOREIGN KEY (idinfant) REFERENCES healthmonitoringapi.infant(idinfant); <file_sep>/src/main/java/com/healthmonitoringapi/config/SwaggerConfig.java package com.healthmonitoringapi.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger.web.ApiKeyVehicle; import springfox.documentation.swagger.web.SecurityConfiguration; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @Profile("dev") @EnableSwagger2 public class SwaggerConfig { @Value("${version}") private String version; @Value("${swagger_user_email}") private String swaggerUserEmail; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage("com.healthmonitoringapi.controller")) .paths(PathSelectors.any()).build().apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("Health Monitoring API") .description("Health Monitoring API - Documentação de acesso aos endpoints.").version(version) .build(); } }
d41c47f8eeae66df87b8743895bc55cdb3c68af9
[ "Java", "Dockerfile", "SQL" ]
20
Java
emersonbnp/health-monitoring-api
d2d003fece9a5076d1995c8098772e42763d09dd
047b77a8c1a28339ecd2560264335b22aa0c309e
refs/heads/main
<repo_name>jaxteam/vite<file_sep>/src/router/index.test.ts import { createMemoryHistory } from 'history' import React from 'react' import ReactDOM from 'react-dom' import MicroApp, {MicroRoutes, MicroContext } from './index' describe('测试路由', function () { // it("memory",function(){ // history.push("/hello/abc") // }) function hello(props: any) { // console.log(props) return React.createElement("div", "", "hello") } const routes: MicroRoutes<any, MicroContext> = [{ path: '/hello/:id', component: () => hello, engine: function (component: JSX.Element, element: HTMLElement) { ReactDOM.render(component, element) return element } }, { path: "/html", component: () => () => "<div>html</div>", engine: function (component: string, element: HTMLElement) { element.innerHTML = component return element } }, { path: '/dom', component: () => () => document.createElement("h1"), engine: function (component: HTMLElement, element: HTMLElement) { element.appendChild(component) return element } }] const app = new MicroApp({ history: createMemoryHistory({ initialEntries: ["/"], initialIndex: 0 }), routes:routes, }).render(document.body) it("memory html", function () { app.push("/html") }) it('memory dom', function () { app.push("/dom") }) it('micro addRouter',function(){ app.addView({ path:'/new', name:"new", component:() => () => "<div>new</div>", engine:function (component: string, element: HTMLElement) { element.innerHTML = component return element } }) app.push("/new") expect("/new").toBe(app.findURL("new")) app.push(app.findURL("new")) }) })<file_sep>/vite.config.ts import { defineConfig } from 'vite' import reactRefresh from '@vitejs/plugin-react-refresh' import vue from '@vitejs/plugin-vue' import { svelte } from '@sveltejs/vite-plugin-svelte' // https://vitejs.dev/config/ export default defineConfig({ plugins: [reactRefresh(),vue(),svelte()] })
c8b6250be66d241d1669cafaf51559b2ab068468
[ "TypeScript" ]
2
TypeScript
jaxteam/vite
f874c60522b37506a5b841ad0159c88651a98e5f
1d93c29d431c5a714e576bda9836ed73300f30c5
refs/heads/master
<file_sep>using System; using NUnit.Framework; using Prova.Tests.ForTestable.Features; using Prova.Tests.ForTestable.Types; using TechTalk.SpecFlow; namespace Prova.Tests.ForTestable { [Binding] public class DefaultDependenciesSteps : Steps { private readonly TestableContext _context; public DefaultDependenciesSteps(TestableContext context) { _context = context; } [Given(@"I clear all the default dependencies for the (.*)")] public void ClearAllTheDefaultDependenciesFor(Type type) { Testable.InstancesOf(type).UseNoDefaults(); } [When(@"I want all testables for the (.*) to use the (.*)")] public void AllTestablesToHaveDefaultDependency(Type testableType, Type defaultDependencyType) { Testable.InstancesOf(testableType).UseDefaultOf(defaultDependencyType); } [When(@"I want all testables for the (.*) to use a function that returns the type Dependency")] public void AllTestablesToHaveDefaultDependencyFunction(Type testableType) { Testable.InstancesOf(testableType).UseDefaultOf(Activator.CreateInstance<Dependency>); } [When(@"I create two testables for the (.*)")] public void CreateTwoTestablesFor(Type type) { _context.Testable = new Testable(type); _context.OtherTestable = new Testable(type); } [When(@"I want to use both the testable instances")] public void UseBothTheTestableInstances() { _context.Instance = _context.Testable.Create(); _context.SecondInstance = _context.OtherTestable.Create(); } [Then(@"I should have two instances with different dependencies of (.*)")] public void ShouldHaveTwoInstancesWithDifferentDependenciesOf(Type type) { Assert.That(_context.Instance.Dependency, Is.InstanceOf(type)); Assert.That(_context.SecondInstance.Dependency, Is.InstanceOf(type)); Assert.That(_context.Instance.Dependency, Is.Not.EqualTo(_context.SecondInstance.Dependency)); } } } <file_sep>using System; using System.Linq.Expressions; using System.Reflection; using NUnit.Framework; namespace Prova.Tests.ForTestable { public class TestableObjectTests { [Test] public void CanProvidePropertyValue() { var t = new TestableObject<MyObject>(); t.With(x => x.Name).SetTo("my name"); Assert.That(t.Create().Name, Is.EqualTo("my name")); } } internal class MyObject { public string Name { get; set; } } internal class TestableObject<T> where T : new() { private ExpressionWrapper<T> _expressionWrapper; public ExpressionWrapper<T> With(Expression<Func<T, dynamic>> expression) { _expressionWrapper = new ExpressionWrapper<T>(expression); return _expressionWrapper; } public T Create() { var foo = new T(); _expressionWrapper.ApplyTo(foo); return foo; } } internal class ExpressionWrapper<T> { private readonly Expression<Func<T, dynamic>> _expression; private dynamic _value; public ExpressionWrapper(Expression<Func<T, dynamic>> expression) { _expression = expression; } public void SetTo(dynamic value) { _value = value; } public void ApplyTo(dynamic instance) { var memberExpression = _expression.Body as MemberExpression; var propertyInfo = memberExpression?.Member as PropertyInfo; propertyInfo?.SetValue(instance, _value); } } } <file_sep>using System; namespace Prova.Tests.ForTestable.Features { public class TestableContext { public Testable Testable { get; set; } public Testable OtherTestable { get; set; } public dynamic Instance { get; set; } public dynamic SecondInstance { get; set; } public dynamic ExpectedDependency { get; set; } public Exception Exception { get; set; } } } <file_sep>using NUnit.Framework; using Prova.Tests.ForTestable.Types; namespace Prova.Tests.ForTestable { public class TestableTests { [Test] public void CanNotUseAbstractType() => Assert.That(() => new Testable<AbstractClass>(), Throws.ArgumentException); [Test] public void CanNotUseTypeWithAmbiguousConstructor() => Assert.That(() => new Testable<AmbiguousConstructor>(), Throws.ArgumentException); [Test] public void CanNotUseTypeWithMultipleConstructors() => Assert.That(() => new Testable<MultipleConstructors>(), Throws.ArgumentException); [Test] public void CanUseTypeWithoutExplicitConstructor() { var testable = new Testable<NoExplicitConstructor>(); Assert.That(testable.Create(), Is.InstanceOf<NoExplicitConstructor>()); } [Test] public void CanUseTypeWithExplicitConstructor() { var testable = new Testable<SingleDependency>(); Assert.That(testable.Create(), Is.InstanceOf<SingleDependency>()); } [Test] public void CanNotProvideAnInvalidDependency() { var testable = new Testable<SingleDependency>(); Assert.That(() => testable.With(new InvalidDependency()), Throws.ArgumentException); } [Test] public void CanImplicitlyProvideDependencies() { var testable = new Testable<SingleDependency>(); Assert.That(testable.Create().Dependency, Is.Not.Null); } [Test] public void CanExplicitlyProvideDependencies() { var testable = new Testable<SingleDependency>(); var dependency = new Dependency(); testable.With(dependency); Assert.That(testable.Create().Dependency, Is.EqualTo(dependency)); } [Test] public void CanNotProvideInvalidDefaultDependency() => Assert.That(Testable.InstancesOf<SingleDependency>().UseDefaultOf<InvalidDependency>, Throws.ArgumentException); [Test] public void CanProvideTypeAsDefaultDependency() { Testable.InstancesOf<SingleDependency>().UseDefaultOf<Dependency>(); var testable = new Testable<SingleDependency>(); Assert.That(testable.Create().Dependency, Is.TypeOf<Dependency>()); } [Test] public void CanProvideFunctionAsDefaultDependency() { Testable.InstancesOf<SingleDependency>().UseDefaultOf(() => new StubDependency()); var testable = new Testable<SingleDependency>(); Assert.That(testable.Create().Dependency, Is.TypeOf<StubDependency>()); } } } <file_sep>using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Prova.Extensions { [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public static class ForIEnumerable { public static bool HasCountOf<T>(this IEnumerable<T> enumerable, int count) { if (enumerable.IsNothing()) return false; return enumerable.Count() == count; } public static bool AreUnique<T>(this IEnumerable<T> enumerable) { if (enumerable.IsNothing()) return true; var list = enumerable as IList<T> ?? enumerable.ToList(); return list.Distinct().Count() == list.Count(); } } } <file_sep>using System; using System.Collections.Generic; namespace Prova.Testables { public static class DefaultDependencyLookup { private static readonly IDictionary<Type, dynamic> Lookup = new Dictionary<Type, dynamic>(); public static dynamic On(Type type) { if (!Lookup.ContainsKey(type)) { Lookup.Add(type, new DefaultDependencies(type)); } return Lookup[type]; } } } <file_sep>using System; using System.Linq; using System.Reflection; using Prova.Extensions; namespace Prova.Testables { public class ConstructorFinder { private readonly Type _type; public ConstructorFinder(Type type) { _type = type; } public ConstructorInfo Find() { if (_type.IsAbstract) throw _type.IsAbstractException(); var constructors = _type.GetConstructors().Where(ParameterTypesAreUnique).ToList(); if (!constructors.HasCountOf(1)) throw _type.TooManyConstructorsException(); return constructors.Single(); } private static bool ParameterTypesAreUnique(ConstructorInfo constructor) { return constructor.GetParameters().Select(p => p.ParameterType).AreUnique(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using TechTalk.SpecFlow; namespace Prova.Tests.ForTestable.Features { [Binding] public class StepArgumentTransformer { private static readonly IEnumerable<Type> AllLoadedTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()); [StepArgumentTransformation("type (.*)")] private Type TransformToType(string typeName) { return AllLoadedTypes.First(x => x.Name == typeName); } [StepArgumentTransformation("instance of (.*)")] public dynamic TransformToInstance(string typeName) { return Activator.CreateInstance(TransformToType(typeName)); } } } <file_sep>using System; namespace Prova.Extensions { public static class ForAction { public static Exception GetException(this Action action) { Exception exception = null; try { if (action.IsNotNothing()) { action(); } } catch (Exception ex) { exception = ex; } return exception; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Prova.Extensions; namespace Prova.Testables { public class DefaultDependencies { private readonly IDictionary<Type, dynamic> _defaults = new Dictionary<Type, dynamic>(); private readonly Type _type; internal DefaultDependencies(Type type) { _type = type; } public void UseDefaultOf<T>() { UseDefaultOf(Activator.CreateInstance<T>); } public void UseDefaultOf<T>(Func<T> function) { var constructor = new Constructor(_type); var parameterType = constructor.TypeOfParameterFor(typeof(T)); if (parameterType.IsNothing()) throw constructor.Type.HasNoMatchingParameterException(parameterType); if (_defaults.ContainsKey(parameterType)) { _defaults[parameterType] = function; } else { _defaults.Add(parameterType, function); } } public dynamic InstanceFor(Type type) { var key = _defaults.Keys.SingleOrDefault(type.IsAssignableFrom); return key.IsNotNothing() ? _defaults[key]() : default(dynamic); } } } <file_sep>using System; namespace Prova.Testables { public static class TypeExceptionExtensions { public static ArgumentException HasNoMatchingParameterException(this Type type, Type parameterType) { return new ArgumentException($"The constructor of the type [{type.Name}] does not contain a dependency assignable from type [{parameterType}]"); } public static ArgumentException IsAbstractException(this Type type) { return new ArgumentException($"The type [{type.Name}] is an abstract class."); } public static ArgumentException TooManyConstructorsException(this Type type) { return new ArgumentException($"Type [{type.Name}] must have a valid public constructor with uniquely typed parameters."); } } } <file_sep>using System.Diagnostics.CodeAnalysis; using NUnit.Framework; using Prova.Extensions; namespace Prova.Tests.ForExtensions { [TestFixture] public class ForIEnumerableTests { [Test] public void AreUniqueShouldReturnFalseForAUniqueArray() { var strings = new[] { "one", "two", "three" }; var result = strings.AreUnique(); Assert.That(result, Is.True); } [Test] [SuppressMessage("ReSharper", "ExpressionIsAlwaysNull")] public void AreUniqueShouldReturnTrueForNullEnumerable() { object[] objects = null; var result = objects.AreUnique(); Assert.That(result, Is.True); } [Test] public void AreUniqueShouldReturnTrueWithRepeatedItem() { var strings = new[] { "one", "one", "two" }; var result = strings.AreUnique(); Assert.That(result, Is.False); } [Test] public void HasCountOfShouldReturnFalseForIncorrectCount() { var strings = new[] { "one", "two", "three" }; var result = strings.HasCountOf(4); Assert.That(result, Is.False); } [Test] [SuppressMessage("ReSharper", "ExpressionIsAlwaysNull")] public void HasCountOfShouldReturnFalseForNullEnumerable() { object[] objects = null; var result = objects.HasCountOf(0); Assert.That(result, Is.False); } [Test] public void HasCountOfShouldReturnTrueForCorrectCount() { var strings = new[] { "one", "two", "three" }; var result = strings.HasCountOf(3); Assert.That(result, Is.True); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Prova.Testables { public class Parameters { private readonly IEnumerable<Type> _parameters; public Parameters(ConstructorInfo constructor) { _parameters = SelectAll(ParametersForThe(constructor), ByParameterType); } public IEnumerable<dynamic> BuildInstancesUsing(Dependencies dependencies) { return _parameters.Select(dependencies.InstanceForType); } private static IEnumerable<Type> SelectAll(IEnumerable<ParameterInfo> parametersInformation, Func<ParameterInfo, Type> selector) { return parametersInformation.Select(selector); } private static IEnumerable<ParameterInfo> ParametersForThe(ConstructorInfo constructor) { return constructor.GetParameters(); } private static Type ByParameterType(ParameterInfo parameter) { return parameter.ParameterType; } public Type ParameterTypeMatching(Type parameterType) { return _parameters.SingleOrDefault(x => x.IsAssignableFrom(parameterType)); } } } <file_sep>namespace Prova.Extensions { public static class ForGeneric { public static bool IsNothing<T>(this T instance) => Equals(instance, default(T)); public static bool IsNotNothing<T>(this T instance) => !instance.IsNothing(); } } <file_sep>using System; using NUnit.Framework; using Prova.Extensions; namespace Prova.Tests.ForExtensions { [TestFixture] public class ForActionTests { [Test] public void GetExceptionShouldReturnAnExceptionThatIsThrownByAction() { var expectedException = new ArithmeticException(); Action action = () => { throw expectedException; }; var exception = action.GetException(); Assert.That(exception, Is.EqualTo(expectedException)); } [Test] public void GetExceptionShouldReturnNullIfActionIsNull() { const Action action = null; var exception = action.GetException(); Assert.That(exception, Is.Null); } [Test] public void GetExceptionShouldReturnNullIfNoExceptionIsThrownByAction() { Action action = () => { }; var exception = action.GetException(); Assert.That(exception, Is.Null); } } } <file_sep>using System; using Prova.Extensions; using Prova.Testables; namespace Prova { public static class Testable { public static DefaultDependencies InstancesOf<T>() => DefaultDependencyLookup.On(typeof(T)); } public class Testable<T> { private readonly Constructor _constructor; private readonly Dependencies _dependencies; public Testable() { _constructor = new Constructor(typeof(T)); _dependencies = new Dependencies(typeof(T)); } public dynamic With(dynamic dependency) { Type parameterType = TypeOf(dependency); if (_constructor.TypeOfParameterFor(parameterType).IsNothing()) { throw _constructor.Type.HasNoMatchingParameterException(parameterType); } _dependencies.Add(dependency); return this; } public dynamic Create() => _constructor.InvokeUsing(_dependencies); private static Type TypeOf(dynamic dependency) => dependency.GetType(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Prova.Testables { public class Constructor { private readonly ConstructorInfo _constructor; private readonly Parameters _parameters; public Constructor(Type type) { Type = type; _constructor = new ConstructorFinder(type).Find(); _parameters = new Parameters(_constructor); } public Type Type { get; } public dynamic InvokeUsing(Dependencies dependencies) { var parameters = _parameters.BuildInstancesUsing(dependencies); return _constructor.Invoke(UsingArrayOf(parameters)); } private static object[] UsingArrayOf(IEnumerable<object> types) => types.ToArray(); public Type TypeOfParameterFor(Type parameterType) => _parameters.ParameterTypeMatching(parameterType); } } <file_sep>using System; using NUnit.Framework; using Prova.Tests.ForTestable.Features; using TechTalk.SpecFlow; namespace Prova.Tests.ForTestable { [Binding] public class DependencyAssertions { private readonly TestableContext _context; public DependencyAssertions(TestableContext context) { _context = context; } [Then(@"I should have a dependency that is not null")] public void ThenIShouldHaveADependencyThatIsNotNull() { Assert.That(_context.Instance.Dependency, Is.Not.Null); } [Then(@"I should have a dependency with a (.*)")] public void ThenIShouldHaveADependencyWith(Type type) { Assert.That(_context.Instance.Dependency, Is.InstanceOf(type)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Rhino.Mocks; namespace Prova.Testables { public sealed class Dependencies { private readonly ICollection<dynamic> _dependencies = new List<dynamic>(); private readonly Type _type; public Dependencies(Type type) { _type = type; } public void Add(dynamic dependency) { _dependencies.Add(dependency); } private dynamic GetRegisteredInstanceFor(Type type) { return _dependencies.SingleOrDefault(type.IsInstanceOfType); } private dynamic GetDefaultInstanceFor(Type type) { return DefaultDependencyLookup.On(_type).InstanceFor(type); } // private static dynamic GetStubbedInstanceFor(Type type) // { // var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // var allTypes = assemblies.SelectMany(a => a.GetTypes()); // var typesThatImplement = allTypes.Where(x => x.GetInterfaces().Any(i => i == type)); // var canned = typesThatImplement.FirstOrDefault(x => x.Name.StartsWith("Canned")); // if (canned.IsNotNothing()) // { // return canned.GetConstructors().FirstOrDefault().Invoke(new object[] { }); // } // return null; // } private static dynamic GetMockLibraryInstanceFor(Type type) { return MockRepository.GenerateStub(type); } public dynamic InstanceForType(Type type) { return GetRegisteredInstanceFor(type) ?? GetDefaultInstanceFor(type) ?? // GetStubbedInstanceFor(type) ?? GetMockLibraryInstanceFor(type); } } } <file_sep>using System; using NUnit.Framework; using Prova.Extensions; namespace Prova.Tests.ForExtensions { [TestFixture] public class ForGenericTests { [Test] public void IsNothingShouldReturnFalseForAValueTypeThatIsNotEmpty() { var theObject = new DateTime(1984, 1, 1); Assert.That(theObject.IsNothing(), Is.False); } [Test] public void IsNothingShouldReturnForFalseAReferenceTypeThatIsNotNull() { var theObject = new Exception(); Assert.That(theObject.IsNothing(), Is.False); } [Test] public void IsNothingShouldReturnTrueForAReferenceTypeThatIsNull() { const Exception theObject = null; Assert.That(theObject.IsNothing()); } [Test] public void IsNothingShouldReturnTrueForAValueTypeThatIsEmpty() { var theObject = new DateTime(); Assert.That(theObject.IsNothing()); } } } <file_sep>using System; using NUnit.Framework; using Prova.Extensions; using TechTalk.SpecFlow; namespace Prova.Tests.ForTestable.Features { [Binding] public class TestableSteps { private readonly TestableContext _context; public TestableSteps(TestableContext context) { _context = context; } [Given(@"I create a testable for a (.*)")] public void CreateTestableWith(Type type) { Action action = () => { Testable.InstancesOf(type).UseNoDefaults(); _context.Testable = new Testable(type); _context.Instance = _context.Testable.Create(); }; _context.Exception = action.GetException(); } [When(@"I tell the testable to use and (.*) as a dependency")] public void TellTheTestableToUseDependency(dynamic dependency) { Action action = () => { _context.ExpectedDependency = dependency; _context.Testable.With(dependency); }; _context.Exception = action.GetException(); } [When(@"I want to use the testable instance")] public void UseTheTestableObject() { _context.Instance = _context.Testable.Create(); } [Then(@"I should have an instance with that has a (.*)")] public void ShouldHaveTestableInstanceWith(Type type) { Assert.That(_context.Instance, Is.InstanceOf(type)); } [Then(@"I should have seen an exception with a (.*)")] public void ShouldHaveSeenAnExceptionWith(Type type) { Assert.That(_context.Exception, Is.InstanceOf(type)); } [Then(@"I should have an instance that uses that dependency")] public void ShouldHaveAnInstanceThatUsesThatExplicitDependency() { Assert.That(_context.Instance.Dependency, Is.EqualTo(_context.ExpectedDependency)); } } } <file_sep>namespace Prova.Tests.ForTestable.Types { public class InvalidDependency { } public interface IDependency { } public class Dependency : IDependency { } public class DifferentDependency : IDependency { } public class StubDependency : IDependency { } // public class CannedDependency : IDependency { } public interface IDefaultDependency { } } <file_sep>using System.Diagnostics.CodeAnalysis; using JetBrains.Annotations; namespace Prova.Tests.ForTestable.Types { public abstract class AbstractClass { [SuppressMessage("ReSharper", "UnusedParameter.Local")] protected AbstractClass(IDependency dependency) { } } [UsedImplicitly] public class NoExplicitConstructor { } [UsedImplicitly] public class AmbiguousConstructor { public AmbiguousConstructor(IDependency dependency1, IDependency dependency2) { } } [UsedImplicitly] public class SingleDependency { public SingleDependency(IDependency dependency) { Dependency = dependency; } [UsedImplicitly] public IDependency Dependency { get; } } [UsedImplicitly] public class MultipleConstructors { public MultipleConstructors() { } public MultipleConstructors(IDependency dependency) { } } } <file_sep>//namespace Prova.Tests.ForTestable.Types //{ // public class HasMultipleDependencies // { // public readonly IDefaultDependency ShouldBeDefault; // public readonly IExplicitDependency ShouldBeExplicit; // public readonly IImplicityDependency ShouldBeImplicit; // public readonly IMockedDependency ShouldBeMocked; // // public HasMultipleDependencies(IDefaultDependency shouldBeDefault, // IExplicitDependency shouldBeExplicit, // IImplicityDependency shouldBeStubbed, // IMockedDependency shouldBeMocked) // { // ShouldBeDefault = shouldBeDefault; // ShouldBeExplicit = shouldBeExplicit; // ShouldBeImplicit = shouldBeStubbed; // ShouldBeMocked = shouldBeMocked; // } // } // // public class DefaultDependency : IDefaultDependency // { // } // // public interface IExplicitDependency // { // } // // public class ExplicitDependency : IExplicitDependency // { // } // // public interface IImplicityDependency // { // } // // public class CannedImplicitDependency : IImplicityDependency // { // } // // public interface IMockedDependency // { // } //}
e2aef2f43565d27bbd495b8f9f903296fcfd9996
[ "C#" ]
24
C#
jcono/Prova
a01dbba9420f2c4236ef83c94095ee4bdd36fba5
2a519e0ea17a387345a81105e3d863a2d8b67cc2
refs/heads/master
<file_sep>![image](https://user-images.githubusercontent.com/30617834/67611212-82336d00-f7f4-11e9-9d87-1b1150405b73.png) # Virus Simulator This is a simple Python application that simulates the spread of a virus within a population. ## Features Beyond the given specifications for this assignment, a few things were added: * A spatial hash table to improve the performance of collision detection * A static class to generate color gradients between a given start and end color * A base Virus class which can be subclassed to create viruses compatible with this application, and which was used to add the following: * RainbowVirus, a virus which infects people with a synchronised animation through the colours of a rainbow * ZebraVirus, people infected with this virus individually alternate between black and white * ImmunisableVirus, people who are cured of this virus cannot be infected by it again * ZombieVirus, people infected by this virus will chase after people who aren't infected by any virus * SnakeVirus, a virus which forms a snake with those infected by it that chases after people who aren't infected by any virus <file_sep>""" COMPSCI 130, Semester 012019 Project Two - Virus Author: <NAME> UPI: falb418 ID: 606316306 """ import turtle import random from math import ceil, copysign from collections import OrderedDict class EfficientCollision: """Implements a spatial hash table to perform collision detection.""" def __init__(self, cell_size): """Initializes an empty spatial hash table with square cells using cell_size as their side length. """ self.cell_size = cell_size self.cells = {} def hash(self, location): """Returns the cell location of each coordinate in the given location. Args: location (list/tuple): coordinates along each dimensions """ return [int(coord / self.cell_size) for coord in location] def get_bounding_box(self, person): """Returns the axis-aligned bounding box for the given person represented by the min and max coordinates along the x and y axes. """ x, y = person.location radius = person.radius xmin, xmax = int(x - radius), int(ceil(x + radius)) ymin, ymax = int(y - radius), int(ceil(y + radius)) return xmin, ymin, xmax, ymax def add(self, person): """Adds the given person to all cells within their axis-aligned bounding box. """ xmin, ymin, xmax, ymax = self.hash(self.get_bounding_box(person)) for x in range(xmin, xmax + 1): for y in range(ymin, ymax + 1): if (x, y) in self.cells: self.cells[(x, y)].append(person) else: self.cells[(x, y)] = [person] def update(self, people): """Clears the hash table and then adds the given people to it.""" self.cells.clear() for person in people: self.add(person) class ColourGradient: """Contains functions related to generating a gradient between two or more colours. """ @staticmethod def linear_sequence(colours, n): """Returns a list representing a linear colour gradient with n interpolated colours in between each colour in the given ordered list of colours. Each colour in colours should be a list or tuple of colour channel values weighted in the same way. e.g. (1.0, 0.0, 0.0) for red Raises: ValueError: cannot create a gradient with < 2 colours." """ if len(colours) < 2: raise ValueError("cannot create a gradient with < 2 colours.") gradient = [colours[0]] for colour in colours[1:]: gradient += ColourGradient.linear(gradient[-1], colour, n) return gradient @staticmethod def linear(start, end, n): """Returns a list representing a linear colour gradient with n interpolated colours in between the given start to end colours. The start and end colours should be a list or tuple of colour channel values weighted in the same way. e.g. (1.0, 0.0, 0.0) for red """ gradient = [start] # 1. Get the change between each colour channel from end to start # 2. Divide each change by n + 1 so that we can add it to each # subsequent interpolated colour until we fall one addition short # of the end colour (which we already have) step = [(e - s) / (n + 1) for s, e in zip(start, end)] # 3. Repeatedly add our step to the start colour to get each subsequent # interpolated colour interpolated = start[:] for _ in range(n): interpolated = [i + s for i, s in zip(interpolated, step)] gradient.append(interpolated) return gradient + [end] class Virus: """Base class for all viruses used to infect people.""" def __init__(self, colour=(1, 0, 0), duration=7): """Creates a virus with the given colour and duration. Args: colour (tuple): RGB colour with each colour channel expressed in the range 0.0 and 1.0 (1.0 for most intense) duration (int): how long this virus will last in hours """ self.colour = colour self.duration = duration self.remaining_duration = duration # @classmethod # def on_world_update(cls, world): # """If defined, this classmethod will automatically be called at the # end of every world update/simulation (i.e. every hour) and is passed # the current world state. # """ # pass @classmethod def reset_class(cls): """This method is called when a virus is added to a world and is used to ensure it is correctly reset to it's initial state. """ pass def __repr__(self): """Returns a string of this virus' name, id and remaining duration. Primarily for debugging. """ return (f'<{self.__class__.__name__} ' f'@ {id(self)} dur: ' f'{self.remaining_duration}/{self.duration}>') def progress(self): """Reduces the remaining duration of this virus by 1.""" self.remaining_duration -= 1 def infect(self, person): """Infects the given person with a new instance of this virus.""" person.infect(self.__class__()) def reset_duration(self): """Sets the remaining duration of this virus to it's initial value.""" self.remaining_duration = self.duration def is_cured(self): """Returns True if this virus has run out, otherwise returns False.""" return self.remaining_duration == 0 def cure(self, person): """Removes this virus from the given person.""" person.remove_virus(self) class RainbowVirus(Virus): """This virus infects people with a synchronised animation through the colours of a rainbow. Private attributes: colours (tuple): RGB colour values (red, orange, yellow, green, blue, indigo, violet, indigo, blue, green, yellow, orange) interpolated n times (see interpolations) between each colour interpolations (int): number of interpolated colours inserted in between each colour in colours colour_count (int): length of colours (including interpolated colours) colour_index (int): current colour in colours that is being displayed """ __colours = ((1, 0, 0), (1, 127 / 255, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (75 / 255, 0, 130 / 255), (148 / 255, 0, 211 / 255)) # Smooth the transition between colours __interpolations = 20 __colours = ColourGradient.linear_sequence(__colours, __interpolations) __colours += __colours[1:-1][::-1] __colour_count = len(__colours) __colour_index = 0 def __init__(self, duration=14): """Creates a new RainbowVirus with the given duration.""" self.duration = duration self.remaining_duration = duration @classmethod def on_world_update(cls, world): """Moves onto the next colour in the rainbow, starting again from the beginning once all the colours have been cycled through. """ cls.__colour_index = (cls.__colour_index + 1) % cls.__colour_count @property def colour(self): """Returns the current colour of the rainbow! This attribute is decorated so that it can be accessed in the same way as all other viruses. """ return RainbowVirus.__colours[RainbowVirus.__colour_index] @colour.setter def colour(self, value): """Raises an AttributeError as instances of this virus cannot have their colour changed. """ raise AttributeError("can't set the colour of RainbowVirus instances") class ZebraVirus(Virus): """People infected with this virus individually alternate between black and white. Private attributes: colours (tuple): RGB colour values for black and white colour_index (int): current colour in colours that is being displayed """ __colours = [(0, 0, 0), (1, 1, 1)] __colour_index = 0 def __init__(self, duration=21): """Creates a new ZebraVirus with the given duration.""" self.duration = duration self.remaining_duration = duration self.__colour_index = ZebraVirus.__colour_index @classmethod def on_world_update(cls, world): """Moves onto the next colour, starting again from the beginning once all the colours have been cycled through. """ cls.__colour_index = not cls.__colour_index @property def colour(self): """Returns the current colour. This attribute is decorated so that it can be accessed in the same way as all other viruses. """ return ZebraVirus.__colours[self.__colour_index == ZebraVirus.__colour_index] @colour.setter def colour(self, value): """Raises an AttributeError as instances of this virus cannot have their colour changed. """ raise AttributeError("can't set the colour of ZebraVirus instances") class ImmunisableVirus(Virus): """People who are cured of this virus cannot be infected by it again. Public attributes: immune (set): people in this set cannot be infected by this virus """ immune = set() def __init__(self, immune_colour=(0, 1, 0), infected_colour=(1, 0, 0), duration=28): """Creates a new ImmunisableVirus with the given attributes. Args: immune_colour (tuple): RGB colour to set people cured of this virus to where each channel is expressed in the range 0.0 to 1.0 infected_colour (tuple): same as immune_colour, but used for people infected by this virus duration (int): how long this virus lasts in hours """ super().__init__(infected_colour, duration) self.immune_colour = immune_colour @classmethod def reset_class(cls): """Clear's this classes set of immune people.""" cls.immune.clear() def infect(self, person): """Infects the given person with a new instance of this virus.""" if person not in ImmunisableVirus.immune: person.infect(ImmunisableVirus()) def cure(self, person): """Removes this virus from the given person, makes them immune to this virus and changes their colour to indicate. """ person.remove_virus(self) person.colour = self.immune_colour ImmunisableVirus.immune.add(person) class ZombieVirus(Virus): """People infected by this virus will chase after people who aren't infected by any virus. Public attributes: idle_colour (tuple): RGB colour of people infected by this virus who aren't chasing anyone chase_colour (tuple): same as idle_colour, but for people who are chasing someone infected (dict): stores (person, virus) pairs, where person is a Person instance and the key to the corresponding ZombieVirus instance they are infected by healthy (list): stores Person instances who aren't infected by anything Private attributes: is_running (bool): determines whether people infected by this virus will be assigned new targets to chase. True if there are people in healthy, False otherwise """ idle_colour = (0.5, 0, 0) chase_colour = (1, 0, 0) infected = {} healthy = [] __is_running = True def __init__(self, duration=-1): """Creates a new ZombieVirus with the given attributes.""" self.duration = duration self.remaining_duration = duration self.target = None @classmethod def on_world_update(cls, world): """Updates the list of healthy people for this class used to help locate targets for people infected by this virus, and assigns targets for people infected by this virus. """ cls.healthy = [p for p in world.people if not p.is_infected()] # If everyone is infected then there's nothing left to target, so we: # - Clear all targets # - Give out new (random) destinations to prevent everyone from # converging on the position of the last healthy person # - Prevent the rest of this method from executing until there # are healthy people to target if not cls.healthy and cls.__is_running: for person, virus in cls.infected.items(): person.destination = person._get_random_location() virus.target = None cls.__is_running = False return # If healthy people appear while this virus has stopped then this # virus can start up again and try to infect them elif cls.healthy and not cls.__is_running: cls.__is_running = True # There's nothing left to infect elif not cls.__is_running: return # Assign targets and destinations to each infected person for person, virus in cls.infected.items(): if virus.target is None or virus.target.is_infected(): virus.target = random.choice(cls.healthy) person.destination = virus.target.location @classmethod def reset_class(cls): """Clears this class' dict of infected people and list of healthy people and set's it's running state to True. """ cls.infected.clear() cls.healthy.clear() cls.__is_running = True @property def colour(self): """Returns idle_colour if this virus isn't chasing anyone, otherwise returns chase_colour. """ if self.target is None: return ZombieVirus.idle_colour return ZombieVirus.chase_colour @colour.setter def colour(self, value): """Raises an AttributeError as instances of this virus cannot have their colour changed. """ raise AttributeError("can't set the colour of ZombieVirus instances") def infect(self, person): """Infects the given person with a new instance of this virus and adds them to ZombieVirus' list of infected people if they don't already have this virus. """ if not person.has_virus(self): instance = self.__class__() person.infect(instance) ZombieVirus.infected[person] = instance def cure(self, person): """Removes this virus from the given person and removes them from ZombieVirus' list of infected people. """ person.remove_virus(self) del ZombieVirus.infected[person] class SnakeVirus(Virus): """This virus forms a snake with those infected by it that chases after people who aren't infected by any virus. In addition, the snake's head only moves along one axis at a time. Public attributes: head_colour (tuple): RGB colour of the person at the head of the snake formed by this virus body_colour (tuple): same as head_colour, but for everyone that isn't at the head of the snake formed by this virus infected (odict): stores (person, virus) pairs, where person is a Person instance and the key to the corresponding SnakeVirus instance they are infected by target (Person): Person instance which will be chased after by the head of the snake formed by this virus until that person is infected. If this is None, the snake will find another random target if possible, otherwise it will roam around randomly """ head_colour = (1, 0, 0) body_colour = (0, 0, 1) infected = OrderedDict() target = None def __init__(self): """Creates a new SnakeVirus.""" self.duration = -1 self.remaining_duration = -1 @classmethod def on_world_update(cls, world): """Updates the list of infected people used by this class to tell it's people where to go and issues orders to everyone infected by this virus. """ cls.healthy = [p for p in world.people if not p.is_infected()] people = list(cls.infected.keys()) for i, person in enumerate(people): if i != 0: # Follow the person before them person.destination = people[i - 1].location continue # Assign a new target if needed, otherwise, if there are no more # healthy people to target, just wander around randomly if cls.healthy: if (cls.target is None or cls.target.is_infected()): cls.target = random.choice(cls.healthy) vector = cls.get_destination_vector(person.location, cls.target.location) else: vector = cls.get_destination_vector(person.location, person.destination) vector = list(vector) # Keep only the component which has the greatest magnitude if abs(vector[0]) > abs(vector[1]): vector[1] = 0 else: vector[0] = 0 # Construct the vector for the next snake head destination destination = [] for pos, component in zip(person.location, vector): destination.append(pos + component) person.destination = tuple(destination) @classmethod def reset_class(cls): """Clears this class' target and list of infected people.""" cls.infected.clear() cls.target = None @staticmethod def get_destination_vector(origin, destination): """Returns a tuple representing a vector from the given origin to the given destination. """ vector = [] for v1, v2 in zip(origin, destination): if (v1 * v2) > 0: # If v1 and v2 have the same sign new_val = abs(abs(v1) - abs(v2)) else: new_val = abs(v1) + abs(v2) if v1 > v2: new_val *= -1 vector.append(new_val) return tuple(vector) @property def colour(self): """Returns head_colour if this virus is at the 'head' of the snake, otherwise returns body_colour. """ # Get the first virus in SnakeVirus.infected for first in SnakeVirus.infected.values(): if self is first: return self.head_colour return self.body_colour @colour.setter def colour(self, value): """Raises an AttributeError as instances of this virus cannot have their colour changed. """ raise AttributeError("can't set the colour of SnakeVirus instances") def infect(self, person): """Infects the given person with a new instance of this virus and adds them to SnakeVirus' list of infected people if they don't already have this virus. """ if not person.has_virus(self): instance = self.__class__() person.infect(instance) SnakeVirus.infected[person] = instance def cure(self, person): """Removes this virus from the given person and removes them from SnakeVirus' list of infected people. """ person.remove_virus(self) del SnakeVirus.infected[person] class Person: """This class represents a person which randomly roams around and can be infected by viruses. A person can be infected by multiple viruses at once, but they cannot be infected by more than one instance of the same type of virus at the same time. """ def __init__(self, world_size, radius=7, colour=(0, 0, 0)): """Creates a new person at a random location who will randomly roam within the given world size. Args: world_size (tuple): width and height of the world which this person can roam around centered at (0, 0) on the default turtlescreen radius (int): radius of this person in pixels colour (tuple): an RGB colour where each channel is a float between 0 and 1.0 Raises: ValueError: world size is smaller than this person """ if any(dim < (radius * 2) for dim in world_size): raise ValueError("world size is smaller than this person") self.world_size = world_size self.radius = radius self.location = self._get_random_location() self.destination = self._get_random_location() self.viruses = list() self.colour = colour def _get_random_location(self): """Returns a random (x, y) position within this person's world size. The returned position will be no closer than 1 radius to the edge of this person's world. """ width, height = self.world_size # # Generate a random (x, y) coordinate within the world's borders x = random.uniform(self.radius, width - self.radius) y = random.uniform(self.radius, height - self.radius) x -= width // 2 y -= height // 2 return x, y def get_colour(self): """Returns the average of this person's viruses colours if they are infected, otherwise returns their default colour. """ colour = self.colour # Calculate the average colour of this person's virus(es) if self.is_infected(): n = len(self.viruses) colours = [virus.colour for virus in self.viruses] colour = [sum(channel) / n for channel in zip(*colours)] return tuple(colour) def draw(self): """Draws this person as a coloured dot at their current location. The colour will be the colour from this colour attribute if they aren't infected, otherwise it will be average colour of the virus(es) they are infected by. """ turtle.penup() # Ensure nothing is drawn while moving turtle.setpos(self.location) turtle.dot(self.radius * 2, self.get_colour()) def collides(self, other): """Returns true if the distance between this person and the other person is less than this + the other person's radius, otherwise returns False. """ if other is self: return False return distance_2d(self.location, other.location) <= \ (self.radius + other.radius) def collision_list(self, people): """Returns a list of people from the given list who are in contact with this person. """ return [person for person in people if self.collides(person)] def infect(self, virus): """Infects this person with the given virus if they aren't already infected by it, otherwise refreshes the virus' duration on this person. """ try: self.get_virus(virus).reset_duration() except: self.viruses.append(virus) def reached_destination(self): """Returns True if this person's location is within 1 radius of destination, otherwise returns False. """ return distance_2d(self.location, self.destination) <= self.radius def progress_illness(self): """Progress this person's viruses, curing them if it's run out.""" for virus in self.viruses.copy(): virus.progress() if virus.is_cured(): self.cure(virus) def update(self): """Updates this person each hour. - Moves this person towards their destination - If the destination is reached then a new destination is set - Progresses any illness """ self.move() if self.reached_destination(): self.destination = self._get_random_location() self.progress_illness() def move(self): """Moves this person radius / 2 towards their destination. If their destination is closer than radius / 2, they will move directly to their destination instead. """ turtle.penup() # Ensure nothing is drawn while moving turtle.setpos(self.location) distance = distance_2d(self.location, self.destination) # Clamp distance below radius / 2 (inclusive) half_radius = self.radius / 2 if distance > half_radius: distance = half_radius # Move the person towards their destination turtle.setheading(turtle.towards(self.destination)) turtle.forward(distance) self.location = turtle.pos() def cure(self, virus=None): """Cures the instance of the given virus' class on this person, otherwise, if a virus isn't given, removes all viruses on this person. """ if virus is None: for v in self.viruses.copy(): v.cure(self) else: virus.cure(self) def remove_virus(self, virus): """Removes the given virus from this person. Raises: ValueError: Person.remove_virus(x): x not in Person.viruses """ try: self.viruses.remove(virus) except: raise ValueError('Person.remove_virus(x): x not in Person.viruses') def is_infected(self): """Returns True if this person is infected, else False.""" return bool(len(self.viruses)) def get_virus(self, virus): """Returns the instance of the given virus' class on this person (if any), otherwise returns None. """ for v in self.viruses: if isinstance(v, virus.__class__): return v return None # For clarity def has_virus(self, virus): """Returns True if this person has the given virus, else False.""" return bool(self.get_virus(virus)) class World: """This class represents a simulated world containing people who can be infected by viruses. """ def __init__(self, width, height, n, viruses=[ RainbowVirus, ZebraVirus, ImmunisableVirus, ZombieVirus, SnakeVirus ]): """Creates a new world centered on (0, 0) containing n people which simulates the spread of the given virus(es) through this world. Args: width (int): horizontal length of the world in pixels height (int): vertical length of the world in pixels n (int): number of people to add to this world viruses (iterable): virus classes that will be used to infect people in this world Raises: ValueError: width and height must be even """ if width % 2 != 0 or height % 2 != 0: raise ValueError("width and height must be even") self.size = (width, height) self.hours = 0 self.people = [] self.viruses = viruses self.collision_table = EfficientCollision(28) for _ in range(n): self.add_person() # Reset each virus and add the on_world_update method for each virus if # they have one self.on_update_methods = [] for cls in self.viruses: cls.reset_class() if hasattr(cls, "on_world_update"): self.on_update_methods.append(cls.on_world_update) def add_person(self): """Adds a new person to this world.""" self.people.append(Person(self.size)) def infect_person(self): """Infects a random person in this world with a random virus. It is possible for the chosen person to already be infected with a virus. """ # If this world has no viruses there's nothing to infect people with if not len(self.viruses): return rand_person = random.choice(self.people) rand_virus = random.choice(self.viruses)() rand_virus.infect(rand_person) def cure_all(self): """Cures all people in this world.""" for person in self.people: person.cure() def update_infections_slow(self): """Infect anyone in contact with an infected person.""" # Stores (key, value) pairs of the form (person, viruses), where: # person = a person object who has collided with an infected person # viruses = a set of the virus(es) to infect this person with to_infect = {} # Loop through each infected person for infected in (p for p in self.people if p.is_infected()): viruses = [v.__class__ for v in infected.viruses] # Add anyone who collided with this infected person to our dict of # people to infect along with the viruses to infect them with for person in infected.collision_list(self.people): if person in to_infect: to_infect[person].update(viruses) else: to_infect[person] = set(viruses) # Infect anyone who collided with an infected person with the virus(es) # of the people they collided with for person, viruses in to_infect.items(): for virus in viruses: virus().infect(person) def update_infections_fast(self): """Infect anyone in contact with an infected person. Uses a spatial hash table to speed up collision detection. """ self.collision_table.update(self.people) # Stores (key, value) pairs of the form (person, viruses), where: # person = a person object who has collided with an infected person # viruses = a set of the virus(es) to infect this person with to_infect = {} # Loop through each infected person for infected in (p for p in self.people if p.is_infected()): viruses = [v.__class__ for v in infected.viruses] cell = tuple(self.collision_table.hash(infected.location)) nearby_people = self.collision_table.cells[cell] # Add anyone who collided with this infected person to our dict of # people to infect along with the viruses to infect them with for person in infected.collision_list(nearby_people): if person in to_infect: to_infect[person].update(viruses) else: to_infect[person] = set(viruses) # Infect anyone who collided with an infected person with the virus(es) # of the people they collided with for person, viruses in to_infect.items(): for virus in viruses: virus().infect(person) def simulate(self): """Simulates one hour in this world. - Updates all people - Updates all infection transmissions - Calls any update method(s) from this world's virus(es) """ self.hours += 1 for person in self.people: person.update() self.update_infections_fast() for method in self.on_update_methods: method(self) def draw(self): """Draws this world on the default turtle screen. - Clears the current screen - Draws all the people in this world - Draws the box that frames this world - Writes the number of hours and number of people infected at the top of the frame """ # Top-left corner of the world width, height = self.size x = 0 - width // 2 y = height // 2 turtle.clear() for person in self.people: person.draw() draw_rect(x, y, width, height) draw_text(x, y, f'Hours: {self.hours}') draw_text(0, y, f'Infected: {self.count_infected()}', align='center') def count_infected(self): """Returns the number of infected people in this world.""" return sum(True for person in self.people if person.is_infected()) def draw_text(x, y, text, colour='black', *args, **kwargs): """Wrapper for turtle.write which takes an (x, y) position to write the text at and an optional text colour. """ turtle.penup() # Ensure nothing is drawn while moving turtle.color(colour) turtle.setpos(x, y) turtle.write(text, *args, **kwargs) def draw_rect(x, y, width, height, colour='black'): """Draws a rectangle starting from the top-left corner.""" # Draw the top-left corner of the rectangle draw_line(x, y, width, orientation="horizontal", colour='black') draw_line(x, y, height, colour='black') # Draw the bottom-right corner of the rectangle x += width y -= height draw_line(x, y, width, orientation="horizontal", reverse=True, colour='black') draw_line(x, y, height, reverse=True, colour='black') def draw_line(x, y, length, orientation="vertical", reverse=False, colour='black'): """Draws a line starting at the given coordinates. Args: x (int): horizontal coordinate on the default turtle screen y (int): vertical coordinate on the default turtle screen length (int): length of the line in pixels orientation (str): 'vertical' to draw a vertical line from the top-down starting at the given x, y coordinates, 'horizontal' to draw the line left-to-right reverse (bool): True to reverse the draw direction, e.g. draw bottom-top instead of top-down colour: colour of the line, can be any valid colour accepted by the turtle module """ if orientation == "vertical": turtle.setheading(180) # South elif orientation == "horizontal": turtle.setheading(90) # East if reverse: length *= -1 turtle.color(colour) turtle.penup() # Ensure nothing is drawn while moving turtle.setpos(x, y) turtle.pendown() turtle.forward(length) turtle.penup() def distance_2d(a, b): """Returns the distance between two 2D points of the form (x, y).""" # Standard distance formula for two points in the form (x, y) return ((b[0] - a[0])**2 + (b[1] - a[1])**2)**0.5 # --------------------------------------------------------- # Should not need to alter any of the code below this line # --------------------------------------------------------- class GraphicalWorld: """Handles the user interface for the simulation space - starts and stops the simulation 'z' - resets the application to the initial state 'x' - infects a random person 'c' - cures all the people """ def __init__(self): self.WIDTH = 800 self.HEIGHT = 600 self.TITLE = 'COMPSCI 130 Project One' self.MARGIN = 50 # gap around each side self.PEOPLE = 200 # number of people in the simulation self.framework = AnimationFramework(self.WIDTH, self.HEIGHT, self.TITLE) self.framework.add_key_action(self.setup, 'z') self.framework.add_key_action(self.infect, 'x') self.framework.add_key_action(self.cure, 'c') self.framework.add_key_action(self.toggle_simulation, " ") self.framework.add_tick_action(self.next_turn) self.world = None def setup(self): """Reset the simulation to the initial state.""" print('resetting the world') self.framework.stop_simulation() self.world = World(self.WIDTH - self.MARGIN * 2, self.HEIGHT - self.MARGIN * 2, self.PEOPLE) self.world.draw() def infect(self): """Infect a person and redraw the world if the simulation isn't running. """ print('infecting a person') self.world.infect_person() if not self.framework.simulation_is_running(): self.world.draw() def cure(self): """Remove infections from all the people and redraw the world if the simulation isn't running. """ print('cured all people') self.world.cure_all() if not self.framework.simulation_is_running(): self.world.draw() def toggle_simulation(self): """Starts and stops the simulation.""" if self.framework.simulation_is_running(): self.framework.stop_simulation() else: self.framework.start_simulation() def next_turn(self): """Perform the tasks needed for the next animation cycle.""" self.world.simulate() self.world.draw() # self.framework.stop_simulation() # To advance one hour at a time class AnimationFramework: """This framework is used to provide support for animation of interactive applications using the turtle library. There is no need to edit any of the code in this framework. """ def __init__(self, width, height, title): self.width = width self.height = height self.title = title self.simulation_running = False self.tick = None # function to call for each animation cycle self.delay = 1 # smallest delay is 1 millisecond turtle.title(title) # title for the window turtle.setup(width, height) # set window display turtle.hideturtle() # prevent turtle appearance turtle.tracer(0, 0) # prevent turtle animation turtle.listen() # set window focus to the turtle window turtle.mode('logo') # set 0 direction as straight up turtle.penup() # don't draw anything turtle.setundobuffer(None) self.__animation_loop() def start_simulation(self): self.simulation_running = True def stop_simulation(self): self.simulation_running = False def simulation_is_running(self): return self.simulation_running def add_key_action(self, func, key): turtle.onkeypress(func, key) def add_tick_action(self, func): self.tick = func def __animation_loop(self): try: if self.simulation_running: self.tick() turtle.ontimer(self.__animation_loop, self.delay) except turtle.Terminator: pass gw = GraphicalWorld() gw.setup() turtle.mainloop() # Need this at the end to ensure events handled properly
d07023afabe6c2108334edfd2b960b57506a7ab8
[ "Markdown", "Python" ]
2
Markdown
NeedsSoySauce/Virus-Simulator
59d59bbd0d422707be33667e4b49b2d726a1f962
a2782daca00f15c0a6a9c6d915b7decfeeb152a1
refs/heads/master
<repo_name>jhorikawa/HoudiniHowtos<file_sep>/Live-0118 Lava Loop Animation for Mobile with VAT and Unity/LavaAnimationVAT/Assets/MeshIndexFormat.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MeshIndexFormat : MonoBehaviour { // Start is called before the first frame update void Start() { var mesh = GetComponent<MeshFilter>().mesh; mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; } // Update is called once per frame void Update() { } } <file_sep>/Live-0113 Optimal Transport (3D Mesh Morphing)/README.md # References [Möbius Registration (V2.52)](https://github.com/mkazhdan/MoebiusRegistration) for spherical parameterization. <file_sep>/README.md # HoudiniHowtos Houdini tutorial files repository used in Youtube videos. ### Facebook page: https://www.facebook.com/ParametricProceduralHoudini/ ### Youtube Channel: https://www.youtube.com/channel/UC5NStd0QmACnWs9DzqJ3vHg ### Patreon: https://www.patreon.com/junichirohorikawa <file_sep>/Snippet-0015 Automate Saving VEX Functions for Reusage/scripts/functions.h void noiseremove(int ptnum; float sc, seed, th){ vector pos = point(0, "P", ptnum); float noiseval = noise(pos * sc + seed); if(noiseval < th){ removepoint(0, ptnum); } }
a6bee8c09caeeade50743a1d95c121336d01f2f4
[ "Markdown", "C#", "C" ]
4
C#
jhorikawa/HoudiniHowtos
ce178576514ad79e5cbcd3c383fc7f579148ce9c
e2bb2fcfea314588f4f960a5077a5f94854f1b94
refs/heads/main
<repo_name>AlmightyLks-SCP/GamemodeManager<file_sep>/GamemodeManager/GMM.cs using Synapse.Api.Plugin; using CustomGamemode; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Diagnostics; using GamemodeManager.EventHandler; namespace GamemodeManager { [PluginInformation( Author = "AlmightyLks", Description = "A Gamemode Manager for Synapse", Name = "GamemodeManager", SynapseMajor = 2, SynapseMinor = 1, SynapsePatch = 0, Version = "1.0.1" )] public class GMM : AbstractPlugin { [Config(section = "GamemodeManager")] public static PluginConfig Config; internal static GamemodeLoader GamemodeLoader { get; private set; } private GMMEventHandler _gmmEventHandler; public override void Load() { var watch = new Stopwatch(); SynapseController.Server.Logger.Info($"<{Information.Name}> loading..."); string gamemodePath = string.Empty; string gamemodeConfigPath = string.Empty; if (Config.CustomGamemodePath == string.Empty) gamemodePath = Path.Combine(PluginDirectory, "Gamemodes"); else gamemodePath = Config.CustomGamemodePath; GamemodeLoader = new GamemodeLoader(gamemodePath); _gmmEventHandler = new GMMEventHandler(GamemodeLoader); watch.Start(); GamemodeLoader.LoadGamemodes(); watch.Stop(); SynapseController.Server.Logger.Info($"<{Information.Name}> loaded {GamemodeLoader.LoadedGamemodes.Count} Gamemodes within {watch.Elapsed.TotalMilliseconds} ms!"); Synapse.Api.Events.EventHandler.Get.Round.WaitingForPlayersEvent += _gmmEventHandler.Round_WaitingForPlayersEvent; Synapse.Api.Events.EventHandler.Get.Round.RoundEndEvent += _gmmEventHandler.Round_RoundEndEvent; Synapse.Api.Events.EventHandler.Get.Round.RoundRestartEvent += _gmmEventHandler.Round_RoundRestartEvent; } } } <file_sep>/README.md # OUTDATED This Plugin was intended for Synapse 2, and is not made, nor compatible with Synapse3. --- # GamemodeManager --- ## Installation: Download the `CustomGamemode.dll` and place it within your `Synapse\dependencies` folder. Place the `GamemodeManager.dll` in your usual plugins folder. Either your configured path or the default Gamemode folder will provide a place for your Gamemodes to be stored and loaded. Done! --- ## Config ```yaml [GamemodeManager] { # Custom Gamemode Path, leave empty for default customGamemodePath: '' # End all Gamemodes on round end autoGamemodeEnd: true } ``` --- ## Commands (Remote Admin) Prefix: `gmm` / `gamemode` / `gamemodemanager` - list List all loaded gamemodes. - reload Reload all Gamemodes from your Gamemode-folder. - start [GamemodeName] Start the Gamemode with the specified name (not case-sensitive). - end [GamemodeName] End a Gamemode. - nextround [GamemodeName] Queue Gamemodes to start next round. - clear Clear the above-mentioned queue. --- ## For Developers: In order to create gamemodes, please download and reference the `CustomGamemode.dll` within your gamemode's project. Do not refer to Synapse's way of plugin-creation, because GamemodeManager has its own way of determining and loading a gamemode. However, you may refer to Synapse's other functionalities. This includes subscribing events, working with Synapse's types, etc... <br><br> Your Gamemode's class needs to implement the `IGamemode` interface, from the referenced `CustomGamemode.dll`. That's it. Quick example with the well-known Gamemode [Peanut Infection](https://github.com/AlmightyLks/PeanutInfection). **Important Note:** First off: Be sure to fill out the implemented properties from `IGamemode` properly, at the very least the `Name`, which refers to the Gamemode's name. GamemodeManager will refer to the Gamemode via that name. Also, please don't use Spaces in that name, use any common type of naming-convention such as snake_case, PascalCase or camelCase. Secondly, please be sure to clean up your event on End. GamemodeManager is not responsible for each gamemode's junk and can't and thus won't do it for you. Also worth mentioning, (yet) gamemodes do not have access to their own configs. This is planned to be realized in the future. <file_sep>/CustomGamemode/IGamemode.cs namespace CustomGamemode { public interface IGamemode { void Start(); void End(); string Name { get; set; } string Author { get; set; } string GitHubRepo { get; set; } string Version { get; set; } } } <file_sep>/GamemodeManager/EventHandler/GMMEventHandler.cs using CustomGamemode; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GamemodeManager.EventHandler { internal class GMMEventHandler { private GamemodeLoader gamemodeLoader; public GMMEventHandler(GamemodeLoader gamemodeLoader) { this.gamemodeLoader = gamemodeLoader; } public void Round_RoundRestartEvent() { if (GMM.Config.AutoGamemodeEnd) foreach (var gamemode in gamemodeLoader.LoadedGamemodes) ((IGamemode)gamemode).End(); } public void Round_RoundEndEvent() { if (GMM.Config.AutoGamemodeEnd) foreach (var gamemode in gamemodeLoader.LoadedGamemodes) ((IGamemode)gamemode).End(); } public void Round_WaitingForPlayersEvent() { foreach (var modeName in gamemodeLoader.NextRoundGamemodes) { var gamemode = gamemodeLoader.LoadedGamemodes.FirstOrDefault((_) => ((IGamemode)_).Name.ToLower() == modeName.ToLower()); if (gamemode == default(IGamemode)) continue; ((IGamemode)gamemode).Start(); } } } } <file_sep>/GamemodeManager/Commands/ToggleGamemode.cs using CustomGamemode; using Synapse.Command; using System; using System.Diagnostics; using System.Linq; namespace GamemodeManager.Commands { [CommandInformation( Name = "gmm", Aliases = new[] { "gamemode", "gamemodemanager" }, Description = "Toggle gamemodes", Permission = "GamemodeManager.Manage", Platforms = new Platform[] { Platform.RemoteAdmin }, Usage = "\"gmm reload\" / \"gmm list\" / \"gmm start [GamemodeName]\" / \"gmm end [GamemodeName]\" / \"gmm nextround [GamemodeName]\" / \"gmm clear\"" )] public class ToggleGamemode : ISynapseCommand { public CommandResult Execute(CommandContext context) { object gamemode; var result = new CommandResult(); var args = context.Arguments.ToArray(); if (args.Length < 1) { result.State = CommandResultState.Error; result.Message = "Invalid input."; return result; } try { switch (args[0]) { case "list": { if (GMM.GamemodeLoader.LoadedGamemodes.Count != 0) { result.State = CommandResultState.Ok; result.Message = String.Join(", ", GMM.GamemodeLoader.LoadedGamemodes.Select((_) => ((IGamemode)_).Name)); } else { result.State = CommandResultState.Ok; result.Message = "No gamemodes loaded."; } break; } case "reload": { Stopwatch watch = new Stopwatch(); GMM.GamemodeLoader.LoadedGamemodes.Clear(); watch.Start(); GMM.GamemodeLoader.LoadGamemodes(); watch.Stop(); result.State = CommandResultState.Ok; result.Message = $"<GamemodeManager> loaded {GMM.GamemodeLoader.LoadedGamemodes.Count} Gamemodes within {watch.Elapsed.TotalMilliseconds} ms!"; break; } case "clear": { GMM.GamemodeLoader.NextRoundGamemodes.Clear(); result.State = CommandResultState.Ok; result.Message = $"Queue cleared."; break; } case "start" when args.Length == 2: { gamemode = GMM.GamemodeLoader.LoadedGamemodes.FirstOrDefault((_) => ((IGamemode)_).Name.ToLower() == args[1].ToLower()); if (gamemode == default(IGamemode)) { result.State = CommandResultState.Error; result.Message = $"{args[1]} - Gamemode not found"; return result; } ((IGamemode)gamemode).Start(); result.State = CommandResultState.Ok; result.Message = $"{((IGamemode)gamemode).Name} started"; break; } case "nextround" when args.Length == 2: { var gamemodeExists = GMM.GamemodeLoader.LoadedGamemodes.Any((_) => ((IGamemode)_).Name.ToLower() == args[1].ToLower()); if (!gamemodeExists) { result.State = CommandResultState.Error; result.Message = $"{args[1]} - Gamemode not found"; } else { GMM.GamemodeLoader.NextRoundGamemodes.Add(args[1]); result.State = CommandResultState.Ok; result.Message = $"{args[1]} queued for next round"; } break; } case "end" when args.Length == 2: { gamemode = GMM.GamemodeLoader.LoadedGamemodes.FirstOrDefault((_) => ((IGamemode)_).Name.ToLower() == args[1].ToLower()); if (gamemode == default(IGamemode)) { result.State = CommandResultState.Error; result.Message = $"{args[1]} - Gamemode not found"; return result; } ((IGamemode)gamemode).End(); result.State = CommandResultState.Ok; result.Message = $"{((IGamemode)gamemode).Name} ended"; break; } default: result.State = CommandResultState.Error; result.Message = "Invalid input."; break; } } catch (Exception e) { result.State = CommandResultState.Error; if (args.Length < 2) { result.Message = $"Error {args[0]}ing gamemode {args[1]}."; SynapseController.Server.Logger.Info($"Error {args[0]}ing gamemode {args[1]}."); SynapseController.Server.Logger.Info(e.StackTrace); } else { result.Message = $"Error {args[0]}ing."; SynapseController.Server.Logger.Info($"Error {args[0]}ing."); SynapseController.Server.Logger.Info(e.StackTrace); } } return result; } } } <file_sep>/GamemodeManager/GamemodeLoader.cs using CustomGamemode; using GamemodeManager.Helper; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace GamemodeManager { internal class GamemodeLoader { internal List<object> LoadedGamemodes { get; set; } internal List<string> NextRoundGamemodes { get; set; } private string _gamemodeDirectory; public GamemodeLoader(string gamemodeDirectory) { _gamemodeDirectory = gamemodeDirectory; LoadedGamemodes = new List<object>(); NextRoundGamemodes = new List<string>(); } //[Credits] Assembly-Loading inspired by Synapse. public void LoadGamemodes() { if (!Directory.Exists(_gamemodeDirectory)) Directory.CreateDirectory(_gamemodeDirectory); var gamemodePaths = Directory.GetFiles(_gamemodeDirectory, "*.dll").ToList(); var gamemodeDict = new Dictionary<Type, List<Type>>(); foreach (var gamemodePath in gamemodePaths) { try { var gamemodeAssembly = Assembly.Load(File.ReadAllBytes(gamemodePath)); foreach (var type in gamemodeAssembly.GetTypes()) { if (!typeof(IGamemode).IsAssignableFrom(type)) continue; var allTypes = gamemodeAssembly.GetTypes().ToList(); allTypes.Remove(type); gamemodeDict.Add(type, allTypes); break; } } catch (Exception e) { SynapseController.Server.Logger.Info($"{Path.GetFileName(gamemodePath)} failed to load.\n{e.StackTrace}"); } } foreach (var infoTypePair in gamemodeDict) { try { SynapseController.Server.Logger.Info($"{infoTypePair.Key.Name} will now be activated!"); object gamemode = Activator.CreateInstance(infoTypePair.Key); LoadedGamemodes.Add(gamemode); } catch (Exception e) { SynapseController.Server.Logger.Error($"Instantiating {infoTypePair.Key.Assembly.GetName().Name} failed!\n{e}"); } } foreach (var gamemode in LoadedGamemodes) SynapseController.Server.Logger.Info(((IGamemode)gamemode).ToInfoString()); } } } <file_sep>/GamemodeManager/Helper/Helper.cs using CustomGamemode; namespace GamemodeManager.Helper { public static class Helper { public static string ToInfoString(this IGamemode gamemode) => $"Name: {gamemode.Name}, Author: {gamemode.Author}, Version: {gamemode.Version}, GitHub: {gamemode.GitHubRepo}"; } } <file_sep>/GamemodeManager/Config/PluginConfig.cs using Synapse.Config; using System.ComponentModel; namespace GamemodeManager { public class PluginConfig : AbstractConfigSection { [Description("Custom Gamemode Path, leave empty for default")] public string CustomGamemodePath { get; set; } = string.Empty; [Description("End all Gamemodes on round end")] public bool AutoGamemodeEnd { get; set; } = true; } }
a60ce11411639fdcd205a5eaf2faef747f08f9f6
[ "Markdown", "C#" ]
8
C#
AlmightyLks-SCP/GamemodeManager
a404c186d7f97ec0191a9da992af744f2dd753be
c88d5d54b1804dbc8e7e0c2363c6f6e11f9bc9b3
refs/heads/master
<file_sep>// guess pegs: 6, in different colors (these are possible options) // key pegs: black/white to indicate yes/no // code: 4 of 6 code peg colors, in specific order // easy: no duplicate colors // hard: duplicates allowed (special feedback rules) // number of turns: 12, 10, or 8 // code is set (random generation) // prompt user for guess // compare guess against code set // provide feedback on guess // for every correct color and correct location, use a black peg // for every correct color and incorrect location, use a white peg // game ends when the code is guessed or number of turns maxed out //game mode buttons var gameModeEasy = document.querySelector("#easy"); var gameModeNormal = document.querySelector("#normal"); var gameModeHard = document.querySelector("#hard"); // game mode colors-banners var easyColors = document.getElementById("easy-colors"); var normalColors = document.getElementById("normal-colors"); var hardColors = document.getElementById("hard-colors"); //instruction number var easyNumber = document.getElementById("easy-number"); var normalNumber = document.getElementById("normal-number"); var hardNumber = document.getElementById("hard-number"); // display solution code var codeDisplay = document.querySelector("#code"); var codeContainerDisplay = document.querySelector("#code-container"); // display color guesses var guessesDisplay = document.querySelector("#guesses"); var hintsDisplay = document.querySelector(".hints-display"); // archive displays var guessesArchiveDisplay = document.querySelector("#guessesArchive"); var hintsArchiveDisplay = document.querySelector("#hintsArchive"); // color bank var guessBank = document.querySelector("#color-guess-bank"); var bankRed = document.querySelector("#bank-red"); var bankOrange = document.querySelector("#bank-orange"); var bankYellow = document.querySelector("#bank-yellow"); var bankGreen = document.querySelector("#bank-green"); var bankBlue = document.querySelector("#bank-blue"); var bankPurple = document.querySelector("#bank-purple"); var bankMagenta = document.querySelector("#bank-magenta"); var bankLime = document.querySelector("#bank-lime"); var bankCyan = document.querySelector("#bank-cyan"); var bankSienna = document.querySelector("#bank-sienna"); var checkGuessButton = document.getElementsByName("check-guess")[0]; var resetTurnButton = document.getElementsByName("reset-turn")[0]; var resetGameButton = document.getElementsByName("reset-game")[0]; // misc displays var turnsLeftDisplay = document.querySelector("#turns-left"); var statusDisplay = document.querySelector("#status-display"); var gameMode = "easy"; var gameStats = { shared: { code: [], guesses: [], guessesArchive: [], guessesArchiveString: "", currentGuess: "", hints: [], hintsArchive: [], hintsArchiveString: "", isInCode: 0, isExactMatch: 0, codeGuessNumber: 0, }, easy: { colors: ["R", "O", "Y", "G", "B", "P"], codeNumber: 4, turnNumber: 10 }, normal: { colors: ["M", "R", "O", "Y", "G", "L", "B", "P"], codeNumber: 6, turnNumber: 8 }, hard: { colors: ["M", "R", "O", "Y", "L", "G", "C", "B", "P", "S"], codeNumber: 8, turnNumber: 8 } } gameModeEasy.addEventListener("click", function() { // gameMode gameModeEasy.classList.add("engaged"); gameModeNormal.classList.remove("engaged"); gameModeHard.classList.remove("engaged"); // color banners easyColors.classList.remove("no-display"); normalColors.classList.add("no-display"); hardColors.classList.add("no-display"); // instructions easyNumber.classList.remove("no-display"); normalNumber.classList.add("no-display"); hardNumber.classList.add("no-display"); // color bank bankMagenta.classList.add("no-display"); bankLime.classList.add("no-display"); bankCyan.classList.add("no-display"); bankSienna.classList.add("no-display"); gameMode = "easy"; resetGame(); displayTurns(); gameSetUp(); }); gameModeNormal.addEventListener("click", function() { // gameMode gameModeNormal.classList.add("engaged"); gameModeEasy.classList.remove("engaged"); gameModeHard.classList.remove("engaged"); // color banners easyColors.classList.add("no-display"); normalColors.classList.remove("no-display"); hardColors.classList.add("no-display"); // instructions easyNumber.classList.add("no-display"); normalNumber.classList.remove("no-display"); hardNumber.classList.add("no-display"); // color bank bankMagenta.classList.remove("no-display"); bankLime.classList.remove("no-display"); bankCyan.classList.add("no-display"); bankSienna.classList.add("no-display"); gameMode = "normal"; resetGame(); displayTurns(); gameSetUp(); }); gameModeHard.addEventListener("click", function() { // gameMode gameModeHard.classList.add("engaged"); gameModeNormal.classList.remove("engaged"); gameModeEasy.classList.remove("engaged"); // color banners easyColors.classList.add("no-display"); normalColors.classList.add("no-display"); hardColors.classList.remove("no-display"); // instructions easyNumber.classList.add("no-display"); normalNumber.classList.add("no-display"); hardNumber.classList.remove("no-display"); // color bank bankMagenta.classList.remove("no-display"); bankLime.classList.remove("no-display"); bankCyan.classList.remove("no-display"); bankSienna.classList.remove("no-display"); gameMode = "hard"; resetGame(); displayTurns(); gameSetUp(); }); // isGameOver() runs inside checkGuess() // otherwise "you're out of turns" displays even if you won on the last turn checkGuessButton.addEventListener("click", function(event) { // console.log("check guess btn clicked"); if(guesses.length != codeNumber) { statusDisplay.classList.remove("no-display"); statusDisplay.textContent = "You're missing at least one guess." } else { statusDisplay.classList.add("no-display"); checkGuess(); displayOldGuesses(); storeOldGuesses(); displayCurrentHints(); storeOldHints(); displayOldHints() turnNumber--; displayTurns(); } }); resetTurnButton.addEventListener("click", function(event) { // console.log("reset btn clicked"); resetTurn(); }); resetGameButton.addEventListener("click", function(event) { // console.log("play again btn clicked"); resetGame(); gameSetUp(); }) bankRed.addEventListener("click", function(event) { // console.log("bankRed clicked"); checkButtonFunction.apply(this); }); bankOrange.addEventListener("click", function(event) { // console.log("bankOrange clicked"); checkButtonFunction.apply(this); }); bankYellow.addEventListener("click", function(event) { // console.log("bankYellow clicked"); checkButtonFunction.apply(this); }); bankGreen.addEventListener("click", function(event) { // console.log("bankGreen clicked"); checkButtonFunction.apply(this); }); bankBlue.addEventListener("click", function(event) { // console.log("bankBlue clicked"); checkButtonFunction.apply(this); }); bankPurple.addEventListener("click", function a(event) { // console.log("bankPurple clicked"); checkButtonFunction.apply(this); }); bankMagenta.addEventListener("click", function(event) { // console.log("bankMagenta clicked"); checkButtonFunction.apply(this); }); bankLime.addEventListener("click", function(event) { // console.log("bankLime clicked"); checkButtonFunction.apply(this); }); bankCyan.addEventListener("click", function(event) { // console.log("bankCyan clicked"); checkButtonFunction.apply(this); }); bankSienna.addEventListener("click", function(event) { // console.log("bankSienna clicked"); checkButtonFunction.apply(this); }); function gameSetUp() { code = gameStats.shared.code; hints = gameStats.shared.hints; guesses = gameStats.shared.guesses; guessesArchive = gameStats.shared.guessesArchive; guessesArchiveString = gameStats.shared.guessesArchiveString; hintsArchive = gameStats.shared.hintsArchive; hintsArchiveString = gameStats.shared.hintsArchiveString; currentGuess = gameStats.shared.currentGuess; isInCode = gameStats.shared.isInCode; isExactMatch = gameStats.shared.isExactMatch; codeGuessNumber = gameStats.shared.codeGuessNumber; if(gameMode == "easy") { codeNumber = gameStats.easy.codeNumber; colors = gameStats.easy.colors; turnNumber = gameStats.easy.turnNumber; } else if(gameMode == "normal") { codeNumber = gameStats.normal.codeNumber; colors = gameStats.normal.colors; turnNumber = gameStats.normal.turnNumber; } else if(gameMode == "hard") { codeNumber = gameStats.hard.codeNumber; colors = gameStats.hard.colors; turnNumber = gameStats.hard.turnNumber; } genCode(codeNumber); } function genCode(codeNumber) { var tempCode = []; while(tempCode.length < codeNumber) { var colorSelector = genNum(); if(!tempCode.includes(colorSelector)) { tempCode.push(colorSelector); } } tempCode.forEach(function(el) { code.push(colors[el]); }); displayTurns(); return code } function genNum() { var x = (Math.floor(Math.random()*colors.length)); return x; } function checkButtonFunction(){ if(codeGuessNumber < codeNumber) { // console.log(this.textContent); currentGuess = this.textContent; getGuess(); createBoxes(guesses, guessesDisplay); codeGuessNumber++; } if(codeGuessNumber == codeNumber) { disableColorBank(); } } function getGuess() { guesses.push(currentGuess); } function checkGuess() { for(var i = 0; i < guesses.length; i++) { if(guesses[i] == code[i]) { // console.log("match!", guesses[i], code[i]); // black key peg isExactMatch++; hints.push("*"); } else if(code.includes(guesses[i])) { // console.log(guesses[i] + " is in the code."); // white key peg isInCode++; hints.push("o"); } } // console.log("hints:", hints); isGameOver(); } function createBoxes(array, webDisplay) { var stringAccumulator = ""; for(var i = 0; i < array.length; i++) { if(array[i] == "R") { stringAccumulator += `<div class="boxes red">R</div> `; } else if(array[i] == "O") { stringAccumulator += `<div class="boxes orange">O</div> `; } else if(array[i] == "Y") { stringAccumulator += `<div class="boxes yellow">Y</div> `; } else if(array[i] == "G") { stringAccumulator += `<div class="boxes green">G</div> `; } else if(array[i] == "B") { stringAccumulator += `<div class="boxes blue">B</div> `; } else if(array[i] == "P") { stringAccumulator += `<div class="boxes purple">P</div> `; } else if(array[i] == "M") { stringAccumulator += `<div class="boxes magenta">M</div> `; } else if(array[i] == "L") { stringAccumulator += `<div class="boxes lime">L</div> `; } else if(array[i] == "C") { stringAccumulator += `<div class="boxes cyan">C</div> `; } else if(array[i] == "S") { stringAccumulator += `<div class="boxes sienna">S</div> `; } } webDisplay.innerHTML = stringAccumulator + `<br/>`; } function storeOldGuesses() { guessesArchiveString += guessesArchiveDisplay.innerHTML; guessesArchiveDisplay.innerHTML = guessesArchiveString; } function displayOldGuesses() { guessesArchive.push(guesses); guessesArchive.forEach(function(turn) { createBoxes(turn, guessesArchiveDisplay); }); } function displayCurrentHints() { hints.sort(); hintsDisplay.innerHTML = hints.join(" "); } function storeOldHints() { hintsArchiveString += `<div class="hint">${hintsDisplay.innerHTML}</div>`; } function displayOldHints() { hintsArchiveDisplay.innerHTML = hintsArchiveString; } function displayTurns() { turnsLeftDisplay.textContent = turnNumber; } function isGameOver() { if(isExactMatch == 4) { displayCode(); disableColorBank(); endofGameStatusDisplay(); resetGameButton.classList.remove("no-display"); statusDisplay.textContent = "You won!"; } else if(turnNumber == 0) { displayCode(); disableColorBank(); endofGameStatusDisplay(); resetGameButton.classList.remove("no-display"); statusDisplay.textContent = "You're out of turns."; } } function disableColorBank() { // if(codeGuessNumber == codeNumber) { // console.log("You're at the maximum guess number."); bankRed.setAttribute("class", "boxes engaged"); bankOrange.setAttribute("class", "boxes engaged"); bankYellow.setAttribute("class", "boxes engaged"); bankGreen.setAttribute("class", "boxes engaged"); bankBlue.setAttribute("class", "boxes engaged"); bankPurple.setAttribute("class", "boxes engaged"); if(gameMode == "normal") { bankMagenta.setAttribute("class", "boxes engaged"); bankLime.setAttribute("class", "boxes engaged"); } if(gameMode == "hard") { bankMagenta.setAttribute("class", "boxes engaged"); bankLime.setAttribute("class", "boxes engaged"); bankCyan.setAttribute("class", "boxes engaged"); bankSienna.setAttribute("class", "boxes engaged"); } // } } function enableColorBank() { bankRed.setAttribute("class", "boxes red"); bankOrange.setAttribute("class", "boxes orange"); bankYellow.setAttribute("class", "boxes yellow"); bankGreen.setAttribute("class", "boxes green"); bankBlue.setAttribute("class", "boxes blue"); bankPurple.setAttribute("class", "boxes purple"); if(gameMode == "normal") { bankMagenta.setAttribute("class", "boxes magenta"); bankLime.setAttribute("class", "boxes lime"); } if(gameMode == "hard") { bankMagenta.setAttribute("class", "boxes magenta"); bankLime.setAttribute("class", "boxes lime"); bankCyan.setAttribute("class", "boxes cyan"); bankSienna.setAttribute("class", "boxes sienna"); } } function resetTurn() { codeGuessNumber = 0; guessesDisplay.textContent = ""; guesses = []; hints = []; hintsDisplay.textContent = ""; isExactMatch = 0; isInCode = 0; currentGuess = ""; enableColorBank(); } function resetGame() { resetTurn(); gameStats.shared.hints = []; hintsArchiveString = ""; hintsArchiveDisplay.textContent = ""; gameStats.shared.guesses = []; gameStats.shared.guessesArchive = []; guessesArchiveString = ""; guessesArchiveDisplay.textContent = ""; gameStats.shared.code = []; codeDisplay.textContent = ""; codeContainerDisplay.classList.add("no-display"); statusDisplay.classList.add("no-display"); resetGameButton.classList.add("no-display"); checkGuessButton.classList.remove("no-display"); resetTurnButton.classList.remove("no-display"); } function endofGameStatusDisplay() { checkGuessButton.classList.add("no-display"); resetTurnButton.classList.add("no-display"); codeContainerDisplay.classList.remove("no-display"); statusDisplay.classList.remove("no-display"); } function displayCode() { createBoxes(code, codeDisplay) } gameSetUp();<file_sep># mastermind # To play, visit https://lsr488.github.io/mastermind/ # Instructions Guess a hidden color code. You'll get feedback on your guesses to help you. A * means you have the correct color in the correct place. A o means you have the correct color but in the wrong place. The placement of the markers do not correspond with the colors' locations. ## GH Pages Repo https://github.com/lsr488/mastermind/tree/gh-pages
8771ebb828c23bf7b90664077a3279d987797465
[ "JavaScript", "Markdown" ]
2
JavaScript
lsr488/mastermind
b93b6a006d629a267ef22e96674a4e85ceb40ca3
86a191f42523b4b15fdcd74c9f6c671ec3f11de1
refs/heads/master
<repo_name>dagint/CFN-VM-Import<file_sep>/README.md # CFN-VM-Imporit ## Summary: This is an AWS cloudformation template to automate the creation and setup of the required IAM policies and roles to use the import export process. It will also create the bucket which should be used to upload and import the virtual machine (VM) into AWS. You can find detailed instructions to get this fully setup here -> http://docs.aws.amazon.com/vm-import/latest/userguide/vmimport-image-import.html ## Outputs: There will be 2 outputs. - The name of the S3 bucket which should be used to upload and import your vm's - An IAM group name which the user performing the import needs to be a member. The group the user should be a member of is "ImportExportGroup". ## Known challenges - This process requires a role with the specific name of "vmimport" if it is not named exactly the imports will fail. This file does create this role with the correct name, but don't modify this role with something custom or it will cause failures. - If there are are any existing roles or groups with the same name existing the template will fail. Please remove those groups if you feel comfortable and try again - You will have to check some additional check boxes during the creation, its more for security awareness letting you know it's creating IAM resources and IAM resources with custom names. - Deleting the cloudformation template will error if there is still data in the S3 bucket. <file_sep>/sample-lambda-auto-vmimport.py import boto3 def lambda_handler(event, context): ec2_client = boto3.client('ec2') s3_object = event[u'Records'][0][u's3'][u'object'][u'key'] s3_bucket = event[u'Records'][0][u's3'][u'bucket'][u'name'] import_vmdk = ec2_client.import_image( Description='Lambda_VMIE', DiskContainers=[ { 'Description':'Import_VMDK', 'Format':'vmdk', 'UserBucket': { 'S3Bucket': s3_bucket, 'S3Key': s3_object }, }, ], LicenseType='BYOL' ) import_vmdk return;
53d0a46c4982fa9e100a20b781004dc8d8ebc609
[ "Markdown", "Python" ]
2
Markdown
dagint/CFN-VM-Import
71765d907a35e7da366f9720a6e2424614b76d93
a64761da19432be23a8b69c042d1d08f9f7629f4
refs/heads/master
<repo_name>Ashok98485/Demystifying-Disease-Identification-and-Diagnosis-Using-Machine-Learning-Classification-Algorithms<file_sep>/README.md # Demystyfy-medical-data- The exponential surge in healthcare data is providing new opportunities to discover meaningful datadriven characteristics and patterns of diseases. Machine learning and deep learning models have been employed for many computational phenotyping and healthcare prediction tasks. However, machine learning models are crucial for wide adaption in medical research and clinical decision making. In this chapter, the authors introduce demystifying diseases identification and diagnosis of various disease using machine learning algorithms like logistic regression, naive Bayes, decision tree, MLP classifier, random forest in order to cure liver disease, hepatitis disease, and diabetes mellitus. This work leverages the initial discoveries made through data exploration, statistical analysis of data to reduce the number of explanatory variables, which led to identifying the statistically significant attributes, mapping those significant attributes to the response, and building classification techniques to predict the outcome and demystify clinical diseases. <file_sep>/ilpdrf.R Lab 1( Bank Loan Prediction Model) ---------------------------------------------- setwd("C:/Users/Dr.Sobhan/Desktop/Dec2016/Data sets/5-Logistic Regression/") loan = read.csv("bank.csv") m1=glm(loan$repaid~loan$age+loan$salary,family=binomial) summary(m1) Lab 2(Polynomial Modeling : Heart Stroke Prediction) -------------------------------------------------------- health= read.csv("health.csv") attach(health) plot(weight,BP,col=Suffered.Heart.storke+1) BPS = BP*BP weights = weight*weight BPweight = BP*weight m1=glm(Suffered.Heart.storke~BP+weight+weights+BPS+BPweight,family=binomial) summary(m1) min(weight) max(weight) me = dim(10) for ( i in 1: 10){ t = (weight> (i-1)*10) & (weight <= i*10) me[i] = mean(Suffered.Heart.storke[t]) } me me = log(me/(1-me)) plot(me,type="l") points(me) =======================================Lab 3===================================== Example 1: ICU Data SIZE: 200 observations, 21 variables SOURCE: <NAME>., <NAME>. and Sturdivant, R.X. (2013) LIST OF VARIABLES: Name Codes/Values Abbreviations ----------------------------------------------------------------------------------------------------------------------------------------- Identification Code ID Number ID Vital Status 0 = Lived, 1=Died STA Age Years AGE Gender 0 = Male,1=Female GENDER Race 1 = White,2=Black,3=Other RACE Service at ICU Admission 0 = Medical,1=Surgical SER Cancer Part of PresentProblem 0 = No,1=Yes CAN History of Chronic Renal Failure 0 = No, 1=Yes CRN Infection Probable at ICU Admission 0 = No,1=Yes INF CPR Prior to ICU Admission 0 = No,1=Yes CPR Systolic Blood Pressure at ICU Admission mm Hg SYS Heart Rate at ICU Admission Beats/min HRA Previous Admission to an ICU within 6 Months 0 = No,1=Yes PRE Type of Admission 0 = Elective 1=Emerggency TYP Long Bone, Multiple, Neck, 0 = No,1=Yes FRA Single Area, or Hip Fracture PO2 from Initial Blood Gases 0 = > 60, 1<60 PO2 PH from Initial Blood Gases 0 => 7.25, 1<7.25 PH PCO2 from initial Blood Gases 0 < 45, 1>=45 PCO Bicarbonate from Initial Blood Gases 0 = >18, 1=<18 BIC Creatinine from Initial Blood Gases 0 = < 2.0, 1>2.0 CRE Level of Consciousness at ICU Admission 0 = No Coma or Stupor,1=Deep stupor,2=Coma LOC icu.dat = read.table("ICU.txt",header=T) summary(icu.dat) model = glm(sta~age+sex+ser+hra+pre+typ+can+sys, family=binomial,data=icu.dat) summary(model) model = glm(sta~age+pre+typ+can, family=binomial,data=icu.dat) summary(model) model = glm(sta~age+typ+can, family=binomial,data=icu.dat) summary(model) #Deviance test #lower.tail = FALSE gives probability of greater or equal pchisq(null.deviance - residual deviance, df.null - df.residual, lower.tail = FALSE) set.seed(1) n=nrow(icu.dat) n n1=floor(n*(0.7)) n1 n2=n-n1 n2 train=sample(1:n,n1) model = glm(sta~age+typ+can, family=binomial,data=icu.dat[train,]) summary(model) pchisq(null.deviance - residual deviance, df.null - df.residual, lower.tail = FALSE) ptrain <- predict(model,newdata=icu.dat[train,],type="response") gg1=floor(ptrain+0.5) ttt=table(icu.dat$sta[train],gg1) error=(ttt[1,2]+ttt[2,1])/n1 error ptest <- predict(model,newdata=icu.dat[-train,],type="response") gg1=floor(ptest+0.5) ttt=table(icu.dat$sta[-train],gg1) error=(ttt[1,2]+ttt[2,1])/n2 error =====================================Lab 4================================================= tp = vector("numeric",7) fp = vector("numeric",7) j=1 for ( i in c(0.3,0.4,0.5,0.6,0.7,0.8,0.9)){ gg1 = floor(ptest+i) ttt=table(icu.dat[-train,"sta"],gg1) tp[j] = ttt[2,2]/(ttt[2,1]+ttt[2,2]) fp[j] = ttt[1,2]/(ttt[1,1]+ttt[1,2]) j= j+1 } plot(tp~fp, type="l") =====================Lab 5(Lasso Logistic regression)=========================== library(glmnet) Xdel = as.matrix(icu.dat[,c("age","sex","ser","hra","pre","typ","can","sys")]) ydel = icu.dat[,"sta"] cv.glmmod<-cv.glmnet(x=Xdel,y=ydel,alpha=1, type.measure = "deviance") plot(cv.glmmod) f<-cv.glmmod$lambda.min f glmmod<-glmnet(x=Xdel,y=ydel, alpha=1, family='binomial') coef(glmmod,s=f) predict(glmmod, newx = Xdel, type = "response", s = c(f)) ===================Lab 6======================================================= Several choices are available to estimate multinomial logistic regression models in R. For example, one can use the command mlogit in the package mlogit, the command vglm in the package VGAM, or the mnlm function in the package textir. data = read.csv("brand.csv") head(data) data$BRAND = factor(data$BRAND) data$BRAND library(nnet) train = sample(1:nrow(data),600) test <- multinom(BRAND ~ FEMALE + AGE, data = data[train,]) summary(test) pp <- fitted(test) predict(test, newdata = data[-train,], "probs") z <- summary(test)$coefficients/summary(test)$standard.errors z p <- (1 - pnorm(abs(z), 0, 1))*2 p <file_sep>/liver1.R setwd("C:/Users/Dr.Sobhan/Desktop/Dec2016/Data sets/5-Logistic Regression/") setwd("C:/data/E/ashok2017/Dec2016/Data sets/5-Logistic Regression") liver= read.table("liver.csv",header=T) summary(liver) liver= read.csv("liver.csv",header=T) summary(liver) attach(liver) plot(Age,Gender,Total_Bilirubin,Direct_Bilirubin,Alkaline_Phosphotase,Alamine_Aminotransferase, Aspartate_Aminotransferase,Total_Protiens,Albumin col=outcome+1) plot(Age,Gender,Total_Bilirubin,Direct_Bilirubin,Alkaline_Phosphotase,Alamine_Aminotransferase, Aspartate_Aminotransferase,Total_Protiens,Albumin,col=outcome+1) plot(Age,Gender,Total_Bilirubin,Direct_Bilirubin,Alkaline_Phosphotase,Alamine_Aminotransferase, Aspartate_Aminotransferase,Total_Protiens,Albumin,col=outcome) plot(Age,Gender,Total_Bilirubin,Direct_Bilirubin,Alkaline_Phosphotase,Alamine_Aminotransferase, Aspartate_Aminotransferase,Total_Protiens,Albumin,col=outcome+1) health= read.csv("health.csv") attach(health) plot(weight,BP,col=Suffered.Heart.storke+1) plot(Total_Bilirubin,Direct_Bilirubin,col=outcome+1) model = glm(outcome~Age+Gender+Total_Bilirubin+Direct_Bilirubin+Alkaline_Phosphotase+Alamine_Aminotransferase+Aspartate_Aminotransferase+Total_Protiens+Albumin, family=binomial,data=liver) summary(model) model = glm(outcome~., family=binomial,data=liver) model1 = glm(outcome~., family=binomial,data=liver) summary(model1) model2 = glm(outcome~1, family=binomial,data=liver) summary(model2) plot(model1) plot(model2) step(model2,scope = list(upper=model),direction="both",test="Chisq",data=liver) step(model2,scope = list(upper=model1),direction="both",test="Chisq",data=liver) step(model1,scope = list(upper=model2),direction="both",test="Chisq",data=liver) step(model2,scope = list(upper=model1),direction="forward",test="Chisq",data=liver) step(model2,scope = list(upper=model1),direction="backward",test="Chisq",data=liver) model.null = glm(Status ~ 1,data=liver,family = binomial(link="logit")) model.null = glm(outcome ~ 1,data=liver,family = binomial(link="logit")) summary(model.null) model.full = glm(outcome ~ 1,data=liver,family = binomial(link="logit")) summary(model.full) model.full = glm(outcome ~ .,data=liver,family = binomial(link="logit")) summary(model.full) finalmodel1 =glm((formula = outcome ~ Direct_Bilirubin+ Total_Bilirubin+ Aspartate_Aminotransferase+ Alamine_Aminotransferase+ Alkaline_Phosphotase, family = binomial, data = liver) finalmodel1 =glm((formula = outcome ~ Direct_Bilirubin + Total_Bilirubin + Aspartate_Aminotransferase + Alamine_Aminotransferase + Alkaline_Phosphotase, family = binomial, data = liver) finalmodel1 =glm((outcome ~ Direct_Bilirubin + Total_Bilirubin + Aspartate_Aminotransferase + Alamine_Aminotransferase + Alkaline_Phosphotase, family = binomial, data = liver) finalmodel1 =glm((outcome ~ Direct_Bilirubin+Total_Bilirubin+Aspartate_Aminotransferase +Alamine_Aminotransferase +Alkaline_Phosphotase, family = binomial,data = liver) finalmodel1 =glm((outcome ~ Direct_Bilirubin+Total_Bilirubin+Aspartate_Aminotransferase +Alamine_Aminotransferase +Alkaline_Phosphotase,family = binomial,data = liver) finalmodel1 =glm(outcome ~ Direct_Bilirubin+Total_Bilirubin+Aspartate_Aminotransferase +Alamine_Aminotransferase +Alkaline_Phosphotase,family = binomial,data = liver) summary(finalmodel1) pchisq(null.deviance - residual deviance, df.null - df.residual, lower.tail = FALSE) pchisq(null.deviance - residual deviance, df.null - df.residual, lower.tail = FALSE) pchisq(null deviance-residual deviance,df.null-df.residual, lower.tail= FALSE) pchisq(null deviance -residual deviance ,df.null-df.residual, lower.tail= FALSE) pchisq(null.deviance - residual deviance, df.null - df.residual, lower.tail = FALSE) n=nrow(liver) n n1=floor(n*(0.7)) n1 n2=n-n1 n2 train=sample(1:n,n1) model = glm(outcome~Direct_Bilirubin+Alamine_Aminotransferase+Total_Protiens+Albumin, family=binomial,data=liver[train,]) summary(model) pchisq(null.deviance - residual deviance, df.null - df.residual, lower.tail = FALSE) pchisq(null.deviance - residual deviance, df.null - df.residual, lower.tail = FALSE) ptrain <- predict(model,newdata=liver[train,],type="outcome") ptrain <- predict(model,newdata=liver[train,],type = outcome) ptrain <- predict(model,data=liver[train,],type = outcome)
b11e4ab6e403e52dddf93f4673d4f1cfd7c8e58d
[ "Markdown", "R" ]
3
Markdown
Ashok98485/Demystifying-Disease-Identification-and-Diagnosis-Using-Machine-Learning-Classification-Algorithms
997196b3abca40c7c4c8f43d41d707558c05a541
961132548afdf4efcd286eabd9c86d2017112de0
refs/heads/master
<repo_name>BouquetTristan/Entrainement_24h<file_sep>/sources/class.c /** *\file class.c *\brief This file contain the class use in the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 13/02/2017 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include"../includes/global.h" #include"../includes/capacity.h" t_class swordman={ "swordman",//name 100,//hp 50,//mp 12, //strenght 7, //defence 10, //precision 10, //agility }; t_class bowman={ "bowman",//name 75,//hp 50,//mp 12, //strenght 5, //defence 12, //precision 13, //agility }; <file_sep>/sources/game.c /** *\file game.c *\brief *\version 1.0 *\author <NAME>, <NAME> *\date 10/02/2017 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include"../includes/global.h" #include"../includes/global.h" #include"../includes/armor.h" #include"../includes/capacity.h" #include"../includes/character.h" #include"../includes/class.h" #include"../includes/weapon.h" int i, j; int carte[T][T]; void initialisation() { for(i=1;i<T-1;i++) { for(j=1;j<T-1;j++) { carte[i][j] = 1; } } perso.posX = 5; perso.posY = 5; } int verifierBordure(int x, int y) { if (carte[x][y] == 0) return 0; else return 1; } void afficherCarte() { system("clear"); char rien = '.'; char personnage = 'X'; char bordure = 'H'; carte[perso.posX][perso.posY] = 2; for(i=0;i<T;i++) { for(j=0;j<T;j++) { if(carte[i][j] == 0) printf("%c ", bordure); if(carte[i][j] == 1) printf("%c ", rien); if(carte[i][j] == 2) printf("%c ", personnage); } printf("\n"); } } void bougerDirection( int haut, int bas, int gauche, int droite) { int verifBordure = verifierBordure(perso.posX-haut+bas, perso.posY-gauche+droite); if(verifBordure == 1) { carte[perso.posX][perso.posY] = 1; perso.posX -= haut; perso.posX += bas; perso.posY -= gauche; perso.posY += droite; afficherCarte(); } else printf("Impossible d'aller dans cette direction\n"); } void deplacer() { char commande[20]; do//Liste des commandes de deplacement { printf("Entrez la direction : "); fgets(commande, sizeof commande, stdin); if(strcmp(commande, "haut\n") == 0) bougerDirection(1, 0, 0, 0); if(strcmp(commande, "bas\n") == 0) bougerDirection(0, 1, 0, 0); if(strcmp(commande, "gauche\n") == 0) bougerDirection(0, 0, 1, 0); if(strcmp(commande, "droite\n") == 0) bougerDirection(0, 0, 0, 1); } while(!(strcmp(commande, "quitter\n") == 0 )); } void main() { initialisation(); afficherCarte(); deplacer(); } <file_sep>/sources/character.c /** *\file character.c *\brief This file contain the character use in the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 13/02/2017 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include"../includes/global.h" #include"../includes/armor.h" #include"../includes/capacity.h" #include"../includes/class.h" #include"../includes/weapon.h" t_character character_create(t_character* character,char* name,int hp,int mp,t_class * class,char * type,int level,t_weapon * weapon,t_armor * armor,t_guild * guild){ strcpy( character->name , name ); character->hp=hp; character->mp=mp; character->class=class; character->level=level; character->weapon=weapon; character->armor=armor; character->guild=guild; } <file_sep>/LesTestsDeGilles/Makefile INCLD = -I./include -lSDL2-2.0 -lSDL2_image all: game game: main.o gcc -o game main.o $(INCLD) main.o: src/main.c gcc -c src/main.c clean: rm -f *.o;<file_sep>/LesTestsDeGilles/src/main.c /* * main.c * * Created on: 04 feb. 2017 * Author: gilles */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #define TRUE 1 #define FALSE 0 const int SCREEN_WIDTH = 800; const int SCREEN_HEIGHT = 500; const char TILES_PATH[] = "assets/tiles/" ; const char MAPS_PATH[] = "assets/maps/" ; typedef struct { int format ; char* map ; int tex_amount; SDL_Texture** textures ; } map_t ; int processEvents (void) { SDL_Event event ; while(SDL_PollEvent (&event)) { switch (event.type) { case SDL_QUIT : return FALSE ; } } return TRUE; } SDL_Texture* loadTexture( SDL_Renderer *renderer, char *path ) { SDL_Texture* newTexture = NULL ; //Load image at specified path SDL_Surface* loadedSurface = IMG_Load( path ) ; if( loadedSurface == NULL ) { fprintf(stderr, "Unable to load image %s! SDL_image Error: %s\n", path, IMG_GetError() ) ; } else { //Create texture from surface pixels newTexture = SDL_CreateTextureFromSurface( renderer, loadedSurface ); SDL_FreeSurface( loadedSurface ); } return newTexture; } void getLine(FILE* stream, char* line, int size, char marker) { int i = 0; char c ; while( i<size-1 && (c=fgetc(stream)) != marker && !feof(stream) ) { if(c != '\n') { line[i] = c ; i++ ; } } } map_t* loadMap(SDL_Renderer *renderer, char *path) { map_t* loadedMap ; int MAX_BUFFER_SIZE = 128; char buffer[MAX_BUFFER_SIZE] ; FILE* file ; int i; int ind; char texpath[256] ; char name[128] ; int reachable ; int format ; int amount ; if( (file = fopen(path,"r")) == NULL) { fprintf(stderr,"Could not open file %s.\n",path) ; return (map_t*) NULL ; } loadedMap = malloc(sizeof(map_t)) ; //File reading //Get headers fscanf(file,"-- texture_amount=%i --\n",&amount) ; fscanf(file,"-- format=%i --\n",&format) ; printf("\n::DEBUG:: format = %i\n",format) ; printf("::DEBUG:: texture_amount = %i\n",amount) ; loadedMap->tex_amount = amount ; loadedMap->format = format ; loadedMap->textures = malloc(sizeof(void*)*amount) ; loadedMap->map = malloc(sizeof(char)*format*format) ; //Get textures info for(i=0; i<amount; i++) { fscanf(file,"%i,%s\n",&ind,name) ; strcpy(texpath,TILES_PATH) ; strcat(texpath,name) ; printf("\n::DEBUG:: ind = %i\n",ind) ; printf("\n::DEBUG:: texpath = %s\n",texpath) ; loadedMap->textures[ind] = loadTexture(renderer, texpath) ; } //Get map data getLine(file, buffer, MAX_BUFFER_SIZE, ';') ; strcpy(loadedMap->map,buffer) ; for(i=0;i<format-1;i++) { getLine(file, buffer, MAX_BUFFER_SIZE, ';') ; strcat(loadedMap->map,buffer) ; } return loadedMap ; } void renderMap(SDL_Renderer *renderer, map_t *map); int main (int argc, char **argv) { SDL_Window *window = NULL ; SDL_Renderer *renderer = NULL ; SDL_Texture *texture = NULL; SDL_Rect viewPortMain ; //xpos ypos width height SDL_Rect tile_template ; tile_template.w = 30 ; tile_template.h = 30 ; map_t *map01; char path[128] ; int run ; int imgFlags ; //Initialization the SDL if (SDL_Init (SDL_INIT_VIDEO) != 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); } //Initialize PNG loading imgFlags = IMG_INIT_PNG ; if( !( IMG_Init( imgFlags ) == imgFlags ) ) { fprintf(stderr, "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() ) ; } window = SDL_CreateWindow ( "Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ) ; renderer = SDL_CreateRenderer (window, -1, SDL_RENDERER_ACCELERATED) ; strcpy(path,MAPS_PATH) ; strcat(path,"map01.map") ; map01 = loadMap(renderer, path) ; //Set the viewport viewPortMain.x = 0 ; viewPortMain.y = 0 ; viewPortMain.w = SCREEN_WIDTH ; viewPortMain.h = SCREEN_HEIGHT ; SDL_RenderSetViewport(renderer, &viewPortMain) ; // Game loop run = TRUE ; while (run) { run = processEvents () ; //Set the drawing color to gray SDL_SetRenderDrawColor (renderer, 150, 150, 150, 255) ; SDL_RenderClear (renderer) ; int format = map01->format; //Render map to screen for(int i=0; i< format; i++) for(int j=0; j< format; j++) { tile_template.x = i*tile_template.w ; tile_template.y = j*tile_template.h ; switch(map01->map[j*format+i]) { case '0' : texture = map01->textures[0]; break ; case '1' : texture = map01->textures[1]; break ; } SDL_RenderCopy( renderer, texture, NULL, &tile_template ) ; } SDL_RenderPresent (renderer) ; SDL_Delay (50) ; } //SDL_DestroyTexture (texture) ; SDL_DestroyTexture (texture); SDL_DestroyRenderer (renderer) ; SDL_DestroyWindow (window) ; IMG_Quit(); SDL_Quit(); return 0 ; } <file_sep>/LesTestsDeGilles/src/test.c /* * main.c * * Created on: 04 feb. 2017 * Author: gilles */ #include <stdio.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #define TRUE 1 #define FALSE 0 const int SCREEN_WIDTH = 800; const int SCREEN_HEIGHT = 450; int processEvents (void) { SDL_Event event ; while(SDL_PollEvent (&event)) { switch (event.type) { case SDL_QUIT : return FALSE ; } } return TRUE; } void render (SDL_Renderer *renderer, SDL_Rect *map) { // Clear the window to gray SDL_SetRenderDrawColor (renderer, 100, 100, 100, 255) ; SDL_RenderClear (renderer) ; //Set the drawing color to white SDL_SetRenderDrawColor (renderer, 255, 255, 255, 255) ; SDL_RenderFillRect (renderer, map) ; SDL_RenderPresent (renderer) ; } int initialize (SDL_Window *window, SDL_Renderer *renderer, SDL_Texture *texture) { int success = TRUE ; if (SDL_Init (SDL_INIT_VIDEO) != 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); success = FALSE; } window = SDL_CreateWindow ( "Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ) ; renderer = SDL_CreateRenderer (window, -1, SDL_RENDERER_ACCELERATED) ; //texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET,200,100); return success; } int main (int argc, char *argv[]) { SDL_Window *window = NULL ; SDL_Renderer *renderer = NULL ; //SDL_Surface *screen = NULL ; SDL_Texture *texture = NULL ; SDL_Rect rect = {0, 0, 400, 400} ; //xpos ypos width height int run ; initialize (window, renderer, texture) ; // Game loop run = TRUE ; while (run) { run = processEvents () ; render (renderer, &rect) ; SDL_Delay (20) ; } SDL_DestroyTexture (texture) ; SDL_DestroyRenderer (renderer) ; SDL_DestroyWindow (window) ; SDL_Quit(); return 0 ; } <file_sep>/includes/weapon.h /** *\file weapon.h *\brief This file contain the weapon use in the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 13/02/2017 */ #ifndef GLOBAL_H #define GLOBAL_H #include<stdio.h> #include <stdlib.h> #include"../includes/global.h" #endif t_weapon wooden_sword; t_weapon wooden_bow; <file_sep>/includes/armor.h /** *\file armor.h *\brief This file contain the armor use in the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 13/02/2017 */ #ifndef GLOBAL_H #define GLOBAL_H #include<stdio.h> #include <stdlib.h> #include"../includes/global.h" #endif t_armor leather_armor; t_armor bronze_armor; <file_sep>/sources/weapon.c /** *\file weapon.c *\brief This file contain the weapon use in the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 13/02/2017 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include"../includes/global.h" const t_weapon wooden_sword={ "wooden sword", //name[25]; 5, //cost; 2, //mulatk; sword, //weaponstyle }; const t_weapon wooden_bow={ "wooden bow", //name[25]; 5, //cost; 2, //mulatk; bow, //weaponstyle };<file_sep>/includes/capacity.h /** *\file capacity.h *\brief This file contain the class use in the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 13/02/2017 */ #ifndef GLOBAL_H #define GLOBAL_H #include<stdio.h> #include <stdlib.h> #include"../includes/global.h" #endif const t_capacity hit; <file_sep>/includes/class.h /** *\file class.h *\brief This file contain the class use in the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 13/02/2017 */ #ifndef GLOBAL_H #define GLOBAL_H #include<stdio.h> #include <stdlib.h> #include"../includes/global.h" #endif const t_class swordman; const t_class bowman; <file_sep>/sources/Editeur.c #include <stdio.h> #include <stdlib.h> #include "../includes/global.h" #include <string.h> int map[L][L][T]; int informationMap[T][IM]; int currentMap = 0; int numberOfMap = 0; t_character character; //Open a file and put information in map[][] void fileOpen(char fileName[C]) { int i = 0, j = 0, f = 0; FILE * file = NULL; file = fopen("data/map.txt", "r"); int data, previousData; if(file != NULL) { data = fgetc(file); while(data != EOF) { previousData = data; data = fgetc(file);// Select code ASCII of character if(strcmp(fileName, "map.txt") == 0) { if(f < IM) { if(data == 10 || data == 32); else { //printf("%i->", data); informationMap[currentMap][f] = data; //printf("%i ", informationMap[currentMap][f]); f++; } } else { if(data == 10 && previousData == 10)//if double \n { currentMap++; numberOfMap++; f = 0; i = 0; } else { if(data == 32);//Don't take space and \n else if(data == 10) { //printf("%i\n",j); i++; j = 0; } else { //printf("Current Map : %i Coordonnées : %i %i ", currentMap, i, j); map[i][j][currentMap] = data; //printf("Data : %i = ", data); //printf("%i \n", map[i][j][currentMap]); //printf("%i ", map[i][j][currentMap]); j++; } } } } } currentMap = 0; } else { printf("The file can't be open.\n"); } fclose(file); } //Initialisation of Map and position of the character void initialisation() { int i,j,k; for(i=0;i<T-1;i++) { for(j=0;j<T-1;j++) { for(k=0;k<C;k++) { map[i][j][k] = 0; informationMap[i][j] = 0; } } } character.posX = 8; character.posY = 7; } //Check the type of position x y int checkBordure(int x, int y) { if (map[x][y][currentMap] == 49) return 1; else if (map[x][y][currentMap] == 51) return 3; else return 0; } int changeFromASCII(int variable) { if(variable == 48) return 0; else if(variable == 49) return 1; else if(variable == 50) return 2; else if(variable == 51) return 3; } int lenghtCurrentMap() { if(informationMap[currentMap][1] == 49) return 16; } //Show the current map void showMap() { system("clear"); //currentMap = 1; int lenght = lenghtCurrentMap(); int i,j; char nothing = '.'; char character_Pos = 'X'; char bordure = 'K'; char door = '_'; map[character.posX][character.posY][currentMap] = 50; for(i=0;i<lenght;i++) { for(j=0;j<lenght;j++) { if(map[i][j][currentMap] == 48) printf("%c ", bordure); if(map[i][j][currentMap] == 49) printf("%c ", nothing); if(map[i][j][currentMap] == 50) printf("%c ", character_Pos); if(map[i][j][currentMap] == 51) printf("%c ", door); } printf("\n"); } } //Move a character in a direction void moveController( int up, int down, int left, int right) { int check = checkBordure(character.posX-up+down, character.posY-left+right); if(check == 1) { map[character.posX][character.posY][currentMap] = 49; character.posX -= up; character.posX += down; character.posY -= left; character.posY += right; } else if(check == 3) { initialisation(); fileOpen("carte.txt"); } else printf("You can't move in this direction\n"); } //Choose the direction to move the character void move() { char command[20]; do//List of command to move { showMap(); printf("Write 'stop' to quit\n"); printf("Write the direction : "); fgets(command, sizeof command, stdin); if(strcmp(command, "up\n") == 0) moveController(1, 0, 0, 0); if(strcmp(command, "down\n") == 0) moveController(0, 1, 0, 0); if(strcmp(command, "left\n") == 0) moveController(0, 0, 1, 0); if(strcmp(command, "right\n") == 0) moveController(0, 0, 0, 1); } while(!(strcmp(command, "stop\n") == 0 )); } //Save all data in txt file void save() { int lenght; int variable, information, saveInformation; FILE * file = NULL; file = fopen("data/map.txt", "w+"); fprintf(file, "\n"); for(int k = 0; k < numberOfMap; k++) { lenght = lenghtCurrentMap(); /*Save information of the map*/ for(int f= 0; f<6; f++) { variable = informationMap[k][f]; variable = changeFromASCII(variable); fprintf(file, "%d ", variable); } fprintf(file, "\n"); /*Save map*/ for(int i = 1; i < lenght; i++) { for(int j = 0; j < lenght-1; j++) { variable = map[i][j][k]; variable = changeFromASCII(variable); fprintf(file, "%d ", variable); } fprintf(file, "\n"); } fprintf(file, "\n\n"); saveInformation = 0; } fclose(file); } //Modificate left and right door on a map void changeDoorVertical(int x, int y) { if(map[x+1][y][currentMap] != 49 || map[x][y][currentMap] != 49 || map[x+1][y][currentMap] != 49) { map[x-1][y][currentMap] = 49; map[x][y][currentMap] = 49; map[x+1][y] [currentMap]= 49; } else { map[x-1][y][currentMap] = 51; map[x][y][currentMap] = 51; map[x+1][y][currentMap] = 51; } } //Modificate top and bottom door on a map void changeDoorHorizontal(int x, int y) { if(map[x][y-1][currentMap] != 49 || map[x][y][currentMap] != 49 || map[x][y+1][currentMap] != 49) { map[x][y-1][currentMap] = 49; map[x][y][currentMap] = 49; map[x][y+1][currentMap] = 49; } else { map[x][y-1][currentMap] = 51; map[x][y][currentMap] = 51; map[x][y+1][currentMap] = 51; } } void changeOfMap(int i) { if(i == 1) if(currentMap < numberOfMap-1) { currentMap++; //printf("%i ", currentMap); } else printf("No next map\n"); else if(currentMap > 0) { currentMap--; //printf("%i ", currentMap); } else printf("No previous map\n"); } //Change map //Add, remove, modificate all map void editing() { int choice, doorChoice, mapChoice; int i; int lenght = lenghtCurrentMap(); do { printf("Menu : \n"); printf("1 - Door\n"); printf("2 - Save\n"); printf("3 - Move character\n"); printf("4 - Change current map\n"); printf("Your choice : "); scanf("%d", &choice); switch(choice) { case 1: showMap(); do { printf("Door menu : \n"); printf("1 - Left door\n"); printf("2 - Top door\n"); printf("3 - Right door\n"); printf("4 - Bottom door\n"); printf("5 - Return\n"); printf("Your choice : "); scanf("%d", &doorChoice); switch(doorChoice) { case 1: changeDoorVertical((lenght)/2, 1); showMap(); printf("Left Door has been modificate\n"); break; case 2: changeDoorHorizontal(2,(lenght-1)/2); showMap(); printf("Top Door has been modificate\n"); break; case 3: changeDoorVertical((lenght)/2, lenght-3); showMap(); printf("Right Door has been modificate\n"); break; case 4: changeDoorHorizontal(lenght-2,(lenght-1)/2); showMap(); printf("Bottom Door has been modificate\n"); break; case 5: showMap(); break; default : printf("This choice isn't attributed\n"); } } while(doorChoice != 5); break;//Change door case 2: save(); showMap(); printf("Your modifications have been saved\n"); break;//Save case 3: move(); showMap(); break;//Move character case 4: showMap(); do { printf("Actual Map : %d\n", currentMap+1); printf("Change Map Menu : \n"); printf("1 - Next Map\n"); printf("2 - Previous Map\n"); printf("3 - Return\n"); printf("Your choice : "); scanf("%d", &mapChoice); switch(mapChoice) { case 1: changeOfMap(1); showMap(); break; case 2: changeOfMap(2); showMap(); break; case 3: showMap(); break; default: printf("This choice isn't attributed map\n"); } } while(mapChoice != 5); break;//Change current map default: printf("This choice isn't attributed\n"); } } while(choice < 50); } void main() { printf("Initialisation.."); initialisation(); printf("..OK\n"); printf("FileOpen.."); fileOpen("map.txt"); printf("..OK\n"); showMap(); editing(); }<file_sep>/sources/armor.c /** *\file armor.c *\brief This file contain the armor use in the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 13/02/2017 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include"../includes/global.h" const t_armor leather_armor={ "leather armor", //name[25]; 5, //cost; 2, //muldef; light, //armorstyle; }; const t_armor bronze_armor={ "bronze armor", //name[25]; 5, //cost; 2, //muldef; intermediate, //armorstyle; };<file_sep>/makefile programme : exe All = armor.o weapon.o capacity.o class.o character.o Editeur.o src = ./sources inc =./includes lib = -lSDL2 -lSDL2_ttf armor.o: $(src)/armor.c $(inc)/global.h gcc -c $^ -g $(lib) weapon.o: $(src)/weapon.c $(inc)/global.h gcc -c $^ -g $(lib) capacity.o: $(src)/capacity.c $(inc)/global.h gcc -c $^ -g $(lib) class.o: $(src)/class.c $(inc)/global.h gcc -c $^ -g $(lib) character.o: $(src)/character.c $(inc)/global.h $(inc)/armor.h $(inc)/weapon.h $(inc)/capacity.h $(inc)/class.h gcc -c $^ -g $(lib) Editeur.o:$(src)/Editeur.c $(inc)/global.h gcc -c $^ -g $(lib) exe: $(All) gcc -o exe $(All) clean: rm *.o <file_sep>/includes/global.h /** *\file global.h *\brief This file contain the element wich are use on all the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 10/02/2017 */ #ifndef GLOBAL_H #define GLOBAL_H #include<stdio.h> #include <stdlib.h> #endif #define T 100 #define C 100 #define IM 6 //Information map #define L 150 typedef struct liste_s { int nb ; void ** liste ; } t_liste ; typedef struct guild t_guild; typedef struct character t_character; typedef enum{true = 1, false = 0}t_bool; /** *\enum t_bool *\brief Boolean type. */ typedef enum{axe,sword,stick,lance,hand,bow}t_weaponstyle; /** *\enum t_weaponstyle *\brief Weapon type. */ typedef enum{light,intermediate,heavy}t_armorstyle; /** *\enum t_armorstyle *\brief armor type. */ typedef struct { char* name; int cost; int damage; int level; }t_capacity; /** *\struct t_capacity *\brief A capacity definition with all it attribute. */ typedef struct { char* name; int cost; int mulatk; t_weaponstyle weaponstyle; }t_weapon; /** *\struct t_weapon *\brief A weapon definition with all it attribute. */ typedef struct { char* name; int cost; int muldef; t_armorstyle armorstyle; }t_armor; /** *\struct t_armor *\brief A armor definition with all it attribute. */ typedef struct { FILE * fic; char * biome; }t_map; /** *\struct t_map *\brief A matrix with it height and width, the biome define the tile style for this map. */ typedef struct { char* name; int hp; int mp; int strenght; int defence; int precision; int agility; t_liste* caplist; t_liste* weaponstyle; t_liste* armorstyle; }t_class; /** *\struct t_class *\brief A class definition with all it attribute the weaponstyle and armorstyle are use to know what kind of weapon and armor the class can wear. */ typedef struct guild { char* name; t_liste* member; int rank; }t_guild; /** *\struct t_guild *\brief Guild definition */ typedef struct { char* name; int gold; t_guild * guild; t_liste current_character; }t_player; /** *\struct t_player *\brief Player definition this information are use to save the game. **/ typedef struct character { char* name; int hp; int mp; int status; t_class * class; char * type; char * location; int posX; int posY; int level; t_weapon * weapon; t_armor * armor; t_guild * guild; }t_character; /** *\struct t_character *\brief A character definition with all it attribute. */ <file_sep>/README.md # Train_24h Jeu qui nous sert d'entrainement aux 24h du code <file_sep>/sources/capacity.c /** *\file capacity.c *\brief This file contain the class use in the game *\author <NAME>, <NAME>, <NAME> *\version 1.0 *\date 13/02/2017 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include"../includes/global.h" const t_capacity hit= { "hit", //name[25] 0, //cost; 1, //damage; 0, //level; };
8ef91f7f5924ad7190b8d63e07db4f00ab0ce3bf
[ "Markdown", "C", "Makefile" ]
17
C
BouquetTristan/Entrainement_24h
e1df9241320fdf700f2530a3b94f2d0f3138ca11
061fcf691d96fd464ee249d20b41222bc93e30a0
refs/heads/master
<repo_name>kafwihi/mvc<file_sep>/Controllers/CarsController copy.cs /*using System.Web;using System.Web.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using mvc.Models; using System.Net.Http; namespace mvc.Controllers {   public class CarsController : Controller   { // GET: Cars public ActionResult Index() { IEnumerable<Cars> cars = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:57265/api/"); //HTTP GET var responseTask = client.GetAsync("cars"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<IList<Cars>>(); readTask.Wait(); cars = readTask.Result; } else //web api sent error response { //log response status here.. cars = Enumerable.Empty<Cars>(); ModelState.AddModelError(string.Empty, "Server error. Please contact administrator."); } } return View(cars); } public ActionResult create() { return View(); } [HttpPost] public ActionResult create(Cars car) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:57265/api/"); //HTTP POST var postTask = client.PostAsJsonAsync<Cars>("cars", car); postTask.Wait(); var result = postTask.Result; if (result.IsSuccessStatusCode) { return RedirectToAction("Index"); } } ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator."); return View(car); } //single out the car public ActionResult Edit(int id) { Cars car = null; using (var client = new HttpClient()) { // System.Diagnostics.Debug.WriteLine("res = " + result); var result = GetResponseString(client,id); if (result!=null) { System.Diagnostics.Debug.WriteLine("res = " + result); // car=result; car = JsonConvert.DesirializeObject(result); } } return View(car); } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string GetResponseString(HttpClient client,int id) { client.BaseAddress = new Uri("http://localhost:57265/api/"); // var request = "http://localhost:57265/api/"; var response = client.GetAsync("cars?id=" + id.ToString()).Result; var content = response.Content.ReadAsStringAsync().Result; return content; } [HttpPost]//updater car public ActionResult Edit(Cars car) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:57265/api/"); //HTTP POST var putTask = client.PutAsJsonAsync<Cars>("cars", car); putTask.Wait(); var result = putTask.Result; if (result.IsSuccessStatusCode) { return RedirectToAction("Index"); } } return View(car); } /*[HttpPost] public IActionResult Index(Cars model){ if(ModelState.IsValid){ //to do } return View(); }*/ /*     // Declares the DbContext class     private CarsContext dataContext;     // The instance of DbContext is passed via dependency injection     public CarsController(CarsContext context)     {       this.dataContext=context;     }     // GET: /<controller>/     // Return the list of cars to the caller view     public IActionResult Index()     {       return View(this.dataContext.Cars.ToList());     }     public IActionResult Create()     {       return View();     }     // Add a new object via a POST request     [HttpPost]     [ValidateAntiForgeryToken]     public IActionResult Create(Cars car)     {       // If the data model is in a valid state ...       if (ModelState.IsValid)       {         // ... add the new object to the collection         dataContext.Cars.Add(car);         // Save changes and return to the Index method         dataContext.SaveChanges();         return RedirectToAction("Index");       }       return View(car);     }     [ActionName("Delete")]     public IActionResult Delete(int? id)     {       if (id == null)       {         return HttpNotFound();       }       Cars car = dataContext.Cars.Single(m => m.id == id);       if (car == null)       {         return HttpNotFound();       }       return View(car);     }     // POST: Cars/Delete/5     // Delete an object via a POST request     [HttpPost, ActionName("Delete")]     [ValidateAntiForgeryToken]     public IActionResult DeleteConfirmed(int id)     {       Cars car = dataContext.Cars.SingleOrDefault(m => m.id == id);       // Remove the car from the collection and save changes       dataContext.Cars.Remove(car);       dataContext.SaveChanges();       return RedirectToAction("Index");     }   } } HttpClient client = new HttpClient(); public async Task<string> GetResponseString() { var request = "http://localhost:51843/api/values/getMessage?id=1"; var response = await client.GetAsync(request); var content = await response.Content.ReadAsStringAsync(); return content; } HttpClient client = new HttpClient(); public string GetResponseString() { var request = "http://localhost:51843/api/values/getMessage?id=1"; var response = client.GetAsync(request).Result; var content = response.Content.ReadAsStringAsync().Result; return content; }*/<file_sep>/Models/Cars.cs using System; namespace mvc.Models { public class Cars{ public String Id {get;set;} public string CarBrand {get;set;} public string CarModel {get;set;} } }<file_sep>/Controllers/AccountController.cs //https://www.youtube.com/watch?v=hb7iJ-mt3_8 using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using mvc.Models; namespace mvc.Controllers { public class AccountController : Controller { public IActionResult Login(){ return View(); } [HttpPost] public IActionResult Login(LoginViewModel model){ if(ModelState.IsValid){ //to do } return View(); } } }<file_sep>/Controllers/CarsController.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using mvc.Models; using System.Net.Http; namespace mvc.Controllers {   public class CarsController : Controller   { // GET: Cars public ActionResult Index() { IEnumerable<Cars> cars = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:57265/api/"); //HTTP GET var responseTask = client.GetAsync("cars"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<IList<Cars>>(); readTask.Wait(); cars = readTask.Result; } else //web api sent error response { //log response status here.. cars = Enumerable.Empty<Cars>(); ModelState.AddModelError(string.Empty, "Server error. Please contact administrator."); } } return View(cars); } public ActionResult create() { return View(); } [HttpPost] public ActionResult create(Cars car) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:57265/api/"); //HTTP POST var postTask = client.PostAsJsonAsync<Cars>("cars", car); postTask.Wait(); var result = postTask.Result; if (result.IsSuccessStatusCode) { return RedirectToAction("Index"); } } ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator."); return View(car); } //single out the car public ActionResult Edit(int id) { //Cars car = null; IList<Cars> car = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:57265/api/"); //HTTP GET var responseTask = client.GetAsync("cars?id=" + id.ToString()); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<IList<Cars>>(); readTask.Wait(); car = readTask.Result; } } return View(car); } [HttpPost]//updater car public ActionResult Edit(Cars car) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:57265/api/"); //HTTP POST var putTask = client.PutAsJsonAsync<Cars>("cars", car); putTask.Wait(); var result = putTask.Result; if (result.IsSuccessStatusCode) { return RedirectToAction("Index"); } } return View(car); } //delete public ActionResult Delete(int id) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:64189/api/"); //HTTP DELETE var deleteTask = client.DeleteAsync("cars/" + id.ToString()); deleteTask.Wait(); var result = deleteTask.Result; if (result.IsSuccessStatusCode) { return RedirectToAction("Index"); } } return RedirectToAction("Index"); }   } }
5254d0ab7878d1e8077c60b0186e708a36be0f03
[ "C#" ]
4
C#
kafwihi/mvc
2c83270fd1e5178860031514033c6d226411736e
c023c5ea41b5256d53e6ebb290568778867fd2fd