All Flashcards

(338 cards)

1
Q

URL stands for?

A

Uniform Resource Locator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Amazonโ€™s full secure home URL

A

https://www.amazon.com

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

HTTPS stands for?

A

Hypertext Transfer Protocol Secure

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

The command to generate a React project inside the current directory.

A

npx create-react-app ./

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Install command needed to use SASS

A

npm install node-sass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

HTML stands for?

A

Hypertext Markup Language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

CSS stands for?

A

Cascading Style Sheets

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

BEM stands for?

A

Block Element Modifier

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

In the URL, https://www.amazon.com/home

What is the โ€˜amazon.comโ€™ part called?

A

Domain

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

In the URL, https://www.amazon.com/home

What is the โ€˜/homeโ€™ part called?

A

Path

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

IP Address stands for?

A

Internet Protocol Address

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is 104.59.62.31 an example of?

A

IP address

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

An IP address is a network deviceโ€™s ___ ___.

A

unique identifier

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

DNS Server stands for?

A

Domain Name System Server

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

PEMDAS stands for?

A

Parenthasis Exponent Multiplication Division Addition Subtraction

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Acronym used to represent the order of math operations in Javascript

A

PEMDAS

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

REPL stands for?

A

Read Evaluate Print Loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Acronym used to represent console operations.

A

REPL

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

List of JS falsy values.

A

false, 0, โ€œโ€, null, undefined, NaN

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

false, 0, โ€œโ€, null, undefined, NaN are Falsy values.

All other values are __.

A

Truthy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

The โ€œfor ofโ€ loop works on ___ like arrays and strings.

A

itterables

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

The โ€œfor inโ€ loop works on ___.

A

objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

CORS stands for?

A

Cross-Origin Resource Sharing

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Give HTML comment with โ€œsome msgโ€ inside.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
HTML5 declaration tag
26
Default shortcut key to toggle Word-wrap mode in VSC.
alt + z
27
What are the Font Awesome Icon types for fas, far, fal, fab, fad, in that order.
solid regular light brand duotone
28
Font Awesome icon to make svg 3 times larger.
fa-3x
29
``` # fill in the blank: \_\_\_(255, 255, 255, 0.4) returns a transparent shade of white ```
rgba
30
#f00
red
31
#0f0
green
32
#00f
blue
33
#fff
white
34
#000
black
35
#ff0
yellow
36
#f0f
fuchsia or magenta
37
#0ff
cyan or aqua
38
What is the hex code for the HTML color 'green'?
#008000
39
#0f0
line
40
box-shadow: 2px 2px 2px 2px rgba(0,0,0,.5) What are these values called from left to right?
horizontal offset vertical offset blur radius color
41
List all of the functions available for the CSS filter property.
blur() brightness() contrast() drop-shadow() grayscale() hue-totate() invert() opacity() saturate() sepia() url()
42
Return a random number from 0 to n (inclusive) using Javascript.
Math.floor(Math.random() \* (n + 1))
43
Return a random number from 1 to n (inclusive) using Javascript.
Math.floor(Math.random() \* n) + 1
44
Return a random number from 0 to n (excluding n) using Javascript.
Math.floor(Math.random() \* n)
45
Return a random number from m to n (inclusive) using Javascript.
Math.floor(Math.random() \* (n - m + 1)) + m
46
Convert the Grinning Face Emoji's Unicode number (U+1F600) into an HTML entity DECIMAL code. Hint: 1f600 hex = 128512 integer
๐Ÿ˜€ & # 1 2 8 5 1 2 ;
47
Convert the Grinning Face Emoji's Unicode number (U+1F600) into an HTML entity HEX code. Hint: 1f600 hex = 128512 integer
๐Ÿ˜€ & # x 1 f 6 0 0 ;
48
ALT codes without leading zeroes (ALT nnn) produce characters & symbols based on IBM Code Page 437 / DOS (codes 0 - 255) Note: Most do not correlate with their Unicode hex value
reminder
49
ALT codes with leading zeroes (ALT 0nnn) produce characters & symbols based on Windows Code Page 1252 (codes 01 - 0255) Note: The decimal code can be derived from their Unicode hex value Note2: These are a strict superset of ASCII wherein the first 128 codes are ASCII
reminder
50
Convert the Grinning Face Emoji's Unicode number (U+1F600) into a CSS string escape value. ie .someClass { content: 'emoji here' }
/1f600
51
Website for Emoji codes
emojipedia.org
52
VS Code Extention to lookup and insert emojis in their single character format using intellisence. ie :emojiName
Emoji Snippets
53
VS Code Extention to lookup and insert an emoji's encoded string according to the current file's language type. ie ji:emojiName
Emoji Code
54
Windows shortcut key to open Emoji Picker
Win + period(.) or Win + semicolon(;)
55
Given the below functions in a single file, how can you export all of them with the 'helpful' function being a default, in TWO lines of code. ``` const helpful = () =\> some code const sayHello = () =\> some code const listFoods = () =\> some code ```
export default helpful export {sayHello, listFoods}
56
Given the below export declaration in the "./test.js" file. How would you import all of its functions? export default helpful export {sayHello, listFoods}
import helpful, {sayHello, listFoods} from './test'
57
What does '000045'.slice(-3) return?
'045'
58
``` const randNum = Math.floor(Math.random() \* 1000) Use the .slice() array function and string litteral notation to return the random number as a string padded with zeros (ie '004' or '051') ```
`00${randNum}`.slice(-3) \\00765.slice(-3) -\> '765' \\004.slice(-) -\> '004'
59
A way to declare default props on a Class or Function based component.
Call FuncOrClassName.defaultProps = { ...someProps } before exporting.
60
POJO stands for?
Plain Old Javascript Object
61
setState() (class based version) with function callback that takes two params.
``` setState((prevState, props) =\> { //some code return newStateObject //the new object only needs to contain the //updated properties } ) ```
62
when using 'this' INSIDE of a function defined inside of a Class, the caller that later executes the function, loses the 'this' reference to the class ('this' becomes undefined, instead of pointing to class instance). You can use the following to fix the reference to this: 1. in the class constructor: this.someFunction = this.someFunction.bind(this) 2. when executing/when called: call-\> this.someFunction.bind(this)() 3. use an arrow function to define the function or execute the function within an arrow function
reminder
63
The arrow function binds 'this' to context of the object it was defined in, rather than the context of the object it's called on.
reminder
64
Command to install FontAwesome Pro
npm install @fortawesom/fontawesome-pro
65
Command to install FontAwesome Free
npm install @fortawesom/fontawesome-free
66
In order to use FontAwesome PRO globally, what two npm commands need to be run?
npm config set "@fortawesome:registry" https://fontawesome.com/ npm config set "//npm.fontawesome.com/:\_authToken" myProTokenId
67
Filename to create in a project to use FontAwesome PRO, locally.
.npmrc
68
What should be added into an local .npmrc to use FontAwesome Pro locally
``` @fortawesome:registry=https://npm.fontawesome.com/ //npm.fontawesome.com/:\_authToken=MyProAuthToken ```
69
Import statement to include FontAwesome PRO
import '@fortawesome/fontawesome-pro/js/all'
70
What are 4 special CSS properties to style the color and opacity of Duo-tone FontAwesome icons
- -fa-primary-color - -fa-primary-opacity - -fa-secondary-color - -fa-secondary-opacity
71
Class name to reverse the primary and secondary opacity for a FontAwesome Duotone icon?
fa-swap-opacity
72
With FontAwesome you need to import css instead of js when you need to dynamically change which icon is used via className. This is because the JS file generates and inserts an SVG. You rendered SVG doesn't change based on className. An it seems the script that generates the SVG is compile time. The CSS version of FontAwesome inserts a Unicode character which is inserted via the CSS class name. So you can dynamically swap out the icon via class name.
reminder
73
CSS property and value (property: value;) to make a square element circular.
border-radius: 50%;
74
A simple Math.random function/equations that returns True 25% of the time.
Math.random() \< .25
75
A simple Math.random function/equations that returns True 72% of the time.
Math.random() \< .72
76
A simple Math.random function/equations that returns false 65% of the time.
Math.random() \>= .65
77
CSS property: value to give only the bottom right of an element a 10px radius.
border-radius: 0 0 10px 0;
78
CSS property: value to give only the top left of an element a 15px radius.
border-radius: 15px 0 0 0;
79
A function to control multiple input fields with one handler. (controlled inputs) This pattern requires that each input field in the group have a matching name property as the value field in the state object. ie (reusing the same handler on mulple form inputs) const [formState, setFormState] = useState({ name1: value1, name2: value2, name3: value3, ...})
``` const handler = e =\> { setFormState(prev =\> { {...prev, [e.target.name]:e.target.value } }) } ```
80
In the below statement, [e.target.name] is called a \_\_\_. {[e.target.name]: e.target.value}
Computed Property
81
On initialization of a component, component code seems to be run twice, even though the return/render only runs once. values generated on the first execution of component code are used in the return/render. but values from the second run are received inside the subcomponents. this won't matter for static initial values, but dynamically generated values should be initialized outside of the component. ie v4() or Math.random() Tried useRef and generating values in separate function. Neither work. UseState does not preserve the first generated value either.
reminder
82
When updating state using an array of objects and needing to edit a single object's values, what pattern should be used to copy the prevState for editing. Note: this pattern is used instead of spreading the array, because the objects would be copied over by reference. AKA the arrays would be separate and unique but the objects and values inside would be tied together between the arrays.
const copyPrev = prevState.map(obj =\> ({...obj}))
83
set a gradient background going from bottom left to top right with colors red, green, then white. Place it an element good for applying the style site wide
body { background: linear-gradient(45deg, red, green, white); }
84
Can the linear-gradient css method be used with the properties background, background-color, or both?
background
85
The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.
reminder
86
const map1 = new Map(); map1. set('a', 1); map1. set('b', 2); map1. set('c', 3); What does map1.get('b') return?
2
87
How can you take an object parameter with unknown prop-name/value pairs, and assign them to the instance of the class in one line of code? ``` constructor(paramObj){ //line of code } ```
Object.assign(this, paramObj)
88
Use the Map() object to create a set called letterMap that tallies a count of each character in the following string. const ABA='abacadabagoose'
``` const letterMap = new Map() for (let ltr of ABA) { letterMap.set(ltr, (letterMap.get(ltr) || 0) + 1) } ```
89
You can conditionally set a function to an event property in react. This is a good way to remove or add events based on some condition. ie Do Something
Reminder
90
You can pass a call back to setState() as a SECOND parameter, which will be run AFTER the new state is set. i.e. setState({someStateProp: newStateValue}, execACallbackAfter) OR i.e. setState((prevSt, props) =\> { return newState}, execACallbackAfter)
Reminder
91
list the three things that can cause a component to rerender.
setState() is called. New prop value is received. forceUpdate is called
92
List the class based life cycle methods.
componentDidMount() componentDidUpdate(prevProps, prevState) componentWillUnmount()
93
For React, when setting a height relative to the body, don't forget that there is a root element between the body and app component.
Reminder
94
When using flex-direction of column, the containing element should have a height. Otherwise, thier is no space between the element to allow for arranging items in the vertical direction.
Reminder
95
One line of code to return a random float from -45 to +45 (not inclusive). only use Math.random() once.
Math.random() \* 90 - 45
96
One line of code to return a random float from -30 to +50 (not inclusive). only use Math.random() once.
Math.random() \* 80 - 30
97
How can you make a box-shadow extend inward toward the center and behind an element, instead of radiating outward
add inset in the css value/definition.
98
When using gsap animations on events, I should use the play, pause, reset, reverse methods instead of recalling the initial method. This should prevent the weird behavior I get when calling the gsap animation multiple times.
Reminder. (not yet proven)
99
Custom Array sorting: arr.sort((a, b) =\> someFunction()) if someFunction returns a value \< 0 a sorts before b if someFunction returns a value \> 0 b sorts before a if someFunction returns a value of 0 the sort stays the same.
Reminder
100
``` const arr = [0, 5, 1, 10, 99, 2, -2, 75, 6, 7, 8] sort the above array in numeric order from largest to smallest ```
arr.sort((a, b) =\> b - a)
101
log out the below fruit names, in order of count, descending. ``` const arr = [ {fruit: 'pear', cnt: 99}, { fruit: 'apple', cnt: 52 }, {fruit: 'orange', cnt: 1}, {fruit: 'Watermelon', cnt: 10}, {fruit: 'banana', cnt: 8}, {fruit: 'grape fruit', cnt: 0}, {fruit: 'peach', cnt: 2} ] ```
arr. sort((a, b) =\> b.cnt - a.cnt) arr. forEach(f =\> console.log(f.fruit))
102
log out the below fruit names, in order of name, descending. ``` const arr = [ {fruit: 'pear', cnt: 99}, { fruit: 'apple', cnt: 52 }, {fruit: 'orange', cnt: 1}, {fruit: 'watermelon', cnt: 10}, {fruit: 'banana', cnt: 8}, {fruit: 'grape fruit', cnt: 0}, {fruit: 'peach', cnt: 2} ] ```
``` arr.sort((a,b) =\> { // if a normally comes before b (a **b.fruit) return -1 return 0 }) ``` arr.forEach(f =\> console.log(f.fruit))**
103
const testObj = {prop1: 'test', cnt: 5} 1 Save the above object to local storage 2 Retrieve the object from local storage and assign it to a newVar as an object.
localStorage.setItem('testObj', JSON.stringify(testObj)) const newVar = JSON.parse(localStorage.getItem('testObj'))
104
What are 3 initial steps to adding React Router?
1. npm install react-router-dom 2. import {BrowserRouter} from 'react-router-dom' 3. Wrap component with in index.js
105
What React Router component is used to allow only the first matching route in a list of routes to be returned.
106
Write a basic React Route that matches the root path only and returns a component called Home.
107
Write a basic React Route that would always return an About component no matter what path it's compared to.
108
Use a React Router component that allow the navigation from the current path to a new path of /newpath/somewhere
109
What is the difference between NavLink and Link
NavLink allows you to pass a special property called activeClassName
110
What does the activeClassName property do for the NavLink component?
When the NavLink is clicked ALL rendered NavLinks that match it's "to" path will dynamically receive the className specified in the property, which is useful for dynamic styling. Note: Can use the "exact" property in the NavLink to prevent partial matches on multiple NavLink "to" paths.
111
Write a basic React Route that matches the root path only and returns a component called About that needs a prop of userName="Test User Jr".
test
112
What is the major reason for using the render prop instead of the component prop for passing components with props into the Route component. example: VS
component will cause the component to unmount and reinstantiated every time a path is matched (aka every time a a matching link is clicked), as where render will follow normal life cycle if a matching path is re-entered (aka, it may rerender by it won't be unmounted and reinstantiated)
113
What are the three props that are passed into a Route's component/render function?
history, location, match
114
What are the four properties found in the Router's component/render function's match property?
isExact, params, path, url
115
withRouter allows you to receive the history prop from react-router-dom, when the component is not from a Route component. You need to encapsulate the component with withRouter in it's export statement.
Reminider
116
1. Immediately redirects you to a new path. Elements after this component don't get rendered and the route that pushed you to the Redirect is not saved to history (aka, you cant get back to it) 2. props.history.push(somePath) Adds a new path to the history and updates the URL. Allows you to back into the page/url that got you to the push statement. 3 props.history.goBack() Will take you back to the previous route stored in history
Reminder
117
CSS property/value to set the background to a gradient? going from left to right angled 25degs to the right, off the vertical the first 10 percent solid white 10% to 75% grade from white to red 75% to 90% grade from red to green 90% to 100% solid green
background: linear-gradient( 115deg, white 0 10%, red 75%, green 90% 100% )
118
React router dom v6: List 7 commonly used named components
BrouserRouter Navigate Link NavLink Routes Route Outlet
119
React-router-dom v6: List the following hooks. Provides a function to traverse browser history (redirect URL). Provides an object to access and update the URL query params. Provides an object with access to param values.
useNavigate() useSearchParams() useParams()
120
ES7 React/Redux/GraphQL/React-Native snippets shortcut to insert a functional component with export using arrow functions
\_rafce
121
ES7 React/Redux/GraphQL/React-Native snippets shortcut to insert a functional component with export and propTypes using arrow functions
\_rafcp
122
What property do you use on a NavLink to prevent the isActive from being triggered when one of its child paths is active?
end=true OR just pass end
123
React Router Dom v6: In the 'to' property for Link, NavLink, Navigate components, you can specify an integer to direct it to jump forward or backward through browser history.
reminder
124
A function that takes a function as an argument, returns a function, or both?
Higher-Order function
125
A technique used to convert a function that takes multiple inputs to one that takes fewer (ie one or none) inputs by returning a function that takes the secondary input. You could then pass and execute the function as a callback since it will return a new function definition.
Currying Review Code-with-mosh Redux Video #7 "Currying" for great example.
126
const add = (a, b, c) =\> a + b + c Rewrite the above function with the Currying technique so that it can be passed into the below as a parameter. const addMore = (addFunc, someVal) =\> addFunc() + someVal The problem that you're trying to solve is the fact that addMore does not provide any values for the add function which you'll be passing to addMore.
const add = (a,b,c) =\> ( ) =\> a + b + c Now running add(2,4,6) returns a new function of ( ) =\> 2 + 4 + 6
127
A function that when the same values are passed in, it will always return the same result. ie const someFunc = (a, b) =\> a \* b someFunc(3, 2) will always return 6
Pure Function
128
Copying an object using the spread operator (ie {...someObj}) results in a shallow copy, meaning that nested objects are still copied by reference. You can copy the nested objects by overwriting their properties with another spread operator. ie { ...someObject, someSubObj: {...someObject.someSubObj}} OR You could copy using JSON.parse(JSON.stringify(someObject)) OR Use a third party library like immer
reminder
129
What are the three building blocks of a Redux application?
Action Store Reducer
130
A Redux Action can be thought of as an event A Redux Store can be thought of as a giant state object A Redux reducer can be thought of as an event handler (a PURE function that updates the store state when an event happens)
reminder
131
What are 4 steps to follow when building a Redux application?
Design the store Define the actions Create reducers Setup the store (based on reducers)
132
Given a single reducer exported by default from a file './reducer', write 4 lines of code to create a Redux store using the reducer and export it by default.
import {createStore } from 'redux' import reducer from './reducer' const store = createStore(reducer) export default store
133
The Redux store object is composed of 5 properties (all methods). With one being Symbol(observable), what are the other 4 along with the params they accept?
dispatch(action) subscribe(listener) getState() replaceReducer(nextReducer)
134
What does the command **pwd** stand for?
Print working directory
135
What is the below array function? Takes a function that loops though each element, returns false and exits the loop if any of the functions returns false, otherwise returns true
.every()
136
What is the below array function? Takes a function that loops though each element, returns a new array with each element being the return value of each function execution.
.map()
137
What is the below array function? Takes a function that loops though each element, returns a new array with each of the original elements where the executed function returned true.
.filter()
138
What is the below array function? Takes a value and returns true if the value is equal (triple equal) to one of the elements in the array and otherwise returns false.
.includes()
139
What is the below array function? Takes a function that loops through each element, returns the first element where the function returns true.
.find()
140
Order of events for an event handler with UseState event handler starts execution hits setVarible call runs any setVariable fn code **schedules** variable update from return value continues to end of event handler code with original variable value state gets updated component code is run through component is rendered all useEffects that include the state variable dependency or No dependency are run in order.
141
**Debouncing** is a technique for having a timeout to wait to see if a user is completed entering data before taking an action. useEffect, its cleanup return, with a setTimeout function is a good way to perform this technique
reminder
142
An example of debouncing in react. ## Footnote useEffect(() =\> { const identifier = setTimeout( setFormIsValid( enteredEmail.includes('@') && enteredPassword.trim().length \> 6 ) , 500) return () =\> { clearTimeout(identifier) } }, [enteredEmail, enteredPassword])
reminder
143
Write the import statement and the line of needed to Portal a render of component to a div element with the id="overlays"
import ReactDOM from 'react-dom' ReactDOM.createPortal(, document.getElementById('overlays'))
144
Write a file to create/initialize/export a context object to store a list of users with addUser and removeUser actions.
import React from 'react' const UserContext = React.createContext({ users: [], addUser: user =\> {}, removeUser: id=\> {} }) export default UserContext
145
Make a UserContext Provider wrapping Component file using the context from the below user-context.js file. import React from 'react' const UserContext = React.createContext({ users: [], addUser: user =\> {}, removeUser: id=\> {} }) export default UserContext
import UsersContext from "./users-context" const UsersProvider = ({children}) =\> { const addUserHandler = user =\> {} const removeUserHandler = id =\> {} const usersContext = { users: [], addUser: addUserHandler, removeUser: removeUserHandler } return ( \< UsersContext.Provider value={usersContext} \> {children} \< /UsersContext.Provider \> ) } export default UserProvider
146
Every time a react component is loaded all of its children will be reloaded and all of their children, regardless of whether the props on the children were changed. If you wrap the child's export with React.memo() this will prevent the child from being reloaded except for when it's props have actually changed. Note: any reference type props (like functions) passed to the child elements would be considered as a change in props, unless you create them using useCallback.
reminder
147
If multiple state variables are changed in a single execution the component does NOT rerender multiple times. Instead, all of the updates are processed as a group before the component rerenders. The exception is any setVar calls during that execution that nested inside of an async function like setTimeout. The individual setVar calls within the group can be run in any order. Thats why multiple calls to the same setVar need to use prev state AND setVar that depend on other other setVar values should be combined and updated using useReducer. useEffect will only be called once, even if more than one of its dependencies were changed. Key point: multiple setVar calls side by side in an execution only causes on rerender Key point2: Multiple set calls -\> all setvar are processed and updated -\> One render -\> One execution for each matching useEffect call REVIEW React course with Max S -\> Sec 12 (video 160 mostly) Understanding scheduling and batching IMPORTANT NOTE In async functions any setVar calls after the first await statement gets executed individually and EACH will cause a rerender (ie batch stops after await statement). The same happens inside a setTimeout call, except an await call is not needed to separate the calls.
reminder
148
useMemo is the same as useCallback, exept you use it for arrays/objects instead of functions. Common to use on stuff like sorting array, to prevent having to resort even though the array hasn't changed. If using on a prop, you need to call it on the parent var that's passing the prop and when processing the prop inside the child.
reminder
149
API stands for?
Application Programming Interface
150
When passing a callback function to an event into another function, using .bind() will allow you define the 'this' context as well as pass in additional parameter values. the additional parameter values will be place before the internally defined parameters. https://academind.com/tutorials/function-bind-event-execution ie Normally you would not be able to pass the below MyFnc var to onClick, because onClick would only pass you the event var. bind allow s you to include boundVal and accept 32 into it's definition. const myFnc = (boundVal, event) =\> boundVal onClick={myFnc.bind(null, 32)}
reminder
151
If you have multiple setUseStateVar executed in succession for the same variable, the prevState value in the function call version is needed to access the values returned from other calls in that execution context AND the **last executed**'s return value is the one that will be applied on the next render. ie the set calls are put on the stack in order and are executed in order (still as a batch for that render cycle). If you use the var value, it will only give you the value from the last render. If you use the prevState, you'll get the value passed from the prev set call in order(time to process the function does not interrupt the order).
reminder
152
What button type property does not trigger a submit on a parent form?
type = "button"
153
List out the 9 common folders you will use to build an express API. Plus a 10th one that will be generated with sequilize setup.
1. config 2. controllers 3. database 4. middleware 5. public 6. router 7. socket 8. uploads 9. validators 10. models
154
List the step/code to setup Sequelize for querying ms SQL.
1. npm install sequelize 2. npm install sequelize-cli -g (needs to be install globally since it runs from the command line as its own function) 3. npm install tedious (this is the ms SQL driver.) 4. create a .sequelizerc file in the root server folder with the following content const path = require('path') module.exports = { 'config': path.resolve('./config', 'database.js'), 'models-path': path.resolve('models'), 'migrations-path': path.resolve('database', 'migrations'), 'seeders-path': path.resolve('database', 'seeders') } 5. sequelize init (command to generate the above files/config) 6. update/fix the generated ./config/database.js file by: a. export the generated object (using module.exports = ) b. update the config values (ideally pulling in values from require('dotenv').config() 7. generate db model code into ./database/migrations path a. sequelize model:create --name [SomeTableName] --attributes [fieldName1:string, fieldName2:integer,etc...] b. note that nothing is enclosed in quotes and don't include brackets 8. update model code with defaults, unique markers, etc as needed 9. sequelize db:migrate (to execute model code and generate database tables, running a second time will not update the database) a. if you want to rerun the command and update the migration, must drop using undo: (see b.) b. sequelize db:migration:undo 10. sequelize seed:create --name users (generates seeder code to help add seed data) a. code is generated in the ./database/seeders directory b. edit code file to insert your made up records. file contains commented code to remind how to do insert objects. The down: property will allow you to write delete code. 11. sequelize db:seed:all (to run insert commands created above) a. sequelize db:seed:undo (to reverse)
155
Node module name used to encrypt passwords
bcrypt
156
Write 2 lines of code to: 1. Import bcrypt into node 2. Use it to save a hashed version of plainTextPwd to a variable called hashedPassword
const bcrypt = require('bcrypt') const hashedPassword = bcrypt.hashSync(plainTextPwd, 10) //10 is the number of hashing rounds
157
NOW( ) is used to get the current date/time in postgreSQL. What is the equivalent command in MSSQL?
GETDATE( )
158
Write statements with bcrypt to determine if the encryptedPwd var is equal to the submittedPwd var. Include the import statement and save the result to passwordIsValid variable.
const bcrypt = require('bcrypt') const passwordIsValid = bcrypt.compareSync(submittedPwd, encryptedPwd)
159
const user = { name: 'jordan', state: 'IL', password: 'mysecretpassword' } Write one line of code to remove the password prop completely from this user object.
delete user.password
160
Write a line of node code to generate a random 64 character hex coded string and save it to a var call secretKey.
const secretKey = require('crypto').randomBytes(64).toString('hex')
161
Write code for node, including the import statement to generate a token from a 'user' object, with the encryption key = someKey, and expires after a week. Save it to a var called token.
const jwt = require('jsonwebtoken') token = jwt(user, someKey, {expires: 60 \* 60 \* 24 \* 7} //expires is in seconds for integer and ms for string number.
162
What is a good validation package I could use in my node API code ?
express-validator
163
What are 9 npm packages I should install by default in my node api's
express express-validator bcrypt dotenv jsonwebtoken sequelize + tedious and/or mssql helmet cors nodemon --save-dev
164
Write out 8 variables likely used in .env file for api (use lower case for easier typing here, but use upper case in app)
app\_key app\_url app\_port db\_server db\_user db\_password db\_name db\_port
165
write 1 line of code that makes process.env object available with .env file values.
require('dotenv').config( )
166
1 What are the 4 property names that you should export from .sequelizerc as part of an object that describes the folder/file path for each property. 2. what function are you going to use to generate the values for each config
config models-path migrations-path seeders-path path.resolve('folderPath', [filename])
167
list out the main properties dbConn.js should export hint) {prop1, prop2, prop3, prop4, prop5: {subProp}}
user password database server options.trustServerCertificate
168
What property name and value do you need to add to fields in a sequelize migration template for MS SQL to: 1. ) apply the current time. 2. ) specify that the field should be unique
defaultValue: sequeslize.literal('GETDATE( )') unique: true
169
List all sequalize-cli commands
sequelize db:migrate Run pending migrations sequelize db:migrate:schema:timestamps:add Update migration table to have timestamps sequelize db:migrate:status List the status of all migrations sequelize db:migrate:undo Reverts a migration sequelize db:migrate:undo:all Revert all migrations ran sequelize db:seed Run specified seeder sequelize db:seed:undo Deletes data from the database sequelize db:seed:all Run every seeder sequelize db:seed:undo:all Deletes data from the database sequelize db:create Create database specified by configuration sequelize db:drop Drop database specified by configuration sequelize init Initializes project sequelize init:config Initializes configuration sequelize init:migrations Initializes migrations sequelize init:models Initializes models sequelize init:seeders Initializes seeders sequelize migration:generate Generates a new migration file sequelize migration:create Generates a new migration file sequelize model:generate Generates a model and its migration sequelize model:create Generates a model and its migration sequelize seed:generate Generates a new seed file sequelize seed:create Generates a new seed file
170
What does ORM stand for, in relation to databases?
Object Relational Mapping
171
What is the additional install package name and corresponding dialect property value needed with sequelize for each of the following databases? 1 Postgres 2 MySQL 3 MariaDB 4 SQLite 5 Microsoft SQL Server
package name / dialect string value 1 pg pg-hstore / postgres 2 mysql2 / mysql 3 mariadb / mariadb 4 sqlite3 / sqlite 5 tedious / mssql
172
findById() is Sequalize was replaced by what after version 5
findByPk
173
What does OWASP stand for?
Open Web Application Security Project
174
What are the top ten web app security risks identified by OWASP?
2021 compaired to 2017 https://owasp.org/www-project-top-ten/ A01:2021-**Broken Access Control** moves up from the fifth position; 94% of applications were tested for some form of broken access control. The 34 Common Weakness Enumerations (CWEs) mapped to Broken Access Control had more occurrences in applications than any other category. A02:2021-**Cryptographic Failures** shifts up one position to #2, previously known as Sensitive Data Exposure, which was broad symptom rather than a root cause. The renewed focus here is on failures related to cryptography which often leads to sensitive data exposure or system compromise. A03:2021-**Injection** slides down to the third position. 94% of the applications were tested for some form of injection, and the 33 CWEs mapped into this category have the second most occurrences in applications. Cross-site Scripting is now part of this category in this edition. A04:2021-**Insecure Design** is a new category for 2021, with a focus on risks related to design flaws. If we genuinely want to โ€œmove leftโ€ as an industry, it calls for more use of threat modeling, secure design patterns and principles, and reference architectures. A05:2021-**Security Misconfiguration** moves up from #6 in the previous edition; 90% of applications were tested for some form of misconfiguration. With more shifts into highly configurable software, itโ€™s not surprising to see this category move up. The former category for XML External Entities (XXE) is now part of this category. A06:2021-**Vulnerable and Outdated Components** was previously titled Using Components with Known Vulnerabilities and is #2 in the Top 10 community survey, but also had enough data to make the Top 10 via data analysis. This category moves up from #9 in 2017 and is a known issue that we struggle to test and assess risk. It is the only category not to have any Common Vulnerability and Exposures (CVEs) mapped to the included CWEs, so a default exploit and impact weights of 5.0 are factored into their scores. A07:2021-**Identification and Authentication Failures** was previously Broken Authentication and is sliding down from the second position, and now includes CWEs that are more related to identification failures. This category is still an integral part of the Top 10, but the increased availability of standardized frameworks seems to be helping. A08:2021-**Software and Data Integrity Failures** is a new category for 2021, focusing on making assumptions related to software updates, critical data, and CI/CD pipelines without verifying integrity. One of the highest weighted impacts from Common Vulnerability and Exposures/Common Vulnerability Scoring System (CVE/CVSS) data mapped to the 10 CWEs in this category. Insecure Deserialization from 2017 is now a part of this larger category. A09:2021-**Security Logging and Monitoring Failures** was previously Insufficient Logging & Monitoring and is added from the industry survey (#3), moving up from #10 previously. This category is expanded to include more types of failures, is challenging to test for, and isnโ€™t well represented in the CVE/CVSS data. However, failures in this category can directly impact visibility, incident alerting, and forensics. A10:2021-**Server-Side Request Forgery** is added from the Top 10 community survey (#1). The data shows a relatively low incidence rate with above average testing coverage, along with above-average ratings for Exploit and Impact potential. This category represents the scenario where the security community members are telling us this is important, even though itโ€™s not illustrated in the data at this time.
175
What does TDD stand for?
Test Driven Development
176
What are the development phases of TDD
Red, Green, Refactor
177
What is the Red phase of TDD?
Write a test for the expected behavior
178
What is the green phase of TDD
Write the code for the red test (expected behavior test) to pass
179
What is the Refactor phase of TDD
Clean up your code (remove code duplication and etc)
180
Jest naming convention is that its root folder be "\_\_test\_\_" and files have an extension of .spec.js or .test.js and are in pascal case (ie UserReg.spec.js)
reminder
181
What is the shortcut key to rename a highlighted file in vscode
F2
182
What is the shortcut key to autoformat current file in vscode
Shift + Alt + F
183
What is the shortcut key to switch over to the Explerer window in vscode
ctrl + shft + e
184
How do you search for or edit shortcut keys in vscode and which are some that I should edit on a new system.
Ctrl + shft + p search for "Preferences: open keyboard shortcuts" Should update explorer.newFile to ctrl + n should update explorer.newFolder to ctrl + shft + n workbench. action.files.save to ctrl + s workbench. action.files.saveAll to ctrl + shft + s
185
What are 7 datatypes in Sequelize along with their corresponding datatypes in MySQL? Sequelize dt / MySQL dt
STRING / VARCHAR(255) TEXT / TEXT BOOLEAN / TINYINT(1) INTEGER / INTEGER FLOAT / FLOAT STRING(2000) / VARCHAR(2000) DATE / DATE
186
What are the 5 properties you can use to configure your model's table (the third parameter in the define( ) function) along with the value type that they accept
timestamps / boolean freezeTableName / boolean tableName / string version / boolean paramoid / boolean
187
For the .sync() function in Sequelize, what are two alternate objects you can pass to change the way it syncs
.sync({force: true}) .sync({alter: true})
188
Describe the 3 properties you can pass .define() when creating a model, in order.
table name as a string an object modeling out the field values for that table options for creating our table
189
How would you add your own auto incrementing - primary key user\_id field to the modeling parameter when configuring the definition of a Sequelize model
{ user\_id: { type: Sequelize.dataTypes.INTEGER, autoIncrement: true, primaryKey: true } }
190
You have two models (User and Product) defined for a sequelize instance (called sequelizeApp1). A.) How would you call the sync methed to build just the User table? B.) How would you sync all tables?
A.) User.sync( ) B.) sequelizeApp1.sync( )
191
What is the property and value to prevent nulls in a sequelize model definition?
allowNull: false
192
Sequelize note: You can use: .build( ) together with .save( ) to create a saveable object separately before saving it to the database. You might do this is you need to run some additional changes/executions to the object before saving it to the database. OR You can use: .create( ) which does the build and save operations all at once.
reminder
193
List out 6 common sequalize data action methods (not query methods) and what they do
.create( ) - builds, saves to db, and returns a data object .build( ) - builds and returns a data object, does not save to db .save( ) - saves/updates a data object to the database (after build/create) .reload( ) - reverts the data object back to its origonal build/create state .destroy( ) - deletes the data object (undos save operation) .bulkCreate([]) - builds, saves to db, and returns an array of data objects
194
write sequelize queries to return the following given a User model and 'sequelize' db instance. ## Footnote 1) select \* from users -- returning a sequelize data array 2) select username, password from users -- returning a sequelize data array 3) select username as 'login\_id', password from users -- returning a sequelize data array 4) select SUM(age) as 'how old' from users -- NOTE: using an 'as alias' is required so that sequelize can return an object property name for the sum of the age. it does not default 'age' 5) select \* from users -- excluding the password and age field 6) select \* from users where age = 45 7) select username, password from users where age=45 8) select top 2 \* from users 9) select \* from users order by username DESC, age ASC 10) select username, SUM(age) as 'sum\_age' from users group by username 11) select \* from users where age=25 **or** username='pizza' 12) select \* from users where age **\>** 25 13) select \* from users where char\_length(username) = 5 14) select \* from users -- RETURN result as POJO
User.findAll() User.findAll({ attributes: ['username', 'password']) User.findAll({attributes: [['username', 'user\_id'], 'password'] User.findAll({attributes: [[sequelize.fn('SUM', sequelize.col('age), 'how old')]] User.findAll({attributes: {exclude: ['password', 'age']}}) User.findAll({where: {age:45}}) User.findAll({attributes: ['username', 'password'], where: {age:45}) User.findAll({limit: 2}) 9) User.findAll({ order: [['username', 'DESC'], ['age', 'ASC'] ] 10) User.findAll({ attributes: ['username', [sequelize.fn('SUM', sequelize.col('age')), 'sum\_age'] ], group: 'username' }) 11) User.findAll({ where: { [**S**equelize.Op.**or**]: { age: 25, username: 'pizza' } } }) 12) User.findAll({ where: { age: { [Sequelize.Op.gt]:25 } } }) 13) User.findAll({ where: sequelize.where( sequelize. fn('char\_length', sequelize.col('username')), 5 ) } 14) User.findAll({ raw: true })
195
Sequelelize: Updating Where (User model, users table, sequelize db instance, Sequelize class) 1) update users set username='tom' where age=45
1) User.update({ username: 'tom'}, {where: {age: 45}})
196
Sequelelize: Delete Where (User model, users table, sequelize db instance, Sequelize class) ## Footnote 1) delete from users where username='pizza' -- returns number of deleted in array container 2) delete from users -- delete all users, not the table
1) User.destroy({where: {username: 'pizza'}}) 2) User.destroy( {truncate: true})
197
Sequelelize: select utility methods (User model, users table, sequelize db instance, Sequelize class) select MAX(age) from users select SUM(age) from users select SUM(age) from users where username='tom'
User.max('age') User.sum('age') User.sum('age', {where: {username: 'tom'}})
198
If you want to await a group of asynchronous functions to complete before proceeding execution, what tool can you use. ie. step 1 await single function step 2 await a single execution step 3 await for the completion of multiple functions BUT allow them to run asynchronously (in any order at same time) step 4 continue execution
Promise.all( [...eachAsyncFunc( )] )
199
What does IIFE stand for?
Immediately invoked function expression
200
List other Sequelize query methods other than .findAll() Hints: 1) returns a result base on Primary Key 2) returns the first row it finds that matches it's conditions. If now conditions given it will just return the first row in the table. 3) queries and returns a record and if not found, it will generate and insert the record 4) return results same as findAll plus it gives a count of records returned
1) .findByPk( ) 2) .findOne( ) 3) .findOrCreate( ) 4) .findAndCountAll()
201
An object key defined with square brackets is called a \_\_\_ ie { [nameVar]: someValue }
Computed property
202
What are the commands to generate a GUID/UUID value for mssql, MySQL, postgres, and sqlite respectively? Note, that it seems that you can use all of these as default generators, except in sqlite, which appears to only accept static defaults.
mssql / newid( ) postgres / gen\_random\_uuid() mysql / uuid( ) sqlite / hex(randomblob(16))
203
Code to get the current dialect value when marking up the up( ) function in sequelize migrations.
queryInterface.sequelize.options.dialect
204
You can use the following vscode settings to enable emmet for all js files. However it's better not to add it and name react components with .jsx, as emmet is on by default for that extension. Also, when emmet is on in .js files that are not react components, it dirties up code completion. ## Footnote "emmet.includeLanguages": { "javascript": "javascriptreact" },
reminder
205
What are the two common obj.method( )'s that you will use for the up/down methods in your seeder file?
queryInterface.bulkInsert() for up queryInterface.bulkDelete() for down
206
What are the two common obj.method( )'s that you will use for the up/down methods in your migrations file?
queryInterface.createTable( ) for up queryInterface.dropTable( ) for down
207
Show math to convert 0b101101 to decimal
45 (25 \* 1) + (24 \* 0) + (23 \* 1) + (22 \* 1) + (21 \* 0) + (20 \* 1) 32 + 0 + 8 + 4 + 0 + 1 = 45
208
Show math to convert 0xAB9 to decimal
2745 (162 \* 10) + (161 \* 11) + (160 \* 9) (256 \* 10) + (16 \* 11) + (1 \* 9) 2560 + 176 + 9 = 2745
209
With sequelize class modeling pattern using the autogenerated index ## Footnote Class pattern with generated index file: index will automatically associate the db connection/instance from config index will use the modelName property for the defined export name. ie modelName.findOne( ) index does not care about the file name nor the classname, so you can name them whatever you want. index provides named exports of { sequelize, Sequelize, eachOfYourModelNames} you must specify timestamps: false if your table/migration does not use updatedAt & createdAt, even if your model does not have them listed in fields (otherwise queries will try to select them) If not using an 'id' column you must add modelClassName.removeAttribute('id') after the init call (before the return call) to remove this default field and to keep it from generating in queries. Also, some queries like findOne will still use 'id' to generate Order by clauses. This can be fixed by specifying an order: value. Alternativly, specifying an alternate PK field will correct the whole issue for this model. the call to findOne() or any other queries will automatically query the tableName = modelName pluralized. You can add a tableName property to the model and specify whatever table name you want the model to query against.
reminder
210
using Sequelizes' .define( ) method to generate model against autogenerated index.js ## Footnote This will work the same as with the generated Model class pattern, just need to export a (sequelize, DataTypes) =\> { //some code }function that returns the object from executing sequelize.define( ). The modelName that is exported by name from index.js comes from the first parameter passed to define. The tableName will be autogenerated from the modelName (pluralized by default unless you pass the freezeTableName: true option). You can pass a tableName: 'someName' option to use a completely different tableName. pass timestamps: false option to stop queries from assuming table has createdAt, updatedAt fields if the table does not have an 'id' field, you need to define an alternate primaryKey fields OR call removeAttribute on the returned sequelize.define( ) variable before returning from the exported function index.js does not care what the filename or return variable name is.
reminder
211
Sequelize assumes your tables will have 'id', 'createdAt', 'updatedAt' fields. If you don't: Sequelize injects an 'id' field into all models by default. You can define an alternate PK field and this default will be overwritten. If you don't have an alternate PK field and no 'id' field, you must use modelName.removeAttribute('id') before using query functions with it. Also, any automatically ordered queries will default with 'id', so you'll need to overwrite with an order: 'something' option. Also, the timestamp option needs to be set to false if you don't have timestamp fields in your table.
reminder
212
the autogenerated models/index.js file, when imported, will: loop through each model file and execute the returned function passing in a dbInstance generated by config. It will return the models created as properties, including a Sequelize property and sequelize property (ie dbInstance) If I import the models/index.js file for its functionality, every model file must have the module.exports signature of (sequelize, DataTypes) =\> modelObj (modelObj can be created with .define( ) or the Model class). Any other type of exports will cause index.js' code to fail. I can separately import these specially exported modules and just pass them my own dbInstance to override the sequelize dbInstance generated by modules/index.js
reminder
213
How do I include a partial scss or CSS file into my current one? ie a \_variables.scss in a ../assest/scss folder
@import '../assets/scss'
214
I have the below \_variables.scss file in '../assets/scss'. What do I add to the file to export the variable for use in a jsx file. Once exported, how do I import it and set a variable equal to one of the values in Javascript? ## Footnote $bg-color: 'gray'; $bg-main: 'blue';
add to variable.scss for export: :export { bgColor: $bg-color; bgMain: $bg-main; } to import: import variables from '../assets/scss/\_variables.scss' to use: const { bgMain } = variables //used destructuring here but can use regular assigning also.
215
What are the 4 css property names to set each of the individual border radiouses?
1. border-top-left-radius 2. border-top-right-radius 3. border-bottom-left-radius 4. border-bottom-right-radius
216
Write code that exports a configured axios object that connects to API at HTTP://localhost:3001 and tell it to use JSON. Don't forget the import and export code.
import axios from 'axios' export default axios.create({ baseURL: 'http://localhost:3001', headers: { Accept: 'application/json' } })
217
What does the Optional Chaining operator (ie ?. ) do?
It can be placed before any property on an object, array index call ( ie [] ), or function execution (ie ( ) ) to escape throwing an error if the object/array/func is undefined. Instead it will return undefined.
218
someObj?.someProp What is the ?. operator, attached to this object, called?
Optional Chaining operator
219
220
With Sequelize queries on Models that contain getters, any call for raw:true will not execute the getter. In order for the getter values to be process, you must be pulling the value from a sequelized object. So, you need to use .toJSON() or call the property directly on the sequelized object, to get the calculated value. ie seqReturnObj.toJSON() or seqReturnObj.someCalculatedProperty.
reminder
221
Helmet can overwrite CORS policy, and has blocked img src=http...somefile.svg elements for some reason. You can use helmet and disable its cors policies by calling it as: app. use(helmet({crossOriginResourcePolicy: {policy:'cross-origin'}})) https: //helmetjs.github.io/
reminder
222
223
Sequelize provides constraint properties and validator properties. Constraint properties apply on db sync or migration only and are only obeyed as a result of database errors. IE javascript will not stop the execution of the sql query. Validation properties are checked before javascript sends a sql query to the database. stuff like unique and all properties inside of validator are Validation properties. stuff like primaryKey, autoIncrement are constraint properties. things like allowNull and defaultValue can be either
reminder
224
Terminal Shortcuts 1. Close current focused tab while in command prompt --- custom * Terminal: Kill the Active Terminal Instance, When: terminalFocus 2. add a tab 3. go up/left one tab while in command prompt 4. go down/right one tab while in command prompt 5. move focus to tab list 6. remove selected tab while in tab list 7. rename selected tab while in tab list 8. move back to command prompt while in tab list 9. scroll up / down
1. ctrl + shft + F4 2. ctrl + shft + ` 3. ctrl + PgUp 4. ctrl + PgDown 5. ctrl + shft + \ 6. Del 7. F2 8. Enter (on selected tab) 9. crtl + shft + PgUp / PgDown
225
With the following axios call in a try catch block. 1) How do you access the data if the call is successful and 2) how do you get the returned API's error data (not the HTTP error)? try { const result = await axios.get(url, { email, password }) console.log( ___ ) // 1. access returned data ie fill in the blank } catch (err) { console.log( ___ ) // 2. access error data sent from api server, not the HTTP error }
* result.data * err.response.data
226
Set the bearer/token on this axiosObj variable using the value stored in token.
axiosObj.defaults.headers['Authorization'] = `Bearer ${token}`
227
What should the client side service functions do (in reference to auth, for now)
Make call with the axios api objects, receiving and passing in needed params. The service will return the desired result data from the axiosObj calls or throw the error received If successful user authentication, the service will apply an Authorization token to the axios API object ie * **try** * const result = await axiosObj.post(somthing) * axiosObj.defaults.headers['Authorization'] = `Bearer ${token}` * return result.data * **catch**(error) * throw error
228
In a controller, how do you get the Bearer token?
req.headers['authorization'] //authorization must be lower case
229
What are the 4 config properties for configuring a Multer uploader middleware? IE multer({prop1, prop2, prop3, prop4})
storage or dest fileFilter limits preservePath
230
What method on the multer object do you use to create a storage config object? What 2 properties does this config object require?
.diskStorage( { } ) destination filename
231
What are the properties of a file returned by multer?
1. **fieldname** 2. **origionalname** 3. **encoding** 4. **mimetype** 5. **size** 6. **destination** - files stored in DiskStorage 7. **filename** - files stored in DiskStorage 8. **path** - files stored in DiskStorage 9. **buffer** - files stored in MemoryStorage
232
When passing a fileFilter function to multer, the function receives req, file, and cb. Within the function, you execute cb(null, false) to reject the file, cb(null, true) to accept the file, and cb(new Error('Some error message')) to throw an error.
reminder
233
234
With file uploads, you can add a third argument (as an object) to the axios call that has an onUploadProgress property that takes a callback function to be run on change of upload progress. The callback passes a progressEven argument that is an object that contains the uploaded and total values.
reminder
235
to use the onUploadProgress event from an imported axios service to update state values, you need to define the call back function or the whole options objected inside your compont (setting your state in the callback's definition) and pass your definition to the axios service function.
reminder.
236
What are the install package names for socket.io on the 1.) client and on the 2.) server
1. socket.io-client 2. socket.io
237
What are the two packages that need to be installed for internationalization in a React project?
i18next react-i18next
238
Write out the basic template to configure and initialize i18n for react to be able to translate 'hello world' and water between english ( en ) and Spanish (es). Including imports.
* import i18n from 'i18next' * import { initReactI18next } from 'react-i18next' // note the capital I * i18n * .use( initReactI18next ) * .init({ * resources: { * en: { * translation: { * "helloWorld": "hello world", //notice use of JSON for word list, not POJO * "water": "water" * } * }, * es: { * translation: { * "helloWorld": "hola world", //notice use of JSON, not POJO * "water": "agua" * } * } * }, * lng: 'es', * fallbackLng: 'en', * interpolation: { * escapeValue: false * } * })
239
You don't make an export statement from a plain .json file. You can simply import from the file into a variable with any name. No need to parse either. ie import anyName from './someFile.json'
reminder
240
List all the property names used in the i18next init method. tab in (3spaces) sub properties
1. resources 2. (languageAbbreviation) 3. translation 4. (wordLabelForTranslation) 5. lng 6. fallbackLng 7. interpolation 8. escapeValue
241
You can create a file for the purpose of executing a function (imported, IFEE, defined). You would would write or inport the function and execute it in the file. You would not export the function from the file. Just importing the file into your app would trigger the execution. ie import './someFileWithExecutedFunc'
reminder
242
How do you access your translations or change language? Write the import and lines of code to do both.
* import { useTranslations } from 'react-i18next' * const { t, i18n } = useTranslations( ) * const textExample = t( 'translatedTextKey' ) * i18n.changeLanguage( 'languageKey' )
243
When adding your own primary key in a sequelize model, you must define it with primaryKey and a an autoIncrement or defaultValue of DataType.UUIDV4 If no id at all then Model.removeAttribute('id') If you use 'id' you can omit it from model unless, you need to default a UUID KEY POINTS: 'id' integer primary key is defaulted into the model and is the only field that is auto excluded from inserts ANY TIME you want the database to generate the default for an insert, you must use exclude the attribute
reminder
244
app.use(helmet({crossOriginResourcePolicy: {policy:'cross-origin'}}))
Reminder
245
REMINDER. Don't try to set the value on a input of type file. You might get the following errors: The above error occurred in the ( input ) component: Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
reminder
246
To set the initial value for a select tag on render in React, you must use the \_???\_ attribute. Most other methods will thrown an error.
defaultValue
247
When doing a model.update() you must add returning: true if you want the updated record back (will get [count, resultsArray] instead of (counts) ) You must add individualHooks: true if you want the hooks to be processed.
reminder
248
a model hook signature = (instance, options) =\> { } The instance param starts out with all it's current dataValues set with the new values passed into the methed called on the model (ie model.update(newObject,{ where: ... } ) ). The values ommited from the passed in object get set to the values currently in the database. the instance object also stores the previous values, those start out as the values pulled from the database. the changed method will return true if you passed in a different value from what's in the database. Done by comparing prevDataValues to current dataValues. If you change a value inside the hook it would shift the current and previous dataValues with your new value.
reminder
249
1. Use the multiple attribute to allow multiple files 2. Use the accept attribute to limit file types (comma separated string of extensions or mime types, including something like image/\*) 3. Whether single or multiple files, the files get stored/added to a FileList object which is read only. 4. The FileList is stored in inputEl.files. It's not an array, but can be spread into an array. 5. To clear an input, you can set inputEl.value = '' (empty string) 6. DataTransfer class allows you to create an alternative to a fileList, but with the ability to add File objects ( using dataTransfer.items.add(file) ) 7. You can add a dataTransfer file list (overwrite an inputs files) with inputEl.files = dataTransfer.files 8. DataTransfer was created for drag and drop but seems to work on simple input file types. 9. You can also set inputEl.\_value (note the underscore) with a regular array of File objects, but it does not update the file count when viewing the original input box. 10. You cant control a file input. You must use references to update the value. 11. https://pqina.nl/blog/the-trouble-with-editing-and-uploading-files-in-the-browser/ form some good info.
reminder
250
251
when chaining errors by rethrowing them, each the receiving function must be an **async** function or use .catch or be a promise. Particularly with receiving functions that use try catch block, you must **await** the statements that the error could be thrown too in the try block. Otherwize you may get an uncaught error from the function rethrowing the error.
reminder
252
an error/json caught from axios is stored in error.response.data
reminder
253
254
When using multiple animated items in one container that leave or reset within the container, you should position: absolute the items, as when they leave, reset or move to the edges of the container, they will cause the container to change causing a jitter or jumping effect on the other items.
reminder
255
Whenever you start a new line with something enclosed in parenthesis, you must close/end the previous line of code with a semicolun to prevent javascript from thinking its executing a function.
reminder
256
You can play audito by using the new Audio('path/fileName') and calling play( ) on the object created const sound = new Audio('path/someFile') sound.play( ) You can also import the sound file and pass the imported variable into the new method. Also, you call play on new Audio using it like an IFEE
reminder
257
you can call scrollIntoView(true) on an element to force a scroll to that element (ie it's a to anchor method) someElRef.current.scrollIntoView(true)
reminder
258
Socket.io cors error from the client. When creating the io object on the server, using socketIo(server, config), you must pass an object to the config param that contains a cors property and set the origin property. otherwise you could trigger a cors error example * const socketIo = require('socket.io') * const SocketServer = (server) =\> { * const io = socketIo(server, { * **cors: {** * **origin: "\*"** * **}** * }) * io.on('connection', (socket) =\> { * socket.on('join', async (user) =\> { * console.log("New user joined: ", user.firstName) * }) * }) * }
reminder
259
If getting an error from my reducers about not being able to convert non-serializable data, you can ignore the error and configure the store to not show the error by adding the below middleware property will look up later on best practice for this issue. * export default configureStore({ * reducer: { * lang: langSlice.reducer, * auth: authSlice.reducer, * chat: chatSlice.reducer * }, * **middleware: (getDefaultMiddleware) =\> getDefaultMiddleware({** * **serializableCheck: false,** * **})** * })
reminder
260
261
what is the heroku command to list all env variables including built in ones, on a deployed app (ie chat-server app)? (assume you already logged into the cli using heroku login)
heroku run printenv -a chat-server
262
If you attempt to deploy an app to a server that self builds, it will fail if you only installed your font awesome pro license/token to the local/global config. What are the steps to allow the hosting service to build with your pro token.
1. create a .npmrc file in the project root 2. Add @fortawesome:registry=https://npm.fontawesome.com/ to the file 3. Add //npm.fontawesome.com/:\_authToken=${FONTAWESOME\_NPM\_AUTH\_TOKEN} to the file 4. Add the actual token to an env var called FONTAWESOME\_NPM\_AUTH\_TOKEN on the host service Alternatively you could skip adding the environment var and replace ${ envVarKey } with the actual token on step 3
263
264
What are the 4 pillars of OOP
Encapsulation Abstraction Inheritance Polymorphism
265
266
command line to generate a console based c# project
dotnet new console
267
command line to start a c# console project
dotnet run
268
What are the implicit (implied) using statements in .net 6.0
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
269
Command to print a list of all the C# project templates.
dotnet new
270
List the primative datatypes in C#
* byte * short * int * long * float * double * decimal * char * bool
271
What is the byte size and range of values for the following primatives? 1. byte 2. short 3. int 4. long 5. float 6. double 7. decimal 8. char 9. bool
1. 1B / 0-255 2. 2B / -32768 to 32767 3. 4B / +- 2.1billion 4. 8B / +- 9.2 \* 10^18 5. 4B / ยฑ1.5 x 10^-45 to ยฑ3.4 x 10^38 6. 8B / ยฑ5.0 ร— 10^-324 to ยฑ1.7 ร— 10^308 7. 16B / ยฑ1.0 x 10^-28 to ยฑ7.9228 x 10^28 8. 2B / Unicode char set 9. 1B / True or False
272
How do you write the assigment of a decimil or float value in C#? use the value 1.25 as an example and someVar as the variable name
float someVar = 1.25f; float someVar = 1.25m;
273
What are 4 common non-primative types in C#?
* String * Array * Enum * Class
274
When deploying a React router app to a web server/service (particularly Netlify) you need to add a ___ file to the public directory with what command? Note: the purpose of this file is to transfer routing over to the route of your app on initial load. It fixes the page not found error when someone loads/refreshes the site from a route. https://www.freecodecamp.org/news/how-to-deploy-react-router-based-app-to-netlify/
\_redirects /\* /index.html 200
275
File uploads to Heroku, through the application, will work, but are only temporary. Uploaded files will be lost when the Heroku dyno restarts (at least daily).
reminder
276
277
process. stdin.on("data", (input)=\> {callback function}) process. stdin.on starts a listener process on the command line the process can be programatically stopped with process.exit() entered input gets suffixed with \r\n
reminder
278
Easiest way to pad leading characters on a string. return someNumberString as a string with 5 digits, using leading zeros.
return someNumberString.padStart(5, '0')
279
convert someNum to a 32 bit binary string
someNum.toString(2)
280
convert a 32bit binary string call someBinString to a decimal number
parseInt(someBinString, 2)
281
282
What does IAM stand for in regard to Amazon Web Services?
Identity Access Management
283
284
What does S3 stand for in Amazon S3
Simple Storage Service
285
What are the properties needed to configure an AWS S3 object? Insure correct casing. resource on S3 aws-sdk - https://stackabuse.com/uploading-files-to-aws-s3-with-node-js/
accessKeyId, secretAccessKey, region, signatureVersion
286
Write the call on s3 needed to get a file upload URL. Insure correct case sensitivity.
* s3.getSignedUrl( * 'putObject', * { * Bucket: 'bucket-name', * ContentType: 'image/\*', * Key: 'thePath/AndFileName.ext', * Expires: someIntSeconds * }, * (err, url) =\> { * //some code to use the url or err * } * )
287
what is the aws s3 url called that can be generated programmatically to allow a non user or application to temporarily add or retrieve a file from your s3 bucket?
presigned URL
288
Generate and configure an S3 object 3 ways. 1. From the default export of 'aws-sdk' ,passing configs to that Class. 2. Pull the default export of aws-sdk and configure the s3 object while creating it. 3. use the named import of S3. just use a presaved config var called awsConfigs to pass in the configs for this problem.
* const AWS = require('aws-sdk') * AWS.config.update(awsConfigs) * const s3 = new AWS.S3() * const AWS = require('aws-sdk') * const s3 = new AWS.S3(awsConfigs) * const S3 = require('aws-sdk/clients/s3') or const {S3} = require('aws-sdk') * const s3 = new S3(awsConfigs)
289
Where do the validation methods for express validator come from?
validator. js https: //www.npmjs.com/package/validator
290
What are the 12 validation methods in express-validator that are additional to those included from validator.js
1. .bail() 2. .custom() 3. .exists() 4. .if() 5. .isArray() 6. .isObject() 7. .isString() 8. .not() 9. .notEmpty() 10. .optional() 11. .run() 12. .withMessage()
291
To keep from getting an Uncontrolled changed to Controlled component error, you must make sure the initial value from your variable is not returning undefined.
reminder
292
write a comparison to determin if a property exists in an object. use the below example const fruits = { apple: '5 in inventory', orange: '2 in inventory', cherries: '0 in inventory' } determin if this this object has a banana property
('banana' **in** fruits) //should return false
293
*'this'* inside of an arrow function represents the *'this'* value of the containing function for which it was defined in. strict mode forces the value of the unbound 'this' variable to be 'undefined' instead of being added to the window object. inside class constructors 'this' follows strict mode rules.
reminder
294
what are the 5 parameters profided in each file(aka module)
module, exports, require, \_\_filename, \_\_dirname
295
`the dog weighs ${someNum} lbs` What kind/type of string does the above expression use
Template String
296
You have to rewatch Mosh H Node.js Extending Event Emmiter lecture, currently Section 2 Vid#21 Great example of creating your own class that extends a Node class and is used in other files.
reminder
297
Show the equivilant x upgradability for the following npm version markers. x representing the part of the version that can be upgraded. ^4.2.5 ~4.2.5 4.2.5
4. x //upgrade patches or minor version 4. 2.x //upgrade with patches 4. 2.5 //keep same version
298
command to list out all node module versions in a tree? command to list only node module versions that your app depends on?
npm list npm list --depth=0
299
command to see the package.json file for a node module?
npm view someNodeModuleName
300
command to see just a node modules's dependencies? command to see all versions of a node module?
npm view moduleName dependencies npm view moduleName versions
301
How to install a specific version of a node module? ie version 2.4.2 of mongoose
npm install mongoose@2.4.2
302
command to list out any dependencies that have newer versions available? command to list out any global packages that have newer versions available?
npm outdated npm -g outdated
303
command to trigger ALL node modules to update to the latest versions (minor and patch) based on their version prefixes (^ or ~) trigger update for ALL global packages Note: to upgrade a major version on ALL outdated node packages, you need something like npm-check-updates module. Note: you should be able to upgrade the major version on a single package by running the install command again.
npm update npm -g update
304
step/commands to add my own package to npm? note: rewatch Mosh H Section 3 videos 38 and 39 Publishing a package and Updating a published package for review and more detail.
cd into the project folder npm login (npm adduser if wanting to create an account via command line) npm publish (project must have a unique name)
305
What does REST stand for?
Representational State Transfer
306
How can you set environment variables on Mac and on Windows? set PORT to 5000 as an expample.
for mac: export PORT=5000 for win: set PORT=5000
307
given the route 'http://somesite.com/api/:id/:classOf?hasDogs=yes?isGraduated=no' what request object holds the id and classOf and what request object holds hasDogs and isGraduated.
req. params req. query
308
what does status 400 mean
Bad Request
309
What does status 404 mean?
Resource not found
310
311
how to designate a static folder in node.js use the public folder which is nested in src from the root a test file can be read using the following get call: http://localhost:3000/pubfiles/test.txt Note/Reminder: the static method is always relative to the root of the app no matter where the call is made from.
app.use('/pubfiles', express.static('src/public'))
312
Express has a list of middleware that can be used with it. You can find the list on Express' website under Resources/Middleware can view at https://expressjs.com/en/resources/middleware.html
reminder
313
Setting env vars: in bash shell you can call: **export** to list all env vars echo $SOME\_VAR to print specific env variable You can set env vars with: **export** *SOME\_VAR="value" OR SOME\_VAR=value (no command)* in Powershell use: $env:SOME\_VAR="production" \*IMPORTANT: These values will NOT persist across terminal sessions. It will only apply to the apps/server sessions running in that terminal window. Best options for persistence or repeat use script the var with a call to app: USER\_ID=239482 USER\_KEY=foobar node app.js OR use a .env but without having to call dotenv in my code create a .env file for the app install dotenv call a dotenv command line before running the app: node **-r dotenv/config** index.js
reminder
314
creating application variables/config based on environment and are not highly secure(not passwords and such) * npm install config * create a folder called config in the root * create JSON files with names that matches exactly to the NODE\_ENV name that you have custom configs for. * import config into any files where you need to pull values * call config.get('property.anySubProperty.etc') Note there is an option to create a file called **custom-environment-variables.json** in this folder which allows you to map the environment variables to config.get() properties just using the environment variable name as the property value. no need to use process.env.VAR\_NAME The above is an easy way to read env variable. BUT it does not set env vars. You still set those using dotenv, command line, or hosted settings.
reminder
315
module for debugging - cleaner alternative to console logging * install debug * const debugMode1 = require('debug')('app:mode1') * const debugMode2 = require('debug')('app:mode2') * const someOtherDebugger = require('debug')('other:debugSomething') * wherever I want to console log something related to a debug use: * debugMode1('Print some message/log related to debug Mode1') * set a DEBUG environment variable with the instance of debug you want to run: * i.e. DEBUG=app:mode1 * start the app like normal with the new environment variable OR set the env variable with the startup command. **Note** you can run multiple debug instances with DEBUG=**app:mode1,app:mode2,etc** OR DEBUG=**app:\***
reminder
316
How would you incorporate the pug templating engine change the default root views folder to src/views and return a pug template as HTML response on the /test route
* app.set('view engine', 'pug') * app.set('views', './src/views') * create a .pug template file in the views path using pug syntax (ie index.pug) * app.get('/', (req, res) =\> { * //any code * res**.render**('index', { pugTemplateVar1: 'some value', pugVar2: 'some val', etc...}) * })
317
In javascript you can reuse the same function name in the same scope, as long as the functions have a different number of parameters. you can even call the alternate signature within the function.
reminder
318
319
320
What are the schema types available for mongoose?
String Number Date Buffer Boolean ObjectID Array
321
Installing and setup steps for MongoDb locally. Install MSI's for MongoDB community, Mongo Shell, Mongo Tools, and Mongo Compass Append the folder path for mongo.exe to the PATH System environment variable (this is just so you don't have to move to this path in order to run mongo on the command line) Make sure MongoDB is running in Services When connecting you may need to use the 127.0.0.1:27017 instead of localhost
reminder
322
What are 8 comparison Operators in mongoose along with their meaning reminder: these operators will be prefixed with $ during use.
eq (equal) ne (not equal) gt (greater than) gte (greater than or equal to) lt (less than) lte (less than or equal to) in (in) nin (not in)
323
324
What are the 3 types of app Tests and their general meanings?
Unit Tests: Testing units of the app withOUT EXTERNAL dependencies Integration Tests: Testing application WITH EXTERNAL dependencies End to End Tests: Testing multiple units (ie classes) of an application together or as a whole. Another example is using selenium to automate a user interface test.
325
in Jest, what is the difference between using the method .toBe() vs .toEqual()
toBe will compare reference variables by reference as where toEqual will compare reference objects by their contained values.
326
for config.js what file name do you use for the config file that has global env settings. ie matches/pulls process.env values by property value name into the config object, no mater what NODE\_ENV your in.
custom-environment-variables.json
327
1 What is the command to install the Nest CLI 2 What is the command to start a nest project?
1. npm install -g @nestjs/cli 2. nest new pathName
328
What are the 7 primative types in Typescript
string, number, boolean, null, undefined, void, symbol
329
What are the 4 object types in typescript?
functions, arrays, classes, and objects
330
A typescript object that is an array with a fixed structure. It resembles an object structure without property names by defining the value type of each index. ie const pepsi: [string, boolean, number] = ['brown', true, 40] index 0 represents the color of the drink index 1 represents whether the drink is carbonated index 2 represents the number of carbs
Tuple
331
How can you predefine a tuple structure for reuse when defining them.
type SomeStructure = [string, boolean, boolean, etcetera]
332
An interface (in Typescript) is a way to define an Object type. objects that receive an interface type are required to have all the properties of that interface. Not less, but the objects are allowed to have more properties. Important note: With an object that has more properties than is defined in its interface, those additional properties become private inside the object. Basically, you cannot read any of the additional properties, only other properties inside the object can use these extra values using the 'this' keyword. The above applies to function parameters that take an object based on an interface type. If you apply an interface to an instance of an object it will restrict you to only define properties that match the interface.
reminder
333
What do the **modifiers** private, protected, and public mean added to methods on a class? Extra Note1: the child class can't escalate the protection level up from that assigned in the parent. Extra Note 2: If you add modifiers to the parameters in the constructor of a class, you do not need to set a 'this' property nor initialize the variable. Also, the same type of protection levels apply.
Private means the method can only be used within the class Protected means the method can only be used in the parent and it's child classes. Public is default and means that the method can be used anywhere outside the class.
334
In classes that extend from a parent that takes initial values, you only need to call super if you need to define the constructor method to add additional parameters on the child class. Basicallically, you don't need to generate a constructor at all, as the constructor from the parent is called by default. But once you add a constructor for other reasons, the parent must be initialized by super.
reminder
335
What is a good website to get a list of ascii character info
www.asciitable.com
336
What are the two Type Guard opperators and the value types that each applies to (in a type guard role)?
typeof for string, boolean, number, symbol instance of for every other value created with a constructor
337
To setup c# development in VS Code, you must: Install the .Net SDK Install the C# extension in VSCode For .net 6 you need to add a setting to VS Code settings: "omnisharp.useModernNet": true
reminder
338
To start a c# program in vscode. to create project in current folder, run: dotnet new [type of project] to get a list of project types, run: dotnet new -l after creating project, if not promoted, go to command pallet and search for .Net Generate assets for build and debug, to add debugging files. To run the project: dotnet run
reminder