2021-05-17

Practice Final Thread.

Please post your solutions to the Practice Final problems to this thread.
Best,
Chris
Please post your solutions to the Practice Final problems to this thread. Best, Chris

-- Practice Final Thread
Masaki Kudo 015134535
Earl Padron 012165647

Question 8: Describe how the value of an object property is looked up in Javascript and the relationship of this to an object's prototype property.

Solution: When Javascript looks up a property of an object, it looks up property in the current instance of that object. If it is not found then it looks in the prototype object of the given function object, and since prototype is an Object, it too has a prototype subobject. So it looks at the prototype property of this subobject to see if the property is set there. This makes inheritance possible in javascript.
(Edited: 2021-05-17)
Masaki Kudo 015134535 Earl Padron 012165647 ---- Question 8: Describe how the value of an object property is looked up in Javascript and the relationship of this to an object's prototype property. ---- Solution: When Javascript looks up a property of an object, it looks up property in the current instance of that object. If it is not found then it looks in the prototype object of the given function object, and since prototype is an Object, it too has a prototype subobject. So it looks at the prototype property of this subobject to see if the property is set there. This makes inheritance possible in javascript.

-- Practice Final Thread
Group 10 Question 10
Members: Sean Chan, Dai Le
a) var express = require('express') var app = express() app.use('/media', express.static(__dirname + '/media')); //Assuming there is an index.html located under /media, express should now take that index.html and serve it to the user when URL/media is in the address bar.
b) var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'user', password: 'password', database: 'database name' }); connection.connect((err) => { if (err) throw err; console.log('Connected!'); });
c) var express = require('express'); var app = express(); var logger = function (req, res, next) { req.logger_name = "Question10Logger"; console.log((new Date()).toISOString() + ": " + req.method); next() } //This creates the logger. From here you could add additional actions to do with the information such as have something that writes it to a file, or alternatively actively filter the inputs and only log inputs with specific keywords. app.use(logger); app.get('/', function (req, res) { res.send(req.path); //in this case we are simply passing along the GET request which is then logged along with the date. });
d) const express = require('express') const app = express() app.use(express.urlencoded({ extended: true })) app.post('/submit-form', (req, res) => { var someValue = req.body.someExampleField //Assuming there is some form whose submit action goes to /submit-form this post endpoint will allow you to read in the fields of the form which are indexed by their unique ids. })
(Edited: 2021-05-17)
'''Group 10''' '''Question 10''' Members: Sean Chan, Dai Le '''a)''' <nowiki>var express = require('express') var app = express() app.use('/media', express.static(__dirname + '/media')); //Assuming there is an index.html located under /media, express should now take that index.html and serve it to the user when URL/media is in the address bar. </nowiki> '''b)''' <nowiki>var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'user', password: 'password', database: 'database name' }); connection.connect((err) => { if (err) throw err; console.log('Connected!'); }); </nowiki> '''c)''' <nowiki>var express = require('express'); var app = express(); var logger = function (req, res, next) { req.logger_name = "Question10Logger"; console.log((new Date()).toISOString() + ": " + req.method); next() } //This creates the logger. From here you could add additional actions to do with the information such as have something that writes it to a file, or alternatively actively filter the inputs and only log inputs with specific keywords. app.use(logger); app.get('/', function (req, res) { res.send(req.path); //in this case we are simply passing along the GET request which is then logged along with the date. }); </nowiki> '''d)''' <nowiki>const express = require('express') const app = express() app.use(express.urlencoded({ extended: true })) app.post('/submit-form', (req, res) => { var someValue = req.body.someExampleField //Assuming there is some form whose submit action goes to /submit-form this post endpoint will allow you to read in the fields of the form which are indexed by their unique ids. })</nowiki>

-- Practice Final Thread
Caitlyn Chau, James Taylor, Tanmay Siwach
Question 2: What is class autoloading in PHP and give a briefly example of how to set it up and how it works. Your example should make use of a namespace that contains your actual first name.
    spl_autoload_register(function ($class) {
        $prefix = 'company\\james\\';
        $len = strlen($prefix);
        if (strncmp($prefix, $class, $len) !== 0) {
            return;
        }
        else{
            $relative_class = substr($class, $len);
        }
        $relative_class = substr($class, $len);
        if(file_exists("./".$relative_class.".php")){
            require_once "./".$relative_class.".php";
        }
    });
    namespace company\james\myclass;
Class autoloading in PHP allows you to minimize the number of files you read in before executing code. Having to use require or require_once statements in each class can significantly slow down performance. In this example, the autoloader gets a string name 'company\james\autoloader'. The autoloader checks if the namespace 'company\james' exists, and if it doesn't it will return. If the namespace does exist, it will check if the files after 'company\james'. It appends .php to that relative class, and if it does exists it reads it into memory.
(Edited: 2021-05-17)
Caitlyn Chau, James Taylor, Tanmay Siwach Question 2: What is class autoloading in PHP and give a briefly example of how to set it up and how it works. Your example should make use of a namespace that contains your actual first name. spl_autoload_register(function ($class) { $prefix = 'company\\james\\'; $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { return; } else{ $relative_class = substr($class, $len); } $relative_class = substr($class, $len); if(file_exists("./".$relative_class.".php")){ require_once "./".$relative_class.".php"; } }); namespace company\james\myclass; Class autoloading in PHP allows you to minimize the number of files you read in before executing code. Having to use require or require_once statements in each class can significantly slow down performance. In this example, the autoloader gets a string name 'company\james\autoloader'. The autoloader checks if the namespace 'company\james' exists, and if it doesn't it will return. If the namespace does exist, it will check if the files after 'company\james'. It appends .php to that relative class, and if it does exists it reads it into memory.

-- Practice Final Thread
6. Briefly explain how each of the following web attacks works: XSS, CSRF, Click Jacking, target blank attacks.
Nikki Gowan, Ajaypal Salh, Patricia Caceres
XSS (Cross-Site Scripting): XSS is a malicious script injection attack. The attack can happen on a website with a form in it when a malicious user or robot enters data in the form that has code instead. This code entered could do anything, and if for instance, the form is for a post on a website, any user that views the post could have cookies stolen, or something else bad depending on the script.
CSRF (Cross-site Request Forgery): A CSRF makes use of cookies to perform an attack. A website may store a cookie onto a user's machine in order to determine if they are logged into an account on the website.If the user visits other websites without logging out of their account, they may click a link that contains a URL designed to perform an action on the original website they had logged into. Because the user has a cookie on their machine that indicates they are logged in, a nefarious action may be processed by the server using their logged in account, without the user knowing.
A simple example is logging into a bank account, navigating to other websites and clicking a link intended to perform a transaction of some kind, which is then processed by a server because the server believes there is a logged in user performing the request.
Click Jacking: Clickjacking is an attack that tricks a user into clicking a webpage element which is invisible or disguised as another element. This can cause users to unwittingly download malware, visit malicious web pages, provide credentials or sensitive information, transfer money, or purchase products online. Typically, clickjacking is performed by displaying an invisible page or HTML element, inside an iframe, on top of the page the user sees. The user believes they are clicking the visible page but in fact they are clicking an invisible element in the additional page transposed on top of it. The invisible page could be a malicious page, or a legitimate page the user did not intend to visit – for example, a page on the user’s banking site that authorizes the transfer of money.
Target Blank Attacks: Target blank attacks are attacks that target an anchor tag with the target=“_blank” attribute, which opens a page in a new tab, and still has access to the old tab. This attack is done when a malicious person posts a link, a user clicks the link to the malicious site, and the tab is rewritten with malicious information to look like a trustworthy site. Anything entered on this malicious site, such as log in information, can be stolen.
(Edited: 2021-05-17)
6. Briefly explain how each of the following web attacks works: XSS, CSRF, Click Jacking, target blank attacks. <br> Nikki Gowan, Ajaypal Salh, Patricia Caceres <br> '''XSS (Cross-Site Scripting):''' XSS is a malicious script injection attack. The attack can happen on a website with a form in it when a malicious user or robot enters data in the form that has code instead. This code entered could do anything, and if for instance, the form is for a post on a website, any user that views the post could have cookies stolen, or something else bad depending on the script. <br> '''CSRF (Cross-site Request Forgery):''' A CSRF makes use of cookies to perform an attack. A website may store a cookie onto a user's machine in order to determine if they are logged into an account on the website.If the user visits other websites without logging out of their account, they may click a link that contains a URL designed to perform an action on the original website they had logged into. Because the user has a cookie on their machine that indicates they are logged in, a nefarious action may be processed by the server using their logged in account, without the user knowing. <br> A simple example is logging into a bank account, navigating to other websites and clicking a link intended to perform a transaction of some kind, which is then processed by a server because the server believes there is a logged in user performing the request. <br> '''Click Jacking:''' Clickjacking is an attack that tricks a user into clicking a webpage element which is invisible or disguised as another element. This can cause users to unwittingly download malware, visit malicious web pages, provide credentials or sensitive information, transfer money, or purchase products online. Typically, clickjacking is performed by displaying an invisible page or HTML element, inside an iframe, on top of the page the user sees. The user believes they are clicking the visible page but in fact they are clicking an invisible element in the additional page transposed on top of it. The invisible page could be a malicious page, or a legitimate page the user did not intend to visit – for example, a page on the user’s banking site that authorizes the transfer of money. <br> '''Target Blank Attacks:''' Target blank attacks are attacks that target an anchor tag with the target=“_blank” attribute, which opens a page in a new tab, and still has access to the old tab. This attack is done when a malicious person posts a link, a user clicks the link to the malicious site, and the tab is rewritten with malicious information to look like a trustworthy site. Anything entered on this malicious site, such as log in information, can be stolen.

-- Practice Final Thread
Question 1: Make a small PHP class Foo in the namespace your_first_name\great_project with method renderFoo() that echo's the word foo. Make a second class Goo in the namespace your_surname\some_other_project which subclasses the class Foo you just wrote and has a method renderGoo which echo goo.

Brian Tao, Aung Lin, Dat Nguyen
 
 
foogoo.php	
<?php 
 
namespace brian\great_project
{
  class Foo
  {
    function renderFoo()
    {
      echo "foo";
    }
  }
} 
 
namespace tao\some_other_project
{
  use brian\great_project\Foo; 
 
  class Goo extends Foo
  {
    function renderGoo()
    {
      echo "goo";
    }
  }
} 
 
index.php	 (for testing purposes)
<?php 
 
require_once("foogoo.php"); 
 
use brian\great_project\Foo;
use tao\some_other_project\Goo; 
 
$foo = new Foo();
$foo->renderFoo(); 
 
$goo = new Goo();
$goo->renderFoo();
$goo->renderGoo(); 
 
(Edited: 2021-05-17)
Question 1: Make a small PHP class Foo in the namespace your_first_name\great_project with method renderFoo() that echo's the word foo. Make a second class Goo in the namespace your_surname\some_other_project which subclasses the class Foo you just wrote and has a method renderGoo which echo goo. <br/> <br/> Brian Tao, Aung Lin, Dat Nguyen <pre> '''foogoo.php''' <?php namespace brian\great_project { class Foo { function renderFoo() { echo "foo"; } } } namespace tao\some_other_project { use brian\great_project\Foo; class Goo extends Foo { function renderGoo() { echo "goo"; } } } '''index.php''' (for testing purposes) <?php require_once("foogoo.php"); use brian\great_project\Foo; use tao\some_other_project\Goo; $foo = new Foo(); $foo->renderFoo(); $goo = new Goo(); $goo->renderFoo(); $goo->renderGoo(); </pre>

-- Practice Final Thread
Group 9 Question 9
Kate Kazantseva, Nhien Lam
a) JSONP
JSONP stands for JSON with Padding. It returns a JS function with JSON data in it. The purpose of JSONP is to do proxying from client side by using the script tag.
Example from lectures: This request https://www.yioop.com/s/news?f=json&callback=myHandleDataCode returns data that looks like: myHandleDataCode({"language":"en-US","link":"http...etc...etc ...});
b) Proxy
Proxy allows us to to make requests to other servers.
Example from lectures:
<?php define ('YIOOP_NEWS_URL', 'https://www.yioop.com/s/news/');
// look at incoming request fields $query = (!empty($_REQUEST['f']) && in_array($_REQUEST['f'], ["rss", "json"])) ?
    "?f=" . $_REQUEST['f'] : "";
$url = YIOOP_NEWS_URL . $query;
// Open the Curl session $request_handle = curl_init($url);
// Don't bother with the HTTP headers. Do bother with the content back curl_setopt($request_handle, CURLOPT_HEADER, false); curl_setopt($request_handle, CURLOPT_RETURNTRANSFER, true);
// Make proxy request $response_content = curl_exec($request_handle);
//determine the content-type of the response $pre_content_type = curl_getinfo($request_handle, CURLINFO_CONTENT_TYPE); $content_type = (empty($pre_content_type)) ? "text/html" : $pre_content_type;
// Set the outgoing proxy content type header("Content-Type: $content_type");
echo $response_content; curl_close($request_handle);
(c) REST (Representational State Transfer) - The idea of REST is that an application state or method is viewed as a resource. Each resource has a URL and one way to tack on to this URL a query to invoke the function and return results.
An example from the lecture slides, the Yioop News Service might be invoked with a line like: http://www.yioop.com/s/news?f=rss&limit=20&num=30 , where "http://www.yioop.com/s/news" is the resource and “f”, “limit”, and “num” are the arguments which control the returned value from the resource.
(d) C10K problem C10K is a problem when servers have over 10,000 simultaneous open connections and a limited thread pool. They are unable to handle all incoming requests and it will slow the servers down once these limits have been exhausted. For example, a server handles a large number of clients at the same time.
(Edited: 2021-05-17)
'''Group 9 Question 9''' Kate Kazantseva, Nhien Lam '''a) JSONP''' JSONP stands for JSON with Padding. It returns a JS function with JSON data in it. The purpose of JSONP is to do proxying from client side by using the script tag. Example from lectures: This request https://www.yioop.com/s/news?f=json&callback=myHandleDataCode returns data that looks like: myHandleDataCode({"language":"en-US","link":"http...etc...etc ...}); '''b) Proxy''' Proxy allows us to to make requests to other servers. Example from lectures: <?php define ('YIOOP_NEWS_URL', 'https://www.yioop.com/s/news/'); // look at incoming request fields $query = (!empty($_REQUEST['f']) && in_array($_REQUEST['f'], ["rss", "json"])) ? "?f=" . $_REQUEST['f'] : ""; $url = YIOOP_NEWS_URL . $query; // Open the Curl session $request_handle = curl_init($url); // Don't bother with the HTTP headers. Do bother with the content back curl_setopt($request_handle, CURLOPT_HEADER, false); curl_setopt($request_handle, CURLOPT_RETURNTRANSFER, true); // Make proxy request $response_content = curl_exec($request_handle); //determine the content-type of the response $pre_content_type = curl_getinfo($request_handle, CURLINFO_CONTENT_TYPE); $content_type = (empty($pre_content_type)) ? "text/html" : $pre_content_type; // Set the outgoing proxy content type header("Content-Type: $content_type"); echo $response_content; curl_close($request_handle); '''(c) REST''' (Representational State Transfer) - The idea of REST is that an application state or method is viewed as a resource. Each resource has a URL and one way to tack on to this URL a query to invoke the function and return results. An example from the lecture slides, the Yioop News Service might be invoked with a line like: http://www.yioop.com/s/news?f=rss&limit=20&num=30 , where "http://www.yioop.com/s/news" is the resource and “f”, “limit”, and “num” are the arguments which control the returned value from the resource. '''(d) C10K problem''' C10K is a problem when servers have over 10,000 simultaneous open connections and a limited thread pool. They are unable to handle all incoming requests and it will slow the servers down once these limits have been exhausted. For example, a server handles a large number of clients at the same time.

-- Practice Final Thread
Group 3, Number 3 Mark Silva, Ilan Granot, Sunny Xu
3. Explain with git commands how to do the following: (a) create a new repository, (b) make a branch, (c) create a patch, (d) make a version tag with your birthdate as the version number.
(a) To create a new repository, you first have to navigate to the project folder where your project is. Then execute the command "git init example_repository" within the terminal. This will then create a repository with the name example_repository in the current directory.
(b) To create a new branch the command is "git branch example_branch". This will create a branch in the current repository with the name example_branch.


(c) To create a new patch the command is "git format-patch rev1 rev2". Where rev1 and rev2 are the hashes of the commits.
(d) For version tags, the command is "git tag -a v03162000 -m "version 03162000". This will create a new tag with the name v03162000 with the message version 03162000

(Edited: 2021-05-17)
Group 3, Number 3 Mark Silva, Ilan Granot, Sunny Xu 3. Explain with git commands how to do the following: (a) create a new repository, (b) make a branch, (c) create a patch, (d) make a version tag with your birthdate as the version number. (a) To create a new repository, you first have to navigate to the project folder where your project is. Then execute the command "git init example_repository" within the terminal. This will then create a repository with the name example_repository in the current directory. (b) To create a new branch the command is "git branch example_branch". This will create a branch in the current repository with the name example_branch. 

(c) To create a new patch the command is "git format-patch rev1 rev2". Where rev1 and rev2 are the hashes of the commits. (d) For version tags, the command is "git tag -a v03162000 -m "version 03162000". This will create a new tag with the name v03162000 with the message version 03162000


-- Practice Final Thread
Group 7 Emily Chan, Sebrianne Ferguson, Christopher Louie
7. Give an application code example of each of the following in Javascript: (a) timer, (b) XHR request, (c) Promise, (d) Module Pattern.
 <!DOCTYPE html>
 <html lang="en" dir="ltr">
 <head>
  <meta charset="utf-8">
  <title>Question 7 for Final</title>
 </head>
 <body>
  <div id="test">
  <button type="button" onclick="changeText()">change text</button>
  </div>
  <script>
    // part c 
    let promise = new Promise((resolve, reject) => {
      // part a
      setTimeout(() => {
        console.log('five seconds have passed');
        resolve();
      }, 5000)
    });
    promise
      .then(() => {
        console.log('Promised passed');
      })
    // part d
    var moviestar = (function() {
      var movies = ["Gilda", "Cover Girl", "You Were Never Lovlier"];
        return {
            name: "Rita Hayworth",
            getName : function () {
                return name;
            },
            getMovies : function () {
                return movies;
            }
        }
    }());
    alert(moviestar.name); // rita hayworth
    alert(moviestar.movies); // undefined
    alert(moviestar.getMovies()); // Gilda, Cover Girl, You Were Never Lovlier
    
    // part b
    function changeText() {
      var request = new XMLHttpRequest();
      request.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
             document.getElementById("test").innerHTML = this.responseText;
          }
      };
      request.open("GET", "filename.txt", true);
      request.send();
    }
  </script>
 </body>
(Edited: 2021-05-17)
'''Group 7''' Emily Chan, Sebrianne Ferguson, Christopher Louie 7. Give an application code example of each of the following in Javascript: (a) timer, (b) XHR request, (c) Promise, (d) Module Pattern. <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Question 7 for Final</title> </head> <body> <div id="test"> <button type="button" onclick="changeText()">change text</button> </div> <script> // part c let promise = new Promise((resolve, reject) => { // part a setTimeout(() => { console.log('five seconds have passed'); resolve(); }, 5000) }); promise .then(() => { console.log('Promised passed'); }) // part d var moviestar = (function() { var movies = ["Gilda", "Cover Girl", "You Were Never Lovlier"]; return { name: "Rita Hayworth", getName : function () { return name; }, getMovies : function () { return movies; } } }()); alert(moviestar.name); // rita hayworth alert(moviestar.movies); // undefined alert(moviestar.getMovies()); // Gilda, Cover Girl, You Were Never Lovlier // part b function changeText() { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("test").innerHTML = this.responseText; } }; request.open("GET", "filename.txt", true); request.send(); } </script> </body>

-- Practice Final Thread
Group 5 (Atul Murali, Christopher Perez, Liuyang Zheng):
function addEvents() {
  var list = document.getElementsByTagName("DIV");
  
  var i = 0;
for(i = 0; i < list.length; i++) {
	div = list[i];
     div.addEventListener('click', function (event) {
     alert(div.innerHTML);
 });
    }
    
}
Group 5 (Atul Murali, Christopher Perez, Liuyang Zheng): function addEvents() { var list = document.getElementsByTagName("DIV"); var i = 0; for(i = 0; i < list.length; i++) { div = list[i]; div.addEventListener('click', function (event) { alert(div.innerHTML); }); } }
[ Next ]
X