├── .vscode └── settings.json ├── CODE_OF_CONDUCT.md ├── CPP ├── CW │ ├── C11.md │ ├── C12.md │ └── L-generator.py └── Lab_12 │ └── 01_Fibonacci │ ├── README.md │ └── question_01.cpp ├── Dart └── README.md ├── Events └── Apple │ └── Nov_07_2024 │ └── README.md ├── Flutter └── README.md ├── JS └── README.md ├── LICENSE ├── Linux └── README.md ├── NoSQL └── README.md ├── NodeJS └── README.md ├── PHP └── README.md ├── PyAPI └── README.md ├── README.md ├── ReactJS └── README.md ├── Redux └── README.md ├── SQL ├── MariaDB.md ├── Practice.md └── README.md ├── SwiftLearning ├── arc │ ├── example1.swift │ ├── example2.swift │ └── main.swift ├── autoclosures │ ├── main.swift │ ├── new.swift │ └── old.swift ├── built-in-functions │ ├── arc.swift │ ├── debug.swift │ ├── dump.swift │ ├── error.swift │ ├── fatalError.swift │ ├── main.swift │ ├── minmax.swift │ ├── precondition.swift │ ├── readLine.swift │ ├── repeatAndSequence.swift │ ├── stride.swift │ ├── swap.swift │ ├── type.swift │ └── zip.swift ├── extensions │ ├── computed.swift │ ├── initalizer.swift │ ├── main.swift │ ├── methods.swift │ ├── mutate.swift │ └── subscript.swift ├── generics │ ├── example1.swift │ └── main.swift ├── inheritance │ ├── animal.swift │ ├── main.swift │ ├── override.swift │ └── super.swift ├── nested_types.swift ├── practice │ ├── main.swift │ └── optionals.swift └── quiz │ ├── main.swift │ ├── notes.txt │ └── questions.swift └── Yii2 └── README.md /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "workbench.colorCustomizations": { 3 | "sideBar.background": "#111111", 4 | "activityBar.activeBackground": "#65c89b", 5 | "activityBar.background": "#65c89b", 6 | "activityBar.foreground": "#15202b", 7 | "activityBar.inactiveForeground": "#15202b99", 8 | "activityBarBadge.background": "#945bc4", 9 | "activityBarBadge.foreground": "#e7e7e7", 10 | "commandCenter.border": "#15202b99", 11 | "sash.hoverBorder": "#65c89b", 12 | "statusBar.background": "#42b883", 13 | "statusBar.foreground": "#15202b", 14 | "statusBarItem.hoverBackground": "#359268", 15 | "statusBarItem.remoteBackground": "#42b883", 16 | "statusBarItem.remoteForeground": "#15202b", 17 | "titleBar.activeBackground": "#42b883", 18 | "titleBar.activeForeground": "#15202b", 19 | "titleBar.inactiveBackground": "#42b88399", 20 | "titleBar.inactiveForeground": "#15202b99" 21 | }, 22 | "peacock.color": "#42b883" 23 | } 24 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | kamaldgrt@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CPP/CW/C11.md: -------------------------------------------------------------------------------- 1 | # C 11 Complete CW 2 | 3 | D: 14062016 4 | 5 | ## Data Representation 6 | 7 | ### Conversions 8 | 9 | #### 1. Decimal to Binary 10 | 11 | - (a) (15)10 -----> (?)2 12 | 13 | ```nim 14 | 2 │ 15 15 | ├────── 16 | 2 │ 7 ----- 1 17 | ├────── 18 | 2 │ 3 ----- 1 19 | ├────── 20 | 2 │ 1 ----- 1 21 | └─────── 22 | ``` 23 | 24 | - (b) (28)10 -----> (?)2 25 | 26 | ```nim 27 | 2 │ 28 28 | ├────── 29 | 2 │ 14 ----- 0 30 | ├────── 31 | 2 │ 7 ----- 0 32 | ├────── 33 | 2 │ 3 ----- 1 34 | ├────── 35 | 2 │ 1 ----- 1 36 | └─────── 37 | ``` 38 | -------------------------------------------------------------------------------- /CPP/CW/C12.md: -------------------------------------------------------------------------------- 1 | # C 12 Notes 2 | 3 | 4 | 5 | **Define encapsulation and explain how it is implemented in C++.** 6 | 7 | - The wrapping up of data and functions (that operate on the data) into 8 | one single unit (called class) is called encapsulation. 9 | - It is implemented by using classes in C++. 10 | - A class is a way to bind the data describing the entity and its 11 | associated member functions together. 12 | - In C++, class makes a data type that is used to create objects 13 | of this type. 14 | - In a class: 15 | 16 | - Data Members : Physical Characteristics 17 | - Member Functions: Behaviour 18 | 19 | - ###### Example of a class: 20 | 21 | ```cpp 22 | class sample { 23 | int a, b; // Data Members 24 | 25 | public: 26 | void read() { // Member Function 27 | a = 1; 28 | b = 5; 29 | } 30 | void show() { // Member Function 31 | cout << a + b; 32 | } 33 | }; 34 | ``` 35 | 36 | --- 37 | 38 | **Define data abstraction and hiding.** 39 | 40 | - The act of representing only the essential features without 41 | including the background details is called data abstraction. 42 | - This concept is implemented using `public` access level specifier 43 | in a class. 44 | - The public members are directly accessible outside the class 45 | using an object of the class. 46 | - The private and the protected members of the class are not directly 47 | accessible from outside the class. 48 | - They are hidden from the outside world. 49 | - Hence, they implement the concept of data hiding. 50 | 51 | - ###### Example: 52 | 53 | ```cpp 54 | class Sample { 55 | int a, b; // Data Members 56 | 57 | public: 58 | void read() { // Member Function 59 | a = 1; 60 | b = 5; 61 | } 62 | void show() { // Member Function 63 | cout << a + b; 64 | } 65 | }; 66 | 67 | int main() { 68 | Sample S; 69 | S.a = 5; // S1 - Invalid as a is a private member 70 | S.b = 10; // S2 - Invalid as b is a private member 71 | S.read(); // S3 - valid 72 | S.show(); // S4 - valid 73 | } 74 | 75 | // Assuming S1 and S2 are edicated, output will be 6. 76 | ``` 77 | 78 | --- 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 91 | 92 | 93 | 94 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 |
Member FunctionsUser-Defined Functions
Public member functions are invoked using an object with a 90 | dot operatorNo such restrictions.
The member functions can access private, protected and public 95 | members of the class.Can directly access only public members of the class.
Member functions are inline by default.Non inline by default.
104 | 105 | --- 106 | 107 | ###### Note: 108 | 109 | - Member functions declared inside a class are inline by default. 110 | - Object -> structure variable / class variable. 111 | - When we define a class memory won't be allocated for data members. 112 | - Member functions statements will be stored in global memory. 113 | - Class / Structure variables are known as instances / objects. 114 | - The private and protected members of a global / local object are 115 | directly accessible inside the member function of the class. 116 | - Inside a class if we have a same class member and global variable, 117 | the member function can access only the class member. 118 | - The only difference between classes and structures w.r.t C++ is 119 | about the access level specifiers. 120 | - Structure will have only data members and class will have data 121 | members and member functions. 122 | - In structure, everything is public and accessible and vice-versa, 123 | in classes it is private by default. 124 | - Prototype of the memebr functions should be given in the class 125 | definition and the declaration 126 | 127 | --- 128 | 129 | **Types of member functions** 130 | 131 | - (i) _Mutator member function_ : Function which accepts, displays or 132 | manipulates the data members. 133 | - (ii) _Accessor member function_ : can be used to access private and 134 | protected data members. 135 | - (iii) _Manager member functions_ : (Constructor & Destructor) 136 | It is a special member function which has the same name as that 137 | of the class. 138 | 139 | --- 140 | 141 | **Constructors and Destructors** 142 | 143 | If a user does not define a constructor, the compiler automatically allocates 144 | memory for data members at a particular location by creating a member function. 145 | This function is called constructor by default. 146 | 147 | ##### How to define a constructor 148 | 149 | - Constructor should have the same name as that of a class. 150 | - no return data type (including the `void` should not be used) 151 | 152 | --- 153 | 154 | **Define a constructor. Explain the concept with a sample example.** 155 | 156 | - Constructor is a member function of a class that has the same name 157 | as that of a class without any return data type (not even void). 158 | - It is called automatically whenever an object is created. 159 | - The constructor allocates space for the data members for the newly 160 | created objects and initializes them with some legal value. 161 | - It has to be defined under public access level specifier only. 162 | 163 | ##### Example: 164 | 165 | ```cpp 166 | class Sample { 167 | int a, b; 168 | 169 | public: 170 | Sample() { // Default Constructor 171 | a = 1; 172 | b = 2; 173 | } 174 | 175 | void show() { 176 | cout << a << " " << b; 177 | } 178 | }; 179 | 180 | int main() { 181 | Sample S; 182 | S.show(); 183 | return 0; 184 | // Output : 185 | // 1 2 186 | } 187 | ``` 188 | 189 | --- 190 | 191 | **Types of Constructors** 192 | 193 | - Default 194 | - Parameterised 195 | - Copy 196 | 197 | --- 198 | 199 | **Default Constructor** 200 | 201 | - A member function which as the same as that of the class, which 202 | does not accept any arguments and which has no return data type 203 | (not even void) is called a default constructor. 204 | - It is invoked automatically whenever an object is created (or) declared 205 | without arguments. 206 | - It allocates space for all the data members of the newly created object 207 | and initialises them with some legal values. 208 | - It has to be defined under the public section only. 209 | 210 | --- 211 | 212 | **Parameterized Constructor** 213 | 214 | - A member function that has the same name as that of the class, which 215 | accepts parameters and does not have any return data type 216 | (not even void) is called a parameterised constructor. 217 | - It is invoked automatically when the object is created with arguments. 218 | - It allocates space for all the data members of the newly created object 219 | and initialises them with the appropriate values accepted as argument. 220 | - It should be defined under public section only. 221 | 222 | ```cpp 223 | class Sample { 224 | int a, b; 225 | 226 | public: 227 | Sample(int l, int m) { // Parameterised Constructor 228 | a = l; 229 | b = m; 230 | } 231 | 232 | void show() { 233 | cout << a << " " << b; 234 | } 235 | }; 236 | 237 | int main() { 238 | Sample S(1, 3); 239 | S.show(); 240 | return 0; 241 | // Output : 242 | // 1 3 243 | } 244 | ``` 245 | 246 | --- 247 | 248 | **Copy Constructor** 249 | 250 | - The member function of a class that has the same name as that of the 251 | class with no return data type and is of the form: 252 | `classname(classname&)` is called a copy constructor. 253 | - It is invoked automatically when an object is created and initialised 254 | to another object of the same class type, in the same statement. 255 | - It is used to initialize the data members of the newly created 256 | object with the corresponding data member of an already existing 257 | object. 258 | - It should be defined under public section only. 259 | 260 | ```cpp 261 | class Sample { 262 | int a, b; 263 | 264 | public: 265 | Sample() { // Default Constructor 266 | a = 1; 267 | b = 2; 268 | } 269 | 270 | Sample(Sample &R) { // Copy Constructor 271 | a = R.a; 272 | b = R.b; 273 | } 274 | 275 | void show() { 276 | cout << a << " " << b; 277 | } 278 | }; 279 | 280 | int main() { 281 | Sample S; 282 | Sample T(S); 283 | T.show(); 284 | return 0; 285 | // Output : 286 | // 1 2 287 | } 288 | ``` 289 | 290 | --- 291 | 292 | **Destructor** 293 | 294 | - The member function of a class that has the same name as that of the 295 | class preceeded by the `~` symbol, with no return data type (not even 296 | void) is called a destrcutor. 297 | - It is called automatically when an object goes out of scope. 298 | - It is used to deallocate space for the data members of an object 299 | that expires. 300 | - It has to be defined under public section only. 301 | - It does not accept any arguments. 302 | 303 | ```cpp 304 | class Sample { 305 | int a, b; 306 | 307 | public: 308 | Sample() { // Default Constructor 309 | a = 1; 310 | b = 2; 311 | } 312 | 313 | ~Sample() { // Destructor 314 | cout << "Object Destroyed\n"; 315 | } 316 | 317 | void show() { 318 | cout << a + b << endl; 319 | } 320 | }; 321 | 322 | int main() { 323 | Sample X; 324 | if (1) { 325 | Sample Y; 326 | Y.show() 327 | } // Destructor called for deallocation of Y 328 | return 0; 329 | } // Destructor called for deallocation of X 330 | 331 | /* Output 332 | 3 333 | Object Destroyed 334 | Object Destroyed 335 | */ 336 | ``` 337 | 338 | --- 339 | 340 | **Similarities between constructor and destructor** 341 | 342 | - Both are member functions defined under public section. 343 | - Should not return any return data type (not even void). 344 | - They come under the category of manager functions. 345 | 346 | --- 347 | 348 | **Differences between constructor and destructor** 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 |
ConstructorDestructor
It is used to allocate space for data members of an object.It is used to deallocate reserved space for the data 361 | members of an object.
Can be overloaded.Cannot be overloaded.
Invoked automatically when object is created.Called automatically when an object goes out of scope.
Can be invoked implicitly / explicitly.Will be called implicitly only.
377 | 378 | --- 379 | 380 | **Stack using 1 D array** 381 | 382 | **_Write a program to implement stack operations on an 1D array of size 5_** 383 | 384 | ```cpp 385 | int A[5], top = -1; 386 | 387 | void push() { 388 | if (top == 4) 389 | cout << "Stack Full"; 390 | else { 391 | top += 1; 392 | cin >> A[top]; 393 | } 394 | } 395 | 396 | void pop() { 397 | if (top == -1) 398 | cout << "Stack Empty"; 399 | else { 400 | cout << "Deleted Element : " << A[top]; 401 | top -= 1; 402 | } 403 | } 404 | 405 | void display() { 406 | for (int i = top; i >= 0; i--) { 407 | cout << A[i]; 408 | if (i == top) 409 | cout << " <---"; 410 | cout << endl; 411 | } 412 | } 413 | 414 | int main() { 415 | int n; 416 | cout << "1. Push 2. Pop 3. Display \n"; 417 | cin >> n; 418 | if (n == 1) 419 | push(); 420 | else if (n == 2) 421 | pop() 422 | else if (n == 3) 423 | display(); 424 | return 0; 425 | } 426 | ``` 427 | 428 | --- 429 | 430 | **Applications of Stack** 431 | 432 | - Reversing a string 433 | - Conversion of infix to postfix 434 | - Evaluation of postfix 435 | 436 | --- 437 | 438 | **Singly Linked List** 439 | 440 | ```c 441 | #include 442 | #include 443 | 444 | //self-referential structure 445 | typedef struct Node 446 | { 447 | int data; 448 | struct Node *Next; 449 | } Node; 450 | 451 | //bare necessities 452 | int nsize = sizeof(Node); 453 | Node *Head = NULL; 454 | 455 | //prototype of the operations that will be performed 456 | void InsAtBeg(int); 457 | void InsAtEnd(int); 458 | void InsAtPos(int, int); 459 | int Count(); 460 | void Search(int); 461 | void Delete(int); //By value 462 | void Delete1(int); 463 | void Display(); 464 | void Insert(); 465 | 466 | int main() 467 | { 468 | char mc, ic, dc; 469 | int x; 470 | 471 | printf("\t\t Operations on a Singly Linked List \n"); 472 | printf("\t\t ---------- -- - ------ ------ ---- \n"); 473 | 474 | printf("\n\n\t 1. Insert \n"); 475 | printf("\t 2. Delete \n"); 476 | printf("\t 3. Count \n"); 477 | printf("\t 4. Search \n"); 478 | printf("\t 5. Display \n"); 479 | printf("\n\t Enter your choice : "); 480 | 481 | scanf("%c", &mc); 482 | 483 | switch (mc) 484 | { 485 | case '1': 486 | Insert(); 487 | break; 488 | case '2': 489 | printf("Enter element to be deleted: "); 490 | scanf("%d", &x); 491 | Delete(x); 492 | break; 493 | case '3': 494 | Count(); 495 | break; 496 | case '4': 497 | Searc(); 498 | break; 499 | case '5': 500 | Display(); 501 | break; 502 | } 503 | 504 | return 0; 505 | } 506 | 507 | int Count() 508 | { 509 | int c = 0; 510 | Node *T = Head; 511 | 512 | while (T != NULL) 513 | { 514 | c = c + 1; 515 | T = T->Next; 516 | } 517 | return c; 518 | } 519 | 520 | void InsAtBeg(int x) 521 | { 522 | Node *N = (Node *)malloc(nsize); 523 | N->data = x; 524 | 525 | if (Head == NULL) 526 | N->Next = NULL; 527 | else 528 | N->Next = Head; 529 | 530 | Head = N; 531 | } 532 | 533 | void InsAtEnd(int x) 534 | { 535 | Node *N = (Node *)malloc(nsize); 536 | 537 | N->data = x; 538 | N->Next = NULL; 539 | 540 | if (Head == NULL) 541 | Head = N; 542 | else 543 | { 544 | Node *T = Head; 545 | 546 | while (T->Next != NULL) 547 | T = T->Next; 548 | 549 | T->Next = N; 550 | } 551 | } 552 | 553 | void InsAtPos(int p, int x) 554 | { 555 | 556 | int size = Count(), i; 557 | 558 | if (p < 1 || p > size + 1) 559 | printf("\n\nInvalid Position."); 560 | else 561 | { 562 | Node *N = (Node *)malloc(nsize), *T; 563 | 564 | N->data = x; 565 | N->Next = NULL; 566 | 567 | if (p == 1) 568 | { 569 | N->Next = Head; 570 | Head = N; 571 | } 572 | else 573 | { 574 | T = Head; 575 | 576 | for (i = 2; i <= (p - 1); i++) 577 | T = T->Next; 578 | 579 | N->Next = T->Next; 580 | T->Next = N; 581 | } 582 | } 583 | } 584 | 585 | void Display() 586 | { 587 | 588 | if (Head == NULL) 589 | printf("\n\t There are no Nodes."); 590 | 591 | else 592 | { 593 | Node *i = Head; 594 | 595 | while (i != NULL) 596 | { 597 | printf("\n\t %d", i->data); 598 | 599 | i = i->Next; 600 | } 601 | } 602 | } 603 | 604 | void Search(int x) 605 | { 606 | int f = 0; 607 | 608 | Node *i = Head; 609 | 610 | while (i != NULL) 611 | { 612 | if (i->data == x) 613 | { 614 | f = 1; 615 | break; 616 | } 617 | 618 | i = i->Next; 619 | } 620 | 621 | if (f) 622 | printf("\n\t %d is present in the List."); 623 | 624 | else 625 | printf("\n\t %d is not present in the List."); 626 | } 627 | 628 | void Delete(int x) 629 | { 630 | Node *t2 = Head->Next, *t1 = Head; 631 | 632 | int f = 0; 633 | 634 | if (Head->data == x) 635 | { 636 | 637 | Head = Head->Next; 638 | free(t1); 639 | f = 1; 640 | printf("A Node has been deleted."); 641 | } 642 | 643 | else 644 | { 645 | while (t2 != NULL) 646 | { 647 | if (t2->data == x) 648 | { 649 | t1->Next = t2->Next; 650 | free(t2); 651 | f = 1; 652 | printf("A Node has been deleted."); 653 | } 654 | else 655 | { 656 | t1 = t2; 657 | t2 = t2->Next; 658 | } 659 | } 660 | } 661 | } 662 | 663 | void Delete1(int position) 664 | { 665 | Node *p, *q; 666 | int i; 667 | 668 | p = Head; 669 | q = Head; 670 | 671 | for (i = 1; i < position - 1; i++) 672 | p = p->Next; 673 | 674 | q = p->Next; 675 | p->Next = q->Next; 676 | free(q); 677 | } 678 | ``` 679 | 680 | --- 681 | 682 | **Stack using Linked List** 683 | 684 | ```c 685 | // Stack using Linked List 686 | //Last In First out 687 | 688 | #include 689 | #include 690 | 691 | // typedef gives an alias name for already 692 | // existing data type 693 | 694 | typedef struct Stack 695 | { 696 | int data; 697 | struct Stack *Next; // self referential structure 698 | } Stack; 699 | 700 | /* 701 | 5 <- topmost element 702 | 1 703 | 3 704 | 6 705 | 7 706 | */ 707 | 708 | // top = 5 <-- 1 <-- 3 <-- 6 <-- 7 <-- NULL; 709 | 710 | Stack *Top = NULL; 711 | int stackSize = sizeof(Stack); 712 | 713 | // Function Prototypes 714 | void Push(); 715 | void Pop(); 716 | void Display(); 717 | 718 | 719 | int main(){ 720 | int userChoice; 721 | 722 | do { 723 | printf("\n\n1. Push 2. Pop 3. Display\n"); 724 | printf("Enter your choice: "); 725 | scanf("%d", &userChoice); 726 | 727 | switch(userChoice) { 728 | case 1: Push(); break; 729 | case 2: Pop(); break; 730 | case 3: Display(); break; 731 | default: printf("Invalid choice!!!!"); 732 | } 733 | 734 | }while(userChoice <= 3 && userChoice >= 1); 735 | 736 | return 0; 737 | } 738 | 739 | void Push() { 740 | Stack *temp = (Stack*)malloc(stackSize); 741 | if (temp == NULL) 742 | printf("Stack Memory full."); 743 | else{ 744 | printf("Enter the value : "); 745 | scanf("%d", &temp->data); 746 | temp->Next = Top; 747 | Top = temp; 748 | } 749 | } 750 | 751 | void Display() { 752 | if (Top == NULL) 753 | printf ("Stack is empty."); 754 | else { 755 | Stack *temp = Top; 756 | while(temp != NULL) 757 | { 758 | printf("%d", temp->data); 759 | if(temp == Top) 760 | printf (" <----- Top"); 761 | printf("\n"); 762 | temp = temp->Next; 763 | } 764 | } 765 | } 766 | 767 | void Pop() { 768 | if (Top == NULL) 769 | printf ("Stack is empty."); 770 | else { 771 | Stack *temp = Top; 772 | printf("\nElement Removed is: %d\n", Top->data); 773 | Top = Top->Next; 774 | free(temp); 775 | } 776 | } 777 | ``` 778 | 779 | --- 780 | 781 | **Queue using Linked List** 782 | 783 | ```c 784 | // To implement queue using Linked List 785 | // First In First Out 786 | 787 | #include 788 | #include 789 | 790 | // typedef gives an alias name for already 791 | // existing data type 792 | 793 | typedef struct Queue 794 | { 795 | int data; 796 | struct Queue *Next; // self referential structure 797 | } Queue; 798 | 799 | /* 800 | Front => 5 -> 1 -> 3 -> 6 -> 7 -> NULL <--- Rear 801 | 802 | Rear (includes 7 and NULL together as a node); 803 | */ 804 | 805 | Queue *Front = NULL; 806 | Queue *Rear = NULL; 807 | int queueSize = sizeof(Queue); 808 | 809 | // Function Prototypes 810 | void EnQueue(); 811 | void DeQueue(); 812 | void Display(); 813 | 814 | 815 | int main(){ 816 | int userChoice; 817 | 818 | do { 819 | printf("\n\n1. EnQueue 2. DeQueue 3. Display\n"); 820 | printf("Enter your choice: "); 821 | scanf("%d", &userChoice); 822 | 823 | switch(userChoice) { 824 | case 1: EnQueue(); break; 825 | case 2: DeQueue(); break; 826 | case 3: Display(); break; 827 | default: printf("Invalid choice!!!!"); 828 | } 829 | 830 | }while(userChoice <= 3 && userChoice >= 1); 831 | 832 | return 0; 833 | } 834 | 835 | void EnQueue() { 836 | Queue *temp = (Queue*)malloc(queueSize); 837 | if (temp == NULL) 838 | printf("Queue is full."); 839 | else{ 840 | printf("Enter the value : "); 841 | scanf("%d", &temp->data); 842 | temp->Next = NULL; 843 | 844 | if(Rear == NULL) 845 | Front = temp; 846 | else 847 | Rear->Next = temp; 848 | Rear = temp; 849 | } 850 | } 851 | 852 | void Display() { 853 | if (Front == NULL) 854 | printf ("Queue is empty."); 855 | else { 856 | Queue *temp = Front; 857 | while(temp != NULL) 858 | { 859 | printf("%d", temp->data); 860 | if(temp == Front) 861 | printf (" <----- Front"); 862 | else if (temp == Rear) 863 | printf (" <----- Rear"); 864 | printf("\n"); 865 | temp = temp->Next; 866 | } 867 | } 868 | } 869 | 870 | void DeQueue() { 871 | if (Front == NULL) 872 | printf ("Queue is empty."); 873 | else { 874 | Queue *temp = Front; 875 | printf("\nElement Removed is: %d\n", Front->data); 876 | 877 | if (Front == Rear) 878 | Front = Rear = NULL; 879 | else 880 | Front = Front->Next; 881 | free(temp); 882 | } 883 | } 884 | ``` 885 | -------------------------------------------------------------------------------- /CPP/CW/L-generator.py: -------------------------------------------------------------------------------- 1 | # L dvision generator for conversions. 2 | # Author: github.com/KamalDGRT 3 | 4 | def give_me_L_division(num, obase): 5 | ''' 6 | Utitly function to display L division tree for a given conversion. 7 | 8 | Arguments: 9 | num -> The number to be converted 10 | obase -> The output base 11 | 12 | Returns: None 13 | ''' 14 | 15 | spaces = " " 16 | 17 | first = True 18 | while(num > 0): 19 | quotient = int(num / obase) 20 | if first: 21 | print(obase, spaces, "│ ", num) 22 | print(spaces, spaces, "├──────") 23 | first = False 24 | continue 25 | else: 26 | print(obase, spaces, "│ ", quotient, " ----- ", num % obase) 27 | num = quotient 28 | if (quotient == 1): 29 | print(spaces, spaces, "└───────") 30 | break 31 | else: 32 | print( spaces, spaces, "├──────") 33 | 34 | if __name__ == "__main__": 35 | give_me_L_division(15, 2) 36 | -------------------------------------------------------------------------------- /CPP/Lab_12/01_Fibonacci/README.md: -------------------------------------------------------------------------------- 1 | # Fibonacci Series and Prime Check 2 | 3 | ### Aim 4 | 5 | To generate the Fibonacci series for the given limit and display 6 | for each number in the series if it is prime (or) composite. 7 | 8 | ### Algorithm 9 | 10 | - `dsiplay_fibonacci_series()` function 11 | 12 | - Argument: variable `n` of integer data type. 13 | - (a) Start 14 | - (b) Read `n`. 15 | - (c) Assign `-1` to `f` and `1` to `s`. 16 | - (d) Perfom the following `n` times: 17 | - (d.1) Compute `t` to be the sum of `f` and `s` 18 | - (d.2) Assign `s` to `f`. 19 | - (d.3) Assign `t` to `s`. 20 | - (d.4) Call `prime_check()` function with `t` as argument. 21 | - (e) Stop 22 | 23 | - `prime_check()` function 24 | - Argument: variable `x` of type integer. 25 | - (a) Start. 26 | - (b) If `x` is `1` or `0`, print `Neither`. Go to step (e). 27 | - (c) Run a loop with control variable taking values from `2` to `x-1`. 28 | - (c.1) Check if any of the values of control variable is a factor of `x` 29 | - (c.2) If it is a factor, go to step (d), else continue the loop. 30 | - (d) If control had come out of step (c) because the loop was completed, 31 | print `Prime`, else print `Composite`. 32 | - (e) Stop 33 | 34 | 35 | ### Output 36 | 37 | ```nim 38 | FIBONACCI SERIES AND PRIME CHECK 39 | --------- ------ --- ----- ----- 40 | 41 | 42 | 43 | Enter number of Terms : 10 44 | 45 | Fibonacci Series Prime check 46 | --------- ------ ----- ----- 47 | 48 | 0 Neither Prime Nor Composite 49 | 1 Neither Prime Nor Composite 50 | 1 Neither Prime Nor Composite 51 | 2 Prime Number 52 | 3 Prime Number 53 | 5 Prime Number 54 | 8 Composite Number 55 | 13 Prime Number 56 | 21 Composite Number 57 | 34 Composite Number 58 | 59 | 60 | Want to continue ? Press (1) then. 2 61 | ``` 62 | -------------------------------------------------------------------------------- /CPP/Lab_12/01_Fibonacci/question_01.cpp: -------------------------------------------------------------------------------- 1 | // Fibonacci Series and Prime Check 2 | 3 | 4 | // Header File(s) 5 | #include 6 | 7 | using namespace std; 8 | 9 | // Function Prototypes 10 | void display_fibonacci_series(int); 11 | void prime_check(int); 12 | 13 | 14 | // Function definitions 15 | 16 | void prime_check(int x) { 17 | int i, s = 0; 18 | for (i = 1; i <= x; i++) 19 | if(x % i == 0) 20 | s++; 21 | if(s < 2) 22 | cout << "\t\t\tNeither Prime Nor Composite"; 23 | else if(s == 2) 24 | cout << "\t\t\t\tPrime Number"; 25 | else if (s > 2) 26 | cout << "\t\t\t\tComposite Number"; 27 | 28 | cout << endl; 29 | } 30 | 31 | void display_fibonacci_series(int n) { 32 | int i, f = -1, s = 1, t, k; 33 | 34 | for(i = 1; i <= n; i++) { 35 | t = f + s; 36 | f = s; 37 | s = t; 38 | cout << "\t" << t; 39 | prime_check(t); 40 | } 41 | } 42 | 43 | int main() { 44 | int n; 45 | char ch; 46 | 47 | do{ 48 | cout << "\n\n\t\t\tFIBONACCI SERIES AND PRIME CHECK"; 49 | cout << "\n\t\t\t--------- ------ --- ----- -----\n"; 50 | 51 | cout << "\n\n\n\tEnter number of Terms : "; 52 | cin >> n; // Accepting number of items 53 | 54 | cout << "\n Fibonacci Series \t\t\tPrime check"; 55 | cout << "\n --------- ------ \t\t\t----- -----\n\n"; 56 | 57 | display_fibonacci_series(n); 58 | 59 | cout << "\n\nWant to continue ? Press (1) then. "; 60 | cin >> ch; 61 | } while(ch == '1'); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /Dart/README.md: -------------------------------------------------------------------------------- 1 | # Dart Notes 2 | 3 | > The notes here has been taken from the handwritten notes of 4 | > [Kamal Sharma](https://github.com/KamalDGRT)'s Telegram channel and 5 | > can be found [here](https://t.me/rkswrites/2). 6 | 7 |
8 | 9 | ### Dart 10 | 11 | **Dart** is the main programming language to develop 12 | **cross-platform** mobile application using 13 | **flutter framework** 14 | 15 |
16 | 17 | ### Contents: 18 | 19 | - Setup 20 | - Fundamental 21 | - Data Types 22 | - String 23 | - Type Conversion 24 | - Constant 25 | - Null 26 | - Operators 27 | - Loop 28 | - Collection [list, set, Map] 29 | - Function 30 | - Class 31 | - Exceptional Handling 32 | 33 |
34 | 35 | ### How to run Dart Code: 36 | 37 | ``` 38 | dart .dart 39 | ``` 40 | 41 | _Install dart extension in Microsoft Visual Studio_ 42 | 43 | Dart is a static type programming language. It is also a 44 | compiled programming language 45 | 46 | Static type means if you defined a variable as a string, you cannot 47 | assign other values like integer (or) double on that string type. 48 | 49 | Dart supports two types of compilation: **ADT, JIT** 50 | 51 | 1. **AOT** - Ahead of time 52 | 2. **JIT** - Just in time 53 | 54 | When we have to run a dart program, we have to compile it then run. It 55 | happens automatically. When we write a dart program, and run it, it 56 | automatically compiles on the fly. This is called just in time 57 | compilation. 58 | 59 | When we deploy our final product, then it will be compiled as AOT 60 | complication with some optimization. 61 | 62 |
63 | 64 | ### Fundamentals 65 | 66 | Every Dart program starts with a main() function. 67 | 68 | ```dart 69 | main() { 70 | var firstName = 'Leo'; 71 | String lastName = 'Valdez'; 72 | print(firstName + lastName); 73 | } 74 | ``` 75 | 76 | when you define variables with `var` keyword, Dart automatically detects 77 | the type based on the value assigned. This is called type inference. 78 | 79 | **Dart supports both: type interface and statically type defined.** 80 | 81 | All the built in dart libraries like collection, and other core functions 82 | are defined in a package. That is called `dart:core` package. 83 | 84 | syntax to import: 85 | 86 | ```dart 87 | import 'dart:core'; 88 | ``` 89 | 90 | The `dart:core` package is automatically imported for most dart 91 | programmers. 92 | 93 | For user-input stuff, we have to import `dart:io`. 94 | 95 | ```dart 96 | main() { 97 | stdout.writeln('What is your name? ') 98 | String name = stdin.readLineSync(); 99 | print('My name is $name'); 100 | } 101 | ``` 102 | 103 | `$name` - String interpolation 104 | 105 | `//` - In-line comment 106 | 107 | ```dart 108 | /* 109 | Block comment 110 | */ 111 | ``` 112 | 113 | `///` - Documentation 114 | 115 |
116 | 117 | ### Data Types 118 | 119 | There are 2 types of available is strongly typed language: The type of a 120 | variable is known at compile time. For example C++, Java, Swift. 121 | 122 | **Dynamically Typed Language:** The type of a variable is known at run 123 | time.
124 | For example: Python, Ruby, JavaScript 125 | 126 | **In Dart programming language, there are 5 basic types:** 127 | 128 | - int 129 | - double 130 | - String 131 | - bool 132 | - dynamic 133 | 134 | After a data-type is assigned using var and the type is recognized, then 135 | you can't assign a new type later. 136 | 137 | Eg: 138 | 139 | ```dart 140 | var a = 10; 141 | a = 'Hello'; //It will return error 142 | ``` 143 | 144 | Dart is an OOP language and everything is an object in here. 145 | 146 | Even the null type is an object. 147 | 148 | Even the function [main()] is also an object which is the subtype of the 149 | function class. 150 | 151 |
152 | 153 | ### String, type conversion, constant, null 154 | 155 | **String** can be either in `''` or `""`. 156 | 157 | In `''`, you have to use `\` to print special characters 158 | 159 | But in `" "` you can use one single quote. 160 | 161 | ```dart 162 | var S3 = 'It\'s easy!'; 163 | var S4 = "It's funny"; 164 | ``` 165 | 166 | To define a raw string, put a r in front of the string. 167 |
168 | i.e, if a `\n` is there, then it won't be evaluated. 169 | I think it applies to all whitespace characters. 170 | 171 | Let's say you want to print a string without any formatting, 172 | then at that time you can prefix it with a `r` in the front. 173 | 174 | Example: 175 | 176 | ```dart 177 | void main() { 178 | var S3 = r"It\'s \n easy!"; 179 | var S4 = "It\'s \n easy!"; 180 | print('String 3 - $S3'); 181 | print('String 4 - $S4'); 182 | } 183 | ``` 184 | 185 | ##### Output 186 | 187 | ``` 188 | String 3 - It\'s \n easy! 189 | String 4 - It's 190 | easy! 191 | ``` 192 | 193 |
194 | 195 | #### String Interpolation 196 | 197 | String interpolation means to replace a variable's value with an actual 198 | value within a string. 199 | 200 | ```dart 201 | main() { 202 | var age = 25; 203 | var str = 'My age is: $age'; 204 | print(str); 205 | } 206 | ``` 207 | 208 |
209 | 210 | #### Multiline string 211 | 212 | we can define multiline string in dart either by using 3 single quotes 213 | in the beginning and end (or) by using 3 double quotes. 214 | 215 | ```dart 216 | main() { 217 | var s1 = ''' 218 | you can create 219 | multi-line string 220 | like this one'''; 221 | print(s1); 222 | } 223 | ``` 224 | 225 |
226 | 227 | #### Type conversion 228 | 229 | It is an important concept in any programming language. 230 | 231 | To convert string to integer value, user parse(). 232 | 233 | ```dart 234 | var one = int.parse('1'); 235 | assert(one == 1); 236 | ``` 237 | 238 | Sometimes we need to convert a string to an integer and vice versa. 239 | 240 | To convert a string to an integer value, you can use the parse() method 241 | of int object. 242 | 243 | ```dart 244 | main() { 245 | // String -> int 246 | var one = int.parse('1'); 247 | assert(one == 1); 248 | 249 | // String -> double 250 | var onePeriodOne = double.parse('1.1'); 251 | assert(onePeriodOne == 1.1); 252 | } 253 | ``` 254 | 255 | If you try to convert a trying with alphabets to integers. you will get 256 | FormatException error. 257 | 258 |
259 | 260 | #### Converting to string 261 | 262 | `toString()` 263 | 264 | ```dart 265 | main() { 266 | // int -> String 267 | String oneAsString = 1.toString(); 268 | assert(oneAsString == '1.1'); 269 | 270 | // double -> String 271 | String piAsString = 3.14159.toStringAsFixed(2); 272 | assert(piAsString == '3.14'); 273 | } 274 | ``` 275 | 276 |
277 | 278 | #### Constant variable 279 | 280 | To define a constant variable in dart, use the keyword `const`. 281 | 282 | ```dart 283 | main() { 284 | const aConstNum = 0; 285 | const aConstBool = true; 286 | const aConstString = 'a constant string'; 287 | 288 | print(aConstNum) 289 | print(aConstBool) 290 | print(aConstString) 291 | 292 | print(aConstNum.runtimeType); 293 | print(aConstBool.runtimeType); 294 | print(aConstString.runtimeType); 295 | } 296 | ``` 297 | 298 | By type interface, the compiler will assign the data types to the 299 | variables. 300 | 301 | ```dart 302 | main() { 303 | int num; 304 | print(num); 305 | } 306 | ``` 307 | 308 | **Output** 309 | 310 | ```dart 311 | null 312 | ``` 313 | 314 | We can also specify null 315 | 316 | ```dart 317 | main() { 318 | int num = null; 319 | print(num); 320 | } 321 | ``` 322 | 323 | **Output** 324 | 325 | ```dart 326 | null 327 | ``` 328 | 329 |
330 | 331 | #### Operators 332 | 333 | All the standard operators from C, C++, Java, and Swift will also work 334 | in dart programming language. 335 | 336 | ```dart 337 | void main() { 338 | int num = 10+22; 339 | num = num-2; 340 | print(num); 341 | 342 | num = num % 5; 343 | print(num); 344 | 345 | // relational ==, !=, >=, <=, <, > 346 | if(num == 0) { 347 | print('Zero'); 348 | } 349 | 350 | num = 100; 351 | num *= 2; 352 | 353 | // != Not equal 354 | if(num != 100) { 355 | print('num is not equal'); 356 | } 357 | 358 | //unary operators 359 | ++num; 360 | num++; 361 | num += 1; 362 | num == 1; 363 | print(num); 364 | 365 | //logical operator: &&, ||, ! 366 | if(num > 200 && num < 203) { 367 | print('200 to 202'); 368 | } 369 | } 370 | ``` 371 | 372 |
373 | 374 | #### Null aware operator `?.`, `??`, `??=` 375 | 376 | It is one of the important operator in dart language. These operators 377 | are common in modern programming languages such as Swift, Kotlin.
378 | In Dart, There are 3 variables of this operators. 379 | 380 | Suppose we want to define a class 381 | 382 | ```dart 383 | class Num { 384 | int num = 10; 385 | } 386 | 387 | main() { 388 | var n = Num(); // To create object 389 | int number = 1; 390 | 391 | if(n!==null) { 392 | number = n.num; 393 | } 394 | print(number) 395 | } 396 | ``` 397 | 398 | **Output:** 399 | 400 | ```dart 401 | 10 402 | ``` 403 | 404 | We can check `null` in another method 405 | 406 | ```dart 407 | number = n?.num; 408 | ``` 409 | 410 | this line will replace: 411 | 412 | > if(n!==null) {
413 | > number = n.num;
414 | > } 415 | 416 | **What that line will do?** 417 | 418 | If n is a valid object then access the property name num and assign 419 | its value to number.
420 | If n is a null object, then skip this. 421 | 422 | ```dart 423 | main() { 424 | number = n?.num ?? 0; 425 | print(number); 426 | } 427 | ``` 428 | 429 | ```dart 430 | number = n?.num ?? 0; 431 | ``` 432 | 433 | When this is null, this will be executed. Kind of like assigning a 434 | default value for null objects. 435 | 436 | `??=` 437 | 438 | This will assign a value if the object is null. 439 | 440 | ```dart 441 | int n; 442 | print(n??=100); 443 | print(n); 444 | ``` 445 | 446 | **Output** 447 | 448 | ```dart 449 | 100 450 | ``` 451 | 452 |
453 | 454 | ### Ternary Operator 455 | 456 | ```dart 457 | void main() { 458 | int x = 100; 459 | var result = x % 2 == 0 ? 'Even' : 'Odd'; 460 | print(result); 461 | } 462 | ``` 463 | 464 | **Output** 465 | 466 | ```dart 467 | Even 468 | ``` 469 | 470 |
471 | 472 | ### Type Test Operator 473 | 474 | ```dart 475 | void main() { 476 | var x = 100; 477 | if(x is int) { 478 | print('Integer'); 479 | } 480 | } 481 | ``` 482 | 483 |
484 | 485 | ### Conditional Statements 486 | 487 | ```dart 488 | void main() { 489 | int number = 100; 490 | 491 | // If else ladder 492 | if (number % 2 == 0) { 493 | print('Even'); 494 | } else if (number % 3 == 0) { 495 | print('Odd'); 496 | } else { 497 | print('Confused'); 498 | } 499 | 500 | // Switch Case 501 | 502 | switch (number) { 503 | case 0: 504 | print('Even'); 505 | break; 506 | case 1: 507 | print('Odd'); 508 | break; 509 | default: 510 | print('Confused'); 511 | } 512 | } 513 | ``` 514 | 515 |
516 | 517 | ### Looping Statement: 518 | 519 | ```dart 520 | void main() { 521 | //Standard for loop 522 | for (var i = 1; i <= 10; ++i) { 523 | print(i); 524 | } 525 | 526 | // For in loop 527 | var numbers = [1, 2, 3]; 528 | for (var n in numbers) { 529 | print(n); 530 | } 531 | 532 | // Standard way of accessing it. 533 | for (var i = 0; i < numbers.length; i++) { 534 | print(numbers[i]); 535 | } 536 | 537 | // forEach loop method 1 538 | numbers.forEach((n) => print(n)); 539 | 540 | // forEach loop method2 541 | numbers.forEach(printNum); 542 | 543 | // while loop 544 | int num = 5; 545 | while (num > 0) { 546 | print(num); 547 | num -= 1; 548 | } 549 | 550 | // do while loop 551 | do { 552 | print(num); 553 | num += 1; 554 | } while (num < 5); 555 | } 556 | 557 | void printNum(num) { 558 | print(num); 559 | } 560 | ``` 561 | 562 |
563 | 564 | ### Break and Continue 565 | 566 | ```dart 567 | void main() { 568 | // example for break 569 | for (var i = 0; i < 10; i++) { 570 | if (i > 5) break; 571 | print(i); 572 | } 573 | 574 | // example for continue 575 | for (var j = 0; j < 10; j++) { 576 | if (j % 2 == 0) continue; 577 | print('Odd: $j'); 578 | } 579 | } 580 | ``` 581 | 582 |
583 | 584 | ### Collections 585 | 586 | There are 3 built-in collection types in Dart Language: 587 | 588 | - Lists 589 | - Sets 590 | - Maps 591 | 592 |
593 | 594 | #### List: Ordered collection of values 595 | 596 | In some programming languages it is called array, but 597 | in Dart programming language. It is called list. 598 | 599 | One way to define list is by using List class 600 | 601 | ```dart 602 | List names = ['Jack', 'Jill']; 603 | ``` 604 | 605 |
606 | 607 | #### Copying a list to another variable 608 | 609 | ```dart 610 | var names2 = names1; 611 | ``` 612 | 613 | It will not copy the list.
614 | Here, the names2 will be like a reference to names 1.
615 | Just like how it is in Python.
616 | So, We will use spread operator to copy. (...) 617 | 618 | ```dart 619 | List games = ['TT', 'Chess']; 620 | var games2 = [...games]; 621 | games[1] = 'Football'; 622 | for (var game in games2) { 623 | print(game); 624 | } 625 | ``` 626 | 627 |
628 | 629 | ### Set: Unordered collection of unique items. 630 | 631 | ```dart 632 | // Set Method 1 633 | var halogens = {'Fluorine', 'Chlorine', 'Fluorine'}; 634 | for (var element in halogens) { 635 | print(element); 636 | } 637 | 638 | // Set Method 2 639 | Set friends = {'Ross', 'Chandler'}; 640 | for (var friend in friends) { 641 | print(friend); 642 | } 643 | ``` 644 | 645 | **To define a empty set:** 646 | 647 | ```dart 648 | Set hobbies = {}; 649 | print(hobbies.runtimeType); 650 | ``` 651 | 652 |
653 | 654 | #### Map 655 | 656 | In Dart Programming Language, Map is a collection of (key -> value) 657 | pair of items 658 | 659 | In python, It is known as dictionary 660 | 661 | ```dart 662 | // Map Method 1 663 | 664 | var gifts = { 665 | // Key : Value 666 | 'first': 'Patridge', 667 | 'second': 'Turtledoves', 668 | 'third': 'Golden Rings' 669 | }; 670 | print(gifts['second']); 671 | 672 | //Map Method 2 673 | var folklore = Map(); 674 | 675 | folklore['first'] = 'the 1'; 676 | folklore['second'] = 'cardigan'; 677 | print(folklore); 678 | ``` 679 | 680 |
681 | 682 | ### Functions 683 | 684 | In Dart Programming Language, each function is an object of class 685 | function. 686 | 687 | #### Syntax: 688 | 689 | ```nim 690 | returnType FunctionName(argList) { 691 | 692 | Statements_1; 693 | Statements_2; 694 | 695 | return 696 | } 697 | ``` 698 | 699 |
700 | 701 | #### Arrow function (`=>`) 702 | 703 | Short way to define a function 704 |
Example 705 | 706 | ``` 707 | dynamic square(var n) => n*n; 708 | ``` 709 | 710 |
711 | 712 | #### Anonymous Function 713 | 714 | A function with no name is called Anonymous function in Dart Programming 715 | Language. 716 | 717 | In python, It is known as Lambda Function. 718 | 719 | ```dart 720 | void main() { 721 | showOutput(square(3)); 722 | showOutput(square1(3.5)); 723 | 724 | print(square1.runtimeType); 725 | 726 | var list = ['apples', 'bananas', 'oranges']; 727 | 728 | //wkt, forEach function takes a function as argument 729 | list.forEach(printF); 730 | 731 | //now, lets try to make a anonymous function 732 | list.forEach((item) { 733 | print(item); 734 | }); 735 | } 736 | 737 | void printF(item) { 738 | print(item); 739 | } 740 | 741 | dynamic square(var num) { 742 | return num * num; 743 | } 744 | 745 | // Arrow function => 746 | dynamic square1(var num) => num * num; 747 | 748 | void showOutput(var msg) { 749 | print(msg); 750 | } 751 | ``` 752 | 753 | There are 2 types of parameters in dart programming language: 754 | 755 | - Positional Parameter/Argument 756 | - Named Parameter/Argument 757 | 758 |
759 | 760 | #### Named Parameter 761 | 762 | When you are using named parameter, you have to specify the name of the 763 | parameter when you are calling the function. 764 | 765 | This is applicable for both: arrow & general function. 766 | 767 | ```dart 768 | void main() { 769 | print(sum(num2:4, num1:2)); 770 | dynamic sum({var num1, var num2}) => num1 + num2; 771 | } 772 | ``` 773 | 774 | By default named parameter is optional and, we can also mix positional 775 | and named parameter together. 776 | 777 | ```dart 778 | 779 | void main() { 780 | print(sum(10)); 781 | } 782 | //method 1 783 | dynamic sum(var num1, {var num2}) => num1 + (num ?? 0); 784 | // default 785 | dynamic sum(var num1, {var num2 = 0}) => num1 + (num ?? 0); 786 | // Positional Optional 787 | dynamic sum(var num1, [var num2]) => num1 + (num ?? 0); 788 | ``` 789 | 790 | ## Class 791 | 792 | Blueprint for an actual object 793 | 794 | ```dart 795 | class Person { 796 | String name; 797 | int age; 798 | 799 | // Constructor 800 | 801 | Person(String name, [int age = 18]) { 802 | this.name = name; 803 | this.age = age; 804 | } 805 | 806 | // Person(this.name, [this.age = 18]); is also a constructor 807 | 808 | // named constructor 809 | Person.guest() { 810 | name = 'Guest'; 811 | age = 10; 812 | } 813 | 814 | void showOutput() { 815 | print(name); 816 | print(age); 817 | } 818 | } 819 | 820 | void main() { 821 | Person person1 = Person('Leo', 24); 822 | 823 | // person1.name = 'Leo'; 824 | // person1.age = 20; 825 | 826 | // person1 = Person.guest(); is possible. 827 | Person p2 = Person.guest(); 828 | Person p3 = Person('Jason'); 829 | 830 | person1.showOutput(); 831 | p2.showOutput(); 832 | p3.showOutput(); 833 | } 834 | ``` 835 | 836 |
837 | 838 | ### Static, Final, Const 839 | 840 |
841 | 842 | #### Final 843 | 844 | For data members
845 | when you want to assign the value only once and want it to be fixed, use 846 | final 847 | 848 | There are two ways to define a constant: 849 | 850 | - Using final keyword 851 | - Using Const keyword 852 | 853 | There's a difference in both ways
854 | In `const`, it happens at compile time and once assigned it cannot be 855 | reassigned 856 | 857 | In final within the class the value gets assigned at runtime. So, it can 858 | be changed using the 859 | constructor 860 | 861 | If you want to use a constant value using a constructor within a class, 862 | you have to put static in 863 | front of the `const` variable. 864 | 865 | So, when you use static it becomes the property of the class rather than 866 | the object. static property 867 | is same for all objects. 868 | 869 | To access static variable 870 | 871 | ```dart 872 | className. 873 | ``` 874 | 875 | You can use `final` and `const` outside classes too. 876 | 877 | ```dart 878 | class X { 879 | final name; // type will be defined by inferred value 880 | static const int age = 24; 881 | 882 | X(this.name); 883 | } 884 | 885 | main() { 886 | var x = X('jack'); 887 | print(x.name); 888 | 889 | print(X.age); // to access static object 890 | 891 | var y = X('Jill'); 892 | print(y.name); 893 | 894 | // You can use final and const out of a class too 895 | final artistName = 'Lauv'; 896 | const albums = 2; 897 | 898 | print(artistName); 899 | print(albums); 900 | } 901 | ``` 902 | 903 |
904 | 905 | ### Inheritance 906 | 907 | In dart, we use the extends keyword to implement inheritance. 908 | 909 | ```dart 910 | class Vehicle { 911 | String model; 912 | int year; 913 | 914 | Vehicle(this.model, this.year) { 915 | print(this.model); 916 | print(this.year); 917 | } 918 | 919 | void showOutput() { 920 | print(model); 921 | print(year); 922 | } 923 | } 924 | 925 | class Car extends Vehicle { 926 | double price; 927 | 928 | Car(String model, int year, this.price) : super(model, year); 929 | 930 | void showOutput() { 931 | super.showOutput(); 932 | print(this.price); 933 | } 934 | } 935 | 936 | void main() { 937 | var car1 = Car('Accord', 2014, 150000); 938 | car1.showOutput(); 939 | } 940 | ``` 941 | 942 |
943 | 944 | ### Method Overriding 945 | 946 | Suppose in a class there is a class method and in the sub class there is 947 | a method with the same name and we want to redefine it, it is called 948 | method overriding. 949 | 950 | If we want to let other programmers to know that this method is 951 | overriding, you can use `@override` notation. 952 | 953 | When you use `@override`, above a method signature, that means that the 954 | compiler will know that this method is overriding. 955 | 956 | Incase there is no method of the original name, it will show an error. 957 |
i.e, If in desired, a method is defined with `@override` and there 958 | is no method in base class with the same name, then it shows error like 959 | "Method doesn't override an inherited method". 960 | 961 | This is basically a safety feature in Dart. when you are overriding a 962 | method, if you do not use the `@override` keyword, it would not show an 963 | error. There is no issue for this. 964 | 965 | You have to use `@override` when you don't have control of super class 966 | method implementation. 967 | 968 | Basically the intent of the `@override` notation is to catch situation 969 | when a super class method 970 | renames.
971 | 972 | A member on an independent subclass which used to override the member 973 | could continue silently working with the superclass implementation. 974 | 975 | So, a good practice would be to use `@override` when you override a 976 | superclass method. 977 | 978 | ```dart 979 | class X { 980 | String name; 981 | 982 | X(this.name); 983 | 984 | void showOutput() { 985 | print(this.name); 986 | } 987 | 988 | dynamic square(dynamic val) { 989 | return val * val; 990 | } 991 | } 992 | 993 | class Y extends X { 994 | Y(String name) : super(name); 995 | 996 | @override 997 | void showOutput() { 998 | print(this.name); 999 | print('Hello'); 1000 | } 1001 | 1002 | //not using @override at this time 1003 | dynamic square(dynamic val) { 1004 | print(val); 1005 | return val * val; 1006 | } 1007 | } 1008 | 1009 | void main() { 1010 | Y y1 = Y('Leo'); 1011 | y1.showOutput(); 1012 | var k = y1.square(2); 1013 | print(k); 1014 | } 1015 | ``` 1016 | 1017 |
1018 | 1019 | ### Getter and Setters 1020 | 1021 | They are special methods that provide read and write access to an 1022 | object's properties. 1023 | 1024 | Normally, each instance variable has an implicit getter plus setter if 1025 | appropriate but if you want you can create additional property by 1026 | implementing getters and setters using the get and set keyword 1027 | 1028 | num -> it is a type inherited from Integer and Double 1029 | 1030 | When we have to call a method. we use () parenthesis but when we are 1031 | using the getter or setter, we 1032 | do not need to use parenthesis. 1033 | 1034 | When we want to access any getter, we have to use the dot operator and 1035 | we want to use the setter, we have to call the setter name with an 1036 | assignment operator 1037 | 1038 | ```dart 1039 | class Rectangle { 1040 | num left, top, width, height; 1041 | 1042 | Rectangle(this.left, this.top, this.width, this.height); 1043 | 1044 | //Define two calculated properties: right and bottom 1045 | num get right => left + width; 1046 | set right(num value) => left = value - width; 1047 | num get bottom => top + height; 1048 | set bottom(num value) => top = value - height; 1049 | } 1050 | 1051 | void main() { 1052 | var rect = Rectangle(3, 4, 20, 15); 1053 | print(rect.left); 1054 | rect.right = 12; 1055 | print(rect.left); 1056 | } 1057 | ``` 1058 | 1059 |
1060 | 1061 | ### Exception Handling: 1062 | 1063 | throw, catch, try, finally 1064 | 1065 | To thrown exception, you have to use throw keyword and exception class 1066 | name and within the exception class name you can provide a message 1067 | 1068 | ```dart 1069 | int mustBeGreaterThanZero(int val) { 1070 | if (val <= 0) { 1071 | throw Exception('Value must be greater than zero'); 1072 | } 1073 | return val; 1074 | } 1075 | 1076 | void letsVerifyTheValue(var val) { 1077 | var valueVerification; 1078 | 1079 | try { 1080 | valueVerification = mustBeGreaterThanZero(val); 1081 | } catch (e) { 1082 | print(e); 1083 | } finally { 1084 | if (valueVerification == null) { 1085 | print('Value is not accepted'); 1086 | } else { 1087 | print('Value verifed: $valueVerification'); 1088 | } 1089 | } 1090 | } 1091 | 1092 | void main() { 1093 | letsVerifyTheValue(10); 1094 | letsVerifyTheValue(0); 1095 | } 1096 | ``` 1097 | -------------------------------------------------------------------------------- /Events/Apple/Nov_07_2024/README.md: -------------------------------------------------------------------------------- 1 | # Build faster and more efficient apps 2 | 3 | ###### 3 phases: 4 | - develop, test, monitor 5 | 6 | ###### Monitoring Tools: 7 | - XCode Organizer 8 | - Regressions 9 | - notifications 10 | - Launch reports 11 | 12 | Note: user has to consent to send reports. 13 | 14 | WWDC Videos on Instruments & Templates 15 | 16 | Disk Writes - one of th common causes of slow launch 17 | 18 | ---- 19 | 20 | tools that can be used in development phase: 21 | - Instruments 22 | 23 | Analyze Heap Memory - WWDC24 24 | 25 | ---- 26 | 27 | Tools that can be used in testing phase 28 | 29 | Performance Unit Tests - good to have. 30 | 31 | ###### Add Performance Tests 32 | - app launch time 33 | - time elapsed 34 | - CPU usage 35 | - memory usage 36 | - Disk writes 37 | - Hitches 38 | - OS Signpost durations 39 | 40 | ###### Customize and run tests 41 | - configure iterations 42 | - run tests directly in Xcode 43 | - View measurements 44 | 45 | ###### Run performance tests in automation 46 | - Use xcodebuild to run tests outside of Xcode 47 | - Consume results in the xcresult bundle 48 | - Turn on performance test diagnostics 49 | 50 | it is always reccomended to use physical devices to test performances 51 | 52 | --- 53 | 54 | Develop + Monitoring Phase 55 | 56 | ###### MetricKit 57 | - Create Custom Analtyics 58 | - receive diagnostics and aggregated metrics 59 | - Collect Testflight analytics before release 60 | 61 | MXMetricManagerSubscriber 62 | 63 | ###### Next Steps: 64 | - consult Xcode Organizer to monitor performance 65 | - turning on Regression Notifications 66 | - Investigate runtime issues 67 | - Add performance tests 68 | - collect metricKit data for detailed insights 69 | 70 | --- 71 | 72 | ### Maximize SwiftUI performance by minimizing updates. 73 | - Karthik Sarve 74 | 75 | ###### Resources: 76 | - Introduction to SwiftUI - WWDC20 77 | - SwiftUI Essentials - WWDC24 78 | 79 | ###### Agenda: 80 | - Keep view initializers and bodies simple 81 | - break down monolithic views 82 | - structure dependencies efficiently 83 | 84 | ###### End Goal: 85 | Reduce the _frequency and cost_ of view updates to achieve greate SwiftUI performance. 86 | 87 | ###### When does a view's body run? 88 | - first render 89 | - value change 90 | - dependency change 91 | - identity change 92 | 93 | ###### Keep view initializers and bodies simple 94 | - initializers run often 95 | - body runs when view value canges 96 | - intializers should intialize 97 | - bodies should declare heirarchy 98 | 99 | - ❌ Avoid parsing text or other calculations 100 | - ❌ Avoid loading data from the network or disk 101 | - ✅ a view's body is just for laying out the view 102 | - ❌ avoid extra work or .. 103 | 104 | --- 105 | 106 | ###### Break Down Monolithic Views 107 | 108 | trying to localize the updates to the singular views. 109 | 110 | - Break up large views 111 | - keep dependencies near uses 112 | - identify hot spots with Instruments 113 | 114 | --- 115 | 116 | #### Structure dependencies efficiently 117 | 118 | ###### View dependencies 119 | - Properties 120 | - `@Environment` 121 | - `@State` and `@Binding` 122 | - `ObservableObject` 123 | - `@Observable` - introduced in iOS 17 124 | 125 | 126 | ###### @Observable Macro 127 | - Adds update tracking to model classes 128 | - reading a property establishes a dependency 129 | - works for computed properties 130 | - ℹ️ all assignments trigger updates 131 | 132 | _**Resources:**_ Discover Observation in Swiftui - WWDC23 133 | 134 | ###### Some things to watch out for 135 | - Watch out for `GeometryReader` in `ScrollView` 136 | - Avoid `Environment` churn 137 | - Beware complex nested structs 138 | 139 | ###### Next Steps: 140 | - profile your app with instruments 141 | - break up your large views 142 | - Migrate to `@Observable` 143 | 144 | 145 | _**Resources:**_ 146 | - Data Essentials in SwiftUI - WWDC20 147 | - Demystify SwiftUI performance - WWDC23 148 | 149 | --- 150 | 151 | ### Reduce Your App's Energy Impact 152 | - Karthik Sarve 153 | 154 | ###### What we are gonna look into: 155 | - Understand energy impact 156 | - Key technologies 157 | - Monitor energy usage 158 | 159 | ###### What is energy 160 | 161 | - Energy = Power x Time 162 | - Are we sending a `High Priority` push notification? 163 | - Is it really required/relevant? 164 | 165 | ###### Direct energy usage 166 | - Runtime 167 | - CPU activity 168 | - Network activity 169 | - Location activity 170 | - Push notifications 171 | 172 | ###### Indirect energy usage 173 | - Crashes and stability problems 174 | - Memory use 175 | - Hangs 176 | - Disk writes 177 | 178 | ###### Key Technologies 179 | To provide best experience try to use 180 | - Transitions to background 181 | - Downloading assets 182 | - App refresh tasks 183 | - Processing & Machine Learning 184 | - Live activities 185 | 186 | ###### Limit work into the background 187 | - Finish in-flight work and clean up 188 | - `beginBackgroundTask(withName:expirationHandler)` 189 | - `endBackgroundTask(_:)` 190 | - Let the system know when the work is complete 191 | - Dangling tasks may result in a termination 192 | 193 | ###### Download assets efficiently 194 | - Background `URLSession` 195 | - Intelligently schedules downloads 196 | - Out-of-process design 197 | - Resumable download and upload support 198 | 199 | _Resources:_ 200 | Build robust and resumable file transfers - WWDC23 201 | 202 | ###### Refresh app data periodically 203 | - `BGAppRefreshTask` 204 | - Opportunistic time to update content 205 | - Considers patterns in behavior 206 | - Best for periodic updates 207 | - Background Notifications 208 | - Low priority push notifications required 209 | - Best for infrequent 210 | 211 | ###### Schedule processing work 212 | - `BGProcessingTask` 213 | - suitable for time-consuming work 214 | - considers charging state 215 | - Handles interruption 216 | 217 | ###### Update Live Activities efficiently 218 | - reduce high energy impact with low priority notifications 219 | - reserve higher priority for urgent updates 220 | - Minimize update frequency 221 | - Use `Text(_:format:)` for countdowns - `New` 222 | 223 | _Resources:_ 224 | Update Live Activities with push notifications - WWDC23 225 | 226 | ---- 227 | 228 | #### Monitorig Energy Usage 229 | 230 | ###### Profile Your app 231 | 232 | - Before ship - Energy Gauges, Instruments, XCTest 233 | - After ship - Xcode Organizer, App Store Connect, MetricKit 234 | 235 | SignPosts Blocks in code can be used to identify in logs in Instruments. 236 | 237 | ###### Next Steps 238 | - Leverage energy efficient APIs to provide updates in background 239 | - Monitor and optimize energy usage continuously 240 | - Improve overall performance 241 | 242 | ---- 243 | 244 | ### Speed up Core ML loading and execution 245 | - Sandhya Kundapur 246 | 247 | ###### Machine Learning Models 248 | - how will it impact app size? 249 | - how long will it take to run? 250 | - 251 | 252 | ###### Overview 253 | - Background 254 | - Model analysis 255 | - App analysis 256 | 257 | ###### Background 258 | - workflow 259 | - compute units 260 | - frameworks 261 | - model loading 262 | 263 | ###### Workflow 264 | - `Train` -> `Prepare` -> `Integrate` 265 | 266 | _Resources:_ 267 | - Train your machine learning and AI models on Apple GPUs - WWDC24 268 | - Explore machine learning on Apple platforms - WWDC24 269 | 270 | ###### Compute units 271 | 272 | - the hardware stuff - cpu, gpu, neural engines 273 | 274 | # Framewokrs 275 | 276 | - model integrations 277 | - Core ML, uses MPS Graph(GPUs) & BNNS Graph(CPUs) 278 | 279 | #### Model loading 280 | 281 | - Source Model(`MLPACKAGE`) -> Compile -> Compiled Model(`MLMODELC`) -> Instantiate.. 282 | 283 | ##### Cache policy 284 | 285 | - persists across 286 | - model reload 287 | - app relaunch 288 | - reboot 289 | 290 | - purged when 291 | - storage pressure 292 | - OS update 293 | - model changes or is deleted 294 | 295 | #### Model Analysis 296 | 297 | ###### Preparation 298 | 299 | - PyTorch , CreateML, MLPAckage 300 | 301 | - How long does it take to load? 302 | - how large is the model on the disk? 303 | - how long will it take to colorize an image? 304 | - how does the performance compare across devices? 305 | - model pruning, paletization? 306 | 307 | #### App Analysis 308 | - Core ML Instrument 309 | - `TaskGroup` 310 | 311 | ###### Wrap up 312 | 313 | - how will it impact app size? 314 | - how long will it take to run? 315 | - will the test change in different devices? 316 | 317 | ###### Next steps 318 | 319 | - analyze your models with the Xcode performance report 320 | - profile your machine learning features 321 | - use compression to improve disk space, speed, memory 322 | -------------------------------------------------------------------------------- /Flutter/README.md: -------------------------------------------------------------------------------- 1 | # Flutter Notes 2 | 3 | I took an Udemy Course for this and started writing down the notes. 4 | 5 | #### What is Flutter ? 6 | 7 | - UiFramework 8 | - collection of code packages & utitly functions for writing cross-platform applications. 9 | 10 | ```mermaid 11 | graph TD; 12 | Flutter -> Android; 13 | Flutter -> iOS; 14 | Flutter -> Windows; 15 | Flutter -> macOS; 16 | Flutter -> Linux; 17 | Flutter -> Web; 18 | ``` 19 | -------------------------------------------------------------------------------- /JS/README.md: -------------------------------------------------------------------------------- 1 | # JavaScript Notes 2 | 3 | ### 1. Running a JS 4 | 5 | - No installation needed. 6 | - All web browsers can run JS. 7 | 8 | To code: 9 | 10 | - Sublime Text / VS Code / Atom 11 | - freeCodeCamp Editor 12 | - CodePen - JS & Console 13 | - Scrimba 14 | 15 | --- 16 | 17 | ### 2. Comment Your JS Code 18 | 19 | - Comments are lines of code that JS will intentionally ignore. 20 | - They are just used to create notes for yourself and others about what the 21 | code does. 22 | 23 | ```js 24 | // in-line comment 25 | ``` 26 | 27 | ```js 28 | /* 29 | This is a multi line 30 | comment 31 | */ 32 | ``` 33 | 34 | --- 35 | 36 | ### 3. Datatypes & Variables 37 | 38 | - In CS, data is anything that is meaningful to the computer. 39 | - JS provides 7 different datatypes that you can see. 40 | - Datatypes: 41 | 42 | - Undefined 43 | - null 44 | - boolean 45 | - string 46 | - symbol 47 | - number 48 | - object 49 | 50 | - **string** is any sort of text 51 | - **undefined**: It is something that hasn't been defined. You may have a 52 | variable that you haven't set to be anything yet. 53 | - **null** means nothing. You've set it to be something and that sometimes 54 | is nothing. 55 | - **boolean**: means true or false. 56 | - **symbol**: It is an immutable primitive value that is unique. 57 | - **object** can store a lot of different key value pairs. 58 | 59 | - You are often going to set data into a variable. 60 | - A variable allows computers to store and manipulate data in a dynamic 61 | fashion. 62 | - It is basically a lable to point to the data. 63 | - A variable is almost like a box and you can fill it with anything. 64 | 65 | ##### Declaring variables 66 | 67 | - To declare a variable, one way is to use the `var` keyword. 68 | - `var` stands for variable. 69 | - It can be set to anything and can be of any datatypes above but it's 70 | common to set it to a string. 71 | - Example: 72 | 73 | ```js 74 | var myName = "Kamal"; 75 | ``` 76 | 77 | - There are 3 ways to declare a variable in JS. 78 | - 2nd way is using `let` keyword. 79 | - Example: 80 | 81 | ```js 82 | let ourName = "freeCodeCamp"; 83 | ``` 84 | 85 | - The third way is to use `const`. 86 | - Example: 87 | 88 | ```js 89 | const pi = 3.14; 90 | ``` 91 | 92 | ##### The difference between `var`, `let` & `const` 93 | 94 | - `var` is going to be able to be used throughout your whole program. 95 | - `let` will only be used within the scope of where you declare it. 96 | - `const` is a variable that should never & can never change. i.e., it is 97 | immutable. 98 | 99 | --- 100 | 101 | ### 4. Storing values with Assignment Operator 102 | 103 | - There is a difference between declaring variables and assigning variables. 104 | - Example: 105 | 106 | ```js 107 | var a; // declaration 108 | var b = 2; // declaration + assignment 109 | // It means '2' is assigned to 'b' 110 | a = 7; // just assignment 111 | ``` 112 | 113 | --- 114 | 115 | ### 5. Initializing variables with Assignment operator 116 | 117 | ```js 118 | var a = 9; 119 | ``` 120 | 121 | --- 122 | 123 | ### 6. Uninitialized variables 124 | 125 | Example: 126 | 127 | ```js 128 | var a; 129 | var b; 130 | var c; 131 | ``` 132 | 133 | - They are uninitialized. 134 | - That means their value is undefined. 135 | - We have not set them to anything. 136 | 137 | So, 138 | 139 | ```js 140 | var a = 5; 141 | var b = 10; 142 | var c = "I am a "; 143 | 144 | a = a + 1; 145 | b = b + 5; 146 | c = c + "String!"; 147 | 148 | console.log(a); 149 | console.log(b); 150 | console.log(c); 151 | ``` 152 | 153 | ##### Output 154 | 155 | ``` 156 | 6 157 | 15 158 | I am a String! 159 | ``` 160 | 161 | --- 162 | 163 | ### 7. Case sensitivity in variable 164 | 165 | - Variable names and function names in JS are case-sensitive. 166 | - That means the capitalization matters. 167 | 168 | So, 169 | 170 | ```js 171 | var aBc; 172 | ABC = 10; 173 | ``` 174 | 175 | - Both are not the same even though they have the same letters. 176 | - General practice is to use camel case. 177 | 178 | --- 179 | 180 | ### 8. Adding numbers 181 | 182 | - Adding 2 numbers in JS is pretty straightforward. 183 | - You use the `+` operator. 184 | 185 | ```js 186 | var sum = 10 + 10; 187 | console.log(sum); 188 | ``` 189 | 190 | ##### Output 191 | 192 | ``` 193 | 20 194 | ``` 195 | 196 | --- 197 | 198 | ### 9. Subtracting Numbers 199 | 200 | - The `-` operator is used. 201 | 202 | ```js 203 | var diff = 45 - 33; 204 | console.log(diff); 205 | ``` 206 | 207 | ##### Output 208 | 209 | ``` 210 | 12 211 | ``` 212 | 213 | --- 214 | 215 | ### 10. Multiplying Numbers 216 | 217 | - The `*` operator is used. 218 | 219 | ```js 220 | var product = 8 * 10; 221 | console.log(product); 222 | ``` 223 | 224 | ##### Output 225 | 226 | ``` 227 | 80 228 | ``` 229 | 230 | --- 231 | 232 | ### 11. Dividing numbers 233 | 234 | - The `/` operator is used. 235 | 236 | ```js 237 | var quotient = 66 / 33; 238 | console.log(quotient); 239 | ``` 240 | 241 | ##### Output 242 | 243 | ``` 244 | 2 245 | ``` 246 | 247 | --- 248 | 249 | ### 12. Incrementing Numbers 250 | 251 | - To increment a number, add `1` to it. 252 | 253 | ```js 254 | var myVar = 87; 255 | myVar = myVar + 1; 256 | console.log(myVar); 257 | 258 | myVar++; 259 | console.log(myVar); 260 | 261 | myVar += 1; 262 | console.log(myVar); 263 | 264 | ++myVar; 265 | console.log(myVar); 266 | ``` 267 | 268 | ##### Output 269 | 270 | ``` 271 | 88 272 | 89 273 | 90 274 | 91 275 | ``` 276 | 277 | --- 278 | 279 | ### 13. Decrementing Numbers 280 | 281 | - To decrement a number, subtract `1` from it. 282 | 283 | ```js 284 | var myVar = 11; 285 | myVar = myVar - 1; 286 | console.log(myVar); 287 | 288 | myVar--; 289 | console.log(myVar); 290 | 291 | myVar -= 1; 292 | console.log(myVar); 293 | 294 | --myVar; 295 | console.log(myVar); 296 | ``` 297 | 298 | ##### Output 299 | 300 | ``` 301 | 10 302 | 9 303 | 8 304 | 7 305 | ``` 306 | 307 | --- 308 | 309 | ### 14. Decimal Numbers 310 | 311 | - These arealso referred to as floating point numbers or floats. 312 | - Example: 313 | - Any number that has a decimal point in it is a decimal point number. 314 | 315 | ```js 316 | var ourDecmial = 5.7; 317 | ``` 318 | 319 | --- 320 | 321 | ### 15. Multiply Decimals 322 | 323 | - It is same as multiplying integers. 324 | - `*` operator is used. 325 | 326 | ```js 327 | var product = 2.05 * 2.5; 328 | console.log(product); 329 | ``` 330 | 331 | ##### Output 332 | 333 | ``` 334 | 5.125 335 | ``` 336 | 337 | --- 338 | 339 | ### 16. Dividing Decimals 340 | 341 | - It is same as dividing integers. 342 | - `/` operator is used. 343 | 344 | ```js 345 | var quotient = 4.4 / 2.0; 346 | console.log(quotient); 347 | ``` 348 | 349 | ##### Output 350 | 351 | ``` 352 | 2.2 353 | ``` 354 | 355 | --- 356 | 357 | ### 17. Finding a remainderr 358 | 359 | - The modulo `%` operator gives us the remainder of 2 numbers. 360 | - Example: 361 | 362 | ```js 363 | var remainder = 11 % 3; 364 | console.log(remainder); 365 | ``` 366 | 367 | ##### Output 368 | 369 | ``` 370 | 2 371 | ``` 372 | 373 | --- 374 | 375 | ### 18. Compound Assignment with Augmented Addition 376 | 377 | ```js 378 | var a = 3; 379 | var b = 17; 380 | var c = 12; 381 | 382 | a = a + 12; 383 | b = a + b; 384 | c = c + 7; 385 | 386 | // The above statements can be written as 387 | 388 | a += 12; 389 | b += a; 390 | c += 7; 391 | ``` 392 | 393 | --- 394 | 395 | ### 19. Compound Assignment with Augmented Subtraction 396 | 397 | ```js 398 | var a = 11; 399 | var b = 9; 400 | var c = 3; 401 | 402 | a = a - 6; 403 | b = b - 15; 404 | c = c + 1; 405 | 406 | // The above statements can be written as 407 | 408 | a -= 6; 409 | b -= 15; 410 | c -= 1; 411 | ``` 412 | 413 | --- 414 | 415 | ### 20. Compound Assignment with Augmented Multiplication 416 | 417 | ```js 418 | var a = 5; 419 | var b = 12; 420 | var c = 4.6; 421 | 422 | a = a * 5; 423 | b = b * 3; 424 | c = c * 10; 425 | 426 | // The above statements can be written as 427 | 428 | a *= 5; 429 | b *= 3; 430 | c *= 10; 431 | ``` 432 | 433 | --- 434 | 435 | ### 21. Compound Assignment with Augmented Division 436 | 437 | ```js 438 | var a = 48; 439 | var b = 108; 440 | var c = 33; 441 | 442 | a = a / 12; 443 | b = b / 4; 444 | c = c / 11; 445 | 446 | // The above statements can be written as 447 | 448 | a /= 12; 449 | b /= 4; 450 | c /= 11; 451 | ``` 452 | 453 | --- 454 | 455 | ### 22. Declaring String Variables 456 | 457 | - Can be enclosed in either single quotes or the double quotes. 458 | 459 | ```js 460 | var firstName = "Alan"; 461 | var lastName = "Turning"; 462 | ``` 463 | 464 | --- 465 | 466 | ### 23. Escaping Literal Quotes in Strings 467 | 468 | Example: 469 | 470 | ```js 471 | var myStr = 'I am a "double quoted" string inside "double quotes"'; 472 | console.log(myStr); 473 | ``` 474 | 475 | ##### Output 476 | 477 | ``` 478 | I am a "double quoted" string inside "double quotes" 479 | ``` 480 | 481 | --- 482 | 483 | ### 24. Quoting Strings with Single Quotes 484 | 485 | - Instead of using escape sequences you can first enclose the entire string 486 | in single quotes and then can use the double quotes in it. 487 | 488 | ```js 489 | var myStr = 'link'; 490 | ``` 491 | 492 | - To use single quotes and double quotes you can use back ticks. 493 | 494 | ```js 495 | var myStr = `'link'`; 496 | console.log(myStr); 497 | ``` 498 | 499 | ##### Output 500 | 501 | ``` 502 | 'link' 503 | ``` 504 | 505 | --- 506 | 507 | ### 25. Escape Sequence in Strings 508 | 509 | | Code | Output | 510 | | ---- | --------------- | 511 | | `\'` | single quote | 512 | | `\"` | double quote | 513 | | `\\` | back slash | 514 | | `\n` | new line | 515 | | `\r` | carriage return | 516 | | `\t` | tab | 517 | | `\b` | back space | 518 | | `\f` | form feed | 519 | 520 | ```js 521 | var myStr = "First Line \n\t\\Second Line\nThird Line"; 522 | console.log(myStr); 523 | ``` 524 | 525 | ##### Output 526 | 527 | ``` 528 | First Line 529 | \Second Line 530 | Third Line 531 | ``` 532 | 533 | --- 534 | 535 | ### 26. Concatenating Strings With Plus Operator 536 | 537 | ```js 538 | var str1 = "first" + "second"; 539 | var str2 = "start" + "end"; 540 | console.log(str1); 541 | console.log(str2); 542 | ``` 543 | 544 | ##### Output 545 | 546 | ``` 547 | firstsecond 548 | startend 549 | ``` 550 | 551 | --- 552 | 553 | ### 27. Concatenating Strings with Plus Equals operator. 554 | 555 | ```js 556 | var str1 = "first"; 557 | str1 += "second"; 558 | console.log(str1); 559 | ``` 560 | 561 | ##### Output 562 | 563 | ``` 564 | firstsecond 565 | ``` 566 | 567 | --- 568 | 569 | ### 28. Constructing Strings with variables 570 | 571 | ```js 572 | var myName = "Alan"; 573 | var str = "My name is " + myName + "."; 574 | console.log(str); 575 | ``` 576 | 577 | ##### Output 578 | 579 | ``` 580 | My name is Alan. 581 | ``` 582 | 583 | --- 584 | 585 | ### 29. Appending variables to Strings 586 | 587 | ```js 588 | var anAdjective = "awesome"; 589 | var myStr = "I am "; 590 | myStr += anAdjective; 591 | console.log(myStr); 592 | ``` 593 | 594 | ##### Output 595 | 596 | ``` 597 | I am awesome 598 | ``` 599 | 600 | --- 601 | 602 | ### 30. Finding the length of a string 603 | 604 | ```js 605 | var nameLength = 0; 606 | var myName = "Alan"; 607 | nameLength = myName.length; 608 | console.log(nameLength); 609 | ``` 610 | 611 | ##### Output 612 | 613 | ``` 614 | 4 615 | ``` 616 | 617 | --- 618 | 619 | ### 31. Bracket Notation to find first character in string 620 | 621 | ```js 622 | var name = "Alan"; 623 | var firstCharacter = name[0]; 624 | console.log(firstCharacter); 625 | ``` 626 | 627 | ##### Output 628 | 629 | ``` 630 | A 631 | ``` 632 | 633 | --- 634 | 635 | ### 32. String Immutability 636 | 637 | - Strings are immutable. i.e., they cannot be altered once created. 638 | - This does not mean they cannot be changed. 639 | - Just that the individual characters of a string literal cannot be changed. 640 | 641 | ```js 642 | var myStr = "Jello"; 643 | myStr[0] = "H"; // Not Possible 644 | myStr = "Hello"; // Possible 645 | ``` 646 | 647 | --- 648 | 649 | ### 33. Bracket Notation to find Nth Character in String 650 | 651 | ```js 652 | var firstName = "Ada"; 653 | var secondLetterOfFirstName = firstName[1]; 654 | console.log(secondLetterOfFirstName); 655 | 656 | var lastName = "Lovelace"; 657 | var thirdLetterOfLastName = lastName[2]; 658 | console.log(thirdLetterOfLastName); 659 | ``` 660 | 661 | ##### Output 662 | 663 | ``` 664 | d 665 | v 666 | ``` 667 | 668 | --- 669 | 670 | ### 34. Bracket Notation to Find Last Character in String 671 | 672 | ```js 673 | var firstName = "Ada"; 674 | var lastLetterOfFirstName = firstName[firstName.length - 1]; 675 | console.log(lastLetterOfFirstName); 676 | 677 | // var lastName = "Lovelace"; 678 | ``` 679 | 680 | ##### Output 681 | 682 | ``` 683 | a 684 | ``` 685 | 686 | --- 687 | 688 | ### 35. Bracket Notation to Find Nth-to-Last Character in String 689 | 690 | ```js 691 | var firstName = "Ada"; 692 | var secondLastLetterOfFirstName = firstName[firstName.length - 2]; 693 | console.log(secondLastLetterOfFirstName); 694 | ``` 695 | 696 | ##### Output 697 | 698 | ``` 699 | d 700 | ``` 701 | 702 | --- 703 | 704 | - In the arrays you can have any datatype. 705 | 706 | ```js 707 | var arr = ["Jan", 24]; 708 | console.log(arr); 709 | ``` 710 | 711 | - A nested array looks like this: 712 | 713 | ```js 714 | var arr = [ 715 | ["Bulls", 23], 716 | ["White Sox", 34], 717 | ]; 718 | ``` 719 | 720 | - Indexing works with arrays too. 721 | - Array indexes can be used to modify the data at a given index. 722 | - Bracket notation `[]` can be used to access elements of a multi-dimensional 723 | arrays. 724 | - Data can be appended to the end of an array using the `push()` function. 725 | It needs the value to be pushed as an argument. 726 | - Data can be removed from the end of an array using the `pop()` function. 727 | It returns the element removed. 728 | - Data can be removed from the start of an array using the `shift()` function. 729 | It returns the element removed. 730 | - Data can be appended to the start of an array using the `unshift()` 731 | function. It needs the value to be pushed as an argument. 732 | - Functions allow us to create reusable codes. 733 | - It is possible to assign a variable without using `var` keyword. 734 | If done such way, then the variable becoms global. 735 | - You can use `===` for strict equality checking. 736 | - You can use `!==` for strict inequality checking. 737 | - The usual comparision operators [`>`, `<`, `>=`, `<=`,] apply to JS too. 738 | - The usual logical operators [`!`, `&&`, `||`] apply to JS too. 739 | - If-else condition is also same as CPP. 740 | - Switch case concepts is same as CPP. 741 | - Switch case fall through is also present. 742 | 743 | --- 744 | 745 | - Object's values can be used through the `.` operator or the `[]` notation. 746 | - To delete a property use `delete .`. 747 | - To check if a object has a specific property: 748 | `.hasOwnProperty(<"propertyName">)`. It is often used with if 749 | condition. 750 | 751 | --- 752 | 753 | ### Record Collection 754 | 755 | ```js 756 | /* Question: 757 | If the value is an empty string remove that property. 758 | If the property is tracks and if you have a value, instead of updating the 759 | whole tracks, append the new value to the end of the tracks. 760 | If the object does not have the property mentioned then create it. 761 | */ 762 | 763 | var collection = { 764 | 2548: { 765 | album: "Slippery When Wet", 766 | artist: "Bon Jovi", 767 | tracks: ["Let it Rock", "You Give Love a Bad Name"], 768 | }, 769 | 2468: { 770 | album: "1999", 771 | artist: "Prince", 772 | tracks: ["1999", "Little Red Corvette"], 773 | }, 774 | 1245: { 775 | artist: "Robert Palmer", 776 | tracks: [], 777 | }, 778 | 5439: { 779 | album: "ABBA Gold", 780 | }, 781 | }; 782 | 783 | // Making a copy of the orginal object 784 | var collectionCopy = JSON.parse(JSON.stringify(collection)); 785 | 786 | // Answer starts here. 787 | function updateRecords(id, prop, value) { 788 | // if value is blank, remove the property 789 | if (value === "") { 790 | delete collection[id][prop]; 791 | } else if (prop === "tracks") { 792 | // if the tracks property is doesn't exist, we need to create it 793 | collection[id][prop] = collection.[id][prop] || []; 794 | collection[id][prop].push(value); 795 | } else { 796 | collection[id][prop] = value; 797 | } 798 | 799 | return collection; 800 | } 801 | 802 | updateRecords(2468, "tracks", "test"); 803 | console.log(updateRecords(5439, "artist", "ABBA")); 804 | ``` 805 | 806 | --- 807 | 808 | - `Math.random()` returns a random number `[0, 1)` 809 | - `Math.floor(Math.random() * n)` to generate random whole numbers `[0, n)` 810 | - To get a random number 2 limits: 811 | 812 | ```js 813 | function randomRange(myMin, myMax) { 814 | return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin; 815 | } 816 | 817 | console.log(randomRange(5, 15)); 818 | ``` 819 | 820 | - `parseInt()` takes in a string and returns an integer 821 | - `parseInt()` can also be used with a radix. i.e. bases. 822 | - Ternary operator `?:` concept is same as CPP. 823 | - Even though an array is declared as `const`, it can still be mutated. 824 | 825 | ```js 826 | const = [5, 7, 2]; 827 | function editInPlace() { 828 | // s = [2, 7, 2]; This type of direct assignment is not possible. 829 | 830 | // This is possible 831 | s[0] = 2; 832 | s[1] = 5; 833 | s[2] = 7; 834 | } 835 | editInPlace(); 836 | console.log(s); 837 | ``` 838 | 839 | - `Object.freeze();` prevents mutation even when `const` is used. 840 | 841 | --- 842 | 843 | ### Use Arrow functions to write concise anonymous functions 844 | 845 | ```js 846 | // Example of an anonymous function 847 | var magic = function () { 848 | return new Date(); 849 | }; 850 | ``` 851 | 852 | - Whenever you have an anonymous function, you can convert it to arrow a 853 | function. 854 | - The above thing can be done as: 855 | 856 | ```js 857 | // Example of an arrow function 858 | var magic = () => { 859 | return new Date(); 860 | }; 861 | ``` 862 | 863 | - The above line can still be simplified. 864 | 865 | ```js 866 | var magic = () => new Date(); 867 | // Instead of `var`, `const` could be used. 868 | ``` 869 | 870 | - Arrow functions with parameters 871 | 872 | ```js 873 | // anonymous function 874 | var myConcat = function (arr1, arr2) { 875 | return arr1.concat(arr2); 876 | }; 877 | console.log(myConcat([1, 2], [3, 4, 5])); 878 | 879 | // arrow function 880 | var myConcat = (arr1, arr2) => arr1.concat(arr2); 881 | console.log(myConcat([1, 2], [3, 4, 5])); 882 | // Once again, instead of `var`, `const` could be used. 883 | ``` 884 | 885 | --- 886 | 887 | ### Writing Higher Order Arrow Functions 888 | 889 | - Arrow functions work really well with higher order functions(HOF) 890 | such as `map`, `filter` and `reduce` 891 | - HOFs take functions as arguments for processing collections of data. 892 | - Whenever one function takes another function as an argument, that is a 893 | good time to use an arrow function. 894 | 895 | ```js 896 | // Question: Get the square of positive integers. 897 | 898 | const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8, 8.34, -2]; 899 | 900 | const squareList = (arr) => { 901 | // This line is succint because of the arrow functions 902 | 903 | const squaredIntegers = arr 904 | .filter( 905 | // The filter function is going to give us the positive integers 906 | // Usually you use paranthesis for arrow functions. 907 | // but if you have a single argument it is not needed. 908 | (num) => Number.isInteger(num) && num > 0 909 | ) 910 | .map( 911 | // To get the square of each number in the array we are using map() 912 | // x means every element from the array that is passed to it 913 | (x) => x * x 914 | ); 915 | return squaredIntegers; 916 | }; 917 | 918 | const squaredIntegers = squaredList(realNumberArray); 919 | console.log(squaredIntegers); 920 | ``` 921 | 922 | --- 923 | 924 | #### Rest Operator 925 | 926 | - The rest operator allows you to create a function that takes a variable 927 | number of arguments. 928 | - The rest operator is 3 dots `...` 929 | 930 | ```js 931 | const sum = (function () { 932 | return function sum(...args) { 933 | return args.reduce((a, b) => a + b, 0); 934 | }; 935 | })(); 936 | 937 | console.log(sum(1, 2, 3, 4, 5)); 938 | ``` 939 | 940 | #### Use the spread operator to evaluate arrays in-place 941 | 942 | - The spread operator looks just like the rest operator (3 dots `...`) 943 | - It expands an already existing array or it spreads out an array. 944 | - It takes an array and spreads out into its individual parts. 945 | - So, it can be used to make a copy of an existing variable. 946 | 947 | ```js 948 | const arr1 = ["JAN", "FEB", "MAR", "APR", "MAY"]; 949 | let arr2; 950 | 951 | (function () { 952 | arr2 = [...arr1]; 953 | arr1[0] = "potato"; 954 | })(); 955 | console.log(arr2); 956 | ``` 957 | 958 | #### Use destructuring assignment to assign variables from objects 959 | 960 | ```js 961 | var voxel = { x: 3.6, y: 7.4, z: 6.54 }; 962 | 963 | // Old way of reading the object's values and assigning to another variable 964 | var x = voxel.x; // x = 3.6 965 | var y = voxel.y; // y = 7.4 966 | var z = voxel.z; // z = 6.54 967 | 968 | // New way of doing things. 969 | // The values of x, y, z from the object are assigned to a, b, c respectively 970 | const { x: a, y: b, z: c } = voxel; // a = 3.6, b = 7.4, c = 6.54 971 | ``` 972 | 973 | #### Destructuring assignment with nested objects 974 | 975 | ```js 976 | const LOCAL_FORECAST = { 977 | today: { min: 72, max: 83 }, 978 | tomorrow: { min: 73.3, max: 84.6 }, 979 | }; 980 | 981 | function getMaxOfTomorrow(forecast) { 982 | const { 983 | tomorrow: { max: maxOfTomorrow }, 984 | } = forecast; 985 | return maxOfTomorrow; 986 | } 987 | 988 | console.log(getMaxOfTomorrow(LOCAL_FORECAST)); 989 | ``` 990 | 991 | #### Use Destructuring Assignment to Assign Variables from Arrays 992 | 993 | - You can use destructuring assignment to assign variables from arrays. 994 | 995 | ```js 996 | const [z, x] = [1, 2, 3, 4, 5, 6]; 997 | console.log(z, x); 998 | // 1,2 999 | // assigns the first 2 elements of the array to z and x respectively. 1000 | ``` 1001 | 1002 | - The difference between destructuring from arrays and destructuring from 1003 | objects is that you cannot specify which element from the array should go 1004 | into a variable. 1005 | - It just goes in order. 1006 | - However, if you want the 4th element, you can add empty commas. 1007 | 1008 | ```js 1009 | const [z, x, , y] = [1, 2, 3, 4, 5, 6]; 1010 | console.log(z, x, y); 1011 | // 1,2,4 1012 | ``` 1013 | 1014 | - You can use destructuring of arrays to switch the places of variables. 1015 | 1016 | ```js 1017 | let a = 8, 1018 | b = 6; 1019 | 1020 | (() => { 1021 | [a, b] = [b, a]; 1022 | })(); 1023 | 1024 | console.log(a); 1025 | console.log(b); 1026 | ``` 1027 | 1028 | #### Use destructuring assignment with the rest operator 1029 | 1030 | - We can do it to re-assign array elements. 1031 | 1032 | ```js 1033 | const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 1034 | function removeFirstTwo(list) { 1035 | const [, , ...arr] = list; 1036 | 1037 | return arr; 1038 | } 1039 | 1040 | const arr = removeFirstTwo(source); 1041 | console.log(arr); 1042 | console.log(source); 1043 | ``` 1044 | 1045 | ##### Output 1046 | 1047 | ``` 1048 | [ 1049 | 3, 4, 5, 6, 1050 | 7, 8, 9, 10 1051 | ] 1052 | [ 1053 | 1, 2, 3, 4, 5, 1054 | 6, 7, 8, 9, 10 1055 | ] 1056 | ``` 1057 | 1058 | #### Use destructuring assignment to pass an object as a function's parameters 1059 | 1060 | ```js 1061 | const stats = { 1062 | max: 56.78, 1063 | standard_deviation: 4.34, 1064 | median: 34.54, 1065 | mode: 23.87, 1066 | min: -0.75, 1067 | average: 35.85, 1068 | }; 1069 | const half = (function () { 1070 | return function half({ max, min }) { 1071 | return (max + min) / 2.0; 1072 | }; 1073 | })(); 1074 | console.log(stats); 1075 | console.log(half(stats)); 1076 | ``` 1077 | 1078 | ##### Output 1079 | 1080 | ``` 1081 | { 1082 | max: 56.78, 1083 | standard_deviation: 4.34, 1084 | median: 34.54, 1085 | mode: 23.87, 1086 | min: -0.75, 1087 | average: 35.85 1088 | } 1089 | 28.015 1090 | ``` 1091 | 1092 | #### Creating Strings using Template Literals 1093 | 1094 | ```js 1095 | const person = { 1096 | name: "Zodiac Hasbro", 1097 | age: 56, 1098 | }; 1099 | 1100 | // Template literal with multi-line and string interpolation 1101 | const greeting = `Hello, my name is ${person.name}! 1102 | I am ${person.age} years old.`; 1103 | 1104 | console.log(greeting); 1105 | 1106 | const result = { 1107 | success: ["max-length", "no-amd", "prefer-arrow-functions"], 1108 | failure: ["no-var", "var-on-top", "linebreak"], 1109 | skipped: ["id-blacklist", "no-dup-keys"], 1110 | }; 1111 | function makeList(arr) { 1112 | const resultDisplayArray = []; 1113 | for (let i = 0; i < arr.length; i++) { 1114 | resultDisplayArray.push(`
  • ${arr[i]}
  • `); 1115 | } 1116 | 1117 | return resultDisplayArray; 1118 | } 1119 | /** 1120 | * makeList(result.failure) should return: 1121 | * [ `
  • no-var
  • `, 1122 | * `
  • var-on-top
  • `, 1123 | * `
  • linebreak
  • ` ] 1124 | **/ 1125 | const resultDisplayArray = makeList(result.failure); 1126 | 1127 | console.log(resultDisplayArray); 1128 | ``` 1129 | 1130 | ##### Output 1131 | 1132 | ``` 1133 | Hello, my name is Zodiac Hasbro! 1134 | I am 56 years old. 1135 | [ 1136 | '
  • no-var
  • ', 1137 | '
  • var-on-top
  • ', 1138 | '
  • linebreak
  • ' 1139 | ] 1140 | ``` 1141 | 1142 | #### Write Concise Object Literal Declarations Using Simple Fields 1143 | 1144 | Usually we do this 1145 | 1146 | ```js 1147 | const createPerson = (name, age, gender) => { 1148 | return { 1149 | name: name, 1150 | age: age, 1151 | gender: gender, 1152 | }; 1153 | }; 1154 | console.log(createPerson("Zodiac Hasbro", 56, "male")); 1155 | ``` 1156 | 1157 | - In the above example we have the `name:name`, `age:age` and `gender:gender`. 1158 | - Instead of doing that, you can just do this: 1159 | 1160 | ```js 1161 | const createPerson = (name, age, gender) => ({ name, age, gender }); 1162 | console.log(createPerson("Zodiac Hasbro", 56, "male")); 1163 | ``` 1164 | 1165 | #### Write Concise Declarative Functions with ES6 1166 | 1167 | - Old roundabout way of using a funciton inside an object 1168 | 1169 | ```js 1170 | const bicycle = { 1171 | gear: 2, 1172 | setGear: function (newGear) { 1173 | this.gear = newGear; 1174 | }, 1175 | }; 1176 | 1177 | bicycle.setGear(3); 1178 | console.log(bicycle.gear); 1179 | ``` 1180 | 1181 | - ES6 way of doing it - just removed the `: function` part 1182 | 1183 | ```js 1184 | const bicycle = { 1185 | gear: 2, 1186 | setGear(newGear) { 1187 | this.gear = newGear; 1188 | }, 1189 | }; 1190 | 1191 | bicycle.setGear(3); 1192 | console.log(bicycle.gear); 1193 | ``` 1194 | 1195 | #### Use class Syntax to Define a Constructor Function 1196 | 1197 | - Older way of creating object with a `new` keyword. 1198 | 1199 | ```js 1200 | var SpaceShuttle = function (targetPlanet) { 1201 | this.targetPlanet = targetPlanet; 1202 | }; 1203 | var zeus = new SpaceShuttle("Jupiter"); 1204 | 1205 | console.log(zeus.targetPlanet); 1206 | ``` 1207 | 1208 | - ES6 way of doing things: 1209 | 1210 | ```js 1211 | class SpaceShuttle { 1212 | constructor(targetPlanet) { 1213 | this.targetPlanet = targetPlanet; 1214 | } 1215 | } 1216 | var zeus = new SpaceShuttle("Jupiter"); 1217 | 1218 | console.log(zeus.targetPlanet); 1219 | ``` 1220 | 1221 | - Example 2 1222 | 1223 | ```js 1224 | function makeClass() { 1225 | class Vegetable { 1226 | constructor(name) { 1227 | this.name = name; 1228 | } 1229 | } 1230 | return Vegetable; 1231 | } 1232 | const Vegetable = makeClass(); 1233 | const carrot = new Vegetable("carrot"); 1234 | console.log(carrot.name); 1235 | ``` 1236 | 1237 | #### Use getters and setters to Control Access to an Object 1238 | 1239 | - Example 1 1240 | 1241 | ```js 1242 | class Book { 1243 | constructor(author) { 1244 | this._author = author; 1245 | } 1246 | // getter 1247 | get writer() { 1248 | return this._author; 1249 | } 1250 | // setter 1251 | set writer(updatedAuthor) { 1252 | this._author = updatedAuthor; 1253 | } 1254 | } 1255 | ``` 1256 | 1257 | - Example 2 1258 | 1259 | ```js 1260 | function makeClass() { 1261 | class Thermostat { 1262 | constructor(temp) { 1263 | this._temp = (5 / 9) * (temp - 32); 1264 | } 1265 | get temperature() { 1266 | return this._temp; 1267 | } 1268 | set temperature(updatedTemp) { 1269 | this._temp = updatedTemp; 1270 | } 1271 | } 1272 | return Thermostat; 1273 | } 1274 | 1275 | const Thermostat = makeClass(); 1276 | const thermos = new Thermostat(76); 1277 | let temp = thermos.temperature; 1278 | thermos.temperature = 26; 1279 | temp = thermos.temperature; 1280 | console.log(temp); 1281 | ``` 1282 | 1283 | #### Why Using Getters and Setters? 1284 | 1285 | - It gives simpler syntax 1286 | - It allows equal syntax for properties and methods 1287 | - It can secure better data quality 1288 | - It is useful for doing things behind-the-scenes 1289 | - It's perfect for classes that will usually only be instantiated 1290 | once per include. 1291 | 1292 | #### Understand the differences between require and import 1293 | 1294 | - In the past people would use the require function to import functions and 1295 | code from other files. 1296 | - But now we have import and export. 1297 | - You can export code from one file and import it in another file. 1298 | - It also allows you to only import certain functions or certain variables. 1299 | 1300 | ```js 1301 | // string_function.js 1302 | export const capitalizeString = str => str.toUpperCase() 1303 | ``` 1304 | 1305 | ```js 1306 | // index.js 1307 | import { capitalizeString } from "./string_function" 1308 | const cap = capitalizeString("hello!"); 1309 | 1310 | console.log(cap); 1311 | ``` 1312 | 1313 | #### Use export export to reuse a code block 1314 | 1315 | ```js 1316 | const capitalizeString = (string) => { 1317 | return string.charAt(0).toUpperCase() + string.slice(1); 1318 | } 1319 | 1320 | export { capitalizeString }; 1321 | 1322 | export const foo = "bar"; 1323 | export const bar = "foo"; 1324 | ``` 1325 | 1326 | #### Use * to Import Everything from a File 1327 | 1328 | ```js 1329 | import * as capitalizeStrings from "capitalize_strings"; 1330 | 1331 | // capitalizeStrings is the object name. 1332 | // The object name can be anything but for best practices it is recommended 1333 | // to use the camel casing of the imported file. 1334 | // It is through this object we will access imported objects. 1335 | ``` 1336 | 1337 | #### Create an Export Fallback with export default 1338 | 1339 | - In the previous exports, we saw about named exports. 1340 | - There is also something called as export defaults. 1341 | - This is a fallback export and it is often used if you want to export 1342 | only one thing from a file. 1343 | 1344 | ```js 1345 | export default function subtract(x,y) {return x - y;} 1346 | ``` 1347 | 1348 | #### Import a default export 1349 | 1350 | - It is pretty much the same as before but there is a slight difference. 1351 | - Lets say we have a file `math_functions.js` and in that we have a default 1352 | export `subtract`. 1353 | - The difference is we won't be using curly braces for default import but we 1354 | still have to say what it is from. i.e. `math_functions`. 1355 | 1356 | ```js 1357 | import subtract from "math_functions"; 1358 | 1359 | subtract(7,4); 1360 | ``` 1361 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Kamal Sharma 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Linux/README.md: -------------------------------------------------------------------------------- 1 | # Linux Notes 2 | 3 | ### Ways to open a Terminal 4 | 5 | - Right Click -> Open Terminal 6 | - Application -> Favourites -> Terminal 7 | - Application -> Utilities -> Terminal 8 | - Press Window button -> type `Terminal` 9 | - Move cursor to top-left -> Select Terminal from the dash 10 | - `Alt` + `F2` -> type `gnome-terminal` -> Press Enter 11 | 12 | ### Terminal Shortcuts 13 | 14 | | Shortcut | Description | 15 | | ---------------------- | ------------------------- | 16 | | `Ctrl` + `Shift` + `+` | Font Size (Increase) | 17 | | `Ctrl` + `-` | Font Size (Decrease) | 18 | | `Ctrl` + `Shift` + `T` | Create a tab in terminal | 19 | | `Ctrl` + `Shift` + `N` | To open _N_ terminals | 20 | | `Ctrl` + `Shift` + `W` | Close a Terminal Tab | 21 | | `Ctrl` + `Q` | Close a Terminal Window | 22 | | `Alt` + `F4` | Close a Terminal Window | 23 | | `Ctrl` + `L` | Clear the Terminal screen | 24 | | `clear` | Clear the Terminal screen | 25 | | one word + `Tab` | Auto complete | 26 | | `Tab` + `Tab` | next possible commands | 27 | | `F11` | Full Scren | 28 | 29 | ### Bash Shell Prompt 30 | 31 | - Scenario 1 32 | 33 | ```nim 34 | [student@desktop0 Documents] $ 35 | ``` 36 | 37 | - Scenario 2 38 | 39 | ```nim 40 | [root@desktop0 Documents] # 41 | ``` 42 | 43 | | Item | Meaning | 44 | | ----------- | ------------------------- | 45 | | `student` | User | 46 | | `desktop0` | Hostname | 47 | | `Documents` | Present Working Directory | 48 | | `$` | Normal User | 49 | | `#` | Root User | 50 | 51 | ### Linux Directories 52 | 53 | | Directory | What it is for | 54 | | --------- | --------------------------------------------------------- | 55 | | `bin` | normal user commands are stored | 56 | | `sbin` | root user commands are stored | 57 | | `lib` | library files are stored (32 bit processor) | 58 | | `lib64` | library files are stored (64 bit processor) | 59 | | `boot` | kernel will boot from this directory | 60 | | `dev` | device information i.e. hard disk | 61 | | `etc` | configuration files are stored here | 62 | | `home` | normal user can be stored | 63 | | `media` | shows the external devices i.e. USB, CD | 64 | | `run` | runtime data for processes started since last boot | 65 | | `mnt` | mounting directory (to link a partition with the folder ) | 66 | | `opt` | Optinal directory (could be used to install some apps) | 67 | | `proc` | Processor info are stored | 68 | | `root` | Root user home directory | 69 | | `srv` | Service information | 70 | | `sys` | System information | 71 | | `temp` | Temporary directory | 72 | | `usr` | `bin`, `sbin`, `lib64`, `lib` are stored in this | 73 | | `var` | Variable directory | 74 | -------------------------------------------------------------------------------- /NoSQL/README.md: -------------------------------------------------------------------------------- 1 | # NoSQL Database 2 | 3 | This file contains the notes that I have taken by watching 4 | [this](https://www.youtube.com/watch?v=xh4gy1lbL2k) video. 5 | 6 | In that course, the instructor is teaching the following stuff: 7 | 8 | - NoSQL 9 | - What is NoSQL 10 | - NoSQL vs SQL 11 | - 4 types of NoSQL databases 12 | - Explanation, Example, Exercise would be given 13 | - Implementing the newly learnt concepts in 2 real life use cases (Projects) 14 | 15 | --- 16 | 17 | ### What is NoSQL? 18 | 19 | - It is an approach to Database Management. 20 | - It is considered to be super flexible as it allows for a variety of data 21 | models such as: 22 | - Key-Value 23 | - Document 24 | - Tabular 25 | - Graph 26 | 27 | ![data models](https://i.imgur.com/txvMV4Y.png) 28 | 29 | - These are the 4 we will be looking at in multi-model databases. 30 | - We have already mentioned that NoSQL databases are casually considered to 31 | be flexible; but officially the defining characteristics of NoSQL 32 | databases are considered to be that they are: 33 | - Non-relational 34 | - Distributed 35 | - Scalable 36 | - Distributed refers to running on clusters of machines globally distributed 37 | to support apps at different geographical locations. 38 | - Scalable means that NoSQL databases are able to store and query large 39 | scale data as well as support high transaction throughput scaling 40 | horizontally. 41 | - In addition to this, they are also partition tolerant -- meaning that they 42 | are able to work in the presence of network partitioning. 43 | - They are also highly available -- meaning that they are able to send 44 | requests even when some machines go down. They can do this as they have 45 | data replication built-in. 46 | - Non-Relational - let's see what it entails. To understand this fully, we 47 | need to look at relational databases first. The relational data model 48 | and SQL were designed for databases that work on a single machine and scale 49 | vertically. We will go into this in a bit more detail later on. In fact, 50 | everything that is mentioned in this point is in contrast to what relational 51 | database is all about which is: 52 | 53 | - Atomicity 54 | - Consistency 55 | - Isolation 56 | - Durability 57 | 58 | or A.C.I.D for short. 59 | We are discussing relational databases as to understand where NoSQL came 60 | from. We have to look at them as well as SQL. 61 | 62 | --- 63 | 64 | ### Structured Query Language (SQL) 65 | 66 | - SQL stands for Structured Query Language. 67 | - It is used for relational databases. 68 | - By relational, it means a collection of tables with rows and columns that 69 | stores a specific set of structured data. 70 | - NoSQL is used for non-relational and relational databases. 71 | - NoSQL means not only SQL. You can use SQL in it if you want to. 72 | 73 | | NoSQL | SQL | 74 | | ------------------------------ | ---------------------------------- | 75 | | A database management approach | Not a database management approach | 76 | | Not a Query Language | A Query Language | 77 | 78 | --- 79 | 80 | ### Why use NoSQL? 81 | 82 | There are 2 reasons for it. 83 | 84 | - Application Development Productivity 85 | - Large Scale Data 86 | 87 | #### Application Development Productivity 88 | 89 | - When developing an app, there is a significant amount of time spent on 90 | organizing data. 91 | - By organizing, I mean mapping data between in-memory data structures 92 | and a relational database. 93 | - So, in another words, a type of database that supports SQL. 94 | - As a Non Relational Database Mangement approach, NoSQL can provide a data 95 | model that benefits the application's need and in turn makes our lives 96 | easier in the long run. 97 | - As the data model is most suited for the application, it makes the 98 | debugging and writing code easier and as well as allows easy evaluation. 99 | 100 | #### Large Scale Data 101 | 102 | - As we know organizations today love to capture as much data as possible 103 | to improve their offerings as well as other things. 104 | - However, capturing large amount of data and processing it quickly is 105 | expensive in terms of operation. 106 | - So, whilst it is easy to do so with relational databases, it is usually 107 | more economic to run large data and processes on lots and lots of little 108 | cheaper machines or clusters that NoSQL databases are explicitly designed 109 | to run on rather than one large one large one as it is typical for 110 | relational databses. 111 | 112 | In conclusion, NoSQL is a database management approach. The characteristics 113 | we can expect from a NoSQL database are that it is: 114 | 115 | - Non-Relational 116 | - Distributed 117 | - Scalable 118 | 119 | --- 120 | 121 | ### NoSQL vs SQL 122 | 123 | - Now, when people look at NoSQL and SQL, they might be tempted to compare 124 | the two. 125 | - But by now, we know we can't do this. 126 | - Why again? This is because once again, NoSQL is a database management 127 | approach and SQL is a language. So, 2 completely different things. 128 | - It might be better going forward to start referring to NoSQL databases 129 | as Non-Relational databases. 130 | 131 | | Non-relational or NoSQL | Relational | 132 | | ----------------------------------------- | -------------------------------- | 133 | | Uses SQL or doesn't use SQL | Uses SQL | 134 | | Not only tables with fixed columns & rows | Tables with fixed columns & rows | 135 | | Flexible Schema | Fixed Schema | 136 | | Scales out horizontally | Scales up vertically | 137 | 138 | --- 139 | 140 | ### Setting Up 141 | 142 | - As mentioned there are 4 main types of NoSQL database systems each using a 143 | different data model. 144 | - Once again, they are: 145 | 146 | - Key-Value 147 | - Document 148 | - Tabular 149 | - Graph 150 | 151 | - Databases have multiple layers. 152 | - The first layer is an **interface** or in other words a visual platform 153 | where you can visit and interact with data which is where you find the 154 | format, the language and the transport. 155 | - In this course the interface that we are going to use is called 156 | DataStax Astra data management system. 157 | - DataStax Astra DB is an auto-scaling Database-As-A-Service built on 158 | Apache Cassandra designed to simplify cloud-native application 159 | development. 160 | - Because it is built on Apache Cassandra, one would be using the 161 | Cassandra Query Language or CQL. 162 | - CQL offers a model close to SQL in the sense that data is put in tables 163 | containing rows and columns. 164 | - It is through these languages that we interact with our database. 165 | - The next layer is the **execution** layer. 166 | - This is where we pass the incoming queries coming from our interface. 167 | - It is also used as an analyser and dispatcher. 168 | - Finally we have the **storage** layer in which the indexing of data 169 | happens. 170 | 171 | The reason for using DataStax Astra is that it allows all 4 database models so 172 | that we need to sign up for different stuff for different purposes. 173 | 174 | We can group these Database Management Systems into families according to the 175 | C.A.P Theorem. According to the C.A.P theorem, a NoSQL database cannot achieve 176 | consistency, availability and partition tolerance. It must sacrifice one of the 177 | three. For example, MongoDB and Kafka, chose to focus on CP and the DBMS that 178 | we are going to use (DataStaxAstra) is built on Apache Cassandra which chose 179 | to focus on A.P. 180 | 181 | So to recap, what we are doing here is using DataStax Astra, which is an 182 | interface essentially, that will will allows us to work with NoSQL database, 183 | which is in this case, Apache Cassandra. To be exact, Apache Cassandra is an 184 | open sourced NoSQL distributed database. The language that we would use to 185 | communicate is Cassandra Query Language or CQL for short, which as mentioned 186 | is very similar to SQL. Most NoSQL databases have their own Query Language 187 | but not all. 188 | 189 | --- 190 | 191 | In the DataStax Astra, create a database. 192 | 193 | - Name it as `fcc_tutorial` 194 | - Keyspace: `tabular` 195 | - Cloud provider: anything that you want, I am choosing AWS 196 | - Region: choose your closest region 197 | - When you create the DB, initially it will be `pending`. 198 | - Wait for it to turn `active`. 199 | 200 | Now that we have set up our Database Management System let's start getting to 201 | some examples. 202 | 203 | --- 204 | 205 | ### Tabular Type 206 | 207 | - It also known as Column Database Type or a Wide Column Database Type. 208 | - Tables are relational and come with a schema. 209 | - We will be creating a table called `books` and will be defining what kind 210 | of rows the table can take. 211 | 212 | | Field Name | Type | 213 | | ---------- | ----------- | 214 | | Book ID | UUID | 215 | | Author | Text | 216 | | Title | Text | 217 | | Year | Int | 218 | | Categories | Set of Text | 219 | | Timestamp | Timestamp | 220 | 221 | UUID = Universally Unique Identifier 222 | 223 | In the DataAstrax dashboard: 224 | 225 | - Click on the database 226 | - Click on `CQL Console` 227 | - Type `describe keyspaces;`. 228 | - Keyspace means logical grouping of tables (in RDBMS, it would be `database`) 229 | - To use the newly created `tabular` keyspace, type `use tabular;` 230 | - Lets create a table in the `tabular` keyspace. 231 | 232 | ```sql 233 | CREATE TABLE IF NOT EXISTS book ( 234 | bookid uuid, 235 | author TEXT, 236 | title TEXT, 237 | year INT, 238 | categories SET , 239 | added TIMESTAMP, 240 | PRIMARY KEY (bookid) 241 | ); 242 | ``` 243 | 244 | uuid is a 128-bit label used for information in computer systems. 245 | 246 | Primary key is something that allows us to identify records uniquely. 247 | The `bookid` will also be our partition key. 248 | 249 | - `DESCRIBE keyspace tabular;` will describe our newly created table. 250 | - To add a record, 251 | 252 | ```sql 253 | INSERT INTO book 254 | (bookid, author, title, year, categories, added) 255 | VALUES 256 | (uuid(), 'Bobby Brown', 'Dealing with Tables', 1999, {'programming', 'computers'}, toTimeStamp(now())); 257 | ``` 258 | 259 | - To check if they have been inserted, you can check with this: 260 | 261 | ```sql 262 | SELECT * FROM book; 263 | ``` 264 | 265 | - Inserting another record. 266 | 267 | ```sql 268 | INSERT INTO book 269 | (bookid, author, title, year, categories, added) 270 | VALUES 271 | (uuid(), 'Andrea Agnes', 'The Moon', 2001, {'space', 'non-fiction'}, toTimeStamp(now())); 272 | ``` 273 | 274 | - Fetching a specific record 275 | 276 | ```sql 277 | SELECT * FROM book 278 | WHERE bookid = 2f0e7571-aa06-4716-bbc0-2f42880a007e; 279 | ``` 280 | 281 | - Creating another table. 282 | 283 | ```sql 284 | CREATE TABLE IF NOT EXISTS restaurant_by_country ( 285 | country TEXT, 286 | name TEXT, 287 | cuisine TEXT, 288 | url TEXT, 289 | PRIMARY KEY ((country), name, url) 290 | ) WITH CLUSTERING ORDER BY (name DESC, url ASC); 291 | ``` 292 | 293 | Whatever we pass in PRIMARY KEY will be our partition key. 294 | 295 | So, 296 | 297 | - `country` - partition key 298 | - `name`, `url` - clustering keys 299 | 300 | Inserting records into this new table. 301 | 302 | ```sql 303 | INSERT INTO restaurant_by_country 304 | (country, name, cuisine, url) 305 | VALUES 306 | ('POLAND', 'Wiejska Karczma', 'traditional', 'www.karczma.pl'); 307 | ``` 308 | 309 | ```sql 310 | INSERT INTO restaurant_by_country 311 | (country, name, cuisine, url) 312 | VALUES 313 | ('SINGAPORE', 'The Shack', 'american', 'www.shack.sg'); 314 | ``` 315 | 316 | ```sql 317 | INSERT INTO restaurant_by_country 318 | (country, name, cuisine, url) 319 | VALUES 320 | ('UNITED KINGDOM', 'The Red Rose', 'pub', 'www.redrose.co.uk'); 321 | ``` 322 | 323 | Fetching all the newly inserted records. 324 | 325 | ```sql 326 | SELECT * FROM restaurant_by_country; 327 | ``` 328 | 329 | Fetching a specific record: 330 | 331 | ```sql 332 | SELECT * from restaurant_by_country 333 | WHERE country='SINGAPORE'; 334 | ``` 335 | 336 | ```sql 337 | INSERT INTO restaurant_by_country 338 | (country, name, cuisine, url) 339 | VALUES 340 | ('SINGAPORE', 'The Hut', 'lebanese', 'www.hut.sg'); 341 | ``` 342 | 343 | ```sql 344 | SELECT * from restaurant_by_country 345 | WHERE country='SINGAPORE'; 346 | ``` 347 | 348 | --- 349 | 350 | ### Document Type Model 351 | 352 | - Document or document oriented database types are arguably one of the 353 | easiest types to deal with. 354 | - This is because they require no schema. 355 | - In tabular data model, we had to define schema, but here we don't. 356 | - As long as our data comes as an object, it is fine. 357 | - The objects are made up of keys and values. 358 | - Example of an object in a `to-do-list application`: 359 | 360 | ```json 361 | { 362 | "id": 0, 363 | "title": "Fix Bike", 364 | "description": "Fix bike before housemate finds out", 365 | "done": true 366 | } 367 | ``` 368 | 369 | - The values part in these objects can be numbers, strings, boolean or 370 | another object. 371 | - This is called JSON (JavaScript Object Notation) and is the popular 372 | format for document database types. 373 | - A group of documents is called a **collection**. 374 | - So, we will not be using the word _tables_ anymore. 375 | - It has been replaced by collections. 376 | - So, keep that in mind moving forward. 377 | 378 | --- 379 | 380 | - Lets make a collection of to-do items using a Document API. 381 | - An API stands for **Application Programming Interface**. 382 | - They allow for technologies to essentially talk with each other and are 383 | essential to so many services we rely on today. 384 | - Examples of API 385 | - twitter API - to fetch tweets 386 | - Map API - for delivery services 387 | 388 | --- 389 | 390 | #### HTTP Request Methods 391 | 392 | The most common are: 393 | 394 | - GET Request 395 | - POST Request 396 | - PUT Request 397 | - DELETE Request 398 | 399 | --- 400 | 401 | #### Creating a new keyspace: document 402 | 403 | - Create a new keyspace in the DataStax Astra dashboard. 404 | - To work with document types, we have to connect with a document API. 405 | - Before we do that, we have to get a token in order to communicate 406 | with our database. 407 | - To do this, go to `Settings` -> `Application Settings` -> 408 | `Organization Settings` -> Choose `Adminsrator` user -> 409 | `Generate Token`. 410 | - Copy Token. 411 | - Click on the database -> `Connect` -> `Swagger UI` 412 | - Create a new empty collection by choosing this 413 | 414 | ```js 415 | POST 416 | ​/v2​/namespaces​/{namespace-id}​/collections 417 | Create a new empty collection in a namespace 418 | ``` 419 | 420 | - Click on `Try it Out`. 421 | - Under `X-Cassandra Token` paste the token value that you copied in above 422 | step. 423 | - Under `namespace-id` fill `document` in it because that is the one that 424 | we created. 425 | - In the body, add the JSON data for the new collection name. 426 | 427 | ```json 428 | { 429 | "name": "first_collection" 430 | } 431 | ``` 432 | 433 | - Scroll down and click `Execute`. 434 | - If it went successfully, you would be getting a response status of 201. 435 | 436 | --- 437 | 438 | ##### Adding stuff into the collection 439 | 440 | - Lets add new stuff into the newly created collection. 441 | - Go to the following endpoint. 442 | 443 | ```js 444 | POST 445 | ​/v2​/namespaces​/{namespace-id}​/collections​/{collection-id} 446 | Create a new document 447 | ``` 448 | 449 | - Click on `Try it Out`. 450 | - Fill in the token. 451 | - `namespace-id` -> `document` 452 | - `collection-id` -> `first_collection` 453 | - In the body I am gonna add this 454 | 455 | ```json 456 | { 457 | "id": 1, 458 | "title": "Make Dinner", 459 | "description": "Make dinner for friends coming over.", 460 | "done": false 461 | } 462 | ``` 463 | 464 | - Click on `Execute`. 465 | - If it all went fine, you will get a `201` response with 466 | a JSON object containing the `documentId`. 467 | 468 | --- 469 | 470 | ##### Getting all the documents present in a collection 471 | 472 | - Lets fetch all the objects present in a collection. 473 | - Go to the following endpoint. 474 | 475 | ```js 476 | GET 477 | ​/v2​/namespaces​/{namespace-id}​/collections​/{collection-id} 478 | Search documents in a collection 479 | ``` 480 | 481 | - Click on `Try it Out`. 482 | - Fill in the token. 483 | - `namespace-id` -> `document` 484 | - `collection-id` -> `first_collection` 485 | - Click on `Execute`. 486 | - If it all went fine, you will be getting a response code of `200` along 487 | with a response body that has all the items. 488 | 489 | --- 490 | 491 | ##### Get a specific document 492 | 493 | - Lets fetch a specific document from a collection. 494 | - Go to the following endpoint. 495 | 496 | ```js 497 | GET 498 | ​/v2​/namespaces​/{namespace-id}​/collections​/{collection-id}​/{document-id} 499 | Get a document 500 | ``` 501 | 502 | - Click on `Try it Out`. 503 | - Fill in the token. 504 | - `namespace-id` -> `document` 505 | - `collection-id` -> `first_collection` 506 | - `document-id` -> `` 507 | - Click on `Execute`. 508 | - If it all went fine, you will be getting a response code of `200` along 509 | with a response body that has one item from from our collection based by 510 | its `documentId` 511 | 512 | --- 513 | 514 | ##### Fetching multiple records based on a condition 515 | 516 | - Lets add another document into the collection. 517 | - Go to the following endpoint. 518 | 519 | ```js 520 | POST 521 | ​/v2​/namespaces​/{namespace-id}​/collections​/{collection-id} 522 | Create a new document 523 | ``` 524 | 525 | - Click on `Try it Out`. 526 | - Fill in the token. 527 | - `namespace-id` -> `document` 528 | - `collection-id` -> `first_collection` 529 | - In the body I am gonna add this 530 | 531 | ```json 532 | { 533 | "id": 2, 534 | "title": "Make Dinner", 535 | "description": "Clean Dishes after dinner", 536 | "done": false 537 | } 538 | ``` 539 | 540 | - Click on `Execute`. 541 | - If it all went fine, you will get a `201` response with 542 | a JSON object containing the `documentId`. 543 | - Let's add another document. 544 | 545 | ```json 546 | { 547 | "id": 10, 548 | "title": "Fix Shoes", 549 | "description": "Take Shoes to fix.", 550 | "done": false 551 | } 552 | ``` 553 | 554 | Now lets try to fetch the records that have the title `Make Dinner`. 555 | 556 | - Go to the following endpoint. 557 | 558 | ```js 559 | GET 560 | ​/v2​/namespaces​/{namespace-id}​/collections​/{collection-id} 561 | Search documents in a collection 562 | ``` 563 | 564 | - Click on `Try it Out`. 565 | - Fill in the token. 566 | - `namespace-id` -> `document` 567 | - `collection-id` -> `first_collection` 568 | - `where` -> `{"title": {"$eq": "Make Dinner"}}` 569 | - Click on `Execute`. 570 | - If it all went fine, you will be getting a response code of `200` along 571 | with a response body that has all the items. 572 | 573 | --- 574 | 575 | ##### Updating a document 576 | 577 | You can use this end point to update a document that is present in a collection. 578 | 579 | ```js 580 | PUT 581 | ​/v2​/namespaces​/{namespace-id}​/collections​/{collection-id}​/{document-id} 582 | Create or update a document with the provided document-id 583 | ``` 584 | 585 | Feel free to play around the various endpoints present in the Swagger UI. 586 | 587 | --- 588 | 589 | ### Key Value Database Model 590 | 591 | - They are considered to be the easiest database type and usually come 592 | looking like this: 593 | 594 | ```js 595 | KEY VALUE 596 | A1 AAA,BBB,CCC 597 | A2 111,222,333 598 | A3 CCC,111,XXX 599 | ``` 600 | 601 | - There will be a key column and a value column. 602 | - You can actually have as many value columns as you wish. 603 | - The important thing here is that we can retrieve data back to us, i.e. 604 | an entire row by the key as that is the identifier in this case. 605 | - Example of a Key Value Database 606 | 607 | ``` 608 | 609 | ``` 610 | 611 | --- 612 | 613 | #### Creating a new keyspace: keyvalue 614 | 615 | - In the DataStax Astra Dashbord, go to the databases tab and create a new 616 | keyspace with the name `keyvalue`. 617 | - This time let us use GraphQL as we have already used Document API before. 618 | - Click on `Connect`. 619 | - Open the GraphQL playground URL. 620 | - Add your Cassandra Token in the `HTTP Headers`. 621 | - By default the graphql query is: 622 | 623 | ```gql 624 | { 625 | keyspaces { 626 | name 627 | } 628 | } 629 | ``` 630 | 631 | - To create a table using GraphQL run this command 632 | 633 | ```gql 634 | mutation { 635 | createTable( 636 | keyspaceName: "keyvalue" 637 | tableName: "shop_inventory" 638 | partitionKeys: [{ name: "key", type: { basic: TEXT } }] 639 | values: [{ name: "value", type: { basic: TEXT } }] 640 | ) 641 | } 642 | ``` 643 | 644 | If it all went fine, you will be getting this message in the output 645 | 646 | ```json 647 | { 648 | "data": { 649 | "createTable": true 650 | } 651 | } 652 | ``` 653 | 654 | Now that the table is created, lets add keys and values. 655 | 656 | - In the URL part, change `/api/graphql-schema` to `/api/graphql/keyvalue`. 657 | - We are adding `keyvalue` as that is the keyspace that we created earlier. 658 | 659 | ```gql 660 | mutation { 661 | insertshop_inventory(value: { key: "3dr53", value: "beans" }) { 662 | value { 663 | key 664 | value 665 | } 666 | } 667 | } 668 | ``` 669 | 670 | The line 671 | 672 | ```gql 673 | insertshop_inventory(value: { key: "3dr53", value: "beans" }) 674 | ``` 675 | 676 | is the insertion part. 677 | 678 | - The statement below it 679 | 680 | ```gql 681 | value { 682 | key 683 | value 684 | } 685 | ``` 686 | 687 | is added to return the newly added record in the table. 688 | 689 | - If it all went fine, you will be getting this: 690 | 691 | ```json 692 | { 693 | "data": { 694 | "insertshop_inventory": { 695 | "value": { 696 | "key": "3dr53", 697 | "value": "beans" 698 | } 699 | } 700 | } 701 | } 702 | ``` 703 | 704 | - Lets add another item. 705 | 706 | ```gql 707 | mutation { 708 | insertshop_inventory(value: { key: "42dhw", value: "shampoo" }) { 709 | value { 710 | key 711 | value 712 | } 713 | } 714 | } 715 | ``` 716 | 717 | - Before actually fetch the data using GraphQL, lets check if we can fetch 718 | the data in the `CQL Console`. 719 | 720 | - `USE keyvalue;` 721 | - `DESCRIBE TABLE "shop_inventory";` 722 | - `SELECT * FROM "shop_inventory";` 723 | 724 | - If you run the above queries in order, you can see the newly inserted 725 | records. 726 | - Lets now see how we can fetch them using GraphQL. 727 | 728 | ```gql 729 | query { 730 | shop_inventory { 731 | values { 732 | key 733 | value 734 | } 735 | } 736 | } 737 | ``` 738 | 739 | - This would return this: 740 | 741 | ```json 742 | { 743 | "data": { 744 | "shop_inventory": { 745 | "values": [ 746 | { 747 | "key": "42dhw", 748 | "value": "shampoo" 749 | }, 750 | { 751 | "key": "3dr53", 752 | "value": "beans" 753 | } 754 | ] 755 | } 756 | } 757 | } 758 | ``` 759 | 760 | Lets insert another record: 761 | 762 | ```gql 763 | mutation { 764 | insertshop_inventory(value: { key: "dhe342", value: "coca cola" }) { 765 | value { 766 | key 767 | value 768 | } 769 | } 770 | } 771 | ``` 772 | 773 | Now lets see how to delete a record. 774 | 775 | ```gql 776 | mutation { 777 | deleteshop_inventory(value: { key: "dhe432" }) { 778 | value { 779 | key 780 | } 781 | } 782 | } 783 | ``` 784 | 785 | **If we try to remove something by the value instead of the primary key that** 786 | **we have assigned, we will get an error.** 787 | 788 | --- 789 | 790 | ### Graph Type Data Model 791 | 792 | - Graph databases are a great way to store data that has relationsips 793 | between other pieces of data or in other words, nodes. 794 | - Each node is connected by an edge to represent this relationship. 795 | - For example, your friends on social media. You and your friends would be 796 | the nodes and the connection you have would be represented by the edges. 797 | - `docker network create graph` 798 | 799 | Clone the repository 800 | 801 | ``` 802 | git clone https://github.com/datastaxdevs/workshop-introduction-to-nosql.git 803 | ``` 804 | 805 | Go inside the newly created directory. 806 | 807 | ``` 808 | docker-compose up -d 809 | ``` 810 | 811 | It will take some time to set it up. 812 | 813 | Graph Database will use Gremlin language. So, you can learn that and then 814 | implement it. 815 | -------------------------------------------------------------------------------- /NodeJS/README.md: -------------------------------------------------------------------------------- 1 | # NodeJS Notes 2 | 3 | Started on 11th December 2021. 4 | 5 | --- 6 | 7 | ### What is NodeJS? 8 | 9 | - NodeJS or Node is an open source and cross platform **runtime environment** 10 | for executing JavaScript code outside of a browser. 11 | - We often use Node to build backend services like APIs. 12 | - Node is ideal for building higly-scalable, data-intensive and real time 13 | apps. 14 | - Node is not a programming language. 15 | - NodeJS is asyncrhonous by default. 16 | - Node is ideal for **I/O-intensive** apps. 17 | - Do not use Node for **CPU-intesive** apps. 18 | - Examples of CPU-intesisve: Video-Encoding, Image Manipulation Service. 19 | 20 | --- 21 | 22 | ### Why NodeJS? 23 | 24 | - NodeJS allows us to create backend using JavaScript. 25 | - If you already know JS then for backend you need not learn yet another 26 | language and all of it intricacies. 27 | - Node is also superfast and will allow us to create really scalable and 28 | fast running websites. 29 | - Companies that use NodeJS: Twitter, Netflix, Trello, Uber 30 | - Node is great for prototyping and agile development. 31 | - Since we use JS in frontend and backend, source code will be cleaner and 32 | more consistent. 33 | - Largest ecosystem of open-sourced libraries. 34 | 35 | --- 36 | 37 | While importing we use `const` because we do not want to accidentaly change it 38 | to something else like `importVar = 1;` 39 | 40 | #### Module Wrapper Function 41 | 42 | Lets say `logger.js` had the following content: 43 | 44 | ```js 45 | var url = "http://mylogger.io/log"; 46 | 47 | function log(message) { 48 | // Send an HTTP Request 49 | console.log(message); 50 | } 51 | 52 | module.exports.log = log; 53 | ``` 54 | 55 | and `app.js` has this: 56 | 57 | ```js 58 | const logger = require("./logger"); 59 | 60 | logger.log("Message from app!"); 61 | ``` 62 | 63 | - Usually when we import a module, node adds a wrapper function and that 64 | will look like this: 65 | 66 | ```js 67 | (function (exports, require, module, __filename, __dirname) { 68 | var url = "http://mylogger.io/log"; 69 | 70 | function log(message) { 71 | // Send an HTTP Request 72 | console.log(message); 73 | } 74 | 75 | module.exports.log = log; 76 | }); 77 | ``` 78 | 79 | --- 80 | 81 | ### Video: Oe421EPjeBE - Node.js and Express.js full course 82 | 83 | #### Date started: 17th December 2021 84 | 85 | #### Topics covered: 86 | 87 | - Fundamentals of Node.js 88 | - Express.js 89 | - MongoDB, Mongoose 90 | - Applications 91 | - Deployment 92 | 93 | - The main goal of this course is to build modern, fast and scalable 94 | server-side web applications with node. 95 | 96 | ### What is NodeJS? 97 | 98 | - Environment to run JS outside of the Browser 99 | - Created in 2009 and is build on top of Chrome's v8 JS engine 100 | - Big community 101 | - Full-Stack 102 | 103 | ### Pre-requisites 104 | 105 | - Basics of HTML, CSS, JS [ES6] 106 | - Callbacks, promises, Async-await 107 | - Youtube - Code Addict 108 | - Playlist - JS Nuggets 109 | 110 | ### Course Structure 111 | 112 | - Introduction 113 | - Installation 114 | - Node Fundamentals 115 | - Express Tutorial 116 | - Building Apps 117 | 118 | ### Difference between Browser JS & Node JS 119 | 120 | | Browser JS | Node.js | 121 | | ---------------- | ---------------- | 122 | | DOM | No DOM | 123 | | Window | No Window | 124 | | Interactive Apps | Server Side Apps | 125 | | No Filesystem | Filesystem | 126 | | Fragmentation | Versions | 127 | | ES6 modules | Common JS | 128 | 129 | ### Global Variables in NodeJS 130 | 131 | - It means that anywhere in the application you can access those variables. 132 | 133 | - Some of those global variables are: 134 | - `__dirname` - path to current directory 135 | - `__filename` - file name 136 | - `require` - function to use modules (CommonJS) 137 | - `module` - info about current module (file) 138 | - `process` - info about env where the program is being executed 139 | 140 | ### Modules in NodeJS 141 | 142 | - Every file is a module. 143 | - You can export multiple stuff or a single stuff. 144 | - Multiple exports example -> `module.exports = { john, peter };` 145 | - Single export example -> `module.exports = sayHI;` 146 | - Single export example -> `module.exports.displayHi = sayHI;` 147 | 148 | ### Builtin modules 149 | 150 | - NodeJS has a lot of built-in modules 151 | - Each module in turn has a lot of properties 152 | - We will cover only some of the built-in stuff 153 | - os 154 | - path 155 | - fs 156 | - http 157 | 158 | ### NPM 159 | 160 | - Package, dependency and module - all mean the same - Shareable JS Code 161 | - `npm` - Global command, comes with node 162 | - `npm --version` - lists out the version 163 | - To install a local dependency (to be used in a particular project) 164 | 165 | ``` 166 | npm i 167 | ``` 168 | 169 | - To install a dependency globally (to be used in any project) 170 | 171 | ``` 172 | npm install -g 173 | ``` 174 | 175 | - In Mac, 176 | 177 | ``` 178 | sudo npm install -g 179 | ``` 180 | 181 | - `package.json` - manifest file (stores important info project/package) 182 | - There are 3 ways to create `package.json` 183 | - manual approach would be creating `package.json` in the root, creating 184 | properties, etc., 185 | - To install a dependency only for development purposes 186 | `npm i nodemon -D` 187 | - To uninstall a package - `npm uninstall bootstrap` 188 | 189 | ### Events in NodeJS 190 | 191 | - Event driven programming is used heavily in NodeJS. 192 | - First listen for an event and then emit it. 193 | 194 | ```js 195 | // get back the class 196 | // if want custom extend from class 197 | // otherwise just for emitting and handling events create instance 198 | const EventEmitter = require("events"); 199 | 200 | const customEmitter = new EventEmitter(); 201 | 202 | // on and emit methods 203 | // keep track of the order 204 | // additional arguments 205 | // built-in modules utilize it 206 | 207 | customEmitter.on("response", (name, id) => { 208 | console.log(`data recieved user ${name} with id:${id}`); 209 | }); 210 | 211 | customEmitter.on("response", () => { 212 | console.log("some other logic here"); 213 | }); 214 | 215 | customEmitter.emit("response", "john", 34); 216 | ``` 217 | 218 | ### Stream 219 | 220 | - Streams are used to read or write sequentially. 221 | - There are 4 types of streams: 222 | - Writeable - only writing 223 | - Readable - only reading 224 | - Duplex - both read and write 225 | - Transform - data can be modified while reading or writing 226 | 227 | --- 228 | 229 | ### API vs SSR 230 | 231 | | API | SSR | 232 | | --------------------------------- | --------------------- | 233 | | Application Programming Interface | Server Side Rendering | 234 | | API - JSON | SSR - Template | 235 | | Send Data | Send Template | 236 | | `res.json()` | `res.render()` | 237 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Notes 2 | 3 | Welcome to my repo! 4 | 5 | Here you can find the notes that I have taken in a digitized format. 6 | 7 | You can find th notes on topcis such as: 8 | 9 | - [CPP Language](CPP/) 10 | - [Dart Programming Language](Dart/) 11 | - [JavaScript Basics](JS/) 12 | - [Linux Related](Linux/) 13 | - [NodeJS](NodeJS/) 14 | - [NoSQL](NoSQL/) 15 | - [PHP Language](PHP/) 16 | - [Python API Development](PyAPI) 17 | - [ReactJS](ReactJS/) 18 | - [Redux](Redux/) 19 | - [Structured Query Languge](SQL/) 20 | - [Yii2 Framework](Yii2/) 21 | -------------------------------------------------------------------------------- /ReactJS/README.md: -------------------------------------------------------------------------------- 1 | # React JS Notes 2 | 3 | Started learning on 19th December 2021 from 4 | [this](https://www.youtube.com/watch?v=4UZrsTqkcW4). 5 | 6 | ### Introduction 7 | 8 | - React is a JavaScript library for building user interfaces. 9 | - Developed by Facebook in 2011 10 | - Some of React's competitors: Angular, Vue, Svelte 11 | - React is all about components. 12 | - Components are independent chunks of user interface. 13 | - Components can be as small as one HTML element. 14 | - The benefit of the components is that you can bunch of independent, 15 | isolated and most importantly reusable user-interfaces. 16 | - In the app, you can have as many components as you want. 17 | - All apps will have at least one component - `Root` component. 18 | 19 | ### Goals 20 | 21 | - Comfortable with React 22 | - Applying theory 23 | - Build your projects 24 | 25 | ### Course Structure 26 | 27 | - Dev Environment 28 | - Tutorial 29 | - Projects 30 | - Redux 31 | 32 | ### Requirements 33 | 34 | - HTML 35 | - CSS 36 | - JavaScript `[ES6]` 37 | - Coding Addict - Javascript Nuggets 38 | 39 | ### Dev Environment 40 | 41 | - NodeJS 42 | - `node --version`, minimum 5.2.0 npx 43 | - Browser = Chrome 44 | - Text Editor = Visual Studio Code 45 | - React Developer Tools 46 | 47 | ### Basic Terminal Commands 48 | 49 | - `pwd` - Present Working Directory 50 | - `ls` - List of files present in a directory 51 | - `mkdir` - Creates a directory 52 | - `cd` - Change directory 53 | - `cd ..` - Navigate one level up 54 | - `clear` - Clears out the console 55 | - `Arrow UP/Down` - Previous commands 56 | 57 | ### NPM 58 | 59 | - `npm init` - creates `package.json` (manifest) file which has a list of 60 | dependencies 61 | - `npm install --save` - Install pacakge locally and add to 62 | `package.json` 63 | - `npm install -g` - Install package globally and access it 64 | anywhere. 65 | - `npm install --save-dev` - Use it only in development 66 | environment 67 | 68 | ### Create React App 69 | 70 | - Technically, you don't need to use `create-react-app` to work with React. 71 | - You can build the whole setup yourself. 72 | - In the long run, `create-react-app` will save a bunch of time. 73 | - Under the hood, `create-react-app` uses `babel` and `webpack`. 74 | - A `babel` is a JS transpiler that converts the newest JS into the good old 75 | JS. 76 | - It will kind of ensure that our app runs on older browsers as well. 77 | - Webpack does a lot of other things as well. 78 | - Essentially, webpack works as a module bundler. 79 | - The main features of webpack would be bundling resources, watching for 80 | changes and running babel transpiler. 81 | - To create a new React app, use `npx create-react-app ` 82 | 83 | ### Folder Structure 84 | 85 | - `node_modules` - contains all the dependencies needed for the project 86 | - `public` - contains the files that will be rendered on the browser 87 | - `src` - contains the `App.js` and other components? 88 | 89 | ### Setting up the 1st component 90 | 91 | - Removed the default boiler plate stuff from `src` 92 | - Creating an empty `index.js`. 93 | - Component names should be capitalized. 94 | - In the `index.js`, I will add the following content. 95 | 96 | ```js 97 | import React from "react"; 98 | import ReactDom from "react-dom"; 99 | 100 | function Greeting() { 101 | return

    This is Kamal and this is my first component

    ; 102 | } 103 | 104 | ReactDom.render(, document.getElementById("root")); 105 | ``` 106 | 107 | - All components must be closed. For example, Either like`` or 108 | like this ``. 109 | - Stateless functional components will always JSX 110 | 111 | ### JSX Rules 112 | 113 | - Return single element 114 | - div / section / article / fragment 115 | - fragment looks like this: `<> ... `, `...` represent content. 116 | - use camelCase for html attribute 117 | - `className` instead of `class` 118 | - close every element 119 | - formatting 120 | 121 | ### Note: 122 | 123 | - You can have only one default export per file. 124 | 125 | --- 126 | 127 | ### Advanced React 128 | 129 | - useState 130 | - useEffect 131 | - Conditional Rendering 132 | - Forms 133 | - useRef 134 | - useReducer 135 | - Prop Drilling 136 | - Context API / useContex 137 | 138 | --- 139 | 140 | ### useState 141 | 142 | - hooks will start with `use` 143 | - components that will be used in these hooks must start with a 144 | capital letter and should be in capital case. 145 | - Hooks can be called only inside of the body of a function component. 146 | - You cannot call the hook conditionally. (i.e. based on some condition) 147 | 148 | ### useEffect 149 | 150 | - runs after every re-render 151 | - cleanup function 152 | - second parameter 153 | - If you add a empty list `[]` as the second argument to the `useEffect` 154 | hook, then that is executed only in the initial render. 155 | - there is no limit on the number of `useEffect` hooks in a given file. 156 | - Clean up functions will be added as a return statement in this hook. 157 | - useEffect cannot be asynchronous. 158 | - i.e. you can not use `async` and `await` here. 159 | 160 | ### useRef 161 | 162 | - useRef works a lot like useState 163 | - of course there are some differences 164 | - as for the similiarties: 165 | - it also preserves the values in between the render 166 | - unlike useState, useRef does not trigger re-render. 167 | - it targets, DOM nodes/ elements 168 | 169 | ### useReducer 170 | 171 | - it is used when you have a more complicated setup 172 | - for simple to do app, it wont be needed, but for complex apsps, 173 | then yes, it is recommended to use. 174 | 175 | ```js 176 | const [state, dispatch] = useReducer(reducer) 177 | ``` 178 | 179 | - reducer is a function 180 | 181 | ```js 182 | const reducer = (state, action) => { return state;} 183 | ``` 184 | 185 | - always return some kind of state in the reducer function. 186 | -------------------------------------------------------------------------------- /Redux/README.md: -------------------------------------------------------------------------------- 1 | # Redux 2 | 3 | - Redux is a state management library for JavaScript apps. 4 | - We can use it with React, Angular, Vue, Vanilla JS 5 | 6 | ### State Management Solutions 7 | 8 | - Flux (by Facebook) 9 | - Redux 10 | - MobX 11 | 12 | ### Pros of Redux 13 | 14 | - Predictable State Changes 15 | - Centralized State 16 | - Easy Debugging 17 | - Preserve page state 18 | - Undo/redo 19 | - Ecosystem of add-ons 20 | 21 | ### Cons of Redux 22 | 23 | - Complexity 24 | - Verbosity 25 | 26 | ### When not to use Redux 27 | 28 | - Tight Budget 29 | - Small to medium-sized apps 30 | - Simple UI/data flow 31 | - Static data 32 | -------------------------------------------------------------------------------- /SQL/Practice.md: -------------------------------------------------------------------------------- 1 | # SQL Practice 2 | 3 | It is my view that if you solve these questions you would have a good 4 | understanding and usage of various SQL commands. 5 | 6 | For now, I will have the questions.
    7 | Later when you complete them, I will provide with the answers in this 8 | same file.
    9 | Try to provide the output of the command too.
    10 | So, to copy the output, it would be easier for you if you execute the 11 | commands in the command prompt. 12 | 13 | Create the following table with the following values.
    14 | 15 | - Database Name : `sqlpractice` 16 | - Table Name : `Student` 17 | 18 | ##### Note 19 | 20 | - The date is in `mm/dd/yyyy` format. 21 | - While storing in the database, store it in the format that our _MySQL_ recognises: `yyyy-mm-dd`. 22 | - While storing the names, it has to be given within the single quotes (`'`). 23 | - Date can be given in single quotes. 24 | - Use the table name instead of `TABLE` while inserting into a table. 25 | - For numerical values, the quotes is not needed. 26 | - For most of the questions answer will be the same for everyone. 27 | - For a few questions, it might vary depending on how you approach the question. 28 | 29 | | Roll | Sname | Gender | Dob | Total | Average | Grade | 30 | | ---- | ------- | ------ | ---------- | ----- | ------- | ----- | 31 | | 1 | Anand | M | 05/13/2001 | 407 | 81.4 | B | 32 | | 2 | Ajay | M | 04/02/2001 | 400 | 80 | C | 33 | | 3 | Bharath | M | 11/05/2000 | 355 | 71 | D | 34 | | 4 | Shivani | F | 05/06/2001 | 476 | 95.2 | A | 35 | | 5 | Sarchin | M | 12/23/2001 | 400 | 80 | C | 36 | | 6 | Dhoni | M | 11/17/2000 | 415 | 83 | B | 37 | | 7 | Kamala | F | 12/05/2001 | 400 | 80 | C | 38 | | 8 | Varun | M | 11/11/2000 | 470 | 94 | A | 39 | | 9 | Rekha | F | 10/15/2000 | 490 | 98 | A | 40 | 41 | #### Hints 42 | 43 | - This the command to create the table: 44 | 45 | ```sql 46 | CREATE TABLE Student( 47 | Roll INT NOT NULL, 48 | Sname char(15), 49 | Gender char(2), 50 | Dob DATE, 51 | Total INT, 52 | Average NUMERIC(10, 2), 53 | Grade char(2) 54 | ); 55 | ``` 56 | 57 | - This is just an example to insert into the table. I am showing the example for the first row. 58 | - For the remaining rows, do it on your own. 59 | 60 | ```sql 61 | INSERT INTO `Student` 62 | (`Roll`, `Sname`, `Gender`, `Dob`, `Total`, `Average`, `Grade`) 63 | VALUES 64 | (1, 'Anand', 'M', '2001-05-13', 407, 81.4, 'B'); 65 | ``` 66 | 67 | ## Questions 68 | 69 | ### Q01. Display name and gender of all the students. 70 | 71 | #### _Answer :_ 72 | 73 | ##### _Query_ : 74 | 75 | ```sql 76 | SELECT Sname, Gender 77 | FROM `Student`; 78 | ``` 79 | 80 | ##### _Output_ : 81 | 82 | ``` 83 | +---------+--------+ 84 | | Sname | Gender | 85 | +---------+--------+ 86 | | Anand | M | 87 | | Ajay | M | 88 | | Bharath | M | 89 | | Shivani | F | 90 | | Sarchin | M | 91 | | Dhoni | M | 92 | | Kamala | F | 93 | | Varun | M | 94 | | Rekha | F | 95 | +---------+--------+ 96 | ``` 97 | 98 | ### Q02. Display the contents of the entire table. 99 | 100 | ### Q03. Display the unique values of `Total` from the table. 101 | 102 | ### Q04. Display roll number and name of the male students. 103 | 104 | ### Q05. Display the roll number and name of male students who have scored above 400. 105 | 106 | ### Q06. Display the details of students who have scored between 400 and 450. (Limits inclusive) 107 | 108 | ### Q07. Display details of male students who have scored between 400 and 450. 109 | 110 | ### Q08. Display names of students who have scored the grades A, B or C from the table. 111 | 112 | ### Q09. Display the name of female students who have scored the grades A or B. 113 | 114 | ### Q10. Display the roll numbers of students who have scored grade other than A or B. 115 | 116 | ### Q11. Display the names of the students born in the year 2001. 117 | 118 | ### Q12. Display the names of the students born in the month of November 2000. 119 | 120 | ### Q13. Display the names of the students born in the year 2000 but not in the month of November. 121 | 122 | ### Q14. Display the different grades obtained by the students. 123 | 124 | ### Q15. Display the name, average and grade of all female students in the following format: 125 | 126 | ``` 127 | Shivani has scored an average of 95.2 with grade A. 128 | ``` 129 | 130 | ### Q16. Assume there is no average column in the table and the Total attribute is the expression of 5 subjects mark. Display the name and average marks of all the female students. 131 | 132 | ### Q17. Display names of students whose name starts with 'A'. 133 | 134 | ### Q18. Display the roll number, name, total of the students whose starts with 'A' and ends with 'd'. 135 | 136 | ### Q19. Display the details of students whose name is exactly 5 charcters in length. 137 | 138 | ### Q20. Display the details of students whose name has 'i'. 139 | 140 | ### Q21. Display the names of students not starting with A or S. 141 | 142 | ### Q22. Display names of students whose birth date is 5. 143 | 144 | ### Q23. Display the names of students in the table in alphabetical order. 145 | 146 | ### Q24. Display the name and total of female students in descending order of total. 147 | 148 | ### Q25. Display the name, grade and total of all the students who have scored above 395 in descending order of their grades and ascending order of their name. 149 | 150 | ### Q26. Find the sum of the total marks obtained by students who have scored the grade 'A'. 151 | 152 | ### Q27. Display the average of the average marks scored by 'A' graders. 153 | 154 | ### Q28. Display the total number of students in the table. 155 | 156 | ### Q29. Display the number of different grades available in the table. 157 | 158 | ### Q30. Display the details of the student(s) who is the youngest in the table. 159 | 160 | ### Q31. Write the Output for the following 161 | 162 | #### Q31.1 163 | 164 | ```sql 165 | SELECT MAX(Dob), MIN(Dob), SUM(Total) 166 | FROM `Student` 167 | WHERE Dob BETWEEN '2001-01-01' AND '2001-12-31'; 168 | ``` 169 | 170 | #### Q31.2 171 | 172 | ```sql 173 | SELECT COUNT(*), MAX(Total), MIN(Total) 174 | FROM `Student` 175 | WHERE Grade IN ('A', 'B'); 176 | ``` 177 | 178 | #### Q31.3 179 | 180 | ```sql 181 | SELECT SUM(Total + 5) 182 | FROM `Student` 183 | WHERE Grade='D'; 184 | ``` 185 | 186 | #### Q31.4 187 | 188 | ```sql 189 | SELECT AVG(Total / 5) 190 | FROM `Student`; 191 | ``` 192 | 193 | ### Q32. Display the count of gender based on gender. 194 | 195 | ### Q33. Display the maximum and minimum marks obtained by the students grade wise. 196 | 197 | ### Q34. Display the maximum and minimum total of the students born in the year 2001 based on their grade. 198 | 199 | ### Q35. Display the number of students grade wise where grades include A and B. 200 | 201 | ### Q36. Display the number of students grade wise where number of students in each grade is more than two. 202 | 203 | ### Q37. Update Varun's date of birth to 12th November 2000. 204 | 205 | ### Q38. Increment Sarchin's mark by 10 and alter his grade to B. 206 | 207 | ### Q39. Create a view V1 which is an exact copy of the _Student_ table. Display it after creation. 208 | 209 | Note: 2 seperate queries to be executed. One for the view and another for the displaying part. 210 | 211 | ### Q40. Create a view V2 which contains roll number and name of all the 'A' graders. 212 | 213 | ### Q41. Display the contents of the new view V2. 214 | 215 | ### Q42. Create a view V3 that has a a copy of roll number and name of all the 'A' graders but with new column names. Display the view after creation. 216 | 217 | Note: 2 seperate queries to be executed. One for the view and another for the displaying part. 218 | 219 | ### Q43. Add a new column age of appropriate data type to the existing table and fill the age. 220 | 221 | Note: First you will be adding a the column. Then you will be calculating the age and updating it in the table. So, 2 separate queries. Have the output of both the queries. 222 | 223 | ### Q44. Remove the column age from the _Student_ table. 224 | 225 | ### Q45. Alter the Average column to FLOAT(10, 2). 226 | 227 | Note: 228 | 229 | - Before executing the query for this question, execute `DESC Student;` and have the output in the markdown file. 230 | - Display the `Student` Table. 231 | - Have the query and the output for that in the markdown file. 232 | - Execute the query to change the column type. 233 | - Paste the query and the output to the markdown file. 234 | - Execute `DESC Student;` and paste the output in the markdown file. 235 | - Display the `Student` table again. 236 | 237 | ### Q46. Display the value of Total / 5 for every female student and give a new column name. 238 | 239 |
    240 | 241 | We need this table for the next set of queries. 242 | 243 | - Table Name : `Personal` 244 | 245 | | Roll | Parent | Address | Phone_No | 246 | | ---- | ------ | ---------------- | -------- | 247 | | 2 | ABC | 1st Cross Street | 12345678 | 248 | | 3 | XYZ | 2nd Cross Street | 41234561 | 249 | | 4 | PQR | 3rd Cross Street | 12370171 | 250 | | 7 | LMN | 4th Cross Street | 40007714 | 251 | | 9 | ABCD | 5th Cross Street | 56789101 | 252 | 253 |
    254 | 255 | ### Q47. Display the student name, parent name and address of all the students. 256 | 257 | ### Q48. Display the roll number, student name and parent name of all 'A' graders. 258 | 259 | ### Q49. Remove the details of those students from the `Student` table who have got 'D' grade. 260 | 261 | ### Q50. Remove the Student table from the database. 262 | -------------------------------------------------------------------------------- /SQL/README.md: -------------------------------------------------------------------------------- 1 | # SQL Notes 2 | 3 | #### Database Concepts 4 | 5 | | Term | Description | 6 | | --------------------- | -------------------------- | 7 | | Relational data model | Tabular form, relations | 8 | | relation | table | 9 | | attribute | every column of a relation | 10 | | tuple | every row of a relation | 11 | | degree of a relation | number of attributes | 12 | | cardinality | number of tuples | 13 | | view | virtual table | 14 | 15 | #### Types of Keys 16 | 17 | - Primary Key 18 | - Alternate Key 19 | - Candidate Key 20 | - Foreign Key 21 | 22 | #### Some important points 23 | 24 | **_Student_** Table 25 | 26 | | Admission_no | Roll_no | Sname | Total | 27 | | ------------ | ------- | ----- | ----- | 28 | | 1234 | 1 | abc | 123 | 29 | | 5678 | 2 | def | 431 | 30 | | 8765 | 3 | ghi | 436 | 31 | | 4321 | 4 | jkl | 172 | 32 | 33 | I will try to explain some concepts using the above table. 34 | 35 | - Primary Key : `Roll_no` 36 | - Aternate Key : `Admission_no` 37 | - Candidates for Primary Key : `Roll_no`, `Admission_no` 38 | 39 | - Two types of operation on a table: 40 | 41 | - Selection Operation 42 | - Projection Operation 43 | 44 | - #### Selection Operation 45 | 46 | - Done on `tuples` (rows) 47 | - Repesented by σ 48 | - Example: σ `Total < 400` (Student) 49 | - Output: 50 | | Admission_no | Roll_no | Sname | Total | 51 | | ------------ | ------- | ----- | ----- | 52 | | 1234 | 1 | abc | 123 | 53 | | 4321 | 4 | jkl | 172 | 54 | 55 | - #### Projection Operation 56 | 57 | - Done on `attributes` (columns) 58 | - Represented by π 59 | - Example: π `Total, Roll_no` (Student) 60 | - Output: 61 | | Total | Roll_no | 62 | | ----- | ------- | 63 | | 123 | 1 | 64 | | 431 | 2 | 65 | | 436 | 3 | 66 | | 172 | 4 | 67 | 68 | - #### Combination of Projection and Selection 69 | 70 | - Example: π `Total, Roll_no``Total < 400`) (Student) 71 | - Output: 72 | | Total | Roll_no | 73 | | ----- | ------- | 74 | | 123 | 1 | 75 | | 172 | 4 | 76 | 77 | - #### Cartesion Product 78 | 79 | - ##### Table 1 : _Student_ 80 | 81 | | Roll | Name | 82 | | ---- | ---- | 83 | | 1 | abc | 84 | | 2 | pqr | 85 | | 3 | xyz | 86 | 87 | - ##### Table 2 : _Teacher_ 88 | 89 | | id | Tname | 90 | | --- | ----- | 91 | | 714 | LMN | 92 | | 120 | RST | 93 | 94 | - ##### _Student_ x _Teacher_ 95 | 96 | | Roll | Name | id | Tname | 97 | | ---- | ---- | --- | ----- | 98 | | 1 | abc | 714 | LMN | 99 | | 1 | abc | 120 | RST | 100 | | 2 | pqr | 714 | LMN | 101 | | 2 | pqr | 120 | RST | 102 | | 3 | xyz | 714 | LMN | 103 | | 3 | xyz | 120 | RST | 104 | -------------------------------------------------------------------------------- /SwiftLearning/arc/example1.swift: -------------------------------------------------------------------------------- 1 | class Person { 2 | var name: String 3 | 4 | // gets called before the object is created 5 | init(_ _name: String) { 6 | print("init method of Person called") 7 | name = _name 8 | } 9 | 10 | func printName() { 11 | print("The name of the person is \(name).") 12 | } 13 | 14 | // performs cleanup before a object is deallocated. 15 | deinit { 16 | print("The delloction happens") 17 | } 18 | } 19 | 20 | 21 | let objectPerson = Person ("Kamal") 22 | objectPerson.printName() 23 | 24 | print("---------------------------") 25 | 26 | if(true) 27 | { 28 | let objectPerson = Person ("Kamal") 29 | objectPerson.printName() 30 | // ARC will dellocate 31 | } 32 | 33 | print("---------------------------") 34 | 35 | var objectPerson1: Person? 36 | var objectPerson2: Person? 37 | 38 | 39 | if(true) 40 | { 41 | let objectPerson = Person ("Kamal") 42 | objectPerson1 = objectPerson 43 | objectPerson2 = objectPerson 44 | objectPerson.printName() 45 | 46 | // ARC wont deallocate 47 | // because objectPerson1 and objectPerson2 that are declared before 48 | // are using the objectPerson 49 | } 50 | 51 | 52 | 53 | objectPerson1 = nil 54 | objectPerson2 = nil 55 | // now it will deinit the objectPerson 56 | -------------------------------------------------------------------------------- /SwiftLearning/arc/example2.swift: -------------------------------------------------------------------------------- 1 | class Person { 2 | var name: String 3 | var job: Job? 4 | 5 | 6 | // gets called before the object is created 7 | init(_ _name: String) { 8 | print("init method of Person is called") 9 | name = _name 10 | } 11 | 12 | func printName() { 13 | print("The name of the person is \(name).") 14 | } 15 | 16 | // performs cleanup before a object is deallocated. 17 | deinit { 18 | print("The deinit of Person is called") 19 | } 20 | } 21 | 22 | 23 | class Job { 24 | var jobDescription: String 25 | var person: Person? 26 | 27 | // gets called before the object is created 28 | init(_ _jobDescription: String) { 29 | print("init method of Job is called") 30 | jobDescription = _jobDescription 31 | } 32 | 33 | // performs cleanup before a object is deallocated. 34 | deinit { 35 | print("The deinit of Job is called") 36 | } 37 | } 38 | 39 | if(true) 40 | { 41 | let kamal = Person("Kamal") 42 | let swiftProgrammer = Job("Swift Programmer") 43 | kamal.job = swiftProgrammer 44 | 45 | // denit gets called for person and job 46 | } 47 | 48 | print("------------------------------------------------") 49 | 50 | if(true) 51 | { 52 | let kamal = Person("Kamal") 53 | let swiftProgrammer = Job("Swift Programmer") 54 | 55 | // a person has a job 56 | kamal.job = swiftProgrammer 57 | 58 | // a job is done by a person 59 | swiftProgrammer.person = kamal 60 | 61 | // deinit wont be called because of a strong reference cycle 62 | // this implies that our code dictates arc on which object to keep in memory 63 | } 64 | 65 | // - when weak keyword is added, then it will be called 66 | // - weak keywword can be added either in one of the class or both of them 67 | // - by default it is strong reference in swift 68 | -------------------------------------------------------------------------------- /SwiftLearning/arc/main.swift: -------------------------------------------------------------------------------- 1 | class Person { 2 | var name: String 3 | weak var job: Job? 4 | 5 | 6 | // gets called before the object is created 7 | init(_ _name: String) { 8 | print("init method of Person is called") 9 | name = _name 10 | } 11 | 12 | func printName() { 13 | print("The name of the person is \(name).") 14 | } 15 | 16 | // performs cleanup before a object is deallocated. 17 | deinit { 18 | print("The deinit of Person is called") 19 | } 20 | } 21 | 22 | 23 | class Job { 24 | var jobDescription: String 25 | var person: Person? 26 | 27 | // gets called before the object is created 28 | init(_ _jobDescription: String) { 29 | print("init method of Job is called") 30 | jobDescription = _jobDescription 31 | } 32 | 33 | // performs cleanup before a object is deallocated. 34 | deinit { 35 | print("The deinit of Job is called") 36 | } 37 | } 38 | 39 | if(true) 40 | { 41 | let kamal = Person("Kamal") 42 | let swiftProgrammer = Job("Swift Programmer") 43 | kamal.job = swiftProgrammer 44 | 45 | // denit gets called for person and job 46 | } 47 | 48 | print("------------------------------------------------") 49 | 50 | if(true) 51 | { 52 | let kamal = Person("Kamal") 53 | let swiftProgrammer = Job("Swift Programmer") 54 | 55 | // a person has a job 56 | kamal.job = swiftProgrammer 57 | 58 | // a job is done by a person 59 | swiftProgrammer.person = kamal 60 | 61 | // deinit wont be called because of a strong reference cycle 62 | // this implies that our code dictates arc on which object to keep in memory 63 | } 64 | 65 | // - when weak keyword is added, then it will be called 66 | // - weak keywword can be added either in one of the class or both of them 67 | // - by default it is strong reference in swift 68 | -------------------------------------------------------------------------------- /SwiftLearning/autoclosures/main.swift: -------------------------------------------------------------------------------- 1 | struct Person: CustomStringConvertible { 2 | let name: String 3 | 4 | var description: String { 5 | print("Asking for Person description.") 6 | return "Person name is \(name)" 7 | } 8 | } 9 | 10 | 11 | let isDebuggingEnabled: Bool = true 12 | 13 | func debugLog(_ message: () -> String) { 14 | /// You could replace this in projects with #if DEBUG 15 | if isDebuggingEnabled { 16 | print("[DEBUG] \(message())") 17 | } 18 | } 19 | 20 | let person = Person(name: "Bernie") 21 | debugLog({ person.description }) 22 | 23 | print("----------------------------------------------------------------") 24 | 25 | func debugLog2(_ message: @autoclosure () -> String) { 26 | /// You could replace this in projects with #if DEBUG 27 | if isDebuggingEnabled { 28 | print("[DEBUG] \(message())") 29 | } 30 | } 31 | 32 | let person2 = Person(name: "Bernie") 33 | debugLog2(person2.description) 34 | -------------------------------------------------------------------------------- /SwiftLearning/autoclosures/new.swift: -------------------------------------------------------------------------------- 1 | func goodMorning(morning: Bool, whom: String) { 2 | if morning { 3 | print("Good morning, \(whom)") 4 | } 5 | } 6 | 7 | func giveAname() -> String { 8 | print("giveAname() is called") 9 | return "Kamal" 10 | } 11 | 12 | goodMorning(morning: true, whom: giveAname()) 13 | goodMorning(morning:true, whom: "Leo") 14 | // if true, the output is: 15 | // giveAname() is called 16 | // Good morning, Kamal 17 | 18 | 19 | goodMorning(morning: false, whom: giveAname()) 20 | // if false, the output is: 21 | // giveAname() is called 22 | 23 | // Expected: call giveAname() to get a string and pass this string to goodMorning. 24 | // The first parameter is false and so the second parameter is unused for this case. 25 | // But function giveAname is called. 26 | 27 | 28 | // => giveAname() is called both the times 29 | 30 | // If giveAname should not be called, then use autoclosure 31 | 32 | 33 | print("-----------------------------------------------------------------") 34 | 35 | func goodMorning2(morning: Bool, whom: @autoclosure () -> String) { 36 | if morning { 37 | print("Good morning, \(whom())") 38 | } 39 | } 40 | 41 | func giveAname2() -> String { 42 | print("giveAname2() is called") 43 | return "Sharma" 44 | } 45 | 46 | goodMorning2(morning: true, whom: giveAname2()) 47 | goodMorning2(morning: true, whom: "Bharath") 48 | goodMorning2(morning: false, whom: "Kaushik") 49 | goodMorning2(morning: false, whom: giveAname2()) 50 | -------------------------------------------------------------------------------- /SwiftLearning/autoclosures/old.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | The @autoclosure attribute can be applied to a closure parameter for a function, 4 | and automatically creates a closure from an expression you pass in. 5 | When you call a function that uses this attribute, 6 | the code you write isn't a closure, but it becomes a closure 7 | */ 8 | func printTest1(_ result: () -> Void) { 9 | print("Before") 10 | result() 11 | print("After") 12 | } 13 | 14 | printTest1({ print("Hello") }) 15 | 16 | 17 | //---------------------------- 18 | print("------------------------------------------") 19 | 20 | 21 | 22 | // Turning an argument into a closure allows us to delay the actual request of the argument. 23 | 24 | func printTest2(_ result: @autoclosure () -> Void) { 25 | print("Before") 26 | result() 27 | print("After") 28 | } 29 | 30 | printTest2(print("Hello")) 31 | 32 | 33 | 34 | /* 35 | These two pieces of code produce identical results thanks to @autoclosure. 36 | In the second code example, the print("Hello") won't be executed immediately 37 | because it gets wrapped inside a closure for execution later. 38 | */ 39 | 40 | 41 | /* 42 | The @autoclosure attribute is used inside Swift wherever code needs 43 | to be passed in and executed only if conditions are right. 44 | */ 45 | 46 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/arc.swift: -------------------------------------------------------------------------------- 1 | class Person 2 | { 3 | var name: String 4 | weak var job: Job? 5 | 6 | init(_name: String) { 7 | debugPrint("init method of Person called") 8 | name = _name 9 | } 10 | 11 | func printName() { 12 | debugPrint("name is \(name)") 13 | } 14 | 15 | deinit { 16 | debugPrint("deinit called for person class") 17 | } 18 | } 19 | 20 | 21 | class Job 22 | { 23 | var jobDescription: String 24 | weak var person: Person? 25 | 26 | init(_jobDescription: String) { 27 | debugPrint("init method of Job called") 28 | jobDescription = _jobDescription 29 | } 30 | 31 | deinit { 32 | debugPrint("deinit called for job class") 33 | } 34 | } 35 | 36 | var objPerson1: Person? 37 | var objPerson2: Person? 38 | 39 | 40 | // if (1 == 1) 41 | // { 42 | // let objPerson = Person(_name: "kamal") 43 | // objPerson1 = objPerson 44 | // objPerson2 = objPerson 45 | // objPerson.printName() 46 | // } 47 | 48 | 49 | 50 | 51 | if (1 == 1) 52 | { 53 | let objPerson = Person(_name: "kamal") 54 | let objJob = Job(_jobDescription: "graduate intern") 55 | objPerson.job = objJob 56 | objJob.person = objPerson 57 | } 58 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/debug.swift: -------------------------------------------------------------------------------- 1 | 2 | var x : Int = -10 3 | var y = abs(x) 4 | print("Abs of \(x) is \(y).") 5 | 6 | debugPrint("One two three four five") 7 | // Prints "One two three four five" 8 | 9 | debugPrint(1...5) 10 | // Prints "ClosedRange(1...5)" 11 | 12 | debugPrint(1.0, 2.0, 3.0, 4.0, 5.0) 13 | // Prints "1.0 2.0 3.0 4.0 5.0" 14 | 15 | debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ") 16 | // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0" 17 | 18 | for n in 1...5 { 19 | debugPrint(n, terminator: "") 20 | } 21 | // Prints "12345" 22 | 23 | var range = "My range: " 24 | debugPrint(1...5, to: &range) 25 | 26 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/dump.swift: -------------------------------------------------------------------------------- 1 | class Abc { 2 | let a = "aa" 3 | let b = "bb" 4 | } 5 | 6 | let abc = Abc() 7 | 8 | // print(abc) 9 | 10 | dump(abc) 11 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/error.swift: -------------------------------------------------------------------------------- 1 | // 1. Create enum of Errors 2 | // 2. Create a Throwing __FUNCTION__ 3 | // 3. Function Call Using try Keyword 4 | // 4. Handling Errors Using do-catch Statement 5 | 6 | 7 | // create an enum with error values 8 | enum DivisionError: Error { 9 | 10 | case dividedByZero 11 | } 12 | 13 | // create a throwing function using throws keyword 14 | func division(numerator: Int, denominator: Int) throws { 15 | 16 | // throw error if divide by 0 17 | if denominator == 0 { 18 | throw DivisionError.dividedByZero 19 | } 20 | 21 | else { 22 | let result = numerator / denominator 23 | print(result) 24 | } 25 | } 26 | 27 | // call throwing function from do block 28 | do { 29 | try division(numerator: 10, denominator: 0) 30 | print("Valid Division") 31 | } 32 | 33 | // catch error if function throws an error 34 | catch DivisionError.dividedByZero { 35 | print("Error: Denominator cannot be 0") 36 | } 37 | 38 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/fatalError.swift: -------------------------------------------------------------------------------- 1 | print ("A") 2 | fatalError("Stoppppping Execution") 3 | print("B") 4 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/main.swift: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KamalDGRT/Notes/f78cfbe25c4b4dfc19d343caa67fa9d00135a630/SwiftLearning/built-in-functions/main.swift -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/minmax.swift: -------------------------------------------------------------------------------- 1 | var a = 10 2 | var b = 20 3 | 4 | var small = min(a, b) 5 | var big = max(a, b) 6 | 7 | var pMax = pointwiseMax(a, b) 8 | print("Min of \(a) and \(b) is \(small).") 9 | print("Max of \(a) and \(b) is \(big).") 10 | print("Pointwise Max : \(pMax).") 11 | 12 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/precondition.swift: -------------------------------------------------------------------------------- 1 | var num = 10 2 | var den = 1 3 | 4 | precondition(den != 0, "The denominator must not be 0.") 5 | var quo = num / den 6 | print("Quotient = \(quo)") 7 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/readLine.swift: -------------------------------------------------------------------------------- 1 | print("Enter Something") 2 | // let str = readLine() 3 | // print(str) 4 | 5 | // Unwrapping the optional 6 | // if let str = readLine(){ 7 | // print(str) 8 | // } 9 | 10 | 11 | // Determining the type of the number entered 12 | // if let input = readLine() 13 | // { 14 | // if let int = Int(input) 15 | // { 16 | // print("Entered input is \(int) of the type:\(type(of: int))") 17 | // } 18 | // else{ 19 | // print("Entered input is \(input) of the type:\(type(of: input))") 20 | // } 21 | // } 22 | 23 | 24 | 25 | let array = readLine()? 26 | .split {$0 == " "} 27 | .map (String.init) 28 | 29 | if let stringArray = array { 30 | print(stringArray) 31 | } 32 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/repeatAndSequence.swift: -------------------------------------------------------------------------------- 1 | let ones = repeatElement(1, count: 5) 2 | for x in ones { 3 | print(x) 4 | } 5 | 6 | // Iterate over all powers of two (ignoring overflow) 7 | // next is a closure that accepts the previous sequence element and returns the next element. 8 | // first: The first element to be returned from the sequence. 9 | for value in sequence(first: 1, next: { $0 * 2 }) { 10 | // value is 1, then 2, then 4, then 8, etc. 11 | print("Value = \(value)") 12 | if value > 100 { 13 | break 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/stride.swift: -------------------------------------------------------------------------------- 1 | // You can use this function to stride over values of any type that 2 | // conforms to the Strideable protocol, such as integers or floating-point types. 3 | // Starting with start, each successive value of the sequence adds stride until the 4 | // next value would be beyond end. 5 | 6 | 7 | for countdown in stride(from: 3, to: 0, by: -1) { 8 | print("\(countdown)...") 9 | } 10 | // 3... 11 | // 2... 12 | // 1... 13 | 14 | for radians in stride(from: 0.0, to: .pi * 2, by: .pi / 2) { 15 | let degrees = Int(radians * 180 / .pi) 16 | print("Degrees: \(degrees), radians: \(radians)") 17 | } 18 | // Degrees: 0, radians: 0.0 19 | // Degrees: 90, radians: 1.5707963267949 20 | // Degrees: 180, radians: 3.14159265358979 21 | // Degrees: 270, radians: 4.71238898038469 22 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/swap.swift: -------------------------------------------------------------------------------- 1 | // Exchanges the values of the two arguments. 2 | 3 | // The two arguments must not alias each other. To swap two elements of a mutable 4 | // collection, use the swapAt(_:_:) method of that collection instead of this function. 5 | 6 | var a = 10 7 | var b = 5 8 | print("Before swapping: a = \(a), b = \(b)") 9 | (a, b) = (b, a) 10 | print("After swapping: a = \(a), b = \(b)") 11 | 12 | print("------------------") 13 | 14 | print("Before swapping: a = \(a), b = \(b)") 15 | swap(&a, &b) 16 | print("After swapping: a = \(a), b = \(b)") 17 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/type.swift: -------------------------------------------------------------------------------- 1 | func printInfo(_ value: Any) { 2 | let t = type(of: value) 3 | print("'\(value)' of type '\(t)'") 4 | } 5 | 6 | let count: Int = 5 7 | printInfo(count) 8 | // '5' of type 'Int' 9 | 10 | 11 | -------------------------------------------------------------------------------- /SwiftLearning/built-in-functions/zip.swift: -------------------------------------------------------------------------------- 1 | let words = ["one", "two", "three", "four"] 2 | let numbers = 1...4 3 | 4 | for (word, number) in zip(words, numbers) { 5 | print("\(word): \(number)") 6 | } 7 | // Prints "one: 1" 8 | // Prints "two: 2 9 | // Prints "three: 3" 10 | // Prints "four: 4" 11 | 12 | 13 | // if there are uneven lengths, then the resulting zip will be of the shorter length 14 | let naturalNumbers = 1...Int.max 15 | let zipped = Array(zip(words, naturalNumbers)) 16 | // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)] 17 | print(zipped) 18 | -------------------------------------------------------------------------------- /SwiftLearning/extensions/computed.swift: -------------------------------------------------------------------------------- 1 | // Computed Properties 2 | 3 | extension Double { 4 | var km: Double { return self * 1_000.0 } 5 | var m: Double { return self } 6 | var cm: Double { return self / 100.0 } 7 | var mm: Double { return self / 1_000.0 } 8 | var ft: Double { return self / 3.28084 } 9 | } 10 | 11 | let oneInch = 25.4.mm 12 | print("One inch is \(oneInch) meters") 13 | // Prints "One inch is 0.0254 meters" 14 | 15 | let inchToCm = oneInch.cm 16 | print("Cm = \(inchToCm)") 17 | 18 | let threeFeet = 3.ft 19 | print("Three feet is \(threeFeet) meters") 20 | // Prints "Three feet is 0.914399970739201 meters" 21 | 22 | let aMarathon = 42.km + 195.m 23 | print("A marathon is \(aMarathon) meters long") 24 | // Prints "A marathon is 42195.0 meters long" 25 | 26 | // Extensions can add new computed properties, but they can’t add stored properties, 27 | // or add property observers to existing properties. 28 | 29 | -------------------------------------------------------------------------------- /SwiftLearning/extensions/initalizer.swift: -------------------------------------------------------------------------------- 1 | // extension as initializers 2 | 3 | struct Size { 4 | var width = 0.0, height = 0.0 5 | } 6 | struct Point { 7 | var x = 0.0, y = 0.0 8 | } 9 | struct Rect { 10 | var origin = Point() 11 | var size = Size() 12 | } 13 | 14 | let defaultRect = Rect() 15 | 16 | print("\(defaultRect)") 17 | 18 | let memberwiseRect = Rect( 19 | origin: Point(x: 2.0, y: 2.0), 20 | size: Size(width: 5.0, height: 5.0) 21 | ) 22 | 23 | print("\(memberwiseRect)") 24 | 25 | print("------------------------") 26 | 27 | extension Rect { 28 | init(center: Point, size: Size) { 29 | let originX = center.x - (size.width / 2) 30 | let originY = center.y - (size.height / 2) 31 | self.init(origin: Point(x: originX, y: originY), size: size) 32 | } 33 | } 34 | 35 | let centerRect = Rect(center: Point(x: 4.0, y: 4.0), 36 | size: Size(width: 3.0, height: 3.0)) 37 | print("\(centerRect)") 38 | // centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0) 39 | -------------------------------------------------------------------------------- /SwiftLearning/extensions/main.swift: -------------------------------------------------------------------------------- 1 | // Subscripts 2 | // Extensions can add new subscripts to an existing type. 3 | 4 | extension Int { 5 | subscript(digitIndex: Int) -> Int { 6 | var decimalBase = 1 7 | for _ in 0.. Void) { 6 | for _ in 0.. Int { 6 | var decimalBase = 1 7 | for _ in 0.. Int { 2 | return num + 1 3 | } 4 | 5 | func Increase_Double_By_One(num: Double) -> Double { 6 | return num + 1.0 7 | } 8 | 9 | // Generic Method 10 | // Strideable is a protocol for numbers 11 | func genericAdd(number: R) -> R { 12 | return number.advanced(by: 1) 13 | } 14 | 15 | print(Increase_Int_By_One(num: 5)) 16 | print(Increase_Double_By_One(num: 6.0)) 17 | 18 | print("---------------------------------------") 19 | print(genericAdd(number: 5)) 20 | print(genericAdd(number: 6.0)) 21 | 22 | // Advantages: 23 | // one method is enough for multiple typealias 24 | // Results in cleaner code 25 | 26 | -------------------------------------------------------------------------------- /SwiftLearning/generics/main.swift: -------------------------------------------------------------------------------- 1 | struct Movie { 2 | let name: String 3 | } 4 | 5 | 6 | let numbers = [1, 3, 5, 7, 9, 11, 13] 7 | let names = ["Anish", "Aakash", "Arun", "Bharath", "Kaushik"] 8 | let movies = [ 9 | Movie(name: "Batman"), 10 | Movie(name: "Harry Potter"), 11 | Movie(name: "Superman"), 12 | Movie(name: "Spiderman") 13 | ] 14 | 15 | func firstAndLast(_ numbers: [Int]) -> (Int, Int) { 16 | return (numbers[0], numbers[numbers.count - 1]) 17 | } 18 | 19 | func firstAndLastString(_ names: [String]) -> (String, String) { 20 | return (names[0], names[names.count - 1]) 21 | } 22 | 23 | let (first, last) = firstAndLast(numbers) 24 | 25 | print(first) 26 | print(last) 27 | 28 | print("-----------------------------------------------------") 29 | 30 | 31 | func genericFirstLast(_ values: [T]) -> (T, T) { 32 | return (values[0], values[values.count - 1]) 33 | } 34 | // When the functionality is almost identical but the data type is different, 35 | // one can opt in to use generics 36 | let (firstStr, lastStr) = genericFirstLast(names) 37 | 38 | print(firstStr) 39 | print(lastStr) 40 | 41 | 42 | print("------------------------------------------") 43 | 44 | let (firstMov, lastMov) = genericFirstLast(movies) 45 | print(firstMov) 46 | print(lastMov) 47 | -------------------------------------------------------------------------------- /SwiftLearning/inheritance/animal.swift: -------------------------------------------------------------------------------- 1 | class Animal { 2 | 3 | // properties and method of the parent class 4 | var name: String = "" 5 | 6 | func eat() { 7 | print("I can eat") 8 | } 9 | } 10 | 11 | // inherit from Animal 12 | class Dog: Animal { 13 | 14 | // new method in subclass 15 | func display() { 16 | 17 | // access name property of superclass 18 | print("My name is ", name); 19 | } 20 | } 21 | 22 | // create an object of the subclass 23 | var labrador = Dog() 24 | 25 | // access superclass property and method 26 | labrador.name = "Johnny" 27 | labrador.eat() 28 | 29 | // call subclass method 30 | labrador.display() 31 | 32 | 33 | 34 | // Output 35 | // I can eat 36 | // My name is Johnny 37 | 38 | -------------------------------------------------------------------------------- /SwiftLearning/inheritance/main.swift: -------------------------------------------------------------------------------- 1 | class Animal { 2 | 3 | // create method in superclass 4 | func eat() { 5 | print("I can eat") 6 | } 7 | } 8 | 9 | // Dog inherits Animal 10 | class Dog: Animal { 11 | 12 | // overriding the eat() method 13 | override func eat() { 14 | 15 | // call method of superclass 16 | super.eat() 17 | print("I eat dog food") 18 | } 19 | } 20 | 21 | // create an object of the subclass 22 | var labrador = Dog() 23 | 24 | // call the eat() method 25 | labrador.eat() 26 | -------------------------------------------------------------------------------- /SwiftLearning/inheritance/override.swift: -------------------------------------------------------------------------------- 1 | class Animal { 2 | 3 | // method in the superclass 4 | func eat() { 5 | print("I can eat") 6 | } 7 | } 8 | 9 | // Dog inherits Animal 10 | class Dog: Animal { 11 | 12 | // overriding the eat() method 13 | override func eat() { 14 | print("I eat dog food") 15 | } 16 | } 17 | 18 | // create an object of the subclass 19 | var labrador = Dog() 20 | 21 | // call the eat() method 22 | labrador.eat() 23 | 24 | 25 | // Output: 26 | // I eat dog food 27 | -------------------------------------------------------------------------------- /SwiftLearning/inheritance/super.swift: -------------------------------------------------------------------------------- 1 | class Animal { 2 | 3 | // create method in superclass 4 | func eat() { 5 | print("I can eat") 6 | } 7 | } 8 | 9 | // Dog inherits Animal 10 | class Dog: Animal { 11 | 12 | // overriding the eat() method 13 | override func eat() { 14 | 15 | // call method of superclass 16 | super.eat() 17 | print("I eat dog food") 18 | } 19 | } 20 | 21 | // create an object of the subclass 22 | var labrador = Dog() 23 | 24 | // call the eat() method 25 | labrador.eat() 26 | 27 | // Output 28 | // I can eat 29 | // I eat dog food 30 | -------------------------------------------------------------------------------- /SwiftLearning/nested_types.swift: -------------------------------------------------------------------------------- 1 | class Employee 2 | { 3 | var dept = Department () 4 | class Department { 5 | var EmpId = 150; 6 | var EmpName = "Kamal"; 7 | 8 | func GetDetails() -> String { 9 | return "Id: \(self.EmpId), Name: \(self.EmpName)" 10 | } 11 | } 12 | } 13 | 14 | 15 | var emp = Employee () 16 | print (emp.dept.GetDetails()) 17 | -------------------------------------------------------------------------------- /SwiftLearning/practice/main.swift: -------------------------------------------------------------------------------- 1 | // Type Casting 2 | 3 | class LivingBeing { 4 | var age :Int? 5 | 6 | init(age:Int?) { 7 | if let age = age { 8 | self.age = age 9 | } 10 | } 11 | } 12 | 13 | class Human: LivingBeing { 14 | var name:String? 15 | 16 | init(name:String?, age:Int?) { 17 | if let name = name { 18 | self.name = name 19 | } 20 | super.init(age: age ?? 0) 21 | } 22 | } 23 | 24 | class Animal: LivingBeing { 25 | var isMammals:Bool? 26 | 27 | init(isMammals:Bool?, age:Int?) { 28 | if let isMammals = isMammals { 29 | self.isMammals = isMammals 30 | } 31 | super.init(age: age ?? 0) 32 | } 33 | } 34 | 35 | let livingBeingArray = [ 36 | Animal(isMammals:true, age:12), 37 | Human(name:"Kamal",age:22) 38 | ] 39 | 40 | // Type Checking - is keyword is used 41 | for item in livingBeingArray { 42 | if item is Animal { 43 | print("item is of type Animal") 44 | } else if item is Human { 45 | print("item is of type Human") 46 | } 47 | } 48 | 49 | // Downcasting 50 | // use as? - when not sure if downcast will succeed 51 | // use as! - use only when you are sure that downcast will succeed 52 | // in as?, if downcast is not successful, it will return nil 53 | 54 | //forced downcasting to Animal 55 | let animalObj = livingBeingArray[0] as! Animal 56 | 57 | //forced downcasting to Human 58 | let humanObj = livingBeingArray[1] as! Human 59 | 60 | // forced downcasting can fail if: 61 | // - we try to downcast the first object to a Human and 62 | // - second object to an Animal. 63 | // In this case the result will be nil 64 | // which a normal type cannot handle and 65 | // the program will crash. 66 | 67 | // let animalObj1 = livingBeingArray[0] as! Human //error and crashes 68 | // let humanObj1 = livingBeingArray[1] as! Animal //error and crashes 69 | 70 | //nil..animalObj is of Human? (optional Human which is the type which we tried to downcast to) 71 | let animalObj2 = livingBeingArray[0] as? Human 72 | 73 | //nil..humanObj is of Animal? (optional Animal which is the type which we tried to downcast to) 74 | let humanObj2 = livingBeingArray[1] as? Animal 75 | 76 | // success, returns Animal? 77 | let animalObj3 = livingBeingArray[0] as? Animal 78 | 79 | // success, returns Human? 80 | let humanObj3 = livingBeingArray[1] as? Human 81 | 82 | // Upcasting 83 | let animalObj4 = livingBeingArray[0] as! Animal 84 | print("\(type(of: animalObj4))") 85 | // print("\(animalObj4?.age)") 86 | // Animal 87 | 88 | let animalObjectAsLivingBeingObj = animalObj4 as LivingBeing 89 | print("\(type(of: animalObjectAsLivingBeingObj))") 90 | // Should print LivingBeing but I am getting Animal 91 | // print("\(animalObjectAsLivingBeingObj?.age)") 92 | 93 | -------------------------------------------------------------------------------- /SwiftLearning/practice/optionals.swift: -------------------------------------------------------------------------------- 1 | // 7 ways to unwrap Optionals 2 | 3 | var name : String? = "Kamal" 4 | 5 | // 1) Forced unwrapping — unsafe. 6 | let person1:String = name! 7 | print("Person 1 : \(person1)") 8 | 9 | 10 | // 2) Implicitly unwrapped variable declaration — unsafe in many cases. 11 | var person2 = name! 12 | print("Person 2 : \(person2)") 13 | 14 | 15 | // 3) Optional binding — safe. 16 | if let person3 = name { 17 | print("Person 3 : \(person3)") 18 | } 19 | 20 | 21 | // 4) Optional chaining — safe. 22 | let person4 = name?.utf8 23 | print("Person 4 : \(person4)") 24 | 25 | 26 | // 5) Nil coalescing operator — safe. 27 | let person5 = name ?? "" 28 | print("Person 5 : \(person5)") 29 | 30 | 31 | // 6) Guard statement — safe. 32 | func greet(_ name: String?) { 33 | guard let unwrapped = name else { 34 | print("You didn't provide a name!") 35 | return 36 | } 37 | 38 | print("Hello, \(unwrapped)!") 39 | } 40 | greet(name) 41 | 42 | // 7) Optional pattern — safe. 43 | if case let person7? = name { 44 | print("Person 7 : \(person7)") 45 | } 46 | -------------------------------------------------------------------------------- /SwiftLearning/quiz/notes.txt: -------------------------------------------------------------------------------- 1 | 24th January: 2 | Difference between function and closure 3 | types of closure and its usage 4 | Enumeration and its usage 5 | Difference between structure and classes in Swift 6 | How to use Structure and Classes in Swift 7 | Status: Done 8 | 9 | 25th January: 10 | Optionals in Swift **** 11 | Inbuilt functions in Swift 12 | Error Handling 13 | Protocols 14 | Extensions 15 | 16 | 17 | 28th January 2022 18 | ARC **** 19 | Retain cycle 20 | Extension (code) 21 | - its usage 22 | - how to implement 23 | 24 | 25 | 31st January 2022 26 | - Extensions (code) 27 | - Nested Types 28 | - 7 ways of unwrapping Optionals 29 | - Type Casting (code with examples) 30 | 31 | 32 | 33 | wwdc latest videos 34 | Apple conference videos 35 | evolution of iOS 36 | device screen sizes 37 | auto layout 38 | constraints 39 | how to write efficient code in swift 40 | 41 | 42 | ADA complaints 43 | banner 44 | 45 | 46 | 47 | https://www.youtube.com/watch?v=1YtpP4Ytgrs 48 | 49 | 50 | By default, what is the default type of closure? 51 | closures are by default non-escaping in Swift 52 | 53 | 54 | https://abhimuralidharan.medium.com/difference-between-a-struct-and-a-class-in-swift-53e08df73714 55 | 56 | Full forms: 57 | ----------- 58 | KT - Knowledge Transfer 59 | AC - Acceptance Criteria 60 | QA - Quality Assurance 61 | UAT - User Acceptance Testing 62 | ADA - Americans with Disabilities Act (ADA) 63 | WVD - Virtual Windows Desktop 64 | IPM - Iteration Planning Meetings 65 | 66 | 67 | 68 | Optionals: 69 | https://www.youtube.com/watch?v=IG_JCxSPa_k 70 | https://www.youtube.com/watch?v=ZL8BFK8bVjk 71 | 72 | 73 | 74 | -------------------------------------------------------------------------- 75 | 76 | Architecture Types 77 | - What is it 78 | - different types of architectures that iOS devs use 79 | - Viper Architecture 80 | - Advatanges of Viper 81 | - What were the architectures before Viper 82 | - Why Viper 83 | - How Viper came into existence 84 | 85 | MVC 86 | MVVM 87 | 88 | 89 | 90 | Types Of iOS Design Architecture Patterns :- 91 | 92 | - MVC Architecture :- Model View Controller 93 | - MVVM Architecture :- Model View ViewModel 94 | - MVP Architecture :- Model View Presenter 95 | - VIPER Architecture :- View Interactor Presenter Entity Routing 96 | 97 | 98 | Why Architecture? 99 | - Large project will go over lots of lines 100 | - So, instead of having it one line, it will be a good practice to split it into modules. 101 | - Kind of like, Divide and Conquer Strategy. 102 | - When modules are present in different files, it becomes easier to detect and fix the bugs. 103 | 104 | Model - It is the part which interacts with the Database 105 | View - It is the part that is shown to the user 106 | Controller - It is the middle-man between the Model and the View 107 | 108 | 109 | V - View (displays info to the user and detects user interaction) 110 | I - Interactor (manipulates the entities/models by fetching data and storing data) 111 | P - Presenter (without the use of the UIKit, it contains the UI related business logic and prepares the data for presentation) 112 | E - Entity(the model objects) 113 | R - Router (aka wireframe, takes care of navigation in our module/application) 114 | 115 | VIPER arcitecture allows for a clearer separation of concerns and sepearates the viewController from handling most of the responsibility in the app. Concerns are separated into modules for each usage (i.e., provide a map for the user) Each module has a aclear layer of routing logic, presentation logic and business logic) 116 | 117 | 118 | 119 | SOLID Principles 120 | S - Single 121 | O - 122 | L - 123 | I - 124 | D - 125 | 126 | 127 | S - Single Responsibilty Principle 128 | O - Open Closed Principle 129 | L - Liskov Substitution Principle 130 | I - Interface Segregation Principle 131 | D - Dipendency Inversion Principle 132 | 133 | 134 | SRP 135 | A class should have one and only one reason to change. 136 | A class/component/package should have only one responsiblity 137 | A class should do only one thing 138 | 139 | --------------------------------------- 140 | 141 | Open/Closed Principle 142 | Software entities should be open for extension but closed for modification 143 | Example: Shapes and its areas 144 | 145 | --------------------------------------- 146 | 147 | Liskov Substitution Principle 148 | 149 | Subtypes must be suitable for their base types. 150 | Inheritance. 151 | You should use inheritance only when the super class is replaceable by a sub-class in all the instances. 152 | Dont use inheritance only to reuse a piece of code. 153 | 154 | --------------------------------------- 155 | 156 | Interface Segregation Principle (ISP) 157 | 158 | The dependency of one class to another one should depend on the smallest possible interface. 159 | * Clients should not be forced to implement interfaces they don't use. 160 | * Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one purpose. 161 | 162 | Example of bad implementaion of ISP 163 | 164 | Animal - feeds, grooms - abstract 165 | 166 | Dog extends Animal - feed and groom 167 | Tiger also extends Animal - feed and groom 168 | but tiger does not need grooming 'cause it is not a domestic animal 169 | 170 | Solution: 171 | Have an another interface called Pet 172 | 173 | I - Animal 174 | I - Pet extends Animal 175 | C - Dog extends Pet 176 | C - Tiger extends Animal 177 | 178 | Why we should have small interfaces: 179 | If we have large interfaces, every time we change the interface, we have to implement the same in the extended classes. 180 | 181 | 182 | ----------------------------------------- 183 | 184 | Dependency Inversion Principle 185 | 186 | Depends upon abstractions (interfaces) not upon concrete classes. 187 | 188 | void copy(OutputDevice dev) 189 | { 190 | int c; 191 | while (c == ReadKeyboard() != EOF) { 192 | if (dev == printer) 193 | writePrinter(c); 194 | else 195 | writeDisk(c); 196 | } 197 | } 198 | 199 | The problem with the above fn is that as the number of output device keeps on increasing, the copy() has to be changed everytime. 200 | 201 | So, A better implementation would be 202 | 203 | 204 | interface Reader 205 | char read() 206 | 207 | interface Writer 208 | char write(char ch) 209 | 210 | voice copy(Reader r, Writer w) { 211 | char ch; 212 | while((ch = r.read() != EOF) { 213 | w.write(ch); 214 | } 215 | } 216 | 217 | 218 | Library Management System 219 | 220 | 10 days 221 | 5 days above, 2 rupees fine per day 222 | borrow a book 223 | total books taken 224 | user can take n number of books 225 | only one admin login 226 | admin can alone access all the details 227 | one user cant see details of another user 228 | system can have n number of users 229 | limit on n 230 | status on how much overdue 231 | 232 | 233 | 234 | ----------------------------------------- 235 | 28th February 2022 236 | 237 | * Closures ***** 238 | What is it 239 | its types and when to use it 240 | where we use closure 241 | advantages of closure 242 | causes and effects on memory 243 | 244 | MVVM Architecture 245 | 246 | Connection between M V VM & Closure 247 | 248 | 249 | func test(a: Int, b:()->()){ 250 | // gets 2 nos 251 | // sum 252 | // PRINT 253 | } 254 | ------------------------------------------ 255 | 256 | 257 | { (parameters) -> returnType in 258 | // statements 259 | } 260 | 261 | --- 262 | 263 | var greet = { 264 | print("Hello, World!") 265 | } 266 | 267 | 268 | // call the closure 269 | greet() 270 | 271 | 272 | 273 | ------ 274 | 275 | 276 | // closure that accepts one parameter 277 | let greetUser = { (name: String) in 278 | print("Hey there, \(name).") 279 | } 280 | 281 | // closure call 282 | greetUser("Delilah") 283 | 284 | 285 | ------------ 286 | 287 | Closures that return a value: 288 | 289 | // closure definition 290 | var findSquare = { (num: Int) -> (Int) in 291 | var square = num * num 292 | return square 293 | } 294 | 295 | // closure call 296 | var result = findSquare(3) 297 | 298 | print("Square:",result) 299 | 300 | ----------------------------------- 301 | 302 | Trailing Closure 303 | In trailing closure, if a function accepts a closure as its last parameter 304 | we can call the function by passing closure as a function body without mentioning the name of the parameter. 305 | 306 | 307 | ------------------------------------- 308 | 309 | Autoclosure 310 | ----------- 311 | 312 | 313 | While calling a function, we can also pass the closure without using the braces {}. 314 | 315 | // define a function with automatic closure 316 | func display(greet: @autoclosure () -> ()) { 317 | // closure call 318 | greet() 319 | } 320 | 321 | // pass closure without {} 322 | display(greet: {print("Hello World!")}) 323 | ------------------------------------ 324 | 325 | Why do we use autoclosures over trailing Closures? 326 | When to use autoclosure? 327 | Why business logic should not be in the view over view-model? 328 | Unit test relation in view-model? (or) Why do we use only UNit test for VM? 329 | MVVM advantages - main advantages (2) 330 | -------------------------------------------------------------------------------- /SwiftLearning/quiz/questions.swift: -------------------------------------------------------------------------------- 1 | struct Question { 2 | var question : String 3 | var option1 : String 4 | var option2 : String 5 | var option3 : String 6 | var option4 : String 7 | var ca : String 8 | var ans : String 9 | var cans : String 10 | 11 | init(question : String, option1 : String, option2 : String, option3 : String, option4 : String, ca : String, ans : String, cans : String) { 12 | self.question = question 13 | self.option1 = option1 14 | self.option2 = option2 15 | self.option3 = option3 16 | self.option4 = option4 17 | self.ca = ca 18 | self.ans = ans 19 | self.cans = cans 20 | 21 | } 22 | 23 | } 24 | 25 | var Topic1 = [question]() 26 | 27 | Topic1.append(Question( 28 | question :"Largest artificial lake in India is", 29 | option1 :" Pushkar Lake", 30 | option2 :" Dal Lake", 31 | option3 :" Govind Sagar(Bhakra)", 32 | option4 :" Nainital Lake", 33 | cans :" Govind Sagar(Bhakra)", 34 | ca :"C" 35 | )) 36 | 37 | Topic1.append(Question( 38 | question :"State in India with the lowest literacy is", 39 | option1 :" Arunachal Pradesh", 40 | option2 :" Mizoram", 41 | option3 :" Manipur", 42 | option4 :" None of these.", 43 | cans :" Arunachal Pradesh", 44 | ca :"A" 45 | )) 46 | 47 | Topic1.append(Question( 48 | question :"India's first TV Centre was set up at :", 49 | option1 :" Calcutta", 50 | option2 :" Mumbai", 51 | option3 :" Delhi", 52 | option4 :" Poona", 53 | cans :" Delhi", 54 | ca :"C" 55 | )) 56 | 57 | Topic1.append(Question( 58 | question :"Which is the India's longest platform?", 59 | option1 :" Delhi", 60 | option2 :" Calcutta", 61 | option3 :" Sonepur", 62 | option4 :" Kharagpur", 63 | cans :" Kharagpur", 64 | ca :"D" 65 | )) 66 | 67 | Topic1.append(Question( 68 | question :"Highest rank in the Indian Army is", 69 | option1 :" Captain", 70 | option2 :" Major General", 71 | option3 :" General", 72 | option4 :" Colonel", 73 | cans :" General", 74 | ca :"C" 75 | )) 76 | 77 | Topic1.append(Question( 78 | question :" City of Gardens ?", 79 | option1 :" Mysore", 80 | option2 :" Gulburga", 81 | option3 :" Bangalore", 82 | option4 :" Shimoga", 83 | cans :" Bangalore", 84 | ca :"C" 85 | )) 86 | 87 | Topic1.append(Question( 88 | question :"Where are Vijayanta Tanks manufactured?", 89 | option1 :" Salem", 90 | option2 :" Avadi", 91 | option3 :" Mysore", 92 | option4 :" Alwaye", 93 | cans :" Avadi.", 94 | ca :"B" 95 | )) 96 | 97 | Topic1.append(Question( 98 | question :"India's first earth Satellite station is situated at:", 99 | option1 :" Thumba (near Trivandrum)", 100 | option2 :" Arvi (near Pune)", 101 | option3 :" Sriharikota on Andhra Coast", 102 | option4 :" None of these.", 103 | cans :" Arvi (near Pune)", 104 | ca :"B" 105 | )) 106 | 107 | Topic1.append(Question( 108 | question :"Chakra of the National Flag of India has", 109 | option1 :" 30 spokes", 110 | option2 :" 36 spokes", 111 | option3 :" 24 spokes", 112 | option4 :" None of these.", 113 | cans :" 24 spokes.", 114 | ca :"C" 115 | )) 116 | 117 | Topic1.append(Question( 118 | question :"Postage stamps were issued in India in", 119 | option1 :" 1852", 120 | option2 :" 1854", 121 | option3 :" 1892", 122 | option4 :" None of these.", 123 | cans :" 1854", 124 | ca :"B" 125 | )) 126 | 127 | Topic1.append(Question( 128 | question :"Supreme Commander of the Armed Forces", 129 | option1 :" Chief of Army Staff", 130 | option2 :" President of India", 131 | option3 :" Prime Minister", 132 | option4 :" Defence Minister", 133 | cans :" President of India.", 134 | ca :"B" 135 | )) 136 | 137 | Topic1.append(Question( 138 | question :"Percentage of land covered by forests", 139 | option1 :" 19.47%", 140 | option2 :" 40%", 141 | option3 :" 17.57%", 142 | option4 :" None of these", 143 | cans :"40%", 144 | ca :"B" 145 | )) 146 | 147 | Topic1.append(Question( 148 | question :"Ajanta Caves situated are situtated in", 149 | option1 :" Andhra Pradesh", 150 | option2 :" Maharashtra", 151 | option3 :" Madhya Pradesh", 152 | option4 :" Tamil Nadu", 153 | cans :" Maharashtra", 154 | ca :"B" 155 | )) 156 | 157 | Topic1.append(Question( 158 | question :"Sri Harikota is situated in which state?", 159 | option1 :" Bihar", 160 | option2 :" Tamil Nadu", 161 | option3 :" Andhra Pradesh", 162 | option4 :" Maharashtra", 163 | cans :" Andhra Pradesh", 164 | ca :"C" 165 | )) 166 | 167 | Topic1.append(Question( 168 | question :"Largest Zoo in India ", 169 | option1 :" Delhi Zoo", 170 | option2 :" Mumbai Zoo", 171 | option3 :" Zoological Garden (Alipore : Calcutta)", 172 | option4 :" None of these.", 173 | cans :" Delhi Zoo.", 174 | ca :"A" 175 | )) 176 | 177 | -------------------------------------------------------------------------------- /Yii2/README.md: -------------------------------------------------------------------------------- 1 | # Yii2 Notes 2 | 3 | Yii is an open source, object-oriented, component-based MVC PHP web 4 | application framework. Yii is pronounced as `"Yee"` and in Chinese it 5 | means `"simple and evolutionary"` and it can be an acronym for `"Yes It Is!"`. 6 | 7 | ### Salient features 8 | 9 | - One of the top 5 PHP framework. 10 | - Fast, secure and efficient PHP framework. 11 | - Framework is written fully in OOP. 12 | - Higly customizable code 13 | 14 | ### Prerequisites 15 | 16 | - Basic knowledge of PHP and OOP 17 | - Basic knowledge of HTML, CSS and JavaScript 18 | - Basic knowledge of database and SQL 19 | 20 | ### Features 21 | 22 | ### Why you should learn Yii2 23 | 24 | - Very fast 25 | - Easily customizable and extensible 26 | - Provides high security 27 | - Sutiable for small and large applications 28 | - Very powerful RESTful support 29 | - In the list of top 5 PHP frameworks 30 | - Quite demanded on US and EU market 31 | - Routing, Validation, etc 32 | 33 | ### Some Important Features 34 | 35 | - MVC (Model View Controller) 36 | - Built-in Bootstrap for CSS 37 | - Has `basic` and `advanced` versions 38 | - Uses `PDO` and `ActiveRecord` 39 | - Works fine with both SQL and NoSQL databases (Eg. MongoDB) 40 | - UI Widgets of BootStrap 41 | - Built-in client side validation 42 | - Powerful routing 43 | - RESTful API support 44 | - Powerful debugger 45 | - RBAC system (Role Based Access Control) 46 | - GII is used to generate code for CRUD (Create Read Update Delete), Model, etc. 47 | - Easily customizable 48 | 49 | and more. 50 | 51 | > Laravel doesn't have built-in client-side validation. There is 52 | > some 3rd party package for Laravel. 53 | --------------------------------------------------------------------------------