TypeScript - Ignore Null or Undefined
With exclamation mark at end of variable name - !
Arbitrary Arguments
Are like Varags in Java; Indicated by an Asterisk - *
Try-with-resources
In “try” block declaration. Can have multiple resources. Resources must implement Auto-Closeable. They are closed in the opposite order from how they were declared. The compiler generates a “finally” block to close these.
Protected TypeScript class
Accessible from self and inheriting classes.
Dictionaries and Dictionary Keys
Declared as key:value pairs as in { uniquekey: value, otheruniquekey: value }.
Keys are immutable.
Keys do not have to all be of the same type.
Executor Service
Uses a type of thread pool. Implementation determines the number of threads and what to do when there are more jobs than threads. Must call shutdown() or shutdownNow() when finished with it.
TreeSet
Unique (no duplicates); Ordered. Must pass in a Comparator to the constructor to determine the sorting order, or <T> must implement Comparable.
Generation Functions
Use “yield” keyword. “yield” returns program flow to the calling code (jumps out of loops). Use instead of “return” which terminates the loop.
Default values in method signatures.
Must be declared last!
Exception Handling
Try/except/else/finally. Except is declared as:
except Exception e {}
And “else” only fires if nothing goes wrong. “Finally” code is always executed.
Slicing Syntax
mycollection[<start>:<stop>:<step>]
where start, stop and step are numbers.
Function Annotations Syntax
def my_func( arg1: type, optional_arg2: type = default_value) -> return_type { #code here }
Default Dictionary
Mapping that calls a factory function to supply missing values.
Counter
Mapping for counting hashable objects.
Chain Map
Fold multiple mapping objects to one view.
Deque
Double-Ended Queue – add to and remove from front and end of queue in constant time.
Named Tuple
Access to elements through field names.
Falsy/Truthy
Numbers equaling 0 are falsy. Empty containers, string, and byte objects are falsy (otherwise truthy). None is falsy. All other objects are truthy.
Ox, Oo, Ob
Hexadecimal, Octal, Binary constants.
Immutable Objects (member variables)
Can have mutable member variables.
CopyOnWriteArrayList
Use when elements will be often read, rarely written. Immutable.
Steps for writing serialized object to file.
1. Open FileOutputStream (connection stream).
2. Open ObjectOutputStream (chain stream).
3. Write the objects.
4. Close ObjectOutputStream.
Optional
Must check for empty with isPresent().
Java RMI
Remote Method Invocation.
Two parts:
1. STUB: client helper.
2. SKELETON: service helper.
Null equivalent
None is a singleton object used to identify null-like values. Functions and methods with no return value return None implicitly.
Conditional
Syntax: a if condition else b
Multi-Line Strings
“””Use
triple
Quotes”””
List syntax
[2,3,4] – mutable
Tuple syntax
(“foo”,3, 4.23) - immutable
Range syntax
range(start, stop, step) -
for example, range(0,9,2)
Checked Exceptions versus Runtime Exceptions
Checked – The compiler cares about. Runtime – caused by logic bugs in code, and are not required to be caught or declared.
“Ducking” an Exception
Declare Exception in method signature as “throws.”
Channels
Client and server apps communicate.
Client opens SocketChannel, server runs ServerSocketChannel and binds it to a port. Client connects to the server app. Then server creates a SocketChannel for each client it needs to converse with.
Multi-Threading runs in…
A separate call stack per thread.
Atomic
Means cannot be interrupted; (no context switching). The JVM must guarantee that the value is always up-to-date.
Synchronized
Can apply to methods or code blocks.
Use with “synchronized” keyword.
Use same object to synchronize on.
Prevents multiple threads from accessing the block at the same time. (Can slow performance).
Stateless Lambdas
Do not rely on values outside of their scope. Cannot read fields or call methods from class they’re in. They can read constant static fields or call static methods.
Functional Interfaces
Contain only one abstract method.
Apply function to stream
stream.map()
Filter stream
stream.filter()
Collect to List
stream.collect(Collectors.toList())
Collect to Map
stream.collect(Collectors.toMap())
Sum of Integers
int mySum = myIntStream.sum();
Declare Stream
Stream<String> myStream = Stream.of(arrayOfString);
Tree Map
Sorted according to natural ordering of keys, or by comparator provided at map creation time.
Streams
Are lazy (can’t traverse twice), parallel, and don’t alter original collection.
Synchronized List
List mySyncList = Collections .synchronizedList( new List<String>())
Package Private (no explicit modifier)
Visible to all classes in package.
Callable
Is a parameterized type that returns a value and can throw an Exception.
Observable
1. Establish Observer.
2. Establish Observable (subject).
3. Observable adds Observer with addObserver().
4. When data changes, call setChanged() and notifyObservers().
Operator Precedence
This will depend on the specific operators involved. Generally, follow common rules of arithmetic and logical operator precedence.
Set/List/Map
Set: Unique, unordered
List: Can have duplicates, ordered
Map: Key/Value pairs. No duplicate keys, can be ordered.
Method Reference
Use a double colon, as in ::
Terminal Operations on a Stream
Check if exists – anyMatch, allMatch, noneMatch
Find a thing – findAny, findFirst, max, min, reduce
Count – count
"Find a thing" operations return optional.
Default Methods
Have a body. Are inherited by subclasses.
Stream Map
Returns a stream with the results of applying a given function to each element.
Convenience Factory Methods
For collections. Immutable.
List.of(), Set.of(), Map.of() and Map.ofEntries()
Syntax for sort by MyVar descending
myList.sort( (one, two) -> two.getMyVar() .compareTo(one .getMyVar()));
Can call methods on an object only if…?
Methods belong to the reference class. For example, with Object obj = new Dog(); obj can call only Object methods, not Dog methods.
Hash code
If a.equals(b) then a.hashCode == b.hashCode – however, if a.hashCode == b.hashCode a does not necessarily equal b. If you override equals you must override hashcode.
O(?) order
O(1), O(log n), O(n), O(n log n), O(n^2)
A class that implements an interface must..?
Implement all of the methods of the interface except for default and static methods.
Syntax to make a constant?
final static Boolean MY_BOOL = true;
Must be assigned a value.
computeIfAbsent()
computeIfPresent()
Take an object key and a lambda; return a value (what you passed or what matches the lambda).
Non-primitive data types
Only String predefined. Can call methods on them. Can be null. Hold a reference to an object.
Instance Variables
Are part of a class but not a method. Live inside the object they belong to, as long as the object lives. Live on the heap.
Stream method,
Stream Pipeline,
Stream returns?
Stream method creates a stream from a collection. Results on terminal operation (lazy evaluation). Stream pipeline is the initial collection, the intermediate operations, and the terminal operations. Stream returns a new object and does not modify the original collection.
Comparator
/Comparable
Comparator is a method you can pass to sort() to determine sort order. Comparable is implemented to override compareTo().
List<E>
List<T>
List<R>
E – Element
T- Type
R – Return Type
Static methods
Static variables
Static methods can access static variables but not instance variables. Static variables have one object per class.
ArrayList holds?
Objects only. Primitives are auto-boxed.
Access Levels
Public – any code anywhere
Protected – same package and external subclasses
Default – same package
Private – self only
When to use list, set, map?
List – when order is important
Set – when uniqueness is important
Map – when you want to find by key.
Print a list
Calls toString() on each element of the list.
Serialize an object
Need ObjectOutputStream. Object must implement Serializable. Use “transient” keyword to skip non-serializable.
Record
Immutable, comes with a constructor, instance variables, access methods (get/set), equals, hashCode, and toString. Constructors can be overridden.
Varags
Use spread operator (an ellipses) …
Can only have one varag parameter in a method, and it must be the last parameter in the signature.
Serialization – skip a variable
Mark with “transient” keyword. Will restore as null (object type) or default value (primitive).
Swing component
Anything that lives on a GUI
paintComponent()
Cannot call this yourself; it is called by the GUI. It takes a Graphics object which you cannot instantiate yourself.
Don’t instantiate me, use…?
“Abstract” keyword. Method with no body, signature ends in a semicolon. All abstract methods must be implemented in first concrete subclass.
Override instance variables?
No, but they can be redefined.
Override inherited methods?
Yes, can be overridden.
Function composition
Combine multiple functions to one.
LinkedList benefits
Can add to and remove from front of list in constant time, and ordered.
Selection sort
Linear scan to find next smallest element and move it to the front, repeat. O(n^2) runtime.
Remote proxy
Local representative to remote object. Local representative forwards method calls to the remote object. The remote object lives on a different JVM heap.
filter()
Takes a predicate and returns a stream resulting from applying that predicate to each collection element.
Predicate
Unary (one argument) function that returns a Boolean.
TreeMap
O(log n) lookup and insertion. Keys are ordered. Must implement Comparable.
Merge Sort
O(n log n) runtime. Divide array in half, sort halves, merge together again. Repeat.
Quick Sort
Partition array into smaller/larger for left/right. Find an element on left that should be on right. Swap them. Repeat. O(n log n) average runtime.
Subclass with private constructor?
Can be inherited by its own or its parents’ inner classes.
Stack vs. Heap?
Stack – LIFO, local variables.
Heap – For objects and data structures that require a longer lifespan.
Dynamic Proxy
Proxy class created at runtime.
Abstract class
Can have abstract and regular methods. Abstract methods can only live on an Abstract class.
Local variables
Are on a method and live on the stack as long as the method is on the stack. For object references, only the reference variable itself lives on the stack.
HashMap
O(1) lookup and insertion. Not ordered.
Virtual Proxy
Representative to an expensive object, defers creation of the object until available/needed, is a surrogate for the object, delegates requests to real object.
Delegate
Assign a method to a variable.
Binary Search
Depends on a sorted array. Compare midpoint, if smaller look left, if larger look right. O(log n)
reduce()
Combine operation. Single result from a sequence of elements. Three parts: Identity, Accumulator, Combiner.
Separation of concerns
As little overlap of classes as possible.
Visitor pattern
Add functionality to a class hierarchy after the hierarchy has been defined.
Synchronization
One thread at a time to complete a task entirely.
O(log n) when…?
Number of elements halved each time.
Shell Sort
Variation on Insertion Sort. Divide list into gap-sized parts, sort sub-list with Insertion Sort, repeat reducing gap size until gap is 1 and array is sorted.
Array contravariance
Not supported.
Array contravariance
Not supported.
Array contravariance
Not supported.
Iterator Pattern
Access elements of a collection sequentially without exposing the underlying representation.
Strategy Pattern
Algorithm varies independently from client. Family of algorithms encapsulated and interchangeable. Multiple algorithms with implementation at runtime.
Proxy Pattern
Surrogate for an object, controls access to the object.
Extend Interface
New interface, with the same properties as the original plus new typed objects.
Powers of 2 between 1 and n
Math.pow(base, exponent)
Factory Pattern
Define interface for creating an object; subclasses decide what to implement. Defer instantiation to subclasses.
Abstract Factory
Interface for groups of related types without specifying concrete subclasses.
Runtime of 2 loops in a row.
O(n)
InvocationHandler
Proxy calls InvocationHandler’s invoke() method which makes decisions about what to do with the request.
isProxyClass()
Static method that returns true if the class is a Dynamic Proxy.
Protection Proxy
Controls access to an object based on access rights.
JVM
Java Virtual Machine; executes code that compiles down to Java ByteCode.
When to use Composite Pattern?
Compose objects to tree structures. When you have collections of objects with whole-part relationships and you want to treat them uniformly.
Command Pattern
Invoker and Receiver are decoupled. Command encapsulates the request as an object.
State Pattern
Abstract State class and inheriting concrete State classes. Context class holds the current state and delegates requests to the concrete state. Use as an alternative to conditionals.
Insertion Sort
Partition the array into sorted and unsorted. Pick from unsorted and place in sorted.
Functional Programming
Pure functions (no side effects) and immutable variables.
How to make shallow copies?
Ellipses (…) for spread operator, Object.assign, Array.from, and slice.
How to iterate over a HashMap?
Call values.iterator()
Why object reflection?
Manipulate runtime behaviors. Testing and debugging. Pass a method to another method without knowing in advance what that method will be.
Radix Sort
“Baskets” of objects grouped by digit. Runtime: O(kn) where n is the number of elements and k is the number of passes.
Securing Microservices
Service to Service Communications, API Gateway security, tracing and logging, Spring Security, etc.
Template Method
Series of steps, some steps abstract and implemented in subclasses.
Stream.reduce() Combiner
Function to combine partial results when parallelized or when types of arguments to the accumulator differ from types of the implementation.
Object composition
“Has-a” relationship of objects – allows objects to be reused in different contexts. What objects DO.
Define a balanced binary tree.
Left and right subtree of any node differ by not more than one. More computationally efficient than unbalanced trees.
Meta Command Pattern
Macro for grouping commands such that multiple occur at once.
Decorator Pattern
Wrap a concrete class with new functionality. Alternative to subclassing.
Iterables
Implement Iterator interface.
TypeScript is…?
A typed superscript of JavaScript
Stream.reduce() accumulator
Takes the previous partial result and the next element.
Tree runtime
O(Branches^depth) - for a binary tree that’s O(2^n)
TypeScript all Optional in class
Use “Partial”
Rest parameters
Multiple arguments passed in. Use spread operator (an ellipses …)
AbstractList
Extended by ArrayList and LinkedList
Stream.reduce() identity
Initial value or default.
What is a hook?
A concrete method with an empty body that can be implemented in subclasses but doesn’t have to be.
Red/Black Tree
Self-balancing. Based on a binary search tree but contains an extra bit for color.
Hollywood Principle
“Don’t call us, we’ll call you!”
Java implement vs extend.
Implement an interface, extend an abstract class. Can do both in a method, but “extends” keyword comes first. Can implement multiple but extend only one.
Vector
Synchronized ArrayList
4 pillars of OOP
Encapsulation
Inheritance
Abstraction
Polymorphism
Overload vs Override
Overload – method with the same name but a different signature.
Override – method with the same name and signature, in a subclass, that is called instead.
Final/Finally/Finalize
Final – immutable
Finally – end of try/catch block
Finalize – garbage collection
Callbacks
Functions passed to other functions as parameters.
Examples of higher order functions
Filter, Map, Reduce.
Null coalescing
Use double question mark (??) – if what is on the left is null, what is on the right of this symbol is used.
Optional Chaining
Use single question mark (?) to check for empty elements.
A higher order function is…?
A method that takes another method as a parameter, returns a method, or both.
Define IFFE
Immediately Invoked Function.
Three states of promises
Pending
Fulfilled
Rejected
Dependency Inversion Principle
“Depend on abstract classes.”
React is…?
A component-based library of JavaScript.
JSX is…?
Syntactic sugar of React. A way of writing HTML+JavaScript that compiles down to vanilla JS using Babel.
Façade Pattern
Define a higher-level interface that stands in front of a system of interfaces and makes them easier to interact with.
Law of Demeter
“Talk only to your friends.” – Reduces dependencies. Disadvantage: Can lead to too many wrappers.
Adapter Pattern
Interface that stands between two interfaces, wrapping the functionality of one to make it compatible with the other.
Class Adapter
Not possible in Java as it requires multiple inheritance.
Observer Pattern
Publish/Subscribe. When object changes state, dependents notified and updated.
Amortized Analysis
Average case.
Memoization
Optimize exponential time recursive functions.
Bubble Sort
Compare pairs of elements sequentially and swap them if the one on the right is smaller. Smaller numbers “bubble” up to the top. O(n2) runtime.
Lambda
Parameters -> Expression
Singleton Pattern
One object of a type in an application. Use getInstance synchronized or an enum.
Override method or property
“Virtual” keyword on base class, “override” to member of same name in derived class.
Queue<T>
FIFO. Enqueue to end; Dequeue at front. Implements IEnumerable.
Init
Immutable. Assign value only during object construction. Force initial non-null value with “required” keyword.
Access Modifiers: Public, private, protected
Public – any assembly can access.
Private – only same class or struct.
Protected – Self or derived.
Access Modifiers: Internal, protected internal, private protected, file
Internal – this assembly.
Protected internal – this assembly or derived assembly.
Private protected - containing class or types derived from the containing class within the current assembly.
File: same file.
Record
Like Lombok in Java. Creates constructors. Record class – immutable positional properties. Read only record struct – same as above. Record struct – mutable.
Create a custom exception
Extend Exception base class.
Stack<T>
LIFO. Push to top, pop from top. Implements IEnumerable.
Multiple inheritance
Not supported.
Subclass access base class
Use “base” keyword.
Subclass overrides method in base class
The more specific version is always used. Even if the base class is calling the overridden method.
Equality
Class – equal if same object in memory.
Struct – equal if same type and value.
Record – also equal if same type and value
CLR vs. CIL
CLR – Common Language Runtime. Executes code that is compiled into CIL – Common Intermediate Language.
Class in multiple files
Use “partial” keyword.
LinkedList<T>
Every node is type LinkedListNode<T> - If empty, first and last node are null. Can store duplicates of same type.
Three constructors for LinkedList
LinkedList() – empty instance.
LinkedList(IEnumerable) – contains elements from specified IEnumerable.
LinkedList(SerializationInfo, Stream Context) – serializable.
XAML stands for?
Extensible Application Markup Language. Design UIs. XML-based.
WPF stands for?
Windows Presentation Foundation. Desktop application UI.
Constructor order
Static constructor called first, before instance created!
Classes vs. Structs
Classes – support inheritance, are reference types, can be null, memory overhead.
Structs – no inheritance, value types, passed by value, cannot be null by default (unless Nullable), no memory overhead (unless boxed).
Default value of uninitialized integer
0 (zero)
Default value of uninitialized Boolean
false
Can you store mixed data types in an array?
Yes, if the array is of type Object.
Async functions vs. Thread.sleep()
Async – method will execute up to first await and then return program flow to the caller, freeing up a thread. The function called by await then executes asynchronously.
Thread.sleep() – pauses current thread for specified amount of time.
Read a line and convert to integer.
Use: int n = convert.toInt32(Console.readline());
Three types of dependency injection
Method, property, constructor.
Call another constructor with…?
Use keyword “this”.
Covariance vs. Contravariance
Covariant – methods that return more derived types.
Contravariant – methods that accept parameters which have less derived types.
Methods to remove elements of a LinkedList
Clear() – remove all nodes.
Remove(LinkedListNode) – remove specified.
Remove(T) – remove first occurrence of T.
RemoveFirst() – remove from start.
RemoveLast() – remove from end.
Check availability of elements with…?
Contains(T) – is given value present?
LinkedList methods to add nodes?
AddAfter() – add after existing node.
AddBefore() – add before existing node.
AddFirst() – add to start of list.
AddLast() – add to end of list.
Invariance
Generic classes are invariant by default. No relationship between derived and base types.
IEnumerable
Get enumerator to cycle through values. No add method; covariant compatibility.
Checked array covariance
Not supported. Can write a non-derived type to an index in an array and it will be a runtime, not a compiler, error.
Nullable annotations
Non-nullable: string! myStr = “value”;
Nullable: string? myStr = null;
Oblivious: no annotation, default behavior.
Nullable types
Value types can be nullable if they append the question mark suffix (?). Reference types can hold null values by default.
Extension methods
Methods that extend a class or interface. Extends behavior of a type.
Records
Class (reference) or Struct (value) types. Can be immutable, not required.
Local Functions
Nest function in method or other local function. Layer of encapsulation.
Pattern matching catchall
(_,_) => false
LINQ stands for?
Language Integrated Query. Syntax for querying data structures.
Task based asynchronous programming model?
Code read synchronously but executes asynchronously. Using async/await.
Upper type bound
Use <: (left arrow colon)
For type or derived types.
Type to left must be subtype of right.
Lower type bound
Use >: (right arrow colon)
Equal to or super type of the bound. Left a supertype of right.
Merge two lists
Use triple colon as in lixtX:::listY
Givens
Automatic injections with “given”/“using” keywords. Allows an instance to be inserted where “using” clause present. Cannot have 2 givens of the same type in scope (the compiler can’t pick one).
Sets
Unique – collections with no duplicates. Unordered.
Opaque types?
Easy way to define new types. Without pattern matching and without equals, hashCode, toString.
Invariant
Default behavior for type parameters. Maintain strict type relationships. Use with mutable.
Companion object
Class and object of same name in same file. Can access private fields and methods without restriction. Compiler considers them one object.
Mixins
Traits and implementations.
@switch annotation
Table switch – value as index.
Lookup switch – compiler sorts. When getting case, uses binary search. Values of cases must be literals for @switch
Cons shell
Head of list. Use :: (double colon).
Available in Java but not in Scala
Static members, checked exceptions.
Union/Intersection/Diff types
Union – all of both.
Intersection – only items in common.
Diff – Items that are in left but not in right.
Fold left
Takes a seed; return type same as seed. Can use to find length of list(String).
Reduce left
Does not take a seed. An example:
list(8,6,22,2).reduceLeft(_max_)
Will return 22.
Tail recursion
If the last call in a recursive function is the recursive call, it can avoid adding extra elements to the stack frame.
Case class
New not required. Automatic: toString, hashCode, equals, properties, and extractors.
Inner classes accessibility
Accessible from outside by object of same class type.
Abstract vs. concrete field in trait
No override needed: var door
Must override or declare class abstract: val door
Exclude class syntax on import
Use =>_ (equals right arrow underscore) in import statement.
Create a stream
Use #:: (pound colon colon)
Variance
+ and -
Defines inheritance of parameterized types. Mutable invariant, immutable covariant, inputs contravariant and outputs covariant.
What is excluded from wildcard import?
Givens!
NotGiven succeeds when…?
NotGiven[Q] succeeds when implicit search for Q fails.
Export
Expose a method inside another class or object as part of another. Cannot expose a constructor. Can exclude some methods from export.
Contravariance
Use with immutable. If S extends T, then Class[T] extends Class[S]
Covariant Type
Use with immutable. If S extends T then Class[S] extends Class[T]
Call-by-name syntax
Delay evaluation to usage (lazy).
foo (s:=> String)
Traits
Define a type. Use with “extends”.
When methods of 2 inherited traits are identical, then…?
Override or call Super.
Illegal trait inheritance
When superclass B does not derive from required superclass A.
How to extend from trait with implementation to Java class?
Wrap in Scala class.
Implicit conversions
Givens.
Variance and FunctionN traits
FunctionN traits have contravariant parameters and covariant results.
When abstract?
If there is no equals (=) assignment. Methods with “def” and functions with “val” are abstract.
Follow Java bean specification
@BeanProperty will create getters and setters. Must use “var” for this.
Generics
Classes and traits that take type parameters.
ADT stands for…?
Algebraic Data Types
Equivalent of java.util.list?
Scala.collection.mutable.Buffer
For Java callers of Scala methods, what for exceptions?
Annotate with @throws
Parameterized types?
Types generated by generic classes and traits.
Collections defaults?
Immutable. Seq, Set, Map – basic types.
Get method return value?
Option[T] = None or
Option[T] = Some(myVal)
Inheritance syntax
Use:
class ClassA extends ClassB with TraitA with TraitB
Multiple inheritance?
Not supported but you can extend from multiple traits like implementing multiple interfaces in Java.
Value classes
Like boxing. Extend AnyVal. 1 parameter. No inner classes. Variables within methods only. Can’t be extended.
When to use += (plus equals) on a collection?
When you want a mutable collection mutated.
Statement vs. Expression?
Statement: execute code, no return.
Expression: return a value.
Closure
A function with a return value dependent on the value of a variable outside that function.
What are val, var, lazy?
Use “val” for read-only, mutable.
Use “var” for mutable.
Use “lazy” for evaluation when accessed.
What is “Object”?
Class with one instance, (singleton) – static.
What is “Trait”?
Like an interface in Java.
Unit type
Like void in Java.
Mark a variable private?
Use underscore at beginning. Example: _myvar
Properties and Setters
A property (marked @property) can have a setter (marked @propertyname.setter)
Class inheritance syntax?
Use:
class ChildClass(ParentClass):
When is calling super() from __init__ necessary?
When overriding __init__ in a derived class.
What is “pass”?
A way to create a new empty class.
What does vars() do?
Give it an object and it returns all mutable attributes and their values.
Multiple inheritance?
Multiple inheritance IS SUPPORTED in Python.
Syntax for new dictionary and add a value.
bar = {}
bar["mykey"] = myval
Why use dataclasses annotation?
Using @dataclass decorator on a class will cause automatic creation of __init__ and instance variables. Can use keywords to control features.
What are some keywords for dataclass?
Examples taking a boolean: init (default init), repr (as string), eq (equals), order (comparisons), frozen (mutability)
What is an __init__.py file?
Executed when a package is imported and contains import statements for package member classes.
What does a.replace() return?
A new string, and it does not modify the original ("a").
What does a.count("foo") return?
The number of occurrences of "foo" as an integer.
Example input validation methods?
Include isnumeric(), isalpha(), isalnum()
In regex, what does the span() method do?
Returns the exact position in a string where the match occurred.
In regex, what does the prefix “r” do?
Treats contents as a raw string.
In regex, what does re.sub() do?
Performs find and replace operation.
What are f-strings?
Formatted string literals.
String compression syntax?
import zlib then use:
zlib.compress( data.encode() )
Operator symbol for exponent?
Use ** (double asterisk).
What does fabs(n) do?
Return absolute value of n as a float.
What does fmod(x,y) do?
Return remainder from x/y as a float.
What does round() do?
Round floats to nearest whole number.
When to use decimal instead of float?
When precision is important.
How to format date and time?
Use strftime() function.
Method to calculate change in value from one date and time to another?
Use timedelta method.
How to return a datetime object that isn’t now?
Use datetime.datetime() and pass it your date and time integers (year, month, day, hour, minute, second).
What is the walrus operator?
Allows you to assign a value to a variable within an expression. Use colon equals (:=)
What does readlines() return?
A list, not a string.
How to make a method static?
Use the @staticmethod annotation.
What does the pickle module do?
Allows you to serialize an object and save it.
What does urllib do?
Module allowing you to download web pages and interact with web servers.
What is Django?
Django is a Python framework that makes it easier to create web sites using Python
What module to use for unit tests?
Use unittest module.
Difference between sort and sorted?
Sorted does not modify the original list.
How to sort by a function?
Pass key = myfunc to sort().
Syntax for multiple argument lambda?
a = lambda x,y,z: x+y+z
In multithreading what does join() do?
Waits until thread finishes before exiting program.
What does using a lock accomplish?
Avoids race conditions.
What are race conditions?
Two or more threads using the same method at the same time resulting in unexpected consequences.
Module to use for profiling?
Use cProfile module.
What is profiling?
Breakdown in time spent on each section of code. Useful for optimization.
Syntax for multiple assignment?
Use: a,b,c = 1,2,3