PCAP Flashcards

1
Q

State the differences between a compiled language and an interpreted language.

A

Compiled language:

After compilation, the program can be freely distributed without the need of the interpreter. You must have a compiler for each type of system. Faster execution. Examples: C, C++, Go.

Interpreted language:

The translation is done each time the program runs. The interpreter must be installed in all the computers to make the code run. Slower execution. Examples: PHP, Ruby, Python, Java.

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

How do you use binary, hexadecimal and scientific notation in Python?

A

Binary: 0bnnnnnnn

Hexadecimal: 0xnnnnnnn

Scientific notation: nEn, example: 3E8

Large numbers: use underscores (_) to separate big chunks of numbers

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

What are the three different ways you can specify a range in Python?

A
  1. range(2,8,3): range(start, end, increment). The end does not touch
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

List two ways in which you can slice a sequence in Python:

A
  1. Slice function: (,)
    • Returns a slice object similar to a range function.
    • You must specify the start, end and step.
      • lista = [i for i in range(10)]
      • x = slice(start=None, end, step=None)
      • sliced = lista[x]
  2. Bracket slicing - Index Operator: (:)
    • lista = [i for i in range(10)]
    • x = lista [start : end : step]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Calculate the module of the following operations:

  1. 4 % 6 =
  2. 2.33 % 2.1 =
  3. 10 % 3 =
A

RAr(AbArAb)

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

What are the different tuple methods?

A

Leia Meditated Meanwhile Surfers Inhaled Clever Irishmen.

len, min, max, slice, in, count, index

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

List two ways in which you can declare a tuple.

A
  1. Parenthesis:
    • my_tuple = (1, )
    • (s1, s2) = (1, 2)
  2. No parenthesis:
    • my_tuple = 1, 2, 3
    • s1, s2 = 1, 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

random Module most used functions and methods:

A

Strong Robocop Romanced Round Croutons Slowly

Seed, Random, Randrange, Randint, Choice, Sample

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

Useful methods of the datetime.date class:

A
  • .weekday():0 : Monday
  • .isoweekday(): 1: Monday (ISO)
  • .isoformat(): string : YYYY-MM-DD
  • .replace(): replaces the specified parameters.
  • .strftime(): readable string format.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Useful methods of the datetime.datetime class:

A
  • .today(), .now()

  • .strftime()
  • .strptime()

  • .fromisoformat(): returns a datetime coming from a string in ISO format
  • .isoformat()

  • .combine(): combines a date and a time
  • .replace()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Enlist all the different formatting styles that can be used with strftime:

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

Useful methods of the Calendar.Calendar class:

A

Generators:

  • .itermonthdates(year, month): datetime objects.
  • .itermonthdays(year, month): int (day#).
  • .itermonthdays2(year, month): tuple (day#, weekday#)
  • .itermonthdays3(year, month): tuple (year#, month#, day#)
  • .itermonthdays4(year, month): tuple (year#, month#, day#, weekday#)

Lists:

  • monthdatescalendar(year, month): datetime (separated in weeks).
  • monthdayscalendar(year,month): int (day#) (separated in weeks).
  • monthdays2calendar(year,month): tuple (day#, weekday#) (separated in weeks).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a Python generator?

A
  • collections
    • ⇒ Iterator()
      • ⇒ Generator (yield, list-like)
      • ⇒ [], (), {}, set()
      • ⇒ str(), b””, bytearray(), range(), map()
  • Generator:
    • yield statement:

def gen():

x = 0

for x in range(10):

if x%2 :

yield x

  • list-like:

it = (x for x in range(10) if x % 2)

(PARENTHESIS)

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

tkinter

How do you create the root window in an OOP program?

A
  1. root = tkinter.Tk()
  2. app = Application(root)
  3. App: def \_\_init\_\_(Frame):
    • super().\_\_init\_\_()
    • self.main = tkinter.Frame
  4. Pack self.main and this will be the master of all widgets.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

tkinter

What is the process to create a RadioButton?

A

1. Create a variable: tkinter.BooleanVar, DoubleVar, IntVar, StringVar.

  1. Set a default value for it.
  2. Create the radiobutton:
    • r1 = tkinter.RadioButton(master, variable =, value=,...)
  3. Define the function that sets the tkinter variable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

tkinter:

What is the process for creating a Calendar?

A
  1. pip install tkcalendar
  2. import tkcalendar.
  3. tcal = tkcalendar.Calendar(master, )
  4. date_temp = tcal.get_date():String
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

tkinter:

What is the process to create image widgets?

A
  1. pip install Pillow
  2. Imports:
    • import PIL
    • from PIL import ImageTk, Image
  3. Create image object:
    • ima = ImageTk.PhotoImage(Image.open("whatever.jpg"))
    • ima = ImageTk.BitmapImage(Image.open("whatever.bmp"))
  4. Use the image:
    • ​lbl = tkinter.Label(master, image=ima)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the process to use gspread?

A
  1. Google Cloud Console:
    1. https://console.cloud.google.com/
    2. API’s and services.
    3. Create Credentials ⇒ Create a service account (Key type = JSON).
    4. Share the Google Sheet with the client’s email.
  2. Code:
    1. pip:
      • pip install oauth2client
    2. imports:
      • import gspread
      • from oauth2client.service_account import ServiceAccountCredentials
    3. Create creds:
      • creds = ServiceAccountCredentials.from_json_keyfile_name("")
      • client = gspread.authorize(creds)
    4. Open a worksheet:
      • sheet = client.open("name")
      • worksheet1 = sheet.worksheet("name")
    5. ​Using gspread:
      1. Get a value:
        1. val = ws.cell(1,2)
        2. vals = ws.row_values(2)
      2. Update a value:
        1. ws.update_cell(1,2, "hello")
        2. ws.update("A1:B1", [[1, 2],[3, 4]])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the meaning of API?

A

Application Programming Interface

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

What are the basic principles of a REST API?

A

REpresentational State Transfer.

It has 6 constraints (LUCCCS):

  1. Layered:
    • Intermediate dedicated servers(security, load balancing), client does not know to which server it’s communicating.
  2. Uniform Interface:
    1. Resource Based:
      • Server sends a representation of resources. Uniquely identified resource.
    2. Self-descriptive Messages:
      • Each message contains everything needed.
    3. Hypermedia (HATEOAS):
      • Body, request - response headers, URIS.
  3. Cacheable:
    • The client caches info to decrease client-server interactions. Improves client performance.
  4. Client server architecture:
    • Server: data storage. Client: UI. HTTP requests, client portability, client-server independence.
  5. Code on demand (optional)
    • Server returns code to the client (Javascript, Java applets).
  6. Statelessness:
    • Each client request should have the creds, so no session keeps open by the server.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What does OAuth stand for?

A

Open Authorization

(HTTP requests)

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

What types of OAuth grants exist?

A
  1. Resource owner password credentials:
    • Resource owner supplies creds.
    • Unsafe.
  2. Client credentials:
    • Resources are owned by the client itself.
  3. Authorization code:
    • Most commonly used.
    • Auth server issues an auth code, then access token - refresh token.
    • Resource owner credentials, never shared.
  4. Implicit:
    • No Oauth code is issued, only access tokens.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you use map()?

A
  • Transform a set of items without the need for iteration in one single expression:
  • map_object = map (callable, iterable)
  • Callable (function):
    • Class constructors: Class()
    • User defined function.
    • Built-in function.
    • lambda functions.
  • Example:
    • mapa = map(lambda x,y: x-y, [5,5,5],[1,3,5])
    • >> 4 2 0
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you use a lambda function? What are they useful for?

A
  • lambda arguments(n, *): expression(just 1, no statements)
  • Wherever a regular function object is allowed (lambda: syntactic sugar, anonymous function).
  • Functional paradigm, often used with map(), filter(), reduce().
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is a JSON file?

A

JavaScript Object Notation

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

What is the basic process for a pickle file?

A
  • Python specific.
  • Read:

with open("file.pickle", "rb") as file:

data = pickle.load(file)

  • Write:

with open("file.pickle", "wb") as file:

pickle.dump(any_object, file)

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

What are the most used types of HTTP request methods?

A
  • GET: request data.
    • /test/demo_form.php?name1=value1&name2=value2
  • POST: send data to a server
    • data sent is stored in the request body of the HTTP request
  • HEAD: response identical to that of a GET request, but without the response body.
  • DELETE /file.html HTTP/1.1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What are the basic elements of an API?

A
  • Most of the time, API means REST API.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What does GIT stand for?

A

Global Information Tracker

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

What are other types of version control systems?

A
  • Azure DevOps:
    • Team Foundation Version Control (TFVC) or Git
    • Entire application lifecycle:
      • Reporting.
      • Requirements management.
      • Project management (for both agile software development and waterfall teams)
      • Automated builds
      • Testing
      • Release management.
  • Apache Subversion:
    • Versioning and revision control system distributed as open source.
  • Perforce:
    • Software used for developing and running applications, including version control software, web-based repository management, developer collaboration, application lifecycle management, web application servers, debugging tools and Agile planning software (DevOps).
  • Mercurial:
    • Free, distributed source control management tool.
    • Mainly Python.
    • $ hg clone “URL”, $ hg add (new files)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is the basic process for creating a GIT repo?

A
  • Download GIT.
    • git-scm.com
  • Init repo:

$ git init

  • Create a .gitgnore file.
  • First Time config:

$ git config --global user.name "name"

$ git config --global user.email "something@mail.com"

  • Commit:

$ git add filename.txt, $ git add .

$ git commit -m "description"

$ git status

$ git log

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

What is a git branch?

A
  • $ git branch testing
    • Diverge from the main line.
    • Default branch name:master(git init creates it)
    • HEAD: Pointer to current branch
  • Commit object:
    • Pointer to snapshot,
    • Author’s name and email address,
    • Message,
    • Pointers to parent or parents:
      • Initial commit: 0.
      • Normal commit: 1
      • Merge of two or more branches: Multiple parents.
  • Switch to branch:
    • $ git checkout testing
  • Create and switch:
    • $ git switch -c new-branch.

-c, --create

  • $ git log and branches:
    • Commit history for branch: $ git log branch_name
    • All branches: $ git log --all
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How do you return to a specific snapshot of a GIT repo?

A
  • $ git checkout 40fd555
  • $ git checkout branch_name
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is the HEAD in a GIT repo?

A
  • HEAD: Pointer to current branch.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

How do you set up a remote repo?

A
  • Create a GitHub account.
  • Create a new repository.
  • In the Local repo:

$ git remote add origin https://github.com/oarpavon99/whatever.git

  • LocalRemote:

$ git push -u origin master

$ git push -u(save changes) origin(where?) master(branch)

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

What are the different types of tags that you can include in a GIT version?

A
  • $ git tag
    • -l: list tags that match a pattern -l "v1.8.5*"
      • -lw: lightweight tag (≈ branch)
      • -d: delete tag-d v1.4
  • Annotated:
    • $ git tag -a v1.4 -m "my version 1.4"
      • ​$ git tag -a v1.2 9fceb02(checksum) (tag later)
  • Show tag:
    • $ git show
      • Tagger info, date of tag, tag message
      • Commit info.
  • Checkout tag:
    • $ git checkout v2.0.0
      • No new commits (unreachable)
    • -b version2 v2.0.0 : new branch ‘version2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

How do you remove a file from a remote repo?

A
  • git rm - Remove files.
    • --cached: stage for removal, not working directory
    • -r : recursive removal of working directory
  • To remove it from a remote repo(Github): ` `
    1. git rm --cached
    2. git add
    3. git commit -m ""
    4. git push -u origin master / git push
      ` `
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

How do you remove a file from a local repo?

A
  1. git rm --cached
  2. git add
  3. git commit -m ""
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is merge used for?

A
40
Q

What is the difference between a generator and an iterator?

A
  • A generator is a subclass of an iterator that has an easier syntax. Limited functionality, not so general as collections.Iterator
  • There are two types:
    • Yield statement.
    • List like generators.
41
Q

What is the iterator protocol?

A

An iterator class definition should have the following 3 methods to comply with the protocol:

  1. \_\_iter\_\_():
    • return self (the iterator)
  2. \_\_next\_\_():
    • What happens in the next iteration?
  3. raise StopIteration:
    • When should the iterations stop?
    • Must be raised by \_\_next\_\_ method.
42
Q

What are the 4 pillars of OOP?

A
  1. Encapsulation:
    • class:
      • variables
      • methods
    • information hiding: __private, _protected, public
    • GET / SET methods
  2. Abstraction:
    • User interacts with methods, not implementation
  3. Polymorphism:
    • Static Polymorphism:
    • same name, different behavior
    • type
    • number
    • order
    • DynamicPo
  4. Inheritance:
    • whatever
    • whatever
43
Q

What do you use the reduce() function for?

A
  • functools.reduce(function (two args), iterable)
  • Applies a function in a cumulative manner yielding one final value.
  • More Pythonic solutions:
    • sum(), math.prod(), max(), min(), all(), any()
44
Q

What do you use the filter() function for?

A
  • fil = filter(function, iterable)
  • Returns a that can be converted to a list.
  • The filter object contains the items of the function returns True.
45
Q

How do you define a custom Exception?

A

Define custom Exceptions:

class CustomException(Exception):

def \_\_init\_\_ (self, msg):

super().\_\_init\_\_(msg)

Raise custom Exceptions:

def checkforexceptions(whatever):

if condition:

raise Exception

46
Q

How do you call a custom exception?

A

Raise custom Exceptions:

def checkforexceptions(whatever):

if condition:

raise Exception

47
Q

What would you use for-else or while-else loops for?

A
48
Q

Can you pass arguments to an Exception?

A
49
Q

Classify the Exceptions:

A

Base Exception (not meant to be directly inherited by user-defined classes)

⇒ Exception (built-in, non-system-exiting exceptions)

⇒ ArithmethicError

ZeroDivisionError, FloatingPointError

⇒ AssertionError

⇒ StopIteration

⇒ ValueError

Right type but an inappropriate value.

⇒ TypeError

Operation or function is applied to an object of inappropriate type.

Raised by user code to indicate that an attempted operation on an object is not supported.

⇒ LookupError

⇒ IndexError

Sequence subscript is out of range.

⇒ KeyError

Dictionary key is not found.

⇒ OSError

⇒ FileExistsError

errno EEXIST

⇒FileNotFoundError

errno ENOENT

⇒ KeyboardInterrupt

⇒ SystemExit

50
Q

What is a shell?

A
  • Computer program which exposes an operating system’s services to a human user or other program.
  • For example:
    • Windows Shell (Windows’ GUI).
    • CLI shells (Command Line Interface): Bash (Unix) or CMD prompt in Windows.
51
Q

What is bash?

A
  • Unix CLI shell.
  • Default login shell for most Linux distributions since 1989.
  • Replaced Bourne Shell (Bourne Again sh - bash (sh: name of the language)
52
Q

What is syntactic sugar?

A

It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

53
Q

What are some useful examples of syntactic sugar?

A
`x = something if condition else otherthing`
# python ternary
`a += 1`
# equivalent to a = a + 1
`1 < x < 10`
# equivalent to 1 \< x and x \< 10
`[x for x in range(10)]`
# List comprehension
54
Q

What is an OrderedDict, and what is the difference with a regular Dictionary?

A
  • Create:
    • from collections import OrderedDict
    • dic = OrderedDict()
  • Methods:
    • dic.popitem()
    • dic.move_to_end(key)
  • Equality:
    • Checks for keys and values but also order of insertion.
  • New operators for dictionaries in Python 3.9:
    • | merge
    • |= update
55
Q

What are the uses of the yield statement?

A
  • When resumed, the function remember where it was before the last yield run.
  • Similar to return:
    • Return sends a specified value back to its caller whereas yield can produce a sequence of values.
  • yield expression is used when defining a generator function and thus can only be used inside def.
  • yield expressions are allowed anywhere in a try construct.
56
Q

What is a bytearray? What do you use them for?

A
  • Always created by calling the constructor:
    • bytearray(), bytearray(10), bytearray(range(20)), bytearray(b'Hi!').
  • Basic building block of a binary file: pictures, music, video, etc.
  • Methods:
    • bytes.decode(encoding="utf-8", errors="str")
    • # Regular sequence methods:
      • bytearray.count(sub[, start[, end]])
      • bytes.replace(old, new[, count])
      • bytes.find(sub[, start[, end]])
      • bytes.index(sub[, start[, end]])
      • bytes.lstrip([chars])
      • bytes.rsplit(sep=None, maxsplit=-1)
      • bytes.isalpha()
57
Q

What are the different file open modes?

A
  • with open("file.ext", "xt"/"rt") as file:
  • XARW:
    • “x”: create
    • “a”: append
    • “r”: read
    • “w”: write
  • “t”: Text Mode
  • “b”: Binary Mode
  • ”+”: Open to update
58
Q

What are the most common HTTP response status codes​?

A
  1. Informational responses (100–199)
  2. Successful responses (200–299)
    • 200 OK:
      • GET: The resource has been fetched and is transmitted in the message body.
      • HEAD: The entity headers are in the message body.
      • PUT or POST: The resource describing the result of the action is transmitted in the message body.
      • TRACE: The message body contains the request message as received by the server.
    • 201 Created: Resource created.
  3. Redirects (300–399)
  4. Client errors (400–499):
    • 400 Bad Request: client error (e.g., malformed request syntax, deceptive request routing).
    • 401 Unauthorized: request has not been applied because it lacks valid authentication credentials for the target resource.
    • 403 Forbidden: server understood the request but refuses to authorize it.
    • 404 Not Found: server can’t find the requested resource. Links that lead to a 404 page are often called broken or dead links.
  5. Server errors (500–599)
    • 500 Internal Server Error: Server encountered an unexpected condition that prevented it from fulfilling the request. Generic “catch-all” response. Usually, this indicates the server cannot find a better 5xx error code to response.
    • 503 Service Unavailable: Server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded.
59
Q

Useful methods in OS module?

A
  • os:

Rats Stabbed Wieners.

* `os.rename("old_file_name", "new_file_name")`
* `os.stat("file_ name"): `
    * `st_size = # size in bytes.`
    * `st_mtime = # last modified (timestamp).` ` `
* `os.walk(top="path"): `
    * `# returns a tuple with the tree structure for iteration.` ` ` * **os.path:**

Beasts Discussed Indecent Spielberg.

* `os.path.basename("path")`
* `os.path.dirname("path")`
* `os.path.isdir("path")`
* `os.path.splittext("path"): `
    * `# returns a list with the path and the file extension.`
60
Q

Where do you find the Path class?

A

from pathlib import Path

  • A subclass of PurePath
  • Correspondence to tools in the os module:
    • Path.cwd()
    • Path.stat()
    • Path.exists()
    • Path.is_dir()
    • Path.mkdir()
    • Path.open()
    • Path.touch()
  • p = Path(direccion.name)
    • with open(p, "rt", encoding="utf-8") as file:
61
Q

Useful methods in CSV module?

A
  • csv.reader(csvfile, dialect='', **fmtparams)
    • Reader object which will iterate over lines.
    • csvfile: any object that supports the iterator protocol and returns a string.
    • Dialect : ‘excel’, excel-tab’, ‘unix’ (‘\n’ as line terminator and quoting all fields)
    • csvreader.\_\_next\_\_()
  • csv.writer(csvfile, dialect='', **fmtparams)
    • csvwriter.writerow(row)

**fmtparams = Dialects and Formatting Parameters

62
Q

What are the different characteristics of the 3 programming paradigms?

A
  • Procedural programming, structured programming
    • Specifies the steps a program must take to reach a desired state.
    • Use of global variables.
  • Functional programming
    • Treat programs as evaluating mathematical functions and avoids state and mutable data.
    • Functions pass values, less global variables.
  • Object-oriented programming (OOP)
    • Organizes programs as objects: instances, data structures consisting of datafields and methods together with their interactions.
63
Q

What are dunder methods?

A
  • Special, predefined methods. (double underscore: __init__ or __str__).
  • There are hundreds of Special methods available to implement in Python.
  • The special methods provide a common API that allows developers to create interactive classes.
  • Create classes with native data structures behavior.
  1. Object Initialization:
    • \_\_init\_\_
  2. Object Representation:
    • \_\_repr\_\_: The “official” string representation of an object. This is how you would make an object of the class. The goal of __repr__ is to be unambiguous.
    • \_\_str\_\_: The “informal” or nicely printable string representation of an object. This is for the enduser.
  3. Iteration:
    • Sequences:
      • \_\_len\_\_: >>> len(obj)
      • \_\_getitem\_\_: >>> obj[1]
    • \_\_reversed\_\_: reversed(obj)
  4. Arithmetic Operators:
    • \_\_add\_\_: >>> 1 + 2, (also: -, *, /, //)
  5. Callable:
    • \_\_call\_\_: >>> obj()
  6. Delete:
    • \_\_del\_\_: >>> del(obj)
64
Q

Useful list methods?

A
  • Sequences: support the \_\_len\_\_ and \_\_getitem\_\_ methods. Lists, tuples, ranges, strings, bytes.
    • Common Sequence methods (lists, tuples, ranges, strings, bytes- b’‘-ASCII):
      • in, +, *, s[i], len(), index(), count(), min(), max(), sort()
    • Mutable Sequence methods (lists, bytearray):
      • Direct assignation: s[i] = x
      • del(), clear(), copy()
      • append(), insert(i, x), pop([i]), remove(), reverse()
  • ​​List supports both sets of instructions.
65
Q

How do you turn off the computer using command line?

A

> shutdown /s /t : xxx time in seconds

> shutdown /p: Immediate shutdown

> shutdown /a: Abort shutdown

66
Q

What do you use the global keyword for?

A
67
Q

What is the difference between parameters and arguments?

A
68
Q

What is argument tuple packing?

A
69
Q

What is argument tuple unpacking?

A
70
Q

What is name mangling?

A
71
Q

What is the precedence order for the 3 types of ways of passing arguments to a function or method?

A
72
Q

Create some list comprehension arrays:

  • 4 rows x 5 columns
  • 1 row x 7 columns
  • 3 rows x 10 columns
A
73
Q

What is a \_\_pycache\_\_ file? What is the name format for it?

A
74
Q

What is the special variable \_\_name\_\_ used for?

A
75
Q

How do you raise an assertion error?

A
  • assert expression1, expression2 OR "TEXT"
    • Debugging assertions into a program.
  • raise AssertionError("Hola amiguitos")
    • >> AssertionError: Hola amiguitos
76
Q

What is the expected output of the following code snippet?

assert False

A

assert False

>> AssertionError

assert True

>>

77
Q

What is Unicode?

A
  • Backward compatible with ASCII. ≈ 1 million Code points.
  • Processing, storage and interchange of text data in any language. U+20AC, U+0800
  • Unicode Transformation Formats (UTF): UTF-8, UTF-16, and UTF-32.
  • 95% of websites as of 2020. Unicode Consortium.
78
Q

What is UTF-8?

A
  • 1,112,064 code points
  • Lower numerical values Code Points (frequently used) ⇒ fewer bytes.
  • World Wide Web Consortium recommends UTF-8 as the default encoding in XML and HTML
79
Q

What are the restricted keywords in Python?

A
  • 35 keywords:
    • from, import, with, as
    • class, def, lambda, global, local
    • for, while, if, elif, else, try, except, assert, raise, finally,
    • pass, continue, break, return, yield
    • and, or, not, is, in, non, del, True, False, None
    • await, async
80
Q

Please enlist all the different list comprehension - like data structures.

A
  • Set comprehension (no duplicates, no particular order):
    • >>> quote = "life, uh, finds a way"
    • >>> unique_vowels = {i for i in quote if i in 'aeiou'}
  • Dictionary comprehensions:
    • >>> squares = {i: i * i for i in range(10)}
81
Q

Types of lambda expressions:

A
  • lambda [parameter_list] : expression
  • Characteristics:
    • Anonymous function
    • Syntactic Sugar.
    • Wherever a function object is allowed.
    • Functional paradigm.
  • def (parameters):
    • return expression
82
Q

Most useful options for pip install:

A
  • pip install x_package == version
  • -U, --upgrade: upgrade to the newest version
  • --force-reinstall: reinstall all packages (even if up-to-date)
  • -r, --requirement
83
Q

What is the difference between index() and find() for a string?

A
  • Both have an identical syntax:
    • "string".index("substring", start(int), end(int))
    • "string".find("substring", start(int), end(int))
  • If "substring" is not found:
    • index returns ValueError
    • find returns -1
84
Q

What does isinstance() do?

A
  • isinstance(object, classinfo)
    • True: if object is instance or subclass of classinfo
85
Q

What is a closure? Why would I want to use them?

A
86
Q

Most frequent Linux errors:

A
  • 2 - ENOENT: No such file or directory
  • 9- EBADF: Bad file number (unopened stream)
  • 13 - EACCES: Permission denied (read only)
  • 17 - EEXIST: File exists
  • 21 - EISDIR: Is a directory
  • 24 - EMFILE: Too many open files
  • 27 - EFBIG: File too large
  • 28 - ENOSPC: No space left on device
87
Q

What is errno?

A
  • Module standard errno system symbols (linux/include/errno.h)
  • errno.errorcode:
    • errno.errorcode[errno.EPERM]
    • >> 'EPERM'
88
Q

What is sterror?

A
  • os.strerror(errno.ENOSPC)
    • Return the error message corresponding to the error code in code.
    • On platforms where strerror() returns NULL when given an unknown error number, ValueError is raised.
89
Q

What is encapsulation?

A
  • class:
    • variables
    • methods
  • Information hiding: \_\_private, _protected, public
  • GET / SET methods
90
Q

Useful classes - methods of shelve module:

A
91
Q

What are the OAuth 2.0 roles?

A
  1. Resource owner: End user ⇒ Credentials ⇒ Limited scope
  2. Client: App.
  3. API’s Resource Server: Hosts user’s information.
  4. API’s Auth Server: Access tokens.
92
Q

Explain the OAuth2.0 endpoints:

A
  1. Authorization Endpoint:
    • Used by Auth code (returns code) and Implicit (returns token) grants.
  2. Token Endpoint:
    1. Client presents Auth code or Refresh Token, Auth server grants access.
    2. Used by Auth code, resource owner, client credentials.
  3. Redirection Endpoint:
    • OAuth redirects to a URI.
93
Q

Describe the Auth Code grant:

A
  1. Auth request:
    • Client sends:
      • Client ID.
      • Scope.
      • State.
      • Redirection URI.
  2. Auth grant:
    • Auth code is sent to Auth server. An access/refresh token will be issued.
  3. Access Token:
    • The client sends the access token to the Resource server to have access to resources.
94
Q

Explain the basic process to configure OAuth2.0 with a Google Cloud API:

A
  1. Create an OAuth2.0 client:
    • Client ID & secret.
  2. Configure consent screen:
    • App name.
    • Developer email.
    • Scopes.
  3. App type:
    • Local web server.
  4. Add redirect URI.
    • http://localhost.8080/ (same port as in run local server).
  5. Get client ID & secrets
    • JSON.
95
Q

How do you use a Google API using OAuth2.0?

A
  1. Install:
    • pip install google-auth-oauthlib
    • pip install google-api-python-client.
  2. Import:
    • from google_auth_oauthlib.flow import InstalledAppFlow
    • from googleapiclient.discovery import build
  3. Instance the Auth Flow:
    1. self.flow = InstalledAppFlow.from_client_secrets_file( "creds_00.json", scopes=[] )
  4. OAuth2.0:
    1. Ask user auth.
      • self.flow.run_local_server( port=8080, prompt="consent", authorization_prompt_message="" )
    2. Get credentials , access-refresh token:
      • self.flow.credentials
  5. ​​Service:
  • self.service = build("classroom", "v1", credentials=creds)
  • request = self.service.courses().list(courseStates="ACTIVE", teacherId="me")
  • response = request.execute()