mirror of
https://github.com/m-lamonaca/dev-notes.git
synced 2025-04-11 05:16:40 +00:00
merge main into NET-6
This commit is contained in:
commit
b33336d7c1
21 changed files with 299 additions and 178 deletions
Database
DotNet
HTML
Java
JavaScript
Node.js/Standard Packages
PHP
Rust
iOS
|
@ -328,7 +328,7 @@ db.getCollectionNames().forEach(function(collection) {
|
|||
print("Indexes for " + collection + ":");
|
||||
printjson(indexes);
|
||||
});
|
||||
db.<collection>.getIndexes() # view collenction's index
|
||||
db.<collection>.getIndexes() # view collection's index
|
||||
|
||||
db.<collection>.dropIndexes() # drop all indexes
|
||||
db.<collection>.dropIndex( { "index-name": 1 } ) # drop a specific index
|
||||
|
|
|
@ -257,6 +257,80 @@ Project
|
|||
}
|
||||
```
|
||||
|
||||
## State Management
|
||||
|
||||
### Blazor WASM
|
||||
|
||||
```cs
|
||||
// setup state singleton
|
||||
builder.Services.AddSingleton<StateContainer>();
|
||||
```
|
||||
|
||||
```cs
|
||||
// StateContainer singleton
|
||||
using System;
|
||||
|
||||
public class StateContainer
|
||||
{
|
||||
private int _counter;
|
||||
|
||||
public string Property
|
||||
{
|
||||
get => _counter;
|
||||
set
|
||||
{
|
||||
_counter = value;
|
||||
NotifyStateChanged(); // will trigger StateHasChanged(), causing a render
|
||||
}
|
||||
}
|
||||
|
||||
public event Action OnChange;
|
||||
|
||||
private void NotifyStateChanged() => OnChange?.Invoke();
|
||||
}
|
||||
```
|
||||
|
||||
```cs
|
||||
// component that changes the state
|
||||
@inject StateContainer State
|
||||
|
||||
// Delegate event handlers automatically trigger a UI render
|
||||
<button @onClick="@HandleClick">
|
||||
Change State
|
||||
</button>
|
||||
|
||||
@code {
|
||||
private void HandleClick()
|
||||
{
|
||||
State.Property += 1; // update state
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```cs
|
||||
// component that should be update on state change
|
||||
@implements IDisposable
|
||||
@inject StateContainer State
|
||||
|
||||
<p>Property: <b>@State.Property</b></p>
|
||||
|
||||
@code {
|
||||
|
||||
// StateHasChanged notifies the component that its state has changed.
|
||||
// When applicable, calling StateHasChanged causes the component to be rerendered.
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
State.OnChange += StateHasChanged;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
State.OnChange -= StateHasChanged;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Javascript/.NET Interop
|
||||
|
||||
[Call Javascript from .NET](https://docs.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet)
|
||||
|
|
127
DotNet/C#/C#.md
127
DotNet/C#/C#.md
|
@ -33,7 +33,7 @@ to native code later.
|
|||
```cs
|
||||
// comment
|
||||
/* multi line comment */
|
||||
// / single line xml comment (docstring)
|
||||
/// single line xml comment (docstring)
|
||||
/** multi line xml string (docsting) */
|
||||
```
|
||||
|
||||
|
@ -1219,16 +1219,6 @@ type OutMethod(type param1, out type param2){}
|
|||
OutMethod(arg1, out var arg2); // create out variable on the fly
|
||||
```
|
||||
|
||||
<!-- TODO: ### References to variables
|
||||
|
||||
**Constraints**:
|
||||
|
||||
```cs
|
||||
string _string = null; // init string object
|
||||
ref string referenceToString = ref _string; // referenceToString points to _string, it's a reference
|
||||
referenceToString = "value"; // data goes through referenceToString and into _string
|
||||
``` -->
|
||||
|
||||
### Returning Multiple Values with Tuples
|
||||
|
||||
**Must** be C# 7+.
|
||||
|
@ -2101,13 +2091,13 @@ Any method from any accessible class or struct that matches the delegate type ca
|
|||
This makes it possible to programmatically change method calls, and also plug new code into existing classes.
|
||||
|
||||
```cs
|
||||
// dedlegate definition
|
||||
public delegate Type DelegateName(Type param, ...); // can take any method with specidied type params and return type
|
||||
public delegate bool Predicate<in T>(T obj);
|
||||
// delegate definition
|
||||
public delegate Type Delegate(Type param, ...); // can take any method with specidied type params and return type
|
||||
public delegate Type Delegate<T>(T param); // generic delegate
|
||||
|
||||
// delegate creation
|
||||
var delegate = new Delegate<Type>(method); // explicit creation, useful when compiler cannot infer delegate type
|
||||
Delegate<Type> delegate = method; // implicit creation
|
||||
var delegate = new Delegate<Type>(Method); // explicit creation, useful when compiler cannot infer delegate type
|
||||
Delegate<Type> delegate = Method; // implicit creation
|
||||
```
|
||||
|
||||
### [Multicast Delegates](https://docs.microsoft.com/en-us/dotnet/api/system.multicastdelegate)
|
||||
|
@ -2115,9 +2105,9 @@ Delegate<Type> delegate = method; // implicit creation
|
|||
**Multicast Delegares** are delegates that can have more than one element in their invocation list.
|
||||
|
||||
```cs
|
||||
Delegate<Type> multicastDelegate = method1 + method2 + ...; // multicast delegate creation
|
||||
multicastDelegate += method; // add method to delegate
|
||||
multicastDelegate -= method; // remove method from delegate
|
||||
Delegate<Type> multicastDelegate = Method1 + Method2 + ...; // multicast delegate creation
|
||||
multicastDelegate += Method; // add method to delegate
|
||||
multicastDelegate -= Method; // remove method from delegate
|
||||
```
|
||||
|
||||
**NOTE**: Delegate removal behaves in a potentially surprising way if the delegate removed refers to multiple methods.
|
||||
|
@ -2129,7 +2119,7 @@ Invoking a delegate with a single target method works as though the code had cal
|
|||
Invoking a multicast delegate is just like calling each of its target methods in turn.
|
||||
|
||||
```cs
|
||||
Delegate<Type> delegate = method;
|
||||
Delegate<Type> delegate = Method;
|
||||
|
||||
delegate(args); // use delegat as standard method
|
||||
delegate.DynamicInvoke(argsArray); // Dynamically invokes the method represented by the current delegate.
|
||||
|
@ -2181,12 +2171,6 @@ var f = int (x) => x; // explicitly specifying the return type of an implicit i
|
|||
var f = static void (_) => Console.Write("Help");
|
||||
```
|
||||
|
||||
### Captured Variables
|
||||
|
||||
<!-- TODO: page 396 of Ian Griffiths - Programming C%23 8.0_Build Cloud, Web, and Desktop Applications -->
|
||||
|
||||
<!-- todo: static anonymous functions -->
|
||||
|
||||
---
|
||||
|
||||
## [Events](https://www.tutorialsteacher.com/csharp/csharp-event)
|
||||
|
@ -2197,10 +2181,11 @@ The class who raises events is called _Publisher_, and the class who receives th
|
|||
Typically, a publisher raises an event when some action occurred. The subscribers, who are interested in getting a notification when an action occurred, should register with an event and handle it.
|
||||
|
||||
```cs
|
||||
public delegate void EventDelegate(object sender, CustomEventArgs args); // called on event trigger
|
||||
|
||||
public class Publisher
|
||||
{
|
||||
|
||||
public event Delegate<Type> Event;
|
||||
public event EventDelegate Event;
|
||||
|
||||
// A derived class should always call the On<EventName> method of the base class to ensure that registered delegates receive the event.
|
||||
public virtual void OnEvent(Type param)
|
||||
|
@ -2215,19 +2200,15 @@ public class Publisher
|
|||
```cs
|
||||
public class Subscriber
|
||||
{
|
||||
|
||||
Publisher publisher = new Publisher();
|
||||
|
||||
public Subscriber()
|
||||
{
|
||||
publisher.Event += eh_Event; // register handler (+= syntax)
|
||||
publisher.OnEvent += Handler; // register handler (+= syntax)
|
||||
}
|
||||
|
||||
// event handler, handles the event because it matches the signature of the Event delegate.
|
||||
public Delegate<Type> eh_Event()
|
||||
{
|
||||
// act
|
||||
}
|
||||
// event handler, matches the signature of the Event delegate.
|
||||
public Type Handler() { /* act */ }
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -2254,22 +2235,17 @@ public class Subsciber
|
|||
|
||||
public Subscriber()
|
||||
{
|
||||
publisher.Event += eh_Event; // register handler (+= syntax)
|
||||
publisher.OnEvent += Handler; // register handler (+= syntax)
|
||||
}
|
||||
|
||||
public void eh_Event(object sender, EventArgs e)
|
||||
{
|
||||
// act
|
||||
}
|
||||
public Type Handler(object sender, EventArgs e) { /* act */ }
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Event Args
|
||||
|
||||
```cs
|
||||
public class CustomEventArgs : EventArgs {
|
||||
// custom attributes
|
||||
}
|
||||
public class CustomEventArgs : EventArgs { }
|
||||
|
||||
public class Publisher
|
||||
{
|
||||
|
@ -2287,13 +2263,10 @@ public class Subsciber
|
|||
|
||||
public Subscriber()
|
||||
{
|
||||
publisher.Event += eh_Event; // register handler (+= syntax)
|
||||
publisher.OnEvent += Handler; // register handler (+= syntax)
|
||||
}
|
||||
|
||||
public void eh_Event(object sender, CustomEventArgs e)
|
||||
{
|
||||
// act
|
||||
}
|
||||
public Type Handler(object sender, CustomEventArgs e) { /* act */ }
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -2900,6 +2873,53 @@ n << m
|
|||
n * 2^m
|
||||
```
|
||||
|
||||
## Unsafe Code & Pointers
|
||||
|
||||
The `unsafe` keyword denotes an *unsafe context*, which is required for any operation involving pointers.
|
||||
|
||||
In an unsafe context, several constructs are available for operating on pointers:
|
||||
|
||||
- The `*` operator may be used to perform pointer indirection ([Pointer indirection][ptr_indirection]).
|
||||
- The `->` operator may be used to access a member of a struct through a pointer ([Pointer member access][ptr_member_acces]).
|
||||
- The `[]` operator may be used to index a pointer ([Pointer element access][ptr_elem_access]).
|
||||
- The `&` operator may be used to obtain the address of a variable ([The address-of operator][ptr_addr_of]).
|
||||
- The `++` and `--` operators may be used to increment and decrement pointers ([Pointer increment and decrement][ptr_incr_decr]).
|
||||
- The `+` and `-` operators may be used to perform pointer arithmetic ([Pointer arithmetic][ptr_math]).
|
||||
- The `==`, `!=`, `<`, `>`, `<=`, and `>=` operators may be used to compare pointers ([Pointer comparison][ptr_comparison]).
|
||||
- The `stackalloc` operator may be used to allocate memory from the call stack ([Stack allocation][stack_alloc]).
|
||||
|
||||
The `fixed` statement prevents the garbage collector from relocating a movable variable. It's only permitted in an unsafe context.
|
||||
It's also possible to use the fixed keyword to create fixed size buffers.
|
||||
|
||||
The `fixed` statement sets a pointer to a managed variable and "pins" that variable during the execution of the statement.
|
||||
Pointers to movable managed variables are useful only in a fixed context. Without a fixed context, garbage collection could relocate the variables unpredictably.
|
||||
The C# compiler only allows to assign a pointer to a managed variable in a fixed statement.
|
||||
|
||||
```cs
|
||||
unsafe Type UnsafeMethod() { /* unasfe context */ }
|
||||
// or
|
||||
unsafe
|
||||
{
|
||||
// Using fixed allows the address of pt members to be taken,
|
||||
// and "pins" pt so that it is not relocated.
|
||||
Point pt = new Point();
|
||||
fixed (int* p = &pt.x)
|
||||
{
|
||||
*p = 1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[ptr_indirection]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-indirection)
|
||||
[ptr_member_acces]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-member-access)
|
||||
[ptr_elem_access]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-element-access)
|
||||
[ptr_addr_of]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#the-address-of-operator)
|
||||
[ptr_incr_decr]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-increment-and-decrement)
|
||||
[ptr_math]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-arithmetic)
|
||||
[ptr_comparison]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-comparison)
|
||||
[stack_alloc]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#stack-allocation)
|
||||
[fixed_buffers]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#fixed-size-buffers)
|
||||
|
||||
### Native Memory
|
||||
|
||||
```cs
|
||||
|
@ -2912,3 +2932,14 @@ unsafe
|
|||
NativeMemory.Free(buffer);
|
||||
}
|
||||
```
|
||||
|
||||
### DllImport & Extern
|
||||
|
||||
The `extern` modifier is used to declare a method that is implemented externally.
|
||||
A common use of the extern modifier is with the `DllImport` attribute when using Interop services to call into *unmanaged* code.
|
||||
In this case, the method must also be declared as `static`.
|
||||
|
||||
```cs
|
||||
[DllImport("avifil32.dll")]
|
||||
private static extern void AVIFileInit();
|
||||
```
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# Reactive Extensions (Rx)
|
||||
|
||||
The **Reactive Extensions** for .NET, or **Rx**, are designed for working with asynchro‐nous and event-based sources of information.
|
||||
The **Reactive Extensions** for .NET, or **Rx**, are designed for working with asynchronous and event-based sources of information.
|
||||
Rx provides services that help orchestrate and synchronize the way code reacts to data from these kinds of sources.
|
||||
|
||||
Rx’s fundamental abstraction, `IObservable<T>`, represents a sequence of items, and its operators are defined as extension methods for this interface.
|
||||
|
@ -14,8 +14,8 @@ Because Rx implements standard LINQ operators, it's possible to write queries ag
|
|||
|
||||
## Foundamental Interfaces
|
||||
|
||||
The two most important types in Rx are the `IObservable<T>` and `IObserver<T>` interfaces. They are important enough to be in the System namespace.
|
||||
The other parts of Rx are in the `System.Reactive` NuGet package.
|
||||
The two most important types in Rx are the `IObservable<T>` and `IObserver<T>` interfaces.
|
||||
They are important enough to be in the System namespace. The other parts of Rx are in the `System.Reactive` NuGet package.
|
||||
|
||||
```cs
|
||||
public interface IObservable<out T>
|
||||
|
@ -31,7 +31,8 @@ public interface IObserver<in T>
|
|||
}
|
||||
```
|
||||
|
||||
The fundamental abstraction in Rx, `IObservable<T>`, is implemented by *event sources*. Instead of using the `event` keyword, it models events as a *sequence of items*. An `IObservable<T>` provides items to subscribers as and when it’s ready to.
|
||||
The fundamental abstraction in Rx, `IObservable<T>`, is implemented by *event sources*. Instead of using the `event` keyword, it models events as a *sequence of items*.
|
||||
An `IObservable<T>` provides items to subscribers as and when it’s ready to do so.
|
||||
|
||||
It's possible to subscribe to a source by passing an implementation of `IObserver<T>` to the `Subscribe` method.
|
||||
The source will invoke `OnNext` when it wants to report events, and it can call `OnCompleted` to indicate that there will be no further activity.
|
||||
|
|
|
@ -85,7 +85,7 @@ The body contains the actual content of the page. Everything that is contained i
|
|||
## JavaScript
|
||||
|
||||
XHTML and older: `<script src="js/scripts.js" type="text/javascript"></script>`
|
||||
HTML5: `<script src="js/scripts.js"></script>` (HTML5 spect states that `type` attribute is redundant and shoul be omitted)
|
||||
HTML5: `<script src="js/scripts.js"></script>` (HTML5 spect states that `type` attribute is redundant and shoul be omitted)
|
||||
The `<script>` tag is used to define a client-side script (JavaScript).
|
||||
The `<script>` element either contains scripting statements, or it points to an external script file through the src attribute.
|
||||
|
||||
|
|
14
Java/Java.md
14
Java/Java.md
|
@ -55,7 +55,7 @@ System.out.print(output_1 + _ + output_n);
|
|||
[String.format() Examples](https://dzone.com/articles/java-string-format-examples)
|
||||
|
||||
```java
|
||||
System.out.printf("stringa %..", variable);
|
||||
System.out.printf("string %..", variable);
|
||||
System.out.println(String.format(format, args));
|
||||
```
|
||||
|
||||
|
@ -79,11 +79,11 @@ Scanner scanner = new Scanner(System.in); //Scanner obj init
|
|||
scanner.useDelimiter("delimitatore"); //delimiter setting
|
||||
scanner.close() //closing of Scanner, releases memory
|
||||
|
||||
int variabile_int_1 = scanner.nextInt(); //takes integer number
|
||||
int variable_int_1 = scanner.nextInt(); //takes integer number
|
||||
String string_1 = scanner.nextLine(); //takes line of text (\n ends line)
|
||||
String string_1 = scanner.next(); //takes text (spacec ends word)
|
||||
double variabile_double_1 = scanner.nextDouble(); //takes double decimal number
|
||||
boolean variabile_bool = scanner.netxBoolean(); //takes boolean value
|
||||
double variable_double_1 = scanner.nextDouble(); //takes double decimal number
|
||||
boolean variable_bool = scanner.netxBoolean(); //takes boolean value
|
||||
//(TRUE, FALSE, true, false, True, False)
|
||||
```
|
||||
|
||||
|
@ -137,8 +137,8 @@ Type variable = new WrapperClass(primitiveValue); //automatic unboxing
|
|||
WrapperClass.MIN_VALUE //constant holding min possible value of wrapper class
|
||||
WrapperClass.MAX_VALUE //constant holding man possible value of wrapper class
|
||||
|
||||
ClasseWrapper.parseClasseWrapper(stringa); //converte il valore di una stringa in uno della classe wrapper (metodo statico), eccezione NumberFOrmatException se l'operazione fallisce
|
||||
ClasseWrapper.toString(valore_tipo_primitivo); //converte il valore della classe wrapper in una string (metodo statico)
|
||||
WrapperClass.parseClasseWrapper(string); // converts the tring to the wrapper class, NumberFOrmatException on error
|
||||
WrapperClass.toString(primitive); // converts the wrapper class value to a string
|
||||
```
|
||||
|
||||
### String & Char
|
||||
|
@ -167,7 +167,7 @@ Escape Character | Character
|
|||
### String Concatenation
|
||||
|
||||
The value of the variable is appende to the string literal.
|
||||
`"text" + variabile`
|
||||
`"text" + variable`
|
||||
String are immutable. Concatenation creates a new string.
|
||||
|
||||
### String Conversion to Number
|
||||
|
|
|
@ -7,7 +7,7 @@ The document object is *globally available* in the browser. It allows to access
|
|||
|
||||
### Selecting Nodes from the DOM
|
||||
|
||||
`getElementById()` and `querySelector()` return a single element.
|
||||
`getElementById()` and `querySelector()` return a single element.
|
||||
`getElementsByClassName()`, `getElementsByTagName()`, and `querySelectorAll()` return a collection of elements.
|
||||
|
||||
```js
|
||||
|
@ -16,14 +16,14 @@ Javascript
|
|||
var node = document.getElementById('id');
|
||||
|
||||
// By Tag Name
|
||||
var node = document.getElementsByTagName('tag');
|
||||
var nodes = document.getElementsByTagName('tag');
|
||||
|
||||
// By Class Name
|
||||
var node = document.getElementsByClassName('class');
|
||||
var nodes = document.getElementsByClassName('class');
|
||||
|
||||
// By CSS Query
|
||||
var node = document.querySelector('css-selector');
|
||||
var node = document.querySelectorAll('css-selector');
|
||||
var nodes = document.querySelectorAll('css-selector');
|
||||
```
|
||||
|
||||
## Manupulating the DOM
|
||||
|
@ -119,7 +119,7 @@ document.createTextNode('text');
|
|||
domNode.appendChild(childToAppend); // insert childTaAppend after domNode
|
||||
|
||||
// insert node before domNode
|
||||
domNode.insertBEfore(childToInsert, domnode);
|
||||
domNode.insertBefore(childToInsert, domnode);
|
||||
domNode.parentNode.insertBefore(childToInsert, nodeAfterChild);
|
||||
|
||||
// remove a node
|
||||
|
|
|
@ -63,6 +63,9 @@ window.setInterval(callbackFunction, delayMilliseconds);
|
|||
//To stop an animation store the timer into a variable and clear it
|
||||
window.clearTimeout(timer);
|
||||
window.clearInterval(timer);
|
||||
|
||||
// execute a callback at each frame
|
||||
window.requestAnimationFrame(callbackFunction);
|
||||
```
|
||||
|
||||
### Element Position & dimensions
|
||||
|
|
|
@ -28,16 +28,15 @@
|
|||
*/
|
||||
```
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
| Elements | Case |
|
||||
| -------- | --------- |
|
||||
| variable | camelCase |
|
||||
|
||||
### Modern Mode
|
||||
|
||||
If located at the top of the script the whole script works the “modern” way (enables post-ES5 functionalities).
|
||||
`"use strict"`
|
||||
|
||||
```js
|
||||
"use strict"
|
||||
|
||||
// script contents
|
||||
```
|
||||
|
||||
### Pop-Up message
|
||||
|
||||
|
@ -328,8 +327,7 @@ if (condition) {
|
|||
|
||||
### Ternary Operator
|
||||
|
||||
`condition ? instruction1 : istruction2;`
|
||||
Ff TRUE execute instruction1, execute instruction2 otherwise.
|
||||
`condition ? <expr1> : <expr2>;`
|
||||
|
||||
### Switch Statement
|
||||
|
||||
|
@ -480,6 +478,7 @@ for(let key in dict) {
|
|||
// do something with "key" and "value" variables
|
||||
}
|
||||
|
||||
Object.keys(dict).forEach(key => { });
|
||||
```
|
||||
|
||||
## Functions
|
||||
|
|
|
@ -4,8 +4,10 @@
|
|||
npx degit sveltejs/template <project name>
|
||||
|
||||
# set project to use typescript
|
||||
npm install --save-dev @tsconfig/svelte typescript svelte-preprocess svelte-check
|
||||
node scripts/setupTypeScript.js
|
||||
|
||||
# or using vite
|
||||
npm init vite@latest
|
||||
```
|
||||
|
||||
## App Entrypoint
|
||||
|
|
|
@ -11,7 +11,7 @@ https.request(
|
|||
method: "GET", // POST, ...
|
||||
path: "/page/?param=value"
|
||||
},
|
||||
(response) => { // respnse is IncomingMessage
|
||||
(response) => { // response is IncomingMessage
|
||||
// do stuff
|
||||
}
|
||||
).end();
|
||||
|
|
|
@ -62,7 +62,7 @@ $stmt->execute();
|
|||
By default PDO converts all results into strings since it is a generic driver for multiple databases.
|
||||
Its possible to disable this behaviour setting `PDO::ATTR_STRINGIFY_FETCHES` and `PDO::ATTR_EMULATE_PREPARES` as `false`.
|
||||
|
||||
**NOTE**: `FETCH_OBJ` abd `FETCH_CLASS` return classes and don't have this bheaviour.
|
||||
**NOTE**: `FETCH_OBJ` abd `FETCH_CLASS` return classes and don't have this behaviour.
|
||||
|
||||
```php
|
||||
pdo->setAttribute()
|
||||
|
@ -82,7 +82,7 @@ $stmt = $pdo->prepare($sql);
|
|||
$stmt->execute([':marker' => value]);
|
||||
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$stmt->debugDumpParams(); # print the SQK query that has been sent to the database
|
||||
$stmt->debugDumpParams(); # print the SQL query that has been sent to the database
|
||||
```
|
||||
|
||||
## [SQLite3](https://www.php.net/manual/en/book.sqlite3.php)
|
||||
|
|
|
@ -15,7 +15,6 @@ class Foo
|
|||
## Dependency Injection Container
|
||||
|
||||
The **Dependecy Injection Container** (DIC) allow to archive all the dependencies in a single `Container` class. Some offer automatic resolution of the dependecies.
|
||||
Containers aid the developer in the handling of the dependecies: get/has/set.
|
||||
|
||||
## [PHP-DI](https://php-di.org/)
|
||||
|
||||
|
|
57
PHP/PHP.md
57
PHP/PHP.md
|
@ -15,7 +15,7 @@ declare(strict_types=1); # activates variable type checking on function argumen
|
|||
include "path\\file.php"; # import an external php file, E_WARNING if fails
|
||||
include_once "path\\file.php"; # imports only if not already loaded
|
||||
|
||||
require "path\\file.php"; # # import an external php file, E_COMPILE_ERROR if fails
|
||||
require "path\\file.php"; # import an external php file, E_COMPILE_ERROR if fails
|
||||
require_once "path\\file.php"; # imports only if not already loaded
|
||||
```
|
||||
|
||||
|
@ -34,7 +34,7 @@ return [
|
|||
```
|
||||
|
||||
```php
|
||||
$config = include "config.php"; // retireve config wnd store into variable
|
||||
$config = include "config.php"; // retireve config and store into variable
|
||||
```
|
||||
|
||||
## Namespace
|
||||
|
@ -136,12 +136,12 @@ $c = 7E-10; // 0.0000000007
|
|||
### Mathematical Operators
|
||||
|
||||
| Operator | Operation |
|
||||
|----------|----------------|
|
||||
| -------- | -------------- |
|
||||
| `-` | Subtraction |
|
||||
| `*` | Multiplication |
|
||||
| `/` | Division |
|
||||
| `%` | Modulo |
|
||||
| `**` | Exponentiatio |
|
||||
| `**` | Exponentiation |
|
||||
| `var++` | Post Increment |
|
||||
| `++var` | Pre Increment |
|
||||
| `var--` | Post Decrement |
|
||||
|
@ -164,7 +164,7 @@ A string is a sequrnce of ASCII characters. In PHP a string is an array of chara
|
|||
### String Concatenation
|
||||
|
||||
```php
|
||||
$string1 . $string2; method 1
|
||||
$string1 . $string2; # method 1
|
||||
$string1 .= $string2; # method 2
|
||||
```
|
||||
|
||||
|
@ -190,7 +190,7 @@ define ('CONSTANT_NAME', 'value')
|
|||
|
||||
### Magic Constants `__NAME__`
|
||||
|
||||
- `__FILE__`: sctipt path + scrit filename
|
||||
- `__FILE__`: script path + script filename
|
||||
- `__DIR__`: file directory
|
||||
- `__LINE__`: current line number
|
||||
- `__FUNCTION__`: the function name, or {closure} for anonymous functions.
|
||||
|
@ -261,7 +261,7 @@ list($array1 [, $array2, ...]) = $data; # Python-like tuple unpacking
|
|||
|
||||
### Associative Arrays
|
||||
|
||||
Associative arrays have a value as an index. Alternative names are *hash tables* or *dictionaries*.
|
||||
Associative arrays have a value as an index. Alternative names are _hash tables_ or _dictionaries_.
|
||||
|
||||
```php
|
||||
$italianDay = [
|
||||
|
@ -282,7 +282,7 @@ $italianDay["Mon"]; # evaluates to Lunedì
|
|||
### Conditional Opeartors
|
||||
|
||||
| Operator | Operation |
|
||||
|-------------|--------------------------|
|
||||
| ----------- | ------------------------ |
|
||||
| $a `==` $b | value equality |
|
||||
| $a `===` $b | value & type equality |
|
||||
| $a `!=` $b | value inequality |
|
||||
|
@ -299,13 +299,13 @@ With `==` a string evaluates to `0`.
|
|||
### Logical Operators
|
||||
|
||||
| Operator | Example | Result |
|
||||
|----------|-------------|------------------------------------------------------|
|
||||
| -------- | ----------- | ---------------------------------------------------- | --- | ------------------------------------ |
|
||||
| `and` | `$a and $b` | TRUE if both `$a` and `$b` are TRUE. |
|
||||
| `or` | `$a or $b` | TRUE if either `$a` or `$b` is TRUE. |
|
||||
| `xor` | `$a xor $b` | TRUE if either `$a` or `$b` is TRUE, but *not both*. |
|
||||
| `not` | `!$a` | TRUE if `$a` is *not* TRUE. |
|
||||
| `xor` | `$a xor $b` | TRUE if either `$a` or `$b` is TRUE, but _not both_. |
|
||||
| `not` | `!$a` | TRUE if `$a` is _not_ TRUE. |
|
||||
| `and` | `$a && $b` | TRUE if both `$a` and `$b` are TRUE. |
|
||||
| `or` | `$a || $b` | TRUE if either `$a` or `$b` is TRUE. |
|
||||
| `or` | `$a | | $b` | TRUE if either `$a` or `$b` is TRUE. |
|
||||
|
||||
### Ternary Operator
|
||||
|
||||
|
@ -334,7 +334,7 @@ if $a > $b
|
|||
if $a == $b
|
||||
return 0;
|
||||
if $a < $b
|
||||
return 0;
|
||||
return -1;
|
||||
```
|
||||
|
||||
### `If` - `Elseif` - `Else`
|
||||
|
@ -535,7 +535,7 @@ $foo = function (type $parameter) use ($average) {
|
|||
|
||||
### Union Types (PHP 8)
|
||||
|
||||
**Union types** are a collection of two or more types which indicate that *either* one of those *can be used*.
|
||||
**Union types** are a collection of two or more types which indicate that _either_ one of those _can be used_.
|
||||
|
||||
```php
|
||||
public function foo(Foo|Bar $input): int|float;
|
||||
|
@ -560,8 +560,8 @@ foo(
|
|||
|
||||
### Scope & Visibility
|
||||
|
||||
`public` methods and attrivutes are visible to anyone (*default*).
|
||||
`private` methods and attrivutes are visible only inside the class in which are declared.
|
||||
`public` methods and attributes are visible to anyone (_default_).
|
||||
`private` methods and attributes are visible only inside the class in which are declared.
|
||||
`protected` methods and attributes are visible only to child classes.
|
||||
|
||||
`final` classes cannot be extended.
|
||||
|
@ -595,15 +595,15 @@ class ClassName
|
|||
}
|
||||
}
|
||||
|
||||
$object = new ClassName; # case insensitive (CLASSNAME, CLassName, classname)
|
||||
$object->attrivute = value;
|
||||
$object = new ClassName; # case insensitive (CLASSNAME, ClassName, classname)
|
||||
$object->attribute = value;
|
||||
$object->func();
|
||||
$object::CONSTANT;
|
||||
|
||||
$var = $object; # copy by reference
|
||||
$var = clone $object # copy by value
|
||||
|
||||
$object instanceof ClassName // check typo of the object
|
||||
$object instanceof ClassName // check type of the object
|
||||
```
|
||||
|
||||
### Static classes, attributes & methods
|
||||
|
@ -698,10 +698,10 @@ class ClassName implements InterfaceName {
|
|||
|
||||
### Traits
|
||||
|
||||
`Traits` allows the riutilization of code inside different classes without links of inheritance.
|
||||
It can be used to mitigate the problem of *multiple inheritance*, which is absent in PHP.
|
||||
`Traits` allows the reutilization of code inside different classes without links of inheritance.
|
||||
It can be used to mitigate the problem of _multiple inheritance_, which is absent in PHP.
|
||||
|
||||
In case of functions name conflic it's possible to use `insteadof` to specify which function to use. It's also possible to use an *alias* to resolve the conflicts.
|
||||
In case of functions name conflic it's possible to use `insteadof` to specify which function to use. It's also possible to use an _alias_ to resolve the conflicts.
|
||||
|
||||
```php
|
||||
trait TraitName {
|
||||
|
@ -784,7 +784,7 @@ hash($algorithm, $data);
|
|||
|
||||
Algorithms currently supported:
|
||||
|
||||
- **PASSWORD_DEFAULT** - Use the *bcrypt* algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP.
|
||||
- **PASSWORD_DEFAULT** - Use the _bcrypt_ algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP.
|
||||
- **PASSWORD_BCRYPT** - Use the **CRYPT_BLOWFISH** algorithm to create the hash. This will produce a standard `crypt()` compatible hash using the "$2y$" identifier. The result will always be a 60 character string, or FALSE on failure.
|
||||
- **PASSWORD_ARGON2I** - Use the **Argon2i** hashing algorithm to create the hash. This algorithm is only available if PHP has been compiled with Argon2 support.
|
||||
- **PASSWORD_ARGON2ID** - Use the **Argon2id** hashing algorithm to create the hash. This algorithm is only available if PHP has been compiled with Argon2 support.
|
||||
|
@ -792,11 +792,11 @@ Algorithms currently supported:
|
|||
**Supported options for PASSWORD_BCRYPT**:
|
||||
|
||||
- **salt** (string) - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.
|
||||
If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.
|
||||
**Warning**: The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.
|
||||
If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.
|
||||
**Warning**: The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.
|
||||
|
||||
- **cost** (integer) - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.
|
||||
If omitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.
|
||||
If omitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.
|
||||
|
||||
**Supported options for PASSWORD_ARGON2I and PASSWORD_ARGON2ID**:
|
||||
|
||||
|
@ -868,19 +868,18 @@ error_log(sprintf("[%s] Error: _", date("Y-m-d h:i:s")), 3, "path\\log.log")
|
|||
|
||||
## Exception Handling
|
||||
|
||||
PHP offers the possibility to handle errors with the *exception model*.
|
||||
PHP offers the possibility to handle errors with the _exception model_.
|
||||
|
||||
```php
|
||||
try {
|
||||
// dangerous code
|
||||
|
||||
} catch(ExcpetionType1 | ExceptionType2 $e) {
|
||||
printf("Errore: %s", $e->getMessage());
|
||||
} catch(Excpetion $e) {
|
||||
// handle or report exception
|
||||
}
|
||||
|
||||
throw new ExceptionType("message"); // trow an exception
|
||||
throw new ExceptionType("message"); // throw an exception
|
||||
```
|
||||
|
||||
All exceptions in PHP implement the interface `Throwable`.
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
# [SimpleMVC](https://github.com/ezimuel/simplemvc) Mini-Framework
|
||||
|
||||
Mini framework MVC per scopi didattici basato su Dependency Injection ([PHP-DI][php-di]), Routing ([FastRoute][fastroute]), PSR-7 ([nyholm/psr7][psr7]) e Templates ([Plates][plates])
|
||||
SimpleMVC is a micro MVC framework for PHP using [FastRoute][fastroute], [PHP-DI][php-di], [Plates][plates] and [PHP-DI][php-di] standard for HTTP messages.
|
||||
|
||||
This framework is mainly used as tutorial for introducing the Model-View-Controller architecture in modern PHP applications.
|
||||
|
||||
[php-di]: https://php-di.org/
|
||||
[fastroute]: https://github.com/nikic/FastRoute
|
||||
|
|
|
@ -95,7 +95,7 @@ echo $template->render('template_name', [ "marker" => value, ... ]);
|
|||
It's necessary to verify that the output is in the necessary format.
|
||||
|
||||
Plates offerts `$this->escape()` or `$this->e()` to validate the output.
|
||||
In general the output validation allows toprevent [Cross-Site Scripting][owasp-xss] (XSS).
|
||||
In general the output validation allows to prevent [Cross-Site Scripting][owasp-xss] (XSS).
|
||||
|
||||
[owasp-xss]: https://owasp.org/www-community/attacks/xss/
|
||||
|
||||
|
|
|
@ -42,7 +42,8 @@ PHPUnit can be configured in a XML file called `phpunit.xml`:
|
|||
|
||||
### Test Structure
|
||||
|
||||
**PHPUnit** tests are grouped in classes suffixed with `Test`. Each class *extends* `PHPUnit\Framework\TestCase`. A test is a method of a *test class* prefized with `test`.
|
||||
**PHPUnit** tests are grouped in classes suffixed with `Test`. Each class *extends* `PHPUnit\Framework\TestCase`.
|
||||
A test is a method of a *test class* prefized with `test`.
|
||||
PHPUnit is executed from the command line with `vendor/bin/phpunit --colors`.
|
||||
|
||||
```php
|
||||
|
@ -120,16 +121,15 @@ public function testExceptionNotTrown()
|
|||
// same as
|
||||
|
||||
/**
|
||||
* @dataProvider provideExamNames
|
||||
* @doesNotPerformAssertions
|
||||
*/
|
||||
public function testAggiungiEsameNoExceptions(string $esame)
|
||||
public function testNoExceptions(string $esame)
|
||||
{
|
||||
$this->studente->aggiungiEsame($esame);
|
||||
// code that should succeed (exceptions will make the test fail)
|
||||
}
|
||||
```
|
||||
|
||||
### Test Setup & Teardown
|
||||
### Test Setup & Teardown (Example)
|
||||
|
||||
```php
|
||||
class ClassTest extends TestCase
|
||||
|
|
17
PHP/Web.md
17
PHP/Web.md
|
@ -25,9 +25,9 @@ Handling of HTTP requests happend using the following global variables:
|
|||
```html
|
||||
<!-- method MUST BE post -->
|
||||
<!-- must have enctype="multipart/form-data" attribute -->
|
||||
<form name="invio_file" action="file.php" method="POST" enctype="multipart/form-data">
|
||||
<form name="<name>" action="file.php" method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="photo" />
|
||||
<input type="submit" name="Invio" />
|
||||
<input type="submit" name="Send" />
|
||||
</form>
|
||||
```
|
||||
|
||||
|
@ -36,13 +36,13 @@ Files in `$_FILES` are memorized in a system temp folder. They can be moved with
|
|||
```php
|
||||
if (! isset($_FILES['photo']['error'])) {
|
||||
http_response_code(400); # send a response code
|
||||
echo'<h1>Non è stato inviato nessun file</h1>';
|
||||
echo'<h1>No file has been sent</h1>';
|
||||
exit();
|
||||
}
|
||||
|
||||
if ($_FILES['photo']['error'] != UPLOAD_ERR_OK) {
|
||||
http_response_code(400);
|
||||
echo'<h1>Il file inviato non è valido</h1>';
|
||||
echo'<h1>The sent file is invalid</h1>';
|
||||
exit();
|
||||
}
|
||||
|
||||
|
@ -50,11 +50,11 @@ $path = '/path/to/' . $_FILES['photo']['name'];
|
|||
|
||||
if (! move_uploaded_file($_FILES['photo']['tmp_name'], $path)) {
|
||||
http_response_code(400);
|
||||
echo'<h1>Errore durante la scrittura del file</h1>';
|
||||
echo'<h1>Error while writing the file</h1>';
|
||||
exit();
|
||||
}
|
||||
|
||||
echo'<h1>File inviato con successo</h1>';
|
||||
echo'<h1>File succesfully sent</h1>';
|
||||
```
|
||||
|
||||
### `$_SERVER`
|
||||
|
@ -80,7 +80,7 @@ $_SERVER["HTTP_USER_AGENT"];
|
|||
|
||||
All sites **must** have a page for the consensus about using cookies.
|
||||
|
||||
**Cookies** are HTTP headers used to memorize key-value info *on the client*. They are sent from the server to the client to keep track of info on the user that is visting the website.
|
||||
**Cookies** are HTTP headers used to memorize key-value info *on the client*. They are sent from the server to the client to keep track of info on the user that is visting the website.
|
||||
When a client recieves a HTTP response that contains `Set-Cookie` headers it has to memorize that info and reuse them in future requests.
|
||||
|
||||
```http
|
||||
|
@ -127,7 +127,8 @@ if(isset($_COOKIE["cookie_name"])) {}
|
|||
|
||||
PHP generates a cookie named `PHPSESSID` containing a *session identifier* and an *hash* generated from `IP + timestamp + pseudo-random number`.
|
||||
|
||||
To use the session it's necesary to recall the function `session_start()` at the beginning of a PHP script that deals with sesssions; after starting the session information in be savend in the `$_SESSION` array.
|
||||
To use the session it's necesary to recall the function `session_start()` at the beginning of a PHP script that deals with sessions.
|
||||
After starting the session information in be savend in the `$_SESSION` array.
|
||||
|
||||
```php
|
||||
$_SESSION["key"] = value; // save data in session file (serialized data)
|
||||
|
|
|
@ -40,25 +40,25 @@ These features, sometimes collectively referred to as the module system, include
|
|||
|
||||
### Packages & Crates
|
||||
|
||||
A crate is a binary or library. The crate root is a source file that the Rust compiler starts from and makes up the root module of he crate.
|
||||
A crate is a binary or library. The crate root is a source file that the Rust compiler starts from and makes up the root module of he crate.
|
||||
A package is one or more crates that provide a set of functionality. A package contains a `Cargo.toml` file that describes how to build those crates.
|
||||
|
||||
Several rules determine what a package can contain. A package must contain `zero` or `one` **library crates** (`lib` ?), and no more.
|
||||
Several rules determine what a package can contain. A package must contain `zero` or `one` **library crates** (`lib` ?), and no more.
|
||||
It can contain as many `binary` crates as you’d like, but it must contain at least one crate (either library or binary).
|
||||
|
||||
If a package contains `src/main.rs` and `src/lib.rs`, it has two crates: a library and a binary, both with the same name as the package.
|
||||
If a package contains `src/main.rs` and `src/lib.rs`, it has two crates: a library and a binary, both with the same name as the package.
|
||||
A package can have multiple binary crates by placing files in the `src/bin` directory: each file will be a separate binary crate.
|
||||
|
||||
A crate will group related functionality together in a scope so the functionality is easy to share between multiple projects.
|
||||
|
||||
Cargo follows a convention that `src/main.rs` is the crate root of a binary crate with the same name as the package.
|
||||
Cargo follows a convention that `src/main.rs` is the crate root of a binary crate with the same name as the package.
|
||||
Likewise, Cargo knows that if the package directory contains `src/lib.rs`, the package contains a library crate with the same name as the package, and `src/lib.rs` is its crate root.
|
||||
|
||||
### Modules
|
||||
|
||||
Modules allow to organize code within a crate into groups for readability and easy reuse. Modules also control the privacy of items, which is whether an item can be used by outside code (*public*) or is an internal implementation detail and not available for outside use (*private*).
|
||||
|
||||
Define a module by starting with the `mod` keyword and then specify the name of the moduleand place curly brackets around the body of the module.
|
||||
Define a module by starting with the `mod` keyword and then specify the name of the moduleand place curly brackets around the body of the module.
|
||||
Inside modules, it's possible to have other modules. Modules can also hold definitions for other items, such as structs, enums, constants, traits, or functions.
|
||||
|
||||
### Paths
|
||||
|
@ -80,10 +80,12 @@ crate::module::function(); // abs path (same crate)
|
|||
|
||||
### Public vs Private
|
||||
|
||||
Modules aren’t useful only for organizing the code. They also define Rust’s privacy boundary: the line that encapsulates the implementation details external code isn’t allowed to know about, call, or rely on. So, to make an item like a function or struct private, put it in a module.
|
||||
Modules aren’t useful only for organizing the code. They also define Rust’s privacy boundary:
|
||||
the line that encapsulates the implementation details external code isn’t allowed to know about, call, or rely on.
|
||||
So, to make an item like a function or struct private, put it in a module.
|
||||
|
||||
The way privacy works in Rust is that all items (functions, methods, structs, enums, modules, and constants) are *private by default*.
|
||||
Items in a parent module can’t use the private items inside child modules, but items in child modules can use the items in their ancestor modules.
|
||||
The way privacy works in Rust is that all items (functions, methods, structs, enums, modules, and constants) are *private by default*.
|
||||
Items in a parent module can’t use the private items inside child modules, but items in child modules can use the items in their ancestor modules.
|
||||
The reason is that child modules wrap and hide their implementation details, but the child modules can see the context in which they’re defined.
|
||||
|
||||
```rs
|
||||
|
@ -99,8 +101,9 @@ pub mod public_module {
|
|||
mod file_level_module; // define a module for the whole file (same name as file)
|
||||
```
|
||||
|
||||
It's possible to use `pub` to designate *structs* and *enums* as public, but there are a few extra details.
|
||||
If `pub` is used before a struct definition, this makes the struct public, but the struct’s fields will still be private. It's possible make each field public or not on a case-by-case basis.
|
||||
It's possible to use `pub` to designate *structs* and *enums* as public, but there are a few extra details.
|
||||
If `pub` is used before a struct definition, this makes the struct public, but the struct’s fields will still be private.
|
||||
It's possible make each field public or not on a case-by-case basis.
|
||||
|
||||
In contrast, if an enum is made public, all of its variants are then public.
|
||||
|
||||
|
@ -108,14 +111,14 @@ In contrast, if an enum is made public, all of its variants are then public.
|
|||
|
||||
```rs
|
||||
use <crate_name>::module; // import module (abs path, other crate)
|
||||
use crate::module; // s (abs path, same crate)
|
||||
use self::module; // // import module (rel path, same crate)
|
||||
use crate::module; // import module (abs path, same crate)
|
||||
use self::module; // import module (rel path, same crate)
|
||||
|
||||
use <crate_name>::module as alias; // import module w/ aliass
|
||||
pub use <crate_name>::module; // re-exporting (import and make available to others)
|
||||
|
||||
use <crate_name>::module::{self, Item}; // import multiple paths
|
||||
use use <crate_name>::module::*; // import all public items (Glob operator)
|
||||
pub use <crate_name>::module::*; // import all public items (Glob operator)
|
||||
|
||||
module::function(); // use func w/ shorter path
|
||||
```
|
||||
|
@ -124,9 +127,17 @@ module::function(); // use func w/ shorter path
|
|||
|
||||
```txt
|
||||
src
|
||||
|_main.rs --> app entrypoint
|
||||
|_lib.rs --> export module-folders
|
||||
|_main.rs --> default executable file
|
||||
|_lib.rs --> default library file
|
||||
|__module
|
||||
| |_mod.rs --> export module-files
|
||||
| |_file.rs
|
||||
| |_mod.rs --> export submodules
|
||||
| |_submodule.rs --> submodule
|
||||
```
|
||||
|
||||
```rs
|
||||
// main.rs
|
||||
mod module; // delcare module direcotry as a module
|
||||
|
||||
// mod.rs
|
||||
pub mod sub_module; // declare sub_module file as a module
|
||||
```
|
||||
|
|
59
Rust/Rust.md
59
Rust/Rust.md
|
@ -21,8 +21,8 @@ fn main() { //program entry point
|
|||
|
||||
The `Result` types are **enumerations**, often referred to as *enums*. An enumeration is a type that can have a *fixed set of values*, and those values are called the enum’s **variants**.
|
||||
|
||||
For `Result`, the variants are `Ok` or `Err`.
|
||||
The `Ok` variant indicates the operation was *successful*, and inside `Ok` is the successfully generated value.
|
||||
For `Result`, the variants are `Ok` or `Err`.
|
||||
The `Ok` variant indicates the operation was *successful*, and inside `Ok` is the successfully generated value.
|
||||
The `Err` variant means the operation failed, and `Err` contains information about how or why the operation failed.
|
||||
|
||||
The purpose of the `Result` types is to encode error-handling information.
|
||||
|
@ -51,7 +51,8 @@ io::stdin() // read line from stdin
|
|||
.expect("Error Message"); // in case of errors return an error message (io::Result) -- NEEDED
|
||||
```
|
||||
|
||||
The `::` syntax in the `::new` line indicates that `new` is an **associated function** of the `String` type. An associated function is implemented on a type rather than on a particular instance of the type. Some languages call this a `static method`.
|
||||
The `::` syntax in the `::new` line indicates that `new` is an **associated function** of the `String` type.
|
||||
An associated function is implemented on a type rather than on a particular instance of the type. Some languages call this a `static method`.
|
||||
|
||||
The `&` indicates that this argument is a reference, which gives a way to let multiple parts of the code access one piece of data without needing to copy that data into memory multiple times.
|
||||
|
||||
|
@ -71,10 +72,11 @@ const CONSTANT_NAME: type = value; // constant must have the type annotation
|
|||
|
||||
### Shadowing
|
||||
|
||||
It's possible declare a new variable with the *same name* as a previous variable, and the new variable *shadows* the previous variable.
|
||||
It's possible declare a new variable with the *same name* as a previous variable, and the new variable *shadows* the previous variable.
|
||||
By using let, it's possible to perform a few transformations on a value but have the variable be immutable after those transformations have been completed.
|
||||
|
||||
The other difference between *mut* and *shadowing* is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name.
|
||||
The other difference between *mut* and *shadowing* is that because we’re effectively creating a new variable when we use the let keyword again,
|
||||
we can change the type of the value but reuse the same name.
|
||||
|
||||
```rs
|
||||
let x: u32 = 10;
|
||||
|
@ -96,8 +98,8 @@ let x: i32 = 11; // shadowing
|
|||
|
||||
### Floating-Point Types
|
||||
|
||||
Rust also has two primitive types for floating-point numbers, which are numbers with decimal points.
|
||||
Rust’s floating-point types are `f32` and `f64`, which are 32 bits and 64 bits in size, respectively.
|
||||
Rust also has two primitive types for floating-point numbers, which are numbers with decimal points.
|
||||
Rust’s floating-point types are `f32` and `f64`, which are 32 bits and 64 bits in size, respectively.
|
||||
The default type is `f64` because on modern CPUs it’s roughly the same speed as `f32` but is capable of more precision.
|
||||
|
||||
### Numeric Operation
|
||||
|
@ -112,7 +114,7 @@ The default type is `f64` because on modern CPUs it’s roughly the same speed a
|
|||
|
||||
### Boolean Types
|
||||
|
||||
Boolean types in Rust have two possible values: `true` and `false`.
|
||||
Boolean types in Rust have two possible values: `true` and `false`.
|
||||
Booleans are one byte in size. The Boolean type in Rust is specified using `bool`.
|
||||
|
||||
### Character Types
|
||||
|
@ -136,7 +138,7 @@ s.push_str(""); // appending string literals
|
|||
|
||||
### Tuple Types
|
||||
|
||||
A tuple is a general way of grouping together a number of values with a variety of types into one compound type.
|
||||
A tuple is a general way of grouping together a number of values with a variety of types into one compound type.
|
||||
Tuples have a *fixed length*: once declared, they cannot grow or shrink in size.
|
||||
|
||||
```rs
|
||||
|
@ -149,7 +151,7 @@ tup.0; // member access
|
|||
|
||||
### Array Types
|
||||
|
||||
Every element of an array must have the *same type*. Arrays in Rust have a fixed length, like tuples.
|
||||
Every element of an array must have the *same type*. Arrays in Rust have a fixed length, like tuples.
|
||||
An array isn’t as flexible as the `vector` type, though. A vector is a similar collection type provided by the standard library that *is allowed to grow or shrink in size*.
|
||||
|
||||
```rs
|
||||
|
@ -178,7 +180,7 @@ let slice = &a[start..end];
|
|||
|
||||
Rust code uses *snake_case* as the conventional style for function and variable names.
|
||||
|
||||
Function definitions in Rust start with `fn` and have a set of parentheses after the function name.
|
||||
Function definitions in Rust start with `fn` and have a set of parentheses after the function name.
|
||||
The curly brackets tell the compiler where the function body begins and ends.
|
||||
|
||||
Rust doesn’t care where the functions are defined, only that they’re defined somewhere.
|
||||
|
@ -261,23 +263,23 @@ for i in (start..end) { // (start..stop) is like python's range(start, stop)
|
|||
|
||||
Ownership is Rust’s most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector.
|
||||
|
||||
All programs have to manage the way they use a computer’s memory while running.
|
||||
Some languages have garbage collection that constantly looks for no longer used memory as the program runs; in other languages, the programmer must explicitly allocate and free the memory.
|
||||
Rust uses a third approach: memory is managed through a system of ownership with a set of rules that the compiler checks at compile time.
|
||||
All programs have to manage the way they use a computer’s memory while running.
|
||||
Some languages have garbage collection that constantly looks for no longer used memory as the program runs; in other languages, the programmer must explicitly allocate and free the memory.
|
||||
Rust uses a third approach: memory is managed through a system of ownership with a set of rules that the compiler checks at compile time.
|
||||
None of the ownership features slow down your program while it’s running.
|
||||
|
||||
### Stack & Heap
|
||||
|
||||
Both the stack and the heap are parts of memory that are available to your code to use at runtime, but they are structured in different ways.
|
||||
|
||||
The *stack* stores values in the order it gets them and removes the values in the opposite order. This is referred to as *last in, first out*.
|
||||
The *stack* stores values in the order it gets them and removes the values in the opposite order. This is referred to as *last in, first out*.
|
||||
Adding data is called *pushing* onto the stack, and removing data is called *popping* off the stack.
|
||||
|
||||
All data stored on the stack must have a known, fixed size. Data with an unknown size at compile time or a size that might change must be stored on the heap instead.
|
||||
|
||||
The heap is less organized: when you put data on the heap, you request a certain amount of space. The memory allocator finds an empty spot in the heap that is big enough, marks it as being in use, and returns a **pointer**, which is the address of that location. This process is called *allocating on the heap* and is sometimes abbreviated as just *allocating*.
|
||||
|
||||
Pushing to the stack is faster than allocating on the heap because the allocator never has to search for a place to store new data; that location is always at the top of the stack.
|
||||
Pushing to the stack is faster than allocating on the heap because the allocator never has to search for a place to store new data; that location is always at the top of the stack.
|
||||
Comparatively, allocating space on the heap requires more work, because the allocator must first find a big enough space to hold the data and then perform bookkeeping to prepare for the next allocation.
|
||||
|
||||
Accessing data in the heap is slower than accessing data on the stack because you have to follow a pointer to get there. Contemporary processors are faster if they jump around less in memory.
|
||||
|
@ -292,15 +294,15 @@ Keeping track of what parts of code are using what data on the heap, minimizing
|
|||
|
||||
### Ways Variables and Data Interact
|
||||
|
||||
A "shallow copy" of a variable allocated on the heap (C#'s reference value) the original variable goes out of scope and only the "copy" remains.
|
||||
A "shallow copy" of a variable allocated on the heap (C#'s reference value) the original variable goes out of scope and only the "copy" remains.
|
||||
A "deep copy" (`var.clone()`) makes a copy of the data in the new variable without make the original fall out of scope.
|
||||
|
||||
When a variable goes out of scope, Rust calls a special function for us. This function is called `drop`, and it’s where the code to return the memory is located.
|
||||
|
||||
Rust has a special annotation called the `Copy` trait that we can place on types that are stored on the stack.
|
||||
Rust has a special annotation called the `Copy` trait that we can place on types that are stored on the stack.
|
||||
If a type has the `Copy` trait, an older variable is still usable after assignment.
|
||||
|
||||
Rust won’t let us annotate a type with the `Copy` trait if the type, or any of its parts, has implemented the `Drop` trait.
|
||||
Rust won’t let us annotate a type with the `Copy` trait if the type, or any of its parts, has implemented the `Drop` trait.
|
||||
If the type needs something special to happen when the value goes out of scope and we add the `Copy` annotation to that type, we’ll get a compile-time error.
|
||||
|
||||
```rs
|
||||
|
@ -365,11 +367,11 @@ fn takes_and_gives_back(a_string: String) -> String { // a_string comes into sco
|
|||
|
||||
*Mutable references* have one big restriction: you can have *only one* mutable reference to a particular piece of data in a particular scope.
|
||||
|
||||
The benefit of having this restriction is that Rust can prevent **data races** at compile time.
|
||||
The benefit of having this restriction is that Rust can prevent **data races** at compile time.
|
||||
A data race is similar to a race condition and happens when these three behaviors occur:
|
||||
|
||||
- Two or more pointers access the same data at the same time.
|
||||
- At least one of the pointers is being used to write to the data.
|
||||
- Two or more pointers access the same data at the same time.
|
||||
- At least one of the pointers is being used to write to the data.
|
||||
- There’s no mechanism being used to synchronize access to the data.
|
||||
|
||||
```rs
|
||||
|
@ -388,8 +390,8 @@ fn borrow2(var: &mut Type) {
|
|||
|
||||
A **struct**, or structure, is a custom data type that allows to name and package together multiple related values that make up a meaningful group.
|
||||
|
||||
To define a struct enter the keyword struct and name the entire struct.
|
||||
A struct’s name should describe the significance of the pieces of data being grouped together.
|
||||
To define a struct enter the keyword struct and name the entire struct.
|
||||
A struct’s name should describe the significance of the pieces of data being grouped together.
|
||||
Then, inside curly brackets, define the names and types of the pieces of data, which we call *fields*.
|
||||
|
||||
```rs
|
||||
|
@ -518,7 +520,7 @@ impl Enum
|
|||
|
||||
The `Option` type is used in many places because it encodes the very common scenario in which a value could be something or it could be nothing. Expressing this concept in terms of the type system means the compiler can check whether you’ve handled all the cases you should be handling; this functionality can prevent bugs that are extremely common in other programming languages.
|
||||
|
||||
he `Option<T>` enum is so useful that it’s even included in the prelude; you don’t need to bring it into scope explicitly.
|
||||
he `Option<T>` enum is so useful that it’s even included in the prelude; you don’t need to bring it into scope explicitly.
|
||||
In addition, so are its variants: you can use `Some` and `None` directly without the `Option::` prefix.
|
||||
|
||||
```rs
|
||||
|
@ -533,7 +535,8 @@ enum Option<T> {
|
|||
|
||||
### Match Expression + Comparing
|
||||
|
||||
A **match expression** is made up of *arms*. An arm consists of a *pattern* and the code that should be run if the value given to the beginning of the match expression fits that arm’s pattern.
|
||||
A **match expression** is made up of *arms*.
|
||||
An arm consists of a *pattern* and the code that should be run if the value given to the beginning of the match expression fits that arm’s pattern.
|
||||
Rust takes the value given to match and looks through each arm’s pattern in turn.
|
||||
|
||||
**NOTE**: `match` arms must be exaustive for compilation.
|
||||
|
@ -595,7 +598,3 @@ let v = vec![
|
|||
Enum::Text("TEST")
|
||||
];
|
||||
```
|
||||
|
||||
### String
|
||||
|
||||
### Hash Map
|
||||
|
|
|
@ -4,17 +4,17 @@ A page of the app.
|
|||
|
||||
## Views, Functions & Variables
|
||||
|
||||
`@State` allows the view to respond to every change of the anotated variable. This variables get initialized by the view in which they belong and are not "recieved" from external objects.
|
||||
`@State` allows the view to respond to every change of the anotated variable. This variables get initialized by the view in which they belong and are not "recieved" from external objects.
|
||||
SwiftUI memorizes internally the value of the `@State` property and updates the view every time it changes.
|
||||
|
||||
`@Binding` is used for properties that are passed to the view from another. The recieveing view can read the binfing value, react to changes and modify it's value.
|
||||
`@Binding` is used for properties that are passed to the view from another. The recieveing view can read the binfing value, react to changes and modify it's value.
|
||||
`@Binding` variables are passed with the prefix `$`,
|
||||
|
||||
### Simple View
|
||||
|
||||
- Simplest view.
|
||||
- Permits the visualization of simple UIs.
|
||||
- Constituited bay a body of type `View`
|
||||
- Constituited by a body of type `View`
|
||||
|
||||
```swift
|
||||
struct SimpleViewName: View {
|
||||
|
@ -58,8 +58,8 @@ Most common view to present array contents, it automatically hendles the scrolli
|
|||
I can be inegrate d in a `NavigaionView` to handle a `DeailView` of a selectted item in the list.
|
||||
|
||||
The basic object that creates the table view is the `List()`. It's job is to create a "cell" for every element in the array.
|
||||
The array can be filttered with a *search bar*.
|
||||
The array elements can be grouped with the `Section()` object that groups cells under a common name un the table.
|
||||
The array can be filtered with a *search bar*.
|
||||
The array elements can be grouped with the `Section()` object that groups cells under a common name in the table.
|
||||
|
||||
```swift
|
||||
// view name can be any
|
||||
|
@ -83,7 +83,7 @@ struct TableCell: View {
|
|||
}
|
||||
```
|
||||
|
||||
Every cell can have a link to visualize he details of the selected object. This is done by using `NavigationView` and `NavigationLink`.
|
||||
Every cell can have a link to visualize the details of the selected object. This is done by using `NavigationView` and `NavigationLink`.
|
||||
|
||||
The `NavigationView` contains the list and the property `.navigationBarTitle()` sets the view title.
|
||||
It's possible to add other controls in the top part of the view (buttons, ...) using the property `.navigationBarItems()`.
|
||||
|
@ -129,7 +129,7 @@ struct TabBarView: View {
|
|||
}
|
||||
```
|
||||
|
||||
The `TabBar` conostruction is made applying the `.tabItem{}` parameter to the object or page that the tab will link to.
|
||||
The `TabBar` construction is made applying the `.tabItem{}` parameter to the object or page that the tab will link to.
|
||||
It's possible to specify up to 5 `.tabItem{}` elements that will be displayed singularly in the `TabBar`.
|
||||
|
||||
Fron the 6th elemnet onwards, the first 4 elemens will appear normally, meanwhile the 5th will become a "more" element that will open a `TableView` with the list of the other `.tabItem{}` elements. This page permis to define which elements will be visible.
|
||||
|
|
Loading…
Add table
Reference in a new issue