{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"index.html","title":"Dev Notes","text":"

Personal notes on various programming languages, technologies, tools, etc. to be used as quick reference.

Note: These notes are not meant to be comprehensive but to contain frequently used information. For complete and up to date documentation always go to the primary source.

"},{"location":"containers/docker.html","title":"Docker","text":""},{"location":"containers/docker.html#images-containers","title":"Images & Containers","text":"

Containerization is an approach to software development in which an application or service, its dependencies, and its configuration (abstracted as deployment manifest files) are packaged together as a container image.

Just as shipping containers allow goods to be transported by ship, train, or truck regardless of the cargo inside, software containers act as a standard unit of software deployment that can contain different code and dependencies. Containerizing software this way enables developers and IT professionals to deploy them across environments with little or no modification.

Containers also isolate applications from each other on a shared OS. Containerized applications run on top of a container host that in turn runs on the OS. Containers therefore have a much smaller footprint than virtual machine (VM) images.

In short, containers offer the benefits of isolation, portability, agility, scalability, and control across the entire application lifecycle workflow.

"},{"location":"containers/docker.html#containers-vs-virtual-machines","title":"Containers vs Virtual Machines","text":"

A container runs natively on Linux and shares the kernel of the host machine with other containers. It runs a discrete process, taking no more memory than any other executable, making it lightweight.

By contrast, a virtual machine (VM) runs a full-blown \"guest\" operating system with virtual access to host resources through a hypervisor. In general, VMs incur a lot of overhead beyond what is being consumed by your application logic.

"},{"location":"containers/docker.html#docker-terminology","title":"Docker Terminology","text":"

Container image: A package with all the dependencies and information needed to create a container. An image includes all the dependencies (such as frameworks) plus deployment and execution configuration to be used by a container runtime. Usually, an image derives from multiple base images that are layers stacked on top of each other to form the container\u2019s filesystem. An image is immutable once it has been created.

Dockerfile: A text file that contains instructions for building a Docker image. It\u2019s like a batch script, the first line states the base image to begin with and then follow the instructions to install required programs, copy files, and so on, until you get the working environment you need.

Build: The action of building a container image based on the information and context provided by its Dockerfile, plus additional files in the folder where the image is built. You can build images with the following Docker command: docker build

Container: An instance of a Docker image. A container represents the execution of a single application, process, or service. It consists of the contents of a Docker image, an execution environment, and a standard set of instructions. When scaling a service, you create multiple instances of a container from the same image. Or a batch job can create multiple containers from the same image, passing different parameters to each instance.

Volumes: Offer a writable filesystem that the container can use. Since images are read-only but most programs need to write to the filesystem, volumes add a writable layer, on top of the container image, so the programs have access to a writable filesystem. The program doesn\u2019t know it\u2019s accessing a layered filesystem, it\u2019s just the filesystem as usual. Volumes live in the host system and are managed by Docker.

Tag: A mark or label you can apply to images so that different images or versions of the same image (depending on the version number or the target environment) can be identified.

Multi-stage Build: Is a feature, since Docker 17.05 or higher, that helps to reduce the size of the final images. For example, a large base image, containing the SDK can be used for compiling and publishing and then a small runtime-only base image can be used to host the application.

Repository (repo): A collection of related Docker images, labeled with a tag that indicates the image version. Some repos contain multiple variants of a specific image, such as an image containing SDKs (heavier), an image containing only runtimes (lighter), etc. Those variants can be marked with tags. A single repo can contain platform variants, such as a Linux image and a Windows image.

Registry: A service that provides access to repositories. The default registry for most public images is Docker Hub (owned by Docker as an organization). A registry usually contains repositories from multiple teams. Companies often have private registries to store and manage images they\u2019ve created.

Multi-arch image: For multi-architecture, it\u2019s a feature that simplifies the selection of the appropriate image, according to the platform where Docker is running.

Docker Hub: A public registry to upload images and work with them. Docker Hub provides Docker image hosting, public or private registries, build triggers and web hooks, and integration with GitHub and Bitbucket.

Azure Container Registry: A public resource for working with Docker images and its components in Azure. This provides a registry that\u2019s close to your deployments in Azure and that gives you control over access, making it possible to use your Azure Active Directory groups and permissions.

Docker Trusted Registry (DTR): A Docker registry service (from Docker) that can be installed on-premises so it lives within the organization\u2019s datacenter and network. It\u2019s convenient for private images that should be managed within the enterprise. Docker Trusted Registry is included as part of the Docker Datacenter product. For more information, see Docker Trusted Registry (DTR).

Docker Compose: A command-line tool and YAML file format with metadata for defining and running multi-container applications. You define a single application based on multiple images with one or more .yml files that can override values depending on the environment. After you\u2019ve created the definitions, you can deploy the whole multi-container application with a single command (docker-compose up) that creates a container per image on the Docker host.

Cluster: A collection of Docker hosts exposed as if it were a single virtual Docker host, so that the application can scale to multiple instances of the services spread across multiple hosts within the cluster. Docker clusters can be created with Kubernetes, Azure Service Fabric, Docker Swarm and Mesosphere DC/OS.

Orchestrator: A tool that simplifies the management of clusters and Docker hosts. Orchestrators enable you to manage their images, containers, and hosts through a command-line interface (CLI) or a graphical UI. You can manage container networking, configurations, load balancing, service discovery, high availability, Docker host configuration, and more. An orchestrator is responsible for running, distributing, scaling, and healing workloads across a collection of nodes. Typically, orchestrator products are the same products that provide cluster infrastructure, like Kubernetes and Azure Service Fabric, among other offerings in the market.

"},{"location":"containers/docker.html#docker-cli","title":"Docker CLI","text":""},{"location":"containers/docker.html#docker-run","title":"docker run","text":"Bash
docker run <image>  # run selected app inside a container (downloaded from Docker Hub if missing from image)\ndocker run -d|--detach <image>  # run docker container in the background (does not occupy stdout & stderr)\ndocker run -i|--interactive <image>  # run docker container in interactive mode (read stdin)\ndocker run -t|--tty <image>  # run docker container allocating a pseudo-TTY (show prompts)\ndocker run -p|--publish <host_port>:<container_port> <image>  # map container ports\ndocker run -v|--volume <existing_host_dir>:<container_dir> <image>  # map container directory to a host directory (external volumes)\ndocker run -v|--volume <volume_name>:<container_dir> <image>  # map container directory to a host directory under the docker main folder (external volumes)\ndocker run -e|--env NAME=value <image>  # set container env vars\ndocker run --entrypoint <executable> <args> <image>  # run with a non-default entrypoint\ndocker run --name=<container_name> <image>  # set container name\n

Warn: <image> must be last argument

"},{"location":"containers/docker.html#docker-container","title":"docker container","text":"Bash
docker container ls  # list of currently running containers\ndocker container ls -a|--all  # list of all containers, running and exited\ndocker container rm <container>  # remove one or more containers\ndocker container prune  # remove stopped containers\n\ndocker container inspect <container>  # full details about a container\ndocker container logs <container>  # see container logs\n\ndocker container stop <container>  # stop a running container\ndocker container start <container>  # start a stopped container\n\ndocker container exec <container> <command>  # exec a command inside a container\n
"},{"location":"containers/docker.html#docker-image","title":"docker image","text":"Bash
docker image ls  # list of existing images\ndocker image rm <image>  # remove one or more images\ndocker image prune <image>  # remove unused images\ndocker image pull <image>  # download an image w/o starting the container\n
"},{"location":"containers/docker.html#docker-build","title":"docker build","text":"Bash
docker build -t <tag> -f <dockerfile> <context>  # build image with specific tag (usually user/app:version)\ndocker build -t <tag> -f <dockerfile> --build-arg ARG=value <context>  # pass args to ARG steps\n
"},{"location":"containers/docker.html#docker-push","title":"docker push","text":"Bash
docker push <image>  # publish image to registry (defaults to Docker Hub)\n
"},{"location":"containers/docker.html#dockerfile","title":"Dockerfile","text":"Docker
# starting image or scratch\nFROM <base_image>:<tag>\n\n# run commands (e.g: install dependencies)\nRUN <command>\n\n# define working directory (usually /app)\nWORKDIR <path>\n\n# copy source code into the image in a specified location\nCOPY <src> <dir_in_container>\n\n# accept args from docker run (--build-arg arg_name=value)\nARG <arg_name>\n\n# set env values inside the container\nENV <ENV_VAR> <value>\n\n# Exec form (Preferred form)\nCMD [\"<executable>\", \"<arg1>\", \"<arg2>\"]\nENTRYPOINT [\"<executable>\", \"<arg1>\", \"<arg2>\"]\n\n# Shell form\nCMD <executable> <arg1> <arg2>\nENTRYPOINT <executable> <arg1> <arg2>\n
"},{"location":"containers/docker.html#cmd-vs-entrypoint","title":"CMD vs ENTRYPOINT","text":"

CMD is used to provide all the default scenarios which can be overridden. Anything defined in CMD can be overridden by passing arguments in docker run command.

ENTRYPOINT is used to define a specific executable (and it's arguments) to be executed during container invocation which cannot be overridden. The user can however define arguments to be passed in the executable by adding them in the docker run command.

"},{"location":"containers/docker.html#docker-multi-stage-build","title":"Docker Multi-Stage Build","text":"

With multi-stage builds, it's possible to use multiple FROM statements in the Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build.

It's possible to selectively copy artifacts from one stage to another, leaving behind everything not wanted in the final image.

Docker
FROM <base_image>:<tag> AS <runtime_alias>\nRUN <command>  # install external dependencies (apt get ...)\n\n# --- START of BUILD LAYERS --- #\nFROM <base_image>:<tag> AS <build_alias>\nWORKDIR <app_path>\n\n# install project dependencies\nCOPY <src> <dir_in_container>  # add lockfiles\nRUN <command>  # install project dependencies from lockfiles\n\nCOPY <src> .<dir_in_container>  # bring in all source code\nWORKDIR <build_location>\nARG version\nRUN <command>  # build project\n# --- END of BUILD LAYERS --- #\n\nFROM <runtime_alias> AS <deploy_alias>\nWORKDIR <app_path>\n\n# bring in release build files\nCOPY --from=<build_alias|stage_number> <src> <dir_in_container>\nCMD [\"executable\"]  # run app\n
Docker
FROM mcr.microsoft.com/dotnet/<runtime|aspnet>:<alpine_tag> AS runtime\nRUN <command>  # install external dependencies (apt get ...)\n\n# --- START of BUILD LAYERS --- #\nFROM mcr.microsoft.com/dotnet/sdk:<tag> as build\nWORKDIR /app\n\n# install project dependencies\nCOPY *.sln ./src\nCOPY src/*.csproj ./src\nRUN dotnet restore\n\n# publish app\nCOPY /src ./src  # bring in all source code\nWORKDIR /app/src  # reposition to build location\nARG version\nRUN dotnet publish <project>|<solution> -c Release -o out /p:Version=$version\n# --- END of BUILD LAYERS --- #\n\nFROM runtime AS final-runtime\nWORKDIR /app\nCOPY --from=build /app/out .\n\nENTRYPOINT [\"dotnet\", \"<project>.dll\"]\n
"},{"location":"containers/docker.html#networking","title":"Networking","text":"

Starting container networks: bridge (default), none, host.

Bash
docker run <image> --network=none/host  # specify a non-default network to be used\ndocker run <image> --add-host=<hostname>:<ip>  # add hostname mapping\ndocker network ls  # list all available networks\n

Note: Mapping host-gateway to an hostname allows the container to reach the host network even with networks types different from host

"},{"location":"containers/docker.html#user-defined-networks","title":"User-defined Networks","text":"Bash
docker network create --driver NETWORK_TYPE --subnet GATEWAY_TP/SUBNET_MASK_SIZE NETWORK_NAME\n
"},{"location":"containers/docker.html#embedded-dns","title":"Embedded DNS","text":"

Docker has an internal DNS that allows finding other container by their name instead of their IP. The DNS always runs at the address 127.0.0.11.

"},{"location":"containers/docker.html#exposing-ports","title":"Exposing Ports","text":"

By default, containers on bridge networks don't expose any ports to the outside world. Using the --publish or -p flag makes a port available to services outside the bridge network. This creates a firewall rule in the host, mapping a container port to a port on the Docker host to the outside world.

Here are some examples:

Flag value Description -p 8080:80 Map port 8080 on the host to TCP port 80 in the container. -p 192.168.1.100:8080:80 Map port 8080 on the host IP 192.168.1.100 to TCP port 80 in the container. -p 8080:80/udp Map port 8080 on the host to UDP port 80 in the container. -p 8080:80/tcp -p 8080:80/udp Map TCP and UDP port 8080 on the host to TCP and UDP port 80 in the container.

Warn: Publishing container ports is insecure by default. A published port it becomes available not only to the host, but to the outside world as well. If the localhost IP address (127.0.0.1, or ::1) is included with the publish flag, only the host and its containers can access the published container port.

Bash
docker run --publish 127.0.0.1:8080:80 --publish '[::1]:8080:80' nginx\n
"},{"location":"containers/docker.html#docker-storage","title":"Docker Storage","text":""},{"location":"containers/docker.html#file-system","title":"File System","text":"Bash
/var/lib/docker\n|_<storage_driver>\n|_containers\n|_image\n|_network\n|_volumes\n| |_specific_volume\n|_...\n
"},{"location":"containers/docker.html#copy-on-write","title":"Copy-On-Write","text":"

To modify a file during while the container runs docker creates a local copy in the specific container and the local copy will be modified.

"},{"location":"containers/docker.html#volumes","title":"Volumes","text":"

volume mounting: create a volume under the docker installation folder (/var/lib/docker/volumes/). bind mounting: link docker to an exiting folder to be used as a volume.

Bash
docker run -v <existing_dir>:<container_dir> <image>:<tag>  # older command for bind mounting\ndocker run --mount type=bind, source=:<existing_dir>, target=<container_dir> <image>:<tag>  # modern command for bind mounting\n
"},{"location":"containers/docker.html#docker-compose","title":"Docker Compose","text":"

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application\u2019s services. Then, with a single command, you create and start all the services from your configuration.

Using Compose is basically a three-step process:

  1. Define the app\u2019s environment with a\u00a0Dockerfile\u00a0so it can be reproduced anywhere.
  2. Define the services that make up your app in\u00a0docker-compose.yml\u00a0so they can be run together in an isolated environment.
  3. Run\u00a0docker-compose up\u00a0and Compose starts and runs the entire app.
YAML
version: 3.x\nservices:\n  <service_name>:\n    image: <image_name>\n    image: <image_url>\n    build: <path>  # path to folder containing a Dockerfile to build the image\n    build:\n      context: <path>\n      dockerfile: <*.Dockerfile>\n      args:  # pass args to dockerfile\n        ARG: <value>\n        - ARG=<value>\n    ports: \n      - <host_port>:<container_port>\n    extra_hosts:  # add hostname mappings to container network interface config\n      - <hostname>:<ip>\n      - <hostname>:host-gateway  # map host machine network\n    profiles:  # partition services into sets\n      - <profile_name>\n    networks:  # attach container to one or more networks\n      - <network_name>\n    depends_on:  # make sure dependencies are running before this container\n      - <container_name>\n    environment:  # declare a env vars for this service\n      ENV_VAR: <value>\n      - ENV_VAR=<value>\n    env_file:\n      - <path/to/env/file>  # reusable env file\n    volumes:\n      - \"./<rel/path/to/volume>:<in/container/path/to/data>\"  # service-dedicated volume\n      - \"<volume_name>:<in/container/path/to/data>\"  # reuseable volume\n    healthcheck:\n      disable: <bool>  # set to true to disable\n      test: curl -f http://localhost  # set to [\"NONE\"] to disable\n      interval:  # interval between checks (default 30s)\n      timeout:  # check fail timeout (default 30s)\n      retries:  # num of retries before unhealty (default 3)\n      start_period:  # container init grace pediod (default 5s)\n      start_interval:  # check interval in start period\n\n# reusable volume definitions\nvolumes:\n  - <volume_name>:\n\n# create networks\nnetworks:\n  <network_name>:\n
"},{"location":"containers/kubernetes.html","title":"Kubernetes (k8s)","text":""},{"location":"containers/kubernetes.html#cluster-architecture","title":"Cluster Architecture","text":"

A Kubernetes cluster consists of a set of worker machines, called nodes, that run containerized applications. Every cluster has at least one worker node.

The worker node(s) host the pods that are the components of the application workload. The control plane manages the worker nodes and the pods in the cluster. In production environments, the control plane usually runs across multiple computers and a cluster usually runs multiple nodes, providing fault-tolerance and high availability.

"},{"location":"containers/kubernetes.html#control-plane","title":"Control Plane","text":"

The control plane is the container orchestration layer that exposes the API and interfaces to define, deploy, and manage the lifecycle of containers. It's components are:

Note: in production environment there are at least two control planes to ensure constant availability of their functionalities

"},{"location":"containers/kubernetes.html#node","title":"Node","text":"

Nodes are the worker machines in kubernetes. The node components are:

"},{"location":"containers/kubernetes.html#kubernetes-components","title":"Kubernetes Components","text":""},{"location":"containers/kubernetes.html#pod","title":"Pod","text":"

Pods are the smallest unit in kubernetes. They are an abstraction over a set of running containers. The pod abstraction is used to make kubernetes independent from the container technology.

Each pod has it's own IP address inside the virtual network of the cluster; this makes pod communication possible. Since pods are ephemeral resources when a pod dies another one will replace it. The new pod will get a new IP address.

"},{"location":"containers/kubernetes.html#service","title":"Service","text":"

Services are permanent IP addresses and ar used to resolve the issue of changing pod IPs. Each pod can be attached to a service. The lifecycle of a service is detached from a pod. External services are used to make the contents of a pod accessible from the outside of the cluster while internal services are not exposed.

"},{"location":"containers/kubernetes.html#ingress","title":"Ingress","text":"

Ingresses are the components hat forwards external requests to specific services. Ingresses are used to expose services through secure protocols and friendly URLs instead of service IPs.

"},{"location":"containers/kubernetes.html#configmap","title":"ConfigMap","text":"

ConfigMaps are external configurations used to store non-confidential data in key-value pairs. Pods can consume ConfigMaps as environment variables, command-line arguments, or as configuration files in a volume.

ConfigMaps allow to decouple environment-specific configuration from container images, so that applications are easily portable.

"},{"location":"containers/kubernetes.html#secret","title":"Secret","text":"

Secrets contains a small amount of sensitive data such as a password, a token, or a key. Such information might otherwise be put in a Pod specification or in a container image.

Secrets are similar to ConfigMaps but are specifically intended to hold confidential data.

Because Secrets can be created independently of the Pods that use them, there is less risk of the Secret (and its data) being exposed during the workflow of creating, viewing, and editing Pods.

Warn: secrets, by default, are not encrypted: they are stored in base64. Consider using third-party encryption tools.

"},{"location":"containers/kubernetes.html#volumes","title":"Volumes","text":"

Volumes are physical storage attached to a pod in order to persist data when a pod is shut down.

Warn: kubernetes does not manage data persistance. Backups must be managed externally.

"},{"location":"containers/kubernetes.html#deployment","title":"Deployment","text":"

Deployments are a description of the desired state of the cluster. The deployment controller changes the actual state to match the desired one.

Deployments can be used to manage the scaling of the replicas of a pod.

"},{"location":"containers/kubernetes.html#replicaset","title":"ReplicaSet","text":"

ReplicaSets are groups of identical pods and are used to guarantee the availability of the replicated application. ReplicaSets are used to manage stateless applications.

"},{"location":"containers/kubernetes.html#statefulset","title":"StatefulSet","text":"

StatefulSets are group of pods with guarantees about the ordering and uniqueness of the pods. StatefulSets are used to manage pods that need consistent state like databases.

"},{"location":"containers/kubernetes.html#daemonset","title":"DaemonSet","text":"

DaemonSets ensure the all or some nodes in a cluster run a copy of a specific pod.

"},{"location":"containers/kubernetes.html#jobs","title":"Jobs","text":"

Jobs create one or more Pods and will continue to retry execution of the Pods until a specified number of them successfully terminate.

As pods successfully complete, the Job tracks the successful completions. When a specified number of successful completions is reached, the task is complete.

"},{"location":"containers/kubernetes.html#kubernetes-configuration","title":"Kubernetes Configuration","text":"

Each kubernetes configuration file is composed by 3 parts:

Note: kubernetes config files are written in YAML

"},{"location":"containers/kubernetes.html#kubectl","title":"kubectl","text":""},{"location":"containers/kubernetes.html#kubectl-get","title":"kubectl get","text":"Bash
kubectl config get-contexts  # list available contexts\n\nkubectl get namespaces  # list namespaces inside current context\n\nkubectl get pod -n|--namespace <namespace>  # list pods inside namespace\nkubectl get pod [-n|--namespace <namespace>] <pod> -o|--output jsonpath='{.spec.containers[*].name}'  # list containers inside pod\n
"},{"location":"containers/kubernetes.html#kubectl-exec","title":"kubectl exec","text":"Bash
kubectl exec [-i|--stdin] [-t|--tty] [-n|--namespace <namespace>] <pod> [-c|--container <container>] -- <command>  # execute a command inside a container\n
"},{"location":"containers/kubernetes.html#kubectl-logs","title":"kubectl logs","text":"Bash
kubectl logs [-f|--follow] [-n|--namespace <namespace>] <pod> [-c|--container]  # get pod/container logs\n
"},{"location":"databases/mongo-db.html","title":"MongoDB","text":"

The database is a container of collections. The collections are containers of documents.

The documents are schema-less that is they have a dynamic structure that can change between documents in the same collection.

"},{"location":"databases/mongo-db.html#data-types","title":"Data Types","text":"Type Example Value Function Text \"Text\" Boolean true Number 42 Objectid \"_id\": {\"$oid\": \"<id>\"} ObjectId(\"<id>\") ISODate \"<key>\": {\"$date\": \"YYYY-MM-DDThh:mm:ss.sssZ\"} ISODate(\"YYYY-MM-DD\") Timestamp Timestamp(11421532) Embedded Document {\"a\": {...}} Embedded Array {\"b\": [...]}

It's mandatory for each document ot have an unique field _id. MongoDB automatically creates an ObjectId() if it's not provided.

"},{"location":"databases/mongo-db.html#databases-collections-usage","title":"Databases & Collections Usage","text":"

To create a database is sufficient to switch towards a non existing one with use <database> (implicit creation). The database is not actually created until a document is inserted.

Bash
show dbs  # list all databases\nuse <database>  # use a particular database\nshow collections  # list all collection for the current database\n\ndbs.dropDatabase()  # delete current database\n\ndb.createCollection(name, {options})  # explicit collection creation\ndb.<collection>.insertOne({document})  # implicit collection creation\n
"},{"location":"databases/mongo-db.html#operators-mql-syntax","title":"Operators (MQL Syntax)","text":"JSON
/* --- Update operators --- */\n{ \"$inc\":  { \"<key>\": \"<increment>\", ... } }  // increment value\n{ \"$set\":  { \"<key>\": \"<value>\", ... } }  // set value\n{ \"$unsetset\":  { \"<key>\": \"true\", ... } }  // unset value\n{ \"$push\": { \"<key>\": \"<value>\", ... } }  // add a value to an array field or turn field into array\n{ \"$pop\": { \"<key>\": <-1 | 1>, ... } }  // remove first or last array element\n{ \"$pull\": { \"<key>\": \"<value | condition>\", ... } }  // remove a specific item in the array\n{ \"$pullAll\": { \"<key>\": [ \"<value1>\", \"<value2>\" ... ], ... } }  // remove all specified values from array\n\n/* --- Query Operators --- */\n{ \"<key>\": { \"$in\": [ \"<value_1>\", \"<value_2>\", ...] } } // Membership\n{ \"<key>\": { \"$nin\": [ \"<value_1>\", \"<value_2>\", ...] } }  // Membership\n{ \"<key>\": { \"$exists\": true } }  // Field Exists\n\n/* --- Comparison Operators (DEFAULT: $eq) --- */\n{ \"<key>\": { \"$gt\":  \"<value>\" }}  // >\n{ \"<key>\": { \"$gte\": \"<value>\" }}  // >=\n{ \"<key>\": { \"$lt\":  \"<value>\" }}  // <\n{ \"<key>\": { \"$lte\": \"<value>\" }}  // <=\n{ \"<key>\": { \"$eq\":  \"<value>\" }}  // ==\n{ \"<key>\": { \"$ne\":  \"<value>\" }}  // !=\n\n/* --- Logic Operators (DEFAULT $and) --- */\n{ \"$and\": [ { \"<expression>\" }, ...] }\n{ \"$or\":  [ { \"<expression>\" }, ...] }\n{ \"$nor\": [ { \"<expression>\" }, ...] }\n{ \"$not\": { \"<expression>\" } }\n\n/* --- Array Operators --- */\n{ \"<key>\": { \"$all\": [\"value>\", \"<value>\", ...] } } // field contains all values\n{ \"<key>\": { \"$size\": \"<value>\" } }\n{ \"<array-key>\": { \"$elemMatch\": { \"<item-key>\": \"<expression>\" } } }  // elements in array must match an expression\n\n/* --- REGEX Operator --- */\n{ \"<key>\": { \"$regex\": \"/pattern/\", \"$options\": \"<options>\" } }\n{ \"<key>\": { \"$regex\": \"pattern\", \"$options\": \"<options>\" } }\n{ \"<key>\": { \"$regex\": \"/pattern/<options>\" } }\n{ \"<key>\": \"/pattern/<options>\" }\n
"},{"location":"databases/mongo-db.html#expressive-query-operator","title":"Expressive Query Operator","text":"

Note: $<key> is used to access the value of the field dynamically

JSON
{ \"$expr\": { \"<expression>\" } }  // aggregation expression, variables, conditional expressions\n{ \"$expr\":  { \"$<comparison_operator>\": [ \"$<key>\", \"$<key>\" ] } }  // compare field values (operators use aggregation syntax)\n
"},{"location":"databases/mongo-db.html#mongo-query-language-mql","title":"Mongo Query Language (MQL)","text":""},{"location":"databases/mongo-db.html#insertion","title":"Insertion","text":"

It's possible to insert a single document with the command insertOne() or multiple documents with insertMany().

Insertion results:

Bash
# explicit collection creation, all options are optional\ndb.createCollection( <name>,\n   {\n        capped: <boolean>,\n        autoIndexId: <boolean>,\n        size: <number>,\n        max: <number>,\n        storageEngine: <document>,\n        validator: <document>,\n        validationLevel: <string>,\n        validationAction: <string>,\n        indexOptionDefaults: <document>,\n        viewOn: <string>,\n        pipeline: <pipeline>,\n        collation: <document>,\n        writeConcern: <document>\n   }\n)\n\ndb.createCollection(\"name\", { capped: true, size: max_bytes, max: max_docs_num } )  # creation of a capped collection\n# SIZE: int - will be rounded to a multiple of 256\n\n# implicit creation at doc insertion\ndb.<collection>.insertOne({ document }, options)  # insert a document in a collection\ndb.<collection>.insertMany([ { document }, { document }, ... ], options)  # insert multiple docs\ndb.<collection>.insertMany([ { document }, { document } ] , { \"ordered\": false })  # allow the unordered insertion, only documents that cause errors wont be inserted\n

Note: If insertMany() fails the already inserted documents are not rolled back but all the successive ones (even the correct ones) will not be inserted.

"},{"location":"databases/mongo-db.html#querying","title":"Querying","text":"Bash
db.<collection>.findOne()  # find only one document\ndb.<collection>.find(filter)  # show selected documents\ndb.<collection>.find().pretty()  # show documents formatted\ndb.<collection>.find().limit(n)  # show n documents\ndb.<collection>.find().limit(n).skip(k)  # show n documents skipping k docs\ndb.<collection>.find().count()  # number of found docs\ndb.<collection>.find().sort({ \"<key-1>\": 1, ... , \"<key-n>\": -1 })  # show documents sorted by specified keys in ascending (1) or descending (-1) order\n\n# projection\ndb.<collection>.find(filter, { \"<key>\": 1 })  # show selected values form documents (1 or true => show, 0 or false => don't show, cant mix 0 and 1)\ndb.<collection>.find(filter, { _id: 0, \"<key>\": 1 })  # only _id can be set to 0 with other keys at 1\ndb.<collection>.find(filter, { \"<array-key>\": { \"$elemMatch\": { \"<item-key>\": \"<expression>\" } } })  # project only elements matching the expression\n\n# sub documents & arrays\ndb.<collection>.find({ \"<key>.<sub-key>.<sub-key>\": \"<expression>\" })\ndb.<collection>.find({ \"<array-key>.<index>.<sub-key>\": \"<expression>\" })\n\n# GeoJSON - https://docs.mongodb.com/manual/reference/operator/query/near/index.html\ndb.<collection>.find(\n    {\n        <location field>: {\n            $near: {\n                $geometry: { type: \"Point\", coordinates: [ <longitude> , <latitude> ] },\n                $maxDistance: <distance in meters>,\n                $minDistance: <distance in meters>\n            }\n        }\n    }\n)\n\ndb.<collection>.find().hint( { \"<key>\": 1 } )  # specify the index\ndb.<collection>.find().hint( \"index-name\" )  # specify the index using the index name\n\ndb.<collection>.find().hint( { $natural : 1 } )  # force the query to perform a forwards collection scan\ndb.<collection>.find().hint( { $natural : -1 } )  # force the query to perform a reverse collection scan\n

Note: { <key>: <value> } in case of a field array will match if the array contains the value

"},{"location":"databases/mongo-db.html#updating","title":"Updating","text":"

Update Operators

Bash
db.<collection>.replaceOne(filter, update, options)\ndb.<collection>.updateOne(filter, update, {upsert: true})  # modify document if existing, insert otherwise\n\ndb.<collection>.updateOne(filter, { \"$push\": { ... }, \"$set\": { ... }, { \"$inc\": { ... }, ... } })\n
"},{"location":"databases/mongo-db.html#deletion","title":"Deletion","text":"Bash
db.<collection>.deleteOne(filter, options)\ndb.<collection>.deleteMany(filter, options)\n\ndb.<collection>.drop()  # delete whole collection\ndb.dropDatabase()  # delete entire database\n
"},{"location":"databases/mongo-db.html#mongodb-database-tools","title":"MongoDB Database Tools","text":""},{"location":"databases/mongo-db.html#mongoimport","title":"Mongoimport","text":"

Utility to import all docs into a specified collection. If the collection already exists --drop deletes it before reuploading it. WARNING: CSV separators must be commas (,)

Bash
mongoimport <options> <connection-string> <file>\n\n--uri=<connectionString>\n--host=<hostname><:port>, -h=<hostname><:port>\n--username=<username>, -u=<username>\n--password=<password>, -p=<password>\n--collection=<collection>, -c=<collection>  # Specifies the collection to import.\n--ssl  # Enables connection to a mongod or mongos that has TLS/SSL support enabled.\n--type <json|csv|tsv>  # Specifies the file type to import. DEFAULT: json\n--drop  # drops the collection before importing the data from the input.\n--headerline  # if file is CSV and first line is header\n--jsonarray  # Accepts the import of data expressed with multiple MongoDB documents within a single json array. MAX 16 MB\n
"},{"location":"databases/mongo-db.html#mongoexport","title":"Mongoexport","text":"

Utility to export documents into a specified file.

Bash
mongoexport --collection=<collection> <options> <connection-string>\n\n--uri=<connectionString>\n--host=<hostname><:port>, -h=<hostname><:port>\n--username=<username>, -u=<username>\n--password=<password>, -p=<password>\n--db=<database>, -d=<database>\n--collection=<collection>, -c=<collection>\n--type=<json|csv>\n--out=<file>, -o=<file>  #Specifies a file to write the export to. DEFAULT: stdout\n--jsonArray  # Write the entire contents of the export as a single json array.\n--pretty  # Outputs documents in a pretty-printed format JSON.\n--skip=<number>\n--limit=<number>  # Specifies a maximum number of documents to include in the export\n--sort=<JSON>  # Specifies an ordering for exported results\n
"},{"location":"databases/mongo-db.html#mongodump-mongorestore","title":"Mongodump & Mongorestore","text":"

mongodump exports the content of a running server into .bson files.

mongorestore Restore backups generated with mongodump to a running server.

"},{"location":"databases/mongo-db.html#indexes","title":"Indexes","text":"

Indexes support the efficient execution of queries in MongoDB.

Without indexes, MongoDB must perform a collection scan (COLLSCAN): scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect (IXSCAN).

Indexes are special data structures that store a small portion of the collection's data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.

Indexes slow down writing operations since the index must be updated at every writing.

"},{"location":"databases/mongo-db.html#index-types","title":"Index Types","text":"

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. The index skips over any document that is missing the indexed field.

"},{"location":"databases/mongo-db.html#diagnosis-and-query-planning","title":"Diagnosis and query planning","text":"Bash
db.<collection>.find({...}).explain()  # explain won't accept other functions\ndb.explain().<collection>.find({...})  # can accept other functions\ndb.explain(\"executionStats\").<collection>.find({...})  # more info\n
"},{"location":"databases/mongo-db.html#index-creation","title":"Index Creation","text":"Bash
db.<collection>.createIndex( <key and index type specification>, <options> )\n\ndb.<collection>.createIndex( { \"<key>\": <type>, \"<key>\": <type>, ... } )  # normal, compound or multikey (field is array) index\ndb.<collection>.createIndex( { \"<key>\": \"text\" } )  # text index\ndb.<collection>.createIndex( { \"<key>\": 2dsphere } )  # geospatial 2dsphere index\n\n# sparse index\ndb.<collection>.createIndex(\n    { \"<key>\": <type>, \"<key>\": <type>, ... },\n    { sparse: true }  # sparse option\n)\n\n# custom name\ndb.<collection>.createIndex(\n  { <key and index type specification>, },\n  { name: \"index-name\" }  # name option\n)\n
"},{"location":"databases/mongo-db.html#index-management","title":"Index Management","text":"Bash
# view all db indexes\ndb.getCollectionNames().forEach(function(collection) {\n   indexes = db[collection].getIndexes();\n   print(\"Indexes for \" + collection + \":\");\n   printjson(indexes);\n});\ndb.<collection>.getIndexes()  # view collection's index\n\ndb.<collection>.dropIndexes()  # drop all indexes\ndb.<collection>.dropIndex( { \"index-name\": 1 } )  # drop a specific index\n
"},{"location":"databases/mongo-db.html#cluster-administration","title":"Cluster Administration","text":""},{"location":"databases/mongo-db.html#mongod","title":"mongod","text":"

mongod is the main deamon process for MongoDB. It's the core process of the database, handling connections, requests and persisting the data.

mongod default configuration:

mongod config file mongod command line options

"},{"location":"databases/mongo-db.html#basic-shell-helpers","title":"Basic Shell Helpers","text":"Bash
db.<method>()  # database interaction\ndb.<collection>.<method>()  # collection interaction\nrs.<method>();  # replica set deployment and management\nsh.<method>();  # sharded cluster deployment and management\n\n# user management\ndb.createUser()\ndb.dropUser()\n\n# collection management\ndb.renameCollection()\ndb.<collection>.createIndex()\ndb.<collection>.drop()\n\n# database management\ndb.dropDatabase()\ndb.createCollection()\n\n# database status\ndb.serverStatus()\n\n# database command (underlying to shell helpers and drivers)\ndb.runCommand({ \"<COMMAND>\" })\n\n# help\ndb.commandHelp(\"<command>)\n
"},{"location":"databases/mongo-db.html#logging","title":"Logging","text":"

The process log displays activity on the MongoDB instance and collects activities of various components:

Log Verbosity Level:

Bash
db.getLogComponents()  # get components and their verbosity\ndb.adminCommand({\"getLog\": \"<scope>\"})  # retrieve logs (getLog must be run on admin db -> adminCommand)\ndb.setLogLevel(<level>, \"<component>\");  # set log level (output is OLD verbosity levels)\n\ntail -f /path/to/mongod.log  # read end og log file\n

Note: Log Message Structure: <timestamp> <severity-level> <component> <connection> <event> ...

"},{"location":"databases/mongo-db.html#database-profiling","title":"Database Profiling","text":"

Profiling Levels:

Events captured by the profiler:

Note: Logs are saved in the system.profile capped collection.

Bash
db.setProfilingLevel(n)  # set profiler level\ndb.setProfilingLevel(1, { slowms: <ms> })\ndb.getProfilingStatus()  # check profiler status\n\ndb.system.profile.find().limit(n).sort( {} ).pretty()  # see logs\ndb.system.profile.find().limit(n).sort( { ts : -1 } ).pretty()  # sort by decreasing timestamp\n
"},{"location":"databases/mongo-db.html#authentication","title":"Authentication","text":"

Client Authentication Mechanisms:

"},{"location":"databases/mongo-db.html#authorization-role-based-access-control-rbac","title":"Authorization: Role Based Access Control (RBAC)","text":"

Each user has one or more Roles. Each role has one or more Privileges. A privilege represents a group of actions and the resources those actions apply to.

By default no user exists so the ONLY way to act is to connect locally to the server. This is the \"localhost exception\" and it closes after the first user is created.

Warn: Always create an admin user first (ideally with the userAdmin role)

Role's Resources:

Role's Privileges: { resource: { <resource> }, actions: [ \"<action>\" ] }

A role can inherit from multiple others and can define network restrictions such as Server Address and Client Source.

Built-in Roles Groups and Names:

Bash
db.createUser({\n    user: \"<username>\",\n    pwd: \"<password>\",\n    roles: [ { role: \"<role>\", db: \"<database>\" } ]\n})\n\ndb.createRole({\n    role: \"<role>\",\n    privileges: [\n        { resource: { cluster: true }, actions: [ \"<action>\", ... ] },\n        {\n            resource: { \n                db: \"<database>\",\n                collection: \"<collection>\"\n            },\n            actions: [ \"<action>\", ... ]\n        },\n    ],\n    roles: [\n        { role: \"<role>\", db: \"<database>\" }  # inherited permissions\n    ]\n})\n\n# add role to existing user\ndb.grantRolesToUser(\n    \"<user>\",\n    [\n        { \n            role: \"<role>\"\n            db: \"<database>\",\n            collection: \"<collection>\",\n        }\n    ]\n)\n\n# show role privileges\ndb.runCommand({\n    rolesInfo: { db: \"<database>\", role: \"<role>\" },\n    showPrivileges: true \n})\n
"},{"location":"databases/mongo-db.html#replica-set","title":"Replica set","text":"

A replica set in MongoDB is a group of mongod processes that maintain the same dataset. Replica sets provide redundancy and high availability, and are the basis for all production deployments.

"},{"location":"databases/mongo-db.html#sharding","title":"Sharding","text":"

Sharding is a MongoDB concept through which big datasets are subdivided in smaller sets and distributed towards multiple instances of MongoDB. It's a technique used to improve the performances of large queries towards large quantities of data that require al lot of resources from the server.

A collection containing several documents is splitted in more smaller collections (shards) Shards are implemented via cluster that are none other a group of MongoDB instances.

Shard components are:

"},{"location":"databases/mongo-db.html#aggregation-framework","title":"Aggregation Framework","text":"

Sequence of operations applied to a collection as a pipeline to get a result: db.collection.aggregate(pipeline, options). Each step of the pipeline acts on its inputs and not on the original data in the collection.

"},{"location":"databases/mongo-db.html#variables","title":"Variables","text":"

Variable syntax in aggregations:

"},{"location":"databases/mongo-db.html#match-aggregation-stage","title":"$match Aggregation Stage","text":"

Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.

Bash
db.<collection>.aggregate([ \n    { \"$match\": { \"<query>\" } },\n\n    # key exists and is an array\n    { $match: { \"<array-key>\": { $elemMatch: { $exists: true } } } }\n})\n

Note: $match can contain the $text query operation but it must ber the first in a pipeline Note: $match cannot contain use $where Note: $match uses the same syntax as find()

"},{"location":"databases/mongo-db.html#project-aggregation-stage","title":"$project Aggregation Stage","text":"

Passes along the documents with the requested fields to the next stage in the pipeline. The specified fields can be existing fields from the input documents or newly computed fields.

$project Array Expression Operators:

$project Arithmetic Expression Operators:

Bash
db.<collection>.aggregate([ \n     { \n        \"$project\": { \n            \"_id\": 0,  # discard value\n            \"<key>\": 1,  # keep value\n            \"<key>\": \"$<other-key>\"  # reassign or create field,\n            \"<key>\": { \"<expression>\" } # calculate field value.\n\n            # filter elements in an array\n            \"<key>\": {\n                \"$filter\": {\n                    \"input\": \"$<array-key>\",\n                    \"as\": \"<name-of-item>\",\n                    \"cond\": { \"<bool-expression>\" }\n                }\n            },\n\n            # transform array items\n            \"<key>\": {\n                \"$map\": {\n                    \"input\": \"$<array-key>\",\n                    \"as\": \"<item>\",\n                    \"in\": { \"<expression>\" }\n                    # $$<item> is the current item's value\n                }\n            }\n\n            # apply expression to each element in an array and combine them\n            \"<key>\": {\n                \"$reduce\": {\n                    \"input\": \"<array-key>\",\n                    \"initialValue\": \"<value>\",\n                    \"in\": { \"<expression>\" }\n                    # $$this is current document, $$value is current accumulated value\n                }\n            }\n        }\n    } \n])\n
"},{"location":"databases/mongo-db.html#addfields-aggregation-stage","title":"$addFields Aggregation Stage","text":"

Adds new fields to documents (can be result of computation). $addFields outputs documents that contain all existing fields from the input documents and newly added fields.

Bash
db.<collection>.aggregate({\n    { $addFields: { <newField>: <expression>, ... } }\n})\n
"},{"location":"databases/mongo-db.html#group-aggregation-stage","title":"$group Aggregation Stage","text":"

The $group stage separates documents into groups according to a \"group key\". The output is one document for each unique group key.

Bash
db.<collection>.aggregate([ \n     { \n        \"$group\": {\n            \"_id\": \"<expression>\",  # Group By Expression (Required)\n            \"<key-1>\": { \"<accumulator-1>\": \"<expression-1>\" },\n            ...\n        } \n    }\n])\n
"},{"location":"databases/mongo-db.html#unwind-aggregation-stage","title":"$unwind Aggregation Stage","text":"

Deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element

Bash
db.<collection>.aggregate([ \n     { \"$unwind\": \"<array-key>\" }\n\n     { \n        \"$unwind\": {\n            \"path\": \"<array-key>\",  # array to unwind\n            \"includeArrayIndex\": \"<string>\",  # name of index field\n            \"preserveNullAndEmptyArrays\": <bool>\n        } \n     }\n], { \"allowDiskUse\": <bool> })\n
"},{"location":"databases/mongo-db.html#count-aggregation-stage","title":"$count Aggregation Stage","text":"Bash
db.<collection>.aggregate([ \n     { \"$count\": \"<count-key>\" }\n])\n
"},{"location":"databases/mongo-db.html#sort-aggregation-stage","title":"$sort Aggregation Stage","text":"Bash
db.<collection>.aggregate([ \n     { \n        \"$sort\": { \n            \"<key-1>\": \"<sort order>\", \n            \"<key-2>\": \"<sort order>\", \n            ... \n        } \n    }\n], { \"allowDiskUse\": <bool> })\n

Note: can take advantage of indexes if early int the pipeline and before any %project, $group and $unwind Note: By default $sort will use up to 10 MB of RAM. Setting allowDiskUse: true will allow for larger sorts

"},{"location":"databases/mongo-db.html#skip-aggregation-stage","title":"$skip Aggregation Stage","text":"Bash
db.<collection>.aggregate([ \n     { \"$skip\": \"<positive 64-bit integer>\" }\n])\n
"},{"location":"databases/mongo-db.html#limit-aggregation-stage","title":"$limit Aggregation Stage","text":"Bash
db.<collection>.aggregate([ \n     { \"$limit\": \"<positive 64-bit integer>\" }\n])\n
"},{"location":"databases/mongo-db.html#lookup-aggregation-stage","title":"$lookup Aggregation Stage","text":"

Performs a left outer join to a collection in the same database to filter in documents from the \"joined\" collection for processing. The $lookup stage adds a new array field to each input document. The new array field contains the matching documents from the \"joined\" collection.

Note: To combine elements from two different collections, use the $unionWith pipeline stage.

Bash
db.<collection>.aggregate([ \n    {\n        \"$lookup\": {\n            \"from\": \"<foreign-collection>\",\n            \"localField\": \"<key>\",\n            \"foreignField\": \"<foreign-collection>.<key>\",\n            \"as\": \"<output array field>\"\n        }\n    }\n])\n
"},{"location":"databases/mongo-db.html#graphlookup-aggregation-stage","title":"$graphLookup Aggregation Stage","text":"

Performs a recursive search on a collection, with options for restricting the search by recursion depth and query filter.

The collection on which the aggregation is performed and the from collection can be the same (in-collection search) or different (cross-collection search)

Bash
db.<collection>.aggregate([\n    {\n        $graphLookup: {\n            from: <collection>,  # starting collection of the search\n            startWith: <expression>,  # initial value(s) of search\n            connectFromField: <string>,  # source of the connection\n            connectToField: <string>,  # destination of the connection\n            as: <string>,  # array of found documents\n            maxDepth: <number>,  # recursive search depth limit (steps inside from collection)\n            depthField: <string>,  # field containing distance from start\n            restrictSearchWithMatch: <document>  # filter on found documents\n        }\n    }\n], { allowDiskUse: true })\n

Note: Having the connectToField indexed will improve search performance Warn: Can exceed the 100 Mb memory limit even with { allowDiskUse: true }

"},{"location":"databases/mongo-db.html#sortbycount-aggregation-stage","title":"$sortByCount Aggregation Stage","text":"

Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.

Each output document contains two fields: an _id field containing the distinct grouping value, and a count field containing the number of documents belonging to that grouping or category.

The documents are sorted by count in descending order.

Bash
db.<collection>.aggregate([\n    { $sortByCount:  <expression> }\n])\n
"},{"location":"databases/redis.html","title":"Redis","text":"

Redis is in the family of databases called key-value stores.

The essence of a key-value store is the ability to store some data, called a value, inside a key. This data can later be retrieved only if we know the exact key used to store it.

Often Redis it is called a data structure server because it has outer key-value shell, but each value can contain a complex data structure, such as a string, a list, a hashes, or ordered data structures called sorted sets as well as probabilistic data structures like hyperloglog.

"},{"location":"databases/redis.html#redis-commands","title":"Redis Commands","text":""},{"location":"databases/redis.html#server-startup","title":"Server Startup","text":"Bash
redis-server  # start the server\nredis-cli\n
"},{"location":"databases/redis.html#key-value-pairs","title":"Key-Value Pairs","text":"Bash
SET <key> <value> [ EX <seconds> ] # store a key-value pair, TTL optional\nGET <key>  # read a key content\nEXISTS <key>  # check if a key exists\nDEL <key>  # delete a key-value pair\n\nINCR <key>  # atomically increment a number stored at a given key\nINCRBY <key> <amount>  # increment the number contained inside a key by a specific amount\nDECR <key>\nDECRBY <key> <amount>\n\n# re-setting the key will make it permanent (TTL -1)\nEXPIRE <key> <seconds>  # make the key expire after <second> seconds\nTTL <key>  # see remaining seconds before expiry\nPEXPIRE <key> <seconds>  # make the key expire after <second> milli-seconds\nPTTL <key>  # see remaining milli-seconds before expiry\nPERSIST <key>  # make the key permanent\n
"},{"location":"databases/redis.html#lists","title":"Lists","text":"

A list is a series of ordered values.

Bash
RPUSH <key> <value1> <value2> ... # add one or more values to the end of the list\nLPUSH <key> <value1> <value2> ...  # add one or more values to the start of a list\n\nLLEN  # number of items in the list\nLRANGE <key> <start_index> <end_index>  # return a subset of the list, end index included. Negative indexes count backwards from the end\n\nLPOP  # remove and return the first item fro the list\nRPOP  # remove and return the last item fro the list\n
"},{"location":"databases/redis.html#sets","title":"Sets","text":"

A set is similar to a list, except it does not have a specific order and each element may only appear once.

Bash
SADD <key> <value1> <value2> ... # add one or more values to the set (return 0 if values are already inside)\nSREM <key> <value>  # remove the given member from the set, return 1 or 0 to signal if the member was actually there or not.\nSPOP <key> <value>  # remove and return value from the set\n\nSISMEMBER <key> <value>  # test if value is in the set\nSMEMBERS <key>  # lis of all set items\n\nSUINION <key1> <key2> ...  # combine two or more sets and return the list of all elements.\n
"},{"location":"databases/redis.html#sorted-sets","title":"Sorted Sets","text":"

Sets are a very handy data type, but as they are unsorted they don't work well for a number of problems. This is why Redis 1.2 introduced Sorted Sets.

A sorted set is similar to a regular set, but now each value has an associated score. This score is used to sort the elements in the set.

Bash
ZADD <key> <score> <value>  # add a value with it's score\n\nZRANGE <key> <start_index> <end_index>  # return a subset of the sortedSet\n\n...\n
"},{"location":"databases/redis.html#hashes","title":"Hashes","text":"

Hashes are maps between string fields and string values, so they are the perfect data type to represent objects.

Bash
HSET <key> <field> <value> [ <field> <value> ... ] # set the string of a hash field\nHSETNX <key> <field> <value>  # set the value of a hash field, only if the field does not exist\n\nHEXISTS <key> <field>  # determine if a hash field exists\n\nHLEN <key>  # get the number of fields in a hash\nHSTRLEN <key> <field>  # get the length of the value of a hash field\nHGETALL <key>  # get all fields and values in a hash\nHGET <key> <field>  # get data on a single field\nHKEYS <key>  # get all the fields in a hash\nHVALS <key>  # get all the values in a hash\n\nHDEL <key> <field_1> <field_2> ...  # delete one or more field hashes\n\nHMGET <key> <field> [<field> ...]  # get the values of all the given hash fields\nHMSET <key> <field> <value> [<field> <value> ...]  # set multiple hash fields to multiple values\n\nHINCRBY <key> <field> <amount>  # increment the integer value of a hash field by the given number\nHINCRBYFLOAT <key> <field> <amount> # increment the float value of a hash field by the given amount\n\nHSCAN <key> <cursor> [MATCH <pattern>] [COUNT <count>]  # incrementally iterate hash fields and associated values\n
"},{"location":"databases/sql.html","title":"SQL","text":""},{"location":"databases/sql.html#ddl","title":"DDL","text":"SQL
show databases;    -- mostra database\nCREATE DATABASE <database>;    -- database creation\nuse <database_name>;    -- usa un database particolare\nexit;    -- exit mysql\n\nshow tables;    -- mostra tabelle del database\n\n-- INLINE COMMENT\n/* MULTI-LINE COMMENT */\n
"},{"location":"databases/sql.html#table-creation","title":"Table Creation","text":"SQL
CREATE TABLE <table_name>\n    (<field_name> <field_type> <option>,\n    ...);\n
"},{"location":"databases/sql.html#primary-key-from-multiple-fields","title":"PRIMARY KEY from multiple fields","text":"SQL
CREATE TABLE <table_name>(\n    ...,\n    PRIMARY KEY (<field1>, ...),\n);\n
"},{"location":"databases/sql.html#table-field-options","title":"Table Field Options","text":"SQL
PRIMARY KEY -- marks primary key as field option\nNOT NULL -- marks a necessary field\nREFERENCES <table> (<field>) -- adds foreign key reference\nUNIQUE (<field>) -- set field as unique (MySQL)\n<field> UNIQUE -- T-SQL\n
"},{"location":"databases/sql.html#table-modification","title":"Table Modification","text":"SQL
ALTER TABLE <table>\n    ADD PRIMARY KEY (<field>, ...),    -- definition of PK after table creation\n    ADD <field_name> <field_type> <option>;    -- addition of a new field, field will have no value in the table\n\nALTER TABLE <table>\n    CHANGE <field_name> <new_name> <new_type>;\n    ALTER COLUMN <field_name> <new_name> <new_type>;    -- T-SQL\n\nALTER TABLE <table>\n    DROP <field>;\n\nALTER TABLE <table>\n    ADD FOREIGN KEY (<field>) REFERENCES <TABLE> (<FIELD>);\n
"},{"location":"databases/sql.html#dml","title":"DML","text":""},{"location":"databases/sql.html#data-insertion","title":"Data Insertion","text":"SQL
INSERT INTO <table> (field_1, ...) VALUES (value_1, ...), (value_1, ...);\nINSERT INTO <table> VALUES (value_1, ...), (value_1, ...);    -- field order MUST respect tables's columns order\n
"},{"location":"databases/sql.html#data-update","title":"Data Update","text":"SQL
UPDATE <table> SET <field> = <value>, <field> = <value>, ... WHERE <condition>;\n
"},{"location":"databases/sql.html#data-elimination","title":"Data Elimination","text":"SQL
DELETE FROM <table> WHERE <condition>\nDELETE FROM <table> -- empty the table\n
"},{"location":"databases/sql.html#data-selection","title":"Data Selection","text":"

*: denotes all table fields

SQL
SELECT * FROM <table>;    -- show table contents\nSHOW columns FROM <table>;    -- show table columns\nDESCRIBE <table>;    -- shows table\n
"},{"location":"databases/sql.html#alias","title":"Alias","text":"SQL
SELECT <field> as <alias>; -- shows <field/funzione> with name <alias>\n
"},{"location":"databases/sql.html#conditional-selection","title":"Conditional Selection","text":"SQL
SELECT * FROM <table> WHERE <condition>;    -- shows elements that satisfy the condition\nAND, OR, NOT    -- logic connectors\n\nSELECT * FROM <table> WHERE <field> Between <value_1> AND <value_2>;\n
"},{"location":"databases/sql.html#ordering","title":"Ordering","text":"SQL
SELECT * FROM <table> ORDER BY <field>, ...;    -- shows the table ordered by <field>\nSELECT * FROM <table> ORDER BY <field>, ... DESC;    -- shows the table ordered by <field>, decreasing order\nSELECT * FROM <table> ORDER BY <field>, ... LIMIT n;    -- shows the table ordered by <field>, shows n items\nSELECT TOP(n) * FROM <table> ORDER BY <field>, ...;    -- T-SQL\n
"},{"location":"databases/sql.html#grouping","title":"Grouping","text":"SQL
SELECT * FROM <table> GROUP BY <field>;\nSELECT * FROM <table> GROUP BY <field> HAVING <condition>;\nSELECT DISTINCT <field> FROM <table>;    -- shows elements without repetitions\n
"},{"location":"databases/sql.html#ricerca-caratteri-in-valori","title":"Ricerca caratteri in valori","text":"

%: any number of characters

SQL
SELECT * FROM <table> WHERE <field> LIKE '<char>%';    -- selects items in <field> that start with <char>\nSELECT * FROM <table> WHERE <field> LIKE '%<char>';    -- selects items in <field> that end with <char>\nSELECT * FROM <table> WHERE <field> LIKE '%<char>%';    -- selects items in <field> that contain <char>\nSELECT * FROM <table> WHERE <field> NOT LIKE '%<char>%';    -- selects items in <field> that do not contain <char>\n
"},{"location":"databases/sql.html#selection-from-multiple-tables","title":"Selection from multiple tables","text":"SQL
SELECT a.<field>, b.<field> FROM <table> AS a, <table> AS b\n    WHERE a.<field> ...;\n
"},{"location":"databases/sql.html#functions","title":"Functions","text":"SQL
SELECT COUNT(*) FROM <field>;    -- count of items in <field>\nSELECT MIN(*) FROM <table>;    -- min value\nSELECT MAX(*) FROM <table>;    -- max value\nSELECT AVG(*) FROM <table>;    -- mean of values\nALL (SELECT ...)\nANY (SELECT ...)\n
"},{"location":"databases/sql.html#nested-queries","title":"Nested Queries","text":"SQL
SELECT * FROM <table> WHERE EXISTS (SELECT * FROM <table>)  -- selected field existing in subquery\nSELECT * FROM <table> WHERE NOT EXISTS (SELECT * FROM <table>)  -- selected field not existing in subquery\n
"},{"location":"databases/sql.html#new-table-from-data","title":"New table from data","text":"

Create new table with necessary fields:

SQL
CREATE TABLE <table> (\n    (<field_name> <field_type> <option>,\n    ...);\n)\n

Fill fields with data from table:

SQL
INSERT INTO <table>\n    SELECT <fields> FROM <TABLE> WHERE <condition>;\n
"},{"location":"databases/sql.html#join","title":"Join","text":"SQL
SELECT * FROM <table1> JOIN <table2> ON <table1>.<field> = <table2>.<field>;\nSELECT * FROM <table1> LEFT JOIN <table2> ON <condition>;\nSELECT * FROM <table1> RIGHT JOIN <table2> ON <condition>\n

Inner Join, Left Join, Right Join, Full Outer Join

"},{"location":"databases/sql.html#multiple-join","title":"Multiple Join","text":"SQL
SELECT * FROM <table1>\nJOIN <table2> ON <table1>.<field> = <table2>.<field>\nJOIN <table3> ON <table2>.<field> = <table3>.<field>;\n

char, nchar, varchar, nvarchar

"},{"location":"databases/sql.html#t-sql-mssql-server","title":"T-SQL (MSSQL Server)","text":""},{"location":"databases/sql.html#t-sql-insert-from-table","title":"T-SQL Insert From table","text":"SQL
USE [<db_name>]\n\nSET IDENTITY_INSERT [<destination_table>] ON\n\nINSERT INTO <table> (field_1, ...)\n\nSELECT (field_1, ...) FROM <source_table>\n\nSET IDENTITY_INSERT [<destination_table>] OFF\n
"},{"location":"databases/sql.html#t-sql-parametric-query","title":"T-SQL Parametric Query","text":"SQL
-- variable declaration\nDECLARE @var_name <type>\n\n-- init variable (input parameter)\nSET @var_name = <value>\n\n-- use in query (memorize data)\nSELECT @var_name = COUNT(*)  -- query won't show results in the \"table view\" since param is used in SELECT\nFROM <table> ...\n\n-- display message (query won't show results in the \"table view\")\nPRINT 'Text: ' + @var_name\nPRINT 'Text: ' + CONVERT(type, @var_name)  -- convert data before printing\nGO\n
"},{"location":"databases/sql.html#t-sql-view","title":"T-SQL View","text":"

A view represents a virtual table. Join multiple tables in a view and use the view to present the data as if the data were coming from a single table.

SQL
CREATE VIEW <name> AS\nSELECT * FROM <table> ...\n
"},{"location":"databases/sql.html#t-sql-stored-procedure","title":"T-SQL Stored Procedure","text":"

Stored Procedure How-To T-SQL Stored Procedure

Stored Procedure Definition:

SQL
CREATE PROCEDURE <Procedure_Name>\n    -- Add the parameters for the stored procedure here\n    <@Param1> <Datatype_For_Param1> = <Default_Value_For_Param1>,\n    <@Param2> <Datatype_For_Param2>\nAS\nBEGIN\n    -- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.\n    SET NOCOUNT ON;  -- don't return number of selected rows\n\n    -- Insert statements for procedure here\n    SELECT ...\nEND\nGO\n

Stored Procedure call in query:

SQL
USE <database>\nGO\n\n-- Stored Procedure call\nEXECUTE <Procedure_Name>\n-- or\nEXEC <Procedure_Name>\n
"},{"location":"languages/markdown.html","title":"Markdown Notes","text":""},{"location":"languages/markdown.html#headings","title":"Headings","text":"Markdown
Heading 1\n=========\n\nHeading 2\n---------\n\n# Heading 1\n## Heading 2\n### Heading 3\n
"},{"location":"languages/markdown.html#text-formatting","title":"Text Formatting","text":"Markdown
*Italic*    _Italic_\n**Bold**    __Bold__\n\n~GitHub's strike-trough~\n
"},{"location":"languages/markdown.html#links-images","title":"Links & Images","text":"Markdown
[link text](http://b.org \"title\")\n\n[link text][anchor]\n[anchor]: http://b.org \"title\"\n\n![alt attribute](http://url/b.jpg \"title\")\n\n![alt attribute][anchor]\n[anchor]: http://url/b.jpg \"title\"\n
Markdown
> Blockquote\n\n* unordered list        - unordered list\n* unordered list        - unordered list\n* unordered list        - unordered list\n\n1) ordered list         1. ordered list\n2) ordered list         2. ordered list\n3) ordered list         3. ordered list\n\n- [ ] empty checkbox\n- [x] checked checkbox\n
"},{"location":"languages/markdown.html#horizontal-rule","title":"Horizontal rule","text":"Markdown
---                     ***\n
"},{"location":"languages/markdown.html#code","title":"Code","text":"Markdown
`inline code`\n\n    ```lang\n    multi-line\n    code block\n    ```\n
"},{"location":"languages/markdown.html#table","title":"Table","text":"Markdown
| column label | column label | column label  |\n|:-------------|:------------:|--------------:|\n| left-aligned | centered     | right-aligned |\n| row contents | row contents | row contents  |\n
"},{"location":"languages/assembly/intel.html","title":"Assembly (Intel)","text":""},{"location":"languages/assembly/intel.html#compiling-linking","title":"Compiling & Linking","text":"Bash
# compiling\nnasm -g -f elf64 src.asm  # -g adds debug info, -f specifies the 64bit ELF format\n\n# linking\nld -o src src.o  # -o specifies the output name\n
"},{"location":"languages/assembly/intel.html#basics","title":"Basics","text":""},{"location":"languages/assembly/intel.html#exports-sections","title":"Exports & Sections","text":"

Symbols can be exported to be linked against with the linker

Every program in ELF has several sections:

GAS
; export the '_start' symbol for linking\nglobal _start\n\n; specify a section\nsection .data\nsection .text\n
"},{"location":"languages/assembly/intel.html#labels-declarations","title":"Labels & Declarations","text":"

Anything that's on the beginning of a line and is followed by a colon (:) is a label. Labels generally store addresses.

Declaration instructions:

Note: See the NASM manual, section 3.2.1 for the full list. Note: all byte declarations are Little Endian

GAS
arr: db 0x12,0x34,0x56,0x78,0x90\n
"},{"location":"languages/assembly/intel.html#registers","title":"Registers","text":"

There are several registers available on x86_64. Some serve a specific purposes (e.g. registers for storing floating point ; numbers), while others are called \"general purpose\" registers.

There are 16 of them:

The prefix r means that instructions will use all 64 bits in the registers.

For all those registers, except r8 through r15, it's possible to access:

For registers rax through rdx, it's possible to access:

"},{"location":"languages/assembly/intel.html#instructions","title":"Instructions","text":"

Instructions are operations that the CPU knowns how to execute directly. They are separated from their operands by whitespace, and the operands are separated from other with commas.

GAS
<instr> <operand1>, <operand2>, ..., <operand_n>\n\n; Intel syntax dictates the first operand is the destination, and the second is the source\n<instr> DEST, SOURCE\n
GAS
mov eax, 0x12345678  ; copies 4 bytes to eax\ninc rdi  ; INC: increment\ndec rsi  ; DEC: decrement\n
"},{"location":"languages/assembly/intel.html#add","title":"add","text":"

Adds the two operands and stores the result in the destination.

GAS
add rdi, rbx  ; Equivalent to rdi += rbx\n
"},{"location":"languages/assembly/intel.html#sub","title":"sub","text":"

Subtract the two operands and stores the result in the destination.

GAS
sub rsi, rbx  ; Equivalent to rsi -= rbx\n
"},{"location":"languages/assembly/intel.html#mul-div-imul-idiv","title":"mul, div, imul, idiv","text":"

mul and div interpret their operands as unsigned integers. imul and idiv interpret their operands as signed integers in two's complement.

mul and div instructions take a single operand because they use fixed registers for the other number.

For mul, the result is rax * <operand>, and it's a 128-bit value stored in rdx:rax, meaning the 64 lower bits are stored in rdx, while the 64 upper bits are stored in rax.

For div, the operand is the divisor and the dividend is rdx:rax, meaning it's a 128-bit value whose 64 upper bits are in rdx and whose 64 lower bits are in rax. The quotient is a 64-bit value stored in rax, and the remainder is also a 64-bit value, stored in rdx.

"},{"location":"languages/assembly/intel.html#and-or-xor","title":"and, or, xor","text":"GAS
and rdi, rsi  ; bitwise AND\nor rdi, rsi  ; bitwise OR\nxor rdi, rsi  ; bitwise XOR\n
"},{"location":"languages/assembly/intel.html#shr-shl","title":"shr, shl","text":"GAS
shr rsi, 2  ; right (logical) bitshift: equivalent to rsi >> 2\nshl rsi, 3  ; left (logical) bitshift: equivalent to rsi << 3\n

Note: there's sar for arithmetic right shift and sal for arithmetic shift left.

"},{"location":"languages/assembly/riscv.html","title":"Assembly (RISC-V)","text":"

Assembly programs are encoded as plain text files and contain four main elements:

"},{"location":"languages/assembly/riscv.html#assembly-language","title":"Assembly Language","text":""},{"location":"languages/assembly/riscv.html#labels","title":"Labels","text":"

Labels are \"markers\" that represent program locations. They can be inserted into an assembly program to \"mark\" a program position so that it can be referred to by assembly instructions.

GAS
x:  # <-- label definition\n  .word 10\n\nsum:\n  lw a0, x\n  addi a0, a0, 10\n  ret\n

Assemblers usually accept two kinds of labels: symbolic and numeric labels.

Symbolic labels are de\ufb01ned by an identifier followed by :. They are stored as symbols in the symbol table and are often used to identify global variables and routines.

Numeric labels are de\ufb01ned by a single decimal digit followed by :. They are used for local reference and are not included in the symbol table of executable files. They can be redefined repeatedly in the same assembly program.

References to numeric labels contain a suffix that indicates whether the reference is to a numeric label positioned before (b suffix) or after (f suffix) the reference.

"},{"location":"languages/assembly/riscv.html#symbols","title":"Symbols","text":"

Program symbols are \"names\" that are associated with numerical values and the symbol table is a data structure that maps each program symbol to its value. Labels are automatically converted into program symbols by the assembler and associated with a numerical value that represents its position in the program, which is a memory address.

It's possible to explicitly define symbols with the .set (or .equ) directive.

GAS
.set answer, 42\n\nget_answer:\n  li a0, answer\n  ret\n
"},{"location":"languages/assembly/riscv.html#references-relocations","title":"References & Relocations","text":"

Each reference to a label must be replaced by an address during the assembling and linking processes. Relocation is the process in which the code and data are assigned new memory addresses so that they do not conflict with addresses of coming from the other linked sources.

The relocation table is a data structure that contains information that describes how the program instructions and data need to be modi\ufb01ed to re\ufb02ect the addresses reassignment. Each object \ufb01le contains a relocation table and the linker uses their information to adjust the code when performing the relocation process.

"},{"location":"languages/assembly/riscv.html#global-vs-local-symbols","title":"Global vs Local Symbols","text":"

Symbols are classified as local or global symbols.

Local symbols are only visible on the same \ufb01le, i.e., the linker does not use them to resolve undefined references on other files. Global symbols, on the other hand, are used by the linker to resolve undefined reference on other files.

By default, the assembler registers labels as local symbols. The .globl directive instructs the assembler to register a label as a global symbol.

GAS
.globl exit\n\nexit:\n  li a0, 0\n  li a7, 93\n  ecall\n
"},{"location":"languages/assembly/riscv.html#program-entry-point","title":"Program Entry Point","text":"

Every program has an entry point: the point from which the CPU must start executing the program. The entry point is de\ufb01ned by an address, which is the address of the first instruction that must be executed.

GAS
.globl start # <-- program entry point \n

Note: the start label must be registered as a global symbol for the linker to recognize it as the entry point.

"},{"location":"languages/assembly/riscv.html#program-sections","title":"Program Sections","text":"

Executable and object files, and assembly programs are usually organized in sections. A section may contain data or instructions, and the contents of each section are mapped to a set of consecutive main memory addresses.

The following sections are often present on executable files generated for Linux-based systems:

When linking multiple object files, the linker groups information from sections with the same name and places them together into a single section on the executable \ufb01le.

To instruct the assembler to add the assembled information into other sections, the programmer (or the compiler) may use the .section <name> directive.

GAS
.section .text\n\nupdate_y:\n  la t1, y\n  sw a0, (t1)\n  ret\n\nupdate_x:\n  la t1, x\n  sw a0, (t1)\n  ret\n\n.section .data\n\nx: .word 10\ny: .word 12\n
"},{"location":"languages/assembly/riscv.html#assembly-instructions","title":"Assembly Instructions","text":"

Assembly instructions are instructions that are converted by the assembler into machine instructions. They are usually encoded as a string that contains a mnemonic and a sequence of parameters, known as operands.

A pseudo-instruction is an assembly instruction that does not have a corresponding machine instruction on the ISA, but can be translated automatically by the assembler into one or more alternative machine instructions to achieve the same effect.

The operands of assembly instructions may contain:

"},{"location":"languages/assembly/riscv.html#immediate-values","title":"Immediate Values","text":"

Immediate values are represented on assembly language by a sequence of alphanumeric characters.

GAS
li a0, 10        # load value ten into register a0\n2 li a1, 0xa     # load value ten into register a1\n3 li a2, 0b1010  # load value ten into register a2\n4 li a3, 012     # load value ten into register a3\n5 li a4, \u20190\u2019     # load value forty eight into register a4\n6 li a5, \u2019a\u2019     # load value ninety seven into register a5\n
"},{"location":"languages/assembly/riscv.html#the-value-directives","title":"The .<value> Directives","text":"

The .byte, .half, .word, and .dword directives add one or more values to the active section. Their arguments may be expressed as immediate values, symbols (which are replaced by their value during the assembling and linking processes) or by arithmetic expressions that combine both.

The .string, .asciz, and .ascii directives add strings to the active section. The string is encoded as a sequence of bytes.

Directive Arguments Description .byte expr [, expr]* Emit one or more 8bit comma separated words .half expr [, expr]* Emit one or more 16bit comma separated words .word expr [, expr]* Emit one or more 32bit comma separated words .dword expr [, expr]* Emit one or more 64bit comma separated words .string string Emit NULL terminated string .asciz string Alias for .string .ascii string Emit string without NULL character"},{"location":"languages/assembly/riscv.html#the-set-and-equ-directives","title":"The .set and .equ directives","text":"

The .set name, expression directive adds a symbol to the symbol table. It takes a name and an expression as arguments, evaluates an expression to a value and store the name and the resulting value into the symbol table.

The .equ directive performs the same task as the .set directive.

"},{"location":"languages/assembly/riscv.html#the-globl-directive","title":"The .globl directive","text":"

The .globl directive can be used to turn local symbols into global ones.

GAS
.global start\n.global max_value\n\n.set max_value, 42\n\nstart:\n  li a0, max_value\n  jal process_temp\n  ret\n
"},{"location":"languages/assembly/riscv.html#the-skip-directive","title":"The .skip directive","text":"

The .bss section is dedicated for storing uninitialized global variables. These variables need to be allocated on memory, but they do not need to be initialized by the loader when a program is executed. As a consequence, their initial value do not need to be stored on executable nor object files.

To allocate variables on the .bss section it suffices to declare a label to identify the variable and advance the .bss location counter by the amount of bytes the variable require, so further variables are allocated on other address. The .skip N directive is a directive that advances the location counter by N units and can be used to allocate space for variables on the .bss section.

GAS
.section .bss\nx: .skip 4\ny: .skip 80\nz: .skip 4\n
"},{"location":"languages/assembly/riscv.html#the-align-directive","title":"The .align directive","text":"

Some ISA's require instructions or multi-byte data to be stored on addresses that are multiple of a given number.

The proper way of ensuring the location counter is aligned is by using the .align N directive. The .align N directive checks if the location counter is a multiple of 2^N, if it is, it has no effect on the program, otherwise, it advances the location counter to the next value that is a multiple of 2^N.

"},{"location":"languages/bash/commands.html","title":"Bash Commands","text":"

Note: Square brackets ([]) denotes optional commands/flags/arguments. Uppercase denotes placeholders for arguments.

"},{"location":"languages/bash/commands.html#basic-commands","title":"Basic Commands","text":""},{"location":"languages/bash/commands.html#elevated-privileges-and-users","title":"Elevated Privileges and Users","text":"

sudo vs su

Bash
sudo su  # login as root (user must be sudoers, root password not required) DANGEROUS\nsudo -s  # act as root and inherit current user environment (env as is now, along current dir and env vars) SAFE (can modify user environment)\nsudo -i  # act as root and and use a clean environment (goes to user's home, runs .bashrc) SAFEST\nsudo COMMAND  # run a command w\\ root permissions\nsudo -u USER COMMAND # run command as user\n\nsu  # become root (must know root password) DANGEROUS\nsu - USER  # change user and load it's home folder\nsu USER  # change user but don't load it's home folder\n
"},{"location":"languages/bash/commands.html#getting-info","title":"Getting Info","text":"Bash
man COMMAND  # show command manual\nhelp COMMAND  # show command info\nwhatis COMMAND  # one-line command explanation\napropos COMMAND  # search related commands\nwhich COMMAND  # locate a command\nhistory  # list of used commands\n\nid  # Print user and group information for the specified USER, or (when USER omitted) for the current user\n
"},{"location":"languages/bash/commands.html#moving-showing-directory-contents","title":"Moving & Showing Directory Contents","text":"Bash
pwd  # print working (current) directory\nls [option]... [FILE]...   # list directory contents (\"list storage\")\ncd rel_path  # change directory to path (rel_path must be inside current directory)\ncd abs_path  # change directory to path\ncd ..  # change directory to parent directory\ncd ~  # go to /home\ncd -  # go to previous directory\npushd PATH  # go from current directory to path\npopd  # return to previous directory (before pushd)\n
"},{"location":"languages/bash/commands.html#creating-reading-copying-moving-modifying-files-and-directories","title":"Creating, Reading, Copying, Moving, Modifying Files And Directories","text":"Bash
touch FILE  # change FILE timestamp fi exists, create file otherwise\ncat [FILE]  # concatenate files and print on standard output (FD 1)\ncat >> FILE  # append following content ot file (Ctrl+D to stop)\nfile FILE  # discover file extension and format\nstat FILE  # display file or file system status\n\ntail  # output the last part of a file\ntail [-nNUM]  # output the last NUM lines\n\nmore  # filter for paging through text one screenful at a time\nless  # opposite of more (display big file in pages), navigate with arrow keys or space bar\n\ncut  # remove sections from each line of files\ncut -[d --delimiter=DELIM]  # use DELIM instead of TAB for field delimiter\ncut [-f --fields=LIST]  # select only these fields\n\ndf  # report file system disk space usage\n\nrm FILE  # remove file or directories\nrm DIRECTORY -r  # remove directory an all its contents (recursive)\nrmdir DIRECTORY  # remove directory only if is empty\n\nmkdir DIRECTORY  # make directories\n\nmv SOURCE DESTINATION  # move or rename files\nmv SOURCE DIRECTORY  # move FILE to DIRECTORY\n\ncp SOURCE DESTINATION  # copy SOURCE to DESTINATION\n
"},{"location":"languages/bash/commands.html#files-permissions-ownership","title":"Files Permissions & Ownership","text":"Bash
chmod MODE FILE  # change file (or directory) permissions\nchmod OCTAL-MODE FILE  # change file (or directory) permissions\n\nchown [OPTION]... [OWNER][:[GROUP]] FILE...  # change file owner and group\nchgrp [OPTION]... GROUP FILE...  # change group ownership\n

File Permissions:

Directory Permissions:

Common Octal Files Permissions:

Common Octal Directory Permissions:

"},{"location":"languages/bash/commands.html#finding-files-and-directories","title":"Finding Files And Directories","text":"Bash
find [path] [expression]   # search file in directory hierarchy\nfind [start-position] -type f -name FILENAME  # search for a file named \"filename\"\nfind [start-position] -type d -name DIRNAME  # search for a directory named \"dirname\"\nfind [path] -exec <command> {} \\;  # execute command on found items (identified by {})\n\n[[ -f \"path\" ]]  # test if a file exists\n[[ -d \"path\" ]]  # test if a folder exists\n[[ -L \"path\" ]]  # test if is symlink\n
"},{"location":"languages/bash/commands.html#other","title":"Other","text":"Bash
tee  # copy standard input and write to standard output AND files simultaneously\ntee [FILE]\ncommand | sudo tee FILE  # operate on file w/o using shell as su\n\necho  # display a line of text\necho \"string\" > FILE  # write lin of text to file\necho \"string\" >> FILE  # append line of text to end of file (EOF)\n\nwget URL  # download repositories to linux machine\n\ncurl  # download the contents of a URL\ncurl [-I --head]  # Fetch the headers only\n\nps [-ax]  # display processes\nkill <PID>   # kill process w/ Process ID <PID>\nkillall PROCESS  # kill process by nane\n\ngrep  # search through a string using a REGEX\ngrep [-i]  # grep ignore case\n\nsource script.sh  # load script as a command\ndiff FILES  # compare files line by line\n\n# sudo apt install shellcheck\nshellcheck FILE  # shell linter\n\nxargs [COMMAND]  # build and execute command lines from standard input\n# xargs reads items form the standard input, delimited by blanks or newlines, and executes the COMMAND one or more times with the items as arguments\nwatch [OPTIONS] COMMAND  # execute a program periodically, showing output full-screen\nwatch -n SECONDS COMMAND  # execute command every SECONDS seconds (no less than 0.1 seconds)\n
"},{"location":"languages/bash/commands.html#data-wrangling","title":"Data Wrangling","text":"

Data wrangling is the process of transforming and mapping data from one \"raw\" data form into another format with the intent of making it more appropriate and valuable for a variety of downstream purposes such as analytics.

Bash
sed  # stream editor for filtering and transforming text\nsed -E \"s/REGEX/replacement/\"  # substitute text ONCE (-E uses modern REGEX)\nsed -E \"s/REGEX/replacement/g\"  # substitute text multiple times (every match)\n\nwc [FILE] # print newline, word and byte count for each file\nwc [-m --chars] FILE  # print character count\nwc [-c --bytes] FILE  # print bytes count\nwc [-l --lines] FILE  # print lines count\nwc [-w --words] FILE  # print word count\n\nsort [FILE]  # sort lines of a text file\n\nuniq [INPUT [OUTPUT]]  # report or omit repeated lines (from INPUT to OUTPUT)\nuniq [-c --count]  # prefix lines w/ number of occurrences\nuniq [-d --repeated]  # print only duplicare lines, one for each group\nuniq [-D]  # print only duplicare lines\n\npaste [FILE]  # merge lines of files\npaste [-d --delimiters=LIST]  # use delimiters from LIST\npaste [- --serial]  # paste one file at a time instead of in parallel\n\nawk '{program}'  # pattern scanning and processing language\nawk [-f --file PROGRAM_FILE]  # read program source from PROGRAM_FILE instead of from first argument\n\nbc [-hlwsqv long-options] [FILE]  # arbitrary precision calculator language\nbc [-l --mathlib] [FILE]  # use standard math library\n
"},{"location":"languages/bash/scripting.html","title":"Bash Scripting","text":"

Bash Manual

Ctrl+Shift+C: copy Ctrl+Shift+C: paste

"},{"location":"languages/bash/scripting.html#bash-use-modes","title":"Bash Use Modes","text":"

Interactive mode \u2192 shell waits for user's commands Non-interactive mode \u2192 shell runs scripts

"},{"location":"languages/bash/scripting.html#file-directories-permissions","title":"File & Directories Permissions","text":"

File:

Directory:

"},{"location":"languages/bash/scripting.html#file-descriptors","title":"File Descriptors","text":"

FD 0 \"standard input\" \u2192 Channel for standard input (default keyboard) FD 1 \"standard output\" \u2192 Channel for the default output (default screen) FD 2 \"standard error\" \u2192 Channel for error messages, info messages, prompts (default keyboard) File descriptors chan be joined to create streams that lead to files, devices or other processes.

Bash gets commands by reading lines. As soon as it's read enough lines to compose a complete command, bash begins running that command. Usually, commands are just a single line long. An interactive bash session reads lines from you at the prompt. Non-interactive bash processes read their commands from a file or stream. Files with a shebang as their first line (and the executable permission) can be started by your system's kernel like any other program.

"},{"location":"languages/bash/scripting.html#first-line-of-bash","title":"First Line Of Bash","text":"

#!/bin/env bash shebang indicating which interpreter to use

"},{"location":"languages/bash/scripting.html#simple-command","title":"Simple Command","text":"Bash
[ var=value ... ] command [ arg ... ] [ redirection ... ]  # [.] is optional component\n
"},{"location":"languages/bash/scripting.html#pipelines-commands-concatenation","title":"Pipelines (commands concatenation)","text":"Bash
command | file.ext  # link the first process' standard output to the second process' standard input\ncommand |& file.ext  # link the first process' standard output & standard error to the second process' standard input\n
"},{"location":"languages/bash/scripting.html#lists-sequence-of-commands","title":"Lists (sequence of commands)","text":"Bash
command_1; command_2; ...  # execute command in sequence, one after the other\ncommand_1 || command_2 || ...  # execute successive commands only if preceding ones fail\ncommand_1 && command_2 && ..  # execute successive commands only if preceding ones succeeds\n
"},{"location":"languages/bash/scripting.html#compound-commands-multiple-commands-as-one","title":"COMPOUND COMMANDs (multiple commands as one)","text":"Bash
# block of commands executed as one\n<keyword>\n    command_1; command_2; ...\n<end_keyword>\n\n{command_1; command_2; ...}  # sequence of commands executed as one\n
"},{"location":"languages/bash/scripting.html#functions-blocks-of-easily-reusable-code","title":"Functions (blocks of easily reusable code)","text":"

function_name () {compound_command} Bash does not accept func arguments, parentheses must be empty

"},{"location":"languages/bash/scripting.html#command-names-running-programs","title":"Command names & Running programs","text":"

To run a command, bash uses the name of your command and performs a search for how to execute that command. In order, bash will check whether it has a function or builtin by that name. Failing that, it will try to run the name as a program. If bash finds no way to run your command, it will output an error message.

"},{"location":"languages/bash/scripting.html#the-path-to-a-program","title":"The path to a program","text":"

When bash needs to run a program, it uses the command name to perform a search. Bash searches the directories in your PATH environment variable, one by one, until it finds a directory that contains a program with the name of your command. To run a program that is not installed in a PATH directory, use the path to that program as your command's name.

"},{"location":"languages/bash/scripting.html#command-arguments-quoting-literals","title":"Command arguments & Quoting literals","text":"

To tell a command what to do, we pass it arguments. In bash, arguments are tokens, that are separated from each other by blank space. To include blank space in an argument's value, you need to either quote the argument or escape the blank space within. Failing that, bash will break your argument apart into multiple arguments at its blank space. Quoting arguments also prevents other symbols in it from being accidentally interpreted as bash code.

"},{"location":"languages/bash/scripting.html#managing-a-commands-input-and-output-using-redirection","title":"Managing a command's input and output using redirection","text":"

By default, new commands inherit the shell's current file descriptors. We can use redirections to change where a command's input comes from and where its output should go to. File redirection allows us to stream file descriptors to files. We can copy file descriptors to make them share a stream. There are also many other more advanced redirection operators.

"},{"location":"languages/bash/scripting.html#redirections","title":"Redirections","text":"Bash
[x]>file  # make FD x write to file\n[x]<file  # make FD x read from file\n\n[x]>&y  # make FD x write to FD y's stream\n[x]<&y  # make FD x read from FD y's stream\n&>file  # make both FD 1 (standard output) & FD 2 (standard error) write to file\n\n[x]>>file  # make FD x append to end of file\nx>&-, x<&-  # close FD x (stream disconnected from FD x)\n[x]>&y-, [x]<&y-  # replace FD x with FD y\n[x]<>file  # open FD x for both reading and writing to file\n
"},{"location":"languages/bash/scripting.html#pathname-expansion-filname-pattern-glob-matching","title":"Pathname Expansion (filname pattern [glob] matching)","text":"

* matches any kind of text (even no text). ? matches any single character. [characters] matches any single character in the given set. [[:classname:]] specify class of characters to match. {} expand list of arguments (applies command to each one)

shopt -s extglob enables extended globs (patterns)

+(pattern [| pattern ...]) matches when any of the patterns in the list appears, once or many times over. (\"at least one of ...\"). *(pattern [| pattern ...]) matches when any of the patterns in the list appears, once, not at all, or many times over. (\"however many of ...\"). ?(pattern [| pattern ...]) matches when any of the patterns in the list appears, once, not at all, or many times over. (\"however many of ...\"). @(pattern [| pattern ...]) matches when any of the patterns in the list appears just once. (\"one of ...\"). !(pattern [| pattern ...]) matches only when none of the patterns in the list appear. (\"none of ...\").

"},{"location":"languages/bash/scripting.html#command-substitution","title":"Command Substitution","text":"

With Command Substitution, we effectively write a command within a command, and we ask bash to expand the inner command into its output and use that output as argument data for the main command.

Bash
$(inner_command)  # $ --> value-expansion prefix\ncommand !*  # !* expands to everything except the first argument in the previous line\ncommand !$  # refers to the last argument of the previous command\nsudo !! # !! expands to the entire previous command\n
"},{"location":"languages/bash/scripting.html#shell-variables","title":"Shell Variables","text":"Bash
varname=value  # variable assignment\nvarname=\"$(command)\"  # command substitution, MUST be double-quoted\n\"$varname\", \"${varname}\"  # variable expansion, MUST be double-quoted (name substituted w/ variable content)\n\n$$  # pid\n$#  # number of arguments passed\n$@  # all arguments passed\n${n}  # n-th argument passed to the command\n$0  # name of the script\n$_  # last argument passed to the command\n$?  # error message of the last (previous) command\n!!  # executes last command used (echo !! prints the last command)\n
"},{"location":"languages/bash/scripting.html#parameter-expansion-modifiers-in-double-quotes","title":"Parameter Expansion Modifiers (in double-quotes)","text":"

${parameter#pattern} removes the shortest string that matches the pattern if it's at the start of the value. ${parameter##pattern} removes the longest string that matches the pattern if it's at the start of the value. ${parameter%pattern} removes the shortest string that matches the pattern if it's at the end of the value. ${parameter%%pattern} removes the longest string that matches the pattern if it's at the end of the value. ${parameter/pattern/replacement} replaces the first string that matches the pattern with the replacement. ${parameter//pattern/replacement} replaces each string that matches the pattern with the replacement. ${parameter/#pattern/replacement} replaces the string that matches the pattern at the beginning of the value with the replacement. ${parameter/%pattern/replacement} replaces the string that matches the pattern at the end of the value with the replacement. ${#parameter} expands the length of the value (in bytes). ${parameter:start[:length]} expands a part of the value, starting at start, length bytes long. Counts from the end rather than the beginning by using a (space followed by a) negative value. ${parameter[^|^^|,|,,][pattern]} expands the transformed value, either upper-casing or lower-casing the first or all characters that match the pattern. Omit the pattern to match any character.

"},{"location":"languages/bash/scripting.html#decision-statements","title":"Decision Statements","text":""},{"location":"languages/bash/scripting.html#if-statement","title":"If Statement","text":"

Only the final exit code after executing the entire list is relevant for the branch's evaluation.

Bash
if command_list; then\n    command_list;\nelif command_list; then\n    command_list;\nelse command_list;\nfi\n
"},{"location":"languages/bash/scripting.html#test-command","title":"Test Command","text":"

[[ argument_1 <operator> argument_2 ]]

"},{"location":"languages/bash/scripting.html#arithmetic-expansion-and-evaluation","title":"Arithmetic expansion and evaluation","text":"

(( expression ))

"},{"location":"languages/bash/scripting.html#comparison-operators","title":"Comparison Operators","text":"Bash
[[ \"$a\" -eq \"$b\" ]]  # is equal to\n[[ \"$a\" -ne \"$b\" ]]  # in not equal to\n[[ \"$a\" -gt \"$b\" ]]  # greater than\n[[ \"$a\" -ge \"$b\" ]]  # greater than or equal to\n[[ \"$a\" -lt \"$b\" ]]  # less than\n[[ \"$a\" -le \"$b\" ]]  # less than or equal to\n
"},{"location":"languages/bash/scripting.html#arithmetic-comparison-operators","title":"Arithmetic Comparison Operators","text":"Bash
((\"$a\" > \"$b\"))  # greater than\n((\"$a\" >= \"$b\"))   # greater than or equal to\n((\"$a\" < \"$b\"))  # less than\n((\"$a\" <= \"$b\"))   # less than or equal to\n
"},{"location":"languages/bash/scripting.html#string-comparison-operators","title":"String Comparison Operators","text":"Bash
[ \"$a\" = \"$b\" ]    # is equal to (whitespace around operator)\n\n[[ $a == z* ]]     # True if $a starts with an \"z\" (pattern matching)\n[[ $a == \"z*\" ]]   # True if $a is equal to z* (literal matching)\n[ $a == z* ]       # File globbing and word splitting take place\n[ \"$a\" == \"z*\" ]   # True if $a is equal to z* (literal matching)\n\n[ \"$a\" != \"$b\" ]   # is not equal to, pattern matching within a [[ ... ]] construct\n\n[[ \"$a\" < \"$b\" ]]  # is less than, in ASCII alphabetical order\n[ \"$a\" \\< \"$b\" ]   # \"<\" needs to be escaped within a [ ] construct.\n\n[[ \"$a\" > \"$b\" ]]  # is greater than, in ASCII alphabetical order\n[ \"$a\" \\> \"$b\" ]   # \">\" needs to be escaped within a [ ] construct.\n
"},{"location":"languages/bash/scripting.html#commands-short-circuit-evaluation","title":"Commands short circuit evaluation","text":"Bash
command_1 || command_2  # if command_1 fails executes command_2\ncommand_1 && command_2  # executes command_2 only if command_1 succeeds\n
"},{"location":"languages/bash/scripting.html#loops","title":"Loops","text":"Bash
for var in iterable ; do\n    # command here\ndone\n
"},{"location":"languages/bash/scripting.html#script-hardening","title":"Script Hardening","text":"Bash
set -o errexit  # exit on error\nset -o nounset  # fail on unset variable (bypass with ${VAR:-})\nset -o pipefail  # file entire pipeline if one step fails\n\n# hook to enable tracing\nif [[ \"${TRACE-0}\" == \"1\" ]]; then\n    set -o xtrace\nfi\n
"},{"location":"languages/c/c.html","title":"C/C++","text":""},{"location":"languages/c/c.html#library-import","title":"Library Import","text":"C
#include <stdio.h>  // search in current + system directories\n#include \"lib.h\" // search in current directory\n
"},{"location":"languages/c/c.html#special-operators","title":"Special Operators","text":"Operator Operator Name :: global reference operator & address operator (returns a memory address) * deferentiation operator (returns the pointed value)"},{"location":"languages/c/c.html#namespace-definition","title":"Namespace definition","text":"

Can be omitted and replaced by namespace:: using namespace <namespace>;

"},{"location":"languages/c/c.html#main-function","title":"Main Function","text":"C
int main(int argc, char *argv[]) { }\n
"},{"location":"languages/c/c.html#variables-types","title":"Variables & Types","text":""},{"location":"languages/c/c.html#constant-declaration","title":"Constant Declaration","text":"C
#define constant_name value\nconst type constant_name = value;\n
"},{"location":"languages/c/c.html#variable-declaration","title":"Variable Declaration","text":"C
type var_name = value;    //c-like initialization\ntype var_name (value);    //constructor initialization\ntype var_name {value};    //uniform initialization\ntype var_1, var_2, ..., var_n;\n
"},{"location":"languages/c/c.html#type-casting","title":"Type Casting","text":"

(type) var; type(var);

"},{"location":"languages/c/c.html#variable-types","title":"Variable Types","text":"Type Value Range Byte short -32768 to 32765 1 unsigned short 0 to 65535 1 int -2147483648 to 2147483647 4 unsigned int 0 to 4294967295 4 long -2147483648 to 2147483647 4 unsigned long 0 to 4294967295 4 long long 8 float \u00b1 3.4e \u00b1 38 (~7 digits) 4 double \u00b1 1.7e \u00b1 308 (~15 digits) 8 long double 16 (?) Type Value bool true or false char ascii characters string sequence of ascii characters NULL empty value"},{"location":"languages/c/c.html#integer-numerals","title":"Integer Numerals","text":"Example Type 75 decimal 0113 octal (zero prefix) 0x4 hexadecimal (0x prefix) 75 int 75u unsigned int 75l long 75ul unsigned long 75lu unsigned long"},{"location":"languages/c/c.html#floating-point-numerals","title":"Floating Point Numerals","text":"Example Type 3.14159L long double 60.22e23f float Code Value 3.14159 3.14159 6.02e23 6.022 * 10^23 1.6e-19 1.6 * 10^-19 3.0 3.0"},{"location":"languages/c/c.html#characterstring-literals","title":"Character/String Literals","text":"

'z' single character literal \"text here\" string literal

"},{"location":"languages/c/c.html#special-characters","title":"Special Characters","text":"Escape Character Character \\n newline \\r carriage return \\t tab \\v vertical tab \\b backspace \\f form feed \\a alert (beep) \\' single quote (') \\\" double quote (\") \\? question mark (?) \\\\ backslash () \\0 string termination character"},{"location":"languages/c/c.html#standard-inputoutput","title":"Standard Input/Output","text":""},{"location":"languages/c/c.html#standard-output","title":"Standard Output","text":"C
#include <stdio.h>\n\nprintf_s(\"text %<fmt_spec>\", variable);\n
"},{"location":"languages/c/c.html#standard-input","title":"Standard Input","text":"C
#include <stdio.h>\n\nscanf_s(\"%<fmt_spec>\", &variable);    //return number of successfully accepted inputs\n
"},{"location":"languages/c/c.html#format-specifiers-widthlengthspecifier","title":"Format Specifiers %[width].[length][specifier]","text":"Specifier Specified Format %d, %i singed decimal integer %u unsigned decimal integer %o unsigned octal %x unsigned hexadecimal integer %X unsigned hexadecimal integer (UPPERCASE) %f decimal floating point (lowercase) %F decimal floating point (UPPERCASE) %e scientific notation (lowercase) %E scientific notation (UPPERCASE) %a hexadecimal floating point (lowercase) %A hexadecimal floating point (UPPERCASE) %c character %s string %p pointer address"},{"location":"languages/c/c.html#operators","title":"Operators","text":""},{"location":"languages/c/c.html#arithmetic-operators","title":"Arithmetic Operators","text":"Operator Operation a + b sum a - b subtraction a * b multiplication a / b division a % b modulo a++ increment a-- decrement"},{"location":"languages/c/c.html#comparison-operators","title":"Comparison Operators","text":"Operator Operation a == b equal to a != b not equal to a > b greater than a < b lesser than a >= b greater than or equal to a <= b lesser than or equal to"},{"location":"languages/c/c.html#logical-operator","title":"Logical Operator","text":"Operator Operation !a, not a logical negation (NOT) a && b, a and b logical AND a || b, a or b logical OR"},{"location":"languages/c/c.html#conditional-ternary-operator","title":"Conditional Ternary Operator","text":"

condition ? result_1 : result_2 If condition is true evaluates to result_1, and otherwise to result_2

"},{"location":"languages/c/c.html#bitwise-operators","title":"Bitwise Operators","text":"Operator Operation ~a, compl a bitwise NOT a & b, a bitand b bitwise AND a | b, a bitor b bitwise OR a ^ b, a xor b, bitwise XOR a << b bitwise left shift a >> b bitwise right shift"},{"location":"languages/c/c.html#compound-assignment-operators","title":"Compound Assignment Operators","text":"Operator Operation a += b a = a + b a -= b a = a - b a *= b a = a * b a /= b a = a / b a %= b a = a % b a &= b a = a & b a |= b a = a a ^= b a = a ^ b a <<= b a = a << b a >>= b a = a >> b"},{"location":"languages/c/c.html#operator-precedence","title":"Operator Precedence","text":"
  1. !
  2. *, /, %
  3. +, -
  4. <, <=, <, >=
  5. ==, !=
  6. &&
  7. ||
  8. =
"},{"location":"languages/c/c.html#common-functions","title":"Common Functions","text":""},{"location":"languages/c/c.html#mathematical-functions","title":"Mathematical Functions","text":"C
#include <cmath>\n\nabs(x);    // absolute value\nlabs(x);    //absolute value if x is long, result is long\nfabs(x);    //absolute value if x i float, result is float\nsqrt(x);    // square root\nceil(x);    // ceil function (next integer)\nfloor(x);    // floor function (integer part of x)\nlog(x);    // natural log of x\nlog10(x);    // log base 10 of x\nexp(x);    // e^x\npow(x, y);    // x^y\nsin(x);\ncos(x);\ntan(x);\nasin(x);    //arcsin(x)\nacos(x);    //arccos(x)\natan(x);    //arctan(x)\natan2(x, y);    //arctan(x / y)\nsinh(x);    //hyperbolic sin(x)\ncosh(x);    //hyperbolic cos(x)\ntanh(x);    //hyperbolic tan(X)\n
"},{"location":"languages/c/c.html#character-functions","title":"Character Functions","text":"C
isalnum(c);    //true if c is alphanumeric\nisalpha(c);    //true if c is a letter\nisdigit(c);    //true if char is 0 1 2 3 4 5 6 7 8 9\niscntrl(c);    //true id c is DELETE or CONTROL CHARACTER\nisascii(c);    //true if c is a valid ASCII character\nisprint(c);    //true if c is printable\nisgraph(c);    //true id c is printable, SPACE excluded\nislower(c);    //true if c is lowercase\nisupper(c);    //true if c is uppercase\nispunct(c);    //true if c is punctuation\nisspace(c);    //true if c is SPACE\nisxdigit(c);    //true if c is HEX DIGIT\n\ntolower(c);    //transforms character in lowercase\ntoupper(c);    //transform character in uppercase\n
"},{"location":"languages/c/c.html#string-functions","title":"String Functions","text":"C
strlen(string);    //return length (num of chars) of the string\nstrcat(destination, source);    //appends chars of string2 to string1\nstrncat(string1, string2, nchar);    //appends the first n chars of string 2 to string1\nstrcpy(string1, string2.c_str());    //copies string2 into string1 char by char\nstrncpy(string1, string2, n);    //copy first n chars from string2 to string1\nstrcmp(string1, string2);    //compares string1 w/ string2\nstrncmp(string1, string2, n);    //compares first n chars\n//returns < 0 if string1 precedes string2\n//returns 0 if string1 == string2\n// returns > 0 if string1 succeeds string2\nstrchr(string, c);    //returns index of c in string if it exists, NULL otherwise\nstrstr(string1, string2);    //returns pointer to starting index of string1 in string2\nstrpbrk(string, charSet);    //Returns a pointer to the first occurrence of any character from strCharSet in str, or a NULL pointer if the two string arguments have no characters in common.\n
"},{"location":"languages/c/c.html#string-conversion","title":"String Conversion","text":"C
atof(string);    //converts string in double if possible\natoi(string);    //converts string in integer if possible\natol(string);    //converts string in long if possible\n
"},{"location":"languages/c/c.html#string-methods","title":"String Methods","text":"C++
string.at(pos);    // returns char at index pos\nstring.substr(start, end);    // returns substring between indexes START and END\nstring.c_str();    //reads string char by char\nstring.find(substring);    // The zero-based index of the first character in string object that matches the requested substring or characters\n
"},{"location":"languages/c/c.html#vectors","title":"Vectors","text":"C
#include <vector>\nvector<type> vector_name = {values};    //variable length array\n
"},{"location":"languages/c/c.html#decision-statements","title":"Decision Statements","text":""},{"location":"languages/c/c.html#if-statements","title":"If Statements","text":"C
if (condition) { }\n\nif (condition) \n{\n\n}\nelse if (condition) \n{\n\n}\nelse\n{\n\n}\n
"},{"location":"languages/c/c.html#switch","title":"Switch","text":"C
switch (expression) {\n    case constant_1:\n        //code here\n        break;\n\n    case constant_2:\n        //code here\n        break;\n\n    default:\n        //code here\n}\n
"},{"location":"languages/c/c.html#loop-statements","title":"Loop Statements","text":""},{"location":"languages/c/c.html#while-loop","title":"While Loop","text":"C
while (condition) {\n    //code here\n}\n
"},{"location":"languages/c/c.html#do-while","title":"Do While","text":"C
do {\n    //code here\n} while (condition);\n
"},{"location":"languages/c/c.html#for-loop","title":"For Loop","text":"C
for (initialization; condition; increase) {\n    //code here\n}\n
"},{"location":"languages/c/c.html#break-statement","title":"Break Statement","text":"

break; leaves a loop, even if the condition for its end is not fulfilled.

"},{"location":"languages/c/c.html#continue-statement","title":"Continue Statement","text":"

continue; causes the program to skip the rest of the loop in the current iteration.

"},{"location":"languages/c/c.html#functions","title":"Functions","text":"

Functions must be declared before the main function. It is possible to declare functions after the main only if the prototype is declared before the main. To return multiple variables those variables can be passed by reference so that their values is adjourned in the main.

C
type function_name(type argument1, ...); // function prototype\n\ntype functionName (parameters) {\n    return <expression>;\n}\n\nvoid functionName (parameters) { }\n
"},{"location":"languages/c/c.html#arguments-passed-by-reference-without-pointers","title":"Arguments passed by reference without pointers","text":"

Passing arguments by reference causes modifications made inside the function to be propagated to the values outside. Passing arguments by values copies the values to the arguments: changes remain inside the function.

C
type functionName (type &argument1, ...) {\n    //code here\n    return <expression>;\n}\n

functionName (arguments);

"},{"location":"languages/c/c.html#arguments-passed-by-reference-with-pointers","title":"Arguments passed by reference with pointers","text":"

Passing arguments by reference causes modifications made inside the function to be propagated to the values outside. Passing arguments by values copies the values to the arguments: changes remain inside the function.

C
type function_name (type *argument_1, ...) {\n    instructions;\n    return <expression>;\n}\n

function_name (&argument_1, ...);

"},{"location":"languages/c/c.html#arrays","title":"Arrays","text":"C
type arrayName[dimension];    //array declaration\ntype arrayName[dimension] = {value1, value2, ...};    //array declaration & initialization, values number must match dimension\n\narray[index]    //item access, index starts at 0 (zero)\narray[index] = value;    //value assignment at position index\n
"},{"location":"languages/c/c.html#array-as-function-parameter","title":"Array as function parameter","text":"

The dimension is not specified because it is determined by the passed array. The array is passed by reference.

C
type function(type array[]){\n    //code here\n}\n\n//array is not modifiable inside the function (READ ONLY)\ntype function(const type array[]){\n    //code here\n}\n\nfunction(array);    //array passed w/out square brackets []\n
"},{"location":"languages/c/c.html#multi-dimensional-array-matrix","title":"Multi-Dimensional Array (Matrix)","text":"C
type matrix[rows][columns];\nmatrix[i][j]    //element A_ij of the matrix\n
"},{"location":"languages/c/c.html#matrix-as-function-parameter","title":"Matrix as function parameter","text":"C
//matrix passed by reference, second dimension is mandatory\ntype function(type matrix[][columns]){\n    //code here\n};\n\n//matrix values READ ONLY\ntype function(const type matrix[][columns]){\n    //code here\n}\n\ntype function(type matrix[][dim2]...[dimN]){\n    //code here\n}\n
"},{"location":"languages/c/c.html#structs","title":"Structs","text":""},{"location":"languages/c/c.html#struct-definition","title":"Struct Definition","text":"C
struct Struct {\n    type field1;\n    type field2;\n    type field3;\n    type field4;\n};\n\nStruct variable;    // struct-type variable\nvariable.field    // field access\n
"},{"location":"languages/c/c.html#pointers","title":"Pointers","text":"

Pointers hold memory addresses of declared variables, they should be initialized to NULL.

C
type *pointer = &variable;     //pointer init and assignment\ntype *pointer = NULL;\ntype *pointer = otherPointer;\ntype **pointerToPointer = &pointer;    // pointerToPointer -> pointer -> variable\n

&variable extracts the address, the pointer holds the address of the variable. pointer type and variable type must match. (*) \u2192 \"value pointed to by\"

C
pointer    //address of pointed value (value of variable)\n*pointer    //value of pointed variable\n**pointer //value pointed by *pointer (pointer to pointer)\n
"},{"location":"languages/c/c.html#pointer-to-array","title":"Pointer to array","text":"C
type *pointer;\ntype array[dim] = {};\n\n\npointer = array;    //point to array (pointer points to first \"cell\" of array)\npointer++;    //change pointed value to successive \"cell\" of array\n
"},{"location":"languages/c/c.html#pointers-arrays-functions","title":"Pointers, Arrays & Functions","text":"C
func(array)    //pass entire array to function (no need to use (&) to extract address)\n\ntype func(type* array){\n    array[index]    //access to item of array at index\n}\n
"},{"location":"languages/c/c.html#pointer-to-struct","title":"Pointer to Struct","text":"C
(*structPointer).field    //access to field value\nstructPointer->structField    //access to field value\n
"},{"location":"languages/c/c.html#dynamic-structures","title":"Dynamic Structures","text":"

Dynamic structures are structures without a fixed number of items.

Every item in a dynamic structure is called node. Every node is composed by two parts:

Lists are linear dynamic structures in which is only defined the preceding and succeeding item. A List is a group of homogeneous items (all of the same type).

Trees, Graphs are non linear dynamic structures in which an item cha have multiple successors.

"},{"location":"languages/c/c.html#stack","title":"Stack","text":"

A Stack is a list in with nodes can be extracted from one side only (LIFO). The extraction of an item from the top is called pop

C
// node structure\nstruct Node {\n    type value;\n    stack *next;\n}\n
"},{"location":"languages/c/c.html#node-insertion","title":"Node Insertion","text":"C
Node *stackNode;    //current node\nNode* head = NULL;    //pointer to head of stack\n\nint nodeValue;\n//assign value to nodeValue\n\nstackNode = (*Node)malloc(sizeof(Node));    //create new node\n\nstackNode->value = nodevalue;    //valorize node\nstackNode->next = head;    //update node pointer to old head adding it to the stack\n\nhead = stackNode;    //update head to point to new first node\n
"},{"location":"languages/c/c.html#node-deletion","title":"Node Deletion","text":"C
stackNode = head->next;    //memorize location of second node\nfree(head);    //delete first node\nhead = stackNode;    //update head to point to new first node\n
"},{"location":"languages/c/c.html#passing-head-to-functions","title":"Passing Head To Functions","text":"C
type function(Node** head)    //value of head passed by address (head is Node*)\n{\n    *head = ...    //update value of head (pointed variable/object/Node)\n}\n
"},{"location":"languages/c/c.html#queue","title":"Queue","text":"

A Queue is a list in which nodes enter from one side and can be extracted only from the other side (FIFO).

"},{"location":"languages/c/c.html#linked-list","title":"Linked List","text":"

A Linked List is list in which nodes can be extracted from each side and from inside the linked list.

Linked lists can be linear, circular or bidirectional. In circular linked lists the last node points to the first.

Nodes of bidirectional linked lists are composed by three parts:

Thus the first and last node will have a component empty since they only point to a single node.

"},{"location":"languages/c/c.html#dynamic-memory-allocation","title":"Dynamic Memory Allocation","text":"

C does not automatically free allocated memory when nodes are deleted. It must be done manually.

C
list *pointer = (list*)malloc(sizeof(list));    //memory allocation\nfree(pointer)    //freeing of memory\n

malloc() returns a void pointer thus the list must be casted to a void type with (list*)

"},{"location":"languages/c/c.html#files","title":"Files","text":"

The object oriented approach is based on the use of streams. A Stream can be considered a stream of data that passes sequentially from a source to a destination.

The available classes in C++ to operate on files are:

"},{"location":"languages/c/c.html#file-opening","title":"File Opening","text":"

Filename can be string literal or CharArray (use c_str()).

C
ifstream file;\nfile.open(\"filename\");    //read from file\n\nofstream file;\nfile.open(\"filename\");    //write to file\n\n\nfstream file;\nfile.open(\"filename\", ios::in);    //read form file\nfile.open(\"filename\", ios::out);    //write to file\nfile.open(\"filename\", ios::app);    //append to file\nfile.open(\"filename\", ios::trunc);    //overwrite file\nfile.open(\"filename\", ios::nocreate);    //opens file only if it exists, error otherwise. Does not create new file\nfile.open(\"filename\", ios::noreplace);    //opens file only if it not exists, error otherwise. If it not exists the file is created.\nfile.open(\"filename\", ios::binary);    //opens file in binary format\n

If file opening fails the stream has value 0, otherwise the value is the assigned memory address. Opening modes can be combined with the OR operator: ios::mode | ios::mode.

"},{"location":"languages/c/c.html#stream-state-input-errors","title":"Stream state & Input errors","text":"

Once a stream is in a state of error it will remain so until the status flags are explicitly resetted. The input operations on such a stream are void until the reset happens. To clear the status of a stream the clear() method is used. Furthermore, when an error on the stream happens the stream is not cleared of it's characters contents. To clear the stream contents the ignore() method is used.

"},{"location":"languages/css/css.html","title":"CSS","text":""},{"location":"languages/css/css.html#applying-css-to-html","title":"Applying CSS to HTML","text":""},{"location":"languages/css/css.html#inline-css","title":"Inline CSS","text":"

The style only applies to one element at a time.

HTML
<tag style=\"property:value\"></tag>\n
"},{"location":"languages/css/css.html#embedded-css","title":"Embedded CSS","text":"

The style is not shared but only applies to one HTML file.

HTML
<style>\n    selector {\n        property: value;\n    }\n</style>\n
"},{"location":"languages/css/css.html#external-css","title":"External CSS","text":" HTML
<link rel=\"stylesheet\" href=\"style.css\">\n
"},{"location":"languages/css/css.html#css-selectors","title":"CSS Selectors","text":"

A CSS selector points to an html element to style.

CSS
selector {\n    property: value;\n    property: value;\n}\n
"},{"location":"languages/css/css.html#multiple-selectors","title":"Multiple Selectors","text":"CSS
selector1, selector2 { property: value; }\n
"},{"location":"languages/css/css.html#nested-selectors","title":"Nested Selectors","text":"

Used to select tags nested in other tags.

CSS
outerSelector innerSelector { property: value; }\n
"},{"location":"languages/css/css.html#id-selector","title":"ID Selector","text":"

Can only apply to one element in a page.

CSS
#selector { property: value; }    /* selects <tag id=\"selector\"> */\n
"},{"location":"languages/css/css.html#class-selector","title":"Class Selector","text":"

Many elements can have the same class, classes are used to group HTML elements together.

CSS
.selector { property: value; }    /* selects <tag class=\"selector\"> */\n
"},{"location":"languages/css/css.html#universal-selector","title":"Universal Selector","text":"CSS
* { property: value; }    /* selects every HTML element */\n
"},{"location":"languages/css/css.html#descendant-selector-space","title":"Descendant selector (space)","text":"

Selects an element that resides anywhere within an identified ancestor element.

CSS
article h2 { property: value; }\n
HTML
<!-- Will NOT match -->\n<h2>title</h2>\n<article>\n    <!-- WILL match -->\n    <h2>subtitle</h2>\n    <div>\n        <!-- WILL match -->\n        <h2>subtitle</h2>\n    </div>\n</article>\n
"},{"location":"languages/css/css.html#direct-child-selector","title":"Direct child selector (>)","text":"

Selects an elements that resides immediately inside an identified parent element.

CSS
article > p { property: value; }\n
HTML
<!-- Will NOT match -->\n<p>Lorem ipsum dolor sit amet</p>\n<article>\n    <!-- WILL match -->\n    <p>This paragraph will be selected</p>\n    <div>\n        <!-- Will NOT match -->\n        <p>Lorem ipsum dolor sit amet</p>\n    </div>\n</article>\n
"},{"location":"languages/css/css.html#general-sibling-selector","title":"General sibling selector (~)","text":"

Selects an element that follows anywhere after the prior element. Both elements share the same parent.

CSS
h2 ~ p { property: value; }\n
HTML
<section>\n    <!-- Will NOT match -->\n    <p>Lorem ipsum dolor sit amet</p>\n    <h2>title</h2>\n    <!-- WILL match -->\n    <p>This paragraph will be selected</p>\n    <div>\n        <!-- Will NOT match -->\n        <p>Lorem ipsum dolor sit amet</p>\n    </div>\n    <!-- WILL match -->\n    <p>This paragraph will be selected</p>\n</section>\n<!-- Will NOT match -->\n<p>Lorem ipsum dolor sit amet</p>\n
"},{"location":"languages/css/css.html#adjacent-sibling-selector","title":"Adjacent sibling selector (+)","text":"

Selects an element that follows directly after the prior element. Both elements share the same parent.

CSS
h2 + p { property: value; }\n
HTML
<section>\n    <!-- Will NOT match -->\n    <p>Lorem ipsum dolor sit amet</p>\n    <h2>title</h2>\n    <!-- WILL match -->\n    <p>This paragraph will be selected</p>\n    <div>\n        <!-- Will NOT match -->\n        <p>Lorem ipsum dolor sit amet</p>\n    </div>\n    <!-- Will NOT match -->\n    <p>Lorem ipsum dolor sit amet</p>\n</section>\n<!-- Will NOT match -->\n<p>Lorem ipsum dolor sit amet</p>\n
"},{"location":"languages/css/css.html#namespace-separator","title":"Namespace Separator (|)","text":"

The namespace separator separates the selector from the namespace, identifying the namespace, or lack thereof, for a type selector.

CSS
@namespace <namespace> url(\"<XML-namespace-URL>\");\n\n/* specific namespace */\nnamespace|selector { property: value; }\n\n/* any namespace */\n*|selector { property: value; }\n\n/* no namespace */\n|selector { property: value; }\n
CSS
@namespace svg url('http://www.w3.org/2000/svg');\n\na {\n  color: orangered;\n  text-decoration: underline dashed;\n  font-weight: bold;\n}\n\nsvg|a {\n  fill: blueviolet;\n  text-decoration: underline solid;\n  text-transform: uppercase;\n}\n
HTML
<p>This paragraph \n    <!-- will be colored orangered -->\n    <a href=\"#\">has a link</a>.\n</p>\n\n<svg width=\"400\" viewBox=\"0 0 400 20\">\n  <!-- will be colored blueviolet -->\n  <a href=\"#\">\n    <text x=\"0\" y=\"15\">Link created in SVG</text>\n  </a>\n</svg>\n
"},{"location":"languages/css/css.html#column-selector","title":"Column Selector (||)","text":"

The column combinator (||) is placed between two CSS selectors. It matches only those elements matched by the second selector that belong to the column elements matched by the first.

CSS
column-selector || cell-selector { property: value; }\n
"},{"location":"languages/css/css.html#attribute-present-selector-tagattr","title":"Attribute Present Selector (tag[attr])","text":"

a[target]{ property: value; } will match

HTML
<a href=\"#\" target=\"_blank\">click here</a>\n
"},{"location":"languages/css/css.html#attribute-equals-selector","title":"Attribute Equals Selector (=)","text":"

a[href=\"https://google.com\"] { property: value; } will match

HTML
<a href=\"http://google.com/\">search on google</a>\n
"},{"location":"languages/css/css.html#attribute-contains-selector","title":"Attribute Contains Selector (*=)","text":"

a[href*=\"login\"] { property: value; } will match

HTML
<a href=\"/login.php\">login page</a>\n
"},{"location":"languages/css/css.html#attribute-begins-with-selector","title":"Attribute Begins With Selector (^=)","text":"

a[href^=\"Https://\"] { property: value; } will match

HTML
<a href=\"https://www.bbc.com/\">The BBC</a>\n
"},{"location":"languages/css/css.html#attribute-ends-with-selector","title":"Attribute Ends With Selector ($=)","text":"

a[href$=\".pdf\"] { property: value; }

HTML
<!-- WILL match -->\n<a href=\"/docs/menu.pdf\">download menu</a>\n<!-- Will NOT match -->\n<a href=\"/audio/song.mp3\">download song</a>\n
"},{"location":"languages/css/css.html#attribute-spaced-selector","title":"Attribute Spaced Selector (~=)","text":"

img[alt~=\"child\"] { property: value; }

HTML
<!-- WILL match -->\n<img src=\"child.jpg\" alt='a small child'>\n<!-- Will NOT match -->\n<img src=\"child.jpg\" alt='a-small-child'>\n<!-- Will NOT match -->\n<img src=\"child.jpg\" alt='asmallchild'>\n
"},{"location":"languages/css/css.html#attribute-hyphenated-selector","title":"Attribute Hyphenated Selector (|=)","text":"

p[lang|=\"en\"] { property: value; }

HTML
<!-- WILL match -->\n<p lang=\"en\">English</p>\n<!-- WILL match -->\n<p lang=\"en-US\">American english</p>\n<!-- Will NOT match -->\n<p lang=\"fr\">Fran\u00e7ais</p>\n
"},{"location":"languages/css/css.html#pseudo-classes","title":"Pseudo-Classes","text":"

Pseudo-classes can style elements based on their current state. They must be specified after the base case.

CSS
selector:pseudo-class { property: value; }\n
"},{"location":"languages/css/css.html#link-pseudo-classes","title":"Link Pseudo-Classes","text":"

a:link {...} selects only <a> tags that have href attribute, same as a[href]. a:visited {...} selects links that have already been visited by the current browser.

"},{"location":"languages/css/css.html#user-action-pseudo-classes","title":"User Action Pseudo-Classes","text":"

a:hover {...} selects a link when the mouse rolls over it (hover state). a:active {...} selects the link while it's being activated (clicked or otherwise). selector:focus {...} selects an element when the user focuses on it (e.g. tab w/ keyboard). Often used on links, inputs, text-areas.

"},{"location":"languages/css/css.html#user-interface-state-pseudo-classes","title":"User Interface State Pseudo-Classes","text":"

input:enabled {...} selects an input that is in the default state of enabled and available for use. input:disabled {...} selects an input that has the attribute. input:checked {...} selects checkboxes or radio buttons that are checked. input:indeterminate {...} selects checkboxes or radio button that has neither selected nor unselected.

"},{"location":"languages/css/css.html#structural-position-pseudo-classes","title":"Structural & Position Pseudo-Classes","text":"

selector:first-child {...} selects an element if it's the first child within its parent. selector:last-child {...} selects an element if it's the last element within its parent. selector:only-child {...} will select an element if it is the only element within a parent.

selector:first-of-type {...} selects the first element of its type within a parent. selector:last-of-type {...} selects the last element of its type within a parent. selector:only-of-type {...} selects an element if it is the only of its type within a parent.

selector:nth-child() {...} selects elements based on a simple provided algebraic expression (e.g. \"2n\" or \"4n-1\"). Can select even/odd elements, \"every third\", \"the first five\", etc. selector:nth-of-type() {...} works like :nth-child in places where the elements at the same level are of different types. selector:nth-last-of-type() {...} like :nth-of-type but counts up from the bottom instead of the top. selector:nth-last-child() {...} like :nth-child but counts up from the bottom instead of the top.

"},{"location":"languages/css/css.html#empty-negation-pseudo-classes","title":"Empty & Negation Pseudo-Classes","text":"

selector:empty {...} selects elements with no content (empty tags). selector:not() {...} selects elements that do not have a certain tag, attribute, class, ID, etc.

"},{"location":"languages/css/css.html#pseudo-elements","title":"Pseudo-Elements","text":"

Dynamic elements that don't exist in the document tree. When used within selectors allow unique parts of the page to be stylized. Only one pseudo-element may be used within a selector at a given time.

"},{"location":"languages/css/css.html#textual-pseudo-elements","title":"Textual Pseudo-Elements","text":"

selector::first-letter {...} selects the first letter of the text within an element. selector::first-line {...} selects the first line of text within an element.

"},{"location":"languages/css/css.html#content-pseudo-elements","title":"Content Pseudo-Elements","text":"

selector::before {...} creates a pseudo-element before, or in front of, the selected element. selector::after {...} creates a pseudo-element after, or behind, the selected element. These pseudo-elements appear nested within the selected element, not outside of it.

CSS
selector::<after|before> {\n    property: value;\n    content: \" (\" attr(attribute_name) \")\";\n    property: value;\n}\n
"},{"location":"languages/css/css.html#fragment-pseudo-elements","title":"Fragment Pseudo-Elements","text":"

selector::selection {...} identifies part of the document that has been selected, or highlighted, by a user's actions.

"},{"location":"languages/css/css.html#css-cascading","title":"CSS Cascading","text":"

The browser assigns different priorities to CSS depending on the type of selector.

  1. Inline CSS (Most Important)
  2. ID selector
  3. Class selector
  4. Element selector (Least Important)

The browser also assigns priority based on the specificity of the selection. More specific selectors have higher priority. Rules lower in the file overwrite higher rules in the file.

"},{"location":"languages/css/css.html#cascading-override-with-important","title":"Cascading Override With !important","text":"

The !important declaration overrides any other declaration. Using it is very bad practice because it makes debugging more difficult by breaking the natural cascading in stylesheets.

Only use !important when:

CSS
selector[style*=\"property:value\"] {\n    property: value !important;\n}\n
"},{"location":"languages/css/css.html#specificity","title":"Specificity","text":"

A weight is applied to a CSS declaration, determined by the number of each selector type:

Note: The selectors declared inside :not() contribute to the weight.

"},{"location":"languages/css/css.html#units","title":"Units","text":""},{"location":"languages/css/css.html#absolute-length-units","title":"Absolute Length units","text":"Unit Name Equivalent to cm centimeters 1cm = 38px = 25/64in mm Millimeters 1mm = 1/10th of 1cm Q Quarter-millimeters 1Q = 1/40th of 1cm in Inches 1in = 2.54cm = 96px pc Picas 1pc = \u2159th of 1in pt Points 1pt = 1/72th of 1in px Pixels 1px = 1/96th of 1in"},{"location":"languages/css/css.html#relative-length-units","title":"Relative Length Units","text":"Unit Relative to rem Font size of the root element. em Font size of the parent or the element itself ex x-height of the element's font. ch The advance measure (width) of the glyph \"0\" of the element's font. lh Line height of the element. vw 1% of the viewport's width. vh 1% of the viewport's height. vmin 1% of the viewport's smaller dimension. vmax 1% of the viewport's larger dimension. % Relative to the parent element"},{"location":"languages/css/css.html#common-element-properties","title":"Common Element Properties","text":""},{"location":"languages/css/css.html#color","title":"Color","text":"CSS
selector {\n    color: color-name;\n    color: #<hex-digits>;\n    color: rgb();\n    color: hsl();\n}\n
"},{"location":"languages/css/css.html#background","title":"Background","text":"CSS
selector {\n    background: <image> <position> / <size> <repeat> <attachment> <origin> <clip> <color>;\n\n    background-image: <image-path>;\n\n    background-position: <top|bottom|left|right|center>;\n    background-position: <inherit|initial|revert|revert-layer|unset>;\n    background-position: <x> <y>\n\n    background-size: <size>;\n    background-size: <width> <height>;\n    background-size: <size>, <size>;  /* multiple background */\n\n\n    background-repeat: <horizontal> <vertical>;\n    background-repeat: <repeat|no-repeat|repeat-x|repeat-y|space|round>;\n\n    background-attachment: <scroll|fixed|local>;\n\n    background-origin: <border-box|padding-box|content-box>;\n    background-clip: <border-box|padding-box|content-box|text>\n\n    background-color: <color>;\n    background-color: color-name;\n    background-color: #<hex-digits>;\n    background-color: rgb();\n    background-color: hsl();\n}\n
"},{"location":"languages/css/css.html#font","title":"Font","text":"CSS
selector {\n    font: <style> <weight> <size> <family>;\n    font-style: <style>;\n    font-weight: <weight>;\n    font-size: <size>;\n    font-family: <family>;\n\n    /* specific font name */\n    font-family: \"Font Name\";\n\n    /* generic name */\n    font-family: generic-name;\n\n    /* comma separated list */\n    font-family: \"Font Name\", generic-name;\n}\n
"},{"location":"languages/css/css.html#text-decoration-aliment","title":"Text Decoration & Aliment","text":"CSS
selector {\n    text-decoration: <line> <color> <style> <thickness>;\n    text-align: alignment;\n}\n

text-decoration values:

text-align values:

"},{"location":"languages/css/css.html#size","title":"Size","text":"CSS
selector {\n    width: <size>;\n    max-width: <size>;\n    min-width: <size>;\n\n    height: <size>;\n    max-height: <size>;\n    min-height: <size>;\n\n    aspect-ratio: <width> / <height>;\n}\n

Note: width and height properties do not have effect on inline elements.

"},{"location":"languages/css/css.html#hiding-elements","title":"Hiding Elements","text":"

There are several methods to 'hide' elements:

Rule Collapse Events Tab Order display: none Yes No No visibility: hidden No No No opacity: 0 No Yes Yes"},{"location":"languages/css/css.html#box-model","title":"Box Model","text":""},{"location":"languages/css/css.html#padding","title":"Padding","text":"

Space between the border and the content.

It's possible to specify the padding for each side of the element:

CSS
selector {\n    padding-top: <size>;\n    padding-right: <size>;\n    padding-bottom: <size>;\n    padding-left: <size>;\n\n    padding: <top> <right> <bottom> <left>;  /* Four values (TRBL) */\n    padding: <top> <right/left> <bottom>;  /* Three values (T/TL/B) */\n    padding: <top/bottom> <right/left>;    /* Two values (TB/RL) */\n    padding: <all>;    /* One value */\n}\n

Note: Padding adds to the total size of the box, unless box-sizing: border-box; is used.

"},{"location":"languages/css/css.html#border","title":"Border","text":"

Borders are specified as \"size, style, color\".

CSS
selector {\n    border: <size> <style> <color>;\n    border-width: <size>;\n    border-style: <style>;\n    border-color: <color>;\n\n    border-top: <size> <style> <color>;\n    border-right: <size> <style> <color>;\n    border-bottom: <size> <style> <color>;\n    border-left: <size> <style> <color>;\n\n    border-top-width: <size>;\n    border-right-width: <size>;\n    border-bottom-width: <size>;\n    border-left-width: <size>;\n\n    border-top-style: <size>;\n    border-right-style: <size>;\n    border-bottom-style: <size>;\n    border-left-style: <size>;\n\n    border-top-color: <size>;\n    border-right-color: <size>;\n    border-bottom-color: <size>;\n    border-left-color: <size>;\n\n    border-radius: <top-left> <top-right> <bottom-tight> <bottom-left>;\n    border-radius: <top-left> <top-right/bottom-left> <bottom-right>;\n    border-radius: <top-left/bottom-right> <top-right/bottom-left>;\n    border-radius: <all>;\n\n    border-top-left-radius: <size>;\n    border-top-right-radius: <size>;\n    border-bottom-right-radius: <size>;\n    border-bottom-left-radius: <size>;\n}\n

Note: Border adds to the total size of the box, unless box-sizing: border-box; is used

"},{"location":"languages/css/css.html#box-sizing","title":"Box Sizing","text":"

Defines whether the width and height (and min/max) of an element should include padding and borders or not.

CSS
selector {\n    box-sizing: content-box;    /* Border and padding are not included */\n    box-sizing: border-box;    /* Include the content, padding and border */\n}\n
"},{"location":"languages/css/css.html#margin","title":"Margin","text":"

Transparent area around the box that separates it from other elements.

It's possible to specify the margin for each side of the element.

CSS
selector {\n    margin-top: <size>;\n    margin-right: <size>;\n    margin-bottom: <size>;\n    margin-left: <size>;\n\n    margin: <top> <right> <bottom> <left>;  /* Four values (TRBL) */\n    margin: <top> <right/left> <bottom>;  /* Three values (T/TL/B) */\n    margin: <top/bottom> <right/left>;    /* Two values (TB/RL) */\n    margin: <all>;    /* One value */\n}\n

Note: Top and bottom margins of near elements are collapsed into a single margin that is equal to the largest of the two margins.

"},{"location":"languages/css/css.html#element-positioning","title":"Element Positioning","text":""},{"location":"languages/css/css.html#static-positioning","title":"Static Positioning","text":"

All HTML elements are positioned static by default. Static elements are positioned in the normal flow of the page. Static elements ignore top, bottom, right, or left property specifications.

In normal flow block elements flow from top to bottom making a new line after every element. In normal flow inline elements flow from left to right wrapping to next line when needed.

CSS
selector {\n    position: static;\n}\n
"},{"location":"languages/css/css.html#relative-positioning","title":"Relative positioning","text":"

Takes the element out of the normal flow, allowing it to be moved in relation to the top, bottom, right, or left but does not affect the elements surrounding it. Makes an element a \"positioning context\" in which to position other elements relative to it. The relative value will still put the element in the normal flow, but then offset it according to top, bottom, right and left properties.

CSS
selector {\n    position: relative;\n}\n
"},{"location":"languages/css/css.html#absolute-positioning","title":"Absolute Positioning","text":"

Positions element outside of the normal flow and other elements act as if it's not there. An absolutely positioned element is offset from its container block, set with the properties top, bottom, right and left. Its container block is the first surrounding element that has any position other than static. If no such element is found, the container block is <html>.

CSS
selector {\n    position: absolute;\n}\n
"},{"location":"languages/css/css.html#fixed-positioning","title":"Fixed Positioning","text":"

The fixed value takes an element out of the normal flow, it positions it relative to the viewport. Parent positioning will no longer affect fixed elements.

CSS
selector {\n    position: fixed;\n}\n
"},{"location":"languages/css/css.html#sticky-positioning","title":"Sticky Positioning","text":"

Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.

CSS
selector {\n    position: sticky;\n}\n

Note: sticky is not supported by IE and still needs to be prefixed for webkit based browsers

"},{"location":"languages/css/css.html#z-index","title":"Z-Index","text":"

When elements overlap, the order of overlapping can be changed with z-index:

Nesting is important: if element B is on top of element A, a child of element A can never be higher than element B.

CSS
selector {\n    z-index: <int>;\n}\n
"},{"location":"languages/css/css.html#layouts","title":"Layouts","text":"CSS
div {\n    display: inline; /* Default of all elements, unless UA (user agent) stylesheet overrides */\n    display: block; /* block is default for elements like <div> and <section>*/\n    display: inline-block; /* Characteristics of block, but sits on a line */\n    display: flex;\n    display: grid; /* divide page into major regions or define the relationship in terms of size */\n    display: none; /* Hide */\n}\n
"},{"location":"languages/css/css.html#inline","title":"Inline","text":""},{"location":"languages/css/css.html#block","title":"Block","text":""},{"location":"languages/css/css.html#inline-block","title":"Inline Block","text":""},{"location":"languages/css/css.html#none","title":"None","text":""},{"location":"languages/css/css.html#flex","title":"Flex","text":"CSS
selector {\n    display: \"flex\";\n    flex-direction: <row|column>;\n}\n
"},{"location":"languages/css/css.html#grid","title":"Grid","text":"CSS
selector {\n    display: grid;\n    grid-template-columns: 1fr 1fr 1fr;  /* 3 equal columns */\n    grid-template-rows: 1fr 1fr 1fr;  /* 3 equal rows */\n}\n
"},{"location":"languages/css/css.html#variables","title":"Variables","text":"CSS
:root {\n    /* define variables on :root element */\n    --variable: value;\n}\n\nselector {\n    --variable: value;  /* overwrite value */\n    prop: var(--variable);  /* use value of variable */\n}\n
"},{"location":"languages/css/css.html#responsive-design","title":"Responsive Design","text":"

A responsive website or application automatically adjusts to the screen and adapts to any device.

"},{"location":"languages/css/css.html#viewport-meta-tag","title":"Viewport Meta-Tag","text":"

Is located in the <head> of the HTML document. It defines how a site should render in a web browser for mobile devices and makes media queries will work as intended.

HTML
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n
"},{"location":"languages/css/css.html#media-queries","title":"Media Queries","text":"

Media queries allow the customization of web pages for specific devices screen sizes. A media query is a logical expression: true or false; if a media query is true, the related rules are applied to the target device.

CSS
@media type operator (feature) {\n    selector { property: value; }\n}\n\n/* AND logic: Both conditions must be true */\n@media screen and (min-width: 400px) and (orientation: landscape) {\n    selector { property: value; }\n}\n/* OR logic: At least one conditions should be true */\n@media screen and (min-width: 400px), screen and (orientation: landscape) {\n    selector { property: value; }\n}\n\n/* NOT logic: Negates the entire condition */\n@media not all and (orientation: landscape) {\n    selector { property: value; }\n}\n

Types:

Features:

It's possible to specify a media attribute in the link element. This applies a whole stylesheet when the condition is true:

HTML
<link rel=\"stylesheet\" media=\"screen and (min-width: 900px)\" href=\"widescreen.css\">\n<link rel=\"stylesheet\" media=\"screen and (max-width: 600px)\" href=\"smallscreen.css\">\n

It's also possible to have different stylesheets based on media type:

HTML
<link rel=\"stylesheet\" type=\"text/css\" href=\"screen.css\" media=\"screen\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"print.css\" media=\"print\">\n
"},{"location":"languages/dotnet/asp.net/blazor.html","title":"Blazor","text":"

Blazor apps are based on components. A component in Blazor is an element of UI, such as a page, dialog, or data entry form.

Components are .NET C# classes built into .NET assemblies that:

The component class is usually written in the form of a Razor markup page with a .razor file extension. Components in Blazor are formally referred to as Razor components.

"},{"location":"languages/dotnet/asp.net/blazor.html#components-razor","title":"Components (.razor)","text":"

Blazor Components

C#
@page \"/route/{RouteParameter}\"  // make component accessible from a URL\n@page \"/route/{RouteParameter?}\"  // specify route parameter as optional\n@page \"/route/{RouteParameter:<type>}\"  // specify route parameter type\n\n@namespace <Namespace>  // set the component namespace\n@using <Namespace>  // using statement\n@inherits BaseType  // inheritance\n@attribute [Attribute]  // apply an attribute\n@inject Type objectName  // dependency injection\n\n// html of the page here\n\n<Namespace.ComponentFolder.Component />  // access component w/o @using\n<Component Property=\"value\"/>  // insert component into page, passing attributes\n<Component @onclick=\"@CallbackMethod\">\n    @ChildContent  // segment of UI content\n</Component>\n\n@code {\n    // component model (Properties, Methods, ...)\n\n    [Parameter]  // capture attribute \n    public Type Property { get; set; } = defaultValue;\n\n    [Parameter]  // capture route parameters\n    public type RouteParameter { get; set;}\n\n    [Parameter] // segment of UI content\n    public RenderFragment ChildContent { get; set;}\n\n    private void CallbackMethod() { }\n}\n
"},{"location":"languages/dotnet/asp.net/blazor.html#state-management","title":"State Management","text":""},{"location":"languages/dotnet/asp.net/blazor.html#passing-state-with-navigationmanager","title":"Passing state with NavigationManager","text":"

It's now possible to pass state when navigating in Blazor apps using the NavigationManager.

C#
navigationManager.NavigateTo(\"/<route>\", new NavigationOptions { HistoryEntryState = value });\n

This mechanism allows for simple communication between different pages. The specified state is pushed onto the browser\u2019s history stack so that it can be accessed later using either the NavigationManager.HistoryEntryState property or the LocationChangedEventArgs.HistoryEntryState property when listening for location changed events.

"},{"location":"languages/dotnet/asp.net/blazor.html#blazor-wasm","title":"Blazor WASM","text":"C#
// setup state singleton\nbuilder.Services.AddSingleton<StateContainer>();\n
C#
// StateContainer singleton\nusing System;\n\npublic class StateContainer\n{\n    private int _counter;\n\n    public string Property\n    {\n        get => _counter;\n        set\n        {\n            _counter = value;\n            NotifyStateChanged();  // will trigger StateHasChanged(), causing a render \n        }\n    }\n\n    public event Action OnChange;\n\n    private void NotifyStateChanged() => OnChange?.Invoke();\n}\n
C#
// component that changes the state\n@inject StateContainer State\n\n// Delegate event handlers automatically trigger a UI render\n<button @onClick=\"@HandleClick\">\n    Change State\n</button>\n\n@code {\n    private void HandleClick()\n    {\n        State.Property += 1;  // update state\n    }\n}\n
C#
// component that should be update on state change\n@implements IDisposable\n@inject StateContainer State\n\n<p>Property: <b>@State.Property</b></p>\n\n@code {\n\n    // StateHasChanged notifies the component that its state has changed. \n    // When applicable, calling StateHasChanged causes the component to be rerendered.\n\n    protected override void OnInitialized()\n    {\n        State.OnChange += StateHasChanged;\n    }\n\n    public void Dispose()\n    {\n        State.OnChange -= StateHasChanged;\n    }\n}\n
"},{"location":"languages/dotnet/asp.net/blazor.html#data-binding-events","title":"Data Binding & Events","text":"C#
<p>\n    <button @on{DOM EVENT}=\"{DELEGATE}\" />\n    <button @on{DOM EVENT}=\"{DELEGATE}\" @on{DOM EVENT}:preventDefault />  // prevent default action\n    <button @on{DOM EVENT}=\"{DELEGATE}\" @on{DOM EVENT}:preventDefault=\"{CONDITION}\" />  // prevent default action if CONDITION is true\n\n    <button @on{DOM EVENT}=\"{DELEGATE}\" @on{DOM EVENT}:stopPropagation />\n    <button @on{DOM EVENT}=\"{DELEGATE}\" @on{DOM EVENT}:stopPropagation=\"{CONDITION}\" />  // stop event propagation if CONDITION is true\n\n    <button @on{DOM EVENT}=\"@(e => Property = value)\" />  // change internal state w/ lambda\n    <button @on{DOM EVENT}=\"@(e => DelegateAsync(e, value))\" />  // invoke delegate w/ lambda\n\n    <input @ref=\"elementReference\" />\n\n    <input @bind=\"{PROPERTY}\" /> // updates variable on ONCHANGE event (focus loss)\n    <input @bind=\"{PROPERTY}\" @bind:event=\"{DOM EVENT}\" />  // updates value on DOM EVENT\n    <input @bind=\"{PROPERTY}\" @bind:format=\"{FORMAT STRING}\" />  // use FORMAT STRING to display value\n\n    <ChildComponent @bind-{PROPERTY}=\"{PROPERTY}\" @bind-{PROPERTY}:event=\"{EVENT}\" />  // bind to child component {PROPERTY}\n    <ChildComponent @bind-{PROPERTY}=\"{PROPERTY}\" @bind-{PROPERTY}:event=\"{PROPERTY}Changed\" />  // bind to child component {PROPERTY}, listen for custom event\n\n    <input @bind=\"{PROPERTY}\" @bind:after=\"{DELEGATE}\" />  // run async logic after bind event completion\n    <input @bind:get=\"{PROPERTY}\" @bind:set=\"PropertyChanged\" />  // two-way data binding\n</p>\n\n@code {\n    private ElementReference elementReference;\n\n    public string Property { get; set; }\n\n    public EventCallback<Type> PropertyChanged { get; set; }  // custom event {PROPERTY}Changed\n\n    // invoke custom event\n    public async Task DelegateAsync(EventArgs e, Type argument)\n    {   \n        /* ... */\n\n        await PropertyChanged.InvokeAsync(e, argument);  // notify parent bound prop has changed\n        await elementReference.FocusAsync();  // focus an element in code\n    }\n\n    [Parameter] public TValue Value { get; set; }\n    [Parameter] public EventCallback<TValue> ValueChanged { get; set; }\n}\n

Note: When a user provides an unparsable value to a data-bound element, the unparsable value is automatically reverted to its previous value when the bind event is triggered. Note: The @bind:get and @bind:set modifiers are always used together. The @bind:get modifier specifies the value to bind to and the @bind:set modifier specifies a callback that is called when the value changes

"},{"location":"languages/dotnet/asp.net/blazor.html#javascriptnet-interop","title":"Javascript/.NET Interop","text":"

Call Javascript from .NET Call .NET from Javascript

"},{"location":"languages/dotnet/asp.net/blazor.html#render-blazor-components-from-javascript","title":"Render Blazor components from JavaScript","text":"

To render a Blazor component from JavaScript, first register it as a root component for JavaScript rendering and assign it an identifier:

C#
// Blazor Server\nbuilder.Services.AddServerSideBlazor(options =>\n{\n    options.RootComponents.RegisterForJavaScript<Counter>(identifier: \"counter\");\n});\n\n// Blazor WebAssembly\nbuilder.RootComponents.RegisterForJavaScript<Counter>(identifier: \"counter\");\n

Load Blazor into the JavaScript app (blazor.server.js or blazor.webassembly.js) and then render the component from JavaScript into a container element using the registered identifier, passing component parameters as needed:

JavaScript
let containerElement = document.getElementById('my-counter');\nawait Blazor.rootComponents.add(containerElement, 'counter', { incrementAmount: 10 });\n
"},{"location":"languages/dotnet/asp.net/blazor.html#blazor-custom-elements","title":"Blazor custom elements","text":"

Experimental support is also now available for building custom elements with Blazor using the Microsoft.AspNetCore.Components.CustomElements NuGet package. Custom elements use standard HTML interfaces to implement custom HTML elements.

To create a custom element using Blazor, register a Blazor root component as custom elements like this:

C#
options.RootComponents.RegisterAsCustomElement<Counter>(\"my-counter\");\n
"},{"location":"languages/dotnet/asp.net/filters.html","title":"Filters","text":"

Filters in ASP.NET Core allow code to be run before or after specific stages in the request processing pipeline.

Built-in filters handle tasks such as:

Custom filters can be created to handle cross-cutting concerns. Examples of cross-cutting concerns include error handling, caching, configuration, authorization, and logging. Filters avoid duplicating code.

"},{"location":"languages/dotnet/asp.net/filters.html#how-filters-work","title":"How filters work","text":"

Filters run within the ASP.NET Core action invocation pipeline, sometimes referred to as the filter pipeline. The filter pipeline runs after ASP.NET Core selects the action to execute.

"},{"location":"languages/dotnet/asp.net/filters.html#filter-types","title":"Filter types","text":"

Each filter type is executed at a different stage in the filter pipeline:

"},{"location":"languages/dotnet/asp.net/filters.html#implementation","title":"Implementation","text":"

Filters support both synchronous and asynchronous implementations through different interface definitions.

For example, OnActionExecuting is called before the action method is called. OnActionExecuted is called after the action method returns. Asynchronous filters define an On-Stage-ExecutionAsync method, for example OnActionExecutionAsync.

Interfaces for multiple filter stages can be implemented in a single class.

C#
public class SampleActionFilter : IActionFilter\n{\n    public void OnActionExecuting(ActionExecutingContext context)\n    {\n        // Do something before the action executes.\n    }\n\n    public void OnActionExecuted(ActionExecutedContext context)\n    {\n        // Do something after the action executes.\n    }\n}\n\n\npublic class SampleAsyncActionFilter : IAsyncActionFilter\n{\n    public async Task OnActionExecutionAsync(\n        ActionExecutingContext context, ActionExecutionDelegate next)\n    {\n        // Do something before the action executes.\n        await next();\n        // Do something after the action executes.\n    }\n}\n
"},{"location":"languages/dotnet/asp.net/filters.html#built-in-filter-attributes","title":"Built-in filter attributes","text":"

ASP.NET Core includes built-in attribute-based filters that can be subclassed and customized. Several of the filter interfaces have corresponding attributes that can be used as base classes for custom implementations.

Filter attributes:

"},{"location":"languages/dotnet/asp.net/filters.html#filter-scopes","title":"Filter scopes","text":"

A filter can be added to the pipeline at one of three scopes:

C#
services.AddScoped<CustomActionFilterAttribute>();\n\n[ServiceFilter(typeof(CustomActionFilterAttribute))]\npublic IActionResult Action()\n{\n    return Ok();\n}\n
C#
services.AddControllersWithViews(options => { \n    options.Filters.Add(new CustomResponseFilterAttribute(args)); \n});\n\n\n[CustomResponseFilterAttribute(args)]\npublic class SampleController : Controller\n
C#
builder.Services.AddControllersWithViews(options =>\n{\n    options.Filters.Add(typeof(CustomActionFilter));\n});\n
"},{"location":"languages/dotnet/asp.net/filters.html#filter-order-of-execution","title":"Filter Order of Execution","text":"

When there are multiple filters for a particular stage of the pipeline, scope determines the default order of filter execution. Global filters surround class filters, which in turn surround method filters.

As a result of filter nesting, the after code of filters runs in the reverse order of the before code. The filter sequence:

"},{"location":"languages/dotnet/asp.net/filters.html#cancellation-and-short-circuiting","title":"Cancellation and Short-Circuiting","text":"

The filter pipeline can be short-circuited by setting the Result property on the ResourceExecutingContext parameter provided to the filter method.

C#
public class ShortCircuitingResourceFilterAttribute : Attribute, IResourceFilter\n{\n    public void OnResourceExecuting(ResourceExecutingContext context)\n    {\n        context.Result = new ContentResult()\n        {\n            Content = \"Resource unavailable - header not set.\"\n        };\n    }\n\n    public void OnResourceExecuted(ResourceExecutedContext context)\n    {\n    }\n}\n
"},{"location":"languages/dotnet/asp.net/filters.html#dependency-injection","title":"Dependency Injection","text":"

Filters can be added by type or by instance. If an instance is added, that instance is used for every request. If a type is added, it's type-activated.

A type-activated filter means:

Filters that are implemented as attributes and added directly to controller classes or action methods cannot have constructor dependencies provided by dependency injection (DI). Constructor dependencies cannot be provided by DI because attributes must have their constructor parameters supplied where they're applied.

The following filters support constructor dependencies provided from DI:

"},{"location":"languages/dotnet/asp.net/filters.html#servicefilterattribute","title":"ServiceFilterAttribute","text":"C#
builder.Services.AddScoped<CustomFilterFromDI>();\n\npublic class CustomFilterFromDI : IResultFilter\n{\n    private readonly ILogger _logger;\n\n    public CustomFilterFromDI(ILogger logger) =>  _logger = logger;\n\n    public void OnResultExecuting(ResultExecutingContext context)\n    {\n    }\n\n    public void OnResultExecuted(ResultExecutedContext context)\n    {\n    }\n}\n\n[ServiceFilter(typeof(CustomFilterFromDI))]\npublic IActionResult Action() => OK();\n
"},{"location":"languages/dotnet/asp.net/middleware.html","title":"Middleware","text":"

Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component:

Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.

Request delegates are configured using Run, Map, and Use extension methods.

An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are middleware, also called middleware components.

Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. When a middleware short-circuits, it's called a terminal middleware because it prevents further middleware from processing the request.

"},{"location":"languages/dotnet/asp.net/middleware.html#middleware-pipeline","title":"Middleware Pipeline","text":"

The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the other.

Each delegate can perform operations before and after the next delegate. Exception-handling delegates should be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline. It's possible to chain multiple request delegates together with Use.

The next parameter represents the next delegate in the pipeline. It's possible to short-circuit the pipeline by not calling the next parameter. When a delegate doesn't pass a request to the next delegate, it's called short-circuiting the request pipeline. Short-circuiting is often desirable because it avoids unnecessary work.

It's possible to perform actions both before and after the next delegate:

C#
// \"inline\" middleware, best if in own class\napp.Use(async (context, next) =>\n{\n    // Do work that doesn't write to the Response.\n    await next.Invoke();\n    // Do logging or other work that doesn't write to the Response.\n});\n

Run delegates don't receive a next parameter. The first Run delegate is always terminal and terminates the pipeline.

C#
// \"inline\" middleware, best if in own class\napp.Use(async (context, next) =>\n{\n    // Do work that doesn't write to the Response.\n    await next.Invoke();\n    // Do logging or other work that doesn't write to the Response.\n});\n\napp.Run(async context =>\n{\n    // no invocation of next\n});\n
"},{"location":"languages/dotnet/asp.net/middleware.html#middleware-order","title":"Middleware Order","text":"

The Endpoint middleware executes the filter pipeline for the corresponding app type.

The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.

C#
if (env.IsDevelopment())\n{\n    app.UseDeveloperExceptionPage();\n    app.UseDatabaseErrorPage();\n}\nelse\n{\n    app.UseExceptionHandler(\"/Error\");\n    app.UseHsts();\n}\n\napp.UseHttpsRedirection();\napp.UseStaticFiles();\napp.UseCookiePolicy();\n\napp.UseRouting();\napp.UseRequestLocalization();\napp.UseCors();\n\napp.UseAuthentication();\napp.UseAuthorization();\napp.UseSession();\napp.UseResponseCompression();\napp.UseResponseCaching();\n\napp.UseEndpoints(endpoints =>\n{\n    endpoints.MapRazorPages();\n    endpoints.MapControllers();\n});\n

Built-in Middleware

"},{"location":"languages/dotnet/asp.net/middleware.html#branching-the-middleware-pipeline","title":"Branching the Middleware Pipeline","text":"

Map extensions are used as a convention for branching the pipeline. Map branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.

When Map is used, the matched path segments are removed from HttpRequest.Path and appended to HttpRequest.PathBase for each request.

MapWhen branches the request pipeline based on the result of the given predicate. Any predicate of type Func<HttpContext, bool> can be used to map requests to a new branch of the pipeline.

UseWhen also branches the request pipeline based on the result of the given predicate. Unlike with MapWhen, this branch is rejoined to the main pipeline if it doesn't short-circuit or contain a terminal middleware.

"},{"location":"languages/dotnet/asp.net/middleware.html#custom-middleware-classes","title":"Custom Middleware Classes","text":"

Middleware is generally encapsulated in a class and exposed with an extension method.

C#
public class CustomMiddleware\n{\n    private readonly RequestDelegate _next;\n\n    public CustomMiddleware(RequestDelegate next)\n    {\n        _next = next;\n    }\n\n    public async Task InvokeAsync(HttpContext context)\n    {\n        // Do work that doesn't write to the Response.\n        await _next(context);  // Call the next delegate/middleware in the pipeline\n        // Do logging or other work that doesn't write to the Response.\n    }\n}\n

The middleware class must include:

"},{"location":"languages/dotnet/asp.net/middleware.html#middleware-extension-methods","title":"Middleware Extension Methods","text":"C#
using Microsoft.AspNetCore.Builder;\n\npublic static class MiddlewareExtensions\n{\n    public static IApplicationBuilder UseCustom(this IApplicationBuilder builder)\n    {\n        return builder.UseMiddleware<CustomMiddleware>();\n    }\n}\n
C#
// other middlewares\n\napp.UseCustom();  // add custom middleware in the pipeline\n\napp.UseEndpoints(endpoints => endpoints.MapControllers());\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html","title":"Minimal API","text":"

Note: Requires .NET 6+

C#
var builder = WebApplication.CreateBuilder(args);\n\nbuilder.Services.AddSingleton<IService, Service>();\nbuilder.Services.AddScoped<IService, Service>();\nbuilder.Services.AddTransient<IService, Service>();\n\nvar app = builder.Build();\n\n// [...]\n\napp.Run();\n//or\napp.RunAsync();\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#application-settings","title":"Application Settings","text":"

App settings are loaded (in order) from:

  1. appsettings.json
  2. appsettings.<Environment>.json
  3. User Secrets

The environment is controlled by the env var ASPNETCORE_ENVIRONMENT. If a setting is present in multiple locations, the last one is used and overrides the previous ones.

"},{"location":"languages/dotnet/asp.net/minimal-api.html#user-secrets","title":"User Secrets","text":"

User secrets are specific to each machine and can be initialized with dotnet user-secrets init. Each application is linked with it's settings by a guid.

The settings are stored in:

Setting a value is done with dotnet user-secrets set <key> <value>, keys can be nested by separating each level with : or __.

"},{"location":"languages/dotnet/asp.net/minimal-api.html#swagger","title":"Swagger","text":"C#
builder.Services.AddEndpointsApiExplorer();\nbuilder.Services.AddSwaggerGen();\n\n// [...]\n\napp.UseSwagger();\napp.UseSwaggerUI();\n\n// add returned content metadata to Swagger\napp.MapGet(\"/route\", Handler).Produces<Type>(statusCode);\n\n// add request body contents metadata to Swagger\napp.MapPost(\"/route\", Handler).Accepts<Type>(contentType);\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#mvc","title":"MVC","text":"C#
builder.Services.AddControllersWithViews();\n//or\nbuilder.Services.AddControllers();\n\n// Configure the HTTP request pipeline.\nif (app.Environment.IsDevelopment())\n{\n    app.UseDeveloperExceptionPage();\n}\nelse\n{\n    app.UseExceptionHandler(\"/Home/Error\");\n\n    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.\n    app.UseHsts();\n}\n\napp.UseHttpsRedirection();\napp.UseStaticFiles();\n\napp.UseRouting();\n\napp.UseAuthorization();\n\napp.MapControllers();\n// or\napp.MapControllerRoute(\n    name: \"default\",\n    pattern: \"{controller=Home}/{action=Index}/{id?}\");\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#routing-handlers-results","title":"Routing, Handlers & Results","text":"

To define routes and handlers using Minimal APIs, use the Map(Get|Post|Put|Delete) methods.

C#
// the dependencies are passed as parameters in the handler delegate\napp.MapGet(\"/route/{id}\", (IService service, int id) => {\n\n    return entity is not null ? Results.Ok(entity) : Results.NotFound();\n});\n\n// pass delegate to use default values\napp.MapGet(\"/search/{id}\", Search);\nIResult Search(int id, int? page = 1, int? pageSize = 10) { /* ... */ }\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#route-groups","title":"Route Groups","text":"

The MapGroup() extension method, which helps organize groups of endpoints with a common prefix. It allows for customizing entire groups of endpoints with a singe call to methods like RequireAuthorization() and WithMetadata().

C#
var group = app.MapGroup(\"<route-prefix>\");\n\ngroup.MapGet(\"/\", GetAllTodos);  // route: /<route-prefix>\ngroup.MapGet(\"/{id}\", GetTodo);  // route: /<route-prefix>/{id}\n\n// [...]\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#typedresults","title":"TypedResults","text":"

The Microsoft.AspNetCore.Http.TypedResults static class is the \u201ctyped\u201d equivalent of the existing Microsoft.AspNetCore.Http.Results class. It's possible to use TypedResults in minimal APIs to create instances of the in-framework IResult-implementing types and preserve the concrete type information.

C#
public static async Task<IResult> GetAllTodos(TodoDb db)\n{\n    return TypedResults.Ok(await db.Todos.ToArrayAsync());\n}\n
C#
[Fact]\npublic async Task GetAllTodos_ReturnsOkOfObjectResult()\n{\n    // Arrange\n    var db = CreateDbContext();\n\n    // Act\n    var result = await TodosApi.GetAllTodos(db);\n\n    // Assert: Check the returned result type is correct\n    Assert.IsType<Ok<Todo[]>>(result);\n}\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#multiple-result-types","title":"Multiple Result Types","text":"

The Results<TResult1, TResult2, TResultN> generic union types, along with the TypesResults class, can be used to declare that a route handler returns multiple IResult-implementing concrete types.

C#
// Declare that the lambda returns multiple IResult types\napp.MapGet(\"/todos/{id}\", async Results<Ok<Todo>, NotFound> (int id, TodoDb db)\n{\n    return await db.Todos.FindAsync(id) is Todo todo\n        ? TypedResults.Ok(todo)\n        : TypedResults.NotFound();\n});\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#filters","title":"Filters","text":"C#
public class ExampleFilter : IRouteHandlerFilter\n{\n    public async ValueTask<object?> InvokeAsync(RouteHandlerInvocationContext context, RouteHandlerFilterDelegate next)\n    {\n        // before endpoint call\n        var result = next(context);\n        /// after endpoint call\n        return result;\n    }\n}\n
C#
app.MapPost(\"/route\", Handler).AddFilter<ExampleFilter>();\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#context","title":"Context","text":"

With Minimal APIs it's possible to access the contextual information by passing one of the following types as a parameter to your handler delegate:

C#
app.MapGet(\"/hello\", (ClaimsPrincipal user) => {\n    return \"Hello \" + user.FindFirstValue(\"sub\");\n});\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#openapi","title":"OpenAPI","text":"

The Microsoft.AspNetCore.OpenApi package exposes a WithOpenApi extension method that generates an OpenApiOperation derived from a given endpoint\u2019s route handler and metadata.

C#
app.MapGet(\"/todos/{id}\", (int id) => ...)\n    .WithOpenApi();\n\napp.MapGet(\"/todos/{id}\", (int id) => ...)\n    .WithOpenApi(operation => {\n        operation.Summary = \"Retrieve a Todo given its ID\";\n        operation.Parameters[0].AllowEmptyValue = false;\n    });\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#validation","title":"Validation","text":"

Using Minimal Validation by Damian Edwards. Alternatively it's possible to use Fluent Validation.

C#
app.MapPost(\"/widgets\", (Widget widget) => {\n    var isValid = MinimalValidation.TryValidate(widget, out var errors);\n\n    if(isValid)\n    {\n        return Results.Created($\"/widgets/{widget.Name}\", widget);\n    }\n\n    return Results.BadRequest(errors);\n});\n\nclass Widget\n{\n    [Required, MinLength(3)]\n    public string? Name { get; set; }\n\n    public override string? ToString() => Name;\n}\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#json-serialization","title":"JSON Serialization","text":"C#
// Microsoft.AspNetCore.Http.Json.JsonOptions\nbuilder.Services.Configure<JsonOptions>(opt =>\n{\n    opt.SerializerOptions.PropertyNamingPolicy = new SnakeCaseNamingPolicy();\n});\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#authorization","title":"Authorization","text":"C#
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();\n\nbuilder.Services.AddAuthorization();\n// or\nbuilder.Services.AddAuthorization(options =>\n{\n    // for all endpoints\n    options.FallbackPolicy = new AuthorizationPolicyBuilder()\n      .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)\n      .RequireAuthenticatedUser();\n})\n// or\nbuilder.Authentication.AddJwtBearer();  // will automatically add required middlewares\n\n// [...]\n\napp.UseAuthentication();\napp.UseAuthorization(); // must come before routes\n\n// [...]\n\napp.MapGet(\"/alcohol\", () => Results.Ok()).RequireAuthorization(\"<policy>\");  // on specific endpoints\napp.MapGet(\"/free-for-all\", () => Results.Ok()).AllowAnonymous();\napp.MapGet(\"/special-secret\", () => \"This is a special secret!\")\n    .RequireAuthorization(p => p.RequireClaim(\"scope\", \"myapi:secrets\"));\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#local-jwt-tokens","title":"Local JWT Tokens","text":"

The user-jwts tool is similar in concept to the existing user-secrets tools, in that it can be used to manage values for the app that are only valid for the current user (the developer) on the current machine. In fact, the user-jwts tool utilizes the user-secrets infrastructure to manage the key that the JWTs will be signed with, ensuring it\u2019s stored safely in the user profile.

Bash
dotnet user-jwts create  # configure a dev JWT fot the current user\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#output-caching","title":"Output Caching","text":"C#
builder.Services.AddOutputCaching();  // no special options\nbuilder.Services.AddOutputCaching(options => \n{\n    options => options.AddBasePolicy(x => x.NoCache())  // no cache policy\n\n    Func<OutputCacheContext, bool> predicate = /* discriminate requests */\n    options.AddBasePolicy(x => x.With(predicate).CachePolicy());\n    options.AddBasePolicy(\"<policy-name>\", x => x.CachePolicy());  // named policy\n});\n\n// [...]\n\napp.UseOutputCaching();  // following middlewares can use output cache\n\n// [...]\n\napp.MapGet(\"/<route>\", RouteHandler).CacheOutput();  // cache forever\napp.MapGet(\"/<route>\", RouteHandler).CacheOutput().Expire(timespan);\n\napp.MapGet(\"/<route>\", RouteHandler).CacheOutput(x => x.CachePolicy());\napp.MapGet(\"/<route>\", RouteHandler).CacheOutput(\"<policy-name>\");\n\napp.MapGet(\"/<route>\", RouteHandler).CacheOutput(x => x.VaryByHeader(/* headers list */));\napp.MapGet(\"/<route>\", RouteHandler).CacheOutput(x => x.VaryByQuery(/* query key */));\napp.MapGet(\"/<route>\", RouteHandler).CacheOutput(x => x.VaryByValue());\n\napp.MapGet(\"/<route>\", [OutputCache(/* options */)]RouteHandler);\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#cache-eviction","title":"Cache Eviction","text":"C#
app.MapGet(\"/<route-one>\", RouteHandler).CacheOutput(x => x.Tag(\"<tag>\"));  // tag cache portion\n\napp.MapGet(\"/<route-two>\", (IOutputCacheStore cache, CancellationToken token) => \n{\n    await cache.EvictByTag(\"<tag>\", token);  // invalidate a portion of the cache\n});\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#custom-cache-policy","title":"Custom Cache Policy","text":"C#
app.MapGet(\"/<route-one>\", RouteHandler).CacheOutput(x => x.AddCachePolicy<CustomCachePolicy>());\n
C#
class CustomCachePolicy : IOutputCachePolicy\n{\n    public ValueTask CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken) { }\n\n    public ValueTask ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellationToken) { }\n\n    public ValueTask ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken) { }\n}\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#options-pattern","title":"Options Pattern","text":"

The options pattern uses classes to provide strongly-typed access to groups of related settings.

JSON
{\n    \"SecretKey\": \"Secret key value\",\n    \"TransientFaultHandlingOptions\": {\n        \"Enabled\": true,\n        \"AutoRetryDelay\": \"00:00:07\"\n    },\n    \"Logging\": {\n        \"LogLevel\": {\n            \"Default\": \"Information\",\n            \"Microsoft\": \"Warning\",\n            \"Microsoft.Hosting.Lifetime\": \"Information\"\n        }\n    }\n}\n
C#
// options model for binding\npublic class TransientFaultHandlingOptions\n{\n    public bool Enabled { get; set; }\n    public TimeSpan AutoRetryDelay { get; set; }\n}\n
C#
// setup the options\nbuilder.Services.Configure<TransientFaultHandlingOptions>(builder.Configuration.GetSection<TransientFaultHandlingOptions>(nameof(Options)));\nbuilder.Services.Configure<TransientFaultHandlingOptions>(builder.Configuration.GetSection<TransientFaultHandlingOptions>(key));\n
C#
class DependsOnOptions\n{\n  private readonly IOptions<TransientFaultHandlingOptions> _options;\n\n  public DependsOnOptions(IOptions<TransientFaultHandlingOptions> options) => _options = options;\n}\n
"},{"location":"languages/dotnet/asp.net/minimal-api.html#options-interfaces","title":"Options interfaces","text":"

IOptions<TOptions>:

IOptionsSnapshot<TOptions>:

IOptionsMonitor<TOptions>:

"},{"location":"languages/dotnet/asp.net/razor-syntax.html","title":"Razor Syntax","text":""},{"location":"languages/dotnet/asp.net/razor-syntax.html#markup","title":"Markup","text":"C#
@page  // set this as razor page\n\n@model <App>.Models.Entity  // if MVC set type of elements passed to the view \n@model <Page>Model  // if Razor page set underlying class\n\n@* razor comment *@\n\n// substitute @variable with it's value\n<tag>@variable</tag>\n\n@{\n    // razor code block\n    // can contain C# or HTML\n\n    Model  // access to passed @model (MVC)\n}\n\n@if (condition) { }\n\n@for (init, condition, iteration) { }\n\n@Model.Property  // display Property value (MVC)\n
"},{"location":"languages/dotnet/asp.net/razor-syntax.html#tag-helpers-aspnet-core","title":"Tag Helpers (ASP.NET Core)","text":"

Tag helpers are reusable components for automating the generation of HTML in Razor Pages. Tag helpers target specific HTML tags.

Example:

HTML
<!-- tag helpers for a lin in ASP.NET MVC -->\n<a class=\"nav-link text-dark\" asp-area=\"\" asp-controller=\"Home\" asp-action=\"Index\">Home</a>\n
"},{"location":"languages/dotnet/asp.net/razor-syntax.html#managing-tag-helpers","title":"Managing Tag Helpers","text":"

The @addTagHelper directive makes Tag Helpers available to the view. Generally, the view file is Pages/_ViewImports.cshtml, which by default is inherited by all files in the Pages folder and subfolders, making Tag Helpers available.

C#
@using <App>\n@namespace <App>.Pages  // or <Project>.Models\n@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers\n

The first parameter after @addTagHelper specifies the Tag Helpers to load (* for all Tag Helpers), and the second parameter (e.g. Microsoft.AspNetCore.Mvc.TagHelpers) specifies the assembly containing the Tag Helpers. Microsoft.AspNetCore.Mvc.TagHelpers is the assembly for the built-in ASP.NET Core Tag Helpers.

"},{"location":"languages/dotnet/asp.net/razor-syntax.html#opting-out-of-individual-elements","title":"Opting out of individual elements","text":"

It's possible to disable a Tag Helper at the element level with the Tag Helper opt-out character (!)

Text Only
<!-- disable email validation -->\n<!span asp-validation-for=\"Email\" ></!span>\n
"},{"location":"languages/dotnet/asp.net/razor-syntax.html#explicit-tag-helpers","title":"Explicit Tag Helpers","text":"

The @tagHelperPrefix directive allows to specify a tag prefix string to enable Tag Helper support and to make Tag Helper usage explicit.

Text Only
@tagHelpersPrefix th:\n
"},{"location":"languages/dotnet/asp.net/razor-syntax.html#important-tag-helpers-asp-html-helpers-html","title":"Important Tag Helpers (asp-) & HTML Helpers (@Html)","text":"

Understanding Html Helpers

C#
@model <App>.Models.Entity\n\n// Display the name of the property\n@Html.DisplayNameFor(model => model.EntityProp)\n@nameof(Model.EntityProp)\n\n// Display the value of the property\n@Html.DisplayFor(model => model.EntityProp)\n@Model.EntityProp\n\n<from>\n    // use the property as the label, eventually w/ [DisplayName(\"...\")]\n    <label asp-for=\"EntityProp\"></label>\n    @Html.LabelFor()\n\n    // automatically set the value at form compilation and submission\n    <input asp-for=\"EntityProp\"/>\n    @Html.EditorFor()\n</from>\n\n// route config is {Controller}/{Action}/{Id?}\n<a asp-controller=\"<Controller>\" asp-action=\"<Action>\">Link</a>  // link to /Controller/Action\n<a asp-controller=\"<Controller>\" asp-action=\"<Action>\" asp-route-Id=\"@model.Id\">Link</a>  // link to /Controller/Action/Id\n@Html.ActionLink(\"<Link Text>\", \"<Action>\", \"<Controller>\", new { @HTmlAttribute = value, Id = value }) // link to /Controller/Action/Id\n\n// link to /Controller/Action?queryParameter=value\n@Html.ActionLink(\"<Link Text>\", \"<Action>\", \"<Controller>\", new { @HTmlAttribute = value, queryParameter = value })\n<a asp-controller=\"<Controller>\" asp-action=\"<Action>\" asp-route-queryParameter=\"value\">Link</a>  // asp-route-* for query strings\n
"},{"location":"languages/dotnet/asp.net/razor-syntax.html#select-tag-helper","title":"Select Tag Helper","text":"

StackOverflow SelectList Docs

In ViewModel.cs:

C#
class ViewModel \n{\n    public int EntityId { get; set; }  // value selected in form ends up here\n\n    // object has numeric id and other props\n    public SelectList Entities = new()\n\n    public ViewModel(){ }  // parameterless constructor (NEEDED)\n}\n

In View.cs

C#
@model ViewModel\n\n<form asp-controller=\"Controller\" asp-action=\"PostAction\">\n\n    <select asp-for\"EntityId\" asp-items=\"Model.Entities\">\n    </select>\n\n    <button type=\"submit\">Send<button>\n</form>\n

In Controller.cs:

C#
public IActionResult GetAction()\n{\n    var vm = new ViewModel();\n\n    vm.Entities = new SelectList(_context.Entities, \"Id\", \"Text\");  // fill SelectList\n    vm.EntityId = value;  // set selected option (OPTIONAL)\n\n    return View(vm);\n}\n\n\n[HttpPost]\npublic IActionResult PostAction(ViewModel)\n{\n    if(ModelState.IsValid)\n    {\n        // extract info from view model\n        // save to db\n    }\n}\n
"},{"location":"languages/dotnet/asp.net/signalr.html","title":"SignalR","text":"

The SignalR Hubs API enables to call methods on connected clients from the server. In the server code, define methods that are called by client. In the client code, define methods that are called from the server. SignalR takes care of everything behind the scenes that makes real-time client-to-server and server-to-client communications possible.

"},{"location":"languages/dotnet/asp.net/signalr.html#server-side","title":"Server-Side","text":""},{"location":"languages/dotnet/asp.net/signalr.html#configuration","title":"Configuration","text":"

In Startup.cs:

C#
builder.Services.AddSignalR();\n\nvar app = builder.Build();\n\napp.UseEndpoints(endpoints =>\n{\n    endpoints.MapHub(\"/hub/endpoint\");\n});\n
"},{"location":"languages/dotnet/asp.net/signalr.html#creating-hubs","title":"Creating Hubs","text":"C#
public class CustomHub : Hub\n{\n    public task HubMethod(Type args)\n    {\n        // trigger function on all clients and pass args to it\n        return Clients.All.SendAsync(\"CLientMethod\", args);\n\n        // trigger function on caller client and pass args to it\n        return Clients.Caller.SendAsync(\"CLientMethod\", args);\n\n        // trigger function on clients of a group and pass args to it\n        return Clients.Group(\"GroupName\").SendAsync(\"CLientMethod\", args);\n\n        // other operations\n    }\n}\n
"},{"location":"languages/dotnet/asp.net/signalr.html#strongly-typed-hubs","title":"Strongly Typed Hubs","text":"

A drawback of using SendAsync is that it relies on a magic string to specify the client method to be called. This leaves code open to runtime errors if the method name is misspelled or missing from the client.

An alternative to using SendAsync is to strongly type the Hub with Hub<T>.

C#
public interface IHubClient\n{\n    // matches method to be called on the client\n    Task ClientMethod(Type args);\n}\n
C#
public class CustomHub : Hub<IHubClient>\n{\n    public Task HubMethod(Type args)\n    {\n        return Clients.All.ClientMethod(args);\n    }\n}\n

Using Hub<T> enables compile-time checking of the client methods. This prevents issues caused by using magic strings, since Hub<T> can only provide access to the methods defined in the interface.

Using a strongly typed Hub<T> disables the ability to use SendAsync. Any methods defined on the interface can still be defined as asynchronous. In fact, each of these methods should return a Task. Since it's an interface, don't use the async keyword.

"},{"location":"languages/dotnet/asp.net/signalr.html#handling-connection-events","title":"Handling Connection Events","text":"

The SignalR Hubs API provides the OnConnectedAsync and OnDisconnectedAsync virtual methods to manage and track connections. Override the OnConnectedAsync virtual method to perform actions when a client connects to the Hub, such as adding it to a group.

C#
public override async Task OnConnectedAsync()\n{\n    await Groups.AddToGroupAsync(Context.ConnectionId, \"GroupName\");\n    await base.OnConnectedAsync();\n}\n\npublic override async Task OnDisconnectedAsync(Exception exception)\n{\n    await Groups.RemoveFromGroupAsync(Context.ConnectionId, \"GroupName\");\n    await base.OnDisconnectedAsync(exception);\n}\n

Override the OnDisconnectedAsync virtual method to perform actions when a client disconnects. If the client disconnects intentionally (by calling connection.stop(), for example), the exception parameter will be null. However, if the client is disconnected due to an error (such as a network failure), the exception parameter will contain an exception describing the failure.

"},{"location":"languages/dotnet/asp.net/signalr.html#sending-errors-to-the-client","title":"Sending Errors to the client","text":"

Exceptions thrown in the hub methods are sent to the client that invoked the method. On the JavaScript client, the invoke method returns a JavaScript Promise. When the client receives an error with a handler attached to the promise using catch, it's invoked and passed as a JavaScript Error object.

If the Hub throws an exception, connections aren't closed. By default, SignalR returns a generic error message to the client.

If you have an exceptional condition you do want to propagate to the client, use the HubException class. If you throw a HubException from your hub method, SignalR will send the entire message to the client, unmodified.

C#
public Task ThrowException()\n{\n    throw new HubException(\"This error will be sent to the client!\");\n}\n
"},{"location":"languages/dotnet/asp.net/signalr.html#client-side-javascript","title":"Client-Side (JavaScript)","text":""},{"location":"languages/dotnet/asp.net/signalr.html#installing-the-client-package","title":"Installing the client package","text":"Bash
npm init -y\nnpm install @microsoft/signalr\n

npm installs the package contents in the node_modules\\@microsoft\\signalr\\dist\\browser folder. Create a new folder named signalr under the wwwroot\\lib folder. Copy the signalr.js file to the wwwroot\\lib\\signalr folder.

Reference the SignalR JavaScript client in the <script> element. For example:

HTML
<script src=\"~/lib/signalr/signalr.js\"></script>\n
"},{"location":"languages/dotnet/asp.net/signalr.html#connecting-to-a-hub","title":"Connecting to a Hub","text":"

Reconnect Clients Docs

JavaScript
const connection = new signalR.HubConnectionBuilder()\n    .withUrl(\"/hub/endpoint\")\n    .configureLogging(signalR.LogLevel.Information)\n    .withAutomaticReconnect()  // optional\n    .build();\n\n// async/await connection start\nasync function connect() {\n    try {\n        await connection.start();\n        console.log(\"SignalR Connected.\");\n    } catch (err) {\n        console.error(err);\n    }\n};\n\n// promise connection start\nfunction connect() {\n    connection.start()\n    .then(() => {})\n    .catch((err) => {console.error(err)});\n}\n
"},{"location":"languages/dotnet/asp.net/signalr.html#call-hub-methods-fom-the-client","title":"Call hub methods fom the client","text":"

JavaScript clients call public methods on hubs via the invoke method of the HubConnection. The invoke method accepts:

JavaScript
try {\n    await connection.invoke(\"HubMethod\", args);\n} catch (err) {\n    console.error(err);\n}\n

The invoke method returns a JavaScript Promise. The Promise is resolved with the return value (if any) when the method on the server returns. If the method on the server throws an error, the Promise is rejected with the error message. Use async and await or the Promise's then and catch methods to handle these cases.

JavaScript clients can also call public methods on hubs via the the send method of the HubConnection. Unlike the invoke method, the send method doesn't wait for a response from the server. The send method returns a JavaScript Promise. The Promise is resolved when the message has been sent to the server. If there is an error sending the message, the Promise is rejected with the error message. Use async and await or the Promise's then and catch methods to handle these cases.

"},{"location":"languages/dotnet/asp.net/signalr.html#call-client-methods-from-the-hub","title":"Call client methods from the hub","text":"

To receive messages from the hub, define a method using the on method of the HubConnection. The on method accepts:

C#
connection.on(\"ClientMethod\", (args) => { /* ... */});\n
"},{"location":"languages/dotnet/asp.net/web-forms.html","title":"WebForms","text":""},{"location":"languages/dotnet/asp.net/web-forms.html#pageaspx","title":"Page.aspx","text":"

The fist loaded page is Default.aspx and its underlying code.

HTML
<!-- directive -->\n<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"Project.Default\" %>\n\n<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">  <!-- XML Namespace -->\n<head runat=\"server\">  <!-- runat: handle as ASP code -->\n    <title></title>\n</head>\n<body>\n    <!-- web forms require a form tag to be the whole body -->\n    <form id=\"form1\" runat=\"server\">  <!-- runat: handle as ASP code -->\n        <div>\n        </div>\n    </form>\n</body>\n</html>\n
"},{"location":"languages/dotnet/asp.net/web-forms.html#page-directive","title":"Page Directive","text":"C#
<%@ Page Language=\"C#\"  // define language used (can be C# or VB)\n    AutoEventWireup=\"true\"  // automatically create and setup event handlers\n    CodeBehind=\"Default.aspx.cs\"  // define the underlying code file\n    Inherits=\"EmptyWebForm.Default\" %>\n
"},{"location":"languages/dotnet/asp.net/web-forms.html#web-controls","title":"Web Controls","text":"XML
<asp:Control ID=\"\" runat=\"server\" ...></asp:Control>\n\n<!-- Label: empty text will diplay ID, use empty space as text for empty label -->\n<asp:Label ID=\"lbl_\" runat=\"server\" Text=\" \"></asp:Label>\n<!-- TextBox -->\n<asp:TextBox ID=\"txt_\" runat=\"server\"></asp:TextBox>\n<!-- Button -->\n<asp:Button ID=\"btn_\" runat=\"server\" Text=\"ButtonText\" OnClick=\"btn_Click\" />\n<!-- HyperLink -->\n<asp:HyperLink ID=\"lnk_\" runat=\"server\" NavigateUrl=\"~/Page.aspx\">LINK TEXT</asp:HyperLink>\n<!-- LinkButton: POstBackEvent reloads the page -->\n<asp:LinkButton ID=\"lbtHome\" runat=\"server\" PostBackUrl=\"~/Page.aspx\" OnClick=\"lbt_Click\">BUTTON TEXT</asp:LinkButton>\n<!-- Image -->\n<asp:Image ID=\"img_\" runat=\"server\" ImageUrl=\"~/Images/image.avif\"/>\n<!-- ImageButton -->\n<asp:ImageButton ID=\"imb_\" runat=\"server\" ImageUrl=\"~/Images/image.avif\" PostBackUrl=\"~/Page.aspx\"/>\n\n<!-- SqlSataSource; connection string specified in Web.config -->\n<asp:SqlDataSource ID=\"sds_\" runat=\"server\" ConnectionString=\"<%$ ConnectionStrings:ConnectionString %>\" SelectCommand=\"SQL Query\"></asp:SqlDataSource>\n
"},{"location":"languages/dotnet/asp.net/web-forms.html#pageaspxcs","title":"Page.aspx.cs","text":"C#
public partial class Default : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n\n    }\n\n    protected void Control_Event(object sender, EventArgs e)\n    {\n        // actions on event trigger\n    }\n}\n
"},{"location":"languages/dotnet/csharp/async-programming.html","title":"Async Programming","text":""},{"location":"languages/dotnet/csharp/async-programming.html#task-asynchronous-programming-model-tap","title":"Task Asynchronous Programming Model (TAP)","text":"

It's possible to avoid performance bottlenecks and enhance the overall responsiveness of an application by using asynchronous programming. However, traditional techniques for writing asynchronous applications can be complicated, making them difficult to write, debug, and maintain.

C# 5 introduced a simplified approach, async programming, that leverages asynchronous support in the .NET Runtime. The compiler does the difficult work that the developer used to do, and the application retains a logical structure that resembles synchronous code.

In performance-sensitive code, asynchronous APIs are useful, because instead of wasting resources by forcing a thread to sit and wait for I/O to complete, a thread can kick off the work and then do something else productive in the meantime.

The async and await keywords in C# are the heart of async programming.

C#
public async Task<TResult> MethodAsync\n{\n    Task<TResult> resultTask = obj.OtherMethodAsync();\n\n    DoIndependentWork();\n\n    TResult result = await resultTask;\n\n    // if the is no work to be done before awaiting\n    TResult result = await obj.OtherMethodAsync();\n\n    return result;\n}\n

Characteristics of Async Methods:

The method usually includes at least one await expression, which marks a point where the method can't continue until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and control returns to the method's caller.

"},{"location":"languages/dotnet/csharp/async-programming.html#threads","title":"Threads","text":"

Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. It's possible to use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

The async-based approach to asynchronous programming is preferable to existing approaches in almost every case. In particular, this approach is better than the BackgroundWorker class for I/O-bound operations because the code is simpler and there is no need to guard against race conditions. In combination with the Task.Run method, async programming is better than BackgroundWorker for CPU-bound operations because async programming separates the coordination details of running the code from the work that Task.Run transfers to the thread pool.

"},{"location":"languages/dotnet/csharp/async-programming.html#naming-convention","title":"Naming Convention","text":"

By convention, methods that return commonly awaitable types (for example, Task, Task<T>, ValueTask, ValueTask<T>) should have names that end with Async. Methods that start an asynchronous operation but do not return an awaitable type should not have names that end with Async, but may start with \"Begin\", \"Start\", or some other verb to suggest this method does not return or throw the result of the operation.

"},{"location":"languages/dotnet/csharp/async-programming.html#async-return-types","title":"Async Return Types","text":""},{"location":"languages/dotnet/csharp/async-programming.html#task-return-type","title":"Task return type","text":"

Async methods that don't contain a return statement or that contain a return statement that doesn't return an operand usually have a return type of Task. Such methods return void if they run synchronously. If a Task return type is used for an async method, a calling method can use an await operator to suspend the caller's completion until the called async method has finished.

"},{"location":"languages/dotnet/csharp/async-programming.html#tasktresult-return-type","title":"Task<TResult> return type","text":"

The Task<TResult> return type is used for an async method that contains a return statement in which the operand is TResult.

The Task<TResult>.Result property is a blocking property. If it's accessed it before its task is finished, the thread that's currently active is blocked until the task completes and the value is available. In most cases, access the value by using await instead of accessing the property directly.

"},{"location":"languages/dotnet/csharp/async-programming.html#void-return-type","title":"void return type","text":"

The void return type is used in asynchronous event handlers, which require a void return type. For methods other than event handlers that don't return a value, it's best to return a Task instead, because an async method that returns void can't be awaited. Any caller of such a method must continue to completion without waiting for the called async method to finish. The caller must be independent of any values or exceptions that the async method generates.

The caller of a void-returning async method can't catch exceptions thrown from the method, and such unhandled exceptions are likely to cause the application to fail. If a method that returns a Task or Task<TResult> throws an exception, the exception is stored in the returned task. The exception is re-thrown when the task is awaited. Therefore, make sure that any async method that can produce an exception has a return type of Task or Task<TResult> and that calls to the method are awaited.

"},{"location":"languages/dotnet/csharp/async-programming.html#generalized-async-return-types-and-valuetasktresult","title":"Generalized async return types and ValueTask<TResult>","text":"

Starting with C# 7.0, an async method can return any type that has an accessible GetAwaiter method.

Because Task and Task<TResult> are reference types, memory allocation in performance-critical paths, particularly when allocations occur in tight loops, can adversely affect performance. Support for generalized return types means that it's possible to return a lightweight value type instead of a reference type to avoid additional memory allocations.

.NET provides the System.Threading.Tasks.ValueTask<TResult> structure as a lightweight implementation of a generalized task-returning value. To use the System.Threading.Tasks.ValueTask<TResult> type, add the System.Threading.Tasks.Extensions NuGet package to the project.

"},{"location":"languages/dotnet/csharp/async-programming.html#async-composition","title":"Async Composition","text":"C#
public async Task DoOperationsConcurrentlyAsync()\n{\n  Task[] tasks = new Task[3];\n  tasks[0] = DoOperation0Async();\n  tasks[1] = DoOperation1Async();\n  tasks[2] = DoOperation2Async();\n\n  // At this point, all three tasks are running at the same time.\n\n  // Now, we await them all.\n  await Task.WhenAll(tasks);\n}\n\npublic async Task<int> GetFirstToRespondAsync()\n{\n  // Call two web services; take the first response.\n  Task<int>[] tasks = new[] { WebService1Async(), WebService2Async() };\n\n  // Await for the first one to respond.\n  Task<int> firstTask = await Task.WhenAny(tasks);\n\n  // Return the result.\n  return await firstTask;\n}\n
"},{"location":"languages/dotnet/csharp/async-programming.html#execution-synchronization-context","title":"Execution & Synchronization Context","text":"

When the program\u2019s execution reaches an await expression for an operation that doesn\u2019t complete immediately, the code generated for that await will ensure that the current execution context has been captured. When the asynchronous operation completes, the remainder of the method will be executed through the execution context. The execution context handles certain contextual information that needs to flow when one method invokes another (even when it does so indirectly)

While all await expressions capture the execution context, the decision of whether to flow synchronization context as well is controlled by the type being awaited.

Sometimes, it's better to avoid getting the synchronization context involved. If work starting from a UI thread is performed, but there is no particular need to remain on that thread, scheduling every continuation through the synchronization context is unnecessary overhead.

If the asynchronous operation is a Task, Task<T>, ValueTask or ValueTask<T>, it's possible to discard the synchronization context by calling the ConfigureAwait(false). This returns a different representation of the asynchronous operation, and if this iss awaited that instead of the original task, it will ignore the current SynchronizationContext if there is one.

C#
private async Task DownloadFileAsync(string fileName)\n{\n  await OperationAsync(fileName).ConfigureAwait(false);  // discarding original context\n}\n

When writing libraries in most cases you it'ss best to call ConfigureAwait(false) anywhere await is used. This is because continuing via the synchronization context can be expensive, and in some cases it can introduce the possibility of deadlock occurring.

The only exceptions are when are doing something that positively requires the synchronization context to be preserved, or it's know for certain that the library will only ever be used in application frameworks that do not set up a synchronization context. (ASP.NET Core applications do not use synchronization contexts, so it generally doesn\u2019t matter whether or not ConfigureAwait(false) is called in those)

"},{"location":"languages/dotnet/csharp/async-programming.html#error-handling","title":"Error Handling","text":""},{"location":"languages/dotnet/csharp/async-programming.html#argument-validation","title":"Argument Validation","text":"

Inside an async method, the compiler treats all exceptions in the same way: none are allowed to pass up the stack as in a normal method, and they will always be reported by faulting the returned task. This is true even of exceptions thrown before the first await.

If the calling method immediately calls await on the return task, this won\u2019t matter much\u2014it will see the exception in any case. But some code may choose not to wait immediately, in which case it won\u2019t see the argument exception until later.

C#
async Task<string> MethodWithValidationAsync(string argument)\n{\n  if(sting.IsNullOrEmpty(argument))\n  {\n     throw new ArgumentNullException(nameof(argument));  // will be thrown on await of MethodWithValidationAsync\n  }\n\n  // [...]\n\n  return await LongOperationAsync();\n}\n

In cases where you want to throw this kind of exception straightaway, the usual technique is to write a normal method that validates the arguments before calling an async method that does the work, and to make that second method either private or local.

C#
// not marked with async, exception propagate directly to caller\npublic static Task<string> MethodWithValidationAsync(string argument)\n{\n  if(sting.IsNullOrEmpty(argument))\n  {\n     throw new ArgumentNullException(nameof(argument));  // thrown immediately\n  }\n\n  return ActualMethodAsync(argument);  // pass up task of inner method\n}\n\nprivate static async Task<string> ActualMethodAsync(string argument)\n{\n  // [...]\n  return await LongOperationAsync();\n}\n

Note: await extracts only the first exception of an AggregateException, this can cause the loss of information if a task (or group of tasks) has more than one error.

"},{"location":"languages/dotnet/csharp/collections.html","title":"C# Collections","text":""},{"location":"languages/dotnet/csharp/collections.html#arrays","title":"Arrays","text":"

An array is an object that contains multiple elements of a particular type. The number of elements is fixed for the lifetime of the array, so it must be specified when the array is created.

An array type is always a reference type, regardless of the element type. Nonetheless, the choice between reference type and value type elements makes a significant difference in an array's behavior.

C#
type[] array = new type[dimension];\ntype array[] = new type[dimension];  //invalid\n\ntype[] array = {value1, value2, ..., valueN};  // initializer\nvar array = new type[] {value1, value2, ..., valueN};  // initializer (var type needs new operator)\nvar array = new[] {value1, value2, ..., valueN};  // initializer w/ element type inference (var type needs new operator), can be used as method arg\n\narray[index];    // value access\narray[index] = value;    // value assignment\narray.Length;  // dimension of the array\n\n// from IEnumerable<T>\narray.OfType<Type>();  // filter array based on type, returns IEnumerable<Type>\n
"},{"location":"languages/dotnet/csharp/collections.html#array-methods","title":"Array Methods","text":"C#
// overloaded search methods\nArray.IndexOf(array, item);  // return index of searched item in passed array\nArray.LastIndexOf(array, item); // return index of searched item staring from the end of the array\nArray.FindIndex(array, Predicate<T>)  // returns the index of the first item matching the predicate (can be lambda function)\nArray.FindLastIndex(array, Predicate<T>)  // returns the index of the last item matching the predicate (can be lambda function)\nArray.Find(array, Predicate<T>)  // returns the value of the first item matching the predicate (can be lambda function)\nArray.FindLast(array, Predicate<T>)  // returns the value of the last item matching the predicate (can be lambda function)\nArray.FindAll(array, Predicate<T>)  // returns array of all items matching the predicate (can be lambda function)\nArray.BinarySearch(array, value)  // Searches a  SORTED array for a value, using a binary search algorithm; returns the index of the found item\n\nArray.Sort(array);\nArray.Reverse(array);  // reverses the  order of array elements\nArray.Clear(start_index, x);  //removes reference to x elements starting at start index. Dimension of array unchanged (cleared elements value is set tu null)\nArray.Resize(ref array, target_dimension);  //expands or shrinks the array dimension. Shrinking drops trailing values. Array passed by reference.\n\n// Copies elements from an Array starting at the specified index and pastes them to another Array starting at the specified destination index.\nArray.Copy(sourceArray, sourceStartIndex, destinationArray, destinationStartIndex, numItemsToCopy);\n// Copies elements from an Array starting at the first element and pastes them into another Array starting at the first element.\nArray.Copy(sourceArray, destinationArray, numItemsToCopy);\nArray.Clone();  // returns a shallow copy of the array\n
"},{"location":"languages/dotnet/csharp/collections.html#multidimensional-arrays","title":"Multidimensional Arrays","text":"

C# supports two multidimensional array forms: jagged arrays and rectangular arrays (matrices).

C#
//specify first dimension\ntype[][] jagged = new type[][]\n{\n    new[] {item1, item2, item3},\n    new[] {item1},\n    new[] {item1, item2},\n    ...\n}\n\n// shorthand\ntype[][] jagged =\n{\n    new[] {item1, item2, item3},\n    new[] {item1},\n    new[] {item1, item2},\n    ...\n}\n\n// matrices\ntype[,] matrix = new type[n, m];  // n * m matrix\ntype[,] matrix = {{}, {}, {}, ...};  // {} for each row to initialize\ntype[, ,] tensor = new type[n, m, o] // n * m * o tensor\n\nmatrix.Length;  // total number of elements (n * m)\nmatrix.GetLength(int dimension); // get the size of a particular direction\n// row = 0, column = 1, ...\n
"},{"location":"languages/dotnet/csharp/collections.html#lists","title":"Lists","text":"

List<T> stores sequences of elements. It can grow or shrink, allowing to add or remove elements.

C#
using System.Collections.Generics;\n\nList<T> list = new List<T>();\nList<T> list = new List<T> {item_1, ...};  // initialized usable since list implements IEnumerable<T> and has Add() method (even extension method)\nList<T> list = new List<T>(dimension);  // set list starting dimension\nList<T> list = new List<T>(IEnumerable<T>);  // create a list from an enumerable collection\n\n\nlist.Add(item);    //item insertion into the list\nlist.AddRange(IEnumerable<T> collection);  // insert multiple items\nlist.Insert(index, item);  // insert an item at the specified index\nlist.InsertRange(index, item);  // insert items at the specified index\n\nlist.IndexOf(item);  // return index of searched item in passed list\nlist.LastIndexOf(item); // return index of searched item staring from the end of the array\nlist.FindIndex(Predicate<T>)  // returns the index of the first item matching the predicate (can be lambda function)\nlist.FindLastIndex(Predicate<T>)  // returns the index of the last item matching the predicate (can be lambda function)\nlist.Find(Predicate<T>)  // returns the value of the first item matching the predicate (can be lambda function)\nlist.FindLast(Predicate<T>)  // returns the value of the last item matching the predicate (can be lambda function)\nlist.FindAll(Predicate<T>)  // returns list of all items matching the predicate (can be lambda function)\nlist.BinarySearch(value)  // Searches a  SORTED list for a value, using a binary search algorithm; returns the index of the found item\n\nlist.Remove(item);  // remove item from list\nlist.RemoveAt(index);  // remove item at specified position\nlist.RemoveRange(index, quantity);  // remove quantity items at specified position\n\nlist.Contains(item);  // check if item is in the list\nlist.TrueForAll(Predicate<T>);  // Determines whether every element matches the conditions defined by the specified predicate\n\nlist[index];  // access to items by index\nlist[index] = value;  // modify to items by index\nlist.Count;  // number of items in the list\n\nlist.Sort(); // sorts item in crescent order\nlist.Reverse(); // Reverses the order of the elements in the list\n\n// from IEnumerable<T>\nlist.OfType<Type>();  // filter list based on type, returns IEnumerable<Type>\nlist.OfType<Type>().ToList();  // filter list based on type, returns List<Type>\n
"},{"location":"languages/dotnet/csharp/collections.html#iterators","title":"Iterators","text":"

An iterator can be used to step through collections such as lists and arrays.

An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time. When a yield return statement is reached, the current location in code is remembered. Execution is restarted from that location the next time the iterator function is called.

It's possible to use a yield break statement or exception to end the iteration.

Note: Since an iterator returns an IEnumerable<T> is can be used to implement a GetEnumerator().

C#
// simple iterator\npublic static System.Collections.IEnumerable<int> IterateRange(int start = 0, int end)\n{\n    for(int i = start; i < end; i++){\n        yield return i;\n    }\n}\n
"},{"location":"languages/dotnet/csharp/collections.html#list-sequence-interfaces","title":"List & Sequence Interfaces","text":""},{"location":"languages/dotnet/csharp/collections.html#ienumerablet","title":"IEnumerable<T>","text":"

Exposes the enumerator, which supports a simple iteration over a collection of a specified type.

C#
public interface IEnumerable<out T> : IEnumerable\n{\n    IEnumerator<T> GetEnumerator();  // return an enumerator\n}\n\n// iterate through a collection\npublic interface IEnumerator<T>\n{\n    // properties\n    object Current { get; }  // Get the element in the collection at the current position of the enumerator.\n\n    // methods\n    void IDisposable.Dispose();  // Perform application-defined tasks associated with freeing, releasing, or resetting unmanaged resources\n    bool MoveNext();  // Advance the enumerator to the next element of the collection.\n    void Reset();  // Set the enumerator to its initial position, which is before the first element in the collection.\n}\n

Note: must call Dispose() on enumerators once finished with them, because many of them rely on this. Reset() is legacy and can, in some situations, throw NotSupportedException().

"},{"location":"languages/dotnet/csharp/collections.html#icollectiont","title":"ICollection<T>","text":"C#
public interface ICollection<T> : IEnumerable<T>\n{\n    // properties\n    int Count { get; }  // Get the number of elements contained in the ICollection<T>\n    bool IsReadOnly { get; }  // Get a value indicating whether the ICollection<T> is read-only\n\n    // methods\n    void Add (T item);  // Add an item to the ICollection<T>\n    void Clear ();  // Removes all items from the ICollection<T>\n    bool Contains (T item);  // Determines whether the ICollection<T> contains a specific value\n    IEnumerator GetEnumerator ();  // Returns an enumerator that iterates through a collection\n    bool Remove (T item);  // Removes the first occurrence of a specific object from the ICollection<T>\n}\n
"},{"location":"languages/dotnet/csharp/collections.html#ilistt","title":"IList<T>","text":"C#
public interface IList<T> : ICollection<T>, IEnumerable<T>\n{\n    // properties\n    int Count { get; }  // Get the number of elements contained in the ICollection<T>\n    bool IsReadOnly { get; }  // Get a value indicating whether the ICollection<T> is read-only\n    T this[int index] { get; set; }  // Get or set the element at the specified index\n\n    // methods\n    void Add (T item);  // Add an item to the ICollection<T>\n    void Clear ();  // Remove all items from the ICollection<T>\n    bool Contains (T item);  // Determine whether the ICollection<T> contains a specific value\n    void CopyTo (T[] array, int arrayIndex);  // Copy the elements of the ICollection<T> to an Array, starting at a particular Array index\n    IEnumerator GetEnumerator ();  // Return an enumerator that iterates through a collection\n    int IndexOf (T item);  // Determine the index of a specific item in the IList<T>\n    void Insert (int index, T item);  // Insert an item to the IList<T> at the specified index\n    bool Remove (T item);  // Remove the first occurrence of a specific object from the ICollection<T>\n    oid RemoveAt (int index);  // Remove the IList<T> item at the specified index\n}\n
"},{"location":"languages/dotnet/csharp/collections.html#dictionaries","title":"Dictionaries","text":"

ValueCollection KeyCollection

Notes:

C#
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();  // init empty dict\nDictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(IEqualityComparer<TKey>);  // specify key comparer (TKey must implement Equals() and GetHashCode())\n\n// initializer (implicitly uses Add method)\nDictionary<TKey, TValue> dict =\n{\n    { key, value }\n    { key, value },\n    ...\n}\n\n// object initializer\nDictionary<TKey, TValue> dict =\n{\n    [key] = value,\n    [key] = value,\n    ...\n}\n\n// indexer access\ndict[key];  // read value associated with key (throws KeyNotFoundException if key does not exist)\ndict[key] = value;  // modify value associated with key (throws KeyNotFoundException if key does not exist)\n\ndict.Count;  // number of key-value pair stored in the dict\ndict.Keys;  // Dictionary<TKey,TValue>.KeyCollection containing the keys of the dict\ndict.Values;  // Dictionary<TKey,TValue>.ValueCollection containing the values of the dict\n\ndict.Add(key, value);  // ArgumentException if the key already exists\ndict.Clear();  // empty the dictionary\ndict.ContainsKey(key);  // check if a key is in the dictionary\ndict.ContainsValue(value);  // check if a value is in the dictionary\ndict.Remove(key);  // remove a key-value pair\ndict.Remove(key, out var);  // remove key-value pair and copy TValue to var parameter\ndict.TryAdd(key, value);  // adds a key-value pair; returns true if pair is added, false otherwise\ndict.TryGetValue(key, out var);  // put the value associated with kay in the var parameter; true if the dict contains an element with the specified key, false otherwise.\n
"},{"location":"languages/dotnet/csharp/collections.html#sets","title":"Sets","text":"

Collection of non duplicate items.

C#
HashSet<T> set = new HashSet<T>();\n\nset.Add(T); // adds an item to the set; true if the element is added, false if the element is already present.\nset.Clear();  //Remove all elements from a HashSet<T> object.\nset.Contains(T); // Determine whether a HashSet<T> object contains the specified element.\nset.CopyTo(T[]);  // Coy the elements of a HashSet<T> object to an array.\nset.CopyTo(T[], arrayIndex);  // Copy the elements of a HashSet<T> object to an array, starting at the specified array index.\nset.CopyTo(T[], arrayIndex, count);  // Copies the specified number of elements of a HashSet<T> object to an array, starting at the specified array index.\nset.CreateSetComparer();  // Return an IEqualityComparer object that can be used for equality testing of a HashSet<T> object.\nset.ExceptWith(IEnumerable<T>);  // Remove all elements in the specified collection from the current HashSet<T> object.\nset.IntersectWith(IEnumerable<T>); // Modify the current HashSet<T> object to contain only elements that are present in that object and in the specified collection.\nset.IsProperSubsetOf(IEnumerable<T>);  // Determine whether a HashSet<T> object is a proper subset of the specified collection.\nset.IsProperSupersetOf(IEnumerable<T>);  // Determine whether a HashSet<T> object is a proper superset of the specified collection.\nset.IsSubsetOf(IEnumerable<T>);  // Determine whether a HashSet<T> object is a subset of the specified collection.\nset.IsSupersetOf(IEnumerable<T>);  // Determine whether a HashSet<T> object is a superset of the specified collection.\nset.Overlaps(IEnumerable<T>);  // Determine whether the current HashSet<T> object and a specified collection share common elements.\nset.Remove(T);  // Remove the specified element from a HashSet<T> object.\nset.RemoveWhere(Predicate<T>);  // Remove all elements that match the conditions defined by the specified predicate from a HashSet<T> collection.\nset.SetEquals(IEnumerable<T>);  // Determine whether a HashSet<T> object and the specified collection contain the same elements.\nset.SymmetricExceptWith(IEnumerable<T>); // Modify the current HashSet<T> object to contain only elements that are present either in that object or in the specified collection, but not both.\nset.UnionWith(IEnumerable<T>);  // Modify the current HashSet<T> object to contain all elements that are present in itself, the specified collection, or both.\nset.TryGetValue(T, out T);  // Search the set for a given value and returns the equal value it finds, if any.\n
"},{"location":"languages/dotnet/csharp/csharp.html","title":"C#","text":"

.NET Core is a development platform that includes a Common Language Runtime (CoreCLR), which manages the execution of code, and a Base Class Library (BCL), which provides a rich library of classes to build applications from.

The C# compiler (named Roslyn) used by the dotnet CLI tool converts C# source code into intermediate language (IL) code and stores the IL in an assembly (a DLL or EXE file). IL code statements are like assembly language instructions, which are executed by .NET Core's virtual machine, known as CoreCLR.

At runtime, CoreCLR loads the IL code from the assembly, the just-in-time (JIT) compiler compiles it into native CPU instructions, and then it is executed by the CPU on your machine. The benefit of this three-step compilation process is that Microsoft's able to create CLRs for Linux and macOS, as well as for Windows. The same IL code runs everywhere because of the second compilation process, which generates code for the native operating system and CPU instruction set. Regardless of which language the source code is written in, for example, C#, Visual Basic or F#, all .NET applications use IL code for their instructions stored in an assembly.

Another .NET initiative is called .NET Native. This compiles C# code to native CPU instructions ahead of time (AoT), rather than using the CLR to compile IL code JIT to native code later. .NET Native improves execution speed and reduces the memory footprint for applications because the native code is generated at build time and then deployed instead of the IL code.

"},{"location":"languages/dotnet/csharp/csharp.html#basics","title":"Basics","text":""},{"location":"languages/dotnet/csharp/csharp.html#comments","title":"Comments","text":"C#
// comment\n/* multi line comment */\n/// single line xml comment (docstring)\n/** multi line xml string (docstring) */\n
"},{"location":"languages/dotnet/csharp/csharp.html#docstring-structure","title":"Docstring Structure","text":"

/** <tag> content </tag> **/

"},{"location":"languages/dotnet/csharp/csharp.html#naming-convention","title":"Naming Convention","text":"Element Case Namespace PascalCase Class, Interface PascalCase Method PascalCase Field, Property PascalCase Event, Enum, Enum Value, PascalCase Variables, Parameters camelCase"},{"location":"languages/dotnet/csharp/csharp.html#namespaces-imports-aliases","title":"Namespaces, Imports & Aliases","text":"

Hierarchic organization of programs an libraries.

C#
using System;  // import the System Namespace\nusing static System.Console;  // statically import a class to use its static methods w/o qualification\n\n// type aliases\nusing Alias = Namespace.SubNamespace.Type;\nusing LookupTable = Dictionary<string, string>;\nusing Points = (int, int, int)[];\n\n// global using [C# 10], should be in dedicated file\nglobal using <namespace>;\n\nnamespace Namespace;  // [C# 10]\n//or\nnamespace Namespace \n{\n}\n

To enable .NET 6/C# 10 implicit namespace imports:

XML
<ImplicitUsings>enable</ImplicitUsings>\n
"},{"location":"languages/dotnet/csharp/csharp.html#top-level-statementsprograms-c-9","title":"Top Level Statements/Programs (C# 9)","text":"C#
// imports\n\n// code here, no main, no namespace\n
"},{"location":"languages/dotnet/csharp/csharp.html#main-method","title":"Main Method","text":"C#
public static void Main(string[] args)\n{\n    // code here\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#constant-declaration","title":"Constant Declaration","text":"C#
const type CONSTANT_NAME = value;\n
"},{"location":"languages/dotnet/csharp/csharp.html#assignment-operation","title":"Assignment Operation","text":"

type variable1 = value1, variable2 = value2, ...;

If a variable has not been assigned it assumes the default value.

"},{"location":"languages/dotnet/csharp/csharp.html#input","title":"Input","text":"C#
// input is a string, convert before saving in a non String variable\nConsole.ReadLines();    // read util <Return>  is pressed\nConsole.Read();    // read until space\n\n// reading non string input\n<SystemType/Type>.Parse(Console.ReadLines());    // convert string to numerical data type (can cause exception at runtime)\nConvert.To<SystemType>(Console.ReadLines());    // proper conversion and round-up of values (no truncation of values), NULL returns 0 (zero)\n\n// integers numeric base conversion\nConvert.ToString(num, <base>);  //  to specified numeric base\nConvert.ToInt32(string, <base>);  // parse from numeric base\n\nConsole.ReadKey();    // read a key from keyboard and display pressed kay immediately\n
"},{"location":"languages/dotnet/csharp/csharp.html#screen-output","title":"Screen Output","text":"C#
Console.WriteLine();    // single line output\n
"},{"location":"languages/dotnet/csharp/csharp.html#string-formatting","title":"String Formatting","text":"

{index[,alignment][:<formatString><num_decimal_digits>]}

C#
Console.WriteLine(\"Name is {0}, Marks are {1}\", name, marks);    // string composite formatting\nConsole.WriteLine($\"Name is {name}, Marks are {marks}\");    // string interpolation\n\nConsole.WriteLine(\n    format: \"{0} {1}\"  // format can be omitted and passed as first argument of WriteLine/Write\n    arg0: \"String Literal\",\n    arg1: string_variable,\n    ...\n);\n
"},{"location":"languages/dotnet/csharp/csharp.html#number-format-string","title":"Number Format String","text":"

Numeric Format Strings Docs CultureInfo Docs

{index[,alignment][:<formatString><num_decimal_digits>]}

$\"{number:C}\" formats the number as a currency. Currency symbol & symbol position are determined by CultureInfo. $\"{number:D}\" formats the number with decimal digits. $\"{number:F}\" formats the number with a fixed number of decimal digits. $\"{number:E}\" formats the number in scientific notation. $\"{number:E}\" formats the number in the more compact of either fixed-point or scientific notation. $\"{number:N}\" formats the number as a measure. Digits separators are determined by CultureInfo. $\"{number:P}\" formats the number as a percentage. $\"{number:X}\" formats the number as a hexadecimal.

"},{"location":"languages/dotnet/csharp/csharp.html#variable-types","title":"Variable Types","text":""},{"location":"languages/dotnet/csharp/csharp.html#value-type","title":"Value Type","text":"

A value type variable will store its values directly in an area of storage called the STACK. The stack is memory allocated to the code that is currently running on the CPU. When the stack frame has finished executing, the values in the stack are removed.

"},{"location":"languages/dotnet/csharp/csharp.html#reference-type","title":"Reference Type","text":"

A reference type variable will store its values in a separate memory region called the HEAP. The heap is a memory area that is shared across many applications running on the operating system at the same time. The .NET Runtime communicates with the operating system to determine what memory addresses are available, and requests an address where it can store the value. The .NET Runtime stores the value, then returns the memory address to the variable. When your code uses the variable, the .NET Runtime seamlessly looks up the address stored in the variable and retrieves the value that's stored there.

"},{"location":"languages/dotnet/csharp/csharp.html#integer-numeric-types","title":"Integer Numeric Types","text":"Keyword System Type Example Bit/Byte Min Value Max Value sbyte System.SByte 8 bit -128 127 byte System.Byte 8 bit 0 255 short System.Int16 16 bit -32'786 32'767 ushort System.UInt16 16 bit 0 65'535 int System.Int32 123 32 bit -2'47'483'648 2'147'483'647 uint System.UInt32 123u 32 bit 0 4'294'967'296 nint System.IntPtr Arch 0 18'446'744'073'709'551'615 nuint System.UIntPtr Arch -9'223'372'036'854'775'808 9'223'372'036'854'775'807 long System.Int64 123l 64 bit -9'223'372'036'854'775'808 9'223'372'036'854'775'807 ulong System.UInt64 123ul 64 bit 0 18'446'744'073'709'551'615"},{"location":"languages/dotnet/csharp/csharp.html#floating-point-numeric-types","title":"Floating-Point Numeric Types","text":"Keyword System Types Example Bit/Byte Digits Min Value Max Value float System.Single 3.14f 4 byte 6-9 -3.402823 E+38 3.402823 E+38 double System.Double 3.14 8 byte 15-17 -1.79769313486232 E+308 1.79769313486232 E+308 decimal System.Decimal 3.14m 16 byte 28-29 -79'228'162'514'264'337'593'543'950'335 79'228'162'514'264'337'593'543'950'335

The static fields and methods of the MathF class correspond to those of the Math class, except that their parameters are of type Single rather than Double, and they return Single rather than Double values.

"},{"location":"languages/dotnet/csharp/csharp.html#biginteger","title":"BigInteger","text":"

BigInteger represents an integer that will grow as large as is necessary to accommodate values. Unlike the builtin numeric types, it has no theoretical limit on its range.

C#
using System;\nusing System.Numerics;\n\nBigInteger bi;\n
"},{"location":"languages/dotnet/csharp/csharp.html#binary-hexadecimal-numbers","title":"Binary & Hexadecimal Numbers","text":"

Binary literal: 0b<digits> Hexadecimal literal: 0x<digits>

C#
// three variables that store the number 2 million\nint decimalNotation = 2_000_000;\nint binaryNotation = 0b_0001_1110_1000_0100_1000_0000;\nint hexadecimalNotation = 0x_001E_8480;\n
"},{"location":"languages/dotnet/csharp/csharp.html#boolean-type-systemboolean","title":"Boolean Type (System.Boolean)","text":"

bool: true or false

"},{"location":"languages/dotnet/csharp/csharp.html#text-type-systemchar-systemstring","title":"Text Type (System.Char & System.String)","text":"

char: single unicode character string: multiple Unicode characters

"},{"location":"languages/dotnet/csharp/csharp.html#implicit-type","title":"Implicit Type","text":"

The compiler determines the required type based on the assigned value.

C#
var variable = value;  // Inferred tipe cant change after first assignment\n
"},{"location":"languages/dotnet/csharp/csharp.html#dynamic-type","title":"Dynamic Type","text":"C#
dynamic variable = value;\n
"},{"location":"languages/dotnet/csharp/csharp.html#anonymous-types-reference-type","title":"Anonymous types (Reference Type)","text":"C#
// cannot be used as return types\nvar x = new { Key = value, ...};  // read only properties\nx.Key;  // member access\n\nvar y = x with { Key = value };  // with expression [C# 10]\n
"},{"location":"languages/dotnet/csharp/csharp.html#index-range-types-structs","title":"Index & Range Types (Structs)","text":"

A System.Index represents a type that can be used to index a collection either from the start or the end. A System.Range represents a range that has start and end indexes.

C#
Index i = position;\nIndex i = new Index(position, IsFromEnd: false);  // start-relative index\n\nIndex e = ^position;  // end-elative index\nIndex e = new Index(position, IsFromEnd: true);  // end-elative index\narray[^n];  // n-th last item\narray[array.Length - n];  // n-th last item\n\n// range syntax (supported by System.Range struct)\nRange all = 0..^0;\nRange all = 0..;\nRange all = ..^0;\nRange all = ..;\nvar all = Range.All;\n\n// slicing\narray[start..end];  // select elements between start index and end index (non inclusive)\narray[start..^n];  // select elements between start index and n-th last item (non inclusive)\n
"},{"location":"languages/dotnet/csharp/csharp.html#tuples-value-type","title":"Tuples (Value Type)","text":"

Tuples are designed as a convenient way to package together a few values in cases where defining a whole new type wouldn't really be justified.

Tuples support comparison, so it's possible to use the == and != relational operators. To be considered equal, two tuples must have the same shape and each value in the first tuple must be equal to its counterpart in the second tuple.

C#
(Type Var1, Type Var2, ...) variable = (value1, value2, ...);\nvar variable = (Var1: value1, Var2: value2, ...);  // if name are not supplied they default to Item1, Item2, ...\nvar variable = (var1, var2);  // constructed w/ pre-existing values, tuple attributes named after the variables\n

Since the names of the attributes of a tuple do not matter (a tuple is an instance of ValueTuple<Type, Type, ...>) it's possible to assign any tuple to another tuple with the same structure.

C#
(int X, Int Y) a = (1 , 0);\n(int Width, int Height) b = a;\n
"},{"location":"languages/dotnet/csharp/csharp.html#tuple-deconstruction","title":"Tuple Deconstruction","text":"C#
(int X, int Y) point = (10, 35);\n(int a, int b) = point;  // extract data based on position into two variables\n
"},{"location":"languages/dotnet/csharp/csharp.html#records","title":"Records","text":"

I'ts possible to create record types with immutable properties by using standard property syntax or positional parameters:

C#
public record Person\n{\n    public string FirstName { get; init; } = default!;\n    public string LastName { get; init; } = default!;\n};\n// same as\npublic record Person(string FirstName, string LastName);\n\npublic record struct Point\n{\n    public double X {  get; init; }\n    public double Y {  get; init; }\n    public double Z {  get; init; }\n}\n// same as\npublic readonly record struct Point(double X, double Y, double Z);\n

it's also possible to create record types with mutable properties and fields:

C#
// mutable record\npublic record Person\n{\n    public string FirstName { get; set; } = default!;\n    public string LastName { get; set; } = default!;\n};\n\n// mutable record struct\npublic readonly record struct Point(double X, double Y, double Z);\n

While records can be mutable, they're primarily intended for supporting immutable data models. The record type offers the following features:

Note: A positional record and a positional readonly record struct declare init-only properties. A positional record struct declares read-write properties.

"},{"location":"languages/dotnet/csharp/csharp.html#with-expressions","title":"with-expressions","text":"

When working with immutable data, a common pattern is to create new values from existing ones to represent a new state. To help with this style of programming, records allow for a new kind of expression; the with-expression.

C#
var newRecord = oldRecord with { Property = value };\n

With-expressions use object initializer syntax to state what's different in the new object from the old object. it's possible to specify multiple properties. A record implicitly defines a protected \"copy constructor\", a constructor that takes an existing record object and copies it field by field to the new one. The with expression causes the copy constructor to get called, and then applies the object initializer on top to change the properties accordingly.

C#
protected Record(Record original) { /* copy all the fields */ } // generated\n

Note: it's possible to define a custom copy constructor tha will be picked up by the with expression.

"},{"location":"languages/dotnet/csharp/csharp.html#with-expressions-inheritance","title":"with-expressions & Inheritance","text":"

Records have a hidden virtual method that is entrusted with \"cloning\" the whole object. Every derived record type overrides this method to call the copy constructor of that type, and the copy constructor of a derived record chains to the copy constructor of the base record. A with-expression simply calls the hidden \"clone\" method and applies the object initializer to the result.

C#
public record Base{ Type Prop1, Type Prop2 };\npublic record Derived : Base { Type Prop3 };\n\nBase @base  = new Derived { Prop1 = value1, Prop2 =  value2, Prop3 = value3 };\nvar newBase = @base with { Prop2 = value };  // new Derived record even if type of _base is Base since _base contains a Derived record\n
"},{"location":"languages/dotnet/csharp/csharp.html#value-based-equality-inheritance","title":"Value-based Equality & Inheritance","text":"

Records have a virtual protected property called EqualityContract. Every derived record overrides it, and in order to compare equal, the two objects musts have the same EqualityContract.

C#
public record Base{ Type Prop1, Type Prop2 };\npublic record Derived : Base { Type Prop3 };\n\nBase rec1 = new Base { Prop1 = value1, Prop2 = value2 };\nBase rec2 = new Derived { Prop1 = value1, Prop2 =  value2, Prop3 = value3 };\n// will result not equal even if container is of same type\n
"},{"location":"languages/dotnet/csharp/csharp.html#strings","title":"Strings","text":"

.NET strings are immutable. The downside of immutability is that string processing can be inefficient. If a work performs a series of modifications to a string it will end up allocating a lot of memory, because it will return a separate string for each modification. This creates a lot of extra work for .NET's garbage collector, causing the program to use more CPU time than necessary.

In these situations, it's possible to can use a type called StringBuilder. This is conceptually similar to a string but it is modifiable.

C#
\"string contents here\"    // string literal\n@\"string contents here\"    // verbatim string, escape characters printed as-is (raw string literal)\n$\"{variable} contents here\"    // string interpolation\n$@\"{variable} \\n contents here\"    // verbatim string interpolation\nstring stringa_1 = stringa_2 + \"string contents here\";    // string concatenation\nString.Length    // returns the length of the string\n
"},{"location":"languages/dotnet/csharp/csharp.html#string-methods-not-in-place","title":"String Methods (Not In-Place)","text":"C#
string_.IndexOf(<character/string>, startIndex, endIndex);    // index of first occurrence of character/string, -1 otherwise\nstring_.LastIndexOf(<character/string>, startIndex, endIndex);    // index last occurrence of character/string, -1 otherwise\nstring_.IndexOfAny(char_array, startIndex, endIndex);    // index of any of the characters in the supplied array\nstring_.Substring(startIndex, length);    // extract substring\nstring_.Substring(startIndex);    // return every character after startIndex\nstring_.Replace(oldString, newString);    // returns string_ with oldString replaced with newString\nstring_.Insert(startIndex, substring);    // return string_ inserting substring at position startIndex\nstring_.Remove(startIndex, length);    // return string_ removing a substring of length length at position startIndex\nstring_.ToUpper();    // transforms all string in uppercase characters\nstring_.ToLower();    // transforms all string to lowercase characters\nstring_.Contains(target);    // returns True if string contains the target, False otherwise\nstring_.StartsWith(substring);    // Determines whether the start of the string matches the substring.\nstring_.EndsWith(substring);    // Determines whether the end of the string matches the substring.\nstring_.PadLeft(n, 'character');    // insert character n times as left padding. In-place operation\nstring_.PadRight(n, 'character');    // insert character n times as right padding. In-place operation\nstring_.TrimStart();    // trim leading spaces before text\nstring_.TrimEnd();    // trim following spaces after text\nstring_.Trim();    // trim spaces around text\nstring_.GetHashCode()\nstring_.Spit('<separator>');    // returns an array separating the string at the occurrences of <separator> (<separator> MUST BE char)\n\nString.Join('<separator>', (object) iterable);    // returns a string from iterable. values separated by <separator> (<separator> MUST BE char)\nString.Format($\"{variable}\"); // string interpolation outside of a Write/WriteLine\n\nString.Empty;  // value of an empty string, used for string init\n
"},{"location":"languages/dotnet/csharp/csharp.html#raw-string-literals","title":"Raw string literals","text":"

Raw string literals can contain arbitrary text, including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences. A raw string literal starts with at least three double-quote (\"\"\") characters. It ends with the same number of double-quote characters. Typically, a raw string literal uses three double quotes on a single line to start the string, and three double quotes on a separate line to end the string. The newlines following the opening quote and preceding the closing quote aren't included in the final content:

C#
string longMessage = \"\"\"\n    This is a long message.\n    It has several lines.\n        Some are indented\n                more than others.\n    Some should start at the first column.\n    Some have \"quoted text\" in them.\n    \"\"\";\n

Note: Any whitespace to the left of the closing double quotes will be removed from the string literal.

Raw string literals can be combined with string interpolation to include braces in the output text. Multiple $ characters denote how many consecutive braces start and end the interpolation

C#
var location = $$\"\"\"\n    You are at {{{Longitude}}, {{Latitude}}}\n    \"\"\";\n
"},{"location":"languages/dotnet/csharp/csharp.html#nullable-types","title":"Nullable Types","text":""},{"location":"languages/dotnet/csharp/csharp.html#nullable-value-types","title":"Nullable value types","text":"

A nullable value type T? represents all values of its underlying value type T and an additional null value.

Any nullable value type is an instance of the generic System.Nullable<T> structure. Refer to a nullable value type with an underlying type T in any of the following interchangeable forms: Nullable<T> or T?.

Note: Nullable Value Types default to null.

When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable<T> object, not the Nullable<T> object itself. That is, if the HasValue property is true, the contents of the Value property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new Nullable<T> structure initialized to the underlying value.

If the HasValue property of a nullable type is false, the result of a boxing operation is null. Consequently, if a boxed nullable type is passed to a method that expects an object argument, that method must be prepared to handle the case where the argument is null. When null is unboxed into a nullable type, the common language runtime creates a new Nullable<T> structure and initializes its HasValue property to false.

C#
Type? nullableValueType = default;  // assigns null\n\nnullableValueType.HasValue  // boolean, use for null check\nnullableValueType.Value  // underlying value type contents\n
"},{"location":"languages/dotnet/csharp/csharp.html#nullable-reference-types","title":"Nullable reference types","text":"

C# 8.0 introduces nullable reference types and non-nullable reference types that enable to make important statements about the properties for reference type variables:

The ? character appended to a reference type declares a nullable reference type. The null-forgiving operator ! may be appended to an expression to declare that the expression isn't null. Any variable where the ? isn't appended to the type name is a non-nullable reference type.

"},{"location":"languages/dotnet/csharp/csharp.html#nullability-of-types","title":"Nullability of types","text":"

Any reference type can have one of four nullabilities, which describes when warnings are generated:

The nullability of a type in a variable declaration is controlled by the nullable context in which the variable is declared.

"},{"location":"languages/dotnet/csharp/csharp.html#nullable-context","title":"Nullable Context","text":"

Nullable contexts enable fine-grained control for how the compiler interprets reference type variables.

Valid settings are:

In Project.csproj:

XML
<Project Sdk=\"Microsoft.NET.Sdk\">\n    <PropertyGroup>\n        <OutputType>Exe</OutputType>\n        <TargetFramework>...</TargetFramework>\n\n        <!-- set nullabilty context at project level -->\n        <Nullable>enable | warning | annotations | disable</Nullable>\n    </PropertyGroup>\n</Project>\n

In Program.cs:

C#
#nullable enable  // Sets the nullable annotation context and nullable warning context to enabled.\n#nullable disable  // Sets the nullable annotation context and nullable warning context to disabled.\n#nullable restore  // Restores the nullable annotation context and nullable warning context to the project settings.\n#nullable disable warnings  // Set the nullable warning context to disabled.\n#nullable enable warnings  // Set the nullable warning context to enabled.\n#nullable restore warnings  // Restores the nullable warning context to the project settings.\n#nullable disable annotations  // Set the nullable annotation context to disabled.\n#nullable enable annotations  // Set the nullable annotation context to enabled.\n#nullable restore annotations  // Restores the annotation warning context to the project settings.\n
"},{"location":"languages/dotnet/csharp/csharp.html#null-conditional-null-coalescing-null-forgiving-operator-null-checks","title":"Null Conditional, Null Coalescing, Null Forgiving Operator, Null Checks","text":"C#
Type? variable = null;  // the variable can also contain the NULL value (nullable type)\n\n<expr>!  // declare explicitly that the expression is not null (null forgiving operator)\n\n(variable == null ? null : variable.property)\n// same as\nvariable?.property  // if variable != null access it's property (null conditional), return null otherwise\n\nif (variable != null)\n{\n    return variable;\n}\nelse\n{\n    return value;\n}\n// same as\nvar variable = var ?? value  // return var if var != null, return value otherwise\n\nvariable = variable?.property ?? value  // if (variable == null) -> variable = value -- null coalescing\n// same as\nvariable ??= value;  // if (variable == null) -> variable = value -- null coalescing\n\n// null checks through patter matching\nvariable is null\nvariable is not null\n\n// null parameter checking [C# 10]\nArgumentNullException.ThrowIfNull(obj);\n
"},{"location":"languages/dotnet/csharp/csharp.html#nullable-attributes","title":"Nullable Attributes","text":"

It's possible to apply a number of attributes that provide information to the compiler about the semantics of APIs. That information helps the compiler perform static analysis and determine when a variable is not null.

"},{"location":"languages/dotnet/csharp/csharp.html#type-conversion","title":"Type Conversion","text":"C#
variable.GetType();  // System type of variable\n\n(type) variable  // explicit conversion\nnumericalType.ToSting();     // convert numerical value to a string\nnumericalType variable = <SystemType/Type>.Parse();    // convert string to numerical data type (can cause exception at runtime)\n\n<SystemType/Type>.TryParse(value, out variable);    // improved version of Parse()\n/* attempts to parse a string into the given numeric data type.\nIf successful, it will store the converted value in an OUT PARAMETER.\nIt returns a bool to indicate if it was successful or not */\n\nConvert.To<SystemType>(variable);    // proper conversion and round-up of values (no truncation of values)\n
"},{"location":"languages/dotnet/csharp/csharp.html#converting-from-any-type-to-a-string","title":"Converting from any type to a string","text":"

The ToString method converts the current value of any variable into a textual representation. Some types can't be sensibly represented as text, so they return their namespace and type name.

"},{"location":"languages/dotnet/csharp/csharp.html#number-downcasting","title":"Number Downcasting","text":"

The rule for rounding (in explicit casting) in C# is subtly different from the primary school rule:

This rule is known as Banker's Rounding, and it is preferred because it reduces bias by alternating when it rounds up or down.

"},{"location":"languages/dotnet/csharp/csharp.html#converting-from-a-binary-object-to-a-string","title":"Converting from a binary object to a string","text":"

The safest thing to do is to convert the binary object into a string of safe characters. Programmers call this Base64 encoding. The Convert type has a pair of methods, ToBase64String and FromBase64String, that perform this conversion.

"},{"location":"languages/dotnet/csharp/csharp.html#parsing-from-strings-to-numbers-or-dates-and-times","title":"Parsing from strings to numbers or dates and times","text":"

The second most common conversion is from strings to numbers or date and time values. The opposite of ToString is Parse. Only a few types have a Parse method, including all the number types and DateTime.

"},{"location":"languages/dotnet/csharp/csharp.html#preprocessor-directives","title":"Preprocessor Directives","text":"

C# offers a #define directive that lets you define a compilation symbol. These symbols are commonly used in conjunction with the #if directive to compile code in different ways for different situations. It's common to define compilation symbols through the compiler build settings: open up the .csproj file and define the values you want in a <DefineConstants> element of any <PropertyGroup>.

Compilation symbols are typically used in conjunction with the #if, #else, #elif, and #endif directives (#if false also exists).

The .NET SDK defines certain symbols by default. It supports two configurations: Debug and Release. It defines a DEBUG compilation symbol in the Debug configuration, whereas Release will define RELEASE instead. It defines a symbol called TRACE in both configurations.

C#
#if DEBUG\n    // instructions\n#endif\n

C# provides a more subtle mechanism to support this sort of thing, called a conditional method. The compiler recognizes an attribute defined by the .NET class libraries, called ConditionalAttribute, for which it provides special compile time behavior. Method annotated with this attribute will not be present in a non-Debug release.

C#
[System.Diagnostics.Conditional(\"DEBUG\")]\nType Method() { ... }\n
"},{"location":"languages/dotnet/csharp/csharp.html#error-and-warning","title":"#error and #warning","text":"

C# allows choose to generate compiler errors or warnings with the #error and #warning directives. These are typically used inside conditional regions.

C#
#if NETSTANDARD\n    #error .NET Standard is not a supported target for this source file\n#endif\n
"},{"location":"languages/dotnet/csharp/csharp.html#pragma","title":"#pragma","text":"

The #pragma directive provides two features: it can be used to disable selected compiler warnings, and it can also be used to override the checksum values the compiler puts into the .pdb file it generates containing debug information. Both of these are designed primarily for code generation scenarios, although they can occasionally be useful to disable warnings in ordinary code.

C#
#pragma warning disable CS<number>\n
"},{"location":"languages/dotnet/csharp/csharp.html#expressions-operators","title":"Expressions & Operators","text":""},{"location":"languages/dotnet/csharp/csharp.html#primary-expressions","title":"Primary Expressions","text":"Syntax Operation x.m access to member m of object x (\".\" \u2192 member access operator) x(...) method invocation (\"()\" \u2192 method invocation operator) x[...] array access new T(...) object instantiation new T(...){...} object instantiation with initial values new T[...] array creation typeof(T) System.Type of object x nameof(x) name of variable x sizeof(x) size of variable x default(T) default value of T x! declare x as not null"},{"location":"languages/dotnet/csharp/csharp.html#unary-operators","title":"Unary Operators","text":"Operator Operation +x identity -x negation !x logic negation ~x binary negation ++x pre-increment --x pre-decrement x++ post-increment x-- post decrement (type)x explicit casting"},{"location":"languages/dotnet/csharp/csharp.html#mathematical-operators","title":"Mathematical Operators","text":"Operator Operation x + y addition, string concatenation x - y subtraction x * y multiplication x / y integer division, x % y modulo, remainder x << y left bit shift x >> y right bit shift"},{"location":"languages/dotnet/csharp/csharp.html#relational-operators","title":"Relational Operators","text":"Operator Operation x < y less than x <= y less or equal to x > y greater than x >= y greater or equal to x is T true if x is an object of type T x == y equality x != y inequality"},{"location":"languages/dotnet/csharp/csharp.html#logical-operators","title":"Logical Operators","text":"Operator Operation Name ~x bitwise NOT x & y bitwise AND x ^ y bitwise XOR x | y bitwise OR x && y evaluate y only if x is true x || y evaluate y only if x is false x ?? y evaluates to y only if x is null, x otherwise Null coalescing x?.y stop if x == null, evaluate x.y otherwise Null conditional"},{"location":"languages/dotnet/csharp/csharp.html#assignment","title":"Assignment","text":"Operator Operation x += y x = x + y x -= y x = x - y x *= y x = x * y x /= y x = x / y x %= y x = x % y x <<= y x = x << y x >>= y x = x >> y x &= y x = x & y x |= y x = x x ^= y x = x ^ y x ??= y if (x == null) {x = y}"},{"location":"languages/dotnet/csharp/csharp.html#conditional-operator","title":"Conditional Operator","text":"

<condition> ? <return_if_condition_true> : <return_if_condition_false>;

"},{"location":"languages/dotnet/csharp/csharp.html#decision-statements","title":"Decision Statements","text":""},{"location":"languages/dotnet/csharp/csharp.html#if-else-if-else","title":"If-Else If-Else","text":"C#
Object o;\n\nif (condition)\n{\n    // code here\n}\nelse if (o is Type t)  // test variable to determine if matches a type\n{\n    // t gets the value of o if the test succeeds\n}\nelse\n{\n    // code here\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#pattern-matching","title":"Pattern Matching","text":"

Pattern Matching

A pattern describes one or more criteria that a value can be tested against. It's usable in switch statements, switch expressions and if statements.

C#
// type pattern\n<expr> is Type t  // type pattern\n\n// positional pattern\n<expr> is (Type X, Type Y):  // positional pattern\n<expr> is (Type X, _):  // discard pattern\n\n// property pattern\n<expr> is Type { Property: value }:  // is type and property has a certain value\n<expr> is Type { Property: value } out:  // output variable is usable in the block\n<expr> is { Property.InnerProperty: value }  // match nested properties\n\n// constant pattern\n<expr> is literalValue  // e.g. 1, 'c', \"literal\"\n<expr> is CONSTANT\n<expr> is Enum.Value\n\n// logical patterns\n<expr> is not pattern\n<expr> is pattern and pattern\n<expr> is pattern or pattern\n\n// relational pattern\n<expr> is > value\n<expr> is < value\n<expr> is <= value\n<expr> is >= value\n\n// multiple value & nested value patterns\n<expr> is { Property.InnerProperty: value }  // match in nested properties\n<expr> is { Property1 : value1, Property2: value2 }  // multiple inputs\n<expr> is (value1, value2)  // multiple inputs (with deconstruction)\n\n// multiple values and relations\n<expr> is ( > value1, > value2),\n<expr> is { Property1: > value1, Property2: > value2 }\n\n// list patterns\n<expr> is [value1, value2, value1]  // positional match\n<expr> is [value1 or value2, <= value3, >= value4]  // relational comparison\n<expr> is [< 0, .. { Length: 2 or 4 }, > 0]  // item property match\n<expr> is [_, var middle, _] // discarding & capturing\n<expr> is [value1, .., valueN]  // match any number of items\n<expr> is [value1, .. var rest]  // capture any number of items\n
"},{"location":"languages/dotnet/csharp/csharp.html#switch","title":"Switch","text":"

The when keyword can be used to specify a filter condition that causes its associated case label to be true only if the filter condition is also true.

Switch Expressions

C#
switch (expr)\n{\n    // multiple labels for same block\n    case key_0:\n    case key_1:\n        // code here\n        break;  // or return or goto\n\n    case key_2:\n        // code here\n        goto case key_2;  // explicit fall-through (omitting break is not possible in c#)\n\n    case key_3 when (when-condition):\n        // code here\n        break;\n\n    // cases using pattern matching\n\n    default:\n        // code here\n        break;\n}\n\n// return a value based on the value of an input variable or tuple\nvariable switch\n{\n    key_1 => value,\n    key_2 => value,\n    // cases using pattern matching\n    ...\n    _ => default_value  // underscore (_) discard pattern as default case\n};\n
"},{"location":"languages/dotnet/csharp/csharp.html#loop-statements","title":"Loop Statements","text":""},{"location":"languages/dotnet/csharp/csharp.html#while-loop","title":"While Loop","text":"C#
while (condition)\n{\n    // code here\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#do-while-loop","title":"Do-While Loop","text":"

Executes at least one time.

C#
do\n{\n    // code here\n}\nwhile (condition);\n
"},{"location":"languages/dotnet/csharp/csharp.html#for-loop","title":"For Loop","text":"C#
for (initializer; condition; iterator)\n{\n    // code here\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#foreach-loop","title":"Foreach Loop","text":"

Technically, the foreach statement will work on any type that follows these rules:

  1. The type must have a method named GetEnumerator that returns an object.
  2. The returned object must have a property named Current and a method named MoveNext.
  3. The MoveNext method must return true if there are more items to enumerate through or false if there are no more items.

There are interfaces named IEnumerable and IEnumerable<T> that formally define these rules but technically the compiler does not require the type to implement these interfaces.

C#
foreach (type item in iterabile)\n{\n    // code here\n}\n

Note: Due to the use of an iterator, the variable declared in a foreach statement cannot be used to modify the value of the current item. Note: From C# 9 it's possible to implement GetEnumerator() as an extension method making enumerable an class that normally isn't.

Example:

C#
// make integers enumerable\npublic static IEnumerator<int> GetEnumerator(this int source)\n{\n    for(int i = 0; i < number; i++)\n    {\n        yield return i;\n    }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#break-continue","title":"Break, Continue","text":"

break; interrupts and exits the loop. continue; restarts the loop cycle without evaluating the instructions.

"},{"location":"languages/dotnet/csharp/csharp.html#yield-statement","title":"Yield Statement","text":"C#
yield return <expression>;    // returns the results one at a time.\nyield break;    // concludes the iteration\n
"},{"location":"languages/dotnet/csharp/csharp.html#context-statement-using-declarations","title":"Context Statement & Using Declarations","text":"C#
using (Type obj = new Type())  // obj disposed at the end of the using block\n{\n    // code here\n}\n\n// or (C# 8+)\n{\n    // inside a code block (if, loop, function)\n    using Type obj = new Type();  // disposed at the end of the block\n\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#checkedunchecked-statements","title":"Checked/Unchecked Statements","text":"

In checked code block ore expression the mathematic overflow causes an OverflowException. In unchecked code block the mathematic overflow is ignored end the result is truncated.

It's possible configure the C# compiler to put everything into a checked context by default, so that only explicitly unchecked expressions and statements will be able to overflow silently. It is done by editing the .csproj file, adding <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> inside a <PropertyGroup>.

Note: checking can make individual integer operations several times slower.

C#
checked\n{\n    // code here\n}\n\nchecked(<expr>);\n\nunchecked\n{\n    // code here\n}\n\nunchecked(<expr>);\n
"},{"location":"languages/dotnet/csharp/csharp.html#exception-handling","title":"Exception Handling","text":"

Exception Object

C#
try\n{\n    // \"dangerous\" code\n}\ncatch (SpecificException e)\n{\n}\ncatch (SpecificException e) when (condition)  // exception filter\n{\n}\ncatch (Exception e)\n{\n    // code executed if Exception happens\n    e.Message  // exception message\n    e.InnerException  // Exception instance that caused the current exception\n    e.Source  // Get or set the name of the application or the object that causes the error\n}\nfinally\n{\n    // code executed anyway\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#throwing-exceptions","title":"Throwing Exceptions","text":"C#
throw new ExceptionClass();\nthrow new ExceptionClass(\"message\");\n\n// RE-THROWING EXCEPTIONS\ntry\n{\n    // dangerous code\n}\ncatch (SpecificException e)\n{\n    // log error\n    throw;  // rethrow exception w/o loosing StackTrace & TargetSite information (usable only inside catch)\n}\n\n// Immediately terminate a process after writing a message to the Windows Application event log, and then include the message and optional exception information in error reporting to Microsoft.\nEnvironment.FailFast(causeOfFailure);\n
"},{"location":"languages/dotnet/csharp/csharp.html#custom-exceptions","title":"Custom Exceptions","text":"C#
public class CustomException : Exception  // must derive from Exception (either directly or indirectly)\n{\n    public CustomException()\n    {\n    }\n\n    public CustomException(string message)\n        : base(message)\n    {\n    }\n\n    public CustomException(string message, Exception inner)\n        : base(message, inner)\n    {\n    }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#enums","title":"Enums","text":"

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type (int, long, byte, ...). Consecutive names increase the value by one.

C#
[Flags]  // indicate that the flag can be combined (best if values are binary) as a bit mask\nenum EnumType : IntegralNumericType // named values MUST match IntegerNumericType allowed values\n{\n    None = 0,            // if uninitiated value is zero\n    Const = 2,     // value is 2\n    Const2,          // value is Const + 1\n    ...\n}\n\n(Type) EnumType.Const;  // extract the value, will return the name otherwise\n(EnumType) value;  // convert from associated value to enum\n\nEnum.IsDefined(typeof(EnumType), value);  // whether a given integral value, or its name as a string, exists in a specified enumeration.\nenumObj.HasValue(enumType.Const)  // test whether a flag is set in a numeric value\n\nEnumType instance = (EnumType) EnumType.ToObject(typeof(EnumType), value);  // convert a value of any integral type to an enumeration value\n\n// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object\nEnum.Parse(typeof(EnumType), value);\nEnum.TryParse<EnumType>(string, out EnumType enumObj);\n\n// retrieve a string array containing the names of the enumeration members\nstring[] enumNames = Enum.GetNames(typeof(EnumType));\n
"},{"location":"languages/dotnet/csharp/csharp.html#methods","title":"Methods","text":"

The method signature is the number & type of the input parameters defined for the method.

C# makes the fairly common distinction between parameters and arguments: a method defines a list of the inputs it expects (the parameters) and the code inside the method refers to these parameters by name. The values seen by the code could be different each time the method is invoked, and the term argument refers to the specific value supplied for a parameter in a particular invocation.

C#
type MethodName (type parameter, ...)\n{\n    // code here\n    return <expression>;\n}\n\nvoid MethodName (type parameter, ...) {\n    // code here\n    return;  // if type is void return can be used to force early termination or can be omitted\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#expression-body-definition","title":"Expression Body Definition","text":"C#
type MethodName() => <expression>;    // expression result type MUST match method type\n
"},{"location":"languages/dotnet/csharp/csharp.html#arbitrary-number-of-parameter-in-methods","title":"Arbitrary Number Of Parameter In Methods","text":"C#
// params keyword must be last parameter and must be an array\ntype MethodName (type parameter, params type[] args)\n{\n    // code here\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#named-arguments","title":"Named Arguments","text":"C#
type MethodName (type param1, type param2, ...) { }\n\nMethodName(param1: value, param2: value);\nMethodName(param2: value, param1: value);  // order can be any\n\n// Named arguments, when used with positional arguments, are valid as long as they're not followed by any positional arguments, or they're used in the correct position.\nMethodName(value, param2: value);\n
"},{"location":"languages/dotnet/csharp/csharp.html#optional-arguments","title":"Optional Arguments","text":"

The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. Optional parameters are defined at the end of the parameter list, after any required parameters.

A default value must be one of the following types of expressions:

C#
type MethodName (type required, type firstOptional = default_value, type secondOptional = default_value, ...) { }\nMethodName(value1);  // use defaults for optional arguments\nMethodName(required: value, secondOptional: value);  // use default for first optional but pass second optional\n

Note: If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list are not supported.

"},{"location":"languages/dotnet/csharp/csharp.html#passing-values-by-reference-ref-out-in","title":"Passing Values By Reference (ref, out, in)","text":"

Ref Docs, Out Docs, In Docs

The out, in, ref keywords cause arguments to be passed by reference. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument. This behaviour is the same for classes and structs.

An argument that is passed to a ref or in parameter must be initialized before it is passed. However in arguments cannot be modified by the called method. Variables passed as out arguments do not have to be initialized before being passed in a method call. However, the called method is required to assign a value before the method returns.

Use cases:

Note: use in only with readonly value types, because mutable value types can undo the performance benefits. (Mutable value types are typically a bad idea in any case.)

While the method can use members of the passed reference type, it can't normally replace it with a different object. But if a reference type argument is marked with ref, the method has access to the variable, so it could replace it with a reference to a completely different object.

C#
// method declaration\ntype MethodName (type param1,  ref type param2, out type param3, in type param4, ...)\n{\n    // code here\n}\n\n// method call needs REF & OUT keywords, IN keyword is optional (pass by reference regardless)\nMethodName(arg1, ref arg2, out arg3, in arg4);\nMethodName(arg1, ref arg2, out arg3, arg4);\n\ntype OutMethod(type param1, out type param2){}\nOutMethod(arg1, out var arg2);  // create out variable on the fly\n
"},{"location":"languages/dotnet/csharp/csharp.html#returning-multiple-values-with-tuples","title":"Returning Multiple Values with Tuples","text":"

Must be C# 7+. The retuned tuple MUST match the tuple-type in the instantiation

C#
(type returnedVar1, type returnedVar2, ...) MethodName (type parameter, ...)\n{\n   // code here\n   return (expression, expression, ...)\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#returning-multiple-values-w-structs-return-struct-variable","title":"Returning Multiple Values W/ Structs (Return Struct Variable)","text":"C#
StructName MethodName (args)\n{\n   // code here\n   var variable = new StructName     {\n       // code here\n   }\n\n   return variable;\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#local-functions","title":"Local Functions","text":"C#
type OuterMethod(...)\n{\n    var foo = InnerMethod();\n\n    type InnerMethod(...) { }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#extension-methods","title":"Extension Methods","text":"

Extension methods allow their usage applied to the extended type as if their declaration was inside the object's class. Extension methods are not really members of the class for which they are defined. It's just an illusion maintained by the C# compiler, one that it keeps up even in situations where method invocation happens implicitly.

Note: Extension Method can be declared only inside static classes. Extension methods are available only if their namespace is imported with the using keyword.

C#
public static class ExtensionMethods\n{\n    type ExtensionMethod(this type param)\n    {\n        // code here\n    }\n}\n\ntype var = value;\nvar.ExtensionMethod();  // use the method on a object as if the method belongs to the object\n
"},{"location":"languages/dotnet/csharp/csharp.html#iterators","title":"Iterators","text":"

An iterator can be used to step through collections such as lists and arrays.

An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time. When a yield return statement is reached, the current location in code is remembered. Execution is restarted from that location the next time the iterator function is called.

It's possible to use a yield break statement or exception to end the iteration.

Note: Since an iterator returns an IEnumerable<T> is can be used to implement a GetEnumerator().

C#
// simple iterator\npublic static System.Collections.IEnumerable<int> IterateRange(int start = 0, int end)\n{\n    for(int i = start; i < end; i++){\n        yield return i;\n    }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#structs-custom-value-types-classes-custom-reference-types","title":"Structs (Custom Value Types) & Classes (Custom Reference Types)","text":"

Structure types have value semantics. That is, a variable of a structure type contains an instance of the type.

Class types have reference semantics. That is, a variable of a class type contains a reference to an instance of the type, not the instance itself.

Typically, you use structure types to design small data-centric types that provide little or no behavior. If you're focused on the behavior of a type, consider defining a class. Because structure types have value semantics, we recommend you to define immutable structure types.

Creating a new instance of a value type doesn't necessarily mean allocating more memory, whereas with reference types, a new instance means anew heap block. This is why it's OK for each operation performed with a value type to produce a new instance.

The most important question is : does the identity of an instance matter? In other words, is the distinction between one object and another object important?

An important and related question is: does an instance of the type contain state that changes over time? Modifiable value types tend to be problematic, because it's all too easy to end up working with some copy of a value, and not the correct instance. So it's usually a good idea for value types to be immutable. This doesn't mean that variables of these types cannot be modified; it just means that to modify the variable, its contents must be replaced entirely with a different value.

C#
public struct Point\n{\n    public Point(double x, double y)\n    {\n        X = x;\n        Y = y;\n    }\n\n    public double X { get; set; }\n    public double Y { get; set; }\n\n    public override string ToString() => $\"({X}, {Y})\";\n\n}\n

Note: From C# 10 is possible to have a parameterless constructor and make a new struct using a with statement. Note: From C# 11 uninitialized values will be filed with their defaults

The only way to affect a struct variable both inside a method and outside is to use the ref keyword;

"},{"location":"languages/dotnet/csharp/csharp.html#modifiers-methods-variables","title":"Modifiers (Methods & Variables)","text":"

A locally scoped variable is only accessible inside of the code block in which it's defined. If you attempt to access the variable outside of the code block, you'll get a compiler error.

Access Modifiers

C#
// ACCESS MODIFIERS\npublic    // visible from everywhere\nprivate    // not visible outside of the class (default for members)\nprotected    // visible only to the same class and extending classes\ninternal  // available for use only within the assembly (default for classes)\nprotected internal  // can be accessed by any code in the assembly in which it's declared, or from within a derived class in another assembly\nprivate protected  // can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class\nfile  // can be accessed only in the same file in which is declared. Will not clash with other classes/method/interface with the same name\n\nreadonly  // value can be read but not modified\nstatic  // not of the instance of a class\nsealed  // cannot be inherited or overridden (default case), sealing a virtual class/method prevents further modifications (on methods sealed must always be used with override)\nabstract  // derived classes MUST implement this\nvirtual  // can be overridden by derived classes (applicable to Properties)\nnew  // hide base's (parent's) method\n\nasync  // method, lambda expression, or anonymous method is asynchronous\nvolatile // field might be modified by multiple threads that are executing at the same time\nunsafe // unsafe context, required for any operation involving pointers\nextern // method is implemented externally\n

partial indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility.

If any part is declared abstract, then the whole type is considered abstract. If any part is declared sealed, then the whole type is considered sealed. If any part declares a base type, then the whole type inherits that class.

"},{"location":"languages/dotnet/csharp/csharp.html#methods_1","title":"Methods","text":"C#
class Class\n{\n    static Type Method(Type Argument, ...) {}  // static method, can operate ONLY on STATIC VARIABLES\n\n    Type Method(Type Argument, ...) {}  // instance method, can operate on INSTANCE VARIABLES\n\n    // override inherited method\n    public override Type Method()\n    {\n    }\n\n    // visrual methods CAN be overridden\n    public virtual Type Method()\n    {\n    }\n}```\n\n### Constructors\n\n```cs\nclass Class(Type Parameter, ...)  // primary constructor (like records)\n{\n\n    public Class() { }  // parameterless constructor\n\n    // standard constructor\n    public Class(type parameter)\n    {\n        _field = field;\n    }\n\n    // extends an existing constructor adding parameters to the existing ones\n    public Class(type parameter, type other) : this(parameter)\n    {\n        _other = other;\n    }\n}\n

Note: if a primary constructor is used all other constructors must use this(...) to invoke it

"},{"location":"languages/dotnet/csharp/csharp.html#properties-fields","title":"Properties & Fields","text":"

Properties Docs

A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type. A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.

C#
class Class\n{\n\n    public static Type Field = value;    // static (non-instance) public field  w/ initializer\n\n    private Type _field = value;    // private instance field w/ initializer\n    private Type _field;  // private instance field, initialized by constructor\n\n    private type _backingField;\n\n    // PROPERTY\n    public type Property\n    {\n        get { return _backingField }\n        set { _backingField = value; }\n    }\n\n    // PROPERTY WITH EXPRESSION BODY DEFINITIONS\n    public type Property\n    {\n        get => _backingField;\n        set => _backingField = value;\n    }\n\n    // REQUIRED PROPERTY prop must be set at obj init (in constructor or initializer)\n    public required Type Property { get; set; }\n\n    // EXPRESSION-BODIED READ-ONLY PROPERTY\n    public type Property => <expr>;\n\n    // AUTO-PROPERTIES\n    public Property { get; set; }\n    public Property { get; private set; }  // settable only inside class\n    public Property { get; init; } // settable only in constructor, initializer, keyword with\n    public Property { get; }  // can only be setted by constructor\n\n    // MIXED\n    public type Property\n    {\n        get => _backingField;\n        set => { ... }\n    }\n\n    Property = value;  // set\n    Property;  // get\n}\n

Note: The init accessor is a variant of the set accessor which can only be called during object initialization. Because init accessors can only be called during initialization, they are allowed to mutate readonly fields of the enclosing class, just like in a constructor. Note: creating at least one constructor hides the one provided by default (w/ zero parameters).

"},{"location":"languages/dotnet/csharp/csharp.html#object-and-collection-initializers","title":"Object and Collection Initializers","text":"

Object initializers allow to assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements. The object initializer syntax enables to specify arguments for a constructor or omit the arguments (and parentheses syntax).

C#
public class Class\n{\n    // Auto-implemented properties.\n    public Type Prop1 { get; set; }\n    public Type Prop2 { get; set; }\n\n    public Class()\n    {\n    }\n\n    public Class(Type arg)\n    {\n        Prop1 = arg;\n    }\n}\n\n// standard way\nClass obj = new Class(arg1)\nobj.Prop2 = arg2;\n\n// known target type\nClass obj = new(arg1, ...)\n\n// object initializers\nClass obj = new Class { Prop2 = arg2, Prop1 = arg1 };  // w/o constructor\nClass obj = new Class(arg1) { Prop2 = arg2 };  // w/ constructor\n\n// with keyword\nvar copy = original with { Prop = newValue };  // other props are copies of the original\n
C#
public class Matrix\n{\n    private double[,] matrix = new double[3, 3];\n\n    public double this[int row, int column]\n    {\n        // The embedded array will throw out of range exceptions as appropriate.\n        get { return matrix[row, column]; }\n        set { matrix[row, column] = value; }\n    }\n}\n\n// collection initializer\nvar identity = new Matrix\n{\n    [0, 0] = 1.0,\n    [0, 1] = 0.0,\n    [0, 2] = 0.0,\n\n    [1, 0] = 0.0,\n    [1, 1] = 1.0,\n    [1, 2] = 0.0,\n\n    [2, 0] = 0.0,\n    [2, 1] = 0.0,\n    [2, 2] = 1.0,\n};\n\nList<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\nList<int> digits = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];\n\nint[] digits = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\nint[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\nint[] digits = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];\n\nDictionary<int, string> digits = new Dictionary<int, string> {\n    { 0, \"zero\" },\n    { 1, \"one\" },\n    { 2, \"two\" },\n    { 3, \"three\" },\n    { 4, \"four\" },\n    { 5, \"five\" },\n    { 6, \"six\" },\n    { 7, \"seven\" },\n    { 8, \"eight\" },\n    { 9, \"nine\" }\n};\n\nDictionary<int, string> digits = [\n    0: \"zero\",\n    1: \"one\",\n    2: \"two\",\n    3: \"three\",\n    4: \"four\",\n    5: \"five\",\n    6: \"six\",\n    7: \"seven\",\n    8: \"eight\",\n    9: \"nine\"\n];\n
"},{"location":"languages/dotnet/csharp/csharp.html#static-class","title":"Static Class","text":"

The static keyword declares that a member is not associated with any particular instance of the class. Static classes can't instantiate objects and all their methods must be static.

C#
static class Class\n{\n    // static constructor, not called explicitly, has no arguments\n    // triggered by one of two events, whichever occurs first: creating an instance, or accessing any static member of the class.\n    // since it's static and takes no arguments there can be at most one for each class\n    static Class()\n    {\n    }\n\n    static Type _field = value;\n\n    static Type Property { get; set; } = value;\n\n    static Type Method (Type parameter, ...)\n    {\n    }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#class-members-init-order","title":"Class Members Init Order","text":"

Static Field or Method Usage:

  1. Static field initializers in order of apparition
  2. Static Constructor

Class Instantiation (new operator):

  1. Instance field initializers in order of apparition
  2. Instance Constructor

Object Creation: Class object = new Class(arguments); Instance Method Usage: object.method(arguments); Static Method Usage: Class.method(arguments);

"},{"location":"languages/dotnet/csharp/csharp.html#indexers","title":"Indexers","text":"

An indexer is a property that takes one or more arguments, and is accessed with the same syntax as is used for arrays. This is useful when writing a class that contains a collection of objects.

C#
public class Class<T>\n{\n    public T this[int i]\n    {\n        get => ...;  // return the i-th element in the collection\n    }\n}\n\n// null conditional index access\nClass? c = objWithIndexer?[index];\n// same as\nClass? c = objWithIndexer == null ? null : objWithIndexer[index];\n
"},{"location":"languages/dotnet/csharp/csharp.html#abstract-classes","title":"Abstract Classes","text":"

The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes, not instantiated on its own. Members marked as abstract must be implemented by non-abstract classes that derive from the abstract class.

abstract classes have the following features:

Note: Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.

abstract methods have the following features:

abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.

C#
public abstract class Abstract : Interface\n{\n    public abstract Type Property { get; set; }\n\n    // interface methods can be mapped to abstract methods\n    public abstract Type Method();\n    public abstract override Type Method();  // force overriding (derived classes must provide new implementation)\n}\n\npublic class Derived : Abstract\n{\n    public override Type Property\n    {\n        // new behaviour\n        get => <expr>;\n        set => <expr>;\n    }\n\n    public override Type Method() { /* statements */ }  // implementation of abstract method\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#cloning","title":"Cloning","text":"C#
Class obj = new Class()\n\nObject.MemberwiseClone();  // Returns shallow copy of the object\nIClonable.Clone();  //  Creates a new object that is a copy of the current instance.\n
"},{"location":"languages/dotnet/csharp/csharp.html#deconstruction","title":"Deconstruction","text":"

Deconstruction is not limited to tuples. By providing a Deconstruct(...) method(s) C# allows to use the same syntax with the users types.

Note: Types with a deconstructor can also use positional pattern matching.

C#
public readonly struct Size\n{\n    public Size(double w, double h)\n    {\n        W = w;\n        H = h;\n    }\n\n    public void Deconstruct(out double w, out double h)\n    {\n        w = W;\n        h = H;\n    }\n\n    public double W { get; }\n    public double H { get; }\n}\n\n// deconstruction\nvar s = new Size(1 , 2);\n(double w, double h) = s;  // w = 1, h = 2\n\n\n// positional patter matching\ns switch\n{\n    (0, 0) => \"Empty\",\n    (0, _) => \"Extremely narrow\",\n    (double w, 0) => $\"Extremely short, and this wide: {w}\",\n    Size _ => \"Normal\",\n    _ => \"Not a shape\"\n};\n\n// Assignment & Declaration\nint height = 0;\n(int width, height) = size;\n
"},{"location":"languages/dotnet/csharp/csharp.html#operator-overloading","title":"Operator Overloading","text":"

A user-defined type can overload a predefined C# operator. That is, a type can provide the custom implementation of an operation in case one or both of the operands are of that type.

Use the operator keyword to declare an operator. An operator declaration must satisfy the following rules:

Overloadable operators

C#
using System;\n\npublic readonly struct Fraction\n{\n    private readonly int num;\n    private readonly int den;\n\n    public Fraction(int numerator, int denominator)\n    {\n        if (denominator == 0)\n        {\n            throw new ArgumentException(\"Denominator cannot be zero.\", nameof(denominator));\n        }\n        num = numerator;\n        den = denominator;\n    }\n\n    // unary arithmetic operators overloading\n    public static Fraction operator +(Fraction a) => a;\n    public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den);\n\n    // binary arithmetic operators overloading\n    public static Fraction operator +(Fraction a, Fraction b)\n        => new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);\n\n    public static Fraction operator -(Fraction a, Fraction b)\n        => a + (-b);\n\n    public static Fraction operator *(Fraction a, Fraction b)\n        => new Fraction(a.num * b.num, a.den * b.den);\n\n    public static Fraction operator /(Fraction a, Fraction b)\n    {\n        if (b.num == 0)\n        {\n            throw new DivideByZeroException();\n        }\n        return new Fraction(a.num * b.den, a.den * b.num);\n    }\n\n    // conversion operator overloading\n    public static implicit operator float(Fraction f) => f.num / f.den;\n    public static explicit operator Fraction(int i) => new Fraction(i, 1);\n\n    // true & false operator overloading (truthiness and falseness more than exact boolean value)\n    public static bool operator true(Fraction f) => f != 0;\n    public static bool operator false(Fraction f) => f == 0;\n    // if &, |, true, false are overloaded than && and || will work\n\n    // comparison operators overloading\n    public static bool operator ==(Fraction f1, Fraction f2) => f1.num == f2.num && f1.den == f2.den;\n    public static bool operator !=(Fraction f1, Fraction f2) => f1.num != f2.num || f1.den != f2.den;\n    public static bool operator >(Fraction f1, Fraction f2) => ...;\n    public static bool operator >=(Fraction f1, Fraction f2) => ...;\n    public static bool operator <(Fraction f1, Fraction f2) => ...;\n    public static bool operator <=(Fraction f1, Fraction f2) => ...;\n\n    public override bool Equals(object obj)\n    {\n        return obj is Fraction f && this.num == f.num && this.den == f.den;  // same type + same values\n    }\n\n    // required if Equals has been implemented\n    public override int GetHashCode()\n    {\n        return (num, den).GetHashCode();\n    }\n\n    public override string ToString() => $\"{num} / {den}\";\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#nested-types","title":"Nested Types","text":"

A type defined at global scope can be only publicor internal. private wouldn't make sense since that makes something accessible only from within its containing type, and there is no containing type at global scope. But a nested type does have a containing type, so if a nested type is private, that type can be used only from inside the type within which it is nested.

Note: Code in a nested type is allowed to use nonpublic members of its containing type. However, an instance of a nested type does not automatically get a reference to an instance of its containing type.

"},{"location":"languages/dotnet/csharp/csharp.html#interfaces","title":"Interfaces","text":"

An interface declares methods, properties, and events, but it doesn't have to define their bodies. An interface is effectively a list of the members that a type will need to provide if it wants to implement the interface.

C# 8.0 adds the ability to define default implementations for some or all methods, and also to define nested types and static fields.

C#
// can only be public or internal if not nested, any accessibility otherwise\npublic interface IContract\n{\n    // properties\n    Type Property { get; set; }\n\n    // methods (only signature)\n    Type Method(Type param, ...);\n\n    // default interface implementations\n    // (method has body), if not implemented in inheriting class the implementation will be this\n    Type Method(Type param, ...) => <expr>;\n\n    // constants\n    const Type CONSTANT = value;\n\n    // static properties\n    static Type StaticProperty { get; set; }\n    static Type StaticMethod();\n\n    // static abstract members\n    static abstract Type AbstractProperty { get; set; }\n    static abstract Type AbstractMethod();\n\n    static abstract IContract operator +(IContract source);\n\n    // nested types are valid, accessibility is needed\n}\n\npublic interface IContract<T> {}  // interfaces can be generic\n\npublic class Contract : IContract { /* ... */ }\n\nvar contract = new Contract();\ncontract.Property;\ncontract.Method();\n\ncontract.AbstractProperty;\ncontract.AbstractMethod();\n\nIContract.CONSTANT;\nIContract.StaticProperty;\nIContract.StaticMethod();\n

Note: Interfaces are reference types. Despite this, it's possible tp implement interfaces on both classes and structs. However, be careful when doing so with a struct, because when getting hold of an interface-typed reference to a struct, it will be a reference to a box, which is effectively an object that holds a copy of a struct in a way that can be referred to via a reference.

"},{"location":"languages/dotnet/csharp/csharp.html#generics","title":"Generics","text":"

Generics Docs Generic Methods Docs

C#
// type parameter T in angle brackets\n// WARNING: T is not instantiable, new t(), new t[] are INVALID\npublic class GenericClass<T> {\n\n    // constructors\n    public GenericClass() { }\n\n    public GenericClass(T data){\n        Generic = data;\n    }\n\n    public T Generic { get; set; }  // generic type auto-property\n\n    void GenericMethodName(T t) { }  // same generic as class\n    void GenericMethodName<S>(S s) { }  // new generic type\n}\n\nGenericClass<Type> obj = new GenericClass<>();\nGenericClass<Type>[] obj = new GenericClass<>[];  // invalid\n\nobj.GenericMethodName<Type>();  // generic method call\nobj.GenericMethodName(Type param);  // type deduced by input, input type and generic method type must match\n
"},{"location":"languages/dotnet/csharp/csharp.html#multiple-generics","title":"Multiple Generics","text":"C#
public class GenericClass<T1, T2, ...> { }  // number of generic types is not limited\n
"},{"location":"languages/dotnet/csharp/csharp.html#parameters-constraints","title":"Parameters Constraints","text":"

Specify an interface or class that the generic type must implement/inherit.

C# supports only six kinds of constraints on a type argument:

C#
// type constraints\npublic class GenericClass<T> where T : Interface { }\npublic class GenericClass<T> where T: GenericClass { }\n\n// Enums and Delegates (type constraints)\npublic class GenericClass<T> where T : Enum { }\npublic class GenericClass<T> where T : Delegate { }\n\n// reference type constraints (cannot be primitives or structs) --> can test nullability, can use AS operator\npublic class GenericClass<T> where T : class { }  // T must be not nullable reference type\npublic class GenericClass<T> where T : class? { }  // T can be (not)nullable reference type\n\n// value type constraint\npublic class GenericClass<T> where T : struct { }  // T must be a struct or a primitive type\npublic class GenericClass<T> where T : unmanaged { }  // T must be a value type and its contents can only be value types, recursively\n\n// no nulls\npublic class GenericClass<T> where T : notnull { }  // T must be a value type or a not nullable reference type\n\npublic class GenericClass<T> where T : new() { }  // T must provide a parameterless constructor, cannot be abstract\n\n// multiple constraints\npublic class GenericClass<T1, T2>\n    where T1: Interface\n    where T2: Interface1, Interface2\n{ }\n\n// generic methods constraints\npublic T GenericMethod<T>() where T : class?\n{\n    // code here\n    return <expr>;\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#inheritance","title":"Inheritance","text":"

Classes support only single inheritance. Interfaces offer a form of multiple inheritance. Value types do not support inheritance at all. One reason for this is that value types are not normally used by reference, which removes one of the main benefits of inheritance: runtime polymorphism.

Since a derived class inherits everything the base class has\u2014all its fields, methods, and other members, both public and private\u2014an instance of the derived class can do anything an instance of the base could do.

Note: When deriving from a class, it's not possible to make the derived class more visible than its base. This restriction does not apply to interfaces. A public class is free to implement internal or private interfaces. However, it does apply to an interface's bases: a public interface cannot derive from an internal interface.

C#
class BaseClass\n{\n    public virtual Property { get; set; }\n\n    // to be overridden method must be ABSTRACT or VIRTUAL\n    public virtual Type Method() { }\n}\n\n// the base class is ALWAYS the first after the colons\nclass ChildClass : BaseClass, Interface, Interface<Type>\n{\n    public override Type Method() { }  // override base's method (same signature)\n    public override DerivedType Method() { }  // override base's method, can return more specific type (covariant return type, C# 9)\n    public new Type Method() {}  // hide base's method and prevent name conflict warning (hiding method can change signature)\n\n    base.Method();  // call base method\n    type Interface.Method() { }  // explicit implementation of an interface member (resolve name conflict between interfaces)\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#downcasting","title":"Downcasting","text":"

Downcasting is the conversion from a base class type to one of it's derived types.

C#
Base b;\nvar d = (Derived) b;  // explicit casting (if conversion fails throws InvalidCastException)\nvar d = b as Derived;  // as operator (if conversion fails AS will return NULL)\nif(b is Derived d) {}  // type pattern, d contains converted obj (if conversion fails IS returns FALSE)\nif(b is Derived) {}  // simple type pattern (if conversion fails IS returns FALSE)\n
"},{"location":"languages/dotnet/csharp/csharp.html#inheritance-constructors","title":"Inheritance & Constructors","text":"

All of a base class's constructors are available to a derived type, but they can be invoked only by constructors in the derived class. All constructors are required to invoke a constructor on their base class, and if it's not specified which to invoke, the compiler invokes the base's zero-argument constructor. If the base has not a zero-argument constructor the compilation will cause an error. It's possible to invoke a base constructor explicitly to avoid this error.

Initialization order:

  1. Derived class field initializers
  2. Base class field initializers
  3. Base class constructor
  4. Derived class constructor
C#
public class Base\n{\n    public Base(Type param) {}\n}\n\npublic class Derived\n{\n    public Derived() : base(value) {}  // invoke base constructor explicitly passing a fixed value (base has no zero-arg constructor)\n    public Derived(Type param) : base(param) {}  // invoke base constructor explicitly\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#generics-inheritance","title":"Generics Inheritance","text":"

If you derive from a generic class, you must supply the type arguments it requires. You must provide concrete types unless your derived type is generic, in which case it can use its own type parameters as arguments.

C#
public class GenericBase1<T>\n{\n    public T Item { get; set; }\n}\n\npublic class GenericBase2<TKey, TValue>\n{\n    public TKey Key { get; set; }\n    public TValue Value { get; set; }\n}\n\npublic class NonGenericDerived : GenericBase1<Type> {}  // derived is not generic, must use concrete type for base class\npublic class GenericDerived<T> : GenericBase1<T> {}  // derived is generic, can use it's generic type\npublic class MixedDerived<T> : GenericBase2<T, Type>  // derived is generic but base has two types, can use it's generic type but\n

It's allowed to use derived type as a type argument to the base class. And it's also possible to specify a constraint on a type argument requiring it to derive from the derived type.

C#
public class Derived : base<Derived> {}\npublic class Derived<T> where T : Derived<T>\n
"},{"location":"languages/dotnet/csharp/csharp.html#covariance-contravariance-only-for-interfaces","title":"Covariance & Contravariance (only for interfaces)","text":"

The theory behind covariance and contravariance in C#

Covariance and Contravariance are terms that refer to the ability to use a more derived type (more specific) or a less derived type (less specific) than originally specified. Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types.

Note: annotate generic type parameters with out and in annotations to specify whether they should behave covariantly or contravariantly.

C#
public class Base {};\npublic class Derived : Base {}\n\n// COVARIANCE (supply more specific type)\n// method is \"read only\" since it does not modify its argument\n// IEnumerable is covariant (has out parameter) since only \"provides\" objects\nvoid PrintBase(IEnumerable<Base> bases)\n{\n    foreach(Base base in bases)\n    {\n        Console.WritLine(base);\n    }\n}\n\nIEnumerable<Derived> derivedItems = new Derived[] {...};  // array is enumerable of Derived objects\nMethod(derivedItems);  // valid since Derived objects are also Base objects and operation is read only\n\n\n// CONTRAVARIANCE (supply less specific type)\n// IComparer is contravariant (has in parameter) since \"takes in\" objects\nvoid CompareDerived(IComparer<Derived> comparer)\n{\n    var d1 = new Derived();\n    var d2 = new Derived();\n    if(comparer.Compare(d1, d2)) { /* some action */ }\n}\n\nIComparator<Base> baseComparator = new BaseComparator();\nCompareDerived(baseComparator);  // valid since baseComparator can compare Base objects and thus can compare Derived objects\n
"},{"location":"languages/dotnet/csharp/csharp.html#delegates","title":"Delegates","text":"

A delegate is a type that represents a reference to a method with a particular parameter list and return type. Delegates are used to pass methods as arguments to other methods. This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.

Any method from any accessible class or struct that matches the delegate type can be assigned to the delegate. The method can be either static or an instance method. This makes it possible to programmatically change method calls, and also plug new code into existing classes.

C#
// delegate definition\npublic delegate Type Delegate(Type param, ...);  // can take any method with specified type params and return type\npublic delegate Type Delegate<T>(T param);  // generic delegate\n\n// delegate creation\nvar delegate = new Delegate<Type>(Method);  // explicit creation, useful when compiler cannot infer delegate type\nDelegate<Type> delegate = Method;  // implicit creation\n
"},{"location":"languages/dotnet/csharp/csharp.html#multicast-delegates","title":"Multicast Delegates","text":"

Multicast Delegates are delegates that can have more than one element in their invocation list.

C#
Delegate<Type> multicastDelegate = Method1 + Method2 + ...;  // multicast delegate creation\nmulticastDelegate += Method;  // add method to delegate\nmulticastDelegate -= Method;  // remove method from delegate\n

Note: Delegate removal behaves in a potentially surprising way if the delegate removed refers to multiple methods. Subtraction of a multicast delegate succeeds only if the delegate from which subtract contains all of the methods in the delegate being subtracted sequentially and in the same order.

"},{"location":"languages/dotnet/csharp/csharp.html#delegate-invocation","title":"Delegate Invocation","text":"

Invoking a delegate with a single target method works as though the code had called the target method in the conventional way. Invoking a multicast delegate is just like calling each of its target methods in turn.

C#
Delegate<Type> delegate = Method;\n\ndelegate(args);  // use delegate as standard method\ndelegate.DynamicInvoke(argsArray); // Dynamically invokes the method represented by the current delegate.\n\nmulticastDelegate.GetInvocationList();  // list of methods called by the delegate\n
"},{"location":"languages/dotnet/csharp/csharp.html#common-delegate-types","title":"Common Delegate Types","text":"

Note: Each delegate has an overload taking from zero to 16 arguments;

C#
public delegate void Action<in T1, ...>(T1 arg1, ...);\npublic delegate TResult Func<in T1, ..., out TResult>(T1 arg1, ...);\npublic delegate bool Predicate<in T1, ...>(T1 arg1, ...);\n
"},{"location":"languages/dotnet/csharp/csharp.html#type-compatibility","title":"Type Compatibility","text":"

Delegate types do not derive from one another. Any delegate type defined in C# will derive directly from MulticastDelegate. However, the type system supports certain implicit reference conversions for generic delegate types through covariance and contravariance. The rules are very similar to those for interfaces.

"},{"location":"languages/dotnet/csharp/csharp.html#anonymous-functions-lambda-expressions","title":"Anonymous Functions (Lambda Expressions)","text":"

Delegates without explicit separated method.

C#
// lambda variations\nDelegate<Type> lambda = () => <expr>;\nDelegate<Type> lambda = input => <expr>;\nDelegate<Type> lambda = (input) => <expr>;\nDelegate<Type> lambda = (Type input) => <expr>;\nDelegate<Type> lambda = input => { return <expr>; };\nDelegate<Type> lambda = (input) => { return <expr>; };\nDelegate<Type> lambda = (Type input) => { return <expr>; };\nDelegate<Type> lambda = (Type input = default) => { return <expr>; };  // lambda default parameter\n\n// static modifier prevents unintentional capture of local variables or instance state by the lambda\nDelegate<Type> lambda = (static Type input) => <expr>;\n\nType variable = delegate { <expression>; };  // ignore arguments of the method passed to the delegate\n\n// lambda type inference\nvar f = Console.WriteLine;\nvar f = x => x;  // inferring the return type\nvar f = (string x) => x;  // inferring the signature\nvar f = [Required] x => x;  // adding attributes on parameters\nvar f = [Required] (int x) => x;\nvar f = [return: Required] static x => x;  // adding attribute for a return type\nvar f = Type () => default;  // explicit return type\nvar f = ref int (ref int x) => ref x;  // using ref on structs\nvar f = int (x) => x;  // explicitly specifying the return type of an implicit input\nvar f = static void (_) => Console.Write(\"Help\");\n
"},{"location":"languages/dotnet/csharp/csharp.html#events","title":"Events","text":"

Structs and classes can declare events. This kind of member enables a type to provide notifications when interesting things happen, using a subscription-based model.

The class who raises events is called Publisher, and the class who receives the notification is called Subscriber. There can be multiple subscribers of a single event. 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.

C#
public delegate void EventDelegate(object sender, CustomEventArgs args);  // called on event trigger\n\npublic class Publisher\n{\n    public event EventDelegate Event;\n\n    // A derived class should always call the On<EventName> method of the base class to ensure that registered delegates receive the event.\n    public virtual void OnEvent(Type param)\n    {\n        Event?.Invoke(param);\n    }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#registering-event-handlers","title":"Registering Event Handlers","text":"C#
public class Subscriber\n{\n    Publisher publisher = new Publisher();\n\n    public Subscriber()\n    {\n        publisher.OnEvent += Handler;  // register handler (+= syntax)\n    }\n\n    // event handler, matches the signature of the Event delegate.\n    public Type Handler() { /* act */ }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#built-in-eventhandler-delegate","title":"Built-In EventHandler Delegate","text":"

.NET includes built-in delegate types EventHandler and EventHandler<TEventArgs> for the most common events. Typically, any event should include two parameters: the source of the event and event data. The EventHandler delegate is used for all events that do not include event data, the EventHandler<TEventArgs> delegate is used for events that include data to be sent to handlers.

C#
public class Publisher\n{\n    public event EventHandler Event;\n\n    public virtual void OnEvent(EventArgs e)\n    {\n        Event?.Invoke(this, e);\n    }\n}\n\npublic class Subscriber\n{\n    Publisher publisher = new Publisher();\n\n    public Subscriber()\n    {\n        publisher.OnEvent += Handler;  // register handler (+= syntax)\n    }\n\n    public Type Handler(object sender, EventArgs e) { /* act */ }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#custom-event-args","title":"Custom Event Args","text":"C#
public class CustomEventArgs : EventArgs { }\n\npublic class Publisher\n{\n    public event EventHandler<CustomEventArgs> Event;\n\n    public virtual void OnEvent(CustomEventArgs e)\n    {\n        Event?.Invoke(this, e);\n    }\n}\n\npublic class Subscriber\n{\n    Publisher publisher = new Publisher();\n\n    public Subscriber()\n    {\n        publisher.OnEvent += Handler;  // register handler (+= syntax)\n    }\n\n    public Type Handler(object sender, CustomEventArgs e) { /* act */ }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#assemblies","title":"Assemblies","text":"

In .NET the proper term for a software component is an assembly, and it is typically a .dll or .exe file. Occasionally, an assembly will be split into multiple files, but even then it is an indivisible unit of deployment: it has to be wholly available to the runtime, or not at all.

Assemblies are an important aspect of the type system, because each type is identified not just by its name and namespace, but also by its containing assembly. Assemblies provide a kind of encapsulation that operates at a larger scale than individual types, thanks to the internal accessibility specifier, which works at the assembly level.

The runtime provides an assembly loader, which automatically finds and loads the assemblies a program needs. To ensure that the loader can find the right components, assemblies have structured names that include version information, and they can optionally contain a globally unique element to prevent ambiguity.

"},{"location":"languages/dotnet/csharp/csharp.html#anatomy-of-an-assembly","title":"Anatomy of an Assembly","text":"

Assemblies use the Win32 Portable Executable (PE) file format, the same format that executables (EXEs) and dynamic link libraries (DLLs) have always used in \"modern\" (since NT) versions of Windows.

The C# compiler produces an assembly as its output, with an extension of either .dll or .exe. Tools that understand the PE file format will recognize a .NET assembly as a valid, but rather dull, PE file. The CLR essentially uses PE files as containers for a .NET-specific data format, so to classic Win32 tools, a C# DLL will not appear to export any APIs.

With .NET Core 3.0 or later, .NET assemblies won't be built with an extension of .exe. Even project types that produce directly runnable outputs (such as console or WPF applications) produce a .dll as their primary output. They also generate an executable file too, but it's not a .NET assembly. It's just a bootstrapper that starts the runtime and then loads and executes your application's main assembly.

Note: C# compiles to a binary intermediate language (IL), which is not directly executable. The normal Windows mechanisms for loading and running the code in an executable or DLL won't work with IL, because that can run only with the help of the CLR.

"},{"location":"languages/dotnet/csharp/csharp.html#net-metadata","title":".NET MEtadata","text":"

As well as containing the compiled IL, an assembly contains metadata, which provides a full description of all of the types it defines, whether public or private. The CLR needs to have complete knowledge of all the types that the code uses to be able to make sense of the IL and turn it into running code, the binary format for IL frequently refers to the containing assembly's metadata and is meaningless without it.

"},{"location":"languages/dotnet/csharp/csharp.html#resources","title":"Resources","text":"

It's possible to embed binary resources in a DLL alongside the code and metadata. To embed a file select \"Embedded Resource\" as it's Build Action in the file properties. This compiles a copy of the file into the assembly.

To extract the resource at runtime use the Assembly class's GetManifestResourceStream method which is par of the Reflection API.

"},{"location":"languages/dotnet/csharp/csharp.html#multifile-assembly","title":"Multifile Assembly","text":"

.NET Framework allowed an assembly to span multiple files. It was possible to split the code and metadata across multiple modules, and it was also possible for some binary streams that are logically embedded in an assembly to be put in separate files. This feature was rarely used, and .NET Core does not support it. However, it's necessary to know about it because some of its consequences persist. In particular, parts of the design of the Reflection API make no sense unless this feature is known.

With a multifile assembly, there's always one master file that represents the assembly. This will be a PE file, and it contains a particular element of the metadata called the assembly manifest. This is not to be confused with the Win32-style manifest that most executables contain. The assembly manifest is just a description of what's in the assembly, including a list of any external modules or other external files; in a multimodule assembly, the manifest describes which types are defined in which files.

"},{"location":"languages/dotnet/csharp/csharp.html#assembly-resolution","title":"Assembly Resolution","text":"

When the runtime needs to load an assembly, it goes through a process called assembly resolution.

.NET Core supports two deployment options for applications:

"},{"location":"languages/dotnet/csharp/csharp.html#self-contained-deployment","title":"Self-Contained Deployment","text":"

When publishing a self-contained application, it includes a complete copy of .NET Core, the whole of the CLR and all the built-in assemblies. When building this way, assembly resolution is pretty straightforward because everything ends up in one folder.

There are two main advantages to self-contained deployment:

With self-contained deployment, unless the application directs the CLR to look elsewhere everything will load from the application folder, including all assemblies built into .NET.

"},{"location":"languages/dotnet/csharp/csharp.html#framework-dependent-deployment","title":"Framework-Dependent Deployment","text":"

The default build behavior for applications is to create a framework-dependent executable. In this case, the code relies on a suitable version of .NET Core already being installed on the machine. Framework-dependent applications necessarily use a more complex resolution mechanism than self-contained ones.

When such an application starts up it will first determine exactly which version of .NET Core to run. The chosen runtime version selects not just the CLR, but also the assemblies making up the parts of the class library built into .NET.

"},{"location":"languages/dotnet/csharp/csharp.html#assembly-names","title":"Assembly Names","text":"

Assembly names are structured. They always include a simple name, which is the name by which normally refer to the DLL. This is usually the same as the filename but without the extension. It doesn't technically have to be but the assembly resolution mechanism assumes that it is.

Assembly names always include a version number. There are also some optional components, including the public key token, a string of hexadecimal digits, which is required to have a unique name.

"},{"location":"languages/dotnet/csharp/csharp.html#strong-names","title":"Strong Names","text":"

If an assembly's name includes a public key token, it is said to be a strong name. Microsoft advises that any .NET component that is published for shared use (e.g: made available via NuGet) should have a strong name.

As the terminology suggests, an assembly name's public key token has a connection with cryptography. It is the hexadecimal representation of a 64-bit hash of a public key. Strongly named assemblies are required to contain a copy of the full public key from which the hash was generated. The assembly file format also provides space fora digital signature, generated with the corresponding private key.

The uniqueness of a strong name relies on the fact that key generation systems use cryptographically secure random-number generators, and the chances of two people generating two key pairs with the same public key token are vanishingly small. The assurance that the assembly has ot been tampered with comes from the fact that a strongly named assembly must be signed, and only someone in possession of the private key can generate a valid signature. Any attempt to modify the assembly after signing it will invalidate the signature.

"},{"location":"languages/dotnet/csharp/csharp.html#version","title":"Version","text":"

All assembly names include a four-part version number: major.minor.build.revision. However, there's no particular significance to any of these. The binary format that IL uses for assembly names and references limits the range of these numbers, each part must fit in a 16-bit unsigned integer (a ushort), and the highest allowable value in a version part is actually one less than the maximum value that would fit, making the highest legal version number 65534.65534.65534.65534.

As far as the CLR is concerned, there's really only one interesting thing you can do with a version number, which is to compare it with some other version number, either they match or one is higher than the other.

The build system tells the compiler which version number to use for the assembly name via an assembly-level attribute.

Note: NuGet packages also have version numbers, and these do not need to be connected in any way to assembly versions. NuGet does treat the components of a package version number as having particular significance: it has adopted the widely used semantic versioning rules.

"},{"location":"languages/dotnet/csharp/csharp.html#culture","title":"Culture","text":"

All assembly names include a culture component. This is not optional, although the most common value for this is the default neutral, indicating that the assembly contains no culture-specific code or data.

The culture is usually set to something else only on assemblies that contain culture-specific resources. The culture of an assembly's name is designed to support localization of resources such as images and strings.

"},{"location":"languages/dotnet/csharp/csharp.html#reflection","title":"Reflection","text":"

The CLR knows a great deal about the types the programs define and use. It requires all assemblies to provide detailed metadata, describing each member of every type, including private implementation details. It relies on this information to perform critical functions, such as JIT compilation and garbage collection. However, it does not keep this knowledge to itself.

The reflection API grants access to this detailed type information, so the code can discover everything that the runtime can see.

Reflection is particularly useful in extensible frameworks, because they can use it to adapt their behavior at runtime based on the structure of the code.

The reflection API defines various classes in the System.Reflection namespace. These classes have a structural relationship that mirrors the way that assemblies and the type system work.

"},{"location":"languages/dotnet/csharp/csharp.html#assembly","title":"Assembly","text":"

The Assembly class defines three context-sensitive static methods that each return an Assembly. The GetEntryAssembly method returns the object representing the EXE file containing the program's Main method. The GetExecutingAssembly method returns the assembly that contains the method from which it has been called it. GetCallingAssembly walks up the stack by one level, and returns the assembly containing the code that called the method that called GetCallingAssembly.

To inspect an assembly info use the ReflectionOnlyLoadFrom (or ReflectionOnlyLoad) method of the Assembly class. This loads the assembly in such a way that it's possible to inspect its type information, but no code in the assembly will execute, nor will any assemblies it depends on be loaded automatically.

"},{"location":"languages/dotnet/csharp/csharp.html#attributes","title":"Attributes","text":"

In .NET, it's possible to annotate components, types, and their members with attributes. An attribute's purpose is to control or modify the behavior of a framework, a tool, the compiler, or the CLR.

Attributes are passive containers of information that do nothing on their own.

"},{"location":"languages/dotnet/csharp/csharp.html#applying-attributes","title":"Applying Attributes","text":"

To avoid having to introduce an extra set of concepts into the type system, .NET models attributes as instances of .NET types. To be used as an attribute, a type must derive from the System.Attribute class, but it can otherwise be entirely ordinary.

It's possible to pass arguments to the attribute constructor in the annotation.

C#
[AttName]  // simple attribute\n\n[AttName(value)]  // valorize private fields (through the constructor)\n[AttrName(Name = value)]  // valorize public properties or fields (no constructor needed)\n

Note: The real name of an attribute ends with \"Attribute\" ([AttrName] refers to the AttrNameAttribute class)

"},{"location":"languages/dotnet/csharp/csharp.html#multiple-attributes","title":"Multiple Attributes","text":"C#
[Attribute1]\n[Attribute2]\n\n[Attribute1, Attribute2]\n
"},{"location":"languages/dotnet/csharp/csharp.html#defining-custom-attribute-types","title":"Defining Custom Attribute Types","text":"C#
// specify what the attribute can be applied to (enforced by c# compiler)\n[AttributeUsage(AttributeTargets.<TargetType>)]\npublic class CustomAttribute : Attribute\n{\n    // properties to hold information\n\n    // constructor (used to valorize private fields)\n}\n

NOTE: From C# 11 attributes can be generic and have type constraints

"},{"location":"languages/dotnet/csharp/csharp.html#retrieving-attributes","title":"Retrieving Attributes","text":"

It's possible to discover which attributes have been applied through the reflection API. The various targets of attribute have a reflection type representing them (MethodInfo, PropertyInfo, ...) which all implement the interface ICustomAttributeProvider.

C#
public interface ICustomAttributeProvider\n{\n    object[] GetCustomAttributes(bool inherit);\n    object[] GetCustomAttributes(Type attributeType, bool inherit);\n    bool IsDefined(Type attribueType, bool inherit);\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#files-streams","title":"Files & Streams","text":"

A .NET stream is simply a sequence of bytes. That makes a stream a useful abstraction for many commonly encountered features such as a file on disk, or the body of an HTTP response. A console application uses streams to represent its input and output.

The Stream class is defined in the System.IO namespace. It is an abstract base class, with concrete derived types such as FileStream or GZipStream representing particular kinds of streams.

C#
// The most important members of Stream\npublic abstract int Read(byte[] buffer, int offset, int count);\npublic abstract void Write(byte[] buffer, int offset, int count);\npublic abstract long Position { get; set; }\n

Some streams are read-only. For example, if input stream for a console app represents the keyboard or the output of some other program, there's no meaningful way for the program to write to that stream. Some streams are write-only, such as the output stream of a console application. If Read is called on a write-only stream or Write on a read-only one, these methods throw a NotSupportedException.

Both Read and Write take a byte[] array as their first argument, and these methods copy data into or out of that array, respectively. The offset and count arguments that follow indicate the array element at which to start, and the number of bytes to read or write. There are no arguments to specify the offset within the stream at which to read or write. This is managed by the Position property. This starts at zero, but at each read or write, the position advances by the number of bytes processed.

The Read method returns an int. This tells how many bytes were read from the stream, the method does not guarantee to provide the amount of data requested. The reason Read is slightly tricky is that some streams are live, representing a source of information that produces data gradually as the program runs.

Note: If asked for more than one byte at a time, a Stream is always free to return less data than requested from Read for any reason. Never presume that a call to Read returned as much data as it could.

"},{"location":"languages/dotnet/csharp/csharp.html#position-seeking","title":"Position & Seeking","text":"

Streams automatically update their current position each time a read or write operation is completed. The Position property can be set to move to the desired location. This is not guaranteed to work because it's not always possible to support it. Some streams will throw NotSupportedException when trying to set the Position property.

Stream also defines a Seek method, this allows to specify the position required relative to the stream's current position. Passing SeekOrigin.Current as second argument will set the position by adding the first argument to the current position.

C#
public abstract long Seek(long offset, SeekOrigin origin);  // offset can be negative\n
"},{"location":"languages/dotnet/csharp/csharp.html#flushing","title":"Flushing","text":"

Writing data to a Stream does not necessarily cause the data to reach its destination immediately. When a call to Write returns, all that is known is that it has copied the data somewhere; but that might be a buffer in memory, not the final target.

The Stream class therefore offers a Flush method. This tells the stream that it has to do whatever work is required to ensure that any buffered data is written to its target, even if that means making suboptimal use of the buffer.

A stream automatically flushes its contents when calling Dispose. Flush only when it's needed to keep a stream open after writing out buffered data. It is particularly important if there will be extended periods during which the stream is open but inactive.

Note: When using a FileStream, the Flush method does not necessarily guarantee that the data being flushed has made it to disk yet. It merely makes the stream pass the data to the OS. Before calling Flush, the OS hasn't even seen the data, so if the process terminates suddenly, the data would be lost. After Flush has returned, the OS has everything the code has written, so the process could be terminated without loss of data. However, the OS may perform additional buffering of its own, so if the power fails before the OS gets around to writing everything to disk, the data will still be lost.

To guarantee that data has been written persistently (rather than merely ensuring that it has been handed it to the OS), use either the WriteThrough flag, or call the Flush overload that takes a bool, passing true to force flushing to disk.

"},{"location":"languages/dotnet/csharp/csharp.html#streamreader-streamwriter-text-files","title":"StreamReader & StreamWriter (Text Files)","text":"

The most useful concrete text-oriented streams types are StreamReader and StreamWriter, which wrap a Stream object. It's possible to constructing them by passing a Stream as a constructor argument, or a string containing the path of a file, in which case they will automatically construct a FileStream and then wrap that.

Encoding

C#
// Will detect encoding from stream contents\nStreamReader file = new StreamReader(string path);\nStreamReader file = new StreamReader(string path, System.Text.Encoding encoding);  // encoding is System.Text.Encoding\n\n// Default Encoding: UTF-8 w/o BOM (Byte Order Mark)\nStreamWriter file = new StreamWriter(string path);\nStreamWriter file = new StreamWriter(string path, bool boolean);  // true to append data to the file; false to overwrite the file.\nStreamReader file = new StreamReader(string path, System.Text.Encoding encoding);  // encoding is System.Text.Encoding\nStreamReader file = new StreamReader(string path, bool append, System.Text.Encoding encoding);  // encoding is System.Text.Encoding\n\n// USAGE\ntry\n{\n    using (StreamReader file = new StreamReader(path))  // stream to read\n    {\n        while(!file.EndOfStream)  // keep reading until the end op file\n        {\n            file.ReadLine();  // read a whole line from the file\n        }\n    }\n\n    using (StreamWriter file = new StreamWriter(path))  // stream to write\n    {\n        file.write();  // write to file\n    }\n}\ncatch (Exception e)\n{\n    // handle exception\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#stringreader-stringwriter","title":"StringReader & StringWriter","text":"

The StringReader and StringWriter classes serve a similar purpose to MemoryStream: they are useful when working with an API that requires either a TextReader or TextWriter (abstract text streams), but you want to work entirely in memory. Whereas MemoryStream presents a Stream API on top of a byte[] array, StringReader wraps a string as a TextReader, while StringWriter presents a TextWriter API on top of a StringBuilder.

"},{"location":"languages/dotnet/csharp/csharp.html#files-directories","title":"Files & Directories","text":""},{"location":"languages/dotnet/csharp/csharp.html#filestream-class-binary-files","title":"FileStream Class (Binary Files)","text":"

The FileStream class derives from Stream and represents a file from the filesystem.

It' common to use the constructors in which the FileStream uses OS APIs to create the file handle. It's possible to provide varying levels of detail on how this si to be done. At a minimum the file's path and a value from the FileMode enumeration must be provided.

C#
// overloaded FileStream Constructors\npublic FileStream(string path, FileMode mode);\npublic FileStream(string path, FileMode mode, FileAccess access);\npublic FileStream(string path, FileMode mode, FileAccess access, FileShare share);\npublic FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize);\npublic FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync);\npublic FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options);\n
FileMode Behavior if file exists Behavior if file does not exist CreateNew Throws IOException Creates new file Create Replaces existing file Creates new file Open Opens existing file Throws FileNotFoundException OpenOrCreate Opens existing file Creates new file Truncate Replaces existing file Throws FileNotFoundException Append Opens existing file, setting Position to end of file Creates new file

FileAccess Enumeration:

FileShare Enumeration:

FileOptions Enumeration:

Note: The WriteThrough flag will ensure that when the stream is disposed or flushed, all the data written will have been delivered to the drive, but the drive will not necessarily have written that data persistently (drives can defer writing for performance), so data loss id still possible if the power fails.

C#
// object to read or write to a file (file can be binary)\n{\n    using(FileStream fstream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))\n    {\n        // operations on file stream\n    }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#file-class","title":"File Class","text":"

The static File class provides methods for performing various operations on files.

C#
File.Create(string path);  // Return Read/Write FileStream to file\nFile.Open(string path, System.IO.FileMode mode);  // Open a FileStream on the specified path with read/write access with no sharing.\nFile.Open(string path, System.IO.FileMode mode, System.IO.FileAccess access);  // Opens a FileStream on the specified path, with the specified mode and access with no sharing.\nFile.Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share);\nFile.OpenRead(string path);  // Open an existing file for reading, returns a FileStream\nFile.OpenText(string path);  // Open an existing UTF-8 encoded text file for reading, returns a StreamReader\nFile.OpenWrite(string path);  // Open an existing file for writing, returns a FileStream\n\nFile.Delete(string path);  // Delete the specified file\nFile.Move(string sourceFileName, string destFileName, bool overwrite);  // Move specified file to a new location (can specify a new filename and to overwrite the destination file if it already exists)\nFile.Exists(string path);  // Whether the specified file exists.\n\nFile.GetCreationTime(string path);  // Return DateTime set to the creation date and time for the specified file\nFile.GetLastAccessTime(string path);  // Return DateTime set to the date and time that the specified file was last accessed\nFile.GetLastWriteTime(string path);  // Return DateTime set to the date and time that the specified file was last written to\nFile.GetAttributes(string path);  // Return FileAttributes of the file\n\nFile.Encrypt(string path);  // Encrypt a file so that only the account used to encrypt the file can decrypt it.\nFile.Decrypt(string path);  // Decrypt a file that was encrypted by the current account using the Encrypt() method.\n\nFile.ReadAllText(string path);  // Return a string containing all the text in the file\nFile.ReadAllLines(string path);  // Returns a string[] containing all lines of the file\nFile.ReadLines(string path); // Returns IEnumerable<string> containing all the text in the file\nFile.ReadAllBytes(string path);  // Returns a byte[] containing the contents of the file.\n\nFile.WriteAllLines(string path, IEnumerable<string> contents);  // writes a collection of strings to the file\nFile.WriteAllLines(string path, string[] contents);  // writes a collection of strings to the file\n\nFile.AppendAllText(string path, string contents);  // appends the specified string to the file\nFile.AppendAllLines(string path, IEnumerable<string> contents);  // appends a collection of strings to the file\n\n// Replace the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file.\nFile.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);\n
"},{"location":"languages/dotnet/csharp/csharp.html#directory-class","title":"Directory Class","text":"

Exposes static methods for creating, moving, and enumerating through directories and subdirectories.

C#
Directory.CreateDirectory(string path);  // Create directory as specified\nDirectory.Delete(string path);  // Delete an empty directory from a specified path (dir must be writable)\nDirectory.Delete(string path, bool recursive);  // Delete the specified directory and, if indicated, any subdirectories and files in the directory\nDirectory.Move(string sourceDirName, string destDirName);  // Move a file or a directory and its contents to a new location\nDirectory.Exists (string path);  // Whether the given path refers to an existing directory on disk\n\nDirectory.GetLogicalDrives();  // string[] of names of the logical drives on the computer in the form \"<drive letter>:\\\"\nDirectory.GetParent(string path);  // DirectoryInfo of parent directory of the specified path, including both absolute and relative paths\nDirectory.GetCurrentDirectory();  // string of current working directory of the application\nDirectory.SetCurrentDirectory(string path);  // Set the application's current working directory to the specified directory\n\nDirectory.GetCreationTime(string path);  // DateTime set to the creation date and time for the specified directory\nDirectory.GetLastAccessTime(string path);  // DateTime set to the date and time the specified file or directory was last accessed\nDirectory.GetLastWriteTime(string path);  // DateTime set to the date and time the specified file or directory was last written to\n\nDirectory.EnumerateDirectories (string path, string searchPattern, SearchOption searchOption);  // IEnumerable<string> of directory full names that match a search pattern in a specified path\nDirectory.GetDirectories (string path, string searchPattern, System.IO.SearchOption searchOption);  // string[] of directory full names that match a search pattern in a specified path\n\nDirectory.EnumerateFiles(string path, string searchPattern, SearchOption searchOption);  // IEnumerable<string> of full file names that match a search pattern in a specified path\nDirectory.GetFiles(string path, string searchPattern, SearchOption searchOption);  // string[] of full file names that match a search pattern in a specified path\n\nDirectory.EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption);  // IEnumerable<string> array of file names and directory names that match a search pattern in a specified path\nDirectory.GetFileSystemEntries (string path, string searchPattern, SearchOption searchOption);  // string[] array of file names and directory names that match a search pattern in a specified path\n
"},{"location":"languages/dotnet/csharp/csharp.html#path-class","title":"Path Class","text":"C#
Combine(string path1, string path2);  // Combine two strings into a path\nCombine(string[] paths);  // Combine strings into a path\n\nGetFullPath(string path);  // absolute path for the specified path string\nGetFullPath(string path, string basePath);  // absolute path from a relative path and a fully qualified base path\nGetRelativePath (string relativeTo, string path);  // relative path from one path to another\nGetPathRoot (string path);  // Get the root directory information from the path contained in the specified string\nGetDirectoryName (string path);  // directory information for the specified path string\n\nGetExtension (string path);  // extension (including the period \".\") of the specified path string\nGetFileName (string path);  // file name and extension of the specified path string\nGetFileNameWithoutExtension (string path);  // file name of the specified path string without the extension\n\nHasExtension (string path);  // whether a path includes a file name extension\nIsPathFullyQualified (string path);  // whether the specified file path is fixed to a specific drive or UNC path\nIsPathRooted (string path);  // whether the specified path string contains a root\n\nEndsInDirectorySeparator (string path);  // true if the path ends in a directory separator; otherwise, false\nTrimEndingDirectorySeparator (string path);  // Trim one trailing directory separator beyond the root of the specified path\n\nGetInvalidFileNameChar();  // char[] containing the characters that are not allowed in file names\nGetInvalidPathChars();  // char[] containing the characters that are not allowed in path names\n\nGetTempPath();  // path of the current user's temporary folder\nGetTempFileName();  // Create a uniquely named, zero-byte temporary file on disk and returns the full path of that file\nGetRandomFileName();  // random folder name or file name\n\n// get full path from relative\nstring path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @\"relative_path.ext\");  // path to a file in the project directory\n\n// get special folder location\nstring appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n
"},{"location":"languages/dotnet/csharp/csharp.html#fileinfo-directoryinfo-filesysteminfo","title":"FileInfo, DirectoryInfo & FileSystemInfo","text":"

Classes to hold multiple info about a file or directory. If some property changes using the method Refresh() will update the data.

"},{"location":"languages/dotnet/csharp/csharp.html#clr-serialization","title":"CLR Serialization","text":"

Types are required to opt into CLR serialization. .NET defines a [Serializable] attribute that must be present before the CLR will serialize the type (class).

C#
[Serializable]\nclass Class { }\n

Serialization works directly with an object's fields. It uses reflection, which enables it to access all members, whether public or private.

Note: CLR Serialization produces binary streams in a .NET specific format

"},{"location":"languages/dotnet/csharp/csharp.html#datetime-timespan","title":"DateTime & TimeSpan","text":""},{"location":"languages/dotnet/csharp/csharp.html#timespan-struct","title":"TimeSpan Struct","text":"

Object that represents the difference between two dates

C#
TimeSpan Interval = new DateTime() - new DateTime()  // difference between dates\n\n// constructors\nTimeSpan(hours, minutes, seconds);  // all parameters are integers\nTimeSpan(days, hours, minutes, seconds);  // all parameters are integers\nTimeSpan(days, hours, minutes, seconds, milliseconds);  // all parameters are integers\n\n// from primitive types\nTimeSpan interval = TimeSpan.FromSeconds(seconds);\nTimeSpan interval = TimeSpan.FromMinutes(minutes);\nTimeSpan interval = TimeSpan.FromHours(hours);\nTimeSpan interval = TimeSpan.FromDays(days);\n
"},{"location":"languages/dotnet/csharp/csharp.html#memory-efficiency","title":"Memory Efficiency","text":"

The CLR is able to perform automatic memory management thanks to its garbage collector (GC). This comes at a price: when a CPU spends time on garbage collection, that stops it from getting on with more productive work. In many cases, this time will be small enough not to cause visible problems. However, when certain kinds of programs experience heavy load, GC costs can come to dominate the overall execution time.

C# 7.2 introduced various features that can enable dramatic reductions in the number of allocations. Fewer allocations means fewer blocks of memory for the GC to recover, so this translates directly to lower GC overhead. There is a price to pay, of course: these GC-efficient techniques add significant complication to the code.

"},{"location":"languages/dotnet/csharp/csharp.html#spant","title":"Span<T>","text":"

The System.Span<T> (a ref struct) value type represents a sequence of elements of type T stored contiguously in memory. Those elements can live inside an array, a string, a managed block of memory allocated in a stack frame, or unmanaged memory.

A Span<T> encapsulates three things: a pointer or reference to the containing memory (e.g., the string or array), the position of the data within that memory, and its length.

Access to a span contents is done like an and since a Span<T> knows its own length, its indexer checks that the index is in range, just as the built-in array type does.

C#
Span<int> numbers = stackalloc int[] { 1, 2, 3 };\nvar first = numbers[0];\n

Note: Normally, C# won\u2019t allow to use stackalloc outside of code marked as unsafe, since it allocates memory on the stack producing a pointer. However, the compiler makes an exception to this rule when assigning the pointer produced by a stackalloc expression directly into a span.

The fact that Span<T> and ReadOnlySpan<T> are both ref struct types ensures that a span cannot outlive its containing stack frame, guaranteeing that the stack frame on which the stack-allocated memory lives will not vanish while there are still outstanding references to it.

In addition to the array-like indexer and Length properties, Span<T> offers a few useful methods. The Clear and Fill methods provide convenient ways to initialize all the elements in a span either to the default value or a specific value. Obviously, these are not available on ReadOnlySpan<T>.

The Span<T> and ReadOnlySpan<T> types are both declared as ref struct. This means that not only are they value types, they are value types that can live only on the stack. So it's not possible to have fields with span types in a class, or any struct that is not also a ref struct.

This also imposes some potentially more surprising restrictions:

This restriction is necessary for .NET to be able to offer the combination of array-like performance, type safety, and the flexibility to work with multiple different containers.

Note: it's possible to use spans in local methods, and even declare a ref struct variable in the outer method and use it from the nested one, but with one restriction: it's not possible a delegate that refers to that local method, because this would cause the compiler to move shared variables into an object that lives on the heap.

"},{"location":"languages/dotnet/csharp/csharp.html#memoryt","title":"Memory<T>","text":"

The Memory<T> type and its counterpart, ReadOnlyMemory<T>, represent the same basic concept as Span<T> and ReadOnlySpan<T>: these types provide a uniform view over a contiguous sequence of elements of type T that could reside in an array, unmanaged memory, or, if the element type is char, a string. But unlike spans, these are not ref struct types, so they can be used anywhere. The downside is that this means they cannot offer the same high performance as spans.

It's possible to convert a Memory<T> to a Span<T>, and likewise a ReadOnlyMemory<T> to a ReadOnlySpan<T>. This makes these memory types useful when you want something span-like, but in a context where spans are not allowed.

"},{"location":"languages/dotnet/csharp/csharp.html#regular-expressions","title":"Regular Expressions","text":"

regex reference

C#
Match match = Regex.Match(string, pattern, regexOptions);\n\nmatch.Success;  // whether there was a match or not\n\nmatch.Groups[index];  // numbered capture group (first group is always whole match)\nmatch.Groups[name];  // named capture group\n\nmatch.Groups[index].Value;  // whole captured string\nmatch.Groups[index].Captures;  // list of strings in the matched group\nmatch.Groups[index].Index;  // position in the input string of the matched group\n
"},{"location":"languages/dotnet/csharp/csharp.html#unsafe-code-pointers","title":"Unsafe Code & Pointers","text":"

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 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.

C#
unsafe Type UnsafeMethod() { /* unsafe context */ }\n// or\nunsafe\n{\n    // Using fixed allows the address of pt members to be taken,\n    // and \"pins\" pt so that it is not relocated.\n    Point pt = new Point();\n    fixed (int* p = &pt.x)\n    {\n        *p = 1;\n    }\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#native-memory","title":"Native Memory","text":"C#
using System.Runtime.InteropServices;\n\nunsafe\n{\n    byte* buffer = (byte*)NativeMemory.Alloc(100);\n\n    NativeMemory.Free(buffer);\n}\n
"},{"location":"languages/dotnet/csharp/csharp.html#external-code","title":"External Code","text":"

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.

C#
[DllImport(\"avifil32.dll\")]\nprivate static extern void AVIFileInit();\n
"},{"location":"languages/dotnet/csharp/csharp.html#magic-methods","title":"Magic Methods","text":"

Methods needed to implement a behaviour which do not need an interface to work. The methods must be named appropriately and have the correct return type.

"},{"location":"languages/dotnet/csharp/csharp.html#enumerable","title":"Enumerable","text":"C#
public bool MoveNext(/* ... */);\npublic T Current { get; }\n
"},{"location":"languages/dotnet/csharp/csharp.html#awaitable","title":"Awaitable","text":"C#
public TaskAwaiter GetAwaiter(/* ... */);\n
"},{"location":"languages/dotnet/csharp/csharp.html#code-quality","title":"Code Quality","text":""},{"location":"languages/dotnet/csharp/csharp.html#code-analysis","title":"Code Analysis","text":"XML
<PropertyGroup>\n  <AnalisysMode>All</NugetAuditMode>\n</PropertyGroup>\n
Level Description None All rules are disabled. Can selectively opt in to individual rules to enable them. Default Default mode, where certain rules are enabled as build warnings, certain rules are enabled as options IDE suggestions, and the remainder are disabled. Minimum More aggressive mode than Default mode. Certain suggestions that are highly recommended for build enforcement are enabled as build warnings. Recommended More aggressive mode than Minimum mode, where more rules are enabled as build warnings. All All rules are enabled as build warnings. Can selectively opt out of individual rules to disable them."},{"location":"languages/dotnet/csharp/csharp.html#dependency-auditing","title":"Dependency Auditing","text":"XML
<PropertyGroup>\n  <!-- required -->\n  <NugetAuditMode>all|direct</NugetAuditMode>\n\n  <!-- suggested -->\n  <NugetAuditLevel>low|moderate|high|critical</NugetAuditLevel>\n\n  <!-- optional -->\n  <WarningsAsErrors>NU1901;NU1902;NU1903;NU1904</WarningAsErrors>\n</PropertyGroup>\n

The auditing of dependencies is done during the dotnet restore step. A description of the dependencies is checked against a report of known vulnerabilities on the GitHub Advisory Database.

Audit Mode:

"},{"location":"languages/dotnet/csharp/linq.html","title":"LINQ","text":""},{"location":"languages/dotnet/csharp/linq.html#linq-to-objects","title":"LINQ to Objects","text":"

The term LINQ to Objects refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML.

LINQ to Objects will be used when any IEnumerable<T> is specified as the source, unless a more specialized provider is available.

"},{"location":"languages/dotnet/csharp/linq.html#query-expressions","title":"Query Expressions","text":"

All query expressions are required to begin with a from clause, which specifies the source of the query. The final part of the query is a select (or group) clause. This determines the final output of the query and its system type.

C#
// query expression\nvar result = from item in enumerable select item;\n\n// where clause\nvar result = from item in enumerable where condition select item;\n\n// ordering\nvar result = from item in enumerable orderby item.property select item;  // ordered IEnumerable\n\n// let clause, assign expression to variable to avoid re-evaluation on each cycle\nvar result = from item in enumerable let tmp = <sub-expr> ...  // BEWARE: compiled code has a lot of overhead to satisfy let clause\n\n// grouping (difficult to re-implement to obtain better performance)\nvar result = from item in enumerable group item by item.property;  // returns IEnumerable<IGrouping<TKey,TElement>>\n
"},{"location":"languages/dotnet/csharp/linq.html#how-query-expressions-expand","title":"How Query Expressions Expand","text":"

The compiler converts all query expressions into one or more method calls. Once it has done that, the LINQ provider is selected through exactly the same mechanisms that C# uses for any other method call. The compiler does not have any built-in concept of what constitutes a LINQ provider.

C#
// expanded query expression\nvar result = Enumerable.Where(item => condition).Select(item => item);\n

The Where and Select methods are examples of LINQ operators. A LINQ operator is nothing more than a method that conforms to one of the standard patterns.

"},{"location":"languages/dotnet/csharp/linq.html#methods-on-enumerable-or-ienumerablet","title":"Methods on Enumerable or IEnumerable<T>","text":"C#
Enumerable.Range(int start, int end);  // IEnumerable<int> of values between start & end\n\nIEnumerable<TSource>.Select(Func<TSource, TResult> selector);  // map\nIEnumerable<TSource>.Where(Func<T, bool> predicate);  // filter\n\nIEnumerable<T>.FirstOrDefault();  // first element of IEnumerable or default(T) if empty\nIEnumerable<T>.FirstOrDefault(T default);  // specify returned default\nIEnumerable<T>.FirstOrDefault(Func<T, bool> predicate);  // first element to match predicate or default(T)\n// same for LastOrDefault & SingleOrDefault\n\nIEnumerable<T>.Chunk(size);  // chunk an enumerable into slices of a fixed size\n\n// T must implement IComparable<T>\nIEnumerable<T>.Max();\nIEnumerable<T>.Min();\n\n// allow finding maximal or minimal elements using a key selector\nIEnumerable<TSource>.MaxBy(Func<TSource, TResult> selector);\nIEnumerable<TSource>.MinBy(Func<TSource, TResult> selector);\n\nIEnumerable<T>.All(Func<T, bool> predicate);  // check if condition is true for all elements\nIEnumerable<T>.Any(Func<T, bool> predicate);  // check if condition is true for at least one element\n\nIEnumerable<T>.Concat(IEnumerable<T> enumerable);\n\n// Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.\nIEnumerable<TFirst>.Zip(IEnumerable<TSecond> enumerable, Func<TFirst, TSecond, TResult> func);\nIEnumerable<TFirst>.Zip(IEnumerable<TSecond> enumerable); // Produces a sequence of tuples with elements from the two specified sequences.\n

Note: Enumerable provides a set of static methods for querying objects that implement IEnumerable<T>. Most methods are extensions of IEnumerable<T>

C#
Enumerable.Method(IEnumerable<T> source, args);\n// if extension method same as\nIEnumerable<T>.Method(args);\n
"},{"location":"languages/dotnet/csharp/reactive-extensions.html","title":"Reactive Extensions (Rx)","text":"

ReactiveX

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.

This might sound a lot like LINQ to Objects, and there are similarities, not only does IObservable<T> have a lot in common with IEnumerable<T>, but Rx also supports almost all of the standard LINQ operators.

The difference is that in Rx, sequences are less passive. Unlike IEnumerable<T>, Rx sources do not wait to be asked for their items, nor can the consumer of an Rx source demand to be given the next item. Instead, Rx uses a push model in which the source notifies its recipients when items are available.

Because Rx implements standard LINQ operators, it's possible to write queries against a live source. Rx goes beyond standard LINQ, adding its own operators that take into account the temporal nature of a live event source.

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#fundamental-interfaces","title":"Fundamental Interfaces","text":"

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.

C#
public interface IObservable<out T>\n{\n    IDisposable Subscribe(IObserver<T> observer);\n}\n\npublic interface IObserver<in T>\n{\n    void OnCompleted();\n    void OnError(Exception error);\n    void OnNext(T value);\n}\n

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\u2019s 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. If the source wants to report an error, it can call OnError. Both OnCompleted and OnError indicate the end of the stream, an observable should not call any further methods on the observer after that.

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#operators","title":"Operators","text":""},{"location":"languages/dotnet/csharp/reactive-extensions.html#chaining-operators","title":"Chaining Operators","text":"

Most operators operate on an Observable and return an Observable. This allows to apply these operators one after the other, in a chain. Each operator in the chain modifies the Observable that results from the operation of the previous operator. A chain of Observable operators do not operate independently on the original Observable that originates the chain, but they operate in turn, each one operating on the Observable generated by the operator immediately previous in the chain.

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#creating-observables","title":"Creating Observables","text":"

Operators that originate new Observables.

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#transforming-observables","title":"Transforming Observables","text":"

Operators that transform items that are emitted by an Observable.

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#filtering-observables","title":"Filtering Observables","text":"

Operators that selectively emit items from a source Observable.

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#combining-observables","title":"Combining Observables","text":"

Operators that work with multiple source Observables to create a single Observable

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#error-handling-operators","title":"Error Handling Operators","text":"

Operators that help to recover from error notifications from an Observable

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#observable-utility-operators","title":"Observable Utility Operators","text":"

A toolbox of useful Operators for working with Observables

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#conditional-and-boolean-operators","title":"Conditional and Boolean Operators","text":"

Operators that evaluate one or more Observables or items emitted by Observables

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#mathematical-and-aggregate-operators","title":"Mathematical and Aggregate Operators","text":"

Operators that operate on the entire sequence of items emitted by an Observable

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#connectable-observable-operators","title":"Connectable Observable Operators","text":"

Specialty Observables that have more precisely-controlled subscription dynamics

"},{"location":"languages/dotnet/csharp/reactive-extensions.html#operators-to-convert-observables","title":"Operators to Convert Observables","text":""},{"location":"languages/dotnet/csharp/unit-tests.html","title":"Unit Testing","text":"

UnitTest Overloaded Methods Naming standards for unit tests

"},{"location":"languages/dotnet/csharp/unit-tests.html#xunit","title":"xUnit","text":"C#
using System;\nusing Xunit;\n\nnamespace Project.Tests\n{\n    public class ClassTest\n    {\n        [Fact]\n        public void TestMethod()\n        {\n            Assert.Equal(expected, actual);  // works on collections\n            Assert.True(bool);\n            Assert.False(bool);\n            Assert.NotNull(nullable);\n\n            // Verifies that all items in the collection pass when executed against action\n            Assert.All<T>(IEnumerable<T> collection, Action<T> action);\n        }\n    }\n}\n
"},{"location":"languages/dotnet/csharp/unit-tests.html#test-setup-teardown","title":"Test Setup & Teardown","text":"

xUnit.net creates a new instance of the test class for every test that is run, so any code which is placed into the constructor of the test class will be run for every single test. This makes the constructor a convenient place to put reusable context setup code.

For context cleanup, add the IDisposable interface to the test class, and put the cleanup code in the Dispose() method.

"},{"location":"languages/dotnet/csharp/unit-tests.html#mocking-with-moq","title":"Mocking with Moq","text":"C#
var mockObj = new Mock<MockedType>();\n\nmockObj.Setup(m => m.Method(It.IsAny<InputType>())).Returns(value);\nmockObj.Object;  // get mock\n\n// check that the invocation is forwarded to the mock, n times\nmockObj.Verify(m => m.Method(It.IsAny<InputType>()), Times.Once());\n\n// check that the invocation is forwarded to the mock with a specific input\nmockObj.Verify(m => m.Method(input), Times.Once());\n
"},{"location":"languages/dotnet/database/ado.net.html","title":"ADO.NET","text":"

ADO.NET is a set of classes that expose data access services for .NET. The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll.

ADO.NET provider for SQLite

"},{"location":"languages/dotnet/database/ado.net.html#connection-strings","title":"Connection Strings","text":""},{"location":"languages/dotnet/database/ado.net.html#sql-server-2019","title":"SQL Server 2019","text":"

Note: Multiple Active Result Sets (MARS) is a feature that works with SQL Server to allow the execution of multiple batches on a single connection.

"},{"location":"languages/dotnet/database/ado.net.html#sqlite","title":"SQLite","text":""},{"location":"languages/dotnet/database/ado.net.html#connection-to-db","title":"Connection to DB","text":"C#
using System;\nusing System.Data.SqlClient;  // ADO.NET Provider, installed through NuGet\n\nnamespace <namespace>\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            // Connection to SQL Server DBMS\n            SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();\n            connectionString.DataSource = \"<server_name>\";\n            connectionString.UserID = \"<user>\";\n            connectionString.Password = \"<password>\";\n            connectionString.InitialCatalog = \"<database>\";\n\n            // more compact\n            SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder(\"Server=<server_name>;Database=<database>;UID=<user>;Pwd=<password>\")\n        }\n    }\n}\n
"},{"location":"languages/dotnet/database/ado.net.html#db-interrogation","title":"DB Interrogation","text":""},{"location":"languages/dotnet/database/ado.net.html#sqlconnection","title":"SqlConnection","text":"C#
using (SqlConnection connection = new SqlConnection())\n{\n    connection.ConnectionString = connectionString.ConnectionString;\n    connection.Open();  // start communication w/ sql server\n}\n\n// more compact\nusing (SqlConnection connection = new SqlConnection(connectionString)) {\n    connection.Open()\n}\n
"},{"location":"languages/dotnet/database/ado.net.html#sqlcommand","title":"SqlCommand","text":"C#
string sql = \"<sql_instruction>\";\n\nusing (SqlCommand command = new SqlCommand())\n{\n    command.Connection = connection;  // SqlConnection\n    command.CommandText = \"... @Parameter\";  // or name of StoredProcedure\n\n    // add parameters to the SqlParameterCollection, WARNING: table names or columns cannot be parameters\n    command.Parameters.Add(\"@Parameter\", SqlDbType.<DBType>, columnLength).Value = value;\n    command.Parameters.AddWithValue(\"@Parameter\", value);\n    command.Parameters.AddWithValue(\"@Parameter\", (object) value ?? DBNull.Value);  // if Parameter is nullable\n\n    // Create an instance of a SqlParameter object.\n    command.CreateParameter();\n\n    command.CommandType = CommandType.Text;  // or StoredProcedure\n\n    int affectedRows = command.ExecuteNonQuery();  // execute the query and return the number of affected rows\n}\n
"},{"location":"languages/dotnet/database/ado.net.html#sqldatareader","title":"SqlDataReader","text":"C#
using (SqlDataReader cursor = command.ExecuteReader())  // object to get data from db\n{\n    while (cursor.Read())  // get data till possible\n    {\n        // preferred methodology\n        cursor[\"<column_name>\"].ToString();  // retrieve data form the column\n        cursor[<column_index>].ToString();  // retrieve data form the column\n\n        // check for null before retrieving the value\n        if(!cursor.IsDBNull(n))\n        {\n            cursor.Get<SystemType>(index);  // retrieve data form the n-th column\n        }\n    }\n}\n
"},{"location":"languages/dotnet/database/entity-framework.html","title":"Entity Framework","text":""},{"location":"languages/dotnet/database/entity-framework.html#model-data-annotations","title":"Model & Data Annotations","text":"C#
using System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\n\nnamespace <Project>.Model\n{\n    public class Entity\n    {\n        [Key]  // set as PK (Id & EntityId are automatically detected to be PKs)\n        public int Id { get; set; }\n\n        [Required]\n        public Type ForeignObject { get; set; }  // Not Null in DB\n        public Type ForeignObject { get; set; }  // Allow Null in DB\n\n        public int Prop { get; set; }  // Not Null in DB (primitive are not nullable)\n        public int? Prop { get; set; }  // Allow Null in DB\n    }\n}\n
"},{"location":"languages/dotnet/database/entity-framework.html#context","title":"Context","text":"

NuGet Packages to install:

C#
using Microsoft.EntityFrameworkCore;\n\nnamespace <Project>.Model\n{\n    class Context : DbContext\n    {\n        private const string _connectionString = \"Server=<server_name>;Database=<database>;UID=<user>;Pwd=<password>\";\n\n        // connect to db\n        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)\n        {\n            optionsBuilder.UseSqlServer(_connectionString);  // specify connection\n        }\n\n        // or\n\n        public Context(DbContextOptions options) : base(options)\n        {\n        }\n\n        //DBSet<TEntity> represents the collection of all entities in the context (or that can be queried from the database) of a given type\n        public DbSet<Entity> Entities { get; set; }\n        public DbSet<Entity> Entities => Set<Entity>();  // with nullable reference types\n    }\n}\n
"},{"location":"languages/dotnet/database/entity-framework.html#migrations","title":"Migrations","text":"

Create & Update DB Schema if necessary.

In Package Manager Shell:

PowerShell
PM> Add-Migration <migration_name>\nPM> update-database [-Verbose] # use the migrations to modify the db, -Verbose to show SQL queries\n

In dotnet cli:

PowerShell
dotnet tool install --global dotnet-ef  # if not already installed\n\ndotnet ef migrations add <migration_name>\ndotnet ef database update\n
"},{"location":"languages/dotnet/database/entity-framework.html#crud","title":"CRUD","text":""},{"location":"languages/dotnet/database/entity-framework.html#create","title":"Create","text":"C#
context.Add(entity);\ncontext.AddRange(entities);\n\ncontext.SaveChanges();\n
"},{"location":"languages/dotnet/database/entity-framework.html#read","title":"Read","text":"

Referenced Object Not Loading Fix

C#
context.Entities.ToList();\ncontext.Entities.Find(id);\n\n// force read of foreign key identifying referenced obj\ncontext.Entities.Include(c => c.ForeignObject).Find(id);\n
"},{"location":"languages/dotnet/database/entity-framework.html#update","title":"Update","text":"C#
context.Entities.Update(entity);\ncontext.UpdateRange(entities);\n\ncontext.SaveChanges();\n
"},{"location":"languages/dotnet/database/entity-framework.html#delete","title":"Delete","text":"C#
context.Entities.Remove(entity);\ncontext.RemoveRange(entities);\n\ncontext.SaveChanges();\n
"},{"location":"languages/html/html.html","title":"HTML","text":""},{"location":"languages/html/html.html#terminology","title":"Terminology","text":"

Web design: The process of planning, structuring and creating a website. Web development: The process of programming dynamic web applications. Front end: The outwardly visible elements of a website or application. Back end: The inner workings and functionality of a website or application.

"},{"location":"languages/html/html.html#anatomy-of-an-html-element","title":"Anatomy of an HTML Element","text":"

Element: Building blocks of web pages, an individual component of HTML. Tag: Opening tag marks the beginning of an element & closing tag marks the end. Tags contain characters that indicate the tag's purpose content.

<tagname> content </tagname>

Container Element: An element that can contain other elements or content. Stand Alone Element: An element that cannot contain anything else. Attribute: Provides additional information about the HTML element. Placed inside an opening tag, before the right angle bracket. Value: Value is the value assigned to a given attribute. Values must be contained inside quotation marks (\u201c\u201d).

"},{"location":"languages/html/html.html#the-doctype","title":"The Doctype","text":"

The first thing on an HTML page is the doctype, which tells the browser which version of the markup language the page is using.

"},{"location":"languages/html/html.html#xhtml-10-strict","title":"XHTML 1.0 Strict","text":"HTML
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n
"},{"location":"languages/html/html.html#html4-transitional","title":"HTML4 Transitional","text":"HTML
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\">\n
"},{"location":"languages/html/html.html#html5","title":"HTML5","text":"

<!doctype html>

"},{"location":"languages/html/html.html#the-html-element","title":"The HTML Element","text":"

After <doctype>, the page content must be contained between tags.

HTML
<!doctype html>\n<html lang=\"en\">\n    <!-- page contents -->\n</html>\n
"},{"location":"languages/html/html.html#the-head-element","title":"The HEAD Element","text":"

The head contains the title of the page & meta information about the page. Meta information is not visible to the user, but has many purposes, like providing information to search engines. UTF-8 is a character encoding capable of encoding all possible characters, or code points, defined by Unicode. The encoding is variable-length and uses 8-bit code units.

XHTML and HTML4: <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></meta>

HTML5: <meta charset=\"utf-8\">

"},{"location":"languages/html/html.html#html-shiv-polyfill","title":"HTML Shiv (Polyfill)","text":"

Used to make old browsers understand newer HTML5 and newer components.

HTML
<!--[if lt IE 9]>\n    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js\"></script>\n<![endif]-->\n
"},{"location":"languages/html/html.html#the-body-element","title":"The BODY Element","text":"

The body contains the actual content of the page. Everything that is contained in the body is visible to the user.

HTML
<body>\n    <!-- page contents -->\n</body>\n
"},{"location":"languages/html/html.html#javascript","title":"JavaScript","text":"

XHTML and older: <script src=\"js/scripts.js\" type=\"text/javascript\"></script> HTML5: <script src=\"js/scripts.js\"></script> (HTML5 spec states that type attribute is redundant and should 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.

"},{"location":"languages/html/html.html#local-remote-or-inline-javascript","title":"Local, Remote or Inline JavaScript","text":"

Remote: <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> Local: <script src=\"js/main.js\"></script> Inline: <script> javascript-code-here </script>

"},{"location":"languages/html/html.html#forms","title":"Forms","text":"

Forms allow to collect data from the user:

Forms contain elements called controls (text inputs, checkboxes, radio buttons, submit buttons). When users complete a form the data is usually submitted to a web server for processing.

"},{"location":"languages/html/html.html#form-validation","title":"Form Validation","text":"

Validation is a mechanism to ensure the correctness of user input.

Uses of Validation:

"},{"location":"languages/html/html.html#front-end-validation","title":"Front-End Validation","text":"

The application should validate all information to make sure that it is complete, free of errors and conforms to the specifications required by the back-end. It should contain mechanisms to warn users if input is not complete or correct. It should avoid to send \"bad\" data to the back-end.

"},{"location":"languages/html/html.html#back-end-validation","title":"Back-End Validation","text":"

It should never trust that the front-end has done validation since some clever users can bypass the front-end mechanisms easily. Back-end services can receive data from other services, not necessarily front-end, that don't perform validation.

"},{"location":"languages/html/html.html#built-in-validation","title":"Built-In Validation","text":"

Not all browsers validate in the same way and some follow the specs partially. Some browsers don't have validation at all (older desktop browsers, some mobile browsers). Apart from declaring validation intention with HTML5 developers don't have much control over what the browser actually does. Before using build-in validation make sure that it's supported by the target browsers.

"},{"location":"languages/html/html.html#validation-with-javascript","title":"Validation with JavaScript","text":""},{"location":"languages/html/html.html#general-structure-of-html-page","title":"General structure of HTML page","text":"HTML
<!-- HTML Boilerplate -->\n<!DOCTYPE html>\n<html lang=\"en\">\n    <head>\n        <!-- meta tag -->\n        <meta charset=\"utf-8\">\n        <title></title>\n        <meta name=\"description\" content=\"\">\n        <meta name=\"author\" content=\"\">\n\n        <!-- adapt page dimensions to device -->\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\n        <!-- external style sheet here -->\n        <link rel=\"stylesheet\" href=\"path/style-sheet.css\">\n\n        <!-- script if necessary -->\n        <script src=\"_.js\" type=\"text/javascript\"></script>\n\n        <!-- script is executed only after the page finishes loading-->\n        <script src=\"_.js\" defer type=\"text/javascript\"></script>\n    </head>\n    <body>\n\n        <!-- end of body -->\n        <script src=\"_.js\" type=\"text/javascript\"></script>\n    </body>\n</html>\n

Attributes describe additional characteristics of an HTML element. <tagname attribute=\"value\"> content </tagname>

"},{"location":"languages/html/html.html#meta-tag-structure","title":"Meta Tag Structure","text":"

<meta name=\"info-name\" content=\"info-content\">

"},{"location":"languages/html/html.html#paragraph","title":"Paragraph","text":"

Paragraphs allow to format the content in a readable fashion.

HTML
<p> paragraph-content </p>\n<p> paragraph-content </p>\n
"},{"location":"languages/html/html.html#headings","title":"Headings","text":"

Heading numbers indicates hierarchy, not size.

HTML
<h1> Heading 1 </h1>\n<h2> Heading 2 </h2>\n
"},{"location":"languages/html/html.html#formatted-text","title":"Formatted Text","text":"

With semantic value:

Without semantic value, used as last resort:

"},{"location":"languages/html/html.html#elements","title":"Elements","text":"

<br/>: Line break (carriage return). It's not good practice to put line breaks inside paragraphs.

<hr>: horizontal rule (line). Used to define a thematic change in the content.

"},{"location":"languages/html/html.html#linksanchor","title":"Links/Anchor","text":"

Surround content to turn into links.

HTML
<!-- Link to absolute URL -->\n<a href=\"uri/url\" title=\"content-title\" target=\"_self\"> text/image </a>\n\n<!-- links to relative URL -->\n<a href=\"//example.com\">Scheme-relative URL</a>\n<a href=\"/en-US/docs/Web/HTML\">Origin-relative URL</a>\n<a href=\"./file\">Directory-relative URL</a>\n\n<!-- Link to element on the same page -->\n<a href=\"#element-id\"></a>\n\n<!-- Link to top of page -->\n<a href=\"#top\"> Back to Top </a>\n\n<!-- link to email -->\n<a href=\"mailto:address@domain\">address@domain</a>\n\n<!-- link to telephone number -->\n<a href=\"tel:+39(111)2223334\">+39 111 2223334</a>\n\n<!-- download link -->\n<a href=\"./folder/filename\" download>Download</a>\n

target:

"},{"location":"languages/html/html.html#images","title":"Images","text":"HTML
<img src=\"image-location\" alt=\"brief-description\"/>    <!-- image element -->\n<!-- alt should be always be populated for accessibility and SEO purposes -->\n
HTML
<!-- supported by modern browsers -->\n<figure>\n    <img src=\"img-location\" alt=\"description\">\n    <figcaption> caption of the figure </figcaption>\n</figure>\n
"},{"location":"languages/html/html.html#unordered-list-bullet-list","title":"Unordered list (bullet list)","text":"HTML
<ul>\n    <li></li>    <!-- list element -->\n    <li></li>\n</ul>\n
"},{"location":"languages/html/html.html#ordered-list-numbered-list","title":"Ordered list (numbered list)","text":"HTML
<ol>\n    <li></li>\n    <li></li>\n</ol>\n
"},{"location":"languages/html/html.html#description-list-list-of-terms-and-descriptions","title":"Description list (list of terms and descriptions)","text":"HTML
<dl>\n    <dt>term</dt>    <!-- define term/name -->\n    <dd>definition</dd> <!-- describe term/name -->\n    <dt>term</dt>\n    <dd>definition</dd>\n</dl>\n
"},{"location":"languages/html/html.html#tables","title":"Tables","text":"HTML
<table>\n    <thead>    <!-- table head row -->\n        <th></th> <!-- table head, one for each column-->\n        <th></th>\n    </thead>\n    <tbody>    <!-- table content (body) -->\n        <tr> <!-- table row -->\n            <td></td> <!-- table cell -->\n            <td></td>\n        </tr>\n    </tbody>\n</table>\n
"},{"location":"languages/html/html.html#character-codes","title":"Character Codes","text":"Code Character &copy; Copyright &lt; less than (<) &gt; greater than (>) &amp; ampersand (&)"},{"location":"languages/html/html.html#block-element","title":"Block Element","text":"

Used to group elements together into sections, eventually to style them differently.

HTML
<div>\n    <!-- content here -->\n</div>\n
"},{"location":"languages/html/html.html#inline-element","title":"Inline Element","text":"

Used to apply a specific style inline.

HTML
<p> non-styled content <span class=\"...\"> styled content </span> non-styled content </p>\n
"},{"location":"languages/html/html.html#html5-new-tags","title":"HTML5 new tags","text":"HTML
<header></header>\n<nav></nav>\n<main></main>\n<section></section>\n<article></article>\n<aside></aside>\n<footer></footer>\n
"},{"location":"languages/html/html.html#html-forms-inputs","title":"HTML Forms & Inputs","text":"HTML
<form action=\"data-receiver\" target=\"\" method=\"http-method\">\n    <!-- ALL form elements go here -->\n</form>\n

Target:

Method:

PROs & CONs of GET method:

PROs & CONs of POST method:

"},{"location":"languages/html/html.html#basic-form-elements","title":"Basic Form Elements","text":"HTML
<form action=\"\" method=\"\">\n    <label for=\"target-identifier\">label-here</label>\n    <input type=\"input-type\" name=\"input-name\" value=\"value-sent\" id=\"target-identifier\">\n</form>\n\n<!-- SAME AS -->\n\n<form>\n    <label>Label:\n        <input type=\"input-type\" name=\"input-name\" value=\"value-sent\" id=\"target-identifier\">\n    </label>\n</form>\n

Note: The <label> tag is used to define the labels for <input> elements.

Input Attributes:

"},{"location":"languages/html/html.html#text-field","title":"Text Field","text":"

One line areas that allow the user to input text.

HTML
<input type=\"text\" placeholder=\"placeholder-text\" spellcheck=\"true\" pattern=\"\\regex\\\">\n

Note: Text inputs can display a placeholder text that will disappear as soon as some text is entered

"},{"location":"languages/html/html.html#password-field","title":"Password Field","text":"HTML
<input type=\"password\">\n
"},{"location":"languages/html/html.html#radio-buttons","title":"Radio Buttons","text":"HTML
<input type=\"radio\" value=\"value\">\n<input type=\"radio\" value=\"value\" checked>\n
"},{"location":"languages/html/html.html#checkboxes","title":"Checkboxes","text":"HTML
<input type=\"checkbox\">\n<input type=\"checkbox\" checked>\n
"},{"location":"languages/html/html.html#dropdown-menus","title":"Dropdown Menus","text":"HTML
<select multiple>\n    <option value=\"value\">Value</option>\n    <option value=\"value\">Value</option>\n    <option value=\"value\" selected>Value</option>\n</select>\n

Use <select> rather than radio buttons when the number of options to choose from is large selected is used rather than checked. Provides the ability to select multiple options. Conceptually, <select> becomes more similar to checkboxes.

"},{"location":"languages/html/html.html#file-select","title":"File Select","text":"

Upload a local file as an attachment. The accept attribute value is a string that defines the file types the file input should accept. This string is a comma-separated list of unique file type specifiers.

HTML
<input type=\"file\" value=\"filename\" accept=\".txt,application/json,audio/*\">\n
"},{"location":"languages/html/html.html#text-area","title":"Text Area","text":"

Multi line text input.

HTML
<textarea rows=\"row-number\" cols=\"column-number\" >pre-existing editable test</textarea>\n
"},{"location":"languages/html/html.html#submit-reset","title":"Submit & Reset","text":"HTML
<input type=\"submit\" value=\"label\">\n<input type=\"reset\" value=\"label\">\n<!-- OR -->\n<button type=\"submit\" value=\"label\">\n<button type=\"reset\" value=\"label\">\n

submit: sends the form data to the location specified in the action attribute. reset: resets all forms controls to the default values.

"},{"location":"languages/html/html.html#button","title":"Button","text":"HTML
<button type=\"button/reset/submit\" value=\"label\"/>\n\n<!-- can contain HTML -->\n<button type=\"button/reset/submit\" value=\"lebel\"></button>\n
"},{"location":"languages/html/html.html#fieldset","title":"Fieldset","text":"

Group controls into categories. Particularly important for screen readers.

HTML
<fieldset>\n    <legend>Color</legend>\n    <input type=\"radio\" name=\"colour\" value=\"red\" id=\"colour_red\">\n    <label for=\"colour_red\">Red</label>\n    <input type=\"radio\" name=\"colour\" value=\"green\" id=\"colour_green\">\n    <label for=\"colour_green\">Green</label>\n    <input type=\"radio\" name=\"colour\" value=\"blue\" id=\"colour_blue\">\n    <label for=\"colour_blue\">Red</label>\n</fieldset>\n
"},{"location":"languages/html/html.html#email-field","title":"Email Field","text":"

Used to receive a valid e-mail address from the user. Most browsers can validate this without needing javascript. Older browsers don't support this input type.

HTML
<form>\n    <label for=\"user-email\">Email:</label>\n    <input type=\"email\" name=\"user-email\" id=\"form-email\">\n    <button type=\"submit\">Send</button>\n</form>\n
"},{"location":"languages/html/html.html#progress-bar","title":"Progress Bar","text":"HTML
<progress max=\"100\" value=\"70\"> 70% </progress>\n
"},{"location":"languages/html/html.html#slider","title":"Slider","text":"HTML
<input type=\"range\" min=\"0\" max=\"20\">\n
"},{"location":"languages/html/html.html#meter","title":"Meter","text":"

The <meter> HTML element represents either a scalar value within a known range or a fractional value.

HTML
<meter min=\"0\" max=\"100\" low=\"33\" high=\"66\" optimum=\"80\" value=\"50\">current value</meter>\n
"},{"location":"languages/html/html.html#datalist-autocomplete","title":"Datalist (Autocomplete)","text":"

The datalist HTML element can provide suggestions to an input that targets it's id with the list attribute.

HTML
<input list=\"items\">\n\n<datalist id=\"items\">\n    <option value=\"value-1\">\n    <option value=\"value-2\">\n    <option value=\"value-3\">\n</datalist>\n
"},{"location":"languages/html/html.html#more-input-types","title":"More Input Types","text":"HTML
<input type=\"email\" id=\"email\" name=\"email\" />\n<input type=\"url\" id=\"url\" name=\"url\" />\n<input type=\"number\" name=\"\" id=\"identifier\" min=\"min-value\" max=\"max-value\" step=\"\" />\n<input type=\"search\" id=\"identifier\" name=\"\">\n<input type=\"color\" />\n
"},{"location":"languages/html/html.html#using-built-in-form-validation","title":"Using Built-In Form Validation","text":"

One of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements.

If the data entered in an form field follows all of the rules specified by the above attributes, it is considered valid. If not, it is considered invalid.

When an element is valid, the following things are true:

When an element is invalid, the following things are true:

"},{"location":"languages/java/dao.html","title":"Database Access Object","text":""},{"location":"languages/java/dao.html#db","title":"DB","text":"

Connection to the DB.

Java
package dao;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n\npublic class DB {\n\n    private Connection conn;  // db connection obj\n\n    private final String URL = \"jdbc:<dbms>:<db_url>/<database>\";\n    private final String USER = \"\";\n    private final String PWD = \"\";\n\n    public DB() {\n        this.conn = null;\n    }\n\n    public void connect() {\n        try {\n            this.conn = DriverManager.getConnection(URL, USER, PWD);\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n    }\n\n    public void disconnect() {\n        if(conn != null) {\n            try {\n                this.conn.close();\n            } catch (SQLException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n\n    public Connection getConn() {\n        return conn;\n    }\n}\n
"},{"location":"languages/java/dao.html#itypedao","title":"I<Type>DAO","text":"

Interface for CRUD methods on a database.

Java
package dao;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\npublic interface I<Type>DAO {\n\n    String RAW_QUERY = \"SELECT * ...\"\n    public Type Query() throws SQLException;\n}\n
"},{"location":"languages/java/dao.html#typedao","title":"<Type>DAO","text":"

Class implementing I<Type>DAO and handling the communication with the db.

Java
package dao;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class <Type>DAO implements I<Type>DAO {\n\n    private <Type> results;\n\n    private Statement statement;  // SQL instruction container\n    private ResultSet rs;  // Query results container\n    private DB db;\n\n    public <Type>DAO() {\n        db = new DB();\n    }\n\n    @Override\n    public Type Query() throws SQLException {\n        // 1. connection\n        db.connect();\n\n        // 2. instruction\n        statement = db.getConn().createStatement();  // statement creation\n\n        // 3. query\n        rs = statement.executeQuery(RAW_QUERY);  // set the query\n\n        // 4. results\n        while(rs.next()) {\n            // create and valorize Obj\n            // add to results\n        }\n\n        // 5. disconnection\n        db.disconnect()\n\n        // 6. return results\n        return results;\n    }\n}\n
"},{"location":"languages/java/java-collection-framework.html","title":"Java Collection Framework - JCF","text":"

All classes that permit the handling of groups of objects constitute the Java Collection Framework.

A Collection is a container in which several objects are grouped in a single entity.

The Java Collection Framework is constituted by:

"},{"location":"languages/java/java-collection-framework.html#javautilcollections","title":"java.util.Collections","text":""},{"location":"languages/java/java-collection-framework.html#collection-functions","title":"Collection Functions","text":"Java
boolean add (Object o) e.g., <x>.add (<y>)    //append to collection, false if fails\nboolean add (int index, Object o)    //insertion at given index\nboolean addAll (Collection c)    //appends a collection to another\nvoid clear()     //remove items from container\nboolean contains (Object o)    //true if object is in collection\nboolean containsAll (Collection c)    //true if all items of collection are in another\nboolean isEmpty (Object o) e.g., if (<x>.isEmpty()) ...    //true if collection is empty\nboolean remove (Object o)    //remove object from collection\nObject remove (int index)    //remove object at given index\nvoid removeAll (Collection c)    //remove all items form collection\nint size ()    //number og items in collection\nObject [] toArray()    //transform collection in array\nIterator iterator()    //returns iterator to iterate over the collection\n
"},{"location":"languages/java/java-collection-framework.html#collections-methods","title":"Collections Methods","text":"Java
Collection<E>.forEach(Consumer<? super T> action);\n
"},{"location":"languages/java/java-collection-framework.html#iterator","title":"Iterator","text":"

Abstracts the problem of iterating over all the elements of a collection;

"},{"location":"languages/java/java-collection-framework.html#arraylist","title":"ArrayList","text":"

Note: ArrayLists can't contain primitive values. Use wrapper classes instead.

Java
import java.util.ArrayList;\nArrayList<Type> ArrayListName = new ArrayList<Type>(starting_dim);    //resizable array\nArrayList<Type> ArrayListName = new ArrayList<Type>();    //resizable array\nArrayList<Type> ArrayListName = new ArrayList<>();    //resizable array (JAVA 1.8+)\n\n\nArrayListName.add(item);    //append item to collection\nArrayListName.add(index, item);  // add item at position index, shift all item from index and successive towards the end af the ArrayList\nArrayListName.set(index, item);  // substitute EXISTING item\nArrayListName.get(index);    //access to collection item\nArrayListName.remove(item)    //remove first occurrence of item from collection\nArrayListName.remove(index)    //remove item at position index\nArrayListName.clear()    //empties the ArrayList\nArrayListName.contains(object);  // check if object is in the ArrayList\nArrayListName.IndexOf(object);  // returns the index of the object\nArrayListName.isEmpty();  // check wether the list is empty\n\nArrayListName.size();    //dimension of the ArrayList\nArrayListName.tirmToSize();  // reduce ArrayList size to minimum needed\n// ArrayList size doubles when a resize is needed.\n\n//run through to the collection with functional programming (JAVA 1.8+)\nArrayListName.forEach(item -> function(v));\n
"},{"location":"languages/java/java-collection-framework.html#collection-sorting","title":"Collection Sorting","text":"

To sort a collection it's items must implement Comparable<T>:

Java
class ClassName implements Comparable<ClassName> {\n\n    @override\n    public int compareTo(Classname other){\n        //compare logic\n        return <int>;\n    }\n}\n\nList<ClassName> list;\n//valorize List\nCollections.sort(list);    //\"natural\" sorting uses compareTo()\n

Otherwise a Comparator() must be implemented:

Java
class Classname {\n    //code here\n}\n\n// Interface object (!) implements directly a method\nComparator<ClassName> comparator = new Comparator<ClassName>() {\n\n    @Override\n    public int compare(ClassName o1, Classname o2) {\n        //compare logic\n        return <int>;\n    }\n};\n\nList<ClassName> list;\n//valorize List\nCollections.sort(list, comparator);    //\"natural\" sorting uses compareTo()\n

Comparator<T> and Comparable<T> are functional interfaces

"},{"location":"languages/java/java.html","title":"Java","text":"Java
//single line comment\n/* multi line comment */\n/** javaDoc docstring */\n
Java element Case package lowercase class PascalCase variable camelCase method camelCase"},{"location":"languages/java/java.html#basics","title":"Basics","text":"

Package definition: package <package_location>;

"},{"location":"languages/java/java.html#main-method-entry-point-of-algorithm","title":"Main Method (entry point of algorithm)","text":"Java
public static void main (String[] args) {\n    //code here\n}\n
"},{"location":"languages/java/java.html#variable-assignment","title":"Variable Assignment","text":"

Type variable_1 = <expr>, ..., variable_n = <expr>;

"},{"location":"languages/java/java.html#constant-definition-outside-of-main-methodfunction","title":"Constant Definition (outside of main method/function)","text":"Java
public static final Type CONSTANT_NAME = value;\npublic static final double PI = 3.14159;   //example\n
"},{"location":"languages/java/java.html#constant-definition-inside-main-methodfunction","title":"Constant Definition (inside main method/function)","text":"Java
final Type CONSTANT_NAME = value;\nfinal double PI = 3.14159;   //example\n
"},{"location":"languages/java/java.html#screen-output","title":"Screen Output","text":"Java
System.out.println(output_1 + _ + output_n);   //newline at every invocation\nSystem.out.print(output_1 + _ + output_n);\n
"},{"location":"languages/java/java.html#output-formatting","title":"Output Formatting","text":"

String.format() Examples

Java
System.out.printf(\"string %..\", variable);\nSystem.out.println(String.format(format, args));\n

Methods inherited from C. The value pf the variable substitutes %. %d int, %f float, %c char, %s string, %e scientific notation. %digitNumber.decimalDigitNumber specifies the space occupied by the output.

NumberFormat class is used to format a number output.

Java
Locale locale = new Locale(\"language\", \"country\");  // as defined by IETF lang tag, RCF 5646, RCF 4647\nNumberFormat fmt = NumberFormat.getCurrencyInstance(locale);  // format a number as a currency based on a Locale\nfmt.format(number);  // apply format to a number, returns a String\n
"},{"location":"languages/java/java.html#keyboard-input","title":"Keyboard Input","text":"Java
import java.util.Scanner;   //package import\nScanner scanner = new Scanner(System.in);  //Scanner obj init\nscanner.useDelimiter(\"delimitatore\");   //delimiter setting\nscanner.close()  //closing of Scanner, releases memory\n\nint variable_int_1 = scanner.nextInt();   //takes integer number\nString string_1 = scanner.nextLine();   //takes line of text (\\n ends line)\nString string_1 = scanner.next();   //takes text (space ends word)\ndouble variable_double_1 = scanner.nextDouble();  //takes double decimal number\nboolean variable_bool = scanner.nextBoolean();  //takes boolean value\n//(TRUE, FALSE, true, false, True, False)\n

The nextLine() method imports from the last \\n. Thus when switching to a different input method is necessary to call nextLine() one more time to avoid errors.

"},{"location":"languages/java/java.html#primitive-types","title":"Primitive Types","text":"Java
TYPE        WRAPPER     SIZE        MIN_VALUE               MAX_VALUE\nint         Integer                 -2147483648             2147483647\nbyte        Byte        8 bit       -128                    127\nshort       Short       16 bit      -32768                  32767\nlong - L    Long        32 bit      -9223372036854775808    9223372036854775807\nfloat - f   Float       32 bit      1.4 * 10^-45            3.4028235 * 10^38\ndouble - d  Double      64 bit      4.9 * 10^-324           1.7976931348623157 * 10^308\nchar        Character   16 bit      U+0000 (0)              U+FFFF (65535)\nboolean     Boolean                 false                   true\n

Digits can be separated by _ (underscore). If not specified int & double are the default types.

"},{"location":"languages/java/java.html#floating-point-numbers-precision-calcs","title":"Floating-Point numbers & Precision Calcs","text":"

Don't use == or != to confront floating value numbers since they use approximation or have a lot of digits. It's best to check if the difference between two numbers is small enough. For high precision calcs is best to use BigDecimal.

"},{"location":"languages/java/java.html#type-conversion-casting-type-checking","title":"Type Conversion (casting) & Type checking","text":"Java
Type variable = (Type) <expression>;  // convert to other Type\nvar instanceof Type;  // true if var is an instance of Type\n
"},{"location":"languages/java/java.html#wrapper-classes","title":"Wrapper Classes","text":"

Every primitive type has a corresponding wrapper class. Wrapper classes permits the creation of an object with the same type of a primitive type but with added methods and constants.

Java
WrapperClass objectName = new WrapperClass(primitiveValue);  //declaration\nWrapperClass objectName = primitiveValue;  //shortened declaration\n\n\nType variable = object.<Type>Value();  //unboxing\nType variable = object;  //autoboxing\nType variable = new WrapperClass(primitiveValue);  //automatic unboxing\n\nWrapperClass.MIN_VALUE  //constant holding min possible value of wrapper class\nWrapperClass.MAX_VALUE  //constant holding man possible value of wrapper class\n\nWrapperClass.parseClasseWrapper(string);  // converts the tring to the wrapper class, NumberFOrmatException on error\nWrapperClass.toString(primitive);  // converts the wrapper class value to a string\n
"},{"location":"languages/java/java.html#string-char","title":"String & Char","text":"Java
String string = \"text\";  //strings always in double quotes\nchar character = 'C';  //chars always in single quotes\n
"},{"location":"languages/java/java.html#special-characters","title":"Special Characters","text":"Escape Character Character \\n new line \\t tab \\b backspace \\r carriage return \\f form feed \\\\ backslash \\\" double quote \\u<4_hex_digits> unicode characters \\x<digits> hexadecimal characters \\o<digits> octal characters \\<digits> ASCII character"},{"location":"languages/java/java.html#string-concatenation","title":"String Concatenation","text":"

The value of the variable is appende to the string literal. \"text\" + variable String are immutable. Concatenation creates a new string.

"},{"location":"languages/java/java.html#string-conversion-to-number","title":"String Conversion to Number","text":"Java
double d  = Double.parseDouble(string);\nfloat f = Float.parseFloat(string);\nint i = integer.parseInt(string);\n
"},{"location":"languages/java/java.html#string-class-methods","title":"String Class Methods","text":"Java
string.equals(otherString);   // returns TRUE if the strings are equal\nstring.equalsIgnoreCase(otherString);   // returns TRUE if the strings are equals ignoring the case\nstring.charAt(index);  // returns the character at position INDEX\nstring.startsWith(otherString);  // returns TRUE if string starts with otherString\nstring.endsWith(otherString)  // returns TRUE if string ends with otherString\nstring.concat(otherString);   // concatenation of two strings\nstring.indexOf(otherString);  // returns index of the first occurrence of other string\nstring.lastIndexOf(otherString);  // returns index of the last occurrence of other string\nstring.length();    // returns the length of the string\nstring.toLowerCase();   // transform the string in uppercase characters\nstring.toUpperCase();   // transform the string in lowercase characters\nstring.replace(character, newCharacter);   // substitutes character with newCharacter\nstring.replaceAll(regex, replacement);\nstring.substring(start, end);   // returns a substring starting as START and ending at END (included)\nstring.trim();   // removes spaces before and after the string\nstring.Split(delimiter);  // return a String[] generated by splitting string at the occurrence of delimiter\nstring.compareTo(otherString);\n

compareTo() returns a number:

compareTo() compares the lexicographic order (based on UNICODE). To compare in alphabetical order both strings must have the same case.

"},{"location":"languages/java/java.html#mathematical-operations","title":"Mathematical Operations","text":"Java
Math.PI  // value of pi\nMath.E  // value of e\n\nMath.abs(x);  //absolute value of x\nMath.acos(x);\nMath.asin(x)\nMath.atan(x)\nMath.atan2(y, x)\nMath.ceil(x)\nMath.cos(x)\nMath.exp(x);  //e^x\nMath.floor(x)\nMath.log(x)\nMath.max(x, y)\nMath.min(x, y)\nMath.pow(x, y);  //x^y\nMath.random()\nMath.rint(x)\nMath.round(x)\nMath.sin(x)\nMath.sqrt(x);  //square root, x^(1/2)\nMath.tan(x)\nMath.toDegrees(rad)\nMath.toRadians(deg)\n
"},{"location":"languages/java/java.html#arithmetic-operators","title":"Arithmetic Operators","text":"operator operation a + b sum a - b subtraction a * b multiplication a / b division a % b modulo a++ increment a-- decrement"},{"location":"languages/java/java.html#comparison-operators","title":"Comparison Operators","text":"operator operation a == b equal to a != b not equal to a > b greater than a < b lesser than a >= b greater than or equal to a <= b lesser than or equal to"},{"location":"languages/java/java.html#logical-operators","title":"Logical Operators","text":"operator operation !a logical negation (NOT) a && b, logical AND a || b, logical OR"},{"location":"languages/java/java.html#bitwise-operators","title":"Bitwise Operators","text":"operator operation ~a bitwise NOT a & b bitwise AND a | b bitwise OR a ^ b bitwise XOR a << b bitwise left shift a >> b bitwise right shift"},{"location":"languages/java/java.html#compound-assignment-operators","title":"Compound Assignment Operators","text":"operator operation a += b a = a + b a -= b a = a - b a *= b a = a * b a /= b a = a / b a %= b a = a % b a &= b a = a & b a |= b a = a a ^= b a = a ^ b a <<= b a = a << b a >>= b a = a >> b"},{"location":"languages/java/java.html#operator-precedence","title":"Operator Precedence","text":"
  1. unary operators ++ , --, !
  2. binary arithmetic operators *, /, %
  3. binary arithmetic operators +, -
  4. boolean operators <, > , <=, >=
  5. boolean operators ==, !=
  6. bitwise operator &
  7. bitwise operator |
  8. logical operator &&
  9. logical operator ||
"},{"location":"languages/java/java.html#short-circuit-evaluation","title":"Short Circuit Evaluation","text":"

If in (expressionA || expressionB) expressionA results true, Java returns true without evaluating expressionB. If in (expressionA && expressionB) expressionA results false, Java returns false without evaluating expressionB. Full evaluation can be forced using & and |.

"},{"location":"languages/java/java.html#decision-statements","title":"Decision Statements","text":""},{"location":"languages/java/java.html#if-else","title":"If Else","text":"Java
if (condition) {\n    //code here\n} else {\n    //code here\n}\n
"},{"location":"languages/java/java.html#if-else-if-else","title":"If, Else If, Else","text":"Java
if (condition) {\n    //code here\n} else if (condition) {\n    //code here\n} else if (condition){\n    //code here\n} else {\n    //code here\n}\n
"},{"location":"languages/java/java.html#ternary-operator","title":"Ternary Operator","text":"

(condition) ? istruzione_1 : istruzione_2; if condition is true executes instruction1 otherwise executes instruction2.

"},{"location":"languages/java/java.html#switch","title":"Switch","text":"Java
switch (matchExpression) {\n    case matchingPattern:\n        //code here\n        break;\n    case matchingPattern:\n        //code here\n        break;\n    default:\n        //code here\n        break;\n}\n

Omitting the break keyword causes multiple branches to execute the same code.

"},{"location":"languages/java/java.html#loop-statements","title":"Loop Statements","text":""},{"location":"languages/java/java.html#while-loop","title":"While Loop","text":"Java
while (condition) {\n   //code here\n}\n
"},{"location":"languages/java/java.html#do-while-loop","title":"Do While Loop","text":"Java
do {\n    //code here\n} while (espressione_booleana);\n

Loop body executed at least one time

"},{"location":"languages/java/java.html#for-loop","title":"For Loop","text":"Java
for (initializer; condition; iterator) {\n    //code here\n}\n
"},{"location":"languages/java/java.html#foreach-loop","title":"Foreach Loop","text":"Java
for (Type variable : iterable){\n    //code here\n}\n
"},{"location":"languages/java/java.html#multiple-iterators-in-for-loop","title":"Multiple iterators in For Loop","text":"Java
for (initializer1, initializer2; condition; iterator1, iterator2) {\n    //code here\n}\n

The iterator declared in the for is a local variable and can be used only in the for loop block.

"},{"location":"languages/java/java.html#forced-program-termination","title":"Forced Program Termination","text":"

System.exit(returnedValue); forces the termination of the program execution returning a specified value.

"},{"location":"languages/java/java.html#assertion-checks","title":"Assertion Checks","text":"

If the assertion check is enabled (java -ebableassetrions programName) the execution of the algorithm is terminated if an assertion fails. Assertions can be used to check if a variable has a wanted value in a precise point in the code (Sanity Check).

Java
assert <booleanExpression>;\n
"},{"location":"languages/java/java.html#static-methods","title":"Static Methods","text":"

Static methods are not bound to an instance of a class but they act on the class itself.

"},{"location":"languages/java/java.html#static-void-method-definition","title":"Static Void Method Definition","text":"Java
static void methodName (parameters) {\n    //code here\n}\n
"},{"location":"languages/java/java.html#static-method-definition","title":"Static Method Definition","text":"Java
static tipo_metodo methodName (parameters) {\n    //code here\n    return <espressione>;   //returned type MUST match method type\n}\n
"},{"location":"languages/java/java.html#static-method-invocation","title":"Static Method Invocation","text":"Java
methodName(arguments);\nClassName.methodName(arguments);    //if method is used outside its class\n
"},{"location":"languages/java/java.html#array","title":"Array","text":""},{"location":"languages/java/java.html#array-declaration","title":"Array Declaration","text":"Java
Type[] arrayName = new Type[dimension];\n\nType arrayName[] = new Type[dimension];\n\narrayName.length  //length of the array\n

Its possible to break the declaration in two lines

Java
Type[] arrayName;\narrayType = new Type[dimension];\n
"},{"location":"languages/java/java.html#array-creation-by-initialization","title":"Array Creation by Initialization","text":"

Type[] arrayName = {value1, value2, ...} Array dimension is determined by the number of values.

"},{"location":"languages/java/java.html#arrays-as-method-parameters","title":"Arrays as method parameters","text":"Java
static Type methodName (Type[] arrayName) {\n    //code here\n}\n\nmethodName(arrayName);  //[] omitted when passing array as argument\n

Single elements of an array can be passed to a method. Array dimension can be omitted.

"},{"location":"languages/java/java.html#equality-of-arrays","title":"Equality of Arrays","text":"

As arrays ar object in Java, the operators == and != confront the memory address of the arrays. Array contents must be confronted by looping through the array.

"},{"location":"languages/java/java.html#methods-returning-arrays","title":"Methods returning Arrays","text":"Java
static Type[] methodName (parameters) {\n    Type[] arrayName = new Type[dimension];  //array declaration\n    //array valorization\n    return arrayName;\n}\n
"},{"location":"languages/java/java.html#variable-numbers-of-parameters-in-a-method","title":"Variable numbers of parameters in a method","text":"Java
static Type methodName (parameters, tipo[] ArrayName) {\n    //code here\n}\n

It's not necessary to specify a dimension of the array, it's determined by Java

"},{"location":"languages/java/java.html#multi-dimensional-arrays","title":"Multi-Dimensional Arrays","text":"Java
Type[]...[] arrayName = new Type[dimension1]...[dimensionN];\nType arrayName[]...[] = new Type[dimension1]...[dimensionN];\n
"},{"location":"languages/java/java.html#multi-dimensional-arrays-as-parameters","title":"Multi-Dimensional Arrays as parameters","text":"Java
static Type methodName (Type[]...[] ArrayName) {\n    //code here\n}\n
"},{"location":"languages/java/java.html#methods-returning-multi-dimensional-arrays","title":"Methods returning multi-dimensional arrays","text":"Java
static Type[]...[] methodName (parameters) {\n    Type[]...[] array = new Type[dimension1]...[dimensionN];\n    //array valorization\n    return array;\n}\n
"},{"location":"languages/java/java.html#array-length-of-multi-dimensional-arrays","title":"Array Length of multi-dimensional arrays","text":"Java
array.length  //row length\narray[rowIndex].length  //column length\n
"},{"location":"languages/java/java.html#irregular-table-visualization","title":"Irregular Table Visualization","text":"Java
static void viewTable (Type[][] matrix){\n    for (int row = 0; row < matrix.length; row++){   //run through the rows\n        for (int column = 0; column < arrayName[row].length; column++){   //run through the columns\n            System.put.print(arrayName[row][column] + \"\\t\");   //print item followed by a tab\n        }\n        System.out.println();   //newline after each matrix row\n    }\n}\n
"},{"location":"languages/java/java.html#recursion-guidelines","title":"Recursion Guidelines","text":"

The core of the recursion must be constituted by a conditional instruction that permits to handle the cases based on the method argument. At least one of the alternatives must contain a recursive call to che method. The call must resolve reduced version of the task handled by the method. At leats one of the alternatives must not contain a recursive call or it must produce a value that constitutes a base case or an arrest value.

"},{"location":"languages/java/java.html#exception-handling","title":"Exception Handling","text":"

An Exception is an object used to signal an anomalous event. Checked Exceptions must be handled in a catch meanwhile Unchecked Exceptions do not need to be cached like RuntimeException. Unchecked exceptions usually mean that there is an error in the logic of the program that must be fixed.

"},{"location":"languages/java/java.html#try-catch-finally","title":"Try-Catch-Finally","text":"

This construct permits to monitor what happens in a block of code and to specify what to do in case of errors (exceptions).

Java
try {\n    //monitored code\n} catch (SpecificException e) {\n    //in case of errors use this\n} catch (SpecificException1 | SpecificException2 | ... | SpecificExceptionN e) {\n    //in case of errors use this\n} catch (Exception e) {\n    //in case of error use this\n    e.getMessage();  // access to Exception error message\n} finally {\n    //code executed anyways\n}\n

A try-catch construct can handle multiple exceptions at once. Every catch is analyzed in sequence and is executed the first to happen thus is best to leave a generic exception last.

"},{"location":"languages/java/java.html#try-with-resources","title":"Try with Resources","text":"Java
try (\n    //resource definition\n){\n    //dangerous code\n} catch (Exception e) {\n    //in case of error use this\n} finally {\n    //code executed anyway\n}\n
"},{"location":"languages/java/java.html#throw-throws","title":"Throw & Throws","text":"

The throw keyword is used to generate a custom exception in a point of the code. throw is used together with an exception type.

Java
Type methodName(parameters) {\n    if (condition) {\n      throw new Exception(\"error message\");\n    }\n}\n

The throws keyword is used to indicate what exception Type may be thrown by a method. throws is used together with a exception class. It's used to send the exception to the method caller.

Java
Type methodName(parameters) throws ExceptionClass {\n    if (condition) {\n      throw new SpecificException(\"error message\");\n    }\n}\n
"},{"location":"languages/java/java.html#defining-personalized-exceptions","title":"Defining Personalized Exceptions","text":"

A user-defined exception has to inherit from Exception or one of it's descendants.

Java
public class CustomException extends Exception {\n\n    public CustomException(){\n        super(\"Base Message\");  // ese Exception constructor\n    }\n\n    public CustomException(string message){\n        super(message);\n    }\n\n    // CustomException inherits getMessage() from Exception\n\n}\n
"},{"location":"languages/java/java.html#object-oriented-programming","title":"Object Oriented Programming","text":""},{"location":"languages/java/java.html#access-modifiers","title":"Access Modifiers","text":"

public variables, methods, classes are usable outside of class of definition. private variables, methods, classes are only usable inside class of definition. protected variables, methods, classes can be accessed only by defining class, it's descendants and the package. final classes and methods cannot be extended or overridden. If not specified variables, methods and classes are only accessible from the same package.

"},{"location":"languages/java/java.html#instance-method-definition","title":"Instance Method Definition","text":"Java
Type methodName (parameters) {\n    //code here\n}\n
"},{"location":"languages/java/java.html#void-instance-method","title":"Void Instance Method","text":"Java
void methodName (parameters) {\n    //code here\n}\n
"},{"location":"languages/java/java.html#class-definition","title":"Class Definition","text":"Java
public class ClassName {\n    //instance variables declaration\n\n    //instantiation block\n    {\n        // this code is called before the constructor when an object is instantiated\n    }\n\n    //constructors definition\n\n    // getters & setters\n\n    // override of superclass' methods\n\n    //instance methods definition\n}\n
"},{"location":"languages/java/java.html#this-identifier","title":"This identifier","text":"

this.instanceVariable identifies the instance variable It's possible to use this to distinguish between instance and static variables with the same name.

"},{"location":"languages/java/java.html#classes-and-reference-addresses","title":"Classes and Reference Addresses","text":"

A an instance of a class doesn't contain an object of that class but a memory address in which the object is memorized. operations of assignment (=) and confront (==) act on the memory address and not on the values of the objects. To confront object is necessary to define a equals() method that checks if the values of the object attributes are equal.

"},{"location":"languages/java/java.html#constructors","title":"Constructors","text":"

Constructors are special methods that are invoked with the new operator when an object is instantiated. Constructors assign the starting values of the object attributes. If a constructor id defined Java doesn't create the default constructor.

Java
class ClassName (){\n\n    //attributes declaration (aka instance variables)\n\n    //constructor\n    public ClassName(parameters){\n        this.attribute = value;  //value is passed to the constructor at obj instantiation\n    }\n\n    public ClassName(parameters, otherParameters){\n        this(parameters);  // invoke other constructor for subset of parameters, must be FIRST INSTRUCTION\n        this.attribute = value;  // deal with the remaining parameters\n    }\n}\n
"},{"location":"languages/java/java.html#static-variables","title":"Static Variables","text":"

Type staticVariable = value; Static variables are shared by all objects of a class and all static method can act upon them. Static variable do not belong to the class objects.

"},{"location":"languages/java/java.html#getters-setter-methods","title":"Getters & Setter Methods","text":"Java
public void setAttribute(Type attribute){\n    this.attribute = attribute;\n}\n\npublic Type getAttribute(){\n    return this.attribute;\n}\n
"},{"location":"languages/java/java.html#tostring-method","title":"ToString() Method","text":"

Automatically returns a string if the object is directly called in a print method.

Java
@Override\nPublic String toString(){\n    return \"string-representation-of-object\"\n}\n
"},{"location":"languages/java/java.html#static-methods-in-classes","title":"Static Methods in Classes","text":"

Static methods are used to effectuate operations not applied to objects. Outside of the class of definition that are invoked with ClassName.methodName() Static method cannot act on instance variables.

"},{"location":"languages/java/java.html#method-overloading","title":"Method Overloading","text":"

A class can have multiple methods with the same name given that each method has a different number or type of parameters (different method signature).

"},{"location":"languages/java/java.html#inheritance-method-overriding","title":"Inheritance & Method Overriding","text":"

Child classes inherit all methods and attributes from parent class. Child methods can override parent methods to adapt their functionality. Overriding and overridden classes must have the same name. A child class can inherit from only one parent class.

Child class must implement a constructor that instantiates the parent (super) class. super() instantiates the superclass of the child class.

Java
class ChildClass extends ParentClass{\n\n    public ChildClass(parentParameters, childParameters){\n        super(parentParameters);  // if omitted super() is calls (parent's default constructor)\n        // assignments of child attributes\n    }\n\n    //calls overrides parent class (must have same name)\n    @Override\n    Type methodName(parameters){\n        //code here\n    }\n\n    super().methodName(parameters);  // calls the parent's method\n}\n

An overridden method that returns a ParentClass can be overridden to return a ChildClass. This is the only case in which an overridden method can change the returned type. An overridden method can change the access modifier as long as the new modifier is more \"permissive\".

A ParentClass type can contain a ChildClass object. This is useful for using collections and arrays of objects.

Java
ParentClass objectName = ChildClass();  // upcast\n(ChildClass)ParentClassObject;  // downcast\n
"},{"location":"languages/java/java.html#abstract-classes-abstract-methods","title":"Abstract Classes & Abstract Methods","text":"

An Abstract Class is a particular class that contains an Abstract Method. This type of class cannot be instantiated but is used leave the specific implementation of some of it's methods to extending classes. Abstract classes are marked by the abstract keyword.

An abstract method is a method without implementation. The methods must be public and marked with the abstract keyword.

Java
//abstract class\nabstract class className{\n    //attributes here\n    //constructor here\n    //getters & setters here\n\n    public abstract Type methodName();  //no method code\n\n}\n
"},{"location":"languages/java/java.html#interfaces","title":"Interfaces","text":"

An Interface is a class with only abstract methods. An interface has more flexibility than an abstract class. Interfaces are used to set requirements for child classes without specifying how to satisfy those requirements since it's methods will be implemented in child classes. An Interface is marked by the interface keyword. If an implementing class implements only some of the interface's method than the class must be abstract.

Interfaces' methods are always abstract and public, no need for the keyword. Interfaces' attributes are always public static final, no need for the keyword.

A class can implement more than one Interface.

Java
public interface InterfaceName{\n    //attributes here\n\n    Type methodName();  //no method code\n}\n\n// interfaces can extend interfaces\npublic interface OtherInterface extends InterfaceName {\n    //attributes here\n    Type methodName();  // inherited from extended interface\n    Type otherMethod();  // defined in the interface\n}\n\nclass ClassName implements Interface1, Interface2 {...}\n

Types of Interfaces:

Since Java 1.8 interfaces can implements also static methods.

"},{"location":"languages/java/java.html#enumerations","title":"Enumerations","text":"

Enums are used to restrict the type of data to a set of the possible constant values. Enums are classes which constructor is private by default. It's still possible to create a custom constructor to add values.

Java
enum enumName {\n    value1,\n    value2,\n    ... ,\n    valueN;\n}\n\n//definition of an enumeration w/ custom constructor for valorization\n//constructor is not usable outside enum definition\nenum enumName {\n    value1(value),  //call constructor to valorize\n    value2(value),\n    ... ,\n    valueN(value);\n\n    private Type value;\n\n    Type enumName(Type parameter) {\n        this.value = parameter;\n    }\n\n    //getters are allowed, the values is a constant --> no setters\n    public Type getValue(){\n        return this.value;\n    }\n}\n\nenumName variable;  //creation of a variable of type enumName\n
"},{"location":"languages/java/java.html#anonymous-classes","title":"Anonymous Classes","text":"

Anonymous classes make the code more concise. They enable to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Useful if is needed a local class that is used once.

Java
AnonymousClass objectName = new AnonymousClass(Type parameter, ...) {\n\n    // attributes\n\n    // methods\n};\n
"},{"location":"languages/java/java.html#cloning","title":"Cloning","text":"Java
class ClassName implements Clonable {\n\n}\n
"},{"location":"languages/java/java.html#generics","title":"Generics","text":"Java
// WARNING: T is not instantiable, new t(), new t[] are INVALID\npublic class GenericClass<T> {\n    private T generic;\n\n    public GenericClass() { }\n    public GenericClass(T data){\n        this.generic = data;\n    }\n\n    public T getGeneric() {\n        return generic;\n    }\n\n    public void setGeneric(T data) {\n        this. generic = data;\n    }\n\n}\n\nGenericClass<Type> obj = new GenericClass<>();\nGenericClass<Type>[] obj = new GenericClass<>[];  // invalid\n
"},{"location":"languages/java/java.html#multiple-generics","title":"Multiple Generics","text":"Java
public class GenericClass<T1, T2, ...> { }  // number of generic types is not limited\n
"},{"location":"languages/java/java.html#parameters-constraints","title":"Parameters Constraints","text":"

Specify an interface or class that the generic type must implement/inherit.

Java
public class GenericClass<T extends Interface1 & Interface2> { }\npublic class GenericClass<T1 extends Interface1 & Interface2, T2 extends Class1> { }\npublic class GenericClass<T extends Class1> { }\n
"},{"location":"languages/java/java.html#generic-methods","title":"Generic Methods","text":"Java
public class ClassName{\n\n    public <T> methodName() {\n        // code here\n        return <T>_obj\n    }\n\n    public <T> methodName(T obj) {\n        // code here\n        return return <T>_obj\n    }\n}\n\npublic class GenericClass<S> {\n\n    public <T> methodName() {\n        // code here\n        return <T>_obj\n    }\n\n    public <T> methodName(T obj) {\n        // code here\n        return return <T>_obj\n    }\n}\n\nobj.<Type>methodName();  // generic method call\n
"},{"location":"languages/java/java.html#file-io","title":"File I/O","text":""},{"location":"languages/java/java.html#text-files","title":"Text Files","text":""},{"location":"languages/java/java.html#writing-on-a-file","title":"Writing on a file","text":"Java
// opening/creating the file for writing\nPrintWriter outStream = null;  // output stream creation\ntry{\n    outStream = new PrintWriter(filename);  // file-stream binding, file will be empty (creates or overwrites file)\n    outStream = new PrintWriter(new FileOutputStream(filename, true));  // stream for appending text\n} catch (FileNotFoundException e) {\n    // code here\n}\n\n// write on the file\noutStream.print(\"\");\noutStream.println(\"\");\n\noutStream.close()  // close stream and write buffer contents.\n

Note: writing operations do not write directly on the file. The sent data is collected in a buffer. When the buffer is full the data is written in the file. This is called buffering and is used to append up operations.

"},{"location":"languages/java/java.html#reading-from-a-file","title":"Reading from a file","text":"Java
Filereader filereader = new Filereader(\"filename\");  //open the file\nScanner scanner = new Scanner(filereader);  //scanner for the file\n\n\nScanner inStream = null;\ntry{\n    inStream = new Scanner(File(filename));\n} catch (FileNotFoundException e) {\n    // code here\n}\n\ninStream.hasNext();  // true if there is data to be read with next()\ninStream.hasNextDouble();  // true if there is data to be read with nextDouble()\ninStream.hasNextInt();  // true if there is data to be read with nextInt()\ninStream.hasNextLine();  // true if there is data to be read with nextLine()\n\n\nBufferedReader inStream = null;\ntry {\n    inStream = new BufferReader(new Filereader(filename));  //buffed reader for file\n} catch (FileNotFoundException e) {\n    // code here\n}\n\n// BufferedReader Methods\npublic String readLine() throws IOException  // return file line or null (file has ended)\npublic int read() throws IOException  // return an integer representing a char or -1 (file has ended)\npublic long skip(n) throws IOException  // skip n characters\npublic void close() throws IOException  // closes the stream\n
"},{"location":"languages/java/java.html#file-class","title":"File() class","text":"

The File class is an abstraction of the file and it's path. The abstraction is independent from the OS.

Java
File(\"path/to/file\")  // UNIX like path\nFile(\"path\\\\to\\\\file\")  // Windows path\n\nfile.canRead()  // true if file is readable\nfile.canWrite()  // true if file is writable\nfile.delete()  // true if file has been deleted\nfile.exists()  // check if exist a file with the filename used in the constructor\nfile.getName()  // returns the filename\nfile.getPath()  // returns the file's path\nfile.length()  // file length in bytes\n
"},{"location":"languages/java/java.html#binary-files","title":"Binary Files","text":""},{"location":"languages/java/java.html#writing-to-a-binary-file","title":"Writing to a binary file","text":"Java
ObjectOutputStream outStream;\ntry {\n    outStream = new ObjectOutputStream(new FileOutputSteam(filename));\n    // write operations here since they can cause IOException\n} catch (FileNotFoundException e) {\n\n} catch (IOException e){\n\n}\n\n// ObjectOutputStream Methods\npublic ObjectOutputStream(OutputStream streamObj) throws IOException, FileNotFoundException\npublic ObjectOutputStream(new FileOutputStream(filename)) throws IOException, FileNotFoundException\npublic ObjectOutputStream(new FileOutputStream(new File(filename))) throws IOException, FileNotFoundException\npublic void writeInt(int n) throws IOException\npublic void writeLong(long n) throws IOException\npublic void writeDouble(double x) throws IOException\npublic void writeFloat(float x) throws IOException\npublic void writeChar(int c) throws IOException\npublic void writeChar(char c) throws IOException\npublic void writeBoolean(boolean b) throws IOException\npublic void writeUTF(String s) throws IOException\npublic void writeObject(Object obj) throws IOException, NotSerializableException, InvalidClassException  // Object must be serializable\npublic void close()\n
"},{"location":"languages/java/java.html#reading-from-a-binary-file","title":"Reading from a binary file","text":"Java
ObjectInputStream inStream;\ntry {\n    inStream = new ObjectInputStream(new FileinputSteam(filename));\n} catch (FileNotFoundException e) {\n\n} catch (IOException e){\n\n}\n\ntry {\n    while(true){\n        // read fom file\n    }\n} catch (EOFException e) {  // thrown when and of file has been reached\n    // do nothing, only used to stop the cycle\n}\n\n// ObjectOutputStream Methods\npublic ObjectOutputStream(InputStream streamObj) throws IOException, FileNotFoundException\npublic ObjectOutputStream(new FileInputStream(filename)) throws IOException, FileNotFoundException\npublic ObjectOutputStream(new FileInputStream(new File(filename))) throws IOException, FileNotFoundException\npublic void readInt(int n) throws IOException\npublic void readLong(long n) throws IOException\npublic void readDouble(double x) throws IOException\npublic void readFloat(float x) throws IOException\npublic void readChar(int c) throws IOException\npublic void readChar(char c) throws IOException\npublic void readBoolean(boolean b) throws IOException\npublic void readUTF(String s) throws IOException\npublic void readObject(Object obj) throws IOException, NotSerializableException, InvalidClassException  // Object must be serializable\npublic void close()\n
"},{"location":"languages/java/java.html#object-array-io-with-binary-files-serialization","title":"Object & Array I/O with Binary Files (Serialization)","text":"

Needed for a class to be serializable:

An array is serializable if it's base type is a serializable object.

Java
SerializableObject[] array = (SerializableObject[])inStream.readObject();  // read returns Object, cast needed\n
"},{"location":"languages/java/java.html#functional-programming-in-java","title":"Functional Programming in Java","text":""},{"location":"languages/java/java.html#functional-interfaces","title":"Functional Interfaces","text":"

Functional interfaces provide target types for lambda expressions.

General purpose @functionalInterfaces:

Java
// takes input, performs actions, return boolean\npublic interface Predicate<T> {\n    boolean test(T t);\n}\n\n// takes input, performs action, no output returned\npublic interface Consumer<T> {\n    void accept(T t);\n}\n\n// takes no input, performs action, returns an output\npublic interface Supplier<T> {\n    T get();\n}\n\n// takes T as input, performs action, returns R as output\npublic interface Function<T, R> {\n    R apply(T t);\n}\n
"},{"location":"languages/java/java.html#streams","title":"Streams","text":"

In java a stream is a Monad. Monads allow the programmer to compose a sequence of operations, similar to a pipeline chaining expressions together.

The features of Java stream are:

Intermediate Operations:

Terminal Operations:

"},{"location":"languages/java/java.html#lambda-expressions","title":"Lambda Expressions","text":"

Usable only by a @FunctionalInterface's method or a method of a stream.

Java
lambda operator -> body;\n\n//zero parameter\n() -> body;\n\n//one parameter\n(p) -> body\n\n// multiple parameter\n(p1, p2, ...) -> body\n
"},{"location":"languages/java/spring/pom.xml.html","title":"pom.xml","text":"

File specifing project dependencies.

XML
<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>major.minor.patch</modelVersion>\n\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>major.minor.patch.RELEASE</version>\n        <relativePath/> <!-- lookup parent from repository -->\n    </parent>\n\n    <groupId>base_package</groupId>\n    <artifactId>Project_Name</artifactId>\n    <version>major.minor.patch</version>\n    <name>Project_Name</name>\n    <description>...</description>\n\n    <properties>\n        <java.version>11</java.version>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-jpa</artifactId>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <plugins>\n            <plugin>\n                <groupId>org.springframework.boot</groupId>\n                <artifactId>spring-boot-maven-plugin</artifactId>\n            </plugin>\n        </plugins>\n    </build>\n\n</project>\n
"},{"location":"languages/java/spring/spring-project.html","title":"Spring Project","text":""},{"location":"languages/java/spring/spring-project.html#libs","title":"Libs","text":""},{"location":"languages/java/spring/spring-project.html#applicationproperties","title":"application.properties","text":"INI
spring.datasource.url=DB_url\nspring.datasource.username=user\nspring.datasource.password=password\n\nspring.jpa.show-sql=true\n\nserver.port=server_port\n
"},{"location":"languages/java/spring/spring-project.html#package-entities","title":"Package entities","text":"

Model of a table of the DB

Java
package <base_package>.entities;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity  // set as DB Entity (DB record Java implementation)\npublic class Entity {\n\n    @Id  // set as Primary Key\n    @GeneratedValue(strategy = GenerationType.IDENTITY)  // id is autoincremented by the DB\n    private int id;\n\n    // no constructor (Spring requirement)\n\n    // table columns attributes\n\n    // getters & setters\n\n   // toString()\n}\n
"},{"location":"languages/java/spring/spring-project.html#package-dal","title":"Package dal","text":"

Spring Interface for DB connection and CRUD operations.

Java
package <base_package>.dal  // or .repository\n\nimport org.springframework.data.repository.JpaRepository;\nimport org.springframework.data.repository.Query;\nimport org.springframework.data.repository.query.Param;\n\n// interface for spring Hibernate JPA\n// CrudRepository<Entity, PK_Type>\npublic interface IEntityDAO extends JpaRepository<Entity, Integer> {\n\n    // custom query\n    @Query(\"FROM <Entity> WHERE param = :param\")\n    Type query(@Param(\"param\") Type param);\n}\n
"},{"location":"languages/java/spring/spring-project.html#package-services","title":"Package services","text":"

Interfaces and method to access the Data Access Layer (DAL).

In IEntityService.java:

Java
package <base_package>.services;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\n\nimport <base_package>.Entity;\nimport <base_package>.IEntityRepository;\n\n// CRUD method implemented on Entity\npublic interface IEntityService {\n\n    String FIND_ALL = \"SELECT * FROM <table>\"\n    String FIND_ONE = \"SELECT * FROM <table> WHERE id = ?\"\n\n    List<Entity> findAll();\n    Entity findOne(int id);\n    void addEntity(Entity e);\n    void updateEntity(int id, Entity e);\n    void deleteEntity(Entity e);\n    void deleteEntity(int id);\n\n}\n

In EntityService.java:

Java
package <base_package>.services;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport <base_package>.entities.Entity;\nimport <base_package>.repos.ILibriRepository;\n\n// implementation of IEntityService\n@Service\npublic class EntityService implements IEntityService {\n\n    @Autowired  // connection to db (obj created by spring as needed: Inversion Of Control)\n    private IEntityDAO repo;\n\n    @Override\n    public List<Entity> findAll() {\n        return repo.findAll();\n    }\n\n    @Override\n    public Entity findOne(int id) {\n        return repo.findById(id).get();\n    }\n\n    @Override\n    public void addEntity(Entity e) {\n        repo.save(e);\n    }\n\n    @Override\n    public void updateEntity(int id, Entity e) {\n    }\n\n    @Override\n    public void deleteEntity(Entity e) {\n    }\n\n    @Override\n    public void deleteEntity(int id) {\n    }\n\n    // custom query\n    Type query(Type param) {\n        return repo.query(param);\n    }\n}\n
"},{"location":"languages/java/spring/spring-project.html#package-integration","title":"Package integration","text":"

REST API routes & endpoints to supply data as JSON.

Java
package <base_package>.integration;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport <base_package>.entities.Entity;\nimport <base_package>.services.IEntityService;\n\n@RestController  // returns data as JSON\n@RequestMapping(\"/api\")  // controller route\npublic class EntityRestCtrl {\n\n    @Autowired  // connection to service (obj created by spring as needed: Inversion Of Control)\n    private IEntityService service;\n\n    @GetMapping(\"entities\")  // site route\n    public List<Entity> findAll(){\n        return service.findAll();\n    }\n\n    @GetMapping(\"/entities/{id}\")\n    public Entity findOne(@PathVariable(\"id\") int id) {  // use route variable\n        return service.findOne(id);\n    }\n\n    @PostMapping(\"/entities\")\n    public void addEntity(@RequestBody Entity e) {  // added entity is in the request body\n        return service.addEntity(e)\n    }\n\n    // PUT / PATCH -> updateEntity(id, e)\n\n    // DELETE -> deleteEntity(id)\n}\n
"},{"location":"languages/java/web/servlet.html","title":"Servlet","text":"

A Java servlet is a Java software component that extends the capabilities of a server. Although servlets can respond to many types of requests, they most commonly implement web containers for hosting web applications on web servers and thus qualify as a server-side servlet web API.

"},{"location":"languages/java/web/servlet.html#basic-structure","title":"Basic Structure","text":"Java
package <package>;\n\nimport java.io.IOException;\nimport javax.servlet.ServletException;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n@WebServlet(\"/route\")\npublic class <className> extends HttpServlet {\n    private static final long serialVersionUID = 1L;\n\n    /** handle get request */\n    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n\n        // GET REQUEST: load and display page (forward to JSP)\n        // OPTIONAL: add data to request (setAttribute())\n\n    }\n\n    /** handle post request */\n    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n\n        // POST REQUEST: add stuff to DB, page, ...\n\n        doGet(request, response);  // return same page with new  content added (default case)\n    }\n}\n
"},{"location":"languages/java/web/servlet.html#servlet-instructions","title":"Servlet Instructions","text":"Java
request.getParameter()  // read request parameter\n\nresponse.setContentType(\"text/html\");  // to return HTML in the response\n\nresponse.getWriter().append(\"\");  //append content to the http response\n\nrequest.setAttribute(attributeName, value);  // set http attribute of the request\nrequest.getRequestDispatcher(\"page.jsp\").forward(request, response);  // redirect the request to another page\n
"},{"location":"languages/javascript/ajax.html","title":"AJAX","text":"

AJAX: Asynchronous JavaScript and XML

AJAX Interaction:

  1. An event occurs in a web page (the page is loaded, a button is clicked)
  2. 2.An XMLHttpRequest object is created by JavaScript
  3. 3.The XMLHttpRequest object sends a request to a web server
  4. 4.The server processes the request
  5. 5.The server sends a response back to the web page
  6. 6.The response is read by JavaScript
  7. 7.Proper action (like page update) is performed by JavaScript
"},{"location":"languages/javascript/ajax.html#xmlhttprequest","title":"XMLHttpRequest","text":"JavaScript
var request = new XMLHttpRequest();\n\nrequest.addEventListener(event, function() {...});\n\nrequest.open(\"HttpMethod\", \"path/to/api\", true);  // third parameter is asynchronicity (true = asynchronous)\nrequest.setRequestHeader(key, value)  // HTTP Request Headers\nrequest.send()\n

To check the status use XMLHttpRequest.status and XMLHttpRequest.statusText.

"},{"location":"languages/javascript/ajax.html#xmlhttprequest-events","title":"XMLHttpRequest Events","text":"

loadstart: fires when the process of loading data has begun. This event always fires first progress: fires multiple times as data is being loaded, giving access to intermediate data error: fires when loading has failed abort: fires when data loading has been canceled by calling abort() load: fires only when all data has been successfully read loadend: fires when the object has finished transferring data always fires and will always fire after error, abort, or load timeout: fires when progression is terminated due to preset time expiring readystatechange: fires when the readyState attribute of a document has changed

Alternative XMLHttpRequest using onLoad:

JavaScript
var request = new XMLHttpRequest();\nrequest.open('GET', 'myservice/username?id=some-unique-id');\nrequest.onload = function(){\n    if(request.status ===200){\n        console.log(\"User's name is \"+ request.responseText);\n    } else {\n        console.log('Request failed.  Returned status of '+ request.status);\n    }\n};\nrequest.send();\n

Alternative XMLHttpRequest using readyState:

JavaScript
var request = new XMLHttpRequest(),  method ='GET',  url ='https://developer.mozilla.org/';\n\nrequest.open(method, url, true);\nrequest.onreadystatechange = function(){\n    if(request.readyState === XMLHttpRequest.DONE && request.status === 200){\n        console.log(request.responseText);\n    }\n};\nrequest.send();\n

XMLHttpRequest.readyState values: 0 UNSENT: Client has been created. open() not called yet. 1 OPENED: open() has been called. 2 HEADERS_RECEIVED: send() has been called, and headers and status are available. 3 LOADING: Downloading; responseText holds partial data. 4 DONE: The operation is complete.

"},{"location":"languages/javascript/ajax.html#xmlhttprequest-browser-compatibility","title":"XMLHttpRequest Browser compatibility","text":"

Old versions of IE don't implement XMLHttpRequest. You must use the ActiveXObject if XMLHttpRequest is not available

JavaScript
var request =window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');\n\n// OR\n\nvar request;\nif(window.XMLHttpRequest){\n    // code for modern browsers  \n    request = new XMLHttpRequest();\n} else {\n    // code for old IE browsers\n    request = new ActiveXObject('Microsoft.XMLHTTP');\n}\n
"},{"location":"languages/javascript/ajax.html#status-error-handling","title":"Status & Error Handling","text":"

Always inform the user when something is loading. Check the status and give feedback (a loader or message) Errors and responses need to be handled. There is no guarantee that HTTP requests will always succeed.

"},{"location":"languages/javascript/ajax.html#cross-domain-policy","title":"Cross Domain Policy","text":"

Cross domain requests have restrictions.

Examples of outcome for requests originating from: http://store.company.com/dir/page.htmlCross-origin

URL Outcome Reason http://store.company.com/dir2/other.html success http://store.company.com/dir/inner/other.html success https://store.company.com/secure.html failure Different protocol http://store.company.com:81/dir/other.html failure Different port http://news.company.com/dir/other.html failure Different host"},{"location":"languages/javascript/dom.html","title":"Document Object Model (DOM)","text":"

The Document Object Model is a map of the HTML document. Elements in an HTML document can be accessed, changed, deleted, or added using the DOM. The document object is globally available in the browser. It allows to access and manipulate the DOM of the current web page.

"},{"location":"languages/javascript/dom.html#dom-access","title":"DOM Access","text":""},{"location":"languages/javascript/dom.html#selecting-nodes-from-the-dom","title":"Selecting Nodes from the DOM","text":"

getElementById() and querySelector() return a single element. getElementsByClassName(), getElementsByTagName(), and querySelectorAll() return a collection of elements.

JavaScript
Javascript\n// By Id\nvar node = document.getElementById('id');\n\n// By Tag Name\nvar nodes = document.getElementsByTagName('tag');\n\n// By Class Name\nvar nodes = document.getElementsByClassName('class');\n\n// By CSS Query\nvar node = document.querySelector('css-selector');\nvar nodes = document.querySelectorAll('css-selector');\n
"},{"location":"languages/javascript/dom.html#manipulating-the-dom","title":"Manipulating the DOM","text":""},{"location":"languages/javascript/dom.html#manipulating-a-nodes-attributes","title":"Manipulating a node's attributes","text":"

It's possible access and change the attributes of a DOM node using the dot notation.

JavaScript
// Changing the src of an image:\nvar image = document.getElementById('id');\nvar oldImageSource = image.src;\nimage.src = 'image-url';\n\n//Changing the className of a DOM node:\nvar node = document.getElementById('id');\nnode.className = 'new-class';\n
"},{"location":"languages/javascript/dom.html#manipulating-a-nodes-style","title":"Manipulating a node's style","text":"

It's possible to access and change the styles of a DOM nodes via the style property. CSS property names with a - must be camelCased and number properties must have a unit.

CSS
body {\n    color: red;\n    background-color: pink;\n    padding-top: 10px;\n}\n
JavaScript
var pageNode = document.body;\npageNode.style.color = 'red';\npageNode.style.backgroundColor = 'pink';\npageNode.style.paddingTop = '10px';\n
"},{"location":"languages/javascript/dom.html#manipulating-a-nodes-contents","title":"Manipulating a node's contents","text":"

Each DOM node has an innerHTML attribute. It contains the HTML of all its children.

JavaScript
var pageNode = document.body;\nconsole.log(pageNode.innerHTML);\n\n// Set innerHTML to replace the contents of the node:\npageNode.innerHTML = \"<h1>Oh, no! Everything is gone!</h1>\";\n\n// Or add to innerHTML instead:\npageNode.innerHTML += \"P.S. Please do write back.\";\n

To change the actual text of a node, textContent may be a better choice:

innerHTML:

textContent:

"},{"location":"languages/javascript/dom.html#reading-inputs-from-a-form","title":"Reading Inputs From A Form","text":"

In page.html:

HTML
<input type=\"\" id=\"identifier\" value=\"\">\n

In script.js:

JavaScript
var formNode = document.getElementById(\"Identifier\");\nvar value = formNode.value;\n
"},{"location":"languages/javascript/dom.html#creating-removing-dom-nodes","title":"Creating & Removing DOM Nodes","text":"

The document object also allows to create new nodes from scratch.

JavaScript
// create node\ndocument.createElement('tagName');\ndocument.createTextNode('text');\n\ndomNode.appendChild(childToAppend);  // insert childTaAppend after domNode\n\n// insert node before domNode\ndomNode.insertBefore(childToInsert, domnode);\ndomNode.parentNode.insertBefore(childToInsert, nodeAfterChild);\n\n// remove a node\ndomNode.removeChild(childToRemove);\nnode.parentNode.removeChild(node);\n

Example:

JavaScript
var body = document.body;\n\nvar newImg = document.createElement('img');\nnewImg.src = 'http://placekitten.com/400/300';\nnewImg.style.border = '1px solid black';\n\nbody.appendChild(newImg);\n\nvar newParagraph = document.createElement('p');\nvar newText = document.createTextNode('Squee!');\n\nnewParagraph.appendChild(newText);\n\nbody.appendChild(newParagraph);\n
"},{"location":"languages/javascript/dom.html#creating-dom-nodes-with-constructor-functions","title":"Creating DOM Nodes with Constructor Functions","text":"JavaScript
function Node(params) {\n    this.node = document.createElement(\"tag\");\n\n    this.node.attribute = value;\n\n    // operations on the node\n\n    return this.node;\n}\n\nvar node = Node(params);\ndomElement.appendChild(node);\n
"},{"location":"languages/javascript/events-animation.html","title":"Events & Animation","text":""},{"location":"languages/javascript/events-animation.html#events","title":"Events","text":"

Event Types:

"},{"location":"languages/javascript/events-animation.html#managing-event-listeners","title":"Managing Event Listeners","text":"JavaScript
var domNode = document.getElementById(\"id\");\n\nvar onEvent = function(event) {  // parameter contains info on the triggered event\n    event.preventDefault();  // block execution of default action\n    // logic here\n}\n\ndomNode.addEventListener(eventType, callback);\ndomNode.removeEventListener(eventType, callback);\n
"},{"location":"languages/javascript/events-animation.html#bubbling-capturing","title":"Bubbling & Capturing","text":"

Events in Javascript propagate through the DOM tree.

Bubbling and Capturing What Is Event Bubbling in JavaScript? Event Propagation Explained

"},{"location":"languages/javascript/events-animation.html#dispatching-custom-events","title":"Dispatching Custom Events","text":"

Event Options:

JavaScript
let event = new Event(type [,options]);  // create the event, type can be custom\nlet event = new CustomEvent(type, { detail: /* custom data */ });  // create event w/ custom data\ndomNode.dispatchEvent(event);  // launch the event\n

"},{"location":"languages/javascript/events-animation.html#animation","title":"Animation","text":"

The window object is the assumed global object on a page.

Animation in JavascriptThe standard way to animate in JS is to use window methods. It's possible to animate CSS styles to change size, transparency, position, color, etc.

JavaScript
//Calls a function once after a delay\nwindow.setTimeout(callbackFunction, delayMilliseconds);\n\n//Calls a function repeatedly, with specified interval between each call\nwindow.setInterval(callbackFunction, delayMilliseconds);\n\n//To stop an animation store the timer into a variable and clear it\nwindow.clearTimeout(timer);\nwindow.clearInterval(timer);\n\n// execute a callback at each frame\nwindow.requestAnimationFrame(callbackFunction);\n
"},{"location":"languages/javascript/events-animation.html#element-position-dimensions","title":"Element Position & dimensions","text":"

StackOverflow Wrong dimensions at runtime

JavaScript
> console.log(document.getElementById('id').getBoundingClientRect());\nDOMRect {\n    bottom: 177,\n    height: 54.7,\n    left: 278.5,\u200b\n    right: 909.5,\n    top: 122.3,\n    width: 631,\n    x: 278.5,\n    y: 122.3,\n}\n
"},{"location":"languages/javascript/javascript.html","title":"JavaScript","text":""},{"location":"languages/javascript/javascript.html#basics","title":"Basics","text":""},{"location":"languages/javascript/javascript.html#notable-javascript-engines","title":"Notable javascript engines","text":""},{"location":"languages/javascript/javascript.html#comments","title":"Comments","text":"JavaScript
//single line comment\n/*multiline comment*/\n
"},{"location":"languages/javascript/javascript.html#file-header","title":"File Header","text":"JavaScript
/**\n * @file filename.js\n * @author author's name\n * purpose of file\n *\n * detailed explanation of what the file does on multiple lines\n */\n
"},{"location":"languages/javascript/javascript.html#modern-mode","title":"Modern Mode","text":"

If located at the top of the script the whole script works the \u201cmodern\u201d way (enables post-ES5 functionalities).

JavaScript
\"use strict\"\n\n// script contents\n
"},{"location":"languages/javascript/javascript.html#pop-up-message","title":"Pop-Up message","text":"

Interrupts script execution until closure, to be avoided

JavaScript
alert(\"message\");\n
"},{"location":"languages/javascript/javascript.html#print-message-to-console","title":"Print message to console","text":"

console.log(value);

"},{"location":"languages/javascript/javascript.html#variables","title":"Variables","text":""},{"location":"languages/javascript/javascript.html#declaration-initialization","title":"Declaration & Initialization","text":"

var vs let vs const

Variable names can only contain numbers, digits, underscores and $. Variable names are camelCase.

let: Block-scoped; access to variable restricted to the nearest enclosing block. var: Function-scoped

let variable1 = value1, variable2 = value2; var variable1 = value1, variable2 = value2;

"},{"location":"languages/javascript/javascript.html#scope","title":"Scope","text":"

Variable declared with let are in local to the code block in which are declared. Variable declared with var are local only if declared in a function.

JavaScript
function func(){\n    variable = value;  // implicitly declared as a global variable\n    var variable = value;  // local variable\n}\n\nvar a = 10;  // a is 10\nlet b = 10;  // b is 10\n{\n    var x = 2, a = 2;  // a is 2\n    let y = 2, b = 2;  // b is 2\n}\n// a is 2, b is 10\n// x can NOT be used here\n// y CAN be used here\n
"},{"location":"languages/javascript/javascript.html#constants","title":"Constants","text":"

Hard-coded values are UPPERCASE and snake_case, camelCase otherwise. const CONSTANT = value;

"},{"location":"languages/javascript/javascript.html#data-types","title":"Data Types","text":"

Number, String, Boolean, etc are built-in global objects. They are not types. Do not use them for type checking.

"},{"location":"languages/javascript/javascript.html#numeric-data-types","title":"Numeric data types","text":"

Only numeric type is number.

JavaScript
let number = 10;  //integer numbers\nnumber = 15.7;  //floating point numbers\nnumber = Infinity;  //mathematical infinity\nnumber = - Infinity;\nnumber = 1234567890123456789012345678901234567890n;  //BigInt, value > 2^53, \"n\" at the end\nnumber = \"text\" / 2;  //NaN --> not a number.\n

Rounding Decimals in JavaScript Decimal.js

Mathematical expression will never cause an error. At worst the result will be NaN.

"},{"location":"languages/javascript/javascript.html#string-data-type","title":"String data type","text":"JavaScript
let string = \"text\";\nlet string$ = 'text';\nlet string_ = `text ${expression}`;  //string interpolation (needs backticks)\n\nstring.length;  // length of the string\nlet char = string.charAt(index);  // extraction of a single character by position\nstring[index]; // char extraction by property access\nlet index = string.indexOf(substring);  // start index of substring in string\n

Property access is unpredictable:

"},{"location":"languages/javascript/javascript.html#slice-vs-substring-vs-substr","title":"Slice vs Substring vs Substr","text":"

If the parameters to slice are negative, they reference the string from the end. Substring and substr doesn\u00b4t.

JavaScript
string.slice(begin [, end]);\nstring.substring(from [, to]);\nstring.substr(start [, length]);\n
"},{"location":"languages/javascript/javascript.html#boolean-data-type","title":"Boolean data type","text":"JavaScript
let boolean = true;\nlet boolean_ = false;\n
"},{"location":"languages/javascript/javascript.html#null-data-type","title":"Null data type","text":"JavaScript
let _ = null;\n
"},{"location":"languages/javascript/javascript.html#undefined","title":"Undefined","text":"JavaScript
let $;  //value is \"undefined\"\n$ = undefined;\n
"},{"location":"languages/javascript/javascript.html#typeof","title":"Typeof()","text":"JavaScript
typeof x;  //returns the type of the variable x as a string\ntypeof(x);  //returns the type of the variable x as a string\n

The result of typeof null is \"object\". That's wrong. It is an officially recognized error in typeof, kept for compatibility. Of course, null is not an object. It is a special value with a separate type of its own. So, again, this is an error in the language.

"},{"location":"languages/javascript/javascript.html#type-casting","title":"Type Casting","text":"JavaScript
String(value);  //converts value to string\n\nNumber(value);  //converts value to a number\nNumber(undefined);  //--> NaN\nNumber(null);  //--> 0\nNumber(true);  //--> 1\nNumber(false);  //--> 0\nNumber(String);  //Whitespace from the start and end is removed. If the remaining string is empty, the result is 0. Otherwise, the number is \"read\" from the string. An error gives NaN.\n\nBoolean(value);  //--> true\nBoolean(0); //--> false\nBoolean(\"\");  //--> false\nBoolean(null);  //--> false\nBoolean(undefined);  //--> false\nBoolean(NaN);  //--> false\n\n\n//numeric type checking the moronic way\ntypeof var_ == \"number\";  // typeof returns a string with the name of the type\n
"},{"location":"languages/javascript/javascript.html#type-checking","title":"Type Checking","text":"JavaScript
isNaN(var);  // converts var in number and then check if is NaN\n\nNumber(\"A\") == NaN;  //false ?!?\n
"},{"location":"languages/javascript/javascript.html#dangerous-stupid-implicit-type-casting","title":"Dangerous & Stupid Implicit Type Casting","text":"JavaScript
2 + 'text';  //\"2text\", implicit conversion and concatenation\n1 + \"1\";  //\"11\", implicit conversion and concatenation\n\"1\" + 1;  //\"11\", implicit conversion and concatenation\n+\"1\";  //1, implicit conversion\n+\"text\";  // NaN\n1 == \"1\";  //true\n1 === \"1\";  //false\n1 == true;  //true\n0 == false;  //true\n\"\" == false;  //true\n
"},{"location":"languages/javascript/javascript.html#operators","title":"Operators","text":"Operator Operation (...) grouping a.b member access new a(...) object creation a in b membership"},{"location":"languages/javascript/javascript.html#mathematical-operators","title":"Mathematical Operators","text":"Operator Operation a + b addition a - b subtraction a * b multiplication a ** b a^b a / b division a % b modulus"},{"location":"languages/javascript/javascript.html#unary-increment-operators","title":"Unary Increment Operators","text":"Operator Operation --variable prefix decrement ++variable prefix increment variable-- postfix decrement variable++ postfix increment"},{"location":"languages/javascript/javascript.html#logical-operators","title":"Logical Operators","text":"Operator Operation a && b logical AND a || b logical OR !a logical NOT"},{"location":"languages/javascript/javascript.html#comparison-operators","title":"Comparison Operators","text":"Operator Operation a < b less than a <= b less or equal to a > b greater than a >= b greater or equal to a == b equality a != b inequality a === b strict equality a !== b strict inequality"},{"location":"languages/javascript/javascript.html#bitwise-logical-operators","title":"Bitwise Logical Operators","text":"Operator Operation a & b bitwise AND a | b bitwise OR a ^ b bitwise XOR ~a bitwise NOT a << b bitwise left shift a >> b bitwise right shift a >>> b bitwise unsigned right shift"},{"location":"languages/javascript/javascript.html#compound-operators","title":"Compound Operators","text":"Operator Operation a += b a = a + b a -= b a = a - b a *= b a = a * b a **= b a = a ** b a /= b a = a / b a %= b a = a % b a <<= b a = a << b a >>= b a = a >> b a >>>= b a = a >>> b a &= b a = a & b a ^= b a = a ^ b a |= b a = a ! b"},{"location":"languages/javascript/javascript.html#decision-statements","title":"Decision Statements","text":""},{"location":"languages/javascript/javascript.html#if-else","title":"IF-ELSE","text":"JavaScript
if (condition) {\n    //code here\n} else {\n    //code here\n}\n
"},{"location":"languages/javascript/javascript.html#if-else-multi-branch","title":"IF-ELSE Multi-Branch","text":"JavaScript
if (condition) {\n    //code here\n} else if (condition) {\n    //code here\n} else {\n    //code here\n}\n
"},{"location":"languages/javascript/javascript.html#ternary-operator","title":"Ternary Operator","text":"

condition ? <expr1> : <expr2>;

"},{"location":"languages/javascript/javascript.html#switch-statement","title":"Switch Statement","text":"JavaScript
switch (expression) {\n    case expression:\n        //code here\n        break;\n\n    default:\n        //code here\n        break;\n}\n
"},{"location":"languages/javascript/javascript.html#loops","title":"Loops","text":""},{"location":"languages/javascript/javascript.html#while-loop","title":"While Loop","text":"JavaScript
while (condition) {\n    //code here\n}\n
"},{"location":"languages/javascript/javascript.html#do-while-loop","title":"Do-While Loop","text":"JavaScript
do {\n    //code here\n} while (condition);\n
"},{"location":"languages/javascript/javascript.html#for-loop","title":"For Loop","text":"JavaScript
// basic for\nfor (begin; condition; step) { }\n\nfor (var variable in iterable) { }  // for/in statement loops through the properties of an object\nfor (let variable in iterable) { }  // instantiate a new variable at each iteration\n\n// for/of statement loops through the values of an iterable objects\n// for/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.\nfor (var variable of iterable) { }\nfor (let variable of iterable) { }  // instantiate a new variable at each iteration\n\n// foreach (similar to for..of)\niterable.forEach(() => { /* statements */ });\n
"},{"location":"languages/javascript/javascript.html#break-continue-statements","title":"Break & Continue statements","text":"

break; exits the loop. continue; skip to next loop cycle.

JavaScript
label: for(begin; condition; step) {\n    //code here\n}\n\nbreak label;  //breaks labelled loop and nested loops inside it\n
"},{"location":"languages/javascript/javascript.html#arrays","title":"Arrays","text":"JavaScript
let array = [];  // empty array\nlet array = [\"text\", 3.14, [1.41]];  // array declaration and initialization\n\narray.length;  // number of items in the array\narray[index];  // access to item by index\narray[index] = item; // change or add item by index\n\narray.push(item);  //add item to array\narray.pop();  // remove and return last item\n\narray.join(\"separator\");  // construct a string from the items of the array, separated by SEPARATOR\narray.find(item => condition); // returns the value of the first element in the provided array that satisfies the provided testing function\narray.fill(value, start, end);  // fills an array with the passed value\n\n\n// https://stackoverflow.com/a/37601776\narray.slice(start, end);  // RETURN list of items between indexes start and end-1\narray.splice(start, deleteCount, [items_to_add]);  // remove and RETURN items from array, can append a list of items. IN PLACE operation\n
"},{"location":"languages/javascript/javascript.html#filter-map-reduce","title":"filter() & map(), reduce()","text":"JavaScript
let array = [ items ];\n\n// execute an operation on each item, producing a new array\narray.map(function);\narray.map(() => operation); \n\narray.filter(() => condition);  // return an items only if the condition is true\n\n// execute a reducer function on each element of the array, resulting in single output value\narray.reduce((x, y) => ...);\n
"},{"location":"languages/javascript/javascript.html#spread-operator","title":"Spread Operator (...)","text":"JavaScript
// arrays\nlet array1 = [ 1, 2, 3, 4, 5, 6 ];\nlet array2 = [ 7, 8, 9, 10 ];\nlet copy = [ ...array1 ];  // shallow copy\nlet copyAndAdd = [ 0, ...array1, 7 ];  // insert all values in new array\nlet merge = [ ...array1, ...array2 ];  // merge the arrays contents in new array\n\n// objects\nlet obj = { prop1: value1, prop2: value2 };\nlet clone = { ...obj, prop: value };  // shallow copy, and update copy prop\nlet cloneAndAdd = { prop0: value0, ...obj, prop3: value3 };\n\n// strings\nlet alphabet = \"abcdefghijklmnopqrstxyz\"\nlet letters = [ ...alphabet ];  // alphabet.split(\"\")\n\n//function arguments\nlet func = (arg1 = val1, arg2 = val2) => expression;\nlet args = [ value1, value2 ];\nfunc(arg0, ...args);\n
"},{"location":"languages/javascript/javascript.html#dictionaries","title":"Dictionaries","text":"JavaScript
let dict = { FirstName: \"Chris\", \"one\": 1, 1: \"some value\" };\n\n\n// add new or update property\ndict[\"Age\"] = 42;\n\n// direct property by name\n// because it's a dynamic language\ndict.FirstName = \"Chris\";\n
"},{"location":"languages/javascript/javascript.html#iterating-key-value-pairs","title":"Iterating Key-Value pairs","text":"JavaScript
for(let key in dict) {\n  let value = dict[key];\n\n  // do something with \"key\" and \"value\" variables\n}\n\nObject.keys(dict).forEach(key => { });\n
"},{"location":"languages/javascript/javascript.html#functions","title":"Functions","text":""},{"location":"languages/javascript/javascript.html#jsdoc-documentation-standard","title":"JSDOC documentation standard","text":"JavaScript
/**\n * @param {type} parameter - description\n * @returns {type} parameter - description\n * */\n
"},{"location":"languages/javascript/javascript.html#function-declaration","title":"Function Declaration","text":"JavaScript
// ...args will contain extra parameters (rest argument)\nfunction functionName(parameter=default-value, ...args) {\n    //code here\n    return <expression>;\n}\n
"},{"location":"languages/javascript/javascript.html#default-parameters-old-versions","title":"Default Parameters (old versions)","text":"JavaScript
function functionName(parameters) {\n    if (parameter == undefined) {\n        parameter = value;\n    }\n\n    //code here\n    return <expression>;\n}\n
"},{"location":"languages/javascript/javascript.html#function-expressions","title":"Function Expressions","text":"JavaScript
let functionName = function(parameters) {\n    //code here\n    return expression;\n}\n
"},{"location":"languages/javascript/javascript.html#arrow-functions","title":"Arrow Functions","text":"JavaScript
(input) => { /* statements */ }\n(input) => expression;\ninput => expression;  // parenthesis are optional\n() => expression;  // no parameters syntax\n\n// variants\nlet func = (input) => {\n    // code here\n};\n\nlet func = (input) => expression;\nlet func = input => expression;\n\nfunc();  // function call\n\n// return object literal\nlet func = (value) => ({property: value});\n
"},{"location":"languages/javascript/javascript.html#object-oriented-programming","title":"Object Oriented Programming","text":"

An object is a collection of related data and/or functionality.

Note: It's not possible to transform a variable in an object simply by using the object assignment.

JavaScript
let variable = value;\n\n// object literal\nlet obj = {\n    property: value,\n    variable,  // same as variable: variable\n    [property]: value  // dynamic prop name\n\n    object: {\n        ...\n    },\n\n    method: function() {\n        // code here\n        this.propertyName;  // reference to object property inside the object\n    }\n\n    method; () => {\n        obj.propertyName;  // this is undefined here, use full object name\n    }\n};\n\n// access to property (non existant properties will return Undefined)\nobj.property;  // dot notation\nobj[\"property\"];  // array notation\n\n// property modification (will add property if missing)\nobj.property = value;  // dot notation\nobj[\"property\"] = value;  // array notation\n\nobj.func(); //method access\n\ndelete obj.propertyName;  // delete property\n\nObject.keys(obj);  // list of all property names\nObject.entries(obj);  // list contents as key-value pairs\n
"},{"location":"languages/javascript/javascript.html#constructors-and-object-instances","title":"Constructors and object instances","text":"

JavaScript uses special functions called constructor functions to define and initialize objects and their features. Notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object \u2014 it basically just defines properties and methods.

JavaScript
// constructor function definition\nfunction Class(params) {\n    this.property = param;\n\n    this.method = function(params) { /* code here */ }\n}\n\nlet obj = new Class(params);  // object instantiation\n\nlet obj = new Object();  // creates empty object\nlet obj = new Object({\n    // JSON\n});\n
"},{"location":"languages/javascript/javascript.html#prototypes","title":"Prototypes","text":"

Prototypes are the mechanism by which JavaScript objects inherit features from one another.

JavaScript is often described as a prototype-based language; to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from.

An object's prototype object may also have a prototype object, which it inherits methods and properties from, and so on. This is often referred to as a prototype chain, and explains why different objects have properties and methods defined on other objects available to them. If a method is implemented on an object (and not it's prototype) then only that object will heve that method and not all the ones that come from the same prototype.

JavaScript
// constructor function\nfunction Obj(param1, ...) {\n    this.param1 = param1,\n    ...\n}\n\n// method on the object\nObj.prototype.method = function(params) {\n    // code here (operate w/ this)\n}\n\nlet obj = new Obj(args);  // object instantiation\nobj.method();  // call method from prototype\n
"},{"location":"languages/javascript/javascript.html#extending-with-prototypes","title":"Extending with prototypes","text":"JavaScript
// constructor function\nfunction DerivedObj(param1, param2, ...) {\n    Obj.call(this, param1);  // use prototype constructor\n    this.param2 = param2;\n}\n\n// extend Obj\nDerivedObj.prototype = Object.create(Obj.prototype);\n\n// method on object\nDerivedObj.prototype.method = function() {\n    // code here (operate w/ this)\n}\n\nlet dobj = new DerivedObj(args);  // object instantiation\ndobj.method();  // call method from prototype\n
"},{"location":"languages/javascript/javascript.html#classes-es6","title":"Classes (ES6+)","text":"JavaScript
class Obj {\n    constructor(param1, ...) {\n        this.param1 = param1,\n        ...\n    }\n\n    get param1()  // getter\n    {\n        return this.param1;\n    }\n\n    func() {\n        // code here (operate w/ this)\n    }\n\n    static func() { }  // static method\n\n// object instantiation\nlet obj = new Obj(param1, ...);\nobj.func();  // call method\n
"},{"location":"languages/javascript/javascript.html#extending-with-classes","title":"Extending with Classes","text":"JavaScript
class DerivedObj extends Obj {\n    constructor(param1, param2, ...){\n        super(param1);  // use superclass constructor\n        this.param2 = param2;\n    }\n\n    newFunc() { }\n}\n\nlet dobj = DerivedObj();\ndobj.newFunc();\n
"},{"location":"languages/javascript/javascript.html#deconstruction","title":"Deconstruction","text":""},{"location":"languages/javascript/javascript.html#object-deconstruction","title":"Object deconstruction","text":"JavaScript
let obj = {\n    property: value,\n    ...\n}\n\nlet { var1, var2 } = obj;  // extract values from object into variables\nlet { property: var1, property2 : var2 } = obj;  // extract props in variables w/ specified names\nlet { property: var1, var2 = default_value } = obj;  // use default values if object has less then expected props\n
"},{"location":"languages/javascript/javascript.html#array-deconstruction","title":"Array Deconstruction","text":"JavaScript
let array = [ 1, 2, 3, 4, 5, 6 ];\nlet [first, , third, , seventh = \"missing\" ] = array;  // extract specific values from array\n
"},{"location":"languages/javascript/javascript.html#serialization","title":"Serialization","text":"JavaScript
let object = {\n    // object attributes\n}\n\nlet json = JSON.stringify(object);  // serialize object in JSON\n\nlet json = {  /* JSON */ };\nlet object = JSON.parse(json);  // deserialize to Object\n
"},{"location":"languages/javascript/javascript.html#timing","title":"Timing","text":""},{"location":"languages/javascript/javascript.html#timers","title":"Timers","text":"

Function runs once after an interval of time.

JavaScript
// param1, param2, ... are the arguments passed to the function (IE9+)\nlet timerId = setTimeout(func [, milliseconds, param1, param2, ... ]);  // wait milliseconds before executing the code (params are read at execution time)\n\n// works in IE9\nlet timerId =  setTimeout(function(){\n    func(param1, param2);\n}, milliseconds);\n\n// Anonymous functions with arguments\nlet timerId = setTimeout(function(arg1, ...){\n    // code here\n}, milliseconds, param1, ...);\n\nclearTimeout(timerId)  // cancel execution\n\n// example of multiple consecutive schedules\nlet list = [1 , 2, 3, 4, 5, 6, 7, 8, 9, 10, \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]\nfunction useTimeout(pos=0) {\n\n    setTimeout(function(){\n        console.log(list[pos]);\n        pos += 1;  // update value for next call\n\n        if (pos < list.length) {  // recursion exit condition\n            useTimeout(pos);  // schedule next call with new value\n        }\n    }, 1_000, pos);\n}\n\nuseTimeout();\n
"},{"location":"languages/javascript/javascript.html#let-vs-var-with-settimeout","title":"let vs var with setTimeout","text":"JavaScript
// let instantiates a new variable for each iteration\nfor (let i = 0; i < 3; ++i) {\n    setTimeout(function() {\n        console.log(i);\n    }, i * 100);\n}\n// output: 0, 1, 2\n\nfor (var i = 0; i < 3; ++i) {\n    setTimeout(function() {\n        console.log(i);\n    }, i * 100);\n}\n// output: 3, 3, 3\n
"},{"location":"languages/javascript/javascript.html#preserving-the-context","title":"Preserving the context","text":"JavaScript
let obj = {\n    prop: value,\n\n    method1 : function() { /* statement */ }\n\n    method2 : function() {\n        let self = this  // memorize context inside method (otherwise callback will not know it)\n        setTimeout(function() { /* code here (uses self) */ })\n    }\n}\n\n\n// better\nlet obj = {\n    prop: value,\n\n    method1 : function() { /* statement */ }\n\n    method2 : function() {\n        setTimeout(() => { /* code here (uses this) */ })  // arrow func does not create new scope, this context preserved\n    }\n}\n
"},{"location":"languages/javascript/javascript.html#intervals","title":"Intervals","text":"

Function runs regularly with a specified interval. JavaScript is Single Threaded.

JavaScript
// param1, param2, ... are the arguments passed to the function (IE9+)\nlet timerId = setInterval(func, milliseconds [, param1, param2, ... ]); // (params are read at execution time)\n\n// works in IE9\nlet timerId =  setInterval(function(){\n    func(param1, param2);\n}, milliseconds);\n\n// Anonymous functions with arguments\nlet timerId = setInterval(function(arg1, ...){\n    // code here\n}, milliseconds, param1, ...);\n\nclearTimeout(timerId);  // cancel execution\n
"},{"location":"languages/javascript/javascript.html#datetime","title":"DateTime","text":"

A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.

There are generally 4 types of JavaScript date input formats:

JavaScript
// constructors\nnew Date();\nnew Date(milliseconds);\nnew Date(dateString);\nnew Date(year, month, day, hours, minutes, seconds, milliseconds);\n\n// accepts parameters similar to the Date constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.\nDate.UTC(year, month, day, hours, minutes, seconds, milliseconds);\n\n//static methods\nDate.now();  // returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.\n\n// methods\nlet date = new Date();\ndate.toSting(); // returns a string representing the specified Date object\ndate.toUTCString();\ndate.toDateString();\ndate.toTimeString();  // method returns the time portion of a Date object in human readable form in American English.\n\n\n// get date\n\ndare.getMonth();\ndate.getMinutes();\ndate.getFullYear();\n\n// set date\ndate.setFullYear(2020, 0, 14);\ndate.setDate(date.getDate() + 50);\n\n// parse valid dates\nlet msec = Date.parse(\"March 21, 2012\");\nlet date = new Date(msec);\n
"},{"location":"languages/javascript/javascript.html#comparing-dates","title":"Comparing Dates","text":"

Comparison operators work also on dates

JavaScript
let date1 = new Date();\nlet date2 = new Date(\"May 24, 2017 10:50:00\");\n\nif(date1 > date2){\n        console.log('break time');\n} else {\n        console.log('stay in class');\n}\n
"},{"location":"languages/javascript/javascript.html#exports","title":"Exports","text":"

Firefox CORS not HTTP

Note: Firefox 68 and later define the origin of a page opened using a file:/// URI as unique. Therefore, other resources in the same directory or its subdirectories no longer satisfy the CORS same-origin rule. This new behavior is enabled by default using the privacy.file_unique_origin preference.

JSON
\"privacy.file_unique_origin\": \"false\"\n

In page.html

HTML
<script src=\"scripts/module.js\"></script>\n<script src=\"scripts/script.js\"></script>\n

In module.js:

JavaScript
// exporting individual fractures\nexport default function() {}  // one per module\nexport func = () => expression;  // zero or more per module\n\n// Export list\nexport { name1, name2, \u2026, nameN };\n\n// Renaming exports\nexport { variable1 as name1, variable2 as name2, \u2026, nameN };\n\n// Exporting destructured assignments with renaming\nexport const { name1, name2: bar } = o;\n\n // re-export\nexport { func } from \"other_script.js\" \n

In script.js:

JavaScript
import default_func_alias, { func as alias } from \"./module.js\";  // import default and set alias\nimport { default as default_func_alias, func as alias } from \"./module.js\";  // import default and set alias\n\n// use imported functions\ndefault_func_alias();\nalias();\n
JavaScript
import * from \"./module.js\";  // import all\n\nmodule.function();  // use imported content with fully qualified name\n
"},{"location":"languages/javascript/jquery.html","title":"jQuery Library","text":""},{"location":"languages/javascript/jquery.html#including-jquery","title":"Including jQuery","text":""},{"location":"languages/javascript/jquery.html#download-and-link-the-file","title":"Download and link the file","text":"HTML
<head>\n    <script src=\"jquery-x.x.x.min.js\"></script>\n</head>\n
"},{"location":"languages/javascript/jquery.html#use-a-cdn","title":"Use a CDN","text":"HTML
<head>\n    <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/x.x.x/jquery.min.js\"></script>\n</head>\n\n<!-- OR -->\n\n<head>\n    <script src=\"https://ajax.aspnetcdn.com/ajax/jQuery/jquery-x.x.x.min.js\"></script>\n</head>\n
"},{"location":"languages/javascript/jquery.html#what-is-a-cdn","title":"What is a CDN","text":"

A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance. CDNs serve a large fraction of the Internet content today, including web objects (text, graphics and scripts), downloadable objects (media files, software, documents), applications (e-commerce, portals), live streaming media, on-demand streaming media, and social networks.

"},{"location":"languages/javascript/jquery.html#html-manipulation","title":"HTML Manipulation","text":""},{"location":"languages/javascript/jquery.html#finding-dom-elements","title":"Finding DOM elements","text":"JavaScript
$('tag');\n$(\"#id\");\n$(\".class\");\n
"},{"location":"languages/javascript/jquery.html#manipulating-dom-elements","title":"Manipulating DOM elements","text":"JavaScript
$(\"p\").addClass(\"special\");\n
HTML
<!-- before -->\n<p>Welcome to jQuery<p>\n\n<!-- after -->\n<p class=\"special\">Welcome to jQuery<p>\n
"},{"location":"languages/javascript/jquery.html#reading-elements","title":"Reading Elements","text":"HTML
<a id=\"yahoo\" href=\"http://www.yahoo.com\" style=\"font-size:20px;\">Yahoo!</a>\n
JavaScript
// find it & store it\nvar link = $('a#yahoo');\n\n// get info about it\nlink.html(); // 'Yahoo!'\nlink.attr('href'); // 'http://www.yahoo.com'\nlink.css('font-size'); // '20px\n
"},{"location":"languages/javascript/jquery.html#modifying-elements","title":"Modifying Elements","text":"JavaScript
// jQuery\n$('a').html('Yahoo!');\n$('a').attr('href', 'http://www.yahoo.com');\n$('a').css({'color': 'purple'});\n
HTML
<!-- before -->\n<a href=\"http://www.google.com\">Google</a>\n\n<!-- after -->\n<a href=\"http://www.yahoo.com\" style=\"color:purple\">Yahoo</a>\n
"},{"location":"languages/javascript/jquery.html#create-store-manipulate-and-inject","title":"Create, Store, Manipulate and inject","text":"JavaScript
let paragraph = $('<p class=\"intro\">Welcome<p>');  // create and store element\n\nparagraph.css('property', 'value');  // manipulate element\n\n$(\"body\").append(paragraph);  // inject in DOM\n
"},{"location":"languages/javascript/jquery.html#regular-dom-nodes-to-jquery-objects","title":"Regular DOM Nodes to jQuery Objects","text":"JavaScript
var paragraphs = $('p'); // an array\nvar aParagraph = paragraphs[0]; // a regular DOM node\nvar $aParagraph = $(paragraphs[0]); // a jQuery Object\n\n// can also use loops\nfor(var i = 0; i < paragraphs.length; i++) {\n    var element = paragraphs[i];\n    var paragraph = $(element);\n    paragraph.html(paragraph.html() + ' WOW!');\n}\n
"},{"location":"languages/javascript/jquery.html#events","title":"Events","text":"JavaScript
var onButtonClick = function() {  \n    console.log('clicked!');\n}\n\n// with named callback & .on\n$('button').on('click', onButtonClick);\n\n// with anonymous callback & .on\n$('button').on('click', function(){\n    console.log('clicked!');\n});\n\n// with .click & named callback\n$('button').click(onButtonClick);\n
"},{"location":"languages/javascript/jquery.html#preventing-default-event","title":"Preventing Default Event","text":"JavaScript
$('selector').on('event', function(event) {\n    event.preventDefault();\n    // custom logic\n});\n
"},{"location":"languages/javascript/jquery.html#plugins","title":"Plugins","text":"

In the HTML, add a <script> ag that hotlinks to the CDN or source file:

HTML
<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js\"><script>\n

In the JavaScript call the jQuery plugin on the DOM:

JavaScript
$(\"form\").validate();\n

Note: always link to the minified js files.

"},{"location":"languages/javascript/jquery.html#more-jquery","title":"More jQuery","text":""},{"location":"languages/javascript/jquery.html#patters-anti-patterns","title":"Patters & Anti-Patterns","text":"JavaScript
// Pattern: name variables with $var\n$myVar =$('#myNode');\n\n// Pattern: store references to callback functions\nvar callback = function(argument){\n    // do something cool\n};\n\n$(document).on('click', 'p', myCallback);\n\n// Anti-pattern: anonymous functions\n$(document).on('click', 'p', function(argument){\n    // do something anonymous\n});\n
"},{"location":"languages/javascript/jquery.html#chaining","title":"Chaining","text":"JavaScript
banner.css('color', 'red');\nbanner.html('Welcome!');\nbanner.show();\n\n// same as:\nbanner.css('color', 'red').html('Welcome!').show();\n\n// same as:\nbanner.css('color', 'red')\n    .html('Welcome!')\n    .show();\n
"},{"location":"languages/javascript/jquery.html#dom-readiness","title":"DOM Readiness","text":"

DOM manipulation and event binding doesn't work if the <script> is in the <head>

JavaScript
$(document).ready(function() {\n    // the DOM is fully loaded\n});\n\n$(window).on('load', function(){\n    // the DOM and all assets (including images) are loaded\n});\n
"},{"location":"languages/javascript/jquery.html#ajax-jquery-15","title":"AJAX (jQuery 1.5+)","text":"JavaScript
$.ajax({\n    method: 'POST',\n    url: 'some.php',\n    data: { name: 'John', location: 'Boston'}\n})\n.done(function(msg){alert('Data Saved: '+ msg);})\n.fail(function(jqXHR, textStatus){alert('Request failed: '+ textStatus);});\n
"},{"location":"languages/javascript/react/react-router.html","title":"React Router","text":"

Popular routing library. Allows to specify a route through React components, declaring which component is to be loaded for a given URL.

Key Components:

"},{"location":"languages/javascript/react/react-router.html#routers","title":"Routers","text":"

Router Types:

JavaScript
// index.js\n\n//other imports ...\n\nimport { BrowserRouter as Router } from \"react-router-dom\";\n\nReact.render(\n    <Router>\n        <App />\n    </Router>,\n    document.getElementById(\"DomID\");\n)\n
JavaScript
// Component.js\nimport { Route, Route } from \"react-router-dom\";\n\n<div>\n    {/* match route pattern exactly, all sub-routes will be matched otherwise */}\n    <Route path=\"/\" exact element={<Component props={props} />} /> \n    <Route path=\"/route\" element={<Component props={props} />} />\n    ...\n</div>\n\n// only one child can match, similar to Route-case\n<Routes>\n    <Route path=\"/\" exact element={<Component props={props} />} />\n    <Route path=\"/route\" element={<Component props={props} />} />\n    <Route component={PageNotFound} /> {/* matches all non-existent URLs */}\n</Route>\n
"},{"location":"languages/javascript/react/react-router.html#url-parameters-query-string","title":"URL Parameters & Query String","text":"JavaScript
// Given\n<Route path=\"/route/:placeholder\" element={<Component props={props} />} />\n// URL: app.com/route/sub-route?param=value\n\nfunction Component(props) {\n    props.match.params.placeholder;  // sub-route\n    props.location.query;  // { param: value }\n    props.location.pathname; // /route/sub-route?param=value\n}\n
"},{"location":"languages/javascript/react/react-router.html#redirecting","title":"Redirecting","text":"JavaScript
import { Navigate } from \"react-router-dom\";\n\n// redirects to another URL on render, shouldn't be rendered on component mount but after an action\n<Navigate to=\"/route\" />\n<Navigate from=\"/old-route\" to=\"/new-route\" />\n{ condition &&  <Navigate to=\"/route\" /> }  // redirect if condition is true\n\n// or redirect manipulating the history (always in props)\nprops.history.push(\"/new-route\");\n
"},{"location":"languages/javascript/react/react-router.html#prompts","title":"Prompts","text":"JavaScript
import { Prompt } from \"react-router-dom\";\n\n// displays a prompt when the condition is true\n<Prompt when={condition} message=\"prompt message\" />\n
"},{"location":"languages/javascript/react/react-router.html#link","title":"Link","text":"

Clicks on a link created with React-Router will be captured by react an all the routing will happen client side.

JavaScript
import { Link } from \"react-router-dom\";\n\n// TARGET: <Route path=\"/route/:itemId\" />\n<Link to=\"/route/1\">Text</Link>\n\n// add styling attributes to the rendered element when it matches the current URL.\n<NavLink to=\"/route\" exact activeClassName=\"class\">Text</NavLink>\n<NavLink to=\"/route\" activeStyle={ { cssProp: value } }>Text</NavLink>\n
"},{"location":"languages/javascript/react/react-tests.html","title":"Testing React","text":""},{"location":"languages/javascript/react/react-tests.html#jest","title":"Jest","text":""},{"location":"languages/javascript/react/react-tests.html#jest-configuration","title":"Jest Configuration","text":"JavaScript
// jest.config.js\nmodule.exports = {\n  testEnvironment: 'jsdom',\n  moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'],\n  setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],  // add testing-library methods to expect()\n  transform: { '^.+\\\\.tsx?$': 'ts-jest'}  // use ts-jest fo ts files\n}\n
"},{"location":"languages/javascript/react/react-tests.html#jest-tests","title":"Jest Tests","text":"

Expect docs

JavaScript
// .spec.js or .test.js\nit(\"test description\", () => {\n    // test body\n    expect(expected).toEqual(actual);\n});\n\n// group related tests\ndescribe(\"test group name\", () => {\n    it(/* ... */);\n    it(/* ... */);\n});\n
"},{"location":"languages/javascript/react/react-tests.html#snapshots","title":"Snapshots","text":"

In Component.Snapshots.js:

JavaScript
import React from \"react\";\nimport renderer from \"react-test-renderer\";\n\nimport Component from \"./path/to/Component\";\n// import mock data if necessary\n\nit(\"test description\", () => {\n    // renders the DOM tree of the component\n    const tree = renderer.create(<Component funcProp={jest.fn() /* mock function */} /* component props */ />);\n\n    // save a snapshot of the component at this point in time ( in  __snapshots__ folder)\n    // in future test it will be checked to avoid regressions\n    // can be updated during jest --watch pressing \"u\"\n    expect(tree).matchSnapshot();\n});\n
"},{"location":"languages/javascript/react/react-tests.html#enzyme","title":"Enzyme","text":""},{"location":"languages/javascript/react/react-tests.html#enzyme-configuration","title":"Enzyme Configuration","text":"JavaScript
// testSetup.js\nimport { configure } from \"enzyme\";\nimport Adapter from \"enzyme-adapter-react-<version>\";\n\nconfigure({ adapter: new Adapter() });\n
"},{"location":"languages/javascript/react/react-tests.html#enzyme-tests","title":"Enzyme Tests","text":"

In Component.test.js:

JavaScript
import React from \"react\";\nimport { shallow, mount } from \"enzyme\";\n// eventual wrapper components (react-router, react-redux's provider, ...) for mount render\n\n// shallow renders single component w/o children, no DOM generated\n// mount renders component w/ it's children\n\nimport Component from \"./path/to/Component\";\n\n// factory to setup shallow test easily\nfunction testHelper(args) {\n    const defaultProps = { /* default value for props in each test */ };\n\n    const props = { ...defaultProps, ...args };\n    return shallow(<Component {...props} />);\n}\n\n// shallow rendering test\nit(\"test description\", () => {\n    const dom = testHelper(/* optional args */);\n    // or\n    const dom = shallow(<Component /* props */ />);\n\n    // check a property of expected component\n    // selector can be from raw JSX (name of a component)\n    expect(dom.find(\"selector\").property).toBe(expected);\n});\n\n// mount rendering test\nif(\"test description\" () => {\n    const dom = mount(\n        <WrapperComponent>\n            <Component /* props *//>\n        </WrapperComponent>\n    );\n\n    // selector has to be HTML selector since the component is rendered completely\n    // possible to test child components\n    expect(dom.find(\"selector\").property).toBe(expected);\n});\n
"},{"location":"languages/javascript/react/react-tests.html#react-testing-library","title":"React Testing Library","text":"

Encourages to write test based on what the user sees. So components are always mounted and fully rendered.

"},{"location":"languages/javascript/react/react-tests.html#react-testing-library-tests","title":"React Testing Library Tests","text":"

In Components.test.js:

JavaScript
import React from \"react\";\nimport { cleanup, render } from \"@testing-library/react\";\n\nimport Component from \"./path/to/Component\";\n\nafterEach(cleanup);\n\n// factory to setup test easily\nfunction testHelper(args) {\n    const defaultProps = { /* default value for props in each test */ };\n\n    const props = { ...defaultProps, ...args };\n    return render(<Component {...props} />);\n}\n\nit(\"test description\", () => {\n    const { getByText } = testHelper();\n\n    // react testing library func\n    getByText(\"text\");  // check if test is present in the rendered component\n});\n
"},{"location":"languages/javascript/react/react.html","title":"React","text":""},{"location":"languages/javascript/react/react.html#components","title":"Components","text":"

There are two types of react components:

Both types can be stateful and have side effects or be purely presentational.

JSX
// functional component\nconst Component = (props) => {\n    return (\n        <domElementOrComponent... />\n    );\n}\n\n// class component\nclass Component extends React.Component {\n    return (\n        <domElementOrComponent... />\n    );\n}\n

NOTE: a component name must start with an uppercase letter.

Every components has two inputs: props and state. The props input is explicit while the state is implicit. State is used to determine the changes and when to re-render. Within the component state can be changed while the props object represent fixed input values.

JSX syntax can represent HTML but gets converted to pure JavaScript before being sent to the browser:

JavaScript
// JSX\nconst element = (\n  <h1 className=\"greeting\">Hello, world!</h1>\n);\n\n// compiled JS shipped to browser\nconst element = React.createElement(\n  'h1',  // HTML tag name\n  {className: 'greeting'},  // attrs as JSON\n  'Hello, world!'  // tag content (can be nested component)\n);\n
"},{"location":"languages/javascript/react/react.html#app-entry-point","title":"App Entry-point","text":"JavaScript
const container = document.getElementById('root')!;\nconst root = createRoot(container);\n\nconst element = <h1s>Hello World</h1>\nroot.render(element)\n
"},{"location":"languages/javascript/react/react.html#dynamic-expressions","title":"Dynamic Expressions","text":"JavaScript
<tag>{expression}</tag>  // expression is evaluated an it's result is displayed\n<tag onEvent={funcReference}>{expression}</tag>\n<tag onEvent={() => func(args)}>{expression}</tag>\n
"},{"location":"languages/javascript/react/react.html#props","title":"Props","text":"JavaScript
<Component propName={value} />  // pass a value the component\n<Component propName={funcReference} />  // pass a function to the component\n\nfunction Component(props) {\n    // use props with {props.propName}\n}\n\nclass Component extends React.Component{\n    // use props with {this.props.propName}\n    render()\n}\n
"},{"location":"languages/javascript/react/react.html#simple-function-component","title":"Simple Function Component","text":"JavaScript
// Button.js\nimport { useState } from \"react\";\n\nfunction Button() {\n    const [count, setCount] = useState(0);  // hook\n\n    const handleCLick = () => setCount(count + 1);  // logic\n\n    // JSX\n    return (\n        <button onClick={handleCLick}>\n            {count}\n        </button>\n    );\n}\n\nexport default Button;\n
"},{"location":"languages/javascript/react/react.html#simple-class-component","title":"Simple Class Component","text":"JavaScript
class Button extends React.Component {\n\n    state = {count: 0};\n    //or\n    constructor(props) {\n        super(props);\n        this.state = {count: 0};\n    }\n\n    componentDidMount() {}  // called on successful component mount\n\n    handleClick = () => {\n        this.setState({ count: this.state.count + 1 });\n    }\n    // or\n    handleClick = () => {\n        this.setState((state, props) => ({ count: state.count + props.increment }) );\n    }\n\n    render(){\n        return (\n        <button onClick={this.handleClick}>\n            {this.state.count}\n        </button>\n        );\n    }\n}\n
"},{"location":"languages/javascript/react/react.html#nesting-components","title":"Nesting Components","text":"JavaScript
import { useState } from \"react\";\n\nfunction Button(props) {\n  return (\n      <button onClick={props.onClickFunc}>\n          +1\n      </button>\n  );\n}\n\nfunction Display (props) {\n  return (\n      <div>{props.message}</div>\n  );\n}\n\nfunction App() {\n\n    // state must be declare in the outer component it can be passed to each children\n    const [count, setCount] = useState(0);\n    const incrementCounter = () => setCount(count + 1);\n\n    return (\n        <div className=\"App\">\n            <Button onClickFunc={incrementCounter}/>\n            <Display message={count}/>\n        </div>\n    );\n}\n\nexport default App;\n
"},{"location":"languages/javascript/react/react.html#user-input-forms","title":"User Input (Forms)","text":"JavaScript
function Form() {\n    const [userName, setUserName] = useState(\"\");\n\n    handleSubmit = (event) => {\n        event.preventDefault();\n        // ...\n    }\n\n    return(\n        <form onSubmit={handleSubmit}>\n            <input\n                type=\"text\"\n                value={userName}  // controlled component\n                onChange={(event) => setUserName(event.target.value)}  // needed to update UI on dom change\n                required\n            />\n            <button></button>\n        </form>\n    );\n}\n
"},{"location":"languages/javascript/react/react.html#lists-of-components","title":"Lists of Components","text":"JavaScript
// ...\n    <div>\n        {array.map(item => <Component key={uniqueID}>)}\n    </div>\n// ...\n

Note: The key attribute of the component is needed to identify a particular item. It's most useful if the list has to be sorted.

"},{"location":"languages/javascript/react/react.html#hooks","title":"Hooks","text":""},{"location":"languages/javascript/react/react.html#usestate","title":"useState","text":"

Hook used to create a state object.

useState() results:

JavaScript
const [state, setState] = useState(default);\n
"},{"location":"languages/javascript/react/react.html#useeffect","title":"useEffect","text":"

Hook used to trigger an action on each render of the component or when one of the watched items changes.

JavaScript
useEffect(() => {\n    // \"side effects\" operations\n\n    return () => {/* clean up side effect */}  // optional\n}, [/* list of watched items, empty triggers once */]);\n
"},{"location":"languages/javascript/react/react.html#custom-hooks","title":"Custom Hooks","text":"JavaScript
// hook definitions\nconst useCustomHook = () => {\n    // eventual state definitions\n\n    // eventual function definitions\n\n    // ...\n\n    return { obj1, obj2, ... };\n}\n\nconst Component(){\n    // retrieve elements from the hook\n    const {\n        obj1,\n        obj2,\n        ...\n    } = useCustomHook();\n}\n
"},{"location":"languages/javascript/react/redux-tests.html","title":"Redux Testing","text":""},{"location":"languages/javascript/react/redux-tests.html#tests-for-connected-components","title":"Tests for Connected Components","text":"

Connected components are wrapped in a call to connect. Way of solving the problem:

In Component.js:

JavaScript
export function Component(props) { /* ... */ }  // export unconnected component\n\nexport default connect(mapStateToProps, mapDispatchToProps)(Component)  // default export of connected component\n

In Component.test.js:

JavaScript
import React from \"react\";\n// import enzyme or react testing library\n\n// import mock data\nimport { Component } from \"path/to/Component\";  // import unconnected component\n\n// factory to setup test easily\nfunction testHelper(args) {\n    const defaultProps = { \n        /* default value for props in each test and required props */,\n        history = {}  // normally injected by react-router, could also import the router\n    };\n\n    const props = { ...defaultProps, ...args };\n    return mount(<Component {...props} />);  // or render if using react testing library\n}\n\nit(\"test description\", () => {\n    const dom = testHelper();\n\n    // simulate page iteration\n    dom.find(\"selector\").simulate(\"<event>\");\n\n    // find changed component\n    // test expected behaviour of component\n});\n
"},{"location":"languages/javascript/react/redux-tests.html#tests-for-action-creators","title":"Tests for Action Creators","text":"JavaScript
import * as actions from \"path/to/actionCreators\";\n// import eventual action types constants\n// import mock data\n\nit(\"test description\", () => {\n    const data = /* mock data */\n    const expectedAction = { type: TYPE, /* ... */ };\n\n    const actualAction = actions.actionCreator(data);\n\n    expect(actualAction).toEqual(expectedAction);\n});\n
"},{"location":"languages/javascript/react/redux-tests.html#tests-for-reducers","title":"Tests for Reducers","text":"JavaScript
import reducer from \"path/to/reducer\";\nimport * as actions from \"path/to/actionCreators\";\n\nit(\"test description\", () => {\n    const initialState = /* state before the action */;\n    const finalState = /* expected state after the action */\n    const data = /* data passed to the action creator */;\n\n    const action = actions.actionCreator(data);\n    const newState = reducer(initialState, action);\n\n    expect(newState).toEqual(finalState);\n});\n
"},{"location":"languages/javascript/react/redux-tests.html#tests-for-the-store","title":"Tests for the Store","text":"JavaScript
import { createStore } from \"redux\";\n\nimport rootReducer from \"path/to/rootReducer\";\nimport initialState from \"path/to/initialState\";\nimport * as actions from \"path/to/actionCreators\";\n\nit(\"test description\", () => {\n    const store = createStore(storeReducer, initialState);\n\n    const expectedState = /* state after the update */\n\n    const data = /* action creator input */;\n    const action = actions.actionCreator(data);\n    store.dispatch(action);\n\n    const state = store.getState();\n    expect(state).toEqual(expectedState);\n});\n
"},{"location":"languages/javascript/react/redux-tests.html#tests-for-thunks","title":"Tests for Thunks","text":"

Thunk testing requires the mocking of:

JavaScript
import thunk from \"redux-thunk\";\nimport fetchMock from \"fetch-mock\";\nimport configureMockStore from \"redux-mock-store\";\n\n// needed for testing async thunks\nconst middleware = [thunk];  // mock middlewares\nconst mockStore = configureMockStore(middleware);  // mock the store\n\nimport * as actions from \"path/to/actionCreators\";\n// import eventual action types constants\n// import mock data\n\ndescribe(\"Async Actions\", () => {\n    afterEach(() => {\n        fetchMock.restore();  // init fetch mock for each test\n    });\n\n    it(\"test description\", () => {\n        // mimic API call\n        fetchMock.mock(\n            \"*\",  // capture any fetch call\n            {\n                body: /* body contents */,\n                headers: { \"content-type\": \"application/json\" }\n            }\n        );\n\n        // expected action fired from the thunk\n        const expectedActions = [\n            { type: TYPE, /* ... */ },\n            { type: TYPE, /* ... */ }\n        ];\n\n        const store = mockStore({ data: value, ... });  // init mock store\n\n        return store.dispatch(actions.actionCreator())  // act\n            .then(() => {\n                expect(store.getActions()).toEqual(expectedActions);  // assert\n            });\n    });\n});\n
"},{"location":"languages/javascript/react/redux.html","title":"Redux","text":"

Redux is a pattern and library for managing and updating application state, using events called actions. It serves as a centralized store for state that needs to be used across the entire application, with rules ensuring that the state can only be updated in a predictable fashion.

"},{"location":"languages/javascript/react/redux.html#actions-store-immutability-reducers","title":"Actions, Store, Immutability & Reducers","text":""},{"location":"languages/javascript/react/redux.html#actions-action-creators","title":"Actions & Action Creators","text":"

An Action is a plain JavaScript object that has a type field. An action object can have other fields with additional information about what happened. By convention, that information is stored in a field called payload.

Action Creators are functions that create and return action objects.

JavaScript
function actionCreator(data)\n{\n    return { type: ACTION_TYPE, payload: data };  // action obj\n}\n
"},{"location":"languages/javascript/react/redux.html#store","title":"Store","text":"

The current Redux application state lives in an object called the store. The store is created by passing in a reducer, and has a method called getState that returns the current state value.

The Redux store has a method called dispatch. The only way to update the state is to call store.dispatch() and pass in an action object. The store will run its reducer function and save the new state value inside.

Selectors are functions that know how to extract specific pieces of information from a store state value.

In initialState.js;

JavaScript
export default {\n    // initial state here\n}\n

In configStore.js:

JavaScript
// configStore.js\nimport { createStore, applyMiddleware, compose } from \"redux\";\n\nexport function configStore(initialState) {\n    const composeEnhancers =\n        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // support for redux devtools\n\n    return  createStore(\n        rootReducer, \n        initialState, \n        composeEnhancers(applyMiddleware(middleware, ...))\n    );\n}\n\n// available functions & methods\nreplaceReducer(newReducer);  // replace an existing reducer, useful for Hot Reload\nstore.dispatch(action);  // trigger a state change based on an action\nstore.subscribe(listener);\nstore.getState();  // retrieve current state\n
"},{"location":"languages/javascript/react/redux.html#reducers","title":"Reducers","text":"

Reducers are functions that receives the current state and an action, decide how to update the state if necessary, and return the new state.

Reducers must always follow some specific rules:

JavaScript
import initialState from \"path/to/initialState\";\n\nfunction reducer(state = initialState, action) {\n    switch(action.type){\n        case \"ACTION_TYPE\":\n            return { ...state, prop: value };  // return modified copy of state (using spread operator)\n            break;\n\n        default:\n            return state;  // return unchanged state (NEEDED)\n    }\n}\n\n// combining reducers\nimport { combineReducers } from \"redux\";\n\nconst rootReducer = combineReducers({\n    entity: entityReducer.\n    ...\n});\n

Note: multiple reducers can be triggered by the same action since each one operates on a different portion of the state.

"},{"location":"languages/javascript/react/redux.html#react-redux","title":"React-Redux","text":""},{"location":"languages/javascript/react/redux.html#container-vs-presentational-components","title":"Container vs Presentational Components","text":"

Container Components:

Presentational Components:

"},{"location":"languages/javascript/react/redux.html#provider-component-connect","title":"Provider Component & Connect","text":"

Used at the root component and wraps all the application.

JavaScript
// index.js\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Provider } from 'react-redux';\n\nimport { configStore } from 'path/to/configStore';\nimport initialState from \"path/to/initialState\";\nimport App from './App';\n\nconst store = configStore(initialState);\n\nconst rootElement = document.getElementById('root');\nReactDOM.render(\n  <Provider store={store}>\n    <App />\n  </Provider>,\n  rootElement\n);\n
JavaScript
// Component.js\nimport { connect } from 'react-redux';\nimport { increment, decrement, reset } from './actionCreators';\n\n// const Component = ...\n\n// specifies which state is passed to the component (called on state change)\nconst mapStateToProps = (state, ownProps /* optional */) => {\n    // structure of the props passed to the component\n    return { propName: state.property };\n};\n\n// specifies the action passed to a component (the key is the name that the prop will have )\nconst mapDispatchToProps = { actionCreator: actionCreator };\n// or\nfunction mapDispatchToProps(dispatch) {\n    return {\n        // wrap action creators\n        actionCreator: (args) => dispatch(actionCreator(args))\n    };\n}\n// or\nfunction mapDispatchToProps(dispatch) {\n    return {\n        actionCreator: bindActionCreators(actionCreator, dispatch),\n        actions: bindActionCreators(allActionCreators, dispatch)\n    };\n}\n\n// both args are optional\n// if mapDispatch is missing the dispatch function is added to the props\nexport default connect(mapStateToProps, mapDispatchToProps)(Component);\n
"},{"location":"languages/javascript/react/redux.html#async-operations-with-redux-thunk","title":"Async Operations with Redux-Thunk","text":"

Note: Redux middleware runs after and action and before it's reducer.

Redux-Thunk allows to return functions instead of objects from action creators. A \"thunk\" is a function that wraps an expression to delay it's evaluation.

In configStore.js:

JavaScript
import { createStore, applyMiddleware, compose } from \"redux\";\nimport thunk from \"redux-thunk\";\n\nfunction configStore(initialState) {\n    const composeEnhancers =\n        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // support for redux devtools\n\n    return  createStore(\n        rootReducer, \n        initialState, \n        composeEnhancers(applyMiddleware(thunk, ...))  // add thunks middleware\n    );\n}\n
JavaScript
// usually action on async func success\nfunction actionCreator(arg) {\n    return { type: TYPE, data: arg };\n}\n\nexport function thunk() {\n    return function (dispatch) {  // redux-thunk injects dispatch as arg\n        return asyncFunction().then((data) => {  // async function returns a promise\n                dispatch(actionCreator(data));\n            })\n            .catch((error) => {\n                throw error;\n            });\n    };\n}\n\n// or using async/await\nexport async function thunk() {\n    return function (dispatch) {  // redux-thunk injects dispatch as arg\n        try {\n            let data = await asyncFunction();\n            return dispatch(actionCreator(data));\n        } catch(error) {\n                throw error;\n        }\n    }\n}\n
"},{"location":"languages/javascript/react/redux.html#redux-toolkit","title":"Redux-Toolkit","text":"

The Redux Toolkit package is intended to be the standard way to write Redux logic. It was originally created to help address three common concerns about Redux.

Redux Toolkit also includes a powerful data fetching and caching capability dubbed \"RTK Query\". It's included in the package as a separate set of entry points. It's optional, but can eliminate the need to hand-write data fetching logic yourself.

These tools should be beneficial to all Redux users. Whether you're a brand new Redux user setting up your first project, or an experienced user who wants to simplify an existing application, Redux Toolkit can help you make your Redux code better. Installation\u200b Using Create React App\u200b

The recommended way to start new apps with React and Redux is by using the official Redux+JS template or Redux+TS template for Create React App, which takes advantage of Redux Toolkit and React Redux's integration with React components.

Bash
# Redux + Plain JS template\nnpx create-react-app my-app --template redux\n\n# Redux + TypeScript template\nnpx create-react-app my-app --template redux-typescript\n

Redux Toolkit includes these APIs:

"},{"location":"languages/javascript/react/redux.html#configurestore","title":"configureStore","text":"

Included Default Middleware\u200b:

Currently, the return value of getDefaultMiddleware() is:

JavaScript
// development\nconst middleware = [thunk, immutableStateInvariant, serializableStateInvariant]\n\n// production\u200b\nconst middleware = [thunk]\n
JavaScript
import { combineReducers } from 'redux'\nimport { configureStore } from '@reduxjs/toolkit'\nimport monitorReducersEnhancer from './enhancers/monitorReducers'\nimport loggerMiddleware from './middleware/logger'\nimport usersReducer from './usersReducer'\nimport postsReducer from './postsReducer'\n\nconst rootReducer = combineReducers({\n  users: usersReducer,\n  posts: postsReducer,\n})\n\nconst store = configureStore({\n  // reducers combined automatically\n  reducer: rootReducer,\n  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(loggerMiddleware),\n  enhancers: [monitorReducersEnhancer]\n})\n\nexport default store\n
"},{"location":"languages/javascript/react/redux.html#createaction","title":"createAction","text":"JavaScript
import { createAction } from '@reduxjs/toolkit';\n\nconst increment = createAction<number | undefined>('counter/increment');\n\nconst action = increment();  // { type: 'counter/increment' }\nconst action = increment(3);  // { type: 'counter/increment', payload: 3 }\n\nincrement.toString();  // 'counter/increment'\n
"},{"location":"languages/javascript/react/redux.html#createreducer","title":"createReducer","text":"JavaScript
import { createAction, createReducer } from '@reduxjs/toolkit'\n\ninterface CounterState {\n  value: number\n}\n\nconst increment = createAction('counter/increment')\nconst decrement = createAction('counter/decrement')\nconst incrementByAmount = createAction<number>('counter/incrementByAmount')\n\nconst initialState = { value: 0 } as CounterState\n\nconst counterReducer = createReducer(initialState, (builder) => {\n  builder\n    .addCase(increment, (state, action) => {\n      state.value++\n    })\n    .addCase(decrement, (state, action) => {\n      state.value--\n    })\n    .addCase(incrementByAmount, (state, action) => {\n      state.value += action.payload\n    })\n})\n
"},{"location":"languages/javascript/react/redux.html#createslice","title":"createSlice","text":"

A function that accepts an initial state, an object of reducer functions, and a \"slice name\", and automatically generates action creators and action types that correspond to the reducers and state.

Internally, it uses createAction and createReducer, so it's possible to use Immer to write \"mutating\" immutable updates.

Note: action types will have the <slice-name>/<reducer-name> shape.

JavaScript
import { createSlice, PayloadAction } from '@reduxjs/toolkit'\n\ninterface CounterState {\n  value: number\n}\n\nconst initialState = { value: 0 } as CounterState\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState,\n  reducers: {\n    increment(state) {\n      state.value++\n    },\n    decrement(state) {\n      state.value--\n    },\n    incrementByAmount(state, action: PayloadAction<number>) {\n      state.value += action.payload\n    },\n  },\n})\n\nexport const { increment, decrement, incrementByAmount } = counterSlice.actions\nexport default counterSlice.reducer\n
"},{"location":"languages/javascript/react/redux.html#createasyncthunk","title":"createAsyncThunk","text":"

The function createAsyncThunk returns a standard Redux thunk action creator. The thunk action creator function will have plain action creators for the pending, fulfilled, and rejected cases attached as nested fields.

The payloadCreator function will be called with two arguments:

The logic in the payloadCreator function may use any of these values as needed to calculate the result.

JavaScript
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\n\nconst payloadCreator = async (arg, ThunkAPI): Promise<T> => { /* ... */ };\nconst thunk = createAsyncThunk(\"<action-type>\", payloadCreator);\n\nthunk.pending; // action creator that dispatches an '<action-type>/pending'\nthunk.fulfilled; // action creator that dispatches an '<action-type>/fulfilled'\nthunk.rejected; // action creator that dispatches an '<action-type>/rejected'\n\nconst slice = createSlice({\n  name: '<action-name>',\n  initialState,\n  reducers: { /* standard reducer logic, with auto-generated action types per reducer */ },\n  extraReducers: (builder) => {\n    // Add reducers for additional action types here, and handle loading state as needed\n    builder.addCase(thunk.fulfilled, (state, action) => { /* body of the reducer */ })\n  },\n})\n
"},{"location":"languages/javascript/react/redux.html#rtk-query","title":"RTK Query\u200b","text":"

RTK Query is provided as an optional addon within the @reduxjs/toolkit package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer got the app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.

RTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:

C#
import { createApi } from '@reduxjs/toolkit/query'\n\n/* React-specific entry point that automatically generates hooks corresponding to the defined endpoints */\nimport { createApi } from '@reduxjs/toolkit/query/react'\n

RTK Query includes these APIs:

"},{"location":"languages/javascript/svelte/svelte.html","title":"Svelte","text":"Bash
npx degit sveltejs/template <project name>\n\n# set project to use typescript\nnode scripts/setupTypeScript.js\n\n# or using vite\nnpm init vite@latest\n
"},{"location":"languages/javascript/svelte/svelte.html#app-entry-point","title":"App Entry-point","text":"JavaScript
import App from \"./App.svelte\"; // import the component\n\nconst app = new App({\n  target: document.body,\n  props: {\n    // props passed to the App component\n  },\n});\n\nexport default app;\n
"},{"location":"languages/javascript/svelte/svelte.html#components-svelte","title":"Components (.svelte)","text":""},{"location":"languages/javascript/svelte/svelte.html#basic-structure","title":"Basic Structure","text":"HTML
<!-- code for the component -->\n<script lang=\"ts\">\n  import { Component } from \"Component.svelte\";\n\n  export let prop; // make a variable a prop\n</script>\n\n<!-- CSS for the component -->\n<style>\n  /* CSS rules */\n\n  /* target elements outside of the current component */\n  :global(selector) {\n  }\n</style>\n\n<!-- html of the component  -->\n\n<!-- dynamic expressions -->\n<div>{variable}</div>\n\n<!-- nested components -->\n<Component prop=\"{value}\" />\n
"},{"location":"languages/javascript/svelte/svelte.html#if-else","title":"If-Else","text":"JavaScript
{#if <condition>}\n  // markup here\n{:else if <condition>}\n  // markup here\n{:else}\n  // markup here\n{/if}\n
"},{"location":"languages/javascript/svelte/svelte.html#loops","title":"Loops","text":"JavaScript
{#each array as item, index}  // index is optional\n    // markup here\n{/each}\n\n{#each array as item (key)}  // use key to determine changes\n    // markup here\n{/each}\n
"},{"location":"languages/javascript/svelte/svelte.html#await-blocks","title":"Await Blocks","text":"JavaScript
{#await promise}\n <p>...waiting</p>\n{:then number}\n <p>The number is {number}</p>\n{:catch error}\n <p style=\"color: red\">{error.message}</p>\n{/await}\n
"},{"location":"languages/javascript/svelte/svelte.html#event-handling","title":"Event Handling","text":"

The full list of modifiers:

JavaScript
<script>\n  const eventHandler = () => {};\n</script>\n\n<button on:event={eventHandler}>\n// or\n<button on:event={() => eventHandler(args)}>\n\n<button on:event|modifier={eventHandler}>\n

Note: It's possible to chain modifiers together, e.g. on:click|once|capture={...}.

"},{"location":"languages/javascript/svelte/svelte.html#binding","title":"Binding","text":"HTML
<script>\n  let name = \"Foo\";\n</script>\n\n<!-- modify value in real time -->\n<input bind:value=\"{stringValue}\" />\n<input type=\"checkbox\" bind:checked={boolean}/ >\n<!-- ... -->\n
"},{"location":"languages/javascript/svelte/svelte.html#reactive-declarations-reactive-statements","title":"Reactive declarations & Reactive Statements","text":"

Svelte automatically updates the DOM when the component's state changes. Often, some parts of a component's state need to be computed from other parts and recomputed whenever they change.

For these, Svelte has reactive declarations. They look like this:

JavaScript
let count = 0;\n$: double =  count * 2;  // recalculated when count changes\n// or\n$: { }\n$: <expression>\n
"},{"location":"languages/javascript/svelte/svelte.html#routing","title":"Routing","text":"

Svelte Routing

JavaScript
<!-- App.svelte -->\n<script>\n  import { Router, Link, Route } from \"svelte-routing\";\n  import Home from \"./routes/Home.svelte\";\n  import About from \"./routes/About.svelte\";\n  import Blog from \"./routes/Blog.svelte\";\n\n  export let url = \"\";\n</script>\n\n<Router url=\"{url}\">\n  <nav>\n    <Link to=\"/\">Home</Link>\n    <Link to=\"about\">About</Link>\n    <Link to=\"blog\">Blog</Link>\n  </nav>\n  <div>\n    <Route path=\"blog/:id\" component=\"{BlogPost}\" />\n    <Route path=\"blog\" component=\"{Blog}\" />\n    <Route path=\"about\" component=\"{About}\" />\n    <Route path=\"/\"><Home /></Route>\n  </div>\n</Router>\n
"},{"location":"languages/javascript/svelte/svelte.html#data-stores","title":"Data Stores","text":"JavaScript
// stores.js\nimport { writable } from \"svelte/store\";\n\nexport const count = writable(0);\n
HTML
<script>\n  import { onDestroy } from \"svelte\";\n  import { count } from \".path/to/stores.js\";\n\n  const unsubscriber = count.subscribe((value) => {\n    // do stuff on load or value change\n  });\n\n  count.update((n) => n + 1);\n\n  count.set(1);\n  // or\n  $count = 1;\n\n  onDestroy(unsubscriber);\n</script>\n\n<!-- use $ to reference a store value -->\n<p>{$count}</p>\n
"},{"location":"languages/kotlin/kotlin.html","title":"Kotlin","text":""},{"location":"languages/kotlin/kotlin.html#package-imports","title":"Package & Imports","text":"Kotlin
package com.app.uniqueID\n\nimport <package>\n
"},{"location":"languages/kotlin/kotlin.html#variable-constants","title":"Variable & Constants","text":"Kotlin
var variable: Type    //variable declaration\nvar variable = value    //type can be omitted if it can be deduced by initialization\n\nval CONSTANT_NAME: Type = value    //constant declaration\n
"},{"location":"languages/kotlin/kotlin.html#nullable-variables","title":"Nullable Variables","text":"

For a variable to hold a null value, it must be of a nullable type. Nullable types are specified suffixing ? to the variable type.

Kotlin
var nullableVariable: Type? = null\n\nnullableVariable?.method()    //correct way to use\n//if var is null don't execute method() and return null\n\nnullablevariavle!!.method()    //unsafe way\n//!! -> ignore that var can be null\n
"},{"location":"languages/kotlin/kotlin.html#decision-statements","title":"Decision Statements","text":""},{"location":"languages/kotlin/kotlin.html#if-else-if-else","title":"If - Else If - Else","text":"Kotlin
if (condition) {\n    //code here\n} else if (condition) {\n    //code here\n} else {\n    //code here\n}\n
"},{"location":"languages/kotlin/kotlin.html#conditional-expressions","title":"Conditional Expressions","text":"Kotlin
var variable: Type = if (condition) {\n    //value to be assigned here\n} else if (condition) {\n    //value to be assigned here\n} else {\n    //value to be assigned here\n}\n
"},{"location":"languages/kotlin/kotlin.html#when-expression","title":"When Expression","text":"

Each branch in a when expression is represented by a condition, an arrow (->), and a result. If the condition on the left-hand side of the arrow evaluates to true, then the result of the expression on the right-hand side is returned. Note that execution does not fall through from one branch to the next.

Kotlin
when (variable){\n    condition -> value\n    condition -> value\n    else -> value\n}\n\n//Smart casting\nwhen (variable){\n    is Type -> value\n    is Type -> value\n}\n\n//instead of chain of if-else\nwhen {\n    condition -> value\n    condition -> value\n    else -> value\n}\n
"},{"location":"languages/kotlin/kotlin.html#loops","title":"Loops","text":""},{"location":"languages/kotlin/kotlin.html#for-loop","title":"For Loop","text":"Kotlin
for (item in iterable){\n    //code here\n}\n\n//loop in a numerical range\nfor(i in start..end) {\n    //code here\n}\n
"},{"location":"languages/kotlin/kotlin.html#functions","title":"Functions","text":"Kotlin
fun functionName(parameter: Type): Type {\n    //code here\n\n    return <expression>\n}\n
"},{"location":"languages/kotlin/kotlin.html#simplifying-function-declarations","title":"Simplifying Function Declarations","text":"Kotlin
fun functionName(parameter: Type): Type {\n    return if (condition) {\n        //returned value\n    } else {\n        //returned value\n    }\n}\n\nfun functionName(parameter: Type): Type = if (condition) {\n    //returned value\n    else {\n        //returned value\n    }\n}\n
"},{"location":"languages/kotlin/kotlin.html#anonymous-functions","title":"Anonymous Functions","text":"Kotlin
val anonymousFunction: (Type) -> Type = { input ->\n    //code acting on input here\n}\n\nval variableName: Type = anonymousFunction(input)\n
"},{"location":"languages/kotlin/kotlin.html#higher-order-functions","title":"Higher-order Functions","text":"

A function can take another function as an argument. Functions that use other functions as arguments are called higher-order functions. This pattern is useful for communicating between components in the same way that you might use a callback interface in Java.

Kotlin
fun functionName(parameter: Type, function: (Type) -> Type): Type {\n    //invoke function\n    return function(parameter)\n}\n
"},{"location":"languages/kotlin/kotlin.html#object-oriented-programming","title":"Object Oriented Programming","text":""},{"location":"languages/kotlin/kotlin.html#class","title":"Class","text":"Kotlin
//primary constructor\nclass ClassName(private var attribute: Type) {\n\n}\n\nclass ClassName {\n\n    private var var1: Type\n\n    //secondary constructor\n    constructor(parameter: Type) {\n        this.var1 = parameter\n    }\n}\n
"},{"location":"languages/kotlin/kotlin.html#companion-object","title":"Companion Object","text":"

Companion Object Docs

Kotlin
class ClassName {\n\n    // in java: static\n    companion object  {\n        // static components of the class\n    }\n}\n
"},{"location":"languages/kotlin/kotlin.html#collections","title":"Collections","text":""},{"location":"languages/kotlin/kotlin.html#arraylist","title":"ArrayList","text":"Kotlin
var array:ArrayList<Type>? = null  // List init\n\narray.add(item)  //add item to list\n
"},{"location":"languages/php/composer.html","title":"Composer & Autoloading","text":""},{"location":"languages/php/composer.html#autoloading","title":"Autoloading","text":"

The function spl_autoload_register() allows to register a function that will be invoked when PHP needs to load a class/interface defined by the user.

In autoload.php:

PHP
# custom function\nfunction autoloader($class) {\n\n\n    # __DIR__ -> path of calling file\n    # $class -> className (hopefully same as file)\n    # if class is in namespace $class -> Namespace\\className (hopefully folders mirror Namespace)\n\n    $class = str_replace(\"\\\\\", DIRECTORY_SEPARATOR, $class);  # avoid linux path separator issues\n\n    $fileName = sprintf(\"%s\\\\path\\\\%s.php\", __DIR__, $class);  \n    # or\n    $filename = sprintf(\"%s\\\\%s.php\", __DIR__, $class);  # if class is in namespace\n\n    if (file_exists($fileName)) {\n        include $fileName;\n    }\n}\n\nspl_autoload_register('autoloader');  // register function\n

In file.php:

PHP
require \"autoload.php\";\n\n# other code\n

Note: will fuck up if namespaces exists.

"},{"location":"languages/php/composer.html#multiple-autoloading","title":"Multiple Autoloading","text":"

It's possible to resister multiple autoloading functions by calling spl_autoload_register() multiple times.

PHP
# prepend adds the function at the start of the queue\n# throws selects if errors in loading throw exceptions\nspl_autoload_register(callable $func, $throw=TRUE, $prepend=FALSE);\n\nspl_autoload_functions()  # return a list of registered functions.\n
"},{"location":"languages/php/composer.html#composer","title":"Composer","text":"

Open Source project for dependency management and autoloading of PHP libraries and classes.

Composer uses composer.json to define dependencies with third-party libraries. Libraries are downloaded through Packagist and GitHub.

In composer.json:

JSON
{\n    \"require\": {\n        \"php\": \">=7.0\",\n        \"monolog/monolog\": \"1.0.*\"\n    }\n}\n
"},{"location":"languages/php/composer.html#installing-dependencies","title":"Installing Dependencies","text":"

In the same folder of composer.json execute composer install.

Composer will create:

In alternative composer require <lib> will add the library to the project and create a composer.json if missing.

Note: to ignore the php version use composer <command> --ignore-platform-reqs

"},{"location":"languages/php/composer.html#updating-dependencies","title":"Updating Dependencies","text":"

To update dependencies use composer update. To update only the autoloading section use composer dump-autoload.

"},{"location":"languages/php/composer.html#autoloading-project-classes","title":"Autoloading Project Classes","text":"

PSR-4 Spec

Composer can also autoload classes belonging to the current project. It's sufficient to add the autoload keyword in the JSON and specify the path and autoload mode.

JSON
{\n    \"autoload\": {\n        \"psr-4\": {\n            \"RootNamespace\": \"src/\",\n            \"Namespace\\\\\": \"src/Namespace/\",\n            },\n        \"file\": [\n            \"path/to/file.php\",\n            ...\n        ]\n    }\n}\n
"},{"location":"languages/php/database.html","title":"Databases in PHP","text":""},{"location":"languages/php/database.html#php-data-objects-pdo","title":"PHP Data Objects (PDO)","text":"

PDO is the PHP extension for database access through a single API. It supports various databases: MySQL, SQLite, PostgreSQL, Oracle, SQL Server, etc.

"},{"location":"languages/php/database.html#database-connection","title":"Database Connection","text":"PHP
$dsn = \"mysql:dbname=<dbname>;host=<ip>\";\n$user=\"<db_user>\";\n$password=\"<db_password>\";\n\ntry {\n    $pdo = new PDO($dsn, $user, $password);  # connect, can throw PDOException\n} catch (PDOException $e) {\n    printf(\"Connection failed: %s\\n\", $e->getMessage());  # notify error\n    exit(1);\n}\n
"},{"location":"languages/php/database.html#queries","title":"Queries","text":"

To execute a query it's necessary to \"prepare it\" with parameters.

PHP
# literal string with markers\n$sql = 'SELECT fields\nFROM tables\nWHERE field <operator> :marker'\n\n$stmt = $pdo->prepare($sql, $options_array);  # returns PDOStatement, used to execute the query\n$stmt->execute([ ':marker' => value ]);  # substitute marker with actual value\n\n# fetchAll returns all matches\n$result = $stmt->fetchAll();  # result as associative array AND numeric array (PDO::FETCH_BOTH)\n$result = $stmt->fetchAll(PDO::FETCH_ASSOC);  # result as associative array\n$result = $stmt->fetchAll(PDO::FETCH_NUM);  # result as array\n$result = $stmt->fetchAll(PDO::FETCH_OBJ);  # result as object of stdClass\n$result = $stmt->fetchAll(PDO::FETCH_CLASS, ClassName::class);  # result as object of a specific class\n
"},{"location":"languages/php/database.html#parameter-binding","title":"Parameter Binding","text":"PHP
# bindValue\n$stmt = pdo->prepare(sql);\n$stmt->bindValue(':marker', value, PDO::PARAM_<type>);\n$stmt->execute();\n\n# bindParam\n$stmt = pdo->prepare(sql);\n$variable = value;\n$stmt->bindParam(':marker', $variable);  # type optional\n$stmt->execute();\n
"},{"location":"languages/php/database.html#pdo-data-types","title":"PDO & Data Types","text":"

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 behaviour.

PHP
pdo->setAttribute()\n\n$pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);\n$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n\n$stmt = $pdo->prepare($sql);\n$stmt->execute([':marker' => value]);\n$result = $stmt->fetchAll(PDO::FETCH_ASSOC);\n
"},{"location":"languages/php/database.html#pdo-debug","title":"PDO Debug","text":"PHP
$stmt = $pdo->prepare($sql);\n$stmt->execute([':marker' => value]);\n$result = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n$stmt->debugDumpParams();  # print the SQL query that has been sent to the database\n
"},{"location":"languages/php/database.html#sqlite3","title":"SQLite3","text":"PHP
$db = SQLite3(\"db_file.sqlite3\");  // connection\n\n$stmt = $db->prepare(\"SELECT fields FROM tables WHERE field <operator> :marker\");  // prepare query\n$stmt->bindParam(\":marker\", $variable);  // param binding\n\n$result = $stmt->execute();  // retrieve records\n$result->finalize();  // close result set, recommended calling before another execute()\n\n$records = $results->fetchArray(SQLITE3_ASSOC);  // extract records as array (false if no results)\n

Note: Result set objects retrieved by calling SQLite3Stmt::execute() on the same statement object are not independent, but rather share the same underlying structure. Therefore it is recommended to call SQLite3Result::finalize(), before calling SQLite3Stmt::execute() on the same statement object again.

"},{"location":"languages/php/dependency-injection.html","title":"Dependency Injection","text":"

Explicit definition of a class dependencies with the injection through the constructor or getters/setters.

PHP
class Foo\n{\n    public function __construct(PDO $pdo)  // depends on PDO\n    {\n        $this->pdo = $pdo;\n    }\n}\n
"},{"location":"languages/php/dependency-injection.html#dependency-injection-container","title":"Dependency Injection Container","text":"

The Dependency Injection Container (DIC) allow to archive all the dependencies in a single Container class. Some offer automatic resolution of the dependencies.

"},{"location":"languages/php/dependency-injection.html#php-di","title":"PHP-DI","text":"

The dependency injection container for humans. Installation: composer require php-di/php-di

PHP
class Foo\n{\n    private $bar;\n    public function __construct(Bar $bar)  // depends on Bar\n    {\n        $this->bar = $bar;\n    }\n}\n\nclass Bar{}\n\n$container = new DI\\Container();  // DI Container\n$foo = $container->get('Foo');  // get instance of Foo (automatic DI of Bar)\n
"},{"location":"languages/php/dependency-injection.html#dic-configuration","title":"DIC Configuration","text":"PHP
// Foo.php\nclass Foo\n{\n    public function __construct(PDO $pdo)  // depends on PDO\n    {\n        $this->pdo = $pdo;\n    }\n}\n
PHP
// config.php\nuse Psr\\Container\\ContainerInterface;\n\n// config \"primitive\" dependencies (dependency => construct & return)\nreturn [\n    'dsn' => 'sqlite:db.sq3',\n    PDO::class => function(ContainerInterface $c) {\n        return new PDO($c->get('dsn'));\n    },\n\n    ...\n];\n
PHP
$builder = new \\DI\\ContainerBuilder();\n$builder->addDefinitions(\"config.php\");  // load config\n$container = $builder->build();  // construct container\n$cart = $container->get(Foo::class);  // Instantiate & Inject\n

Note: get(\"className\") requires the explicit definition of className in the config file. get(ClassName::class) does not.

"},{"location":"languages/php/php.html","title":"PHP","text":"

PHP Docs

PHP
declare(strict_types=1);  # activates variable type checking on function arguments\n# single line comment\n//single line comment\n/* multi line comment */\n
"},{"location":"languages/php/php.html#include-require","title":"Include, Require","text":"PHP
include \"path\\\\file.php\";  # import an external php file, E_WARNING if fails\ninclude_once \"path\\\\file.php\";  # imports only if not already loaded\n\nrequire \"path\\\\file.php\";  # import an external php file, E_COMPILE_ERROR if fails\nrequire_once \"path\\\\file.php\";  # imports only if not already loaded\n
"},{"location":"languages/php/php.html#import-configs-from-a-file-with-include","title":"Import configs from a file with include","text":"

In config.php:

PHP
//config.php\n\n//store configuration options in associative array\nreturn [\n    setting => value,\n    setting = value,\n]\n
PHP
$config = include \"config.php\";  // retrieve config and store into variable\n
"},{"location":"languages/php/php.html#namespace","title":"Namespace","text":"

PSR-4 Spec

PHP
namespace Foo\\Bar\\Baz;   # set namespace for all file contents, \\ for nested namespaces\n\nuse <PHP_Class>  # using a namespace hides standard php classes (WHY?!?)\n\n# namespace for only a block of code\nnamespace Foo\\Bar\\Baz {\n    function func() {\n        # coded here\n    }\n};\n\n\nFoo\\Bar\\Baz\\func();  # use function from Foo\\Bar\\Baz without USE instruction\n\nuse Foo\\Bar\\Baz\\func; # import namespace\nfunc(); # use function from Foo\\Bar\\Baz\n\nuse Foo\\Bar\\Baz\\func as f;  # use function with an alias\nf();  # use function from Foo\\Bar\\Baz\n\nuse Foo\\Bar\\Baz as fbb  # use namespace with alias\nfnn\\func();  # use function from Foo\\Bar\\Baz\n
"},{"location":"languages/php/php.html#basics","title":"Basics","text":"PHP
declare(strict_types=1);  # activates type checking\n# single line comment\n//single line comment\n/* multi line comment */\n
"},{"location":"languages/php/php.html#screen-output","title":"Screen Output","text":"PHP
echo \"string\";  # string output\necho 'string\\n';  # raw string output\nprintf(\"format\", $variables);  # formatted output of strings and variables\nsprintf(\"format\", $variables);  # return formatted string\n
"},{"location":"languages/php/php.html#user-input","title":"User Input","text":"PHP
$var = readline(\"prompt\");\n\n# if readline is not installed\nif (!function_exists('readline')) {\n    function readline($prompt)\n    {\n        $fh = fopen('php://stdin', 'r');\n        echo $prompt;\n        $userInput = trim(fgets($fh));\n        fclose($fh);\n\n        return $userInput;\n    }\n}\n
"},{"location":"languages/php/php.html#variables","title":"Variables","text":"PHP
$variableName = value;  # weakly typed\necho gettype(&variable);  # output type of variable\n\nvar_dump($var);  # prints info of variable (bit dimension, type & value)\n
"},{"location":"languages/php/php.html#integers","title":"Integers","text":"PHP
&max = PHP_INT_MAX;  # max value for int type -> 9223372036854775807\n&min = PHP_INT_MIN;  # min value for int type -> -9223372036854775808\n&bytes = PHP_INT_SIZE;  # bytes for int type -> 8\n\n&num = 255;  # decimal\n&num = 0b11111111;  # binary\n&num = 0377;  # octal\n&num = 0xff;  # hexadecimal\n
"},{"location":"languages/php/php.html#double","title":"Double","text":"PHP
$a = 1.234; // 1.234\n$b = 1.2e3; // 1200\n$c = 7E-10; // 0.0000000007\n
"},{"location":"languages/php/php.html#mathematical-operators","title":"Mathematical Operators","text":"Operator Operation - Subtraction * Multiplication / Division % Modulo ** Exponentiation var++ Post Increment ++var Pre Increment var-- Post Decrement --var Pre Decrement"},{"location":"languages/php/php.html#mathematical-functions","title":"Mathematical Functions","text":""},{"location":"languages/php/php.html#strings","title":"Strings","text":"

A string is a sequence of ASCII characters. In PHP a string is an array of characters.

"},{"location":"languages/php/php.html#string-concatenation","title":"String Concatenation","text":"PHP
$string1 . $string2; # method 1\n$string1 .= $string2;  # method 2\n
"},{"location":"languages/php/php.html#string-functions","title":"String Functions","text":"PHP
strlen($string);  # returns the string length\nstrpos($string, 'substring');  # position of substring in string\nsubstr($string, start, len);  # extract substring of len from position start\nstrtoupper($string);  # transform to uppercase\nstrtolower($string);  # transform to lowercase\n\nexplode(delimiter, string);  # return array of substrings\n\n$var = sprintf(\"format\", $variables)  # construct and return a formatted string\n
"},{"location":"languages/php/php.html#constants","title":"Constants","text":"PHP
define ('CONSTANT_NAME', 'value')\n
"},{"location":"languages/php/php.html#magic-constants-__name__","title":"Magic Constants __NAME__","text":""},{"location":"languages/php/php.html#array","title":"Array","text":"

Heterogeneous sequence of values.

PHP
$array = (sequence_of_items);  # array declaration and valorization\n$array = [sequence_of_items];  # array declaration and valorization\n\n# index < 0 selects items starting from the last\n$array[index];  # access to the items\n$array[index] = value;   # array valorization (can add items)\n\n$array[] = value;  # value appending\n
"},{"location":"languages/php/php.html#multi-dimensional-array-matrix","title":"Multi Dimensional Array (Matrix)","text":"

Array of array. Can have arbitrary number of nested array

PHP
$matrix = [\n    [1, 2, 3],\n    [4, 5, 6],\n    [7, 8, 9]\n];\n
"},{"location":"languages/php/php.html#array-printing","title":"Array Printing","text":"

Single instruction to print whole array is ``

PHP
$array = [1, 2, 3];\nprint_r($array);  # print all the array values\n
"},{"location":"languages/php/php.html#array-functions","title":"Array Functions","text":"PHP
count($array);  # returns number of items in the array\narray_sum($array)  # sum of the array value\nsort($array);  # quick sort\nin_array($item, $array);  // check if item is in the array\narray_push($array, $item);  // append item to the array\nunset($array[index]);  # item (or variable) deletion\n\n# array navigation\ncurrent();\nkey();\nnext();\nprev();\nreset();\nend();\n\n# sorting\nsort($array, $sort_flags=\"SORT_REGULAR\");\n\narray_values($array);   # regenerates the array fixing the indexes\n\nlist($array1 [, $array2, ...]) = $data;  # Python-like tuple unpacking\n
"},{"location":"languages/php/php.html#associative-arrays","title":"Associative Arrays","text":"

Associative arrays have a value as an index. Alternative names are hash tables or dictionaries.

PHP
$italianDay = [\n    'Mon' => 'Luned\u00ec',\n    'Tue' => 'Marted\u00ec',\n    'Wed' => 'Mercoled\u00ec',\n    'Thu' => 'Gioved\u00ec',\n    'Fri' => 'Venerd\u00ec',\n    'Sat' => 'Sabato',\n    'Sun' => 'Domenica'\n];\n\n$italianDay[\"Mon\"];  # evaluates to Luned\u00ec\n
"},{"location":"languages/php/php.html#conditional-instructions","title":"Conditional Instructions","text":""},{"location":"languages/php/php.html#conditional-operators","title":"Conditional Operators","text":"Operator Operation $a == $b value equality $a === $b value & type equality $a != $b value inequality $a <> $b value inequality $a !== $b value or type inequality $a < $b less than $a > $b greater than $a <= $b less or equal to $a >= $b greater or equal to $a <=> $b spaceship operator

With == a string evaluates to 0.

"},{"location":"languages/php/php.html#logical-operators","title":"Logical Operators","text":"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. and $a && $b TRUE if both $a and $b are TRUE. or $a || $b TRUE if either $a or $b is TRUE."},{"location":"languages/php/php.html#ternary-operator","title":"Ternary Operator","text":"PHP
condition ? result_if_true : result_if_false;\ncondition ?: result_if_false;\n
"},{"location":"languages/php/php.html#null-coalesce","title":"NULL Coalesce","text":"PHP
$var1 = $var2 ?? value;  # if variable == NULL assign value, otherwise return value of $var2\n\n# equivalent to\n$var1 = isset($var2) ? $var2 : value\n
"},{"location":"languages/php/php.html#spaceship-operator","title":"Spaceship Operator","text":"PHP
$a <=> $b;\n\n# equivalent to\nif $a > $b\n    return 1;\nif $a == $b\n    return 0;\nif $a < $b\n    return -1;\n
"},{"location":"languages/php/php.html#if-elseif-else","title":"If - Elseif - Else","text":"PHP
if (condition) {\n  # code here\n} elseif (condition) {\n  # code here\n} else {\n    # code here\n}\n\nif (condition) :\n    # code here\nelseif (condition):\n    # code here\nelse:\n    # code here\nendif;\n
"},{"location":"languages/php/php.html#switch-case","title":"Switch Case","text":"PHP
# weak comparison\nswitch ($var) {\n    case value:\n        # code here\n        break;\n\n    default:\n        # code here\n}\n\n# strong comparison\nswitch (true) {\n    case $var === value:\n        # code here\n        break;\n\n    default:\n        # code here\n}\n
"},{"location":"languages/php/php.html#match-expression-php-8","title":"Match Expression (PHP 8)","text":"

match can return values, doesn't require break statements, can combine conditions, uses strict type comparisons and doesn't do any type coercion.

PHP
$result = match($input) {\n    0 => \"hello\",\n    '1', '2', '3' => \"world\",\n};\n
"},{"location":"languages/php/php.html#loops","title":"Loops","text":""},{"location":"languages/php/php.html#for-foreach","title":"For, Foreach","text":"PHP
for (init, condition, increment){\n    # code here\n}\n\nfor (init, condition, increment):\n    # code here\nendfor;\n\nforeach($sequence as $item) {\n    # code here\n}\n\nforeach($sequence as $item):\n    # code here\nendforeach;\n\n# foreach on dicts\nforeach($sequence as $key => $value) {\n    # code here\n}\n
"},{"location":"languages/php/php.html#while-do-while","title":"While, Do-While","text":"PHP
while (condition) {\n    # code here\n}\n\nwhile (condition):\n    # code here\nendwhile;\n\ndo {\n    # code here\n} while (condition);\n
"},{"location":"languages/php/php.html#break-continue-exit","title":"Break, Continue, exit()","text":"

break stops the iteration. continue skips one cycle of the iteration. exit() terminates the execution of any PHP code.

"},{"location":"languages/php/php.html#functions","title":"Functions","text":"

Function Docstring

Parameters with default values are optional in the function call and must be the last ones in the function declaration. Return type is optional if type checking is disabled.

PHP
declare(strict_types=1);  # activates type checking\n\n/**\n * Summary.\n *\n * Description.\n *\n * @since x.x.x\n *\n * @see Function/method/class relied on\n * @link URL\n * @global type $varname Description.\n * @global type $varname Description.\n *\n * @param type $var Description.\n * @param type $var Optional. Description. Default.\n * @return type Description.\n */\nfunction functionName (type $parameter, $parameter = default_value): Type\n{\n    # code here\n    return <expression>;\n}\n
"},{"location":"languages/php/php.html#void-function","title":"Void function","text":"PHP
function functionName (type $parameter, $parameter = default_value): Void\n{\n    # code here\n}\n
"},{"location":"languages/php/php.html#passing-a-parameter-by-reference","title":"Passing a parameter by reference (&$)","text":"PHP
function functionName (type &$parameter): Type\n{\n    # code here\n    return <expression>;\n}\n
"},{"location":"languages/php/php.html#variable-number-of-parameters-variadic-operator","title":"Variable number of parameters, variadic operator (...)","text":"PHP
function functionName (type $parameter, ...$args): Type\nfunction functionName (type $parameter, type ...$args): Type\n{\n    # code here\n    return <expression>;\n}\n
"},{"location":"languages/php/php.html#nullable-parameters","title":"Nullable parameters","text":"PHP
function functionName (?type $parameter): ?Type\n{\n    # code here\n    return <expression>;\n}\n
"},{"location":"languages/php/php.html#anonymous-functions-closure","title":"Anonymous Functions (Closure)","text":"PHP
# declaration and assignment to variable\n$var = function (type $parameter) {\n    # code here\n};\n\n$var($arg);\n
"},{"location":"languages/php/php.html#use-operator","title":"Use Operator","text":"PHP
# use imports a variable into the closure\n$foo = function (type $parameter) use ($average) {\n    # code here\n}\n
"},{"location":"languages/php/php.html#union-types-php-8","title":"Union Types (PHP 8)","text":"

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;\n
"},{"location":"languages/php/php.html#named-arguments-php-8","title":"Named Arguments (PHP 8)","text":"

Named arguments allow to pass in values to a function, by specifying the value name, to avoid taking their order into consideration. It's also possible to skip optional parameters.

PHP
function foo(string $a, string $b, ?string $c = null, ?string $d = null) { /* \u2026 */ }\n\nfoo(\n    b: 'value b',\n    a: 'value a',\n    d: 'value d',\n);\n
"},{"location":"languages/php/php.html#object-oriented-programming","title":"Object Oriented Programming","text":""},{"location":"languages/php/php.html#scope-visibility","title":"Scope & Visibility","text":"

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.

"},{"location":"languages/php/php.html#class-declaration-instantiation","title":"Class Declaration & Instantiation","text":"PHP
# case insensitive\nclass ClassName\n{\n\n    const CONSTANT = value;  # public by default\n\n    public $attribute;  # null by default if not assigned\n    public Type $attribute;  # specifying the type is optional, it will be enforced if present\n\n    # class constructor\n    public function __construct(value)\n    {\n        $this->attribute =  value\n    }\n\n    public getAttribute(): Type\n    {\n        return $this->attribute;\n    }\n\n    public function func(): Type\n    {\n        # code here\n    }\n}\n\n$object = new ClassName;  # case insensitive (CLASSNAME, ClassName, classname)\n$object->attribute = value;\n$object->func();\n$object::CONSTANT;\n\n$var = $object;  # copy by reference\n$var = clone $object  # copy by value\n\n$object instanceof ClassName  // check type of the object\n
"},{"location":"languages/php/php.html#static-classes-attributes-methods","title":"Static classes, attributes & methods","text":"

Inside static methods it's impossible to use $this. A static variable is unique for the class and all instances.

PHP
class ClassName {\n\n    public static $var;\n\n    public static function func(){\n        //code here\n    }\n\n    public static function other_func(){\n        //code here\n        self::func();\n    }\n}\n\nClassName::func();  // use static function\n\n$obj = new ClassName();\n$obj::$var;  // access to the static variable\n
"},{"location":"languages/php/php.html#dependency-injection","title":"Dependency Injection","text":"

Parameters of the dependency can be modified before passing the required class to the constructor.

PHP
class ClassName\n{\n    private $dependency;\n\n    public function __construct(ClassName requiredClass)\n    {\n        $this->dependency = requiredClass;  # necessary class is passed to the constructor\n    }\n}\n
"},{"location":"languages/php/php.html#inheritance","title":"Inheritance","text":"

If a class is defined final it can't be extended. If a function is declared final it can't be overridden.

PHP
class Child extends Parent\n{\n    public __construct() {\n        parent::__construct();  # call parent's method\n    }\n}\n
"},{"location":"languages/php/php.html#abstract-class","title":"Abstract Class","text":"

Abstract classes cannot be instantiated;

PHP
abstract class ClassName\n{\n    # code here\n}\n
"},{"location":"languages/php/php.html#interface","title":"Interface","text":"

An interface is a \"contract\" that defines what methods the implementing classes must have and implement.

A class can implement multiple interfaces but there must be no methods in common between interface to avoid ambiguity.

PHP
interface InterfaceName {\n\n    // it is possible to define __construct\n\n    // function has no body; must be implements in the class that uses the interface\n    public function functionName (parameters) : Type;  // MUST be public\n}\n\n\nclass ClassName implements InterfaceName {\n    public function functionName(parameters) : Type {\n        //implementation here\n    }\n}\n
"},{"location":"languages/php/php.html#traits","title":"Traits","text":"

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 conflict 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 {\n    // code here\n}\n\nclass ClassName {\n    use TraitName, {TraitName::func() insteadof OtherTrait}, { func() as alias };  # can use multiple traits\n    # code here\n}\n
"},{"location":"languages/php/php.html#anonymous-classes","title":"Anonymous Classes","text":"PHP
$obj = new ClassName;\n\n$obj->method(new class implements Interface {\n    public function InterfaceFunc() {\n        // code here\n    }\n});\n
"},{"location":"languages/php/php.html#serialization-json","title":"Serialization & JSON","text":"PHP
$serialized = serialize($obj);  # serialization\n$obj = unserialize($serialized);  # de-serialization\n\n$var = json_decode(string $json, bool $associative);  # Takes a JSON encoded string and converts it into a PHP variable.\u00f9\n$json = json_encode($value);  # Returns a string containing the JSON representation of the supplied value.\n
"},{"location":"languages/php/php.html#files","title":"Files","text":""},{"location":"languages/php/php.html#readwrite-on-files","title":"Read/Write on Files","text":"PHP
file(filename);  // return file lines in an array\n\n// problematic with large files (allocates memory to read all file, can fill RAM)\nfile_put_contents(filename, data);  // write whole file\nfile_get_contents(filename);  // read whole file\n
"},{"location":"languages/php/php.html#regular-expressions","title":"Regular Expressions","text":"PHP
preg_match('/PATTERN/', string $subject, array $matches);  # returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred\n# $matches[0] = whole matched string\n# $matches[i] = i-th group of the regex\n
"},{"location":"languages/php/php.html#hashing","title":"Hashing","text":"

Supported hashing algrithms:

PHP
hash($algorithm, $data);\n
"},{"location":"languages/php/php.html#password-hashes","title":"Password Hashes","text":"

password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

Algorithms currently supported:

Supported options for PASSWORD_BCRYPT:

Supported options for PASSWORD_ARGON2I and PASSWORD_ARGON2ID:

PHP
password_hash($password, $algorithm);  # create a new password hash using a strong one-way hashing algorithm.\npassword_verify($password, $hash);  # Verifies that a password matches a hash\n
"},{"location":"languages/php/php.html#errors","title":"Errors","text":"

Types of PHP errors:

PHP
$a = new StdClass()\n$a->foo();  // PHP Fatal Error: foo() does not exist\n
PHP
$a = 0;\necho 1/$a;  // PHP Warning: Division by zero\n
PHP
echo $a;  // PHP Notice: $a undefined\n
"},{"location":"languages/php/php.html#error-reporting","title":"Error Reporting","text":"

PHP Error Constants

Its possible to configure PHP to signal only some type of errors. Errors below a certain levels are ignored.

PHP
error_reporting(E_<type>);  // set error report threshold (for log file)\n// does not disable PARSER ERROR\n\nini_set(\"display_errors\", 0);  // don't display any errors on stderr\nini_set(\"error_log\", \"path\\\\error.log\");  // set log file\n
"},{"location":"languages/php/php.html#triggering-errors","title":"Triggering Errors","text":"PHP
// generate E_USER_ errors\ntrigger_error(\"message\");  // default type: E_USER_NOTICE\ntrigger_error(\"message\", E_USER_<Type>);\n\ntrigger_error(\"Deprecated Function\", E_USER_DEPRECATED);\n
"},{"location":"languages/php/php.html#writing-in-the-log-file","title":"Writing in the Log File","text":"

It's possible to use log files unrelated to the php log file.

PHP
error_log(\"message\", 3, \"path\\\\log.log\");  // write log message to a specified file\n\n//example\nerror_log(sprintf(\"[%s] Error: _\", date(\"Y-m-d h:i:s\")), 3, \"path\\\\log.log\")\n
"},{"location":"languages/php/php.html#exception-handling","title":"Exception Handling","text":"

PHP offers the possibility to handle errors with the exception model.

PHP
try {\n    // dangerous code\n} catch(ExceptionType1 | ExceptionType2 $e) {\n    printf(\"Errore: %s\", $e->getMessage());\n} catch(Exception $e) {\n    // handle or report exception\n}\n\nthrow new ExceptionType(\"message\");  // throw an exception\n

All exceptions in PHP implement the interface Throwable.

PHP
Interface Throwable {\n    abstract public string getMessage ( void )\n    abstract public int getCode ( void )\n    abstract public string getFile ( void )\n    abstract public int getLine ( void )\n    abstract public array getTrace ( void )\n    abstract public string getTraceAsString ( void )\n    abstract public Throwable getPrevious ( void )\n    abstract public string __toString ( void )\n}\n
"},{"location":"languages/php/php.html#custom-exceptions","title":"Custom Exceptions","text":"PHP
/**\n * Define a custom exception class\n */\nclass CustomException extends Exception\n{\n    // Redefine the exception so message isn't optional\n    public function __construct($message, $code = 0, Exception $previous = null) {\n        // some code\n\n        // make sure everything is assigned properly\n        parent::__construct($message, $code, $previous);\n    }\n\n    // custom string representation of object\n    public function __toString() {\n        return __CLASS__ . \": [{$this->code}]: {$this->message}\\n\";\n    }\n\n    public function customFunction() {\n        echo \"A custom function for this type of exception\\n\";\n    }\n}\n
"},{"location":"languages/php/plates-templating.html","title":"Templates with Plates","text":""},{"location":"languages/php/plates-templating.html#template","title":"Template","text":"

To separate HTML code and PHP code it's possible to use templates with markers for variable substitution. Variables are created in the PHP code and are passed to the template in the rendering phase. The server transmits only the index.php file to the user. The php file renders the templates as needed.

HTML
<html>\n    <head>\n        <title><?= $this->e($title)?></title>\n    </head>\n\n    <body>\n        <?= $this->section('content')?>\n    </body>\n</html>\n
"},{"location":"languages/php/plates-templating.html#plates","title":"Plates","text":"

Plates is a template engine for PHP. A template engine permits to separate the PHP code (business logic) from the HTML pages.

Installation through composer: composer require league/plates.

PHP
# index.php\nrequire \"vendor/autoload.php\";\n\nuse League\\Plates\\Engine;\n\n$templates = new Engine(\"path\\\\to\\\\templates\");\n\necho $templates->render(\"template_name\", [\n    \"key_1\" => \"value_1\",\n    \"key_2\" => \"value_2\"\n]);\n
PHP
# template.php\n<html>\n    <head>\n        <title><?= $key_1?></title>\n    </head>\n\n    <body>\n        <h1>Hello <?= $key_2 ?></h1>\n    </body>\n</html>\n

Variables in the template are created through an associative array key => value. The key (\"key\") becomes a variable ($key) in the template.

"},{"location":"languages/php/plates-templating.html#layout","title":"Layout","text":"

It's possible to create a layout (a model) for a group of pages to make that identical save for the contents. In a layout it's possible to create a section called content that identifies content that can be specified at runtime.

Note: Since only the template has the data passed eventual loops have to be done there.

PHP
# index.php\nrequire 'vendor/autoload.php';\nuse League\\Plates\\Engine;\n$template = new Engine('/path/to/templates');\necho $template->render('template_name', [ \"marker\" => value, ... ]);\n
PHP
# template.php\n\n# set the layout used for this template\n<?php $this->layout(\"layout_name\", [\"marker\" => value, ...]) ?>  # pass values to the layout\n\n# section contents\n<p> <?= $this->e($marker) ?> </p>\n
PHP
# layout.php\n<html>\n    <head>\n        <title><?= $marker ?></title>\n    </head>\n    <body>\n        <?= $this->section('content')?>  # insert the section\n    </body>\n</html>\n
"},{"location":"languages/php/plates-templating.html#escape","title":"Escape","text":"

It's necessary to verify that the output is in the necessary format.

Plates offers $this->escape() or $this->e() to validate the output. In general the output validation allows to prevent Cross-Site Scripting (XSS).

"},{"location":"languages/php/plates-templating.html#folders","title":"Folders","text":"PHP
# index.php\n$templates->addFolder(\"alias\", \"path/to/template/folder\");  # add a template folder\necho $templates->render(\"folder::template\");  # use a template in a specific folder\n
"},{"location":"languages/php/plates-templating.html#insert","title":"Insert","text":"

It's possible to inject templates in a layout or template. It is done by using the insert() function.

PHP
# layout.php\n<html>\n    <head>\n        <title><?=$this->e($title)?></title>\n    </head>\n    <body>\n        <?php $this->insert('template::header') ?>  # insert template\n\n        <?= $this->section('content')?>  # page contents\n\n        <?php $this->insert('template::footer') ?>  # insert template\n    </body>\n</html>\n
"},{"location":"languages/php/plates-templating.html#sections","title":"Sections","text":"

It's possible to insert page contest from another template with the section() function. The content to be inserted must be surrounded with by the start() and stop() functions.

PHP
# template.php\n\n<?php $this->start(\"section_name\") ?>  # start section\n#  section contents (HTML)\n<?php $this->stop() ?>  # stop section\n\n# append to section is existing, create if not\n<?php $this->push(\"section_name\") ?>\n#  section contents (HTML)\n<?php $this->end() ?>\n
"},{"location":"languages/php/psr-7.html","title":"PSR-7","text":""},{"location":"languages/php/psr-7.html#psr-7_1","title":"PSR-7","text":"

Standard of the PHP Framework Interop Group that defines common interfaces for handling HTTP messages.

Example:

PHP
// empty array if not found\n$header = $request->getHeader('Accept');\n\n// empty string if not found\n$header = $request->getHeaderLine('Accept');\n\n// check the presence of a header\nif (! $request->hasHeader('Accept')) {}\n\n// returns the parameters in a query string\n$query = $request->getQueryParams();\n
"},{"location":"languages/php/psr-7.html#immutability","title":"Immutability","text":"

PSR-7 requests are immutable objects; a change in the data will return a new instance of the object. The stream objects of PSR-7 are not immutable.

"},{"location":"languages/php/unit-tests.html","title":"PHP Unit Test","text":""},{"location":"languages/php/unit-tests.html#installation-configuration","title":"Installation & Configuration","text":""},{"location":"languages/php/unit-tests.html#dev-only-installation","title":"Dev-Only Installation","text":"PowerShell
composer require --dev phpunit/phpunit\n
JSON
    \"require-dev\": {\n        \"phpunit/phpunit\": \"<version>\"\n    }\n
"},{"location":"languages/php/unit-tests.html#config","title":"Config","text":"

PHPUnit can be configured in a XML file called phpunit.xml:

XML
<phpunit xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:noNamespaceSchemaLocation=\"vendor/phpunit/phpunit/phpunit.xsd\"\n         bootstrap=\"vendor/autoload.php\"\n         colors=\"true\">\n\n    <testsuites>\n        <testsuit name=\"App\\\\Tests\">\n            <directory>./test<directory>\n        </testsuit>\n    </testsuites>\n\n    <filter>\n        <whitelist processUncoveredFilesFromWhitelist=\"true\">\n            <directory suffix=\".php\">./src</directory>\n        </whitelist>\n    </filter>\n</phpunit>\n
"},{"location":"languages/php/unit-tests.html#testing","title":"Testing","text":""},{"location":"languages/php/unit-tests.html#test-structure","title":"Test Structure","text":"

PHPUnit tests are grouped in classes suffixed with Test. Each class extends PHPUnit\\Framework\\TestCase. A test is a method of a test class prefixed with test. PHPUnit is executed from the command line with vendor/bin/phpunit --colors.

PHP
namespace App;\n\nclass Filter\n{\n    public function isEmail(string $email): bool\n    {\n        // @todo implement\n    }\n}\n
PHP
namespace App\\Test;\nuse PHPUnit\\Framework\\TestCase;\nuse App\\Filter;\n\nclass FilterTest extends TestCase\n{\n    public function testValidMail()\n    {\n        $filter = new Filter();\n        $this->assertTrue($filter->isEmail(\"foo@bar.com\"));\n    }\n\n    public function testInvalidEmail()\n    {\n        $filter = new Filter();\n        $this->assertFalse($filter->idEmail(\"foo\"));\n    }\n}\n
"},{"location":"languages/php/unit-tests.html#phpunit-assertions","title":"PHPUnit Assertions","text":""},{"location":"languages/php/unit-tests.html#phpunit-testing-exceptions","title":"PHPUnit Testing Exceptions","text":"PHP
public function testAggiungiEsameException(string $esame)\n{\n    $this->expectException(Exception::class);\n    $this->expectExceptionMessage(\"exception_message\");\n\n    // execute code that should throw an exception\n}\n\n// https://github.com/sebastianbergmann/phpunit/issues/2484#issuecomment-648822531\npublic function testExceptionNotThrown()\n{\n    $exceptionWasThrown = false;\n\n    try\n    {\n        // code that should succeed\n    }\n    catch (EsameException $e)\n    {\n        $exceptionWasThrown = true;\n    }\n\n    $this->assertFalse($exceptionWasThrown);\n}\n\n// same as\n\n/**\n* @doesNotPerformAssertions\n*/\npublic function testNoExceptions(string $esame)\n{\n    // code that should succeed (exceptions will make the test fail)\n}\n
"},{"location":"languages/php/unit-tests.html#test-setup-teardown-example","title":"Test Setup & Teardown (Example)","text":"PHP
class ClassTest extends TestCase\n{\n    // initialize the test\n    public function setUp(): void\n    {\n        file_put_contents(\"/tmp/foo\", \"Test\")\n    }\n\n    // reset the test\n    public function tearDown(): void\n    {\n        unlink(\"/tmp/foo\")\n    }\n\n    public function testFoo()\n    {\n        // use temp file\n    }\n}\n

Note: setUp() and tearDown() are called before and after each test method.

"},{"location":"languages/php/unit-tests.html#data-provider","title":"Data Provider","text":"PHP
class DataTest extends TestCase\n{\n    /**\n    * @dataProvider provider\n    */\n    public function testAdd($a, $b, $expected)\n    {\n        $this->assertEquals($expected, $a + $b);\n    }\n\n    // test receives array contents as input\n    public function provider()\n    {\n        // must return array of arrays\n        return [\n            [0, 0, 0],\n            [0, 1, 1]\n        ];\n    }\n\n    // test receives array of arrays as input\n    public function provideArrayOfArrays()\n    {\n        return [\n            [\n                [\n                    [0, 0, 0],\n                    [0, 1, 1]\n                ]\n            ]\n        ];\n    }\n}\n
"},{"location":"languages/php/unit-tests.html#mock-objects","title":"Mock Objects","text":"PHP
class UnitTest extends TestCase\n{\n    public function setUp()\n    {\n        // names of mock are independent from tested class variables\n        $this->mock = $this->createMock(ClassName::class);  // create a mock object of a class\n        $this->returned = $this->createMock(ClassName::class);  // mock of returned object\n\n        $this->mock->method(\"methodName\")  // simulate method on mock\n            ->with($this->equalTo(param), ...)  // specify input params (one param per equalTo)\n            ->willReturn($this->returned);  // specify return value\n    }\n\n    public function testMethod()\n    {\n        $this->mock\n        ->method(\"methodName\")\n        ->with($this->equalTo($arg))  // arg passed to the method\n        ->willReturn(value);  // actual return value for THIS case\n        // or\n        ->will($this->throwException(new Exception()));  // method will throw exception\n\n        // assertions\n    }\n}\n
"},{"location":"languages/php/unit-tests.html#code-coverage-needs-xdebug","title":"Code Coverage (needs XDebug)","text":"PowerShell
vendor/bin/phpunit --coverage-text  # code coverage analysis in the terminal\n
"},{"location":"languages/php/web.html","title":"PHP for the Web","text":""},{"location":"languages/php/web.html#php-internal-web-server","title":"PHP Internal Web Server","text":"

Command Line Web Server in PHP, useful in testing phase. Limited since handles only one request at a time. Do not use in production.

PowerShell
PHP -S <ip:post>  # start web server\nPHP -S <ip:post> -t /path/to/folder  # execute in specified folder at specified address\nPHP -S <ip:post> file.php  # redirect requests to single file\n
"},{"location":"languages/php/web.html#http-methods","title":"HTTP Methods","text":"

Handling of HTTP requests happens using the following global variables:

"},{"location":"languages/php/web.html#_files","title":"$_FILES","text":"HTML
<!-- method MUST BE post -->\n<!-- must have enctype=\"multipart/form-data\" attribute -->\n<form name=\"<name>\" action=\"file.php\" method=\"POST\" enctype=\"multipart/form-data\">\n    <input type=\"file\" name=\"photo\" />\n    <input type=\"submit\" name=\"Send\" />\n</form>\n

Files in $_FILES are memorized in a system temp folder. They can be moved with move_uploaded_file()

PHP
if (! isset($_FILES['photo']['error'])) {\n    http_response_code(400);  # send a response code\n    echo'<h1>No file has been sent</h1>';\n    exit();\n}\n\nif ($_FILES['photo']['error'] != UPLOAD_ERR_OK) {\n        http_response_code(400);\n        echo'<h1>The sent file is invalid</h1>';\n        exit();\n}\n\n$path = '/path/to/' . $_FILES['photo']['name'];\n\nif (! move_uploaded_file($_FILES['photo']['tmp_name'], $path)) {\n    http_response_code(400);\n    echo'<h1>Error while writing the file</h1>';\n    exit();\n}\n\necho'<h1>File successfully sent</h1>';\n
"},{"location":"languages/php/web.html#_server","title":"$_SERVER","text":"

Request Header Access:

PHP
$_SERVER[\"REQUEST_METHOD\"];\n$_SERVER[\"REQUEST_URI\"];\n$_SERVER[\"SERVER_PROTOCOL\"];  // HTTP Versions\n$_SERVER[\"HTTP_ACCEPT\"];\n$_SERVER[\"HTTP_ACCEPT_ENCODING\"];\n$_SERVER[\"HTTP_CONNECTION\"];\n$_SERVER[\"HTTP_HOST\"];\n$_SERVER[\"HTTP_USER_AGENT\"];\n// others\n
"},{"location":"languages/php/web.html#_cookie","title":"$_COOKIE","text":"

Cookie Laws Garante Privacy 8/5/2014

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 visiting the website. When a client receives a HTTP response that contains Set-Cookie headers it has to memorize that info and reuse them in future requests.

HTTP
Set-Cookie: <cookie-name>=<cookie-value>\nSet-Cookie: <cookie-name>=<cookie-value>; Expires=<date>\nSet-Cookie: <cookie-name>=<cookie-value>; Max-Age=<seconds>\nSet-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>\nSet-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>\nSet-Cookie: <cookie-name>=<cookie-value>; Secure\nSet-Cookie: <cookie-name>=<cookie-value>; HttpOnly\n

Anyone can modify the contents of a cookie; for this reason cookies must not contain personal or sensible info.

When a client has memorized a cookie, it is sent in successive HTTP requests through the Cookie header.

HTTP
Cookie: <cookie-name>=<cookie-value>\n

PHP setcookie docs

PHP
setcookie (\nstring $name,\n[ string $value = \"\" ],\n[ int $expire = 0 ],  // in seconds (time() + seconds)\n[ string $path = \"\" ],\n[ string $domain = \"\" ],\n[ bool $secure = false ],  // use https\n[ bool $httponly = false ]  // accessible only through http (no js, ...)\n)\n\n// example: memorize user-id 112 with 24h expiry for site example.com\nsetcookie (\"User-id\", \"112\", time() + 3600*24, \"/\", \"example.com\");\n\n// check if a cookie exists\nif(isset($_COOKIE[\"cookie_name\"])) {}\n
"},{"location":"languages/php/web.html#_session","title":"$_SESSION","text":"

Sessions are info memorized on the server associated to the client that makes an HTTP request.

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 necessary to recall the function session_start() at the beginning of a PHP script that deals with sessions. After starting the session information in be saved in the $_SESSION array.

PHP
$_SESSION[\"key\"] = value;  // save data in session file (serialized data)\n\nunset($_SESSION[\"key\"]);  // delete data from the session\nsession_unset();  # remove all session data\nsession_destroy();  # destroy all of the data associated with the current session.\n# It does not unset any of the global variables associated with the session, or unset the session cookie.\n

Session data is be memorized in a file by serializing $_SESSION. Files are named as sess_PHPSESSID in a folder (var/lib/php/sessions in Linux).

It's possible to modify the memorization system of PHP serialization variables by:

"},{"location":"languages/php/web.html#php-web-instructions","title":"PHP Web Instructions","text":"

http_response_code() is used to return an HTTP response code. If no code is specified 200 OK is returned. header(\"Location: /route\") is used to make a redirect to another UTL.

"},{"location":"languages/php/simple-mvc/rest-api.html","title":"REST API with Simple-MVC","text":""},{"location":"languages/php/simple-mvc/rest-api.html#routing-example","title":"Routing (Example)","text":"PHP
// config/route.php\nreturn [   \n   [ 'GET', '/api/user[/{id}]', Controller\\User::class ],\n   [ 'POST', '/api/user', Controller\\User::class ],\n   [ 'PATCH', '/api/user/{id}', Controller\\User::class ],\n   [ 'DELETE', '/api/user/{id}', Controller\\User::class ]\n];\n
"},{"location":"languages/php/simple-mvc/rest-api.html#controller-example","title":"Controller (Example)","text":"PHP
public class UserController implements ControllerInterface\n{\n    public function __construct(UserModel $user)\n    {\n        $this->userModel = $user;\n\n        // Set the Content-type for all the HTTP methods\n        header('Content-type: application/json');\n    }\n\n    // method dispatcher\n    public function execute(ServerRequestInterface $request)\n    {\n        $method = strtolower($request->getMethod());\n        if (!method_exists($this, $method)) {\n            http_response_code(405); // method not exists\n            return;\n        }\n        $this->$method($request);\n    }\n\n    public function get(ServerRequestInterface $request)\n    {\n        $id = $request->getAttribute('id');\n        try {\n            $result = empty($id)\n                ? $this->userModel->getAllUsers()\n                : $this->userModel->getUser($id);\n        } catch (UserNotFoundException $e) {\n            http_response_code(404); // user not found\n            $result = ['error' => $e->getMessage()];\n        }\n        echo json_encode($result);\n    }\n\n    public function post(ServerRequestInterface $request)\n    {\n        $data = json_decode($request->getBody()->getContents(), true);\n        try {\n            $result = $this->userModel->addUser($data);\n        } catch (InvalidAttributeException $e) {\n            http_response_code(400); // bad request\n            $result = ['error' => $e->getMessage()];\n        } catch (UserAlreadyExistsException $e) {\n            http_response_code(409); // conflict, the user is not present\n            $result = ['error' => $e->getMessage()];\n        }\n        echo json_encode($result);\n    }\n\n    public function patch(ServerRequestInterface $request)\n    {\n        $id = $request->getAttribute('id');\n        $data = json_decode($request->getBody()->getContents(), true);\n        try {\n            $result = $this->userModel->updateUser($data, $id);\n        } catch (InvalidAttributeException $e) {\n            http_response_code(400); // bad request\n            $result = ['error' => $e->getMessage()];\n        } catch (UserNotFoundException $e) {\n            http_response_code(404); // user not found\n            $result = ['error' => $e->getMessage()];\n        }\n        echo json_encode($result);\n    }\n\n    public function delete(ServerRequestInterface $request)\n    {\n        $id = $request->getAttribute('id');\n        try {\n            $this->userModel->deleteUser($id);\n            $result = ['result' => 'success'];\n        } catch (UserNotFoundException $e) {\n            http_response_code(404); // user not found\n            $result = ['error' => $e->getMessage()];\n        }\n        echo json_encode($result);\n    }\n}\n
"},{"location":"languages/php/simple-mvc/simple-mvc.html","title":"SimpleMVC Mini-Framework","text":"

SimpleMVC is a micro MVC framework for PHP using FastRoute, PHP-DI, Plates and PHP-DI standard for HTTP messages.

This framework is mainly used as tutorial for introducing the Model-View-Controller architecture in modern PHP applications.

"},{"location":"languages/php/simple-mvc/simple-mvc.html#installation","title":"Installation","text":"PowerShell
composer create-project ezimuel/simple-mvc\n
"},{"location":"languages/php/simple-mvc/simple-mvc.html#structure","title":"Structure","text":"Text Only
|- config\n|  |- container.php --> DI Container Config (PHP-DI)\n|  |- route.php --> routing\n|- public\n|  |- img\n|  |- index.php  --> app entry-point\n|- src\n|  |- Model\n|  |- View  --> Plates views\n|  |- Controller  --> ControllerInterface.php\n|- test\n|  |- Model\n|  |- Controller\n
"},{"location":"languages/php/simple-mvc/simple-mvc.html#indexphp","title":"index.php","text":"PHP
<?php\ndeclare(strict_types=1);\n\nchdir(dirname(__DIR__));\nrequire 'vendor/autoload.php';\n\nuse DI\\ContainerBuilder;\nuse FastRoute\\Dispatcher;\nuse FastRoute\\RouteCollector;\nuse Nyholm\\Psr7\\Factory\\Psr17Factory;\nuse Nyholm\\Psr7Server\\ServerRequestCreator;\nuse SimpleMVC\\Controller\\Error404;\nuse SimpleMVC\\Controller\\Error405;\n\n$builder = new ContainerBuilder();\n$builder->addDefinitions('config/container.php');\n$container = $builder->build();\n\n// Routing\n$dispatcher = FastRoute\\simpleDispatcher(function(RouteCollector $r) {\n    $routes = require 'config/route.php';\n    foreach ($routes as $route) {\n        $r->addRoute($route[0], $route[1], $route[2]);\n    }\n});\n\n// Build the PSR-7 server request\n$psr17Factory = new Psr17Factory();\n$creator = new ServerRequestCreator(\n    $psr17Factory, // ServerRequestFactory\n    $psr17Factory, // UriFactory\n    $psr17Factory, // UploadedFileFactory\n    $psr17Factory  // StreamFactory\n);\n$request = $creator->fromGlobals();\n\n// Dispatch \n$routeInfo = $dispatcher->dispatch(\n    $request->getMethod(), \n    $request->getUri()->getPath()\n);\nswitch ($routeInfo[0]) {\n    case Dispatcher::NOT_FOUND:\n        $controllerName = Error404::class;\n        break;\n    case Dispatcher::METHOD_NOT_ALLOWED:\n        $controllerName = Error405::class;\n        break;\n    case Dispatcher::FOUND:\n        $controllerName = $routeInfo[1];\n        if (isset($routeInfo[2])) {\n            foreach ($routeInfo[2] as $name => $value) {\n                $request = $request->withAttribute($name, $value);\n            }\n        }\n        break;\n}\n$controller = $container->get($controllerName);\n$controller->execute($request);\n
"},{"location":"languages/php/simple-mvc/simple-mvc.html#routephp","title":"route.php","text":"PHP
<?php\nuse SimpleMVC\\Controller;\n\nreturn [\n    [ 'GET', '/', Controller\\Home::class ],\n    [ 'GET', '/hello[/{name}]', Controller\\Hello::class ],\n    [ \"HTTP Verb\", \"/route[/optional]\", Controller\\EndpointController::class ]\n];\n
"},{"location":"languages/php/simple-mvc/simple-mvc.html#containerphp","title":"container.php","text":"PHP
<?php\nuse League\\Plates\\Engine;\nuse Psr\\Container\\ContainerInterface;\n\nreturn [\n    'view_path' => 'src/View',\n    Engine::class => function(ContainerInterface $c) {\n        return new Engine($c->get('view_path'));\n    }\n\n    // PHP-DI configs\n];\n
"},{"location":"languages/php/simple-mvc/simple-mvc.html#controllerinterfacephp","title":"ControllerInterface.php","text":"

Each controller must implement this interface.

PHP
<?php\ndeclare(strict_types=1);\n\nnamespace SimpleMVC\\Controller;\n\nuse Psr\\Http\\Message\\ServerRequestInterface;\n\ninterface ControllerInterface\n{\n    public function execute(ServerRequestInterface $request);\n}\n
"},{"location":"languages/powershell/commands.html","title":"Powershell Commands","text":"PowerShell
Get-Location  # Gets information about the current working location or a location stack\nSet-Location -Path <path>  # change current working directory to specified path (DEFAULTs to ~)\nGet-ChildItem  -Path <path>  # Gets the items and child items in one or more specified locations.\nGet-Content -Path <file>  # Gets the content of the item at the specified location\n\nWrite-Output # Send specified objects to the next command in the pipeline. If the command is the last in the pipeline, the objects are displayed in the console\nWrite-Host  # Writes customized output to a host.\nClear-Host  # clear shell output\n\nNew-Item -ItemType File -Path filename.ext  # create empty file\nNew-Item -Path folder_name -Type Folder  # create a folder\nNew-Item -ItemType SymbolicLink -Path .\\link -Target .\\Notice.txt  # create a symlink\n\nMove-Item -Path <source> -Destination <target>  # move and/or rename files and folders\nCopy-Item -Path <source> -Destination <target>  # copy (and rename) files and folders\n\nTest-Path \"path\" -PathType Container  # check if the existing path exists and is a folder\nTest-Path \"path\" -PathType Leaf  # check if the existing path exists and is a file\n\n# start, list , kill processes\nStart-Process -FilePath <file>  # open a file with the default process/program\nGet-Process  # Gets the processes that are running on the local computer\nStop-Process [-Id] <System.Int32[]> [-Force] [-Confirm]  # Stops one or more running processes\n\n# network\nGet-NetIPConfiguration  # Gets IP network configuration\nTest-NetConnection <ip> # Sends ICMP echo request packets, or pings, to one or more computers\n\n# compressing into archive\nCompress-Archive -LiteralPath <PathToFiles> -DestinationPath <PathToDestination>  # destination can be a folder or a .zip file\nCompress-Archive -Path <PathToFiles> -Update -DestinationPath <PathToDestination>  # update existing archive\n\n# extraction from archive\nExpand-Archive -LiteralPath <PathToZipFile> -DestinationPath <PathToDestination>\nExpand-Archive -LiteralPath <PathToZipFile>  # extract archive in folder named after the archive in the root location\n\n# filtering stdout/stder\nSelect-String -Path <source> -Pattern <pattern>  # Finds text in strings and files\n
"},{"location":"languages/powershell/scripting.html","title":"PowerShell Scripting","text":"

Cmdlets are formed by a verb-noun pair. Cmdlets are case-insensitive.

It's all .NET A PS string is in fact a .NET System.String All .NET methods and properties are thus available

Note that .NET functions MUST be called with parentheses while PS functions CANNOT be called with parentheses. If you do call a cmdlet/PS function with parentheses, it is the same as passing a single parameter list.

"},{"location":"languages/powershell/scripting.html#screen-output","title":"Screen Output","text":"PowerShell
Write-Host \"message\"\n
"},{"location":"languages/powershell/scripting.html#user-input","title":"User Input","text":"PowerShell
# Reading a value from input:\n$variable = Read-Host \"prompt\"\n
"},{"location":"languages/powershell/scripting.html#variables","title":"Variables","text":"PowerShell
# Declaration\n[type]$var = value\n$var = value -as [type]\n\n[int]$a = 5\n$b = 6 -as [double]  # ?\n\n# Here-string (multiline string)\n@\"\nHere-string\n$a + $b = ($a + $b)\n\"@\n\n@'\nLiteral Here-string\n'@\n\n# Swapping\n$a, $b = $b, $a\n\n# Interpolation\nWrite-Host \"text $variable\"  # single quotes will not interpolate\nWrite-Host (<expression>)\n
"},{"location":"languages/powershell/scripting.html#built-in-variables","title":"Built-in Variables","text":"PowerShell
$True, $False  # boolean\n$null  # empty value\n$?  # last program return value\n$LastExitCode  # Exit code of last run Windows-based program\n$$  # The last token in the last line received by the session\n$^  # The first token\n$PID  # Script's PID\n$PSScriptRoot  # Full path of current script directory\n$MyInvocation.MyCommand.Path  # Full path of current script\n$Pwd  # Full path of current directory\n$PSBoundParameters  # Bound arguments in a function, script or code block\n$Args # Unbound arguments\n\n. .\\otherScriptName.ps1  # Inline another file (dot operator)\n
"},{"location":"languages/powershell/scripting.html#lists-dictionaries","title":"Lists & Dictionaries","text":"PowerShell
$List = @(5, \"ice\", 3.14, $True)  # Explicit syntax\n$List = 2, \"ice\", 3.14, $True  # Implicit syntax\n$List = (1..10)  # Inclusive range\n$List = @()  # Empty List\n\n$String = $List -join 'separator'\n$List = $String -split 'separator'\n\n# List comprehensions\n$List = sequence | Where-Object {$_ command}  # $_ is current object\n$Dict = @{\"a\" = \"apple\"; \"b\" = \"ball\"}  # Dict definition\n$Dict[\"a\"] = \"acorn\"  # Item update\n\n# Loop through keys\nforeach ($k in $Dict.keys) {\n    # Code here\n}\n
"},{"location":"languages/powershell/scripting.html#flow-control","title":"Flow Control","text":"PowerShell
if (condition) {\n    # Code here\n} elseif (condition) {\n    # Code here\n} else {\n    # Code here\n}\n
"},{"location":"languages/powershell/scripting.html#switch","title":"Switch","text":"

Switch has the following parameters:

PowerShell
switch(variable) {\n    20                      { \"Exactly 20\"; break }\n    { $_ -eq 42 }           { \"The answer equals 42\"; break }\n    { $_ -like 's*' }       { \"Case insensitive\"; break }\n    { $_ -clike 's*'}       { \"clike, ceq, cne for case sensitive\"; break }\n    { $_ -notmatch '^.*$'}  { \"Regex matching. cnotmatch, cnotlike, ...\"; break }\n    { $list -contains 'x'}  { \"if a list contains an item\"; break }\n    default                 { \"Others\" }\n}\n\n# syntax\nswitch [-regex|-wildcard|-exact][-casesensitive] (<value>)\n{\n    \"string\"|number|variable|{ expression } { statement_list }\n    default { statement_list }\n}\n\n# or\n\nswitch [-regex|-wildcard|-exact][-casesensitive] -file filename\n{\n    \"string\"|number|variable|{ expression } { statement_list }\n    default { statement_list }\n}\n
"},{"location":"languages/powershell/scripting.html#loops","title":"Loops","text":"PowerShell
# The classic for\nfor(setup; condition; iterator) {\n    # Code here\n}\n\nrange | % { command }\n\nforeach (item in iterable) {\n    # Code Here\n}\n\nwhile (condition) {\n    # Code here\n}\n\ndo {\n    # Code here\n} until (condition)\n\ndo {\n    # Code here\n} while (condition)\n
"},{"location":"languages/powershell/scripting.html#operators","title":"Operators","text":"PowerShell
# Conditionals\n$a -eq $b  # is equal to\n$a -ne $b  # in not equal to\n$a -gt $b  # greater than\n$a -ge $b  # greater than or equal to\n$a -lt $b  # less than\n$a -le $b  # less than or equal to\n\n# Logical\n$true -And $False\n$True -Or $False\n-Not $True\n
"},{"location":"languages/powershell/scripting.html#exception-handling","title":"Exception Handling","text":"PowerShell
try {} catch {} finally {}\ntry {} catch [System.NullReferenceException] {\n    echo $_.Exception | Format-List -Force\n}\n
"},{"location":"languages/powershell/scripting.html#functions","title":"Functions","text":"PowerShell
function func() {}\n\n# function with named parameters\nfunction func ([type]$param=default_value, ...) { }\nfunction func {\n    param([type]$param=default_value, ...)\n\n    # statements\n}\n\n# function call\nfunc argument  \nfunc -param value\n\n# switch parameters\nfunction func ([switch]$param, ...) { }\n\nfunc  # param is $false\nfunc -param  # param is $true\n

If the function defines a Begin, Process or End block, all the code must reside inside those blocks. No code will be recognized outside the blocks if any of the blocks are defined.

If the function has a Process keyword, each object in $input is removed from $input and assigned to $_.

PowerShell
function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]\n{\n  param([type]$parameter1 [,[type]$parameter2])  # other way to specify named parameters\n  dynamicparam {<statement list>}\n\n  # processing pipelines\n  begin {<statement list>}  # runned once, at start of pipeline\n  process {<statement list>}  # runned for each item in the pipeline\n  end {<statement list>}  # runned once, at end of pipeline\n}\n

Optionally, it's possible to provide a brief help string that describes the default value of the parameter, by adding the PSDefaultValue attribute to the description of the parameter, and specifying the Help property of PSDefaultValue.

PowerShell
function Func {\n  param (\n      [PSDefaultValue(Help = defValue)]\n      $Arg = 100\n  )\n}\n
"},{"location":"languages/powershell/scripting.html#script-arguments","title":"Script Arguments","text":""},{"location":"languages/powershell/scripting.html#parsing-script-arguments","title":"Parsing Script Arguments","text":"PowerShell
$args  # array of passed arguments\n$args[$index]  # access to the arguments\n$args.count  # number of arguments\n
"},{"location":"languages/powershell/scripting.html#script-named-arguments","title":"Script Named Arguments","text":"

In scripts.ps1:

PowerShell
param($param1, $param2, ...)  # basic usage\nparam($param1, $param2=defvalue, ...)  # with default values\nparam([Type] $param1, $param2, ...)  # specify a type\nparam([Parameter(Mandatory)]$param1, $param2, ...)  # setting a parameter as necessary\n\nparam([switch]$flag=$false, ...)  # custom flags\n

In PowerShell:

PowerShell
.\\script.ps1 arg1 arg2  # order of arguments will determine which data goes in which parameter\n\n.\\script.ps1 -param2 arg2 -param1 arg1  # custom order\n
"},{"location":"languages/powershell/scripting.html#filters","title":"Filters","text":"

A filter is a type of function that runs on each object in the pipeline. A filter resembles a function with all its statements in a Process block.

PowerShell
filter [<scope:>]<name> {<statement list>}\n
"},{"location":"languages/powershell/scripting.html#powershell-comment-based-help","title":"PowerShell Comment-based Help","text":"

The syntax for comment-based help is as follows:

PowerShell
# .<help keyword>\n# <help content>\n

or

PowerShell
<#\n.<help keyword>\n<help content>\n#>\n

Comment-based help is written as a series of comments. You can type a comment symbol # before each line of comments, or you can use the <# and #> symbols to create a comment block. All the lines within the comment block are interpreted as comments.

All of the lines in a comment-based help topic must be contiguous. If a comment-based help topic follows a comment that is not part of the help topic, there must be at least one blank line between the last non-help comment line and the beginning of the comment-based help.

Keywords define each section of comment-based help. Each comment-based help keyword is preceded by a dot .. The keywords can appear in any order. The keyword names are not case-sensitive.

"},{"location":"languages/powershell/scripting.html#synopsis","title":".SYNOPSIS","text":"

A brief description of the function or script. This keyword can be used only once in each topic.

"},{"location":"languages/powershell/scripting.html#description","title":".DESCRIPTION","text":"

A detailed description of the function or script. This keyword can be used only once in each topic.

"},{"location":"languages/powershell/scripting.html#parameter","title":".PARAMETER","text":"

The description of a parameter. Add a .PARAMETER keyword for each parameter in the function or script syntax.

Type the parameter name on the same line as the .PARAMETER keyword. Type the parameter description on the lines following the .PARAMETER keyword. Windows PowerShell interprets all text between the .PARAMETER line and the next keyword or the end of the comment block as part of the parameter description. The description can include paragraph breaks.

PowerShell
.PARAMETER  <Parameter-Name>\n

The Parameter keywords can appear in any order in the comment block, but the function or script syntax determines the order in which the parameters (and their descriptions) appear in help topic. To change the order, change the syntax.

You can also specify a parameter description by placing a comment in the function or script syntax immediately before the parameter variable name. For this to work, you must also have a comment block with at least one keyword.

If you use both a syntax comment and a .PARAMETER keyword, the description associated with the .PARAMETER keyword is used, and the syntax comment is ignored.

PowerShell
<#\n.SYNOPSIS\n    Short description here\n#>\nfunction Verb-Noun {\n    [CmdletBinding()]\n    param (\n        # This is the same as .Parameter\n        [string]$Computername\n    )\n    # Verb the Noun on the computer\n}\n
"},{"location":"languages/powershell/scripting.html#example","title":".EXAMPLE","text":"

A sample command that uses the function or script, optionally followed by sample output and a description. Repeat this keyword for each example.

"},{"location":"languages/powershell/scripting.html#inputs","title":".INPUTS","text":"

The .NET types of objects that can be piped to the function or script. You can also include a description of the input objects.

"},{"location":"languages/powershell/scripting.html#outputs","title":".OUTPUTS","text":"

The .NET type of the objects that the cmdlet returns. You can also include a description of the returned objects.

"},{"location":"languages/powershell/scripting.html#notes","title":".NOTES","text":"

Additional information about the function or script.

"},{"location":"languages/powershell/scripting.html#link","title":".LINK","text":"

The name of a related topic. The value appears on the line below the .LINK keyword and must be preceded by a comment symbol # or included in the comment block.

Repeat the .LINK keyword for each related topic.

This content appears in the Related Links section of the help topic.

The .Link keyword content can also include a Uniform Resource Identifier (URI) to an online version of the same help topic. The online version opens when you use the Online parameter of Get-Help. The URI must begin with \"http\" or \"https\".

"},{"location":"languages/powershell/scripting.html#component","title":".COMPONENT","text":"

The name of the technology or feature that the function or script uses, or to which it is related. The Component parameter of Get-Help uses this value to filter the search results returned by Get-Help.

"},{"location":"languages/powershell/scripting.html#role","title":".ROLE","text":"

The name of the user role for the help topic. The Role parameter of Get-Help uses this value to filter the search results returned by Get-Help.

"},{"location":"languages/powershell/scripting.html#functionality","title":".FUNCTIONALITY","text":"

The keywords that describe the intended use of the function. The Functionality parameter of Get-Help uses this value to filter the search results returned by Get-Help.

"},{"location":"languages/powershell/scripting.html#forwardhelptargetname","title":".FORWARDHELPTARGETNAME","text":"

Redirects to the help topic for the specified command. You can redirect users to any help topic, including help topics for a function, script, cmdlet, or provider.

PowerShell
# .FORWARDHELPTARGETNAME <Command-Name>\n
"},{"location":"languages/powershell/scripting.html#forwardhelpcategory","title":".FORWARDHELPCATEGORY","text":"

Specifies the help category of the item in .ForwardHelpTargetName. Valid values are Alias, Cmdlet, HelpFile, Function, Provider, General, FAQ, Glossary, ScriptCommand, ExternalScript, Filter, or All. Use this keyword to avoid conflicts when there are commands with the same name.

PowerShell
# .FORWARDHELPCATEGORY <Category>\n
"},{"location":"languages/powershell/scripting.html#remotehelprunspace","title":".REMOTEHELPRUNSPACE","text":"

Specifies a session that contains the help topic. Enter a variable that contains a PSSession object. This keyword is used by the Export-PSSession cmdlet to find the help topics for the exported commands.

PowerShell
# .REMOTEHELPRUNSPACE <PSSession-variable>\n
"},{"location":"languages/powershell/scripting.html#externalhelp","title":".EXTERNALHELP","text":"

Specifies an XML-based help file for the script or function.

PowerShell
# .EXTERNALHELP <XML Help File>\n

The .ExternalHelp keyword is required when a function or script is documented in XML files. Without this keyword, Get-Help cannot find the XML-based help file for the function or script.

The .ExternalHelp keyword takes precedence over other comment-based help keywords. If .ExternalHelp is present, Get-Help does not display comment-based help, even if it cannot find a help topic that matches the value of the .ExternalHelp keyword.

If the function is exported by a module, set the value of the .ExternalHelp keyword to a filename without a path. Get-Help looks for the specified file name in a language-specific subdirectory of the module directory. There are no requirements for the name of the XML-based help file for a function, but a best practice is to use the following format:

PowerShell
<ScriptModule.psm1>-help.xml\n

If the function is not included in a module, include a path to the XML-based help file. If the value includes a path and the path contains UI-culture-specific subdirectories, Get-Help searches the subdirectories recursively for an XML file with the name of the script or function in accordance with the language fallback standards established for Windows, just as it does in a module directory.

For more information about the cmdlet help XML-based help file format, see How to Write Cmdlet Help in the MSDN library.

"},{"location":"languages/powershell/scripting.html#project-oriented-programming","title":"Project Oriented Programming","text":""},{"location":"languages/powershell/scripting.html#classes","title":"Classes","text":"PowerShell
[class]::func()  # use function from a static class\n[class]::attribute  # access to static class attribute\n
"},{"location":"languages/python/python.html","title":"Python Notes","text":""},{"location":"languages/python/python.html#basics","title":"Basics","text":""},{"location":"languages/python/python.html#naming-convention","title":"Naming Convention","text":"

Class -> PascalCase Method, Function -> snake_case Variable -> snake_case

Python
# standard comment\n'''multiline comment'''\n\"\"\"DOCSTRING\"\"\"\n\nhelp(object.method) # return method explanation\ndir(object) # return an alphabetized list of names comprising (some of) the attributes of the given object\n\nimport sys # import module\nfrom sys import argv # import single item from a module\nfrom sys import * # import all elements of a module (no module syntax.method needed)\nimport sys as alias # import the module with an alias, I use alias.method\n\n# CHARACTER SET\nimport string\nstring.ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'\nstring.asci_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nstring.asci_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\nstring.digits = '0123456789'\nstring.hexdigits = '0123456789abcdefABCDEF'\nstring.octdigits = '01234567'\nstring.punctuation\nstring.whitespace\n\n# SPECIAL CHARACTERS\n# (\\a, \\b, \\f, \\n, \\r, \\t, \\u, \\U, \\v, \\x, \\\\)\n
"},{"location":"languages/python/python.html#assignment-operation","title":"Assignment Operation","text":"Python
\"\"\"instructions to the right of = executed before instructions to the left of =\"\"\"\nvariable = expression # the type of the variable is dynamically decided by python based on the content\nvar_1, var_2 = value1, value2 # parallel assignment\nvar_1, var_2 = var_2, var_1 # swap values\n\n# conditional assignment\nx = a if condition else b\nx = a or b # If bool (a) returns False, then x is assigned the value of b\n# a series of OR expressions has the effect of returning the first item that evaluates True, or the last item (last item should be a literal).\n
"},{"location":"languages/python/python.html#variable-type-conversion","title":"Variable Type Conversion","text":"

type(expression)

"},{"location":"languages/python/python.html#expression-assignment","title":"Expression Assignment","text":"Python
(var: = expression) # assign an expression to a variable to avoid repeating the expression\n
"},{"location":"languages/python/python.html#variable-comparison-vs-is","title":"Variable Comparison (== vs is)","text":"

== compares the values \u200b\u200bof objects is compares the identities of objects

"},{"location":"languages/python/python.html#on-screen-output","title":"On Screen Output","text":"Python
print() # print blank line and wrap\nprint('string' * n) # print string n times\nprint('string1 \\ n string2') # wrap with \\ n\nprint(variable) # print variable content\nprint('string', end = '') # print without wrapping\n\n# FORMATTING\nname = 'Alex'\nmarks = 94.5\nprint(name, marks)\nprint('Name is', name, '\\ nMarks are', marks)\n# expand the rest of the expression and write tense before = in output\nprint(f '{name =}, {marks =}') # OUTPUT: name = Alex, marks = 94.5\n\n# USE OF PLACEHOLDERS\nprint('Name is% s, Marks are% 3.2f'%(name, marks)) # method inherited from C. Variable is substituted for% ..\nprint(\"Name is {}, Marks are {}\". format(name, marks))\nprint(\"Name is {1}, Marks are {2}\". format(marks, name)) # indices in brackets sort elements in .format\nprint(\"Name is {n}, Marks are {m}\". format(m = '94 .5 ', n =' Alex ')) # indices in brackets sort elements in .format\nprint(f'Name is {name}, Marks are {marks} ') # formatting with f-strings\n
"},{"location":"languages/python/python.html#format-specification-mini-language","title":"Format Specification Mini-Language","text":"

{value:width.precision symbol}

Format: [[fill]align] [sign] [#] [width] [grouping] [.precision] [type]

[align] Alignment :< left alignment :> right alignment := padding after the mark :^ centered [sign] NUMBER SIGNS :+ sign for both positive and negative numbers :- sign only for negative numbers : space for num > 0, '-' for num < 0 :# alternative form:prefix integers type (0x, 0b, 0o), floats and complexes always have at least one decimal place [grouping] GROUPING :, use comma to separate thousands :_ use underscore to separate thousands [type] OUTPUT TYPE :s output is string :b output is binary :c output is character :d output is a decimal integer (base 10) :or output is octal integer (base 8) :x output is hexadecimal integer (base 16) :X output is hexadecimal integer (base 16) with uppercase :e output is exponential notation (6-digit base precision) :E output is exponential notation (6-digit base precision) uppercase separator :f output is float (6-digit base precision) :% output is percentage (multiplies * 100, displays as:f)"},{"location":"languages/python/python.html#keyboard-input","title":"Keyboard Input","text":"Python
# input always returns a STRING\ns = input() # input request without message\ns = input('Prompt') # request input\ni = int(input('prompt')) # request input with type conversion\n\n# MULTIPLE INPUTS\nlist = [int(x) for x in input('prompt'). split('separator')]\n# save multiple inputs in a list(.split separates values \u200b\u200band defines separator\n
"},{"location":"languages/python/python.html#numeric-types","title":"Numeric Types","text":"Python
a = 77\nb = 1_000_000 # underscore can be used to separate groups of digits\nc = -69\n\n# float numbers\nx = 3.15\ny = 2.71\nz = 25.0\n\nd = 6 + 9j # complex number\n# returns a complex number starting with two reals\ncomplex(real, imag) # -> complex #(real + imag * 1j)\n\ne = 0B1101 # BINARY TYPE(0B ...)\nf = 0xFF # EXADECIMAL TYPE(0X ...)\no = 0o77 # OCTAL TYPE\ng = True # BOOLEAN TYPE\n\n# VARIABLE TYPE CONVERSION\nh = int(y)\ni = float('22 .5 ')\n\n# NUMERIC BASIC CONVERSION\nbin(3616544)\nhex(589)\noct(265846)\n\n# UNICODE CONVERSION\nord(c) # Given a string representing one Unicode character, return an integer representing the Unicode code point of that character\nchr(i) # Return the string representing a character whose Unicode code point is the integer i\n\n\npow(x, y) # x ^ y\nabs(num) # returns absolute value of num(| num |)\nround(num, precision) # rounds number to given precision, does not convert float to int\n
"},{"location":"languages/python/python.html#comparison-of-decimal-numbers","title":"Comparison of Decimal Numbers","text":"

Do not use == or ! = To compare floating point numbers. They are approximations or have several digits. It is worth checking if the difference between the numbers is small enough.

"},{"location":"languages/python/python.html#strings","title":"Strings","text":"Python
string = 'string content' # assignment and creation of string variable\nstring = '''multi\nline\nstring'''\n\nstring3 = string1 + string2 # string concatenation(operator polymorphism +)\n\n# INDEXING(selection of a character in the string)\nstring[0]\nstring[2]\nstring[-3] # selection starting from the bottom(negative index)\n\n# REPETITION (repeat string output)\nprint(string * n)\n\nlen(string) # show the length of a string\n\n# SLICING (extraction of sub-strings, does not include the position of the last index)\nstring[0: 5]\nstring[: 6]\nstring[-3: -1]\n\n# SLICING WITH STEP\nstring[0: 12: 3]\nstring[15 :: - 1]\nstring[:: - 1] # selection in reverse order (negative step)\n\n# STRIPPING (elimination of spaces before and after string)\nstring = 'stripping test'\nstring.strip()\nstring.lstrip() # only left spaces removed\nstring.rstrip() # only right spaces removed\nstring.removeprefix(prefix) # If the string starts with the prefix string, return string [len (prefix):]\nstring.removesuffix(suffix) # If the string ends with the suffix string and that suffix is \u200b\u200bnot empty, return string [: - len (suffix)]\n\n# SUBSTRING IDENTIFICATION\n#returns starting index of the substring or -1 if it is not present\nstring.find('substring', 0, len (string)) # you can specify the start and end index of the search\n\n# COUNT OF APPARITIONS\nstring.count('t')\n\n# REPLACEMENT\nstring.replace('multi', 'multiple')\n\n# UPPER CASE CONVERSION\nstring.upper()\nstring.lower()\nstring.title()\nstring.capitalize()\n\n# SEPARATION IN LIST ELEMENTS\nstring.split()\nstring.split('separator') # separate using separator (separator omitted in list)\nstring.partition('char') # -> tuple # separates the string from the 3 parts at the first occurrence of separator\n\n# IS_CHECK METHODS -> bool\nstring.isalnum()\nstring.isalpha()\nstring.islower()\nstring.isspace()\nstring.istitle()\nstring.isupper()\nstring.endswith('char')\n\n# JOIN INSTRUCTION()\n''.join(iterable) # merges all elements of the iterable into the new string\n\n# FORMATTING\nstring.center(width, 'char') # stretch the string with char to width\n'...\\t...'.expandtabs() # transform tabs into spaces\n
"},{"location":"languages/python/python.html#lists","title":"Lists","text":"Python
list = [9, 11, 'WTC', -5.6, True] # lists can contain data of different types\n\nlist[3] # indexing\nlist[3: 5] # slicing\nlist * 3 # repetition\nlen(list) # length\nlist3 = list1 + list2 # list concatenation (operator + polymorphism)\nlist[index] = value # modify list element\ndel (list [1]) # remove by index (INBUILT IN PYTHON)\n# modify the list between the start and stop indices by reassigning the elements of the iterable\nlist[start: stop] = iterable\n\n# LIST METHODS\nlist.append(object) # add object to background\nlist.count(item) # counts the number of occurrences of item\nlist.extend(sequence) # add sequence elements to the list\nlist.insert(position, object) # insert object in list [position]\nlist.index(item) # returns the index of item\nlist.remove(item) # remove item\npoplist(item) # delete item and return it\nlist.clear() # remove all elements\n\nlist.sort() # sorts in ascending order (in place)\nlist.sort(reverse = True) # sorts in descending order (in place)\nlist.reverse() # invert the string (in place)\n\n# CLONING\nlist1 = [...]\nlist2 = list1 # list2 points to the same object of list 1 (changes are shared)\nlist3 = list1 [:] # list3 is a clone of list1 (no shared changes)\n\n# NESTED LISTS (MATRICES)\nlist_1 = [1, 2, 3]\nlist_2 = [4, 5, 6]\nlist_3 = [7, 8, 9]\n\nmatrix = [list_1, list_2, list_3]\nmatrix [i][j] # identify element of list_i index j\n\n# MAXIMUM AND MINIMUM\nmax(list)\nmin(list)\n\n# ALL () & ANY ()\nall(sequence) # returns TRUE if all elements of the sequence are true\nany(sequence) # returns TRUE if at least one element of the sequence has the value True\n\n# MAP INSTRUCTION\n# apply function to iterable and create new list (map object)\n# function can be lambda\nmap(function, iterable) # -> map object\n\n# FILTER INSTRUCTION ()\n# create a new list composed of the iterable elements for which the function returns TRUE\nfilter(function, iterable) # -> filter object\n\n# ZIP INSTRUCTION ()\n# create a tuple generator by joining two or more iterables\n# [(seq_1 [0], seq_2 [0], ...), (seq_1 [1], seq_2 [1], ...), ...]\n# truncate the sequence to the length of the shortest input sequence\nzip(seq_1, seq_2, ...) # -> zip object (tuple generator)\n\n# LIST COMPREHENSIONS\nvar = [expression for element in sequence if condition] # create list from pre-existing list (instead of map, filter, reduce) applying any manipulations\n# expression can be lambda, if is optional\nvar = [expression if condition else statement for element in sequence] # list comprehension with IF-ELSE\nvar = [expression_1 for element in [expression_2 for element in sequence]] # nested list comprehension\nvar = [(exp_1, exp_2) for item_1 in seq_1 for item_2 in seq_2] # -> [(..., ...), (..., ...), ...]\n
"},{"location":"languages/python/python.html#tuple","title":"Tuple","text":"Python
# TUPLES CANNOT BE MODIFIED\ntuple = (69, 420, 69, 'abc') # tuple assignment\ntuple = (44,) # single element tuples need a comma\n\ntuple[3] # indexing\ntuple * 3 # repetition\ntuple.count(69) # counting\ntuple.index(420) # find index\nlen(tuple) # length tuple\n\n# CONVERSION FROM TUPLE TO LIST\ntuple = tuple(list)\n\n# TUPLE UNPACKING\ntup = (item_1, item_2, etc)\nvar_1, var_2, etc = tup\n# var_1 = item_1, var_2 = item_2, ...\n\ntup = (item_1, (item_2, item_3))\nvar_1, (var_2, var_3) = tup\n# var_1 = item_1, var_2 = item_2, var_3 = item_3\n\n#OPERATOR * VAR (tuple unpacking)\nvar_1, var_2, * rest = sequence # var_1 = seq [0], var_2 = seq [1], rest = seq [2:]\nvar_1, * body, var_2, var_3 = sequence # var_1 = seq [0], body = seq [1: -2], var_2 = sequence [-2], var_3 = seq [-1]\n# * var retrieves the excess items, if in parallel assignment usable max once but in any position\n
"},{"location":"languages/python/python.html#set","title":"Set","text":"Python
# SETS MAY NOT CONTAIN REPEATED ELEMENTS (THEY ARE OMITTED)\n# THE ORDER DOES NOT MATTER (NO SLICING, INDEXING, REPETITION, ...)\nset = {10, 20, 30, 'abc', 20}\nlen(set) # length set\nset() # create empty set ({} create empty dictionary)\n# FREEZING SETS (no longer editable)\nfset = frozenset(set)\n\n# OPERATORS\nset_1 - set_2 # elements in set_1 but not in set_2\nset_1 | set_2 # elements in set_1 or set_2\nset_1 & set_2 # elements in set_1 and set_2\nset_1 ^ set_1 # elements in either set_1 or set_2\nset_1 <= set_2 # elements set_1 also in set_2\nset_1 < set_2 # set_1 <= set_2 and set_1! = set_2\nset_1 >= set_2 # elements set_2 also in set_1\nset_1 > set_2 # set_1> = set_2 and set_1! = set_2\n\n# METHODS SET\nset.pop(item) # remove and return item\nset.add(item) # add item to set\n\nset.copy() # -> set # returns a copy of the set\nset.clear() # remove all elements from the set\nset.remove(item) # remove item from set if present, otherwise raise KeyError\nset.discard(item) # remove item from set if present, otherwise do nothing\nset.difference(* sets) # -> set # returns elements in set that are absent in * sets\nset.difference_update(* sets) # remove differences from set_2\nset.union(* sets) # -> set # returns all elements of sets\nset.update(* sets) # add * sets elements to set\nset.intersection(* sets) # -> set # returns the elements common to sets\nset.intersection_update(* sets) # remove all elements except those common to sets\nset.symmetric_difference(* sets) # -> set # returns elements not common to sets\nset.symmetric_difference_update(* sets) # remove all elements common to sets (leave only uncommon elements)\n\nset_1.isdisjoint(set_2) # -> bool # True if there are no common elements (intersection is empty)\nset_1.issubset(set_2) # -> bool # True if every element of set_1 is also in set_2\nset_1.issuperset(set_2) # -> bool # True if every element of set_2 is also in set_1\n\n# SET COMPREHENSIONS\nvar = {expression for element in sequence if condition}\n\n# SLICE OBJECT\n# [start: stop: step] -> slice object (start, stop, step)\nvar_1 = slice(start, stop, step) # assignment to variable\nvar_2[var_1] # same as var_2 [start: stop: step]\n\n# ELLIPSIS OBJECT\nvar[i, ...] # -> shortcut for var [i,:,:,:,]\n# used for multidimensional slices (NumPy, ...)\n
"},{"location":"languages/python/python.html#bytes-e-bytearray","title":"Bytes e Bytearray","text":"Python
# THE BYTES CANNOT BE MODIFIED OR INDEXED\n# THE BYTEARRAYS CAN BE MODIFIED AND INDEXED\n# YOU CANNOT DO REPETITION AND SLICING ON BYTE OR BYTEARRAY\n\nb = bytes(list)\nba = bytearray(list)\n\n# item of bytes and bytearray is always integer between 0 and 255\n# slice of bytes and bytearray is binary sequence (even if len = 1)\n\n# BYTES AND BYTEARRAY METHODS\nbytes.fromhex(pair_hex_digits) # -> byte literal\nb'bite_literal'.hex() # -> str # returns a string containing hex digit pairs\nbytearray.fromhex(pair_hex_digits) # -> byte literal\nbytes.count(subseq, start, end) # returns subseq appearance count between start and end positions\nbytearray.count(subseq, start, end) # returns subseq appearance count between start and end positions\n
"},{"location":"languages/python/python.html#encoding-decoding-unicode","title":"Encoding-Decoding & Unicode","text":"

Unicode Literals:

Python
# ENCODING\n# transform string into literal byte\n# UnicodeEncodeError on error\n# errors = ignore -> skip error-causing characters\n# errors = replace -> replace? to characters causing error\n# errors = xmlcharrefreplace -> substitutes XML entities for error-causing characters\nstring.encode('utf-8', errors = 'replace') # -> b'byte literals'\n\n# BOM (BYTE ORDER MARK)\n# byte literal given to indicate byte ordering (little-endian vs big-endian)\n# in little-endian the least significant bytes come first (e.g. U + 0045 -> DEC 069 -> encoded as 69 and 0)\n# U + FEFF (ZERO WIDTH NO-BREAK SPACE) -> b '\\ xff \\ xfe' indicates little-endian\n\n# DECODING\n# transform byte literal to string\n# error = 'replace' replaces errors (byte literals not belonging to decoding format) with U + FFFD \"REPLACEMENT CHARACTER\"\nbytes.decode ('utf-8', errors = 'replace') # -> str\n\n# UNICODE NORMALIZATION\n# handling canonical unicode equivalents (e.g. \u00e9, and \\ u0301 are equivalent for unicode)\nunicodedata.normalize(form, unicode_string) # FORM: NFC, NFD, NFCK, NFDK\n# NFC -> \"Normalization Form C\" -> produces the shortest equivalent string\n# NFD -> \"Normalization Form D\" -> produces the longest equivalent string\n\n# CASE FOLDING UNICODE\n# transform to lowercase with some differences (116 differences, 0.11% of Unicode 6.3)\nstring.casefold()\n\n# USEFUL FUNCTIONS FOR NORMALIZED EQUIVALENCE (Source: Fluent Python p. 121, Luciano Ramalho)\nfrom unicodedata import normalize\n\ndef nfc_eual(str_1, str_2):\n    return (normalize('NFC', str1) == normalize('NFC', str2))\ndef fold_equal (str_1, str_2):\n    return (normalize('NFC', str_1).casefold() ==\n            normalize('NFC', st_2).casefold())\n
"},{"location":"languages/python/python.html#memoryview","title":"Memoryview","text":"Python
# memoryview objects allow python to access the data inside the object\n# without copy if it supports the buffer protocol\nv = memoryview(object) # create a memoryview with reference to object\n# slice of memoryview produces new memoryview\n\n# MEMORYVIEW METHODS\nv.tobytes() # return data as bytestring, equivalent to bytes (v)\nv.hex() # returns string containing two hex digits for each byte in the buffer\nv.tolist() # returns the data in the buffer as a list of elements\nv.toreadonly()\nv.release() # release the buffer below\nv.cast(format, shape) # change the format or shape of the memoryview\nsee object # object of the memoryview\nv.format # format of the memoryview\nv.itemsize # size in bytes of each element of the memoryview\nv.ndim # integer indicating the size of the multidimensional array represented\nv.shape # tuple of integers indicating the shape of the memoryview\n
Format String C Type Python Type Standard Size x pad byte no value c char bytes 1 b signed char integer 1 B unsigned char integer 1 ? _Bool bool 1 h short integer 2 H unsigned short integer 2 i int integer 4 I unsigned int integer 4 l long integer 4 L unsigned long integer 4 q long long integer 8 Q unsigned long long integer 8 n ssize_t integer N size_t integer f float float 4 F double float 8 s char[] bytes P char[] bytes"},{"location":"languages/python/python.html#dictionaries","title":"Dictionaries","text":"Python
# SET OF KEY-VALUE PAIRS\nd = {1: 'Alex', 2: 'Bob', 3: 'Carl'}\nd = dict (one = 'Alex', two = 'Bob', three = 'Carl')\nd = dict (zip ([1,2,3], ['Alex', 'Bob', 'Carl']))\nd = dict ([(1, 'Alex'), (2, 'Bob'), (3, 'Carl')])\n\nd[key] # returns value associated with key\nd[4] = 'Dan' # add or change element\nlist(d) # returns a list of all elements\nlen(d) # returns the number of elements\ndel(d[2]) # delete element\n\n# DICTIONARY METHODS\nd.clear() # remove all elements\nd.copy() # shallow copy of the dictionary\nd.get(key) # returns the value associated with key\nd.items() # return key-value pairs (view object)\nd.keys() # return dictionary keys (view object)\nd.values\u200b\u200b() # returns dictionary values \u200b\u200b(view object)\nd.pop(key) # remove and return the value associated with key\nd.popitem() # remove and return the last key-value pair\nd.setdefault(key, default) # if the key is present in the dictionary it returns it, otherwise it inserts it with the default value and returns default\n\nd.update(iterable) # add or modify dictionary elements, argument must be key-value pair\n\n# DICT UNION\nd = {'spam': 1, 'eggs': 2, 'cheese': 3}\ne = {'cheese': 'cheddar', 'aardvark': 'Ethel'}\n\nd | e # {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}\ne | d # {'aardvark': 'Ethel', 'spam': 1, 'eggs': 2, 'cheese': 3}\nd |= e # {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}\n\n# NESTED DICTIONARIES (it is possible to nest dictionaries within dictionaries)\nmy_dict = {'key_1': 123, 'key_2': [12, 23, 33], 'key_3': ['item_0', 'item_1', 'item_2']}\nmy_dict ['key'][0] # returns nested element\n\n# DICT COMPREHENSIONS\nvar = {key: value for element in sequence}\n
"},{"location":"languages/python/python.html#operators","title":"Operators","text":""},{"location":"languages/python/python.html#mathematical-operators","title":"Mathematical Operators","text":"Operator Operation x + y addition, string concatenation x - y subtraction x * y multiplication x *+ y exponentiation x / y division (result always float) x // y integer division x % y modulo, remainder"},{"location":"languages/python/python.html#relational-operators","title":"Relational Operators","text":"Operator Operation x < y less than x <= y less or equal to x > y greater than x >= y greater or equal to x == y equality x != y inequality"},{"location":"languages/python/python.html#assignment","title":"Assignment","text":"Operator Operation x += y x = x + y x -= y x = x - y x *= y x = x * y x /= y x = x / y x //= y x = x // y x %= y x = x % y x <<= y x = x << y x >>= y x = x >> y x &= y x = x & y x | = y x = x x ^= y x = x ^ y"},{"location":"languages/python/python.html#bitwise-operators","title":"Bitwise Operators","text":"Operator Operation ~x bitwise NOT x & y bitwise AND x ^ y bitwise XOR x | y bitwise OR x << y left bit shift x >> y right bit shift"},{"location":"languages/python/python.html#logical-operators","title":"Logical Operators","text":"Operator Operation and logical AND or logical OR not logical NOT"},{"location":"languages/python/python.html#identity-operators","title":"Identity Operators","text":"Operator Operation is reference equality is not reference inequality"},{"location":"languages/python/python.html#membership-operators","title":"Membership Operators","text":"Operator Operation in item in collection not in item not in collection"},{"location":"languages/python/python.html#operator-precedence","title":"OPerator Precedence","text":"
  1. assignment operators +=, -=, *=, /=, %=, **=, //=
  2. binary arithmetic operators *, /, %, // (floor division)
  3. binary arithmetic operators +, -
  4. boolean operators <, >, <=, >=
  5. boolean operators ==, !=
  6. boolean operator and
  7. boolean operator or
  8. boolean operator not
"},{"location":"languages/python/python.html#conditional-statements","title":"Conditional Statements","text":"

Any object can be tested for truth value for use in an if or while condition or as operand of the Boolean operations.

built-in objects considered false:

"},{"location":"languages/python/python.html#if-else","title":"if-else","text":"Python
if (condition):\n    # code here\nelif (condition):\n    # code here\nelse:\n    # code here\n
"},{"location":"languages/python/python.html#context-manager","title":"Context Manager","text":"Python
with resource as target:\n     # code here\n\n# start context manager and bind resource returned by method to target using as operator\ncontextmanager.__enter__(self)\n\n# exit runtime context\n# returns exc_type, exc_value, traceback\ncontextmanager.__exit__(self, exc_type, exc_value, traceback)\n# exc_type: exception class\n# exc_value: exception instance\n# traceback: traceback object\n# NO EXCEPTION -> returns None, None, None\n# SUPPRESSION EXCEPTION: Must return True value\n
"},{"location":"languages/python/python.html#loops","title":"Loops","text":""},{"location":"languages/python/python.html#while","title":"while","text":"Python
while(condition):\n     # code here\nelse:\n     # executed only if condition becomes False\n     # break, continue, return in block while do not perform else block\n     # code here\n
"},{"location":"languages/python/python.html#for","title":"for","text":"Python
for index in sequence: # sequence can be a list, set, tuple, etc ..\n     # code here\nelse:\n     # executed only if for reaches the end of the loop\n     # break, continue, return in block for do not perform else block\n     # code here\n\nfor index in range (start, end, step):\n     # code here\n\nfor key, value in dict.items ():\n     # code here\n
"},{"location":"languages/python/python.html#break-continue","title":"break & continue","text":"

break: causes the loop to exit immediately without executing subsequent iterations continue: skip the remaining iteration statements and continue the loop

"},{"location":"languages/python/python.html#range","title":"range","text":"Python
range(start, end, step) # generate sequence num integers (does not include num stops) with possible step\nlist(range(start, end, step)) # return sequence of integers in a list\n
"},{"location":"languages/python/python.html#enumerate","title":"enumerate","text":"Python
enumerate(iterable) # iterable of item & index pairs\nlist(enumerate(iterable)) # returns list of tuples [(1, iterable [0]), (2, iterable [1]), (3, iterable [2])]\n
"},{"location":"languages/python/python.html#zip","title":"zip","text":"Python
list_1 = [1, 2, 3, 4, 5]\nlist_2 = ['a', 'b', 'c', 'd', 'e']\n\nzip(list_1, list_2) # return zip object\nlist(zip(list_1, list_2)) # returns list of tuples by merging list [(list_1 [0], list_2 [0]), (list_1 [1], list_2 [1]), ...]\n
"},{"location":"languages/python/python.html#shuffle-randint","title":"shuffle & randint","text":"Python
from random import shuffle, randint\nshuffle(iterable) # shuffle the list\nrandint(start, end) # returns a random integer between start and end\n
"},{"location":"languages/python/python.html#in","title":"in","text":"Python
item in iterable # check for the presence of item in iterable (returns True or False)\n
"},{"location":"languages/python/python.html#functions","title":"Functions","text":""},{"location":"languages/python/python.html#function-definition","title":"Function Definition","text":"Python
def function_name (parameters):\n     \"\" \"DOCSTRING\" \"\"\n     # code here\n     return expression # if return id missing the function returns None\n
"},{"location":"languages/python/python.html#specify-type-parameters-in-functions","title":"Specify Type Parameters In Functions","text":" Python
def func (a, b, /, c, d, *, e, f):\n     # code here\n
"},{"location":"languages/python/python.html#docstring-style","title":"Docstring Style","text":"Python
\"\"\"function description\n\nArgs:\n     argument: Type - description of the parameter\n\nReturns:\n     Type - description of <expr>\n\nRaises:\n     Exception: Cause of the exception\n\"\"\"\n
"},{"location":"languages/python/python.html#args-kwargs","title":"args *kwargs","text":"

*args allows the function to accept a variable number of parameters (parameters stored in a tuple) **kwargs allows the function to accept a variable number of key-value parameters (parameters stored in a dictionary)

When used in combination *args always goes before**kwargs (in def function and in function call)

Python
def func(*args, **kwargs):\n    # code here\n
"},{"location":"languages/python/python.html#function-with-default-parameters","title":"Function with default parameters","text":"Python
def function(parameter1 = value1, parameter2 = value3): # default values in case of omitted use of arguments in the call\n     # code here\n     return expression\n\nfunction(parameter2 = value2, parameter1 = value1) # arguments passed with keyword to enforce the order of reference\n
"},{"location":"languages/python/python.html#global-and-local-variables","title":"Global And Local Variables","text":"Python
# global scope\n\ndef external_func():\n     # enclosing local scope\n\n     def internal_func():\n         # local scope\n

LEGB Rule:

Note: variables declared inside a function are not usable outside

Python
def function():\n     # global statement makes a variable global\n     # actions on global variable within the function also have an effect outside\n\n     global variable\n
"},{"location":"languages/python/python.html#iterables-iterators-generators","title":"Iterables, Iterators & Generators","text":"

Iterable: object implementing __iter __(), sequences and objects supporting __getitem__ with index 0

Iterator: object implementing __next__ and __iter__ (iterator protocol), when entirely consumed by next() it becomes unusable. Returns StopIteration when next() has returned all elements.

Generator Function: function with keyword yield (if present also return causes StopIteration), returns a generator that produces the values \u200b\u200bone at a time.

Generator Factory: generator returning function (may not contain yield).

Operation iter():

Note: abc.Iterable does not check for the presence of __getitem__ to decide if a sub-object is a member therefore the best test for iterability is to use iter() and handle exceptions.

"},{"location":"languages/python/python.html#next-iter","title":"next() & iter()","text":"Python
next(iterable) # next item of the iterable or error StopIteration\n\niter(object) # get an iterator from an object\n# call callable_onj.next () with no arguments as long as it returns non-sentinel values\n\niter(callable_obj, sentinel)\n
"},{"location":"languages/python/python.html#customs-generators","title":"Customs Generators","text":"

Used to generate a sequence of values to be used once (they are not stored)

Python
def custom_generator(parameters):\n     while condition: # or for loop\n         yield variable # returns the value without terminating the function, values passed to the caller without storing in a variable\n\n# generator implementation\nfor item in custom_generator(parameters):\n     # code here\n
"},{"location":"languages/python/python.html#termination-generator-and-exception-handling","title":"Termination Generator And Exception Handling","text":"Python
# raise exception at the suspension point and return generator value\n# if the generator terminates without returning values it raises StopIteration\n# if an exception is not handled it is propagated to the caller\ngenerator.throw(ExceptionType, exception_value, traceback)\n\n# raises GeneratorExit to the point of suspension\n# if generator returns a value -> RuntimeError\n# if an exception is raised it propagates to the caller\ngenerator.close()\n
"},{"location":"languages/python/python.html#generator-comprehensions","title":"Generator Comprehensions","text":"Python
# zero-length sequence (instantaneously generated values)\nvar = (for expression iterable in sequence if condition)\n# EDUCATION ENUMERATE ()\n# returns a list of tuples associating a position index to each element of the sequence\n# [(0, sequence [0]), (1, sequence [1]), (2, sequence [2]), ...)\nenumerate(sequence) # -> enumerate object\n
"},{"location":"languages/python/python.html#coroutines","title":"Coroutines","text":"Python
def simple_coroutine():\n    \"\"\"coroutine defined as a generator: yield in block\"\"\"\n\n    # yield in expression to receive data\n    # returns None (no variables on the right of yield)\n    var = yield value # returns value and then suspends coroutine waiting for input\n    # instructions to the right of = executed before instructions to the left of =\n\ngen_obj = simple_coroutine() # returns generator object\nnext(gen_obj) # start coroutine (PRIMING)\ngen_obj.send(None) # start coroutine (PRIMING)\ngen_obj.send(value) # send value to the coroutine (only possible in suspended state)\n\n# STATES OF COROUTINE\ninspect.generatorstate() # returns the status of the coroutine\n# GEN_CREATED: waiting to start execution\n# GEN_RUNNING: currently run by the interpreter (visible if multithreaded)\n# GEN_SUSPENDED: currently suspended by yield statement\n# GEN_CLOSED: execution completed successfully\n\n# COROUTINE PRIMING\nfrom functools import wraps\n\ndef coroutine(func):\n    \"Decorator: primes 'func' by advancing to first 'yield'\"\n\n    @wraps(func)\n    def primer(*args, **kwargs):\n        gen = func(*args, **kwargs)\n        next(gen)\n        return gen\n    return primer\n\n# COROUTINE TERMINATION AND EXCEPTION HANDLING\n# exceptions in unhandled coroutines propagate to subsequent iterations\n# an exception causes the coroutine to terminate which it cannot resume\n\n# yield raises exception, if handled loop continues\n# throw() returns value of the generator\ncoroutine.throw(exc_type, exc_value, traceback)\n\n# yield raises GeneratorExit to the suspension point\n# if the generator yields a value -> RuntimeError\n# if there are other exceptions they are propagated to the caller\ncoroutine.close()\n# coroutine state becomes GEN_CLOSED\n
"},{"location":"languages/python/python.html#yield-from-iterabile","title":"yield from <iterabile>","text":"

Note: auto-priming generators incompatible with yield from

DELEGATING GENERATOR: generator function containing yield from SUBGENERATOR: generator obtained from yield from CALLER-CLIENT: code calling delegating generator

The main function of yield from is to open a bidirectional channel between the external caller (client) and the internal subgenerator so that values and exceptions can pass between the two.

  1. client calls delegating generator, delegating generator calls subgenerator
  2. exhausted subgenerator returns value to yield from <expr> (return <result> statement)
  3. delegating generator returns <expr> to client

  4. Any values that the subgenerator yields are passed directly to the caller of the delegating generator (i.e., the client code).

  5. Any values sent to the delegating generator using send() are passed directly to the subgenerator.

  6. If the sent value is None, the subgenerator's __next__() method is called.
  7. If the sent value is not None, the subgenerator's send() method is called.
  8. If the call raises StopIteration, the delegating generator is resumed.
  9. Any other exception is propagated to the delegating generator.

  10. return <expr> in a generator (or subgenerator) causes StopIteration(<expr>) to be raised upon exit from the generator.

  11. The value of the yield from expression is the first argument to the StopIteration exception raised by the subgenerator when it terminates.

  12. Exceptions other than GeneratorExit thrown into the delegating generator are passed to the throw() method of the subgenerator.

  13. If the call raises StopIteration, the delegating generator is resumed.
  14. Any other exception is propagated to the delegating generator.

  15. If a GeneratorExit exception is thrown into the delegating generator, or the close() method of the delegating generator is called, then the close() method of the subgenerator is called if it has one.

  16. If this call results in an exception, it is propagated to the delegating generator.
  17. Otherwise, GeneratorExit is raised in the delegating generator
Python
def sub_gen():\n     sent_input = yield\n     # result of sub_gen() returned to delegating_gen()\n     # result of yield from <expr>\n\n     return result\n\ndef delegating_gen(var):\n     var = yield from sub_gen() # get values from sub_gen\n\ndef client():\n     result = delegating_gen() # use delegating_gen\n     result.send(None) # terminate sub_gen instance (IMPORTANT)\n
"},{"location":"languages/python/python.html#lambda-functions","title":"LAMBDA Functions","text":"

Possible use within functions. Useful for replacing functions if the logic is simple.

Python
var = lambda argument_list: <expression>\n
"},{"location":"languages/python/python.html#object-oriented-programming","title":"Object Oriented Programming","text":""},{"location":"languages/python/python.html#class-definition","title":"Class Definition","text":"Python
class Class:\n\n    static_var = expression\n\n    def __init__(self, value_1, value_2): # parameterized default constructor\n        self.variable = value_1 # create instance variables\n        self.__private = value_2 # private, accessed via NAME MANGLING\n\n    def method(self, parameters):\n        ...\n\n    @staticmethod\n    def static_method(parameters): # static methods do not affect instance variables (SELF not needed)\n        ...\n\n    @classmethod # method acting on the class and not on the object (useful for alternative constructors)\n    def class_method(cls, parameters):\n        ...\n\n    object = Class(parameters) # creation of an object\n    object.variable = expression # edit public variable\n    object.method(parameters) # invocation method of instance\n    object._Class__private # access to variable specifying the membership class (NAME MANGLING)\n    Class.method(parameters) # static method invocation\n
"},{"location":"languages/python/python.html#setter-getter-with-property","title":"Setter & Getter with @Property","text":"Python
class Class:\n     def __init__(self, parameter):\n         self.__parameter = parameter\n\n     @property # getter\n     def parameter(self):\n         return self.__parameter\n\n     @<parameter>.setter\n     def parameter(self, value):\n         self.__parameter = value\n
"},{"location":"languages/python/python.html#__slots__","title":"__slots__","text":"

The __slots__ attribute implements the Flyweight Design Pattern: it saves the instance attributes in a tuple and can be used to decrease the cost in memory by inserting only the instance variables into it (suppress the instance dictionary).

Default: attributes saved in a dictionary (object .__ dict__) Usage: __slots_ = [attributes]

__slots__ is not inherited by subclasses, it prevents dynamically adding attributes.

"},{"location":"languages/python/python.html#inner-classes","title":"Inner Classes","text":"Python
class Class:\n     def __init__(self, parameters):\n         ...\n\n     class InnerClass:\n         def __init__(self, parameters):\n             ...\n\n         def method(self):\n             ...\n\nobject_1 = Class(arguments) # create 'external' class\nobject_2 = Class.InnerClass(arguments) # inner class created as object of the 'external' class\n
"},{"location":"languages/python/python.html#special-methods","title":"Special Methods","text":"

Special methods are defined by the use of double underscores; they allow the use of specific functions (possibly adapted) on the objects defined by the class.

Python
class Class():\n\n     def __init__(self, parameters):\n         instructions\n\n     # used by str() and print() method\n     # handle requests for impersonation as a string\n     def __str__ (self):\n         return expression # return required\n\n     def __len__ (self):\n         return expression # must return as len requires a length / size\n\n     def __del__ (self): # delete the class instance\n         instruction # any instructions that occur on deletion\n\nobject = Class()\nlen(object) # special function applied to an object\ndel object # delete object\n
"},{"location":"languages/python/python.html#special-methods-list","title":"Special Methods List","text":"

Note: if the operator cannot be applied, returns NotImplemented

Python
# arithmetic operators\n__add__(self, other)         # +\n__sub__(self, other)         # -\n__mul__(self, other)         # *\n__matmul__(self, other)      # (@) matrix multiplication\n__truediv__(self, other)     # /\n__floordiv__(self, other)  # //\n__mod__(self, other)         # %\n__divmod__(self, other)      # divmod()\n__pow__(self, other)         # **, pow()\n__lshift__(self, other)      # <<\n__rshift__(self, other)      # >>\n__and__(self, other)         # &\n__xor__(self, other)         # ^\n__or__(self, other)          # |\n\n# reflex arithmetic operators\n# if self.__ dunder __(other) fails, other.__ dunder__(self) is called\n__radd__(self, other)         # reverse +\n__rsub__(self, other)         # reverse -\n__rmul__(self, other)         # reverse *\n__rmatmul__(self, other)      # reverse @\n__rtruediv__(self, other)     # reverse /\n__rfloordiv__(self, other)    # reverse //\n__rmod__(self, other)         # reverse %\n__rdivmod__(self, other)      # reverse divmod()\n__rpow__(self, other)         # reverse **, pow()\n__rlshift__(self, other)      # reverse <<\n__rrshift__(self, other)      # reverse >>\n__rand__(self, other)         # reverse &\n__rxor__(self, other)         # reverse ^\n__ror__(self, other)          # reverse |\n\n# in-place arithmetic operators\n# base implementation (built-in) like self = self <operator> other\n#! not to be implemented for immutable objects!\n#! in-place operators return self!\n__iadd__(self, other)         # +=\n__isub__(self, other)         # -=\n__imul__(self, other)         # *=\n__imatmul__(self, other)      # @=\n__itruediv__(self, other)     # /=\n__ifloordiv__(self, other)    # //=\n__imod__(self, other)         # %=\n__ipow__(self, other)         # **=\n__ilshift__(self, other)      # <<=\n__irshift__(self, other)      # >>=\n__iand__(self, other)         # &=\n__ixor__(self, other)         # ^=\n__ior__(self, other)          # |=\n\n# unary mathematical operators (-, +, abs (), ~)\n__neg__(self)  # (-) negazione matematica unaria [if x = 2 then -x = 2]\n__pos__(self)  # (+) addizione unaria [x = +x]\n__abs__(self)  # [abs()] valore assoluto [|-x| = x]\n__invert__(self)  # (~) inversione binaria di un intero [~x == -(x + 1)]\n\n# numeric type conversion\n__complex__(self)\n__int__(self)  # if not defined fall-back on __trunc__()\n__float__(self)\n__index__(self)  # conversion in bin(), hex(), oct() e slicing\n\n# operations round() math.trunc(), math.floor(), math.ceil()\n__round__(self)\n__trunc__(self)\n__floor__(self)\n__ceil__(self)\n\n# equality operators\nself.__eq__(other)  # self == other\nself.__ne__(other) # self != other\nself.__gt__(other) # self > other\nself.__ge__(other) # self >= other\nself.__lt__(other) # self < other\nself.__le__(other) # self <= other\n\n# reflected equality operators\nother.__eq__(self)  # other == self,   fall-back id(self) == id(other)\nother.__ne__(self)  # other != self,   fall-back not (self == other)\nother.__gt__(self)  # reverse self < other,   fall-back TypeError\nother.__ge__(self)  # reverse self <= other,   fall-back TypeError\nother.__lt__(self)  # reverse self > other,   fall-back TypeError\nother.__le__(self)  # reverse self >= other,   fall-back TypeError\n\n# called when the instance is \"called\" as a function\n# x (arg1, arg2, arg3) is short for x .__ call __ (arg1, arg2, arg3)\n__call__(self, args)\n\n# string object representation for the developer\n__repr__(self)\n\n# string object representation for user (used by print)\n__str__(self)\n\n# specify formatting for format ), str.format() [format_spec = format-mini-language]\n__format__(format_spec)\n\n# returns unique (integer) value for objects that have equal value\n# __EQ__ MUST EXIST IN THE CLASS, usually hash((self.param_1, self.param_2, ...))\n__hash__(self)\n\n# makes object iterable:\n# - returning self (in the iterator)\n# - returning an iterator (in the iterable)\n# - using yield (in the __iter__ generator)\n__iter__(self)\n\n# returns next available element, StopIteration otherwise (iterator scrolls)\n__next__()\n\n# returns truth value\n__bool__()\n\n# returns item associated with key of a sequence (self [key])\n# IndexError if key is not appropriate\n__getitem__(self, key)\n\n# item assignment operation in sequence (self [key] = value)\n# IndexError if key is not appropriate\n__setitem__(self, key, value)\n\n# operation deleting item in sequence (del self [key])\n# IndexError if key is not appropriate\n__delitem__(self, key)\n\n# called by dict.__getitem__() to implement self [key] if key is not in the dictionary\n__missing__(self, key)\n\n# implement container iteration\n__iter__(self)\n\n# implement membership test\n__contains__(self, item)\n\n# implementation issublass (instance, class)\n__instancecheck__(self, instance)\n\n# implementation issubclass (subclass, class)\n__subclasscheck__(self, subclass)\n\n# implement attribute access (obj.name)\n# called if AttributeError happens or if called by __getattribute __()\n__getattr__(self, name)\n\n# implement value assignment to attribute (obj.name = value)\n__setattr__(self, name, value)\n

Note: Itearbility is tricky.

To make an object directly iterable (for i in object) __iter__() and __next__() are needed. To make an iterable through an index (for i in range(len(object)): object[i]) __getitem()__ is needed.

Some of the mixin methods, such as __iter__(), __reversed__() and index(), make repeated calls to the underlying __getitem__() method. Consequently, if __getitem__() is implemented with constant access speed, the mixin methods will have linear performance; however, if the underlying method is linear (as it would be with a linked list), the mixins will have quadratic performance and will likely need to be overridden.

"},{"location":"languages/python/python.html#inheritance","title":"Inheritance","text":"Python
class Parent ():\n    def __init __ (self, parameters):\n        ...\n\n    def method_1(self):\n        ...\n\n    def method_2(self):\n        ...\n\nclass Child(Parent): # parent class in parentheses to inherit variables and methods\n\n    def __init__(self, parameters, parent_parameters):\n        Parent.__init__(self, parent_parameters) # inherit parent variables\n        ...\n\n    def method (self):\n        ...\n\n    def method_parent_1 (self): # override method (child class with homonymous method to parent class)\n        ...\n\nclass Child(Parent): # parent class in brackets to inherit properties\n\n    def __init__(self, parameters, parent_parameters):\n        super().__init__(parent_parameters) # different method to inherit parent variables (SELF not needed) using SUPER()\n        super(Parent, self).__init__(parent_parameters) # parent constructor invoked separately\n\n    def method(self):\n        ...\n\n    def method_2(self): # parent method updated\n        super().method_2() # invoke parent method as is\n        ...\n
"},{"location":"languages/python/python.html#polymorphism","title":"Polymorphism","text":"

Note: python does not support method overloading

Python
# DUCKTYPING\n# Working with objects regardless of their type, as long as they implement certain protocols\n\nclass Class1:\n    def method_1(self):\n        ...\n\nclass Class2:\n    def method_1(self):\n        ...\n\n# since python is a dynamic language it doesn't matter what type (class) the object passed is\n# the function invokes the object method passed regardless of the object class\ndef polymorph_method(object):\n    object.method_1()\n\n# DEPENDENCY INJECTION WITH DUCKTYPING\nclass Class:\n    def __init__(self, object):\n        self.dependency = object\n\n    def method_1(self): # the function invokes the method of the object passed\n        self.dependency.method_1()\n
"},{"location":"languages/python/python.html#operator-overloading","title":"Operator Overloading","text":"

Operators fundamental rule: always return an object, if operation fails return NotImplemented

Limitations of operator overloading:

"},{"location":"languages/python/python.html#astrazione","title":"Astrazione","text":"

The interfaces are abstract classes with all abstract methods, they are used to indicate which methods such as child classes must have. Interfaces have only a list of abstract methods.

abstract classes have at least one abstract method; child classes that inherit from an abstract class must implement abstract methods. Abstract classes cannot be instantiated.

Virtual subclasses are used to include third-party classes as subclasses of a class of their own. They are recognized as belonging to the parent class without however having to implement their methods.

The @Class.register or Class.register(subclass) decorators are used to mark subclasses.

Python
from abc import abstractmethod, ABC\n\nclass Abstract(ABC): # abstract class MUST INHERIT from parent class ABC\n    def __init__(self, parameters):\n        ...\n\n    def parent_method (self):\n        ...\n\n    @abstractmethod # abstract method MUST be marked with @abstractmethod decorator\n    def abstract_method (self):\n        pass\n        # abstract method MUST be overridden (can be non-empty)\n        # super() to invoke it in the concrete class\n\nclass Child(Abstract):\n\n    def __init__(self, parameters, parent_parameters):\n        parent_class.__init__(self, parent_parameters)\n\n    def method (self):\n        ...\n\n    def parent_method (self): # override method (child class with homonymous method to parent class)\n        ...\n\n    def abstract_method (self): # implementation of abstract method inherited from abstract class (NECESSARY) by override\n        ...\n
"},{"location":"languages/python/python.html#exception-handling","title":"Exception Handling","text":"Python
# CHECK ASERATIONS\nassert condition, 'error message' # if the assertion is false show an error message\n\n# particular errors are objects of a particular class of exceptions which in turn is a child of the base exception class (exception)\nclass CustomExceptionError(Exception): # MUST somehow inherit from class exception (even in later inheritance steps)\n    pass # or instructions\n\n# try block contains code that might cause an exception\n# code inside try and after the error it is not executed\ntry:\n    ...\n    raise CustomExceptionError (\"message\") # raise the exception\n\n# except takes control of error handling without passing through the interpreter\n# block executed if an error occurs in try\n\n# except error specified by class\nexcept ExceptionClass:\n    # Default error message is not shown\n    # the program does not stop\n\n# except on generic errors\nexcept:\n     # code here\n\n# block executed if exception does not occur\nelse:\n    # code here\n\n# block executed in all cases, cleanup code goes here\nfinally:\n    # code here\n
"},{"location":"languages/python/python.html#file","title":"File","text":""},{"location":"languages/python/python.html#opening-a-file","title":"Opening A File","text":"

Text file opening mode:

Open binary file mode:

Note: Linux and MacOSX use UTF-8 everywhere while windows uses cp1252, cp850,mbcs, UTF-8. Don't rely on default encoding and use explicitly UTF-8.

Python
object = open('filename', mode = 'r', encoding = 'utf-8') # encoding MUST BE utf-8 for compatibility\n# filename can be the absolute path to the file location (default: file created in the source code folder)\n# double slash to avoid \\ escaping\n\nwith open('filename') as file:\n    instructions_to_file # block use filename to indicate file\n\n# CLOSE A FILE\nobject.close()\n\n# WRITE TO A FILE\nobject.write(string) # write single string to file\nobject.writelines(* strings) # write multiple strings to file\n\n# READING FROM A FILE\nobject.read() # return ALL the contents of the file (including escape sequence) and place the \"cursor\" at the end of the file\nobject.seek(0) # returns 0 (zero) and places the cursor at the beginning of the file\nobject.readlines() # return list of file lines (ATTENTION: keep everything in memory, be careful with large files)\nobject.readline() # returns single line file\n\n# CHECK FILE EXISTENCE\nimport os, sys\nif os.path.isfile('filepath'): # check file existence (TRUE if it exists)\n    # code here\nelse:\n    # code here\n    sys.exit() # exits the program and does not execute the next cosice\n
"},{"location":"languages/python/python.html#copy","title":"COPY","text":"

SHALLOW COPY: copies the \"container\" and references to the content DEEP COPY: copies the \"container\" and contents (no reference)

Python
copy (x) # returns shallow copy of xor\ndeepcopy (x) # returns shallow copy of x\n
"},{"location":"languages/python/libs/beautiful-soup.html","title":"Beautiful Soup Library","text":""},{"location":"languages/python/libs/beautiful-soup.html#making-the-soup","title":"Making the Soup","text":"Python
from bs4 import BeautifulSoup\nimport requests\nimport lxml  # better html parser than built-in\n\nresponse = requests.get(\"url\")  # retrieve a web page\n\nsoup = BeautifulSoup(response.text, \"html.parser\")  # parse HTML from response w/ python default HTML parser\nsoup = BeautifulSoup(response.text, \"lxml\")  # parse HTML from response w/ lxml parser\n\nsoup.prettify()  # prettify parsed HTML for display\n
"},{"location":"languages/python/libs/beautiful-soup.html#kinds-of-objects","title":"Kinds of Objects","text":"

Beautiful Soup transforms a complex HTML document into a complex tree of Python objects.

"},{"location":"languages/python/libs/beautiful-soup.html#tag","title":"Tag","text":"

A Tag object corresponds to an XML or HTML tag in the original document

Python
soup = BeautifulSoup('<b class=\"boldest\">Extremely bold</b>', 'html.parser')  # parse HTML/XML\n\ntag = soup.b\ntype(tag)  # <class 'bs4.element.Tag'>\nprint(tag)  # <b class=\"boldest\">Extremely bold</b>\n\ntag.name  # tag name\ntag[\"attribute\"]  # access to tag attribute  values\ntag.attrs  # dict of attribue-value pairs\n
"},{"location":"languages/python/libs/beautiful-soup.html#navigable-string","title":"Navigable String","text":"

A string corresponds to a bit of text within a tag. Beautiful Soup uses the NavigableString class to contain these bits of text.

"},{"location":"languages/python/libs/beautiful-soup.html#navigating-the-tree","title":"Navigating the Tree","text":""},{"location":"languages/python/libs/beautiful-soup.html#going-down","title":"Going Down","text":"Python
soup.<tag>.<child_tag>  # navigate using tag names\n\n<tag>.contents  # direct children as a list\n<tag>.children  # direct children as a generator for iteration\n<tag>.descendants  # iterator over all children, recursive\n\n<tag>.string  # tag contents, does not have further children\n# If a tag's only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child\n# If a tag contains more than one thing, then it's not clear what .string should refer to, so .string is defined to be None\n\n<tag>.strings  # generator to iterate over all children's strings (will list white space)\n<tag>.stripped_strings  # generator to iterate over all children's strings (will NOT list white space)\n
"},{"location":"languages/python/libs/beautiful-soup.html#going-up","title":"Going Up","text":"Python
<tag>.parent  # tags direct parent (BeautifulSoup has parent None, html has parent BeautifulSoup)\n<tag>.parents  # iterable over all parents\n
"},{"location":"languages/python/libs/beautiful-soup.html#going-sideways","title":"Going Sideways","text":"Python
<tag>.previous_sibling\n<tag>.next_sibling\n\n<tag>.previous_siblings\n<tag>.next_siblings\n
"},{"location":"languages/python/libs/beautiful-soup.html#going-back-and-forth","title":"Going Back and Forth","text":"Python
<tag>.previous_element  # whatever was parsed immediately before\n<tag>.next_element # whatever was parsed immediately afterwards\n\n<tag>.previous_elements  # whatever was parsed immediately before as a list\n<tag>.next_elements  # whatever was parsed immediately afterwards as a list\n
"},{"location":"languages/python/libs/beautiful-soup.html#searching-the-tree","title":"Searching the Tree","text":""},{"location":"languages/python/libs/beautiful-soup.html#filter-types","title":"Filter Types","text":"Python
soup.find_all(\"tag\")  # by name\nsoup.find_all([\"tag1\", \"tag2\"])  # multiple tags in a list\nsoup.find_all(function)  # based on a bool function\nsoup.find_all(True)  # Match everything\n
"},{"location":"languages/python/libs/beautiful-soup.html#methods","title":"Methods","text":"

Methods arguments:

Python
find_all(name, attrs, recursive, string, limit, **kwargs)  # several results\nfind(name, attrs, recursive, string, **kwargs)  # one result\n\nfind_parents(name, attrs, string, limit, **kwargs)  # several results\nfind_parent(name, attrs, string, **kwargs)  # one result\n\nfind_next_siblings(name, attrs, string, limit, **kwargs)  # several results\nfind_next_sibling(name, attrs, string, **kwargs)  # one result\n\nfind_previous_siblings(name, attrs, string, limit, **kwargs)  # several results\nfind_previous_sibling(name, attrs, string, **kwargs)  # one result\n\nfind_all_next(name, attrs, string, limit, **kwargs)  # several results\nfind_next(name, attrs, string, **kwargs)  # one result\n\nfind_all_previous(name, attrs, string, limit, **kwargs)  # several results\nfind_previous(name, attrs, string, **kwargs)  # one result\n\nsoup(\"html_tag\")  # same as soup.find_all(\"html_tag\")\nsoup.find(\"html_tag\").text  # text of the found tag\nsoup.select(\"css_selector\")  # search for CSS selectors of HTML tags\n
"},{"location":"languages/python/libs/beautiful-soup.html#modifying-the-tree","title":"Modifying the Tree","text":""},{"location":"languages/python/libs/beautiful-soup.html#changing-tag-names-an-attributes","title":"Changing Tag Names an Attributes","text":"Python
<tag>.name = \"new_html_tag\"  # modify the tag type\n<tag>[\"attribute\"]  = \"value\"  # modify the attribute value\ndel <tag>[\"attribute\"]  # remove the attribute\n\nsoup.new_tag(\"name\", <attribute> = \"value\")  # create a new tag with specified name and attributes\n\n<tag>.string = \"new content\"  # modify tag text content\n<tag>.append(item)  # append to Tag content\n<tag>.extend([item1, item2])  # add every element of the list in order\n\n<tag>.insert(position: int, item)  # like .insert in Python list\n\n<tag>.insert_before(new_tag)  # insert tags or strings immediately before something else in the parse tree\n<tag>.insert_after(new_tag)  # insert tags or strings immediately before something else in the parse tree\n\n<tag>.clear()  # remove all tag's contents\n\n<tag>.extract()  # extract and return the tag from the tree (operates on self)\n<tag>.string.extract()  # extract and return the string from the tree (operates on self)\n<tag>.decompose()  # remove a tag from the tree, then completely destroy it and its contents\n<tag>.decomposed  # check if tag has be decomposed\n\n<tag>.replace_with(item)  # remove a tag or string from the tree, and replaces it with the tag or string of choice\n\n<tag>.wrap(other_tag)  # wrap an element in the tag you specify, return the new wrapper\n<tag>.unwrap()  # replace a tag with whatever's inside, good for stripping out markup\n\n<tag>.smooth()  # clean up the parse tree by consolidating adjacent strings\n
"},{"location":"languages/python/libs/numpy.html","title":"NumPy Lib","text":""},{"location":"languages/python/libs/numpy.html#most-important-attributes-attributes","title":"MOST IMPORTANT ATTRIBUTES ATTRIBUTES","text":"Python
array.ndim     # number of axes (dimensions) of the array\narray.shape  # dimensions of the array, tuple of integers\narray.size  # total number of elements in the array\narray.itemsize  # size in bytes of each element\narray.data  # buffer containing the array elements\n
"},{"location":"languages/python/libs/numpy.html#array-creation","title":"ARRAY CREATION","text":"

Unless explicitly specified np.array tries to infer a good data type for the array that it creates. The data type is stored in a special dtype object.

Python
var = np.array(sequence)  # creates array\nvar = np.asarray(sequence)  # convert input to array\nvar = np.ndarray(*sequence)  # creates multidimensional array\nvar = np.asanyarray(*sequence)  # convert the input to an ndarray\n# nested sequences will be converted to multidimensional array\n\nvar = np.zeros(ndarray.shape)  # array with all zeros\nvar = np.ones(ndarray.shape)  # array with all ones\nvar = np.empty(ndarray.shape)  # array with random values\nvar = np.identity(n)  # identity array (n x n)\n\nvar = np.arange(start, stop, step)  # creates an array with parameters specified\nvar = np.linspace(start, stop, num_of_elements)  # step of elements calculated based on parameters\n
"},{"location":"languages/python/libs/numpy.html#data-types-for-ndarrays","title":"DATA TYPES FOR NDARRAYS","text":"Python
var = array.astype(np.dtype)  # copy of the array, cast to a specified type\n# return TypeError if casting fails\n

The numerical dtypes are named the same way: a type name followed by a number indicating the number of bits per element.

TYPE TYPE CODE DESCRIPTION int8, uint8 i1, u1 Signed and unsigned 8-bit (1 byte) integer types int16, uint16 i2, u2 Signed and unsigned 16-bit integer types int32, uint32 i4, u4 Signed and unsigned 32-bit integer types int64, uint64 i8, u8 Signed and unsigned 32-bit integer types float16 f2 Half-precision floating point float32 f4 or f Standard single-precision floating point. Compatible with C float float64, float128 f8 or d Standard double-precision floating point. Compatible with C double and Python float object float128 f16 or g Extended-precision floating point complex64, complex128, complex256 c8, c16, c32 Complex numbers represented by two 32, 64, or 128 floats, respectively bool ? Boolean type storing True and False values object O Python object type string_ S<num> Fixed-length string type (1 byte per character), <num> is string length unicode_ U<num> Fixed-length unicode type, <num> is length"},{"location":"languages/python/libs/numpy.html#operations-between-arrays-and-scalars","title":"OPERATIONS BETWEEN ARRAYS AND SCALARS","text":"

Any arithmetic operations between equal-size arrays applies the operation element-wise.

array + scalar \u2192 element-wise addition ([1, 2, 3] + 2 = [3, 4, 5]) array - scalar \u2192 element-wise subtraction ([1 , 2, 3] - 2 = [-2, 0, 1]) array * scalar \u2192 element-wise multiplication ([1, 2, 3] * 3 = [3, 6, 9]) array / scalar \u2192 element-wise division ([1, 2, 3] / 2 = [0.5 , 1 , 1.5])

array_1 + array_2 \u2192 element-wise addition ([1, 2, 3] + [1, 2, 3] = [2, 4, 6]) array_1 - array_2 \u2192 element-wise subtraction ([1, 2, 4] - [3 , 2, 1] = [-2, 0, 2]) array_1 * array_2 \u2192 element-wise multiplication ([1, 2, 3] * [3, 2, 1] = [3, 4, 3]) array_1 / array_2 \u2192 element-wise division ([1, 2, 3] / [3, 2, 1] = [0.33, 1, 3])

"},{"location":"languages/python/libs/numpy.html#shape-manipulation","title":"SHAPE MANIPULATION","text":"Python
np.reshape(array, new_shape)  # changes the shape of the array\nnp.ravel(array)  #  returns the array flattened\narray.resize(shape)  # modifies the array itself\narray.T  # returns the array transposed\nnp.transpose(array)     # returns the array transposed\nnp.swapaxes(array, first_axis, second_axis)  # interchange two axes of an array\n# if array is an ndarray, then a view of it is returned; otherwise a new array is created\n
"},{"location":"languages/python/libs/numpy.html#joining-arrays","title":"JOINING ARRAYS","text":"Python
np.vstack((array1, array2))   # takes tuple, vertical stack of arrays (column wise)\nnp.hstack((array1, array2))  # takes a tuple, horizontal stack of arrays (row wise)\nnp.dstack((array1, array2)) # takes a tuple, depth wise stack of arrays (3rd dimension)\nnp.stack(*arrays, axis)  # joins a sequence of arrays along a new axis (axis is an int)\nnp.concatenate((array1, array2, ...), axis) # joins a sequence of arrays along an existing axis (axis is an int)\n
"},{"location":"languages/python/libs/numpy.html#splitting-arrays","title":"SPLITTING ARRAYS","text":"Python
np.split(array, indices)  # splits an array into equall7 long sub-arrays (indices is int), if not possible raises error\nnp.vsplit(array, indices)  # splits an array equally into sub-arrays vertically (row wise) if not possible raises error\nnp.hsplit(array, indices)  # splits an array equally into sub-arrays horizontally (column wise) if not possible raises error\nnp.dsplit(array, indices)  # splits an array into equally sub-arrays along the 3rd axis (depth) if not possible raises error\nnp.array_split(array, indices) # splits an array into sub-arrays, arrays can be of different lengths\n
"},{"location":"languages/python/libs/numpy.html#view","title":"VIEW()","text":"Python
var = array.view()  # creates a new array that looks at the same data\n# slicing returns a view\n# view shapes are separated but assignment changes all arrays\n
"},{"location":"languages/python/libs/numpy.html#copy","title":"COPY()","text":"Python
var = array.copy()  # creates a deep copy of the array\n
"},{"location":"languages/python/libs/numpy.html#indexing-slicing-iterating","title":"INDEXING, SLICING, ITERATING","text":"

1-dimensional \u2192 sliced, iterated and indexed as standard n-dimensional \u2192 one index per axis, index given in tuple separated by commas [i, j] (i, j) dots (...) represent as many colons as needed to produce complete indexing tuple

"},{"location":"languages/python/libs/numpy.html#universal-functions-ufunc","title":"UNIVERSAL FUNCTIONS (ufunc)","text":"

Functions that performs element-wise operations (vectorization).

Python
np.abs(array)  # vectorized abs(), return element absolute value\nnp.fabs(array)  # faster abs() for non-complex values\nnp.sqrt(array)  # vectorized square root (x^0.5)\nnp.square(array) # vectorized square (x^2)\nnp.exp(array)  # vectorized natural exponentiation (e^x)\nnp.log(array)  # vectorized natural log(x)\nnp.log10(array)  # vectorized log10(x)\nnp.log2(array)  # vectorized log2(x)\nnp.log1p(array)  # vectorized log(1 + x)\nnp.sign(array)  # vectorized sign (1, 0, -1)\nnp.ceil(array)  # vectorized ceil()\nnp.floor(array)  # vectorized floor()\nnp.rint(array)     # vectorized round() to nearest int\nnp.modf(array)  #  vectorized divmod(), returns the fractional and integral parts of element\nnp.isnan(array)   # vectorized x == NaN, return boolean array\nnp.isinf(array)  # vectorized test for positive or negative infinity, return boolean array\nnp.isfineite(array)  # vectorized test fo finiteness, returns boolean array\nnp.cos(array)  # vectorized cos(x)\nnp.sin(array)  # vectorized sin(x)\nnp.tan(array)  # vectorized tan(x)\nnp.cosh(array)  # vectorized cosh(x)\nnp.sinh(array)   # vector sinh(x)\nnp.tanh(array)  # vectorized tanh(x)\nnp.arccos(array)  # vectorized arccos(x)\nnp.arcsinh(array)  # vectorized arcsinh(x)\nnp.arctan(array)  # vectorized arctan(x)\nnp.arccosh(array)  # vectorized arccosh(x)\nnp.arcsinh(array)  # vectorized arcsin(x)\nnp.arctanh(array)  # vectorized arctanh(x)\nnp.logical_not(array)  # vectorized not(x), equivalent to -array\n\nnp.add(x_array, y_array)  # vectorized addition\nnp.subtract(x_array, y_array)  # vectorized subtraction\nnp.multiply(x_array, y_array)  # vectorized multiplication\nnp.divide(x_array, y_array)  # vectorized division\nnp.floor_divide(x_array, y_array)  # vectorized floor division\nnp.power(x_array, y_array)  # vectorized power\nnp.maximum(x_array, y_array)  # vectorized maximum\nnp.minimum(x_array, y_array)  # vectorized minimum\nnp.fmax(x_array, y_array)  # vectorized maximum, ignores NaN\nnp.fmin(x_array, y_array)  # vectorized minimum, ignores NaN\nnp.mod(x_array, y_array)  # vectorized modulus\nnp.copysign(x_array, y_array)  #  vectorized copy sign from y_array to x_array\nnp.greater(x_array, y_array)  # vectorized x > y\nnp.less(x_array, y_array)  # vectorized x < y\nnp.greter_equal(x_array, y_array)  # vectorized x >= y\nnp.less_equal(x_array, y_array)  # vectorized x <= y\nnp.equal(x_array, y_array)  # vectorized x == y\nnp.not_equal(x_array, y_array)  # vectorized x != y\nnp.logical_and(x_array, y_array)  # vectorized x & y\nnp.logical_or(x_array, y_array)  # vectorized x | y\nnp.logical_xor(x_array, y_array)  # vectorized x ^ y\n
"},{"location":"languages/python/libs/numpy.html#conditional-logic-as-array-operations","title":"CONDITIONAL LOGIC AS ARRAY OPERATIONS","text":"Python
np.where(condition, x, y)  # return x if condition == True, y otherwise\n
"},{"location":"languages/python/libs/numpy.html#mathematical-and-statistical-methods","title":"MATHEMATICAL AND STATISTICAL METHODS","text":"

np.method(array, args) or array.method(args). Boolean values are coerced to 1 (True) and 0 (False).

Python
np.sum(array, axis=None)  # sum of array elements over a given axis\nnp.median(array, axis=None)  # median along the specified axis\nnp.mean(array, axis=None)  # arithmetic mean along the specified axis\nnp.average(array, axis=None)  #  weighted average along the specified axis\nnp.std(array, axis=None)  # standard deviation along the specified axis\nnp.var(array, axis=None)  # variance along the specified axis\n\nnp.min(array, axis=None)  # minimum value along the specified axis\nnp.max(array, axis=None)  # maximum value along the specified axis\nnp.argmin(array, axis=None)  # indices of the minimum values along an axis\nnp.argmax(array, axis=None)  # indices of the maximum values\nnp.cumsum(array, axis=None)  # cumulative sum of the elements along a given axis\nnp.cumprod(array, axis=None)  # cumulative sum of the elements along a given axis\n
"},{"location":"languages/python/libs/numpy.html#methods-for-boolean-arrays","title":"METHODS FOR BOOLEAN ARRAYS","text":"Python
np.all(array, axis=None)  # test whether all array elements along a given axis evaluate to True\nnp.any(array, axis=None)  # test whether any array element along a given axis evaluates to True\n
"},{"location":"languages/python/libs/numpy.html#sorting","title":"SORTING","text":"Python
array.sort(axis=-1)  # sort an array in-place (axis = None applies on flattened array)\nnp.sort(array, axis=-1)  # return a sorted copy of an array (axis = None applies on flattened array)\n
"},{"location":"languages/python/libs/numpy.html#set-logic","title":"SET LOGIC","text":"Python
np.unique(array)  # sorted unique elements of an array\nnp.intersect1d(x, y)  # sorted common elements in x and y\nnp.union1d(x, y)  # sorte union of elements\nnp.in1d(x, y)  #  boolean array indicating whether each element of x is contained in y\nnp.setdiff1d(x, y)  # Set difference, elements in x that are not in y\nnp.setxor1d()  # Set symmetric differences; elements that are in either of the arrays, but not both\n
"},{"location":"languages/python/libs/numpy.html#file-io-with-arrays","title":"FILE I/O WITH ARRAYS","text":"Python
np.save(file, array)  # save array to binary file in .npy format\nnp.savez(file, *array) # save several arrays into a single file in uncompressed .npz format\nnp.savez_compressed(file, *args, *kwargs)  # save several arrays into a single file in compressed .npz format\n# *ARGS: arrays to save to the file. arrays will be saved with names \"arr_0\", \"arr_1\", and so on\n# **KWARGS: arrays to save to the file. arrays will be saved in the file with the keyword names\n\nnp.savetxt(file, X, fmt=\"%.18e\", delimiter=\" \")   # save array to text file\n# X: 1D or 2D\n# FMT: Python Format Specification Mini-Language\n# DELIMITER: {str} -- string used to separate values\n\nnp.load(file, allow_pickle=False)  # load arrays or pickled objects from .npy, .npz or pickled files\nnp.loadtxt(file, dtype=float, comments=\"#\", delimiter=None)\n# DTYPE: {data type} -- data-type of the resulting array\n# COMMENTS: {str} -- characters used to indicate the start of a comment. None implies no comments\n# DELIMITER: {str} -- string used to separate values\n
"},{"location":"languages/python/libs/numpy.html#linear-algebra","title":"LINEAR ALGEBRA","text":"Python
np.diag(array, k=0)  # extract a diagonal or construct a diagonal array\n# K: {int} -- k>0 diagonals above main diagonal, k<0 diagonals below main diagonal (main diagonal k = 0)\n\nnp.dot(x ,y)  # matrix dot product\nnp.trace(array, offset=0, dtype=None, out=None)  # return the sum along diagonals of the array\n# OFFSET: {int} -- offset of the diagonal from the main diagonal\n# dtype: {dtype} -- determines the data-type of the returned array\n# OUT: {ndarray} -- array into which the output is placed\n\nnp.linalg.det(A)  # compute the determinant of an array\nnp.linalg.eig(A)  # compute the eigenvalues and right eigenvectors of a square array\nnp.linalg.inv(A)  # compute the (multiplicative) inverse of a matrix\n# A_inv satisfies dot(A, A_inv) = dor(A_inv, A) = eye(A.shape[0])\n\nnp.linalg.pinv(A)  # compute the (Moore-Penrose) pseudo-inverse of a matrix\nnp.linalg.qr()  # factor the matrix a as qr, where q is orthonormal and r is upper-triangular\nnp.linalg.svd(A)  # Singular Value Decomposition\nnp.linalg.solve(A, B)  # solve a linear matrix equation, or system of linear scalar equations AX = B\nnp.linalg.lstsq(A, B)  # return the least-squares solution to a linear matrix equation AX = B\n
"},{"location":"languages/python/libs/numpy.html#random-number-generation","title":"RANDOM NUMBER GENERATION","text":"Python
np.random.seed()\nnp.random.rand()\nnp.random.randn()\nnp.random.randint()\nnp.random.Generator.permutation(x)  # randomly permute a sequence, or return a permuted range\nnp.random.Generator.shuffle(x)  # Modify a sequence in-place by shuffling its contents\n\nnp.random.Generator.beta(a, b, size=None)  # draw samples from a Beta distribution\n# A: {float, array floats} -- Alpha, > 0\n# B: {int, tuple ints} -- Beta, > 0\n\nnp.random.Generator.binomial(n, p, size=None)  # draw samples from a binomial distribution\n# N: {int, array ints} -- parameter of the distribution, >= 0\n# P: {float, arrey floats} -- Parameter of the distribution, >= 0 and <= 1\n\nnp.random.Generator.chisquare(df, size=None)\n# DF: {float, array floats} -- degrees of freedom, > 0\n\nnp.random.Generator.gamma(shape, scale=1.0, size=None)  # draw samples from a Gamma distribution\n# SHAPE: {float, array floats} -- shape of the gamma distribution, != 0\n\nnp.random.Generator.normal(loc=0.0, scale=1.0, Size=None)  # draw random samples from a normal (Gaussian) distribution\n# LOC: {float, all floats} -- mean (\"centre\") of distribution\n# SCALE: {float, all floats} -- standard deviation of distribution, != 0\n\nnp.random.Generator.poisson(lam=1.0, size=None)  # draw samples from a Poisson distribution\n# LAM: {float, all floats} -- expectation of interval, >= 0\n\nnp.random.Generator.uniform(low=0.0,high=1.0, size=None)  # draw samples from a uniform distribution\n# LOW: {float, all floats} -- lower boundary of the output interval\n# HIGH: {float, all floats} -- upper boundary of the output interval\n\nnp.random.Generator.zipf(a, size=None)  # draw samples from a Zipf distribution\n# A: {float, all floats} -- distribution parameter, > 1\n
"},{"location":"languages/python/libs/pandas.html","title":"Pandas","text":""},{"location":"languages/python/libs/pandas.html#basic-pandas-imports","title":"Basic Pandas Imports","text":"Python
import numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\n
"},{"location":"languages/python/libs/pandas.html#series","title":"SERIES","text":"

1-dimensional labelled array, axis label referred as INDEX. Index can contain repetitions.

Python
s = Series(data, index=index, name='name')\n# DATA: {python dict, ndarray, scalar value}\n# NAME: {string}\ns = Series(dict)  # Series created from python dict, dict keys become index values\n
"},{"location":"languages/python/libs/pandas.html#indexing-selection-slicing","title":"INDEXING / SELECTION / SLICING","text":"Python
s['index']  # selection by index label\ns[condition]  # return slice selected by condition\ns[ : ]  # slice endpoint included\ns[ : ] = *value  # modify value of entire slice\ns[condition] = *value  # modify slice by condition\n
"},{"location":"languages/python/libs/pandas.html#missing-data","title":"MISSING DATA","text":"

Missing data appears as NaN (Not a Number).

Python
pd.isnull(array)  # return a Series index-bool indicating which indexes don't have data\npd.notnull(array)  # return a Series index-bool indicating which indexes have data\narray.isnull()\narray.notnull()\n
"},{"location":"languages/python/libs/pandas.html#series-attributes","title":"SERIES ATTRIBUTES","text":"Python
s.values  # NumPy representation of Series\ns.index  # index object of Series\ns.name = \"Series name\"  # renames Series object\ns.index.name = \"index name\"  # renames index\n
"},{"location":"languages/python/libs/pandas.html#series-methods","title":"SERIES METHODS","text":"Python
pd.Series.isin(self, values)  #  boolean Series showing whether elements in Series matches elements in values exactly\n\n# Conform Series to new index, new object produced unless the new index is equivalent to current one and copy=False\npd.Series.reindex(self, index=None, **kwargs)\n# INDEX: {array} -- new labels / index\n# METHOD: {none (don't fill gaps), pad (fill or carry values forward), backfill (fill or carry values backward)}-- hole filling method\n# COPY: {bool} -- return new object even if index is same -- DEFAULT True\n# FILLVALUE: {scalar} --value to use for missing values. DEFAULT NaN\n\npd.Series.drop(self, index=None, **kwargs)  # return Series with specified index labels removed\n# INPLACE: {bool} -- if true do operation in place and return None -- DEFAULT False\n# ERRORS: {ignore, raise} -- If \"ignore\", suppress error and existing labels are dropped\n# KeyError raised if not all of the labels are found in the selected axis\n\npd.Series.value_counts(self, normalize=False, sort=True, ascending=False, bins=None, dropna=True)\n# NORMALIZE: {bool} -- if True then object returned will contain relative frequencies of unique values\n# SORT: {bool} -- sort by frequency -- DEFAULT True\n# ASCENDING: {bool} -- sort in ascending order -- DEFAULT False\n# BINS: {int} -- group values into half-open bins, only works with numeric data\n# DROPNA: {bool} -- don't include counts of NaN\n
"},{"location":"languages/python/libs/pandas.html#dataframe","title":"DATAFRAME","text":"

2-dimensional labeled data structure with columns of potentially different types. Index and columns can contain repetitions.

Python
df = DataFrame(data, index=row_labels, columns=column_labels)\n# DATA: {list, dict (of lists), nested dicts, series, dict of 1D ndarray, 2D ndarray, DataFrame}\n# INDEX: {list of row_labels}\n# COLUMNS: {list of column_labels}\n# outer dict keys interpreted as index labels, inner dict keys interpreted as column labels\n# INDEXING / SELECTION / SLICING\ndf[col]  # column selection\ndf.at[row, col]  # access a single value for a row/column label pair\ndf.iat[row, col]  # access a single value for a row/column pair by integer position\n\ndf.column_label  # column selection\n\ndf.loc[label]  # row selection by label\ndf.iloc[loc]  # row selection by integer location\n\ndf[ : ]  # slice rows\ndf[bool_vec]  # slice rows by boolean vector\ndf[condition]  # slice rows by condition\n\ndf.loc[:, [\"column_1\", \"column_2\"]]  # slice columns by names\ndf.loc[:, [bool_vector]]  # slice columns by names\n\ndf[col] = *value  # modify column contents, if colon is missing it will be created\ndf[ : ] = *value # modify rows contents\ndf[condition] = *value  # modify contents\n\ndel df[col]  # delete column\n
"},{"location":"languages/python/libs/pandas.html#dataframe-attributes","title":"DATAFRAME ATTRIBUTES","text":"Python
df.index  # row labels\ndf.columns  # column labels\ndf.values  # NumPy representation of DataFrame\ndf.index.name = \"index name\"\ndf.columns.index.name = \"columns name\"\ndf.T # transpose\n
"},{"location":"languages/python/libs/pandas.html#dataframe-methods","title":"DATAFRAME METHODS","text":"Python
pd.DataFrame.isin(self , values)  # boolean DataFrame showing whether elements in DataFrame matches elements in values exactly\n\n# Conform DataFrame to new index, new object produced unless the new index is equivalent to current one and copy=False\npd.DataFrame.reindex(self, index=None, columns=None, **kwargs)\n# INDEX: {array} -- new labels / index\n# COLUMNS: {array} -- new labels / columns\n# METHOD: {none (don't fill gaps), pad (fill or carry values forward), backfill (fill or carry values backward)}-- hole filling method\n# COPY: {bool} -- return new object even if index is same -- DEFAULT True\n# FILLVALUE: {scalar} --value to use for missing values. DEFAULT NaN\n\npd.DataFrame.drop(self, index=None, columns=None, **kwargs)  # Remove rows or columns by specifying label names\n# INPLACE: {bool} -- if true do operation in place and return None -- DEFAULT False\n# ERRORS: {ignore, raise} -- If \"ignore\", suppress error and existing labels are dropped\n# KeyError raised if not all of the labels are found in the selected axis\n
"},{"location":"languages/python/libs/pandas.html#index-objects","title":"INDEX OBJECTS","text":"

Holds axis labels and metadata, immutable.

"},{"location":"languages/python/libs/pandas.html#index-types","title":"INDEX TYPES","text":"Python
pd.Index  # immutable ordered ndarray, sliceable. stores axis labels\npd.Int64Index  # special case of Index with purely integer labels\npd.MultiIndex  # multi-level (hierarchical) index object for pandas objects\npd.PeriodINdex  # immutable ndarray holding ordinal values indicating regular periods in time\npd.DatetimeIndex  # nanosecond timestamps (uses Numpy datetime64)\n
"},{"location":"languages/python/libs/pandas.html#index-attributers","title":"INDEX ATTRIBUTERS","text":"Python
pd.Index.is_monotonic_increasing  # Return True if the index is monotonic increasing (only equal or increasing) values\npd.Index.is_monotonic_decreasing  # Return True if the index is monotonic decreasing (only equal or decreasing) values\npd.Index.is_unique  # Return True if the index has unique values.\npd.Index.hasnans  # Return True if the index has NaNs\n
"},{"location":"languages/python/libs/pandas.html#index-methods","title":"INDEX METHODS","text":"Python
pd.Index.append(self, other)  # append a collection of Index options together\n\npd.Index.difference(self, other, sort=None)  # set difference of two Index objects\n# SORT: {None (attempt sorting), False (don't sort)}\n\npd.Index.intersection(self, other, sort=None)  # set intersection of two Index objects\n# SORT: {None (attempt sorting), False (don't sort)}\n\npd.Index.union(self, other, sort=None)  # set union of two Index objects\n# SORT: {None (attempt sorting), False (don't sort)}\n\npd.Index.isin(self, values, level=None)  # boolean array indicating where the index values are in values\npd.Index.insert(self, loc, item)  # make new Index inserting new item at location\npd.Index.delete(self, loc)  # make new Index with passed location(-s) deleted\n\npd.Index.drop(self, labels, errors='raise')  # Make new Index with passed list of labels deleted\n# ERRORS: {ignore, raise} -- If 'ignore', suppress error and existing labels are dropped\n# KeyError raised if not all of the labels are found in the selected axis\n\npd.Index.reindex(self, target, **kwargs)  # create index with target's values (move/add/delete values as necessary)\n# METHOD: {none (don't fill gaps), pad (fill or carry values forward), backfill (fill or carry values backward)}-- hole filling method\n
"},{"location":"languages/python/libs/pandas.html#arithmetic-operations","title":"ARITHMETIC OPERATIONS","text":"

NumPy arrays operations preserve labels-value link. Arithmetic operations automatically align differently indexed data. Missing values propagate in arithmetic computations (NaN <operator> value = NaN)

"},{"location":"languages/python/libs/pandas.html#addition","title":"ADDITION","text":"Python
self + other\npd.Series.add(self, other, fill_value=None)  # add(), supports substitution of NaNs\npd,Series.radd(self, other, fill_value=None)  # radd(), supports substitution of NaNs\npd.DataFrame.add(self, other, axis=columns, fill_value=None)  # add(), supports substitution of NaNs\npd.DataFrame.radd(self, other, axis=columns, fill_value=None)  # radd(), supports substitution of NaNs\n# OTHER: {scalar, sequence, Series, DataFrame}\n# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns\n# FILLVALUE: {None, float} -- fill missing value\n
"},{"location":"languages/python/libs/pandas.html#subtraction","title":"SUBTRACTION","text":"Python
self - other\npd.Series.sub(self, other, fill_value=None)  # sub(), supports substitution of NaNs\npd.Series.radd(self, other, fill_value=None)  # radd(), supports substitution of NaNs\nps.DataFrame.sub(self, other, axis=columns, fill_value=None)  # sub(), supports substitution of NaNs\npd.DataFrame.rsub(self, other, axis=columns, fill_value=None)  # rsub(), supports substitution of NaNs\n# OTHER: {scalar, sequence, Series, DataFrame}\n# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns\n# FILLVALUE: {None, float} -- fill missing value\n
"},{"location":"languages/python/libs/pandas.html#multiplication","title":"MULTIPLICATION","text":"Python
self * other\npd.Series.mul(self, other, fill_value=None)  # mul(), supports substitution of NaNs\npd.Series.rmul(self, other, fill_value=None)  # rmul(), supports substitution of NaNs\nps.DataFrame.mul(self, other, axis=columns, fill_value=None)  # mul(), supports substitution of NaNs\npd.DataFrame.rmul(self, other, axis=columns, fill_value=None)  # rmul(), supports substitution of NaNs\n# OTHER: {scalar, sequence, Series, DataFrame}\n# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns\n# FILLVALUE: {None, float} -- fill missing value\n
"},{"location":"languages/python/libs/pandas.html#division-float-division","title":"DIVISION (float division)","text":"Python
self / other\npd.Series.div(self, other, fill_value=None)  # div(), supports substitution of NaNs\npd.Series.rdiv(self, other, fill_value=None)  # rdiv(), supports substitution of NaNs\npd.Series.truediv(self, other, fill_value=None)  # truediv(), supports substitution of NaNs\npd.Series.rtruediv(self, other, fill_value=None)  # rtruediv(), supports substitution of NaNs\nps.DataFrame.div(self, other, axis=columns, fill_value=None)  # div(), supports substitution of NaNs\npd.DataFrame.rdiv(self, other, axis=columns, fill_value=None)  # rdiv(), supports substitution of NaNs\nps.DataFrame.truediv(self, other, axis=columns, fill_value=None)  # truediv(), supports substitution of NaNs\npd.DataFrame.rtruediv(self, other, axis=columns, fill_value=None)  # rtruediv(), supports substitution of NaNs\n# OTHER: {scalar, sequence, Series, DataFrame}\n# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns\n# FILLVALUE: {None, float} -- fill missing value\n
"},{"location":"languages/python/libs/pandas.html#floor-division","title":"FLOOR DIVISION","text":"Python
self // other\npd.Series.floordiv(self, other, fill_value=None)  # floordiv(), supports substitution of NaNs\npd.Series.rfloordiv(self, other, fill_value=None)  # rfloordiv(), supports substitution of NaNs\nps.DataFrame.floordiv(self, other, axis=columns, fill_value=None)  # floordiv(), supports substitution of NaNs\npd.DataFrame.rfloordiv(self, other, axis=columns, fill_value=None)  # rfloordiv(), supports substitution of NaNs\n# OTHER: {scalar, sequence, Series, DataFrame}\n# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns\n# FILLVALUE: {None, float} -- fill missing value\n
"},{"location":"languages/python/libs/pandas.html#modulo","title":"MODULO","text":"Python
self % other\npd.Series.mod(self, other, fill_value=None)  # mod(), supports substitution of NaNs\npd.Series.rmod(self, other, fill_value=None)  # rmod(), supports substitution of NaNs\nps.DataFrame.mod(self, other, axis=columns, fill_value=None)  # mod(), supports substitution of NaNs\npd.DataFrame.rmod(self, other, axis=columns, fill_value=None)  # rmod(), supports substitution of NaNs\n# OTHER: {scalar, sequence, Series, DataFrame}\n# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns\n# FILLVALUE: {None, float} -- fill missing value\n
"},{"location":"languages/python/libs/pandas.html#power","title":"POWER","text":"Python
other ** self\npd.Series.pow(self, other, fill_value=None)  # pow(), supports substitution of NaNs\npd.Series.rpow(self, other, fill_value=None)  # rpow(), supports substitution of NaNs\nps.DataFrame.pow(self, other, axis=columns, fill_value=None)  # pow(), supports substitution of NaNs\npd.DataFrame.rpow(self, other, axis=columns, fill_value=None)  # rpow(), supports substitution of NaNs\n# OTHER: {scalar, sequence, Series, DataFrame}\n# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns\n# FILLVALUE: {None, float} -- fill missing value\n
"},{"location":"languages/python/libs/pandas.html#essential-functionality","title":"ESSENTIAL FUNCTIONALITY","text":""},{"location":"languages/python/libs/pandas.html#function-application-and-mapping","title":"FUNCTION APPLICATION AND MAPPING","text":"

NumPy ufuncs work fine with pandas objects.

Python
pd.DataFrame.applymap(self, func)  # apply function element-wise\n\npd.DataFrame.apply(self, func, axis=0, args=())  # apply a function along an axis of a DataFrame\n# FUNC: {function} -- function to apply\n# AXIS: {O, 1, index, columns} -- axis along which the function is applied\n# ARGS: {tuple} -- positional arguments to pass to func in addition to the array/series\n# SORTING AND RANKING\npd.Series.sort_index(self, ascending=True **kwargs)  # sort Series by index labels\npd.Series.sort_values(self, ascending=True, **kwargs)  # sort series by the values\n# ASCENDING: {bool} -- if True, sort values in ascending order, otherwise descending -- DEFAULT True\n# INPALCE: {bool} -- if True, perform operation in-place\n# KIND: {quicksort, mergesort, heapsort} -- sorting algorithm\n# NA_POSITION {first, last} -- 'first' puts NaNs at the beginning, 'last' puts NaNs at the end\n\npd.DataFrame.sort_index(self, axis=0, ascending=True, **kwargs)  # sort object by labels along an axis\npd.DataFrame.sort_values(self, axis=0, ascending=True, **kwargs)  # sort object by values along an axis\n# AXIS: {0, 1, index, columns} -- the axis along which to sort\n# ASCENDING: {bool} -- if True, sort values in ascending order, otherwise descending -- DEFAULT True\n# INPALCE: {bool} -- if True, perform operation in-place\n# KIND: {quicksort, mergesort, heapsort} -- sorting algorithm\n# NA_POSITION {first, last} -- 'first' puts NaNs at the beginning, 'last' puts NaNs at the end\n
"},{"location":"languages/python/libs/pandas.html#descriptive-and-summary-statistics","title":"DESCRIPTIVE AND SUMMARY STATISTICS","text":""},{"location":"languages/python/libs/pandas.html#count","title":"COUNT","text":"Python
pd.Series.count(self)  # return number of non-NA/null observations in the Series\npd.DataFrame.count(self, numeric_only=False)  # count non-NA cells for each column or row\n# NUMERIC_ONLY: {bool} -- Include only float, int or boolean data -- DEFAULT False\n
"},{"location":"languages/python/libs/pandas.html#describe","title":"DESCRIBE","text":"

Generate descriptive statistics summarizing central tendency, dispersion and shape of dataset's distribution (exclude NaN).

Python
pd.Series.describe(self, percentiles=None, include=None, exclude=None)\npd.DataFrame.describe(self, percentiles=None, include=None, exclude=None)\n# PERCENTILES: {list-like of numbers} -- percentiles to include in output,between 0 and 1 -- DEFAULT [.25, .5, .75]\n# INCLUDE: {all, None, list of dtypes} -- white list of dtypes to include in the result. ignored for Series\n# EXCLUDE: {None, list of dtypes} -- black list of dtypes to omit from the result. ignored for Series\n
"},{"location":"languages/python/libs/pandas.html#max-min","title":"MAX - MIN","text":"Python
pd.Series.max(self, skipna=None, numeric_only=None)  # maximum of the values for the requested axis\npd.Series.min(self, skipna=None, numeric_only=None)  # minimum of the values for the requested axis\npd.DataFrame.max(self, axis=None, skipna=None, numeric_only=None)  # maximum of the values for the requested axis\npd.DataFrame.min(self, axis=None, skipna=None, numeric_only=None)  # minimum of the values for the requested axis\n# SKIPNA: {bool} -- exclude NA/null values when computing the result\n# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series\n
"},{"location":"languages/python/libs/pandas.html#idxmax-idxmin","title":"IDXMAX - IDXMIN","text":"Python
pd.Series.idxmax(self, skipna=True)  # row label of the maximum value\npd.Series.idxmin(self, skipna=True)  # row label of the minimum value\npd.DataFrame.idxmax(self, axis=0, skipna=True)  #  Return index of first occurrence of maximum over requested axis\npd.DataFrame.idxmin(self, axis=0, skipna=True)  #  Return index of first occurrence of minimum over requested axis\n# AXIS:{0, 1, index, columns} -- row-wise or column-wise\n# SKIPNA: {bool} -- exclude NA/null values. ff an entire row/column is NA, result will be NA\n
"},{"location":"languages/python/libs/pandas.html#quantile","title":"QUANTILE","text":"Python
pd.Series.quantile(self, q=0.5, interpolation='linear')  # return values at the given quantile\npd.DataFrame.quantile(self, q=0.5, axis=0, numeric_only=True, interpolation='linear') # return values at the given quantile over requested axis\n# Q: {flaot, array} -- value between 0 <= q <= 1, the quantile(s) to compute -- DEFAULT 0.5 (50%)\n# NUMERIC_ONLY: {bool} -- if False, quantile of datetime and timedelta data will be computed as well\n# INTERPOLATION: {linear, lower, higher, midpoint, nearest} -- SEE DOCS\n
"},{"location":"languages/python/libs/pandas.html#sum","title":"SUM","text":"Python
pd.Series.sum(self, skipna=None, numeric_only=None, min_count=0)  # sum of the values\npd.DataFrame.sum(self, axis=None, skipna=None, numeric_only=None, min_count=0)  # sum of the values for the requested axis\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values when computing the result\n# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series\n# MIN_COUNT: {int} -- required number of valid values to perform the operation. if fewer than min_count non-NA values are present the result will be NA\n
"},{"location":"languages/python/libs/pandas.html#mean","title":"MEAN","text":"Python
pd.Series.mean(self, skipna=None, numeric_only=None)   # mean of the values\npd.DataFrame.mean(self, axis=None, skipna=None, numeric_only=None)  # mean of the values for the requested axis\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values when computing the result\n# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series\n
"},{"location":"languages/python/libs/pandas.html#median","title":"MEDIAN","text":"Python
pd.Series.median(self, skipna=None, numeric_only=None)  # median of the values\npd.DataFrame.median(self, axis=None, skipna=None, numeric_only=None)  # median of the values for the requested axis\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values when computing the result\n# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series\n
"},{"location":"languages/python/libs/pandas.html#mad-mean-absolute-deviation","title":"MAD (mean absolute deviation)","text":"Python
pd.Series.mad(self, skipna=None)  # mean absolute deviation\npd.DataFrame.mad(self, axis=None, skipna=None)  # mean absolute deviation of the values for the requested axis\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values when computing the result\n
"},{"location":"languages/python/libs/pandas.html#var-variance","title":"VAR (variance)","text":"Python
pd.Series.var(self, skipna=None, numeric_only=None)  # unbiased variance\npd.DataFrame.var(self, axis=None, skipna=None, ddof=1, numeric_only=None)  #  unbiased variance over requested axis\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values. if an entire row/column is NA, the result will be NA\n# DDOF: {int} -- Delta Degrees of Freedom. divisor used in calculations is N - ddof (N represents the number of elements) -- DEFAULT 1\n# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series\n
"},{"location":"languages/python/libs/pandas.html#std-standard-deviation","title":"STD (standard deviation)","text":"Python
pd.Series.std(self, skipna=None, ddof=1, numeric_only=None)  # sample standard deviation\npd.Dataframe.std(self, axis=None, skipna=None, ddof=1, numeric_only=None)  # sample standard deviation over requested axis\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values. if an entire row/column is NA, the result will be NA\n# DDOF: {int} -- Delta Degrees of Freedom. divisor used in calculations is N - ddof (N represents the number of elements) -- DEFAULT 1\n# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series\n
"},{"location":"languages/python/libs/pandas.html#skew","title":"SKEW","text":"Python
pd.Series.skew(self, skipna=None, numeric_only=None)  # unbiased skew Normalized bt N-1\npd.DataFrame.skew(self, axis=None, skipna=None, numeric_only=None)  #  unbiased skew over requested axis Normalized by N-1\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values when computing the result\n# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series\n
"},{"location":"languages/python/libs/pandas.html#kurt","title":"KURT","text":"

Unbiased kurtosis over requested axis using Fisher's definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1.

Python
pd.Series.kurt(self, skipna=None, numeric_only=None)\npd.Dataframe.kurt(self, axis=None, skipna=None, numeric_only=None)\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values when computing the result\n# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series\n
"},{"location":"languages/python/libs/pandas.html#cumsum-cumulative-sum","title":"CUMSUM (cumulative sum)","text":"Python
pd.Series.cumsum(self, skipna=True)  # cumulative sum\npd.Dataframe.cumsum(self, axis=None, skipna=True)  # cumulative sum over requested axis\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values. if an entire row/column is NA, the result will be NA\n
"},{"location":"languages/python/libs/pandas.html#cummax-cummin-cumulative-maximum-minimum","title":"CUMMAX - CUMMIN (cumulative maximum - minimum)","text":"Python
pd.Series.cummax(self, skipna=True)  # cumulative maximum\npd.Series.cummin(self, skipna=True)  # cumulative minimum\npd.Dataframe.cummax(self, axis=None, skipna=True)  # cumulative maximum over requested axis\npd.Dataframe.cummin(self, axis=None, skipna=True)  # cumulative minimum over requested axis\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values. if an entire row/column is NA, the result will be NA\n
"},{"location":"languages/python/libs/pandas.html#cumprod-cumulative-product","title":"CUMPROD (cumulative product)","text":"Python
pd.Series.cumprod(self, skipna=True)  # cumulative product\npd.Dataframe.cumprod(self, axis=None, skipna=True)  # cumulative product over requested axis\n# AXIS: {0, 1, index, columns} -- axis for the function to be applied on\n# SKIPNA: {bool} -- exclude NA/null values. if an entire row/column is NA, the result will be NA\n
"},{"location":"languages/python/libs/pandas.html#diff","title":"DIFF","text":"

Calculates the difference of a DataFrame element compared with another element in the DataFrame. (default is the element in the same column of the previous row)

Python
pd.Series.diff(self, periods=1)\npd.DataFrame.diff(self, periods=1, axis=0)\n# PERIODS: {int} -- Periods to shift for calculating difference, accepts negative values -- DEFAULT 1\n# AXIS: {0, 1, index, columns} -- Take difference over rows or columns\n
"},{"location":"languages/python/libs/pandas.html#pct_change","title":"PCT_CHANGE","text":"

Percentage change between the current and a prior element.

Python
pd.Series.Pct_change(self, periods=1, fill_method='pad', limit=None, freq=None)\npd.Dataframe.pct_change(self, periods=1, fill_method='pad', limit=None)\n# PERIODS:{int} -- periods to shift for forming percent change\n# FILL_METHOD: {str, pda} -- How to handle NAs before computing percent changes -- DEFAULT pad\n# LIMIT: {int} -- number of consecutive NAs to fill before stopping -- DEFAULT None\n
"},{"location":"languages/python/libs/pandas.html#handling-missing-data","title":"HANDLING MISSING DATA","text":""},{"location":"languages/python/libs/pandas.html#filtering-out-missing-data","title":"FILTERING OUT MISSING DATA","text":"Python
pd.Series.dropna(self, inplace=False)  # return a new Series with missing values removed\npd.DataFrame.dropna(axis=0, how='any', tresh=None, subset=None, inplace=False)  # return a new DataFrame with missing values removed\n# AXIS: {tuple, list} -- tuple or list to drop on multiple axes. only a single axis is allowed\n# HOW: {any, all} -- determine if row or column is removed from DataFrame (ANY = if any NA present, ALL = if all values are NA). DEFAULT any\n# TRESH: {int} -- require that many non-NA values\n# SUBSET: {array} -- labels along other axis to consider\n# INPLACE: {bool} -- if True, do operation inplace and return None -- DEFAULT False\n
"},{"location":"languages/python/libs/pandas.html#filling-in-missing-data","title":"FILLING IN MISSING DATA","text":"

Fill NA/NaN values using the specified method.

Python
pd.Series.fillna(self, value=None, method=None, inplace=False, limit=None)\npd.DataFrame.fillna(self, value=None, method=None, axis=None, inplace=False, limit=None)\n# VALUE: {scalar, dict, Series, DataFrame} -- value to use to fill holes, dict/Series/DataFrame specifying which value to use for each index or column\n# METHOD: {backfill, pad, None} -- method to use for filling holes -- DEFAULT None\n# AXIS: {0, 1, index, columns} -- axis along which to fill missing values\n# INPLACE: {bool} -- if true fill in-place (will modify views of object) -- DEFAULT False\n# LIMIT: {int} --  maximum number of consecutive NaN values to forward/backward fill -- DEFAULT None\n
"},{"location":"languages/python/libs/pandas.html#hierarchical-indexing-multiindex","title":"HIERARCHICAL INDEXING (MultiIndex)","text":"

Enables storing and manipulation of data with an arbitrary number of dimensions. In lower dimensional data structures like Series (1d) and DataFrame (2d).

"},{"location":"languages/python/libs/pandas.html#multiiindex-creation","title":"MULTIIINDEX CREATION","text":"Python
pd.MultiIndex.from_arrays(*arrays, names=None)  # convert arrays to MultiIndex\npd.MultiIndex.from_tuples(*arrays, names=None)  # convert tuples to MultiIndex\npd.MultiIndex.from_frame(df, names=None)  # convert DataFrame to MultiIndex\npd.MultiIndex.from_product(*iterables, names=None)     #  MultiIndex from cartesian product of iterables\npd.Series(*arrays)  # Index constructor makes MultiIndex from Series\npd.DataFrame(*arrays)  # Index constructor makes MultiINdex from DataFrame\n
"},{"location":"languages/python/libs/pandas.html#multiindex-levels","title":"MULTIINDEX LEVELS","text":"

Vector of label values for requested level, equal to the length of the index.

Python
pd.MultiIndex.get_level_values(self, level)\n
"},{"location":"languages/python/libs/pandas.html#partial-and-cross-section-selection","title":"PARTIAL AND CROSS-SECTION SELECTION","text":"

Partial selection \"drops\" levels of the hierarchical index in the result in a completely analogous way to selecting a column in a regular DataFrame.

Python
pd.Series.xs(self, key, axis=0, level=None, drop_level=True)  # cross-section from Series\npd.DataFrame.xs(self, key, axis=0, level=None, drop_level=True)  #  cross-section from DataFrame\n# KEY: {label, tuple of label} -- label contained in the index, or partially in a MultiIndex\n# AXIS: {0, 1, index, columns} -- axis to retrieve cross-section on -- DEFAULT 0\n# LEVEL: -- in case of key partially contained in MultiIndex, indicate which levels are used. Levels referred by label or position\n# DROP_LEVEL: {bool} -- If False, returns object with same levels as self -- DEFAULT True\n
"},{"location":"languages/python/libs/pandas.html#indexing-slicing","title":"INDEXING, SLICING","text":"

Multi index keys take the form of tuples.

Python
df.loc[('lvl_1', 'lvl_2', ...)]  # selection of single row\ndf.loc[('idx_lvl_1', 'idx_lvl_2', ...), ('col_lvl_1', 'col_lvl_2', ...)]  # selection of single value\n\ndf.loc['idx_lvl_1':'idx_lvl_1']  # slice of rows (aka partial selection)\ndf.loc[('idx_lvl_1', 'idx_lvl_2') : ('idx_lvl_1', 'idx_lvl_2')]  # slice of rows with levels\n
"},{"location":"languages/python/libs/pandas.html#reordering-and-sorting-levels","title":"REORDERING AND SORTING LEVELS","text":"Python
pd.MultiIndex.swaplevel(self, i=-2, j=-1)  # swap level i with level j\npd.Series.swaplevel(self, i=-2, j=-1) # swap levels i and j in a MultiIndex\npd.DataFrame.swaplevel(self, i=-2, j=-1, axis=0) # swap levels i and j in a MultiIndex on a partivular axis\n\npd.MultiIndex.sortlevel(self, level=0, ascending=True, sort_remaining=True)  # sort MultiIndex at requested level\n# LEVEL: {str, int, list-like} -- DEFAULT 0\n# ASCENDING: {bool} -- if True, sort values in ascending order, otherwise descending -- DEFAULT True\n# SORT_REMAINING: {bool} -- sort by the remaining levels after level\n
"},{"location":"languages/python/libs/pandas.html#data-loading-storage-file-formats","title":"DATA LOADING, STORAGE FILE FORMATS","text":"Python
pd.read_fwf(filepath, colspecs='infer', widths=None, infer_nrows=100)  # read a table of fixed-width formatted lines into DataFrame\n# FILEPATH: {str, path object} -- any valid string path is acceptable, could be a URL. Valid URLs: http, ftp, s3, and file\n# COLSPECS: {list of tuple (int, int), 'infer'} -- list of tuples giving extents of fixed-width fields of each line as half-open intervals { [from, to) }\n# WIDTHS: {list of int} -- list of field widths which can be used instead of \"colspecs\" if intervals are contiguous\n# INFER_ROWS: {int} -- number of rows to consider when letting parser determine colspecs -- DEFAULT 100\n\npd.read_excel()  # read an Excel file into a pandas DataFrame\npd.read_json()  # convert a JSON string to pandas object\npd.read_html()  # read HTML tables into a list of DataFrame objects\npd.read_sql()  # read SQL query or database table into a DataFrame\n\npd.read_csv(filepath, sep=',', *args, **kwargs )  # read a comma-separated values (csv) file into DataFrame\npd.read_table(filepath, sep='\\t', *args, **kwargs)  # read general delimited file into DataFrame\n# FILEPATH: {str, path object} -- any valid string path is acceptable, could be a URL. Valid URLs: http, ftp, s3, and file\n# SEP: {str} -- delimiter to use -- DEFAULT \\t (tab)\n# HEADER {int, list of int, 'infer'} -- row numbers to use as column names, and the start of the data -- DEFAULT 'infer'\n# NAMES:{array} -- list of column names to use -- DEFAULT None\n# INDEX_COL: {int, str, False, sequnce of int/str, None} -- Columns to use as row labels of DataFrame, given as string name or column index -- DEFAULT None\n# SKIPROWS: {list-like, int, callable} -- Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file\n# NA_VALUES: {scalar, str, list-like, dict} -- additional strings to recognize as NA/NaN. if dict passed, specific per-column NA values\n# THOUSANDS: {str} -- thousand separator\n# *ARGS, **KWARGS -- SEE DOCS\n\n# write object to a comma-separated values (csv) file\npd.DataFrame.to_csv(self, path_or_buf, sep=',', na_rep='', columns=None, header=True, index=True, encoding='utf-8', line_terminator=None, decimal='.', *args, **kwargs)\n# SEP: {str len 1} --  Field delimiter for the output file\n# NA_REP: {str} -- missing data representation\n# COLUMNS: {sequence} -- colums to write\n# HEADER: {bool, list of str} -- write out column names. if list of strings is given its assumed to be aliases for column names\n# INDEX: {bool, list of str} -- write out row names (index)\n# ENCODING: {str} -- string representing encoding to use -- DEFAULT \"utf-8\"\n# LINE_TERMINATOR: {str} -- newline character or character sequence to use in the output file -- DEFAULT os.linesep\n# DECIMAL: {str} -- character recognized as decimal separator (in EU ,)\n\npd.DataFrame.to_excel()\npd.DataFrame.to_json()\npd.DataFrame.to_html()\npd.DataFrame.to_sql()\n
"},{"location":"languages/python/libs/requests.html","title":"Requests Lib","text":""},{"location":"languages/python/libs/requests.html#get-request","title":"GET REQUEST","text":"

Get or retrieve data from specified resource

Python
response = requests.get('URL')    # returns response object\n\n# PAYLOAD -> valuable information of response\nresponse.status_code    # http status code\n

The response message consists of:

Text Only
1xx -> INFORMATIONAL RESPONSE\n2xx -> SUCCESS\n    200 OK -> request successful\n3xx -> REDIRECTION\n4xx -> CLIENT ERRORS\n    404 NOT FOUND -> resource not found\n5xx -> SERVER ERRORS\n
Python
# raise exception HTTPError for error status codes\nresponse.raise_for_status()\n\nresponse.content    # raw bytes of payload\nresponse.encoding = 'utf-8'    # specify encoding\nresponse.text    # string payload (serialized JSON)\nresponse.json()    # dict of payload\nresponse.headers    # response headers (dict)\n
"},{"location":"languages/python/libs/requests.html#query-string-parameters","title":"QUERY STRING PARAMETERS","text":"Python
response = requests.get('URL', params={'q':'query'})\nresponse = requests.get('URL', params=[('q', 'query')])\nresponse = requests.get('URL', params=b'q=query')\n
"},{"location":"languages/python/libs/requests.html#request-headers","title":"REQUEST HEADERS","text":"Python
response = requests.get(\n    'URL',\n    params={'q': 'query'},\n    headers={'header': 'header_query'}\n)\n
"},{"location":"languages/python/libs/requests.html#other-http-methods","title":"OTHER HTTP METHODS","text":""},{"location":"languages/python/libs/requests.html#data-input","title":"DATA INPUT","text":"Python
# requests that entity enclosed be stored as a new subordinate of the web resource identified by the URI\nrequests.post('URL', data={'key':'value'})\n# requests that the enclosed entity be stored under the supplied URI\nrequests.put('URL', data={'key':'value'})\n# applies partial modification\nrequests.patch('URL', data={'key':'value'})\n# deletes specified resource\nrequests.delete('URL')\n# ask for a response but without the response body (only headers)\nrequests.head('URL')\n# returns supported HTTP methods of the server\nrequests.options('URL')\n
"},{"location":"languages/python/libs/requests.html#sending-json-data","title":"SENDING JSON DATA","text":"Python
requests.post('URL', json={'key': 'value'})\n
"},{"location":"languages/python/libs/requests.html#inspecting-the-request","title":"INSPECTING THE REQUEST","text":"Python
# requests lib prepares the requests before sending it\nresponse = requests.post('URL', data={'key':'value'})\nresponse.request.something    # inspect request field\n
"},{"location":"languages/python/libs/requests.html#authentication","title":"AUTHENTICATION","text":"Python
requests.get('URL', auth=('username', 'password'))    # use implicit HTTP Basic Authorization\n\n# explicit HTTP Basic Authorization and other\nfrom requests.auth import HTTPBasicAuth, HTTPDigestAuth, HTTPProxyAuth\nfrom getpass import getpass\nrequests.get('URL', auth=HTTPBasicAuth('username', getpass()))\n
"},{"location":"languages/python/libs/requests.html#personalized-auth","title":"PERSONALIZED AUTH","text":"Python
from requests.auth import AuthBase\nclass TokenAuth(AuthBase):\n    \"custom authentication scheme\"\n\n    def __init__(self, token):\n        self.token = token\n\n    def __call__(self, r):\n        \"\"\"Attach API token to custom auth\"\"\"\n        r.headers['X-TokenAuth'] = f'{self.token}'\n        return r\n\nrequests.get('URL', auth=TokenAuth('1234abcde-token'))\n
"},{"location":"languages/python/libs/requests.html#disabling-ssl-verification","title":"DISABLING SSL VERIFICATION","text":"Python
requests.get('URL', verify=False)\n
"},{"location":"languages/python/libs/requests.html#performance","title":"PERFORMANCE","text":""},{"location":"languages/python/libs/requests.html#request-timeout","title":"REQUEST TIMEOUT","text":"Python
# raise Timeout exception if request times out\nrequests.get('URL', timeout=(connection_timeout, read_timeout))\n
"},{"location":"languages/python/libs/requests.html#max-retries","title":"MAX RETRIES","text":"Python
from requests.adapters import HTTPAdapter\nURL_adapter = HTTPAdapter(max_retries = int)\nsession = requests.Session()\n\n# use URL_adapter for all requests to URL\nsession.mount('URL', URL_adapter)\n
"},{"location":"languages/python/libs/seaborn.html","title":"Seaborn Lib","text":""},{"location":"languages/python/libs/seaborn.html#basic-imports-for-seaborn","title":"Basic Imports For Seaborn","text":"Python
import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# set aesthetic parameters in one step\nsns.set(style='darkgrid')\n#STYLE: {None, darkgrid, whitegrid, dark, white, ticks}\n
"},{"location":"languages/python/libs/seaborn.html#replot-relationship","title":"REPLOT (relationship)","text":"Python
sns.replot(x='name_in_data', y='name_in_data', hue='point_color', size='point_size', style='point_shape', data=data)\n# HUE, SIZE and STYLE: {name in data} -- used to differentiate points, a sort-of 3rd dimension\n# hue behaves differently if the data is categorical or numerical, numerical uses a color gradient\n# SORT: {False, True} -- avoid sorting data in function of x\n# CI: {None, sd} -- avoid computing confidence intervals or plot standard deviation\n# (aggregate multiple measurements at each x value by plotting the mean and the 95% confidence interval around the mean)\n# ESTIMATOR: {None} -- turn off aggregation of multiple observations\n# MARKERS: {True, False} -- evidenziate observations with dots\n# DASHES: {True, False} -- evidenziate observations with dashes\n# COL, ROW: {name in data}  -- categorical variables that will determine the grid of plots\n# COL_WRAP: {int} -- \"Wrap\" the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet.\n# SCATTERPLOT\n# depicts the joint distribution of two variables using a cloud of points\n# kind can be omitted since scatterplot is the default for replot\nsns.replot(kind='scatter')  # calls scatterplot()\nsns.scatterplot()  # underlying axis-level function of replot()\n
"},{"location":"languages/python/libs/seaborn.html#lineplot","title":"LINEPLOT","text":"

Using semantics in lineplot will determine the aggregation of data.

Python
sns.replot(ci=None, sort=bool, kind='line')\nsns.lineplot()  # underlying axis-level function of replot()\n
"},{"location":"languages/python/libs/seaborn.html#catplot-categorical","title":"CATPLOT (categorical)","text":"

Categorical: divided into discrete groups.

Python
sns.catplot(x='name_in_data', y='name_in_data', data=data)\n# HUE: {name in data} -- used to differenziate points, a sort-of 3rd dimension\n# COL, ROW: {name in data}  -- categorical variables that will determine the grid of plots\n# COL_WRAP: {int} -- \"Wrap\" the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet.\n# ORDER, HUE_ORDER: {list of strings} -- order of categorical levels of the plot\n# ROW_ORDER, COL_ORDER: {list of strings} -- order to organize the rows and/or columns of the grid in\n# ORIENT: {'v', 'h'} -- Orientation of the plot (can also swap x&y assignment)\n# COLOR: {matplotlib color} -- Color for all of the elements, or seed for a gradient palette\n# CATEGORICAL SCATTERPLOT - STRIPPLOT\n# adjust the positions of points on the categorical axis with a small amount of random \u201cjitter\u201d\nsns.catplot(kind='strip', jitter=float)\nsns.stripplot()\n# SIZE: {float}  -- Diameter of the markers, in points\n# JITTER: {False, float} -- magnitude of points jitter (distance from axis)\n
"},{"location":"languages/python/libs/seaborn.html#categorical-scatterplot-swarmplot","title":"CATEGORICAL SCATTERPLOT - SWARMPLOT","text":"

Adjusts the points along the categorical axis preventing overlap.

Python
sns.catplot(kind='swarm')\nsns.swarmplot()\n# SIZE: {float}  -- Diameter of the markers, in points\n# CATEGORICAL DISTRIBUTION - BOXPLOT\n# shows the three quartile values of the distribution along with extreme values\nsns.catplot(kind='box')\nsns.boxplot()\n# HUE: {name in data} -- box for each level of the semantic moved along the categorical axis so they don\u2019t overlap\n# DODGE: {bool} -- whether elements should be shifted along the categorical axis if hue is used\n
"},{"location":"languages/python/libs/seaborn.html#categorical-distribution-violinplot","title":"CATEGORICAL DISTRIBUTION - VIOLINPLOT","text":"

Combines a boxplot with the kernel density estimation procedure.

Python
sns.catplot(kind='violin')\nsns.violonplot()\n
"},{"location":"languages/python/libs/seaborn.html#categorical-distribution-boxenplot","title":"CATEGORICAL DISTRIBUTION - BOXENPLOT","text":"

Plot similar to boxplot but optimized for showing more information about the shape of the distribution. It is best suited for larger datasets.

Python
sns.catplot(kind='boxen')\nsns.boxenplot()\n
"},{"location":"languages/python/libs/seaborn.html#categorical-estimate-pointplot","title":"CATEGORICAL ESTIMATE - POINTPLOT","text":"

Show point estimates and confidence intervals using scatter plot glyphs.

Python
sns.catplot(kind='point')\nsns.pointplot()\n# CI: {float, sd} -- size of confidence intervals to draw around estimated values, sd -> standard deviation\n# MARKERS: {string, list of strings} --  markers to use for each of the hue levels\n# LINESTYLES: {string, list of strings} -- line styles to use for each of the hue levels\n# DODGE: {bool, float} -- amount to separate the points for each hue level along the categorical axis\n# JOIN: {bool} -- if True, lines will be drawn between point estimates at the same hue level\n# SCALE: {float} -- scale factor for the plot elements\n# ERRWIDTH: {float} -- thickness of error bar lines (and caps)\n# CAPSIZE: {float} -- width of the \"caps\" on error bars\n
"},{"location":"languages/python/libs/seaborn.html#categorical-estimate-barplot","title":"CATEGORICAL ESTIMATE - BARPLOT","text":"

Show point estimates and confidence intervals as rectangular bars.

Python
sns.catplot(kind='bar')\nsns.barplot()\n# CI: {float, sd} -- size of confidence intervals to draw around estimated values, sd -> standard deviation\n# ERRCOLOR: {matplotlib color} -- color for the lines that represent the confidence interval\n# ERRWIDTH: {float} -- thickness of error bar lines (and caps)\n# CAPSIZE: {float} -- width of the \"caps\" on error bars\n# DODGE: {bool} -- whether elements should be shifted along the categorical axis if hue is used\n
"},{"location":"languages/python/libs/seaborn.html#categorical-estimate-countplot","title":"CATEGORICAL ESTIMATE - COUNTPLOT","text":"

Show the counts of observations in each categorical bin using bars.

Python
sns.catplot(kind='count')\nsns.countplot()\n# DODGE: {bool} -- whether elements should be shifted along the categorical axis if hue is used\n
"},{"location":"languages/python/libs/seaborn.html#univariate-distributions","title":"UNIVARIATE DISTRIBUTIONS","text":""},{"location":"languages/python/libs/seaborn.html#distplot","title":"DISTPLOT","text":"

Flexibly plot a univariate distribution of observations

Python
# A: {series, 1d-array, list}\nsns.distplot(a=data)\n# BINS: {None, arg for matplotlib hist()} -- specification of hist bins, or None to use Freedman-Diaconis rule\n# HIST: {bool} - whether to plot a (normed) histogram\n# KDE: {bool} - whether to plot a gaussian kernel density estimate\n# HIST_KWD, KDE_KWD, RUG_KWD: {dict} -- keyword arguments for underlying plotting functions\n# COLOR: {matplotlib color} -- color to plot everything but the fitted curve in\n
"},{"location":"languages/python/libs/seaborn.html#rugplot","title":"RUGPLOT","text":"

Plot datapoints in an array as sticks on an axis.

Python
# A: {vector} -- 1D array of observations\nsns.rugplot(a=data) # -> axes obj with plot on it\n# HEIGHT: {scalar} --  height of ticks as proportion of the axis\n# AXIS: {'x', 'y'} -- axis to draw rugplot on\n# AX: {matplotlib axes} -- axes to draw plot into, otherwise grabs current axes\n
"},{"location":"languages/python/libs/seaborn.html#kdeplot","title":"KDEPLOT","text":"

Fit and plot a univariate or bivariate kernel density estimate.

Python
# DATA: {1D array-like} -- input data\nsns.kdeplot(data=data)\n# DATA2 {1D array-like} -- second input data. if present, a bivariate KDE will be estimated.\n# SHADE: {bool} -- if True, shade-in the area under KDE curve (or draw with filled contours is bivariate)\n
"},{"location":"languages/python/libs/seaborn.html#bivariate-distribution","title":"BIVARIATE DISTRIBUTION","text":""},{"location":"languages/python/libs/seaborn.html#jointplot","title":"JOINTPLOT","text":"

Draw a plot of two variables with bivariate and univariate graphs.

Python
# X, Y: {string, vector} -- data or names of variables in data\nsns.jointplot(x=data, y=data)\n# DATA:{pandas DataFrame} -- DataFrame when x and y are variable names\n# KIND: {'scatter', 'reg', 'resid', 'kde', 'hex'} -- kind of plot to draw\n# COLOR: {matplotlib color} -- color used for plot elements\n# HEIGHT: {numeric} -- size of figure (it will be square)\n# RATIO: {numeric} -- ratio of joint axes height to marginal axes height\n# SPACE: {numeric} -- space between the joint and marginal axes\n# JOINT_KWD, MARGINAL_KWD, ANNOT_KWD: {dict} -- additional keyword arguments for the plot components\n
"},{"location":"languages/python/libs/seaborn.html#pair-wise-relationisps-in-dataset","title":"PAIR-WISE RELATIONISPS IN DATASET","text":""},{"location":"languages/python/libs/seaborn.html#pairplot","title":"PAIRPLOT","text":"

Plot pairwise relationships in a dataset.

Python
# DATA: {pandas DataFrame} -- tidy (long-form) dataframe where each column is a variable and each row is an observation\nsns.pairplot(data=pd.DataFrame)\n# HUE: {string (variable name)} -- variable in data to map plot aspects to different colors\n# HUE_ORDER: {list of strings} -- order for the levels of the hue variable in the palette\n# VARS: {list of variable names} -- variables within data to use, otherwise every column with numeric datatype\n# X_VARS, Y_VARS: {list of variable names} -- variables within data to use separately for rows and columns of figure\n# KIND: {'scatter', 'reg'} -- kind of plot for the non-identity relationships\n# DIAG_KIND: {'auto', 'hist', 'kde'} -- Kind of plot for the diagonal subplots. default depends hue\n# MARKERS: {matplotlib marker or list}\n# HEIGHT:{scalar} -- height (in inches) of each facet\n# ASPECT: {scalar} -- aspect * height gives the width (in inches) of each facet\n
"},{"location":"languages/python/libs/tkinter.html","title":"Tkinter Module/Library","text":""},{"location":"languages/python/libs/tkinter.html#standard-imports","title":"Standard Imports","text":"Python
from tkinter import *  # import Python Tk Binding\nfrom tkinter import ttk  # import Themed Widgets\n
"},{"location":"languages/python/libs/tkinter.html#geometry-management","title":"GEOMETRY MANAGEMENT","text":"

Putting widgets on screen master widget \u2192 top-level window, frame slave widget \u2192 widgets contained in master widget geometry managers determine size and oder widget drawing properties

"},{"location":"languages/python/libs/tkinter.html#event-handling","title":"EVENT HANDLING","text":"

event loop receives events from the OS customizable events provide a callback as a widget configuration

Python
widget.bind('event', function)  # method to capture any event and than execute an arbitrary piece of code (generally a function or lambda)\n

VIRTUAL EVENT \u2192 hig level event generated by widget (listed in widget docs)

"},{"location":"languages/python/libs/tkinter.html#widgets","title":"WIDGETS","text":"

Widgets are objects and all things on screen. All widgets are children of a window.

Python
widget_name = tk_object(parent_window)  # widget is inserted into widget hierarchy\n
"},{"location":"languages/python/libs/tkinter.html#frame-widget","title":"FRAME WIDGET","text":"

Displays a single rectangle, used as container for other widgets

Python
frame = ttk.Frame(parent, width=None, height=None, borderwidth=num:int)\n# BORDERWIDTH: sets frame border width (default: 0)\n# width, height MUST be specified if frame is empty, otherwise determined by parent geometry manager\n
"},{"location":"languages/python/libs/tkinter.html#frame-padding","title":"FRAME PADDING","text":"

Extra space inside widget (margin).

Python
frame['padding'] = num  # same padding for every border\nframe['padding'] = (horizontal, vertical)  # set horizontal THEN vertical padding\nframe['padding'] = (left, top, right, bottom)  # set left, top, right, bottom padding\n\n# RELIEF: set border style, [flat (default), raised, sunken, solid, ridge, groove]\nframe['relief'] = border_style\n
"},{"location":"languages/python/libs/tkinter.html#label-widget","title":"LABEL WIDGET","text":"

Display text or image without interactivity.

Python
label = ttk.Label(parent, text='label text')\n
"},{"location":"languages/python/libs/tkinter.html#defining-updating-label","title":"DEFINING UPDATING LABEL","text":"Python
var = StringVar()  # variable containing text, watches for changes. Use get, set methods to interact with the value\nlabel['textvariable'] = var  # attach var to label (only of type StringVar)\nvar.set(\"new text label\")  #  change label text\n
"},{"location":"languages/python/libs/tkinter.html#display-images-2-steps","title":"DISPLAY IMAGES (2 steps)","text":"Python
image = PhotoImage(file='filename')  # create image object\nlabel['image'] = image  # use image config\n
"},{"location":"languages/python/libs/tkinter.html#display-image-and-or-text","title":"DISPLAY IMAGE AND-OR TEXT","text":"Python
label['compound'] = value\n

Compound value:

"},{"location":"languages/python/libs/tkinter.html#layout","title":"LAYOUT","text":"

Specifies edge or corner that the label is attached.

Python
label['anchor'] = compass_direction  #compass_direction: n, ne, e, se, s, sw, w, nw, center\n
"},{"location":"languages/python/libs/tkinter.html#multi-line-text-wrap","title":"MULTI-LINE TEXT WRAP","text":"Python
# use \\n for multi line text\nlabel['wraplength'] = size  # max line length\n
"},{"location":"languages/python/libs/tkinter.html#control-text-justification","title":"CONTROL TEXT JUSTIFICATION","text":"Python
label['justify'] = value  #value: left, center, right\n\nlabel['relief'] = label_style\nlabel['foreground'] = color  # color passed with name or HEX RGB codes\nlabel['background'] = color  # color passed with name or HEX RGB codes\n
"},{"location":"languages/python/libs/tkinter.html#font-style-use-with-caution","title":"FONT STYLE (use with caution)","text":"Python
# used outside style option\nlabel['font'] = font\n

Fonts:

"},{"location":"languages/python/libs/tkinter.html#button","title":"BUTTON","text":"

Press to perform some action

Python
button = ttk.Button(parent, text='button_text', command=action_performed)\n
"},{"location":"languages/python/libs/tkinter.html#text-or-image","title":"TEXT or IMAGE","text":"Python
button['text/textvariable'], button['image'], button['compound']\n
"},{"location":"languages/python/libs/tkinter.html#button-invocation","title":"BUTTON INVOCATION","text":"Python
button.invoke()  # button activation in the program\n
"},{"location":"languages/python/libs/tkinter.html#button-state","title":"BUTTON STATE","text":"

Activate or deactivate the widget.

Python
button.state(['disabled'])            # set the disabled flag, disabling the button\nbutton.state(['!disabled'])           # clear the disabled flag\nbutton.instate(['disabled'])          # return true if the button is disabled, else false\nbutton.instate(['!disabled'])         # return true if the button is not disabled, else false\nbutton.instate(['!disabled'], cmd)  # execute 'cmd' if the button is not disabled\n# WIDGET STATE FLAGS: active, disabled, focus, pressed, selected, background, readonly, alternate, invalid\n
"},{"location":"languages/python/libs/tkinter.html#checkbutton","title":"CHECKBUTTON","text":"

Button with binary value of some kind (e.g a toggle) and also invokes a command callback

Python
checkbutton_var = TkVarType\ncheck = ttk.Checkbutton(parent, text='button text', command=action_performed, variable=checkbutton_var, onvalue=value_on, offvalue=value_off)\n
"},{"location":"languages/python/libs/tkinter.html#widget-value","title":"WIDGET VALUE","text":"

Variable option holds value of button, updated by widget toggle. DEFAULT: 1 (while checked), 0 (while unchecked) onvalue, offvalue are used to personalize checked and unchecked values if linked variable is empty or different from on-off value the state flag is set to alternate checkbutton won't set the linked variable (MUST be done in the program)

"},{"location":"languages/python/libs/tkinter.html#config-options","title":"CONFIG OPTIONS","text":"Python
check['text/textvariable']\ncheck['image']\ncheck['compound']\ncheck.state(['flag'])\ncheck.instate(['flag'])\n
"},{"location":"languages/python/libs/tkinter.html#radiobutton","title":"RADIOBUTTON","text":"

Multiple-choice selection (good if options are few).

Python
#RADIOBUTTON CREATION (usually as a set)\nradio_var = TkVarType\nradio_1 = ttk.Radiobutton(parent, text='button text', variable=radio_var, value=button_1_value)\nradio_2 = ttk.Radiobutton(parent, text='button text', variable=radio_var, value=button_2_value)\nradio_3 = ttk.Radiobutton(parent, text='button text', variable=radio_var, value=button_3_value)\n# if linked value does not exist flag state is alternate\n\n# CONFIG OPTIONS\nradio['text/textvariable']\nradio['image']\nradio['compound']\nradio.state(['flag'])\nradio.instate(['flag'])\n
"},{"location":"languages/python/libs/tkinter.html#entry","title":"ENTRY","text":"

Single line text field accepting a string.

Python
entry_var = StringVar()\nentry = ttk.Entry(parent, textvariable=entry_var, width=char_num, show=symbol)\n# SHOW: replaces the entry test with symbol, used for password\n# entries don't have an associated label, needs a separate widget\n
"},{"location":"languages/python/libs/tkinter.html#change-entry-value","title":"CHANGE ENTRY VALUE","text":"Python
entry.get()  # returns entry value\nentry.delete(start, 'end')  # delete between two indices, 0-based\nentry.insert(index, 'text value')  # insert new text at a given index\n
"},{"location":"languages/python/libs/tkinter.html#entry-config-options","title":"ENTRY CONFIG OPTIONS","text":"Python
radio.state(['flag'])\nradio.instate(['flag'])\n
"},{"location":"languages/python/libs/tkinter.html#combobox","title":"COMBOBOX","text":"

Drop-down list of available options.

Python
combobox_var = StringVar()\ncombo = ttk.Combobox(parent, textvariable=combobox_var)\ncombobox.get()  # return combobox current value\ncombobox.set(value)  # set combobox new value\ncombobox.current()  # returns which item in the predefined values list is selected (0-based index of the provided list, -1 if not in the list)\n#combobox will generate a bind-able <ComboboxSelected> virtual event whenever the value changes\ncombobox.bind('<<ComboboxSelected>>', function)\n
"},{"location":"languages/python/libs/tkinter.html#predefined-values","title":"PREDEFINED VALUES","text":"Python
combobox['values'] = (value_1, value_2, ...)  # provides a list of choose-able values\ncombobox.state(['readonly'])  # restricts choose-able values to those provided with 'values' config option\n# SUGGESTION: call selection clear method on value change (on ComboboxSelected event) to avoid visual oddities\n
"},{"location":"languages/python/libs/tkinter.html#listbox-tk-classic","title":"LISTBOX (Tk Classic)","text":"

Display list of single-line items, allows browsing and multiple selection (part og Tk classic, missing in themed Tk widgets).

Python
lstbx = Listbox(parent, height=num, listvariable=item_list:list)\n# listvariable links a variable (MUST BE a list) to the listbox, each element is a item of the listbox\n# manipulation of the list changes the listbox\n
"},{"location":"languages/python/libs/tkinter.html#selecting-items","title":"SELECTING ITEMS","text":"Python
lstbx['selectmode'] = mode  # MODE: browse (single selection), extended (multiple selection)\nlstbx.curselection()  # returns list of indices of selected items\n# on selection change: generate event <ListboxSelect>\n# often each string in the program is associated with some other data item\n# keep a second list, parallel to the list of strings displayed in the listbox, which will hold the associated objects\n# (association by index with .curselection() or with a dict).\n
"},{"location":"languages/python/libs/tkinter.html#scrollbar","title":"SCROLLBAR","text":"Python
scroll = ttk.Scrollbar(parent, orient=direction, command=widget.view)\n# ORIENT: VERTICAL, HORIZONTAL\n# WIDGET.VIEW: .xview, .yview\n# NEEDS ASSOCIATED WIDGET SCROLL CONFIG\nwidget.configure(xscrollcommand=scroll.set)\nwidget.configure(yscrollcommand=scroll.set)\n
"},{"location":"languages/python/libs/tkinter.html#sizegrip","title":"SIZEGRIP","text":"

Box in right bottom of widget, allows resize.

Python
ttk.Sizegrip(parent).grid(column=999, row=999, sticky=(S, E))\n
"},{"location":"languages/python/libs/tkinter.html#text-tk-classic","title":"TEXT (Tk Classic)","text":"

Area accepting multiple line of text.

Python
txt = Text(parent, width=num:int, height=num:int, wrap=flag)  # width is character num, height is row num\n# FLAG: none (no wrapping), char (wrap at every character), word (wrap at word boundaries)\ntxt['state'] = flag  # FLAG: disabled, normal\n# accepts commands xscrollcommand and yscrollcommandand and yview, xview methods\ntxt.see(line_num.char_num)  # ensure that given line is visible (line is 1-based, char is 0-based)\ntxt.get( index, string)   # insert string in pos index (index = line.char), 'end' is shortcut for end of text\ntxt.delete(start, end)  # delete range of text\n
"},{"location":"languages/python/libs/tkinter.html#progressbar","title":"PROGRESSBAR","text":"

Feedback about progress of lenghty operation.

Python
progbar = ttk.Progressbar(parent, orient=direction, length=num:int, value=num, maximum=num:float mode=mode)\n# DIRECTION: VERTICAL, HORIZONTAL\n# MODE: determinate (relative progress of completion), indeterminate (no estimate of completion)\n# LENGTH: dimension in pixel\n# VALUE: sets the progress, updates the bar as it changes\n# MAXIMUM: total number of steps (DEFAULT: 100)\n
"},{"location":"languages/python/libs/tkinter.html#determinate-progress","title":"DETERMINATE PROGRESS","text":"Python
progbar.step(amount)  # increment value of given amount (DEFAULT: 1.0)\n
"},{"location":"languages/python/libs/tkinter.html#indeterminate-progress","title":"INDETERMINATE PROGRESS","text":"Python
progbar.start()  # starts progressbar\nprogbar.stop()  #stoops progressbar\n
"},{"location":"languages/python/libs/tkinter.html#scale","title":"SCALE","text":"

Provide a numeric value through direct manipulation.

Python
scale = ttk.Scale(parent, orient=DIR, length=num:int, from_=num:float, to=num:float, command=cmd)\n# COMMAND: calls cmd at every scale change, appends current value to func call\nscale['value']  # set or read current value\nscale.set(value)  # set current value\nscale.get()  # get current value\n
"},{"location":"languages/python/libs/tkinter.html#spinbox","title":"SPINBOX","text":"

Choose numbers. The spinbox choses item from a list, arrows permit cycling lits items.

Python
spinval = StringVar()\nspin = Spinbox(parent, from_=num, to=num, textvariable=spinval, increment=num, value=lst, wrap=boolean)\n# INCREMENT specifies increment\\decrement by arrow button\n# VALUE: list of items associated with the spinbox\n# WRAP: boolean value determining if value should wrap around if beyond start-end value\n
"},{"location":"languages/python/libs/tkinter.html#grid-geometry-manager","title":"GRID GEOMETRY MANAGER","text":"

Widgets are assigned a \"column\" number and a \"row\" number, which indicates their relative position to each other. Column and row numbers must be integers, with the first column and row starting at 0. Gaps in column and row numbers are handy to add more widgets in the middle of the user interface at a later time. The width of each column (or height of each row) depends on the width or height of the widgets contained within the column or row.

Widgets can take up more than a single cell in the grid (\"columnspan\" and \"rowspan\" options).

"},{"location":"languages/python/libs/tkinter.html#layout-within-cell","title":"LAYOUT WITHIN CELL","text":"

By default, if a cell is larger than the widget contained in it, the widget will be centered within it, both horizontally and vertically, with the master's background showing in the empty space around it. The \"sticky\" option can be used to change this default behavior. The value of the \"sticky\" option is a string of 0 or more of the compass directions \"nsew\", specifying which edges of the cell the widget should be \"stuck\" to. Specifying two opposite edges means that the widget will be stretched so it is stuck to both. Specifying \"nsew\" it will stick to every side.

"},{"location":"languages/python/libs/tkinter.html#handling-resize","title":"HANDLING RESIZE","text":"

Every column and row has a \"weight\" grid option associated with it, which tells it how much it should grow if there is extra room in the master to fill. By default, the weight of each column or row is 0, meaning don't expand to fill space. This is done using the \"columnconfigure\" and \"rowconfigure\" methods of grid. Both \"columnconfigure\" and \"rowconfigure\" also take a \"minsize\" grid option, which specifies a minimum size.

"},{"location":"languages/python/libs/tkinter.html#padding","title":"PADDING","text":"

Normally, each column or row will be directly adjacent to the next, so that widgets will be right next to each other. \"padx\" puts a bit of extra space to the left and right of the widget, while \"pady\" adds extra space top and bottom. A single value for the option puts the same padding on both left and right (or top and bottom), while a two-value list lets you put different amounts on left and right (or top and bottom). To add padding around an entire row or column, the \"columnconfigure\" and \"rowconfigure\" methods accept a \"pad\" option.

Python
widget.grid(column=num, row=num, columnspan=num, rowspan=num, sticky=(), padx=num, pady=num)  # sticky: N, S, E, W\nwidget.columnconfigure(pad=num, weight=num)\nwidget.rowconfigure(pad=num, weight=num)\n\nwidget.grid_slaves()  # returns map, list of widgets inside a master\nwidget.grid_info()  # returns list of grid options\nwidget.grid_configure()  # change one or more option\n\nwidget.grid_forget(slaves)  # takes a list of slaves, removes slaves from grid (forgets slaves options)\nwidget.grid_remove(slaves)  # takes a list of slaves, removes slaves from grid (remembers slaves options)\n
"},{"location":"languages/python/libs/tkinter.html#windows-and-dialogs","title":"WINDOWS AND DIALOGS","text":""},{"location":"languages/python/libs/tkinter.html#creating-toplevel-window","title":"CREATING TOPLEVEL WINDOW","text":"Python
tlw = Toplevel(parent)  # parent of root window, no need to grid it\n\nwindow.destroy()\n# can destroy every widget\n# destroying parent also destroys it's children\n
"},{"location":"languages/python/libs/tkinter.html#changing-behavior-and-style","title":"CHANGING BEHAVIOR AND STYLE","text":"Python
# WINDOW TILE\nwindow.title()  # returns title of the window\nwindow.title('new title')  # sets title\n\n# SIZE AND LOCATION\nwindow.geometry(geo_specs)\n'''full geometry specification: width * height +- x +- y (actual coordinates of screen)\n+x --> x pixels from left edge\n-x --> x pixels from right edge\n+y --> y pixels from top edge\n-y --> y pixels from bottom edge'''\n\n# STACKING ORDER\n# current stacking order (list from lowest to highest) --- NOT CLEANLY EXPOSED THROUGH TK API\nroot.tk.eval('wm stackorder ' + str(window))\n# check if window is above or below\nif (root.tk.eval('wm stackorder '+str(window)+' isabove '+str(otherwindow))=='1')\nif (root.tk.eval('wm stackorder '+str(window)+' isbelow '+str(otherwindow))=='1')\n# raise or lower windows\nwindow.lift()  # absolute position\nwindow.lift(otherwin)  # relative to other window\nwindow.lower()  # absolute position\nwindow.lower(otherwin)   # relative to other window\n\n# RESIZE BEHAVIOR\nwindow.resizable(boolean, boolean)  # sets if resizable in width (1st param) and width (2nd param)\nwindow.minsize(num, num)  # sets min width and height\nwindow.maxsize(num, num)  # sets max width and height\n\n# ICONIFYING AND WITHDRAWING\n# WINDOW STATE: normal. iconic (iconified window), withdrawn, icon, zoomed\nwindow.state()  # returns current window state\nwindow.state('state')  # sets window state\nwindow.iconify()  # iconifies window\nwindow.deiconify()  # deiconifies window\n
"},{"location":"languages/python/libs/tkinter.html#standard-dialogs","title":"STANDARD DIALOGS","text":"Python
# SLEETING FILE AND DIRECTORIES\n# on Windows and Mac invokes underlying OS dialogs directly\nfrom tkinter import filedialog\nfilename = filedialog.askopenfilename()\nfilename = filedialog.asksaveasfilename()\ndirname = filedialog.askdirectory()\n'''All of these commands produce modal dialogs, which means that the commands (and hence the program) will not continue running until the user submits the dialog.\nThe commands return the full pathname of the file or directory the user has chosen, or return an empty string if the user cancels out of the dialog.'''\n\n# SELECTING COLORS\nfrom tkinter import colorchooser\n # returns HEX color code, INITIALCOLOR: exiting color, presumably to replace\ncolorchooser.askcolor(initialcolor=hex_color_code)\n\n# ALERT AND COMFIRMATION DIALOGS\nfrom tkinter import messagebox\nmessagebox.showinfo(title=\"title\", message='text')  # simple box with message and OK button\nmessagebox.showerror(title=\"title\", message='text')\nmessagebox.showwarning(title=\"title\", message='text')\nmessagebox.askyesno(title=\"title\", message='text', detail='secondary text' icon='icon')\nmessagebor.askokcancel(message='text', icon='icon', title='title', detail='secondary text', default=button)  # DEFAULT: default button, ok or cancel\nmessagebox.akdquestion(title=\"title\", message='text', detail='secondary text', icon='icon')\nmessagebox.askretrycancel(title=\"title\", message='text', detail='secondary text', icon='icon')\nmessagebox.askyesnocancel(title=\"title\", message='text', detail='secondary text', icon='icon')\n# ICON: info (default), error, question, warning\n

POSSIBLE ALERT/CONFIRMATION RETURN VALUES:

"},{"location":"languages/python/libs/tkinter.html#separator","title":"SEPARATOR","text":"Python
# horizontal or vertical line between groups of widgets\nseparator = ttk.Separator(parent, orient=direction)\n# DIRECTION: horizontal, vertical\n'''LABEL FRAME'''\n# labelled frame, used to group widgets\nlf = ttk.LabelFrame(parent, text='label')\n'''PANED WINDOWS'''\n# stack multimple resizable widgets\n# panes ara adjustable (drag sash between panes)\npw = ttk.PanedWindow(parent, orient=direction)\n# DIRECTION: horizontal, vertical\nlf1 = ttk.LabelFrame(...)\nlf2 = ttk.LabelFrame(...)\npw.add(lf1)  # add widget to paned window\npw.add(lf2)\npw.insert(position, subwindow)  # insert widget at given position in list of panes (0, ..., n-1)\npw.forget(subwindow)  # remove widget from pane\npw.forget(position)  # remove widget from pane\n
"},{"location":"languages/python/libs/tkinter.html#notebook","title":"NOTEBOOK","text":"

Allows switching between multiple pages

Python
nb = ttk.Notebook(parent)\nf1 = ttk.Frame(parent, ...)  # child of notebook\nf2 = ttk.Frame(parent, ...)\nnb.add(subwindow, text='page title', state=flag)\n# TEXT: name of page, STATE: normal, dusabled (not selectable), hidden\n\nnb.insert(position, subwindow, option=value)\nnb.forget(subwindow)\nnb.forget(position)\nnb.tabs()  # retrieve all tabs\nnb.select()  # return current tab\nnb.select(position/subwindow)  # change current tab\nnb.tab(tabid, option)  # retrieve tab (TABID: position or subwindow) option\nnb.tab(tabid, option=value)   # change tab option\n
"},{"location":"languages/python/libs/tkinter.html#fonts-colors-images","title":"FONTS, COLORS, IMAGES","text":""},{"location":"languages/python/libs/tkinter.html#named-fonts","title":"NAMED FONTS","text":"

Creation of personalized fonts

Python
from tkinter import font\nfont_name = font.Font(family='font_family', size=num, weight='bold/normal', slant='roman/italic', underline=boolean, overstrike=boolean)\n# FAMILY: Courier, Times, Helvetica (support guaranteed)\nfont.families()  # all avaiable font families\n
"},{"location":"languages/python/libs/tkinter.html#colors","title":"COLORS","text":"

Specified w/ HEX RGB codes.

"},{"location":"languages/python/libs/tkinter.html#images","title":"IMAGES","text":"

imgobj = PhotoImage(file='filename') label['image'] = imgobj

"},{"location":"languages/python/libs/tkinter.html#images-w-pillow","title":"IMAGES W/ Pillow","text":"Python
from PIL import ImageTk, Image\nmyimg = ImageTk.PhotoImage(Image.open('filename'))\n
"},{"location":"languages/python/modules/argparse.html","title":"Argpasrse Module","text":""},{"location":"languages/python/modules/argparse.html#creating-a-parser","title":"Creating a parser","text":"Python
import argparse\n\nparser = argparse.ArgumentParser(description=\"description\", allow_abbrev=True)\n

Note: All parameters should be passed as keyword arguments.

"},{"location":"languages/python/modules/argparse.html#adding-arguments","title":"Adding Arguments","text":"Python
ArgumentParser.add_argument(\"name_or_flags\", nargs=\"...\", action=\"...\")\n

Note: All parameters should be passed as keyword arguments.

"},{"location":"languages/python/modules/argparse.html#actions","title":"Actions","text":"

store: This just stores the argument's value. This is the default action.

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo')\n>>> parser.parse_args('--foo 1'.split())\nNamespace(foo='1')\n

store_const: This stores the value specified by the const keyword argument. The store_const action is most commonly used with optional arguments that specify some sort of flag.

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo', action='store_const', const=42)\n>>> parser.parse_args(['--foo'])\nNamespace(foo=42)\n

store_true and store_false: These are special cases of store_const used for storing the values True and False respectively. In addition, they create default values of False and True respectively.

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo', action='store_true')\n>>> parser.add_argument('--bar', action='store_false')\n>>> parser.add_argument('--baz', action='store_false')\n>>> parser.parse_args('--foo --bar'.split())\nNamespace(foo=True, bar=False, baz=True)\n

append: This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. Example usage:

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo', action='append')\n>>> parser.parse_args('--foo 1 --foo 2'.split())\nNamespace(foo=['1', '2'])\n

append_const: This stores a list, and appends the value specified by the const keyword argument to the list. (Note that the const keyword argument defaults to None.) The append_const action is typically useful when multiple arguments need to store constants to the same list. For example:

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--str', dest='types', action='append_const', const=str)\n>>> parser.add_argument('--int', dest='types', action='append_const', const=int)\n>>> parser.parse_args('--str --int'.split())\nNamespace(types=[<class 'str'>, <class 'int'>])\n

count: This counts the number of times a keyword argument occurs. For example, this is useful for increasing verbosity levels: Note: the default will be None unless explicitly set to 0.

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--verbose', '-v', action='count', default=0)\n>>> parser.parse_args(['-vvv'])\nNamespace(verbose=3)\n

help: This prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser.

version: This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked:

Python
>>> import argparse\n>>> parser = argparse.ArgumentParser(prog='PROG')\n>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')\n>>> parser.parse_args(['--version'])\nPROG 2.0\n

extend: This stores a list, and extends each argument value to the list. Example usage:

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument(\"--foo\", action=\"extend\", nargs=\"+\", type=str)\n>>> parser.parse_args([\"--foo\", \"f1\", \"--foo\", \"f2\", \"f3\", \"f4\"])\nNamespace(foo=['f1', 'f2', 'f3', 'f4'])\n
"},{"location":"languages/python/modules/argparse.html#nargs","title":"Nargs","text":"

ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action.

Note: If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action.

N (an integer): N arguments from the command line will be gathered together into a list.

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo', nargs=2)\n>>> parser.add_argument('bar', nargs=1)\n>>> parser.parse_args('c --foo a b'.split())\nNamespace(bar=['c'], foo=['a', 'b'])\n

Note: nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself.

?: One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.

For optional arguments, there is an additional case: the option string is present but not followed by a command-line argument. In this case the value from const will be produced.

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo', nargs='?', const='c', default='d')\n>>> parser.add_argument('bar', nargs='?', default='d')\n>>> parser.parse_args(['XX', '--foo', 'YY'])\nNamespace(bar='XX', foo='YY')\n>>> parser.parse_args(['XX', '--foo'])\nNamespace(bar='XX', foo='c')\n>>> parser.parse_args([])\nNamespace(bar='d', foo='d')\n

*: All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

Python
>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo', nargs='*')\n>>> parser.add_argument('--bar', nargs='*')\n>>> parser.add_argument('baz', nargs='*')\n>>> parser.parse_args('a b --foo x y --bar 1 2'.split())\nNamespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])\n

+: All command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn't at least one command-line argument present.

Python
>>> parser = argparse.ArgumentParser(prog='PROG')\n>>> parser.add_argument('foo', nargs='+')\n>>> parser.parse_args(['a', 'b'])\nNamespace(foo=['a', 'b'])\n>>> parser.parse_args([])\nusage: PROG [-h] foo [foo ...]\nPROG: error: the following arguments are required: foo\n

argparse.REMAINDER: All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities.

Python
>>> parser = argparse.ArgumentParser(prog='PROG')\n>>> parser.add_argument('--foo')\n>>> parser.add_argument('command')\n>>> parser.add_argument('args', nargs=argparse.REMAINDER)\n>>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))\nNamespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')\n
"},{"location":"languages/python/modules/argparse.html#parsing-arguments","title":"Parsing Arguments","text":"Python
# Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace.\nArgumentParser.parse_args(args=None, namespace=None)\n\n#  assign attributes to an already existing object, rather than a new Namespace object\nclass C:\n    pass\n\nc = C()\nparser = argparse.ArgumentParser()\nparser.add_argument('--foo')\nparser.parse_args(args=['--foo', 'BAR'], namespace=c)\nc.foo  # BAR\n\n# return a dict instead of a Namespace\nargs = parser.parse_args(['--foo', 'BAR'])\nvars(args)  # {'foo': 'BAR'}\n
"},{"location":"languages/python/modules/collections.html","title":"Collections Module","text":"Python
# COUNTER ()\n# subclass dictionary for counting hash-capable objects\nfrom collections import Counter\nCounter (sequence) # -> Counter object\n# {item: num included in sequence, ...}\n\nvar = Counter (sequence)\nvar.most_common (n) # produce list of most common elements (most common n)\nsum (var.values \u200b\u200b()) # total of all counts\nvar.clear () #reset all counts\nlist (var) # list unique items\nset (var) # convert to a set\ndict (var) # convert to regular dictionary\nvar.items () # convert to a list of pairs (element, count)\nCounter (dict (list_of_pairs)) # convert from a list of pairs\nvar.most_common [: - n-1: -1] # n less common elements\nvar + = Counter () # remove zero and negative counts\n\n\n# DEFAULTDICT ()\n# dictionary-like object that takes a default type as its first argument\n# defaultdict will never raise a KeyError exception.\n# non-existent keys return a default value (default_factory)\nfrom collections import defaultdict\nvar = defaultdict (default_factory)\nvar.popitem () # remove and return first element\nvar.popitem (last = True) # remove and return last item\n\n\n# OREDERDDICT ()\n# subclass dictionary that \"remembers\" the order in which the contents are entered\n# Normal dictionaries have random order\nname_dict = OrderedDict ()\n# OrderedDict with same elements but different order are considered different\n\n\n# USERDICT ()\n# pure implementation in pythondi a map that works like a normal dictionary.\n# Designated to create subclasses\nUserDict.data # recipient of UserDict content\n\n\n# NAMEDTUPLE ()\n# each namedtuple is represented by its own class\nfrom collections import namedtuple\nNomeClasse = namedtuple (NomeClasse, parameters_separated_from_space)\nvar = ClassName (parameters)\nvar.attribute # access to attributes\nvar [index] # access to attributes\nvar._fields # access to attribute list\nvar = class._make (iterable) # transformain namedtuple\nvar._asdict () # Return OrderedDict object starting from namedtuple\n\n\n# DEQUE ()\n# double ended queue (pronounced \"deck\")\n# list editable on both \"sides\"\nfrom collections import deque\nvar = deque (iterable, maxlen = num) # -> deque object\nvar.append (item) # add item to the bottom\nvar.appendleft (item) # add item to the beginning\nvar.clear () # remove all elements\nvar.extend (iterable) # add iterable to the bottom\nvar.extendleft (iterable) # add iterable to the beginning '\nvar.insert (index, item) # insert index position\nvar.index (item, start, stop) # returns position of item\nvar.count (item)\nvar.pop ()\nvar.popleft ()\nvar.remove (value)\nvar.reverse () # reverse element order\nvar.rotate (n) # move the elements of n steps (dx if n> 0, sx if n <0)\nvar.sort ()\n
"},{"location":"languages/python/modules/csv.html","title":"CSV Module","text":"Python
# iterate lines of csvfile\n.reader (csvfile, dialect, ** fmtparams) -> reader object\n\n# READER METHODS\n.__ next __ () # returns next iterable object line as a list or dictionary\n\n# READER ATTRIBUTES\ndialect # read-only description of the dialec used\nline_num # number of lines from the beginning of the iterator\nfieldnames\n\n# convert data to delimited strings\n# csvfile must support .write ()\n#type None converted to empty string (simplify SQL NULL dump)\n.writer (csvfile, dialect, ** fmtparams) -> writer object\n\n# WRITER METHODS\n# row must be iterable of strings or numbers or of dictionaries\n.writerow (row) # write row formatted according to the current dialect\n.writerows (rows) # write all elements in rows formatted according to the current dialect. rows is iterable of row\n\n# CSV METHODS\n# associate dialect to name (name must be string)\n.register_dialect (name, dialect, ** fmtparams)\n\n# delete the dialect associated with name\n.unregister_dialect ()\n\n# returns the dialect associated with name\n.get_dialect (name)\n\n# list of dialects associated with name\n.list_dialect (name)\n\n# returns (if empty) or sets the limit of the csv field\n.field_size_limit (new_limit)\n\n'''\ncsvfile - iterable object returning a string on each __next __ () call\n          if csv is a file it must be opened with newline = '' (universal newline)\ndialect - specify the dialect of csv (Excel, ...) (OPTIONAL)\n\nfmtparams --override formatting parameters (OPTIONAL) https://docs.python.org/3/library/csv.html#csv-fmt-params\n'''\n\n# object operating as a reader but maps the info in each row into an OrderedDict whose keys are optional and passed through fieldnames\nclass csv.Dictreader (f, fieldnames = None, restket = none, restval = None, dialect, * args, ** kwargs)\n'''\nf - files to read\nfieldnames --sequence, defines the names of the csv fields. if omitted use the first line of f\nrestval, restkey --se len (row)> fieldnames excess data stored in restval and restkey\n\nadditional parameters passed to the underlying reader instance\n'''\n\nclass csv.DictWriter (f, fieldnames, restval = '', extrasaction, dialect, * args, ** kwargs)\n'''\nf - files to read\nfieldnames --sequence, defines the names of the csv fields. (NECESSARY)\nrestval --se len (row)> fieldnames excess data stored in restval and restkey\nextrasaction - if the dictionary passed to writerow () contains key not present in fieldnames extrasaction decides action to be taken (raise cause valueError, ignore ignores additional keys)\n\nadditional parameters passed to the underlying writer instance\n'''\n\n# DICTREADER METHODS\n.writeheader () # write a header line of fields as specified by fieldnames\n\n# class used to infer the format of the CSV\nclass csv.Sniffer\n.sniff (sample, delimiters = None) #parse the sample and return a Dialect class. delimiter is a sequence of possible box delimiters\n.has_header (sample) -> bool # True if first row is a series of column headings\n\n#CONSTANTS\ncsv.QUOTE_ALL # instructs writer to quote (\"\") all fields\ncsv.QUOTE_MINIMAL # instructs write to quote only fields containing special characters such as delimiter, quote char ...\ncsv.QUOTE_NONNUMERIC # instructs the writer to quote all non-numeric fields\ncsv.QUOTE_NONE # instructs write to never quote fields\n
"},{"location":"languages/python/modules/ftplib.html","title":"Ftplib Module","text":""},{"location":"languages/python/modules/ftplib.html#ftp-classes","title":"FTP CLASSES","text":"Python
ftplib.FTP(host=\"\", user=\"\", password=\"\", acct=\"\")\n# if HOST => connect(host)\n# if USER => login(user, password, acct)\n\n\nftplib.FTP_TLS(host=\"\", user=\"\", password=\"\", acct=\"\")\n
"},{"location":"languages/python/modules/ftplib.html#exceptions","title":"EXCEPTIONS","text":"Python
ftplib.error_reply  # unexpected error from server\nftplib.error_temp  # temporary error (response codes 400-499)\nftplib.error_perm  # permanent error (response codes 500-599)\nftplib.error_proto  # error not in ftp specs\nftplib.all_errors  # tuple of all exceptions\n
"},{"location":"languages/python/modules/ftplib.html#ftp-objects","title":"FTP OBJECTS","text":"Python
# method on text files: -lines\n# method on binary files: -binary\n\n# CONNECTION\nFTP.connect(host=\"\", port=0)  # used once per instance\n# DON'T CALL if host was supplied at instance creation\n\nFTP.getwelcome()  # return welcome message\n\nFTP.login(user='anonymous', password='', acct='')\n# called once per instance after connection is established\n# DEFAULT PASSWORD: anonymous@\n# DON'T CALL if host was supplied at instance creation\nFTP.sendcmd(cmd)  # send command string and return response\nFTP.voidcmd(cmd)  # send command string and return nothing if successful\n# FILE TRANSFER\nFTP.abort()  # abort in progress file transfer (can fail)\n\nFTTP.transfercmd(cmd, rest=None)  # returns socket for connection\n# CMD active mode: send EPRT or PORT command and CMD and accept connection\n# CMD passive mode: send EPSV or PASV and start transfer command\n\nFTP.retrbinary(cmd, callback, blocksize=8192, rest=None) # retrieve file in binary mode\n# CMD: appropriate RETR command ('RETR filename')\n# CALLBACK: func called on every block of data received\n\nFTP.rertlines(cmd, callback=None)\n# retrieve file or dir list in ASCII transfer mode\n# CMD: appropriate RETR, LSIT (list and info of files), NLST (list of file names)\n# DEFAULT CALLBACK: sys.stdout\n\nFTP.set_pasv(value)  # set passive mode if value is true, otherwise disable it\n# passive mode on by default\n\nFTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)  # store file in binary mode\n# CMD: appropriate STOR command ('STOR filename')\n# FP: {file object in binary mode} read until EOF in blocks of blocksize\n# CALLBACK: func called on each block after sending\n\nFTP.storlines(cmd, fp, callback=None)  # store file in ASCII transfer mode\n# CMD: appropriate STOR command ('STOR filename')\n# FP: {file object} read until EOF\n# CALLBACK: func called on each block after sending\n
"},{"location":"languages/python/modules/itertools.html","title":"Itertools Module","text":"Python
# accumulate ([1,2,3,4,5]) -> 1, 3 (1 + 2), 6 (1 + 2 + 3), 10 (1 + 2 + 3 + 6), 15 (1+ 2 + 3 + 4 + 5)\n# accumulate (iter, func (,)) -> iter [0], func (iter [0] + iter [1]) + func (prev + iter [2]), ...\naccumulate (iterable, func (_, _))\n\n# iterator returns elements from the first iterable,\n# then proceeds to the next until the end of the iterables\n# does not work if there is only one iterable\nchain (* iterable)\n\n# concatenates elements of the single iterable even if it contains sequences\nchain.from_iterable (iterable)\n\n# returns sequences of length r starting from the iterable\n# items treated as unique based on their value\ncombinations (iterable, r)\n\n# # returns sequences of length r starting from the iterable allowing the repetition of the elements\ncombinations_with_replacement (iterable, r)\n\n# iterator filters date elements returning only those that have\n# a corresponding element in selectors that is true\ncompress (data, selectors)\n\ncount (start, step)\n\n# iterator returning values \u200b\u200bin infinite sequence\ncycle (iterable)\n\n# iterator discards elements of the iterable as long as the predicate is true\ndropwhile (predicate, iterable)\n\n# iterator returning values \u200b\u200bif predicate is false\nfilterfalse (predicate, iterable)\n\n# iterator returns tuple (key, group)\n# key is the grouping criterion\n# group is a generator returning group members\ngroupby (iterable, key = None)\n\n# iterator returns slices of the iterable\nisslice (iterable, stop)\nisslice (iterable, start, stop, step)\n\n# returns all permutations of length r of the iterable\npermutations (iterable, r = None)\n\n# Cartesian product of iterables\n# loops iterables in order of input\n# [product ('ABCD', 'xy') -> Ax Ay Bx By Cx Cy Dx Dy]\n# [product ('ABCD', repeat = 2) -> AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD]\nproduct (* iterable, repetitions = 1)\n\n# returns an object infinite times if repetition is not specified\nrepeat (object, repetitions)\n\n# iterator compute func (iterable)\n# used if iterable is pre-zipped sequence (seq of tuples grouping elements)\nstarmap (func, iterable)\n\n# iterator returning values \u200b\u200bfrom iterable as long as predicate is true\ntakewhile (predicate, iterable)\n\n# returns n independent iterators from the single iterable\ntee (iterable, n = 2)\n\n# produces an iterator that aggregates elements from each iterable\n# if the iterables have different lengths the missing values \u200b\u200bare filled according to fillervalue\nzip_longest (* iterable, fillvalue = None)\n
"},{"location":"languages/python/modules/json.html","title":"JSON Module","text":""},{"location":"languages/python/modules/json.html#json-format","title":"JSON Format","text":"

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

JSON is built on two structures:

An OBJECT is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An ARRAY is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

A VALUE can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

A STRING is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A CHARACTER is represented as a single character string. A STRING is very much like a C or Java string. A NUMBER is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

WHITESPACE can be inserted between any pair of tokens.

"},{"location":"languages/python/modules/json.html#usage","title":"Usage","text":"Python
# serialize obj as JSON formatted stream to fp\njson.dump(obj, fp, cls=None, indent=None, separators=None, sort_keys=False)\n# CLS: {custom JSONEncoder} -- specifies custom encoder to be used\n# INDENT: {int > 0, string} -- array elements, object members pretty-printed with indent level\n# SEPARATORS: {tuple} -- (item_separator, key_separator)\n#   [default: (', ', ': ') if indent=None, (',', ':') otherwise],\n#   specify (',', ':') to eliminate whitespace\n# SORT_KEYS: {bool} -- if True dict sorted by key\n\n# serialize obj as JSON formatted string\njson.dumps(obj, cls=None, indent=None, separators=None, sort_keys=False)\n# CLS: {custom JSONEncoder} -- specifies custom encoder to be used\n# INDENT: {int > 0, string} -- array elements, object members pretty-printed with indent level\n# SEPARATORS: {tuple} -- (item_separator, key_separator)\n#   [default: (', ', ': ') if indent=None, (',', ':') otherwise],\n#   specify (',', ':') to eliminate whitespace\n# SORT_KEYS: {bool} -- if True dict sorted by key\n\n# deserialize fp to python object\njson.load(fp, cls=None)\n# CLS: {custom JSONEncoder} -- specifies custom decoder to be used\n\n# deserialize s (string, bytes or bytearray containing JSON doc) to python object\njson.loads(s, cls=None)\n# CLS: {custom JSONEncoder} -- specifies custom decoder to be used\n
"},{"location":"languages/python/modules/json.html#default-decoder-jsonjsondecoder","title":"Default Decoder (json.JSONDecoder())","text":"

Conversions (JSON -> Python):

"},{"location":"languages/python/modules/json.html#default-encoder-jsonjsonencoder","title":"Default Encoder (json.JSONEncoder())","text":"

Conversions (Python -> Json):

"},{"location":"languages/python/modules/json.html#extending-jsonencoder-example","title":"Extending JSONEncoder (Example)","text":"Python
import json\n\nclass ComplexEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, complex):\n            return [obj.real, obj.image]\n        # Let the base class default method raise the TypeError\n            return json.JSONEncoder.default(self, obj)\n
"},{"location":"languages/python/modules/json.html#retrieving-data-from-json-dict","title":"Retrieving Data from json dict","text":"Python
data = json.loads(json)\ndata[\"key\"]  # retrieve the value associated with the key\ndata[\"outer key\"][\"nested key\"]  # nested key value retrieval\n
"},{"location":"languages/python/modules/logging.html","title":"Logging Module","text":""},{"location":"languages/python/modules/logging.html#configuration","title":"Configuration","text":"Python
# basic configuration for the logging system\nlogging.basicConfig(filename=\"relpath\", level=logging.LOG_LEVEL, format=f\"message format\", **kwargs)  \n# DATEFMT: Use the specified date/time format, as accepted by time.strftime().\n\n# create a logger with a name (useful for having multiple loggers)\nlogger = logging.getLogger(name=\"logger name\")  \nlogger.level  # LOG_LEVEL for this logger\n\n# disable all logging calls of severity level and below\n# alternative to basicConfig(level=logging.LOG_LEVEL)\nlogging.disable(level=LOG_LEVEL)  \n
"},{"location":"languages/python/modules/logging.html#format-basicconfigformat","title":"Format (basicConfig(format=\"\"))","text":"Attribute name Format Description asctime %(asctime)s Human-readable time when the LogRecord was created. Modified by basicConfig(datefmt=\"\") created %(created)f Time when the LogRecord was created (as returned by time.time()). filename %(filename)s Filename portion of pathname. funcName %(funcName)s Name of function containing the logging call. levelname %(levelname)s Text logging level for the message. levelno %(levelno)s Numeric logging level for the message. lineno %(lineno)d Source line number where the logging call was issued (if available). message %(message)s The logged message, computed as msg % args. module %(module)s Module (name portion of filename). msecs %(msecs)d Millisecond portion of the time when the LogRecord was created. name %(name)s Name of the logger used to log the call. pathname %(pathname)s Full pathname of the source file where the logging call was issued (if available). process %(process)d Process ID (if available). processName %(processName)s Process name (if available). thread %(thread)d Thread ID (if available). threadName %(threadName)s Thread name (if available)."},{"location":"languages/python/modules/logging.html#datefmt-basicconfigdatefmt","title":"Datefmt (basicConfig(datefmt=\"\"))","text":"Directive Meaning %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name. %c Locale's appropriate date and time representation. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %I Hour (12-hour clock) as a decimal number [01,12]. %j Day of the year as a decimal number [001,366]. %m Month as a decimal number [01,12]. %M Minute as a decimal number [00,59]. %p Locale's equivalent of either AM or PM. %S Second as a decimal number [00,61]. %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. %x Locale's appropriate date representation. %X Locale's appropriate time representation. %y Year without century as a decimal number [00,99]. %Y Year with century as a decimal number. %z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM [-23:59, +23:59]. %Z Time zone name (no characters if no time zone exists). %% A literal '%' character."},{"location":"languages/python/modules/logging.html#logs","title":"Logs","text":"

Log Levels (Low To High):

Python
logging.debug(msg)  # Logs a message with level DEBUG on the root logger\nlogging.info(msg)  # Logs a message with level INFO on the root logger\nlogging.warning(msg)  # Logs a message with level WARNING on the root logger\nlogging.error(msg)  # Logs a message with level ERROR on the root logger\nlogging.critical(msg)  # Logs a message with level CRITICAL on the root logger\n
"},{"location":"languages/python/modules/shutil.html","title":"Shutil Module","text":"

High-level file operations

Python
# copy file src to fil dst, return dst in most efficient way\nshutil.copyfile(src, dst)\n# dst MUST be complete target name\n# if dst already exists it will be overwritten\n\n# copy file src to directory dst, return path to new file\nshutil.copy(src, dst)\n\n# Recursively copy entire dir-tree rooted at src to directory named dst\n# return the destination directory\nshutil.copytree(src, dst, dirs_exist_ok=False)\n# DIRS_EXIST_OK: {bool} -- dictates whether to raise an exception in case dst\n# or any missing parent directory already exists\n\n# delete an entire directory tree\nshutil.rmtree(path, ignore_errors=False, onerror=None)\n# IGNORE_ERROR: {bool} -- if true errors (failed removals) will be ignored\n# ON_ERROR: handler for removal errors (if ignore_errors=False or omitted)\n\n# recursively move file or directory (src) to dst, return dst\nshutil.move(src, dst)\n# if the destination is an existing directory, then src is moved inside that directory.\n# if the destination already exists but is not a directory,\n# it may be overwritten depending on os.rename() semantics\n# used to rename files\n\n# change owner user and/or group of the given path\nshutil.chown(path, user=None, group=None)\n# user can be a system user name or a uid; the same applies to group.\n#  At least one argument is required\n\n# create archive file and return its name\nshutil.make_archive(base_name, format, [root_dir, base_dir])\n# BASE_NAME: {string} -- name of the archive, including path, excluding extension\n# FROMAT: {zip, tar, gztar, bztar, xztar} -- archive format\n# ROOT_DIR: {path} -- root directory of archive (location of archive)\n# BASE_DIR: {path} -- directory where the archiviation starts\n\n# unpack an archive\nshutil.unpack_archive(filename, [extract_dir, format])\n# FILENAME: full path of archive\n# EXTRACT_DIR: {path} -- directory to unpack into\n# FORMAT: {zip, tar, gztar, bztar, xztar} -- archive format\n\n# return disk usage statistics as Namedtuple w/ attributes total, used, free\nshutil.disk_usage(path)\n
"},{"location":"languages/python/modules/smtplib.html","title":"SMTPlib Module","text":"Python
import smtplib\n\n# SMTP instance that encapsulates a SMTP connection\n# If the optional host and port parameters are given, the SMTP connect() method is called with those parameters during initialization.\ns = smtplib.SMTP(host=\"host_smtp_address\", port=\"smtp_service_port\", **kwargs)\n\ns = smtplib.SMTP_SSL(host=\"host_smtp_address\", port=\"smtp_service_port\", **kwargs)\n# An SMTP_SSL instance behaves exactly the same as instances of SMTP.\n# SMTP_SSL should be used for situations where SSL is required from the beginning of the connection\n# and using starttls() is not appropriate.\n# If host is not specified, the local host is used.\n# If port is zero, the standard SMTP-over-SSL port (465) is used.\n\nSMTP.connect(host='localhost', port=0)\n#Connect to a host on a given port. The defaults are to connect to the local host at the standard SMTP port (25). If the hostname ends with a colon (':') followed by a number, that suffix will be stripped off and the number interpreted as the port number to use. This method is automatically invoked by the constructor if a host is specified during instantiation. Returns a 2-tuple of the response code and message sent by the server in its connection response.\n\nSMTP.verify(address)  # Check the validity of an address on this server using SMTP VRFY\n\nSMTP.login(user=\"full_user_mail\", password=\"user_password\")  # Log-in on an SMTP server that requires authentication\n\nSMTP.SMTPHeloError  # The server didn't reply properly to the HELO greeting\nSMTP.SMTPAuthenticationError  # The server didn't accept the username/password combination.\nSMTP.SMTPNotSupportedError  # The AUTH command is not supported by the server.\nSMTP.SMTPException  # No suitable authentication method was found.\n\nSMTP.starttls(keyfile=None, certfile=None, **kwargs)  # Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted\n# from_addr & to_addrs are used to construct the message envelope used by the transport agents. sendmail does not modify the message headers in any way.\n# msg may be a string containing characters in the ASCII range, or a byte string. A string is encoded to bytes using the ascii codec, and lone \\r and \\n characters are converted to \\r\\n characters. A byte string is not modified.\nSMTP.sendmail(from_addr, to_addrs, msg, **kwargs)\n# from_addr: {string} -- RFC 822 from-address string\n# ro_addrs: {string, list of strings} -- list of RFC 822 to-address strings\n# msg: {string} -- message string\n\n# This is a convenience method for calling sendmail() with the message represented by an email.message.Message object.\nSMTP.send_message(msg, from_addr=None, to_addrs=None, **kwargs)\n# from_addr: {string} -- RFC 822 from-address string\n# ro_addrs: {string, list of strings} -- list of RFC 822 to-address strings\n# msg: {email.message.Message object} -- message string\nSMTP.quit()  # Terminate the SMTP session and close the connection. Return the result of the SMTP QUIT command\n
"},{"location":"languages/python/modules/socket.html","title":"Socket Module","text":""},{"location":"languages/python/modules/socket.html#definition","title":"Definition","text":"

A network socket is an internal endpoint for sending or receiving data within a node on a computer network.

In practice, socket usually refers to a socket in an Internet Protocol (IP) network, in particular for the Transmission Control Protocol (TCP), which is a protocol for one-to-one connections. In this context, sockets are assumed to be associated with a specific socket address, namely the IP address and a port number for the local node, and there is a corresponding socket address at the foreign node (other node), which itself has an associated socket, used by the foreign process. Associating a socket with a socket address is called binding.

"},{"location":"languages/python/modules/socket.html#socket-creation-connection","title":"Socket Creation & Connection","text":"Python
import socket\n\n# socket over the internet, socket is a stream of data\nsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nsocket.connect = ((\"URL\", port: int))  # connect to socket\nsocket.close()  # close connection\n
"},{"location":"languages/python/modules/socket.html#making-http-requests","title":"Making HTTP Requests","text":"Python
import socket\nHTTP_Method = \"GET http://url/resource HTTP/version\\n\\n\".encode()  # set HTTP request (encoded string from UTF-8 to bytes)\nsocket.send(HTTP_Method)   # make HTTP request\n\ndata = socket.recv(buffer_size)  # receive data from socket\ndecoded = data.decode()  # decode data (from bytes to UTF-8)\n
"},{"location":"languages/python/modules/sqlite.html","title":"sqlite3 Module","text":""},{"location":"languages/python/modules/sqlite.html#connecting-to-the-database","title":"Connecting To The Database","text":"

To use the module, you must first create a Connection object that represents the database.

Python
import sqlite3\nconnection = sqlite3.connect(\"file.db\")\n

Once you have a Connection, you can create a Cursor object and call its execute() method to perform SQL commands.

Python
cursor = connection.cursor()\n\ncursor.execute(sql)\nexecutemany(sql, seq_of_parameters)  # Executes an SQL command against all parameter sequences or mappings found in the sequence seq_of_parameters.\n\ncursor.close()  # close the cursor now\n# ProgrammingError exception will be raised if any operation is attempted with the cursor.\n

The data saved is persistent and is available in subsequent sessions.

"},{"location":"languages/python/modules/sqlite.html#query-construction","title":"Query Construction","text":"

Usually your SQL operations will need to use values from Python variables. You shouldn't assemble your query using Python's string operations because doing so is insecure: it makes your program vulnerable to an SQL injection attack

Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor's execute() method.

Python
# Never do this -- insecure!\nc.execute(\"SELECT * FROM stocks WHERE symbol = value\")\n\n# Do this instead\nt = ('RHAT',)\nc.execute('SELECT * FROM stocks WHERE symbol=?', t)\nprint(c.fetchone())\n\n# Larger example that inserts many records at a time\npurchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),\n             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n            ]\nc.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)\n
"},{"location":"languages/python/modules/sqlite.html#writing-operations-to-disk","title":"Writing Operations to Disk","text":"Python
cursor = connection.cursor()\ncursor.execute(\"SQL\")\nconnection.commit()\n
"},{"location":"languages/python/modules/sqlite.html#multiple-sql-instructions","title":"Multiple SQL Instructions","text":"Python
connection = sqlite3.connect(\"file.db\")\ncur = con.cursor()\ncur.executescript(\"\"\"\n    QUERY_1;\n    QUERY_2;\n    ...\n    QUERY_N;\n    \"\"\")\n\ncon.close()\n
"},{"location":"languages/python/modules/sqlite.html#retrieving-records","title":"Retrieving Records","text":"Python
# Fetches the next row of a query result set, returning a single sequence.\n# Returns None when no more data is available.\ncursor.fetchone()  \n\n# Fetches all (remaining) rows of a query result, returning a list.\n# An empty list is returned when no rows are available.\ncursor.fetchall()  \n\n# Fetches the next set of rows of a query result, returning a list.\n# An empty list is returned when no more rows are available.\nfetchmany(size=cursor.arraysize)\n

The number of rows to fetch per call is specified by the size parameter. If it is not given, the cursor's arraysize determines the number of rows to be fetched. The method should try to fetch as many rows as indicated by the size parameter. If this is not possible due to the specified number of rows not being available, fewer rows may be returned.

Note there are performance considerations involved with the size parameter. For optimal performance, it is usually best to use the arraysize attribute. If the size parameter is used, then it is best for it to retain the same value from one fetchmany() call to the next.

"},{"location":"languages/python/modules/time-datetime.html","title":"Time & Datetime","text":""},{"location":"languages/python/modules/time-datetime.html#time","title":"Time","text":"Python
# epoch: elapsed time in seconds (in UNIX starts from 01-010-1970)\nimport time # UNIX time\nvariable = time.time () # returns the time (in seconds) elapsed since 01-01-1970\nvariable = time.ctime (epochseconds) # transform epoch into date\n\nvar = time.perf_counter () # returns the current running time\n# execution time = start time - end time\n
"},{"location":"languages/python/modules/time-datetime.html#timesrtfrime-format","title":"time.srtfrime() format","text":"Format Data %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name. %c Locale's appropriate date and time representation. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %I Hour (12-hour clock) as a decimal number [01,12]. %j Day of the year as a decimal number [001,366]. %m Month as a decimal number [01,12]. %M Minute as a decimal number [00,59]. %p Locale's equivalent of either AM or PM. %S Second as a decimal number [00,61]. %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. %x Locale's appropriate date representation. %X Locale's appropriate time representation. %y Year without century as a decimal number [00,99]. %Y Year with century as a decimal number. %z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM %Z Time zone name (no characters if no time zone exists). %% A literal % character."},{"location":"languages/python/modules/time-datetime.html#datetime","title":"Datetime","text":"Python
import datetime\ntoday = datetime.date.today () # returns current date\ntoday = datetime.datetime.today () # returns the current date and time\n\n# formatting example\nprint ('Current Date: {} - {} - {}' .format (today.day, today.month, today.year))\nprint ('Current Time: {}: {}. {}' .format (today.hour, today.minute, today.second))\n\nvar_1 = datetime.date (year, month, day) # create date object\nvar_2 = datetime.time (hour, minute, second, micro-second) # create time object\ndt = datetime.combine (var_1, var_2) # combine date and time objects into one object\n\ndate_1 = datetime.date ('year', 'month', 'day')\ndate_2 = date_1.replace (year = 'new_year')\n\n#DATETIME ARITHMETIC\ndate_1 - date_2 # -> datetime.timedelta (num_of_days)\ndatetime.timedelta # duration expressing the difference between two date, time or datetime objects\n
"},{"location":"languages/python/modules/unittest.html","title":"Unittest Module","text":"Python
import unittest\nimport module_under_test\n\nclass Test(unittest.TestCase):\n\n    def test_1(self):\n        self.assert*(output, expected_output)\n\nif __name__ == '__main__':\n    unittest.main()\n
"},{"location":"languages/python/modules/unittest.html#testcase-class","title":"TestCase Class","text":"

Instances of the TestCase class represent the logical test units in the unittest universe. This class is intended to be used as a base class, with specific tests being implemented by concrete subclasses. This class implements the interface needed by the test runner to allow it to drive the tests, and methods that the test code can use to check for and report various kinds of failure.

"},{"location":"languages/python/modules/unittest.html#assert-methods","title":"Assert Methods","text":"Method Checks that assertEqual(a, b) a == b assertNotEqual(a, b) a != b assertTrue(x) bool(x) is True assertFalse(x) bool(x) is False assertIs(a, b) a is b assertIsNot(a, b) a is not b assertIsNone(x) x is None assertIsNotNone(x) x is not None assertIn(a, b) a in b assertNotIn(a, b) a not in b assertIsInstance(a, b) isinstance(a, b) assertNotIsInstance(a, b) not isinstance(a, b) Method Checks that assertRaises(exc, fun, *args, **kwds) fun(*args, **kwds) raises exc assertRaisesRegex(exc, r, fun, *args, **kwds) fun(*args, **kwds) raises exc and the message matches regex r assertWarns(warn, fun, *args, **kwds) fun(*args, **kwds) raises warn assertWarnsRegex(warn, r, fun, *args, **kwds) fun(*args, **kwds) raises warn and the message matches regex r assertLogs(logger, level) The with block logs on logger with minimum level Method Checks that assertAlmostEqual(a, b) round(a-b, 7) == 0 assertNotAlmostEqual(a, b) round(a-b, 7) != 0 assertGreater(a, b) a > b assertGreaterEqual(a, b) a >= b assertLess(a, b) a < b assertLessEqual(a, b) a <= b assertRegex(s, r) r.search(s) assertNotRegex(s, r) not r.search(s) assertCountEqual(a, b) a and b have the same elements in the same number, regardless of their order. Method Used to compare assertMultiLineEqual(a, b) strings assertSequenceEqual(a, b) sequences assertListEqual(a, b) lists assertTupleEqual(a, b) tuples assertSetEqual(a, b) sets or frozensets assertDictEqual(a, b) dicts"},{"location":"languages/rust/cargo.html","title":"Cargo build system and package manager","text":""},{"location":"languages/rust/cargo.html#creating-a-project","title":"Creating a project","text":"PowerShell
cargo new project_name  # creates project folder and basic files\ncargo new --vcs=git project_name  # init project as git repo\n
"},{"location":"languages/rust/cargo.html#building-running-checking-a-project","title":"Building, Running & Checking a project","text":"

Inside the project directory:

PowerShell
cargo build  # build project and download eventual needed dependencies\ncargo build --release  # build project for release (build + optimisations)\ncargo run  # executes the built executable\ncargo check  # verifies buildability without producing an executable\n
"},{"location":"languages/rust/cargo.html#dependencies","title":"Dependencies","text":"

In Cargo.toml:

TOML
[dependencies]\ncrate_name = \"<version_number>\"\n
"},{"location":"languages/rust/cargo.html#code-organization","title":"Code Organization","text":"

Rust has a number of features that allow to manage the code's organization, including which details are exposed, which details are private, and what names are in each scope in the programs.

These features, sometimes collectively referred to as the module system, include:

"},{"location":"languages/rust/cargo.html#packages-crates","title":"Packages & Crates","text":"

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. 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. 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. 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.

"},{"location":"languages/rust/cargo.html#modules","title":"Modules","text":"

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 module and 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.

"},{"location":"languages/rust/cargo.html#paths","title":"Paths","text":"

A path can take two forms:

Both absolute and relative paths are followed by one or more identifiers separated by double colons (::).

Rust
module::function();  // rel path (same crate)\nsuper::function();;  // rel path starting in outer module (same crate)\n\ncrate::module::function();  // abs path (same crate)\n<crate_name>::module::function();  // abs path (other crate)\n
"},{"location":"languages/rust/cargo.html#public-vs-private","title":"Public vs Private","text":"

Modules aren\u2019t useful only for organizing the code. They also define Rust\u2019s privacy boundary: the line that encapsulates the implementation details external code isn\u2019t 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\u2019t 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\u2019re defined.

Rust
mod module {\n    fn func() {}\n}\n\n// for a function to be accessible both module and function must be public\npub mod public_module {\n    pub fn public_func() {}\n}\n\nmod file_level_module;  // define a module for the whole file (same name as file)\n

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.

"},{"location":"languages/rust/cargo.html#use","title":"use","text":"Rust
use <crate_name>::module;  // import module (abs path, other crate)\nuse crate::module;  // import module (abs path, same crate)\nuse self::module;  // import module (rel path, same crate)\n\nuse <crate_name>::module as alias;  // import module w/ aliases\npub use <crate_name>::module;  // re-exporting (import and make available to others)\n\nuse <crate_name>::module::{self, Item}; // import multiple paths\npub use <crate_name>::module::*; // import all public items (Glob operator)\n\nmodule::function();  // use func w/ shorter path\n
"},{"location":"languages/rust/cargo.html#separating-into-multiple-files","title":"Separating into multiple files","text":"Text Only
src\n|_main.rs  --> default executable file\n|_lib.rs  --> default library file\n|__module\n|  |_mod.rs --> export submodules\n|  |_submodule.rs --> submodule\n
Rust
// main.rs\nmod module;  // declare module directory as a module\n\n// mod.rs\npub mod sub_module;  // declare sub_module file as a module\n
"},{"location":"languages/rust/concurrency.html","title":"Concurrency","text":"

Rust Book - Concurrency Rust Atomics and Locks - Mara Bos

Operating systems isolate processes from each other as much as possible, allowing a program to do its thing while completely unaware of what any other processes are doing. For example, a process cannot normally access the memory of another process, or communicate with it in any way, without asking the operating system\u2019s kernel first.

However, a program can spawn extra threads of execution, as part of the same process. Threads within the same process are not isolated from each other. Threads share memory and can interact with each other through that memory.

"},{"location":"languages/rust/concurrency.html#threads","title":"Threads","text":"

Every program starts with exactly one thread: the main thread. This thread will execute the main function and can be used to spawn more threads if necessary.

New threads are spawned using the std::thread::spawn function from the standard library. It takes a single argument: the function the new thread will execute. The thread stops once this function returns.

Returning from main will exit the entire program, even if other threads are still running. To make sure the spawned threads have finished their work it's possible to wait by joining them.

Rust
// spawn a new thread\nlet handle = std::thread::spawn(move || {\n\n    // read the current thread ID\n    let thread_id = std::thread::current().id();\n});\n\n// wait for the thread to finish by joining it\nhandle.join();\n

Since a thread might run until the very end of the program\u2019s execution, the spawn function has a 'static lifetime bound on its argument type. In other words, it only accepts functions that may be kept around forever. A closure capturing a local variable by reference may not be kept around forever, since that reference would become invalid the moment the local variable ceases to exist.

Getting a value back out of the thread is done by returning it from the closure. This return value can be obtained from the Result returned by the join method.

Note: if a thread panics the handle will return the panic message so that it can be handled.

Rust
let numbers = Vec::from_iter(0..=1000);\n\n// `move` ensures the tread takes ownership by move the data\nlet handle = thread::spawn(move || {\n    let len = numbers.len();\n    let sum = numbers.iter().sum::<usize>();\n    sum / len\n});\n\n\nlet average = handle.join().unwrap();\n
"},{"location":"languages/rust/concurrency.html#scoped-threads","title":"Scoped Threads","text":"

Scoped threads ensure that all thread spawned within a scope do not outlive said scope. This makes possible to borrow data that outlives the scope. This is possible since the scope spawn function does not have a 'static bound.

Note: it's not possible to spawn multiple threads sharing the same data is one of the is mutating it.

Rust
let numbers = Vec::from_iter(0..=10);\n\nstd::thread::scope(|scope| {\n    // data is borrowed since the `move` keyword is missing\n    scope.spawn(|| { \n        let len = numbers.len(); \n        // ...\n    });\n\n    scope.spawn(|| { /* ... */ });\n});\n
"},{"location":"languages/rust/concurrency.html#shared-ownership","title":"Shared Ownership","text":"

When sharing data between two threads where neither thread is guaranteed to outlive the other, neither of them can be the owner of that data. Any data shared between them will need to live as long as the longest living thread.

There are several ways to create data that is not owned by any single thread:

"},{"location":"languages/rust/concurrency.html#thread-safety-send-and-sync","title":"Thread Safety: Send and Sync","text":"

The Send marker trait indicates that ownership of values of the type implementing Send can be transferred between threads. Any type composed entirely of Send types is automatically marked as Send. Almost all primitive types are Send, aside from raw pointers.

The Sync marker trait indicates that it is safe for the type implementing Sync to be referenced from multiple threads. In other words, any type T is Sync if &T (an immutable reference to T) is Send, meaning the reference can be sent safely to another thread. Similar to Send, primitive types are Sync, and types composed entirely of types that are Syncare also Sync.

Note: All primitive types such as i32, bool, and str are both Send and Sync.

"},{"location":"languages/rust/concurrency.html#locking-protecting-shared-data","title":"Locking: Protecting Shared Data","text":""},{"location":"languages/rust/concurrency.html#mutex","title":"Mutex","text":"

The most commonly used tool for sharing (mutable) data between threads is a mutex, which is short for \"mutual exclusion.\" The job of a mutex is to ensure threads have exclusive access to some data by temporarily blocking other threads that try to access it at the same time.

A mutex has only two states: locked and unlocked.

When a thread locks an unlocked mutex, the mutex is marked as locked and the thread can immediately continue. When a thread then attempts to lock an already locked mutex, that operation will block. The thread is put to sleep while it waits for the mutex to be unlocked. Unlocking is only possible on a locked mutex, and should be done by the same thread that locked it. If other threads are waiting to lock the mutex, unlocking will cause one of those threads to be woken up, so it can try to lock the mutex again and continue its course.

Protecting data with a mutex is simply the agreement between all threads that they will only access the data when they have the mutex locked. That way, no two threads can ever access that data concurrently and cause a data race.

The Rust standard library provides this functionality through std::sync::Mutex<T>. Since the mutex wraps and owns the T it protects, the data can only be accessed through the mutex, allowing for a safe interface that can guarantee only one thread at a time can access the wrapped T.

To ensure a locked mutex can only be unlocked by the thread that locked it, it does not have an unlock() method. Instead, its lock() method returns a a MutexGuard to represent the lock. The MutexGuard allows exclusive access to the data the mutex protects. Unlocking the mutex is done by dropping the guard.

Rust
let mutex = std::sync::Mutex::new(0);\n\nstd::thread::scope(|scope| {\n    scope.spawn(|| {\n        let guard = mutex.lock().unwrap();  // obtain access\n        *guard += 1;  // mutate protected value\n    })\n});\n
"},{"location":"languages/rust/concurrency.html#lock-poisoning","title":"Lock Poisoning","text":"

The lock() method returns a Result since the mutex can become poisoned. A mutex get marked as poisoned when a thread panics while holding the lock. Calling lock() on a poisoned mutex will return an Err. This poisoning mechanism protects against accessing data that may be in an inconsistent state.

Note: The lock is still acquired and the Err variant contains the guard, allowing to correct the data inconsistency.

"},{"location":"languages/rust/concurrency.html#reader-writer-lock","title":"Reader-Writer Lock","text":"

A reader-writer lock understands the difference between exclusive and shared access, and can provide either. It has three states: unlocked, locked by a single writer (for exclusive access), and locked by any number of readers (for shared access).

The Rust standard library provides this lock through the std::sync::RwLock<T> type. It has a read() and write() method for locking as either a reader or a writer and it has two guard types: RwLockReadGuard and RwLockWriteGuard.

The first only implements Deref to behave like a shared reference to the protected data, while the second also implements DerefMut to behave like an exclusive reference.

Most implementations will block new readers when there is a writer waiting, even when the lock is already read-locked. This is done to prevent writer starvation, a situation where many readers collectively keep the lock from ever unlocking, never allowing any writer to update the data.

"},{"location":"languages/rust/concurrency.html#waiting-putting-thread-to-sleep","title":"Waiting: Putting Thread to Sleep","text":""},{"location":"languages/rust/concurrency.html#thread-parking","title":"Thread Parking","text":"

One way to wait for a notification from another thread is called thread parking. A thread can park itself, which puts it to sleep, stopping it from consuming any CPU cycles. Another thread can then unpark the parked thread, waking it up from its sleep.

Thread parking is available through the std::thread::park() function. For unparking, it's possible to call the unpark() method on a Thread handle.

An important property of thread parking is that a call to unpark() before the thread parks itself does not get lost. The request to unpark is still recorded, and the next time the thread tries to park itself, it clears that request and directly continues without actually going to sleep.

Note: calls to unpark() do not stack up.

"},{"location":"languages/rust/concurrency.html#condition-variables","title":"Condition Variables","text":"

Condition variables are a more commonly used option for waiting for something to happen to data protected by a mutex. They have two basic operations: wait and notify.

Threads can wait on a condition variable, after which they can be woken up when another thread notifies that same condition variable. Multiple threads can wait on the same condition variable, and notifications can either be sent to one waiting thread, or to all of them.

To avoid the issue of missing notifications in the brief moment between unlocking a mutex and waiting for a condition variable, condition variables provide a way to atomically unlock the mutex and start waiting. This means there is simply no possible moment for notifications to get lost.

The Rust standard library provides a condition variable as std::sync::Condvar. Its wait method takes a MutexGuard that proves we\u2019ve locked the mutex. It first unlocks the mutex (allowing other threads to work on it) and goes to sleep. When woken up, it relocks the mutex and returns a new MutexGuard (which proves that the mutex is locked again).

It has two notify functions: notify_one to wake up just one waiting thread (if any), and notify_all to wake them all up.

"},{"location":"languages/rust/concurrency.html#atomics","title":"Atomics","text":"

The word atomic comes from the Greek word \u1f04\u03c4\u03bf\u03bc\u03bf\u03c2, meaning indivisible, something that cannot be cut into smaller pieces. In computer science, it is used to describe an operation that is indivisible: it is either fully completed, or it didn\u2019t happen yet.

Atomic operations are the main building block for anything involving multiple threads. All the other concurrency primitives, such as mutexes and condition variables, are implemented using atomic operations.

Each of the available atomic types has the same interface with methods for storing and loading, methods for atomic \"fetch-and-modify\" operations, and some more advanced \"compare-and-exchange\" methods.

Every atomic operation takes an argument of type std::sync::atomic::Ordering, which determines the guarantees about the relative ordering of operations. Based on the ordering the various threads can witness the same operations happening in different orders.

"},{"location":"languages/rust/concurrency.html#load-store","title":"Load & Store","text":"

The first two atomic operations are the most basic ones: load and store. Their function signatures are as follows, using AtomicI32 as an example:

Rust
impl AtomicI32 {\n    pub fn load(&self, ordering: Ordering) -> i32;\n    pub fn store(&self, value: i32, ordering: Ordering);\n}\n

The load method atomically loads the value stored in the atomic variable, and the store method atomically stores a new value in it.

Note: the store method takes a shared reference (&T) even though it modifies itself.

"},{"location":"languages/rust/concurrency.html#fetch-and-modify-operations","title":"Fetch-and-Modify Operations","text":"

The fetch-and-modify operations modify the atomic variable, but also load (fetch) the original value, as a single atomic operation.

Rust
impl AtomicI32 {\n    pub fn fetch_add(&self, v: i32, ordering: Ordering) -> i32;\n    pub fn fetch_sub(&self, v: i32, ordering: Ordering) -> i32;\n    pub fn fetch_or(&self, v: i32, ordering: Ordering) -> i32;\n    pub fn fetch_and(&self, v: i32, ordering: Ordering) -> i32;\n    pub fn fetch_nand(&self, v: i32, ordering: Ordering) -> i32;\n    pub fn fetch_xor(&self, v: i32, ordering: Ordering) -> i32;\n    pub fn fetch_max(&self, v: i32, ordering: Ordering) -> i32;\n    pub fn fetch_min(&self, v: i32, ordering: Ordering) -> i32;\n    pub fn swap(&self, v: i32, ordering: Ordering) -> i32;  // aka fetch_store\n}\n
"},{"location":"languages/rust/concurrency.html#compare-and-exchange-operations","title":"Compare-and-Exchange Operations","text":"

The compare-and-exchange operation checks if the atomic value is equal to a given value, and only if that is the case does it replace it with a new value, all atomically as a single operation. It will return the previous value and tell whether it replaced it or not.

Rust
impl AtomicI32 {\n    pub fn compare_exchange(\n        &self,\n        expected: i32,\n        new: i32,\n        success_order: Ordering,\n        failure_order: Ordering\n    ) -> Result<i32, i32>;\n}\n
"},{"location":"languages/rust/concurrency.html#memory-ordering","title":"Memory Ordering","text":""},{"location":"languages/rust/concurrency.html#reordering-and-optimizations","title":"Reordering and Optimizations","text":"

Processors and compilers perform tricks to make programs run as fast as possible. A processor might determine that two particular consecutive instructions in the program will not affect each other, and execute them out of order, if that is faster. Similarly, a compiler might decide to reorder or rewrite parts of the program if it has reason to believe it might result in faster execution. But only if that wouldn\u2019t change the behavior of the program.

The logic for verifying that a specific reordering or other optimization won\u2019t affect the behavior of the program does not take other threads into account. This is why explicitly telling the compiler and processor what they can and can\u2019t do with the atomic operations it's necessary, since their usual logic ignores interactions between threads and might allow for optimizations that do change the result of the program.

The available orderings in Rust are:

"},{"location":"languages/rust/concurrency.html#the-memory-model","title":"The Memory Model","text":"

The different memory ordering options have a strict formal definition to make sure their assumption are known, and compiler writers know exactly what guarantees they need to provide. To decouple this from the details of specific processor architectures, memory ordering is defined in terms of an abstract memory model.

Rust\u2019s memory model allows for concurrent atomic stores, but considers concurrent non-atomic stores to the same variable to be a data race, resulting in undefined behavior.

"},{"location":"languages/rust/concurrency.html#happens-before-relationship","title":"Happens-Before Relationship","text":"

The memory model defines the order in which operations happen in terms of happens-before relationships. This means that as an abstract model only defines situations where one thing is guaranteed to happen before another thing, and leaves the order of everything else undefined.

Between threads, however, happens-before relationships only occur in a few specific cases, such as when spawning and joining a thread, unlocking and locking a mutex, and through atomic operations that use non-relaxed memory ordering. Relaxed memory ordering is the most basic (and most performant) memory ordering that, by itself, never results in any cross-thread happens-before relationships.

Spawning a thread creates a happens-before relationship between what happened before the spawn() call, and the new thread. Similarly, joining a thread creates a happens-before relationship between the joined thread and what happens after the join() call.

Rust
static X: AtomicI32 = AtomicI32::new(0);\n\nfn main() {\n    X.store(1, Relaxed);\n\n    let t = thread::spawn(f);  // happens after \"store 1\"\n    X.store(2, Relaxed);\n    t.join().unwrap();  // happens before \"store 3\"\n\n    X.store(3, Relaxed);\n}\n\nfn f() {\n    let x = X.load(Relaxed);  // could happen after either before or after \"store 2\"\n    assert!(x == 1 || x == 2);\n}\n
"},{"location":"languages/rust/concurrency.html#relaxed-ordering","title":"Relaxed Ordering","text":"

While atomic operations using Relaxed memory ordering do not provide any happens-before relationship, they do guarantee a total modification order of each individual atomic variable. This means that all modifications of the same atomic variable happen in an order that is the same from the perspective of every single thread.

"},{"location":"languages/rust/concurrency.html#release-and-acquire-ordering","title":"Release and Acquire Ordering","text":"

Release and Acquire memory ordering are used in a pair to form a happens-before relationship between threads. Release memory ordering applies to store operations, while Acquire memory ordering applies to load operations.

A happens-before relationship is formed when an acquire-load operation observes the result of a release-store operation. In this case, the store and everything before it, happened before the load and everything after it.

When using Acquire for a fetch-and-modify or compare-and-exchange operation, it applies only to the part of the operation that loads the value. Similarly, Release applies only to the store part of an operation. AcqRel is used to represent the combination of Acquire and Release, which causes both the load to use Acquire ordering, and the store to use Release ordering.

Rust
use std::sync::atomic::Ordering::{Acquire, Release};\n\nstatic DATA: AtomicU64 = AtomicU64::new(0);\nstatic READY: AtomicBool = AtomicBool::new(false);\n\nfn main() {\n    thread::spawn(|| {\n        DATA.store(123, Relaxed);\n        READY.store(true, Release); // Everything from before this store ..\n    });\n\n    while !READY.load(Acquire) { // .. is visible after this loads `true`.\n        thread::sleep(Duration::from_millis(100));\n        println!(\"waiting...\");\n    }\n    println!(\"{}\", DATA.load(Relaxed));\n}\n
"},{"location":"languages/rust/concurrency.html#consume-ordering","title":"Consume Ordering","text":"

Consume ordering is a lightweight, more efficient, \u200bvariant of Acquire ordering, whose synchronizing effects are limited to things that depend on the loaded value.

Now there\u2019s good news and bad news.

In all modern processor architectures, Consume ordering is achieved with the exact same instructions as Relaxed ordering. In other words, Consume ordering can be \"free,\" which, at least on some platforms, is not the case for acquire ordering. Unfortunately no compiler actually implements Consume ordering.

The concept of a \"dependent\" evaluation hard to define, it\u2019s even harder to keep such dependencies intact while transforming and optimizing a program.

Because of this, compilers upgrade Consume ordering to Acquire ordering, just to be safe. The C++20 standard even explicitly discourages the use of Consume ordering, noting that an implementation other than just Acquire ordering turned out to be infeasible.

"},{"location":"languages/rust/concurrency.html#sequentially-consistent-ordering","title":"Sequentially Consistent Ordering","text":"

The strongest memory ordering is ssequentially consistent ordering (SeqCst). It includes all the guarantees of Acquire ordering (for loads) and Release ordering (for stores), and also guarantees a globally consistent order of operations.

This means that every single operation using SeqCst ordering within a program is part of a single total order that all threads agree on. This total order is consistent with the total modification order of each individual variable.

Since it is strictly stronger than Acquire and Release memory ordering, a sequentially consistent load or store can take the place of an acquire-load or release-store in a release-acquire pair to form a happens-before relationship. In other words, an acquire-load can not only form a happens-before relationship with a release-store, but also with a sequentially consistent store, and similarly the other way around.

Virtually all real-world uses of SeqCst involve a pattern of a store that must be globally visible before a subsequent load on the same thread. For these situations, a potentially more efficient alternative is to instead use Relaxed operations in combination with a SeqCst fence.

"},{"location":"languages/rust/concurrency.html#fences","title":"Fences","text":"

The std::sync::atomic::fence function represents an atomic fence and is either a release fence (Release), an acquire fence (Acquire), or both (AcqRel or SeqCst). A SeqCst fence additionally also takes part in the sequentially consistent total order.

An atomic fence allows to separate the memory ordering from the atomic operation. This can be useful to apply a memory ordering to multiple operations, or to apply it conditionally.

In essence, a release-store can be split into a release fence followed by a (Relaxed) store, and an acquire-load can be split into a (Relaxed) load followed by an acquire fence.

Rust
// The store of a release-acquire relationship\natom.store(1, Release);\n\n// can be substituted by a release fence followed by a relaxed store\nfence(Release);\natom.store(1, Relaxed);\n
Rust
// The load of a release-acquire relationship,\natom.load(Acquire);\n\n// can be substituted by a relaxed load followed by an acquire fence\natom.load(Relaxed);\nfence(Acquire);\n

Note: Using a separate fence can result in an extra processor instruction which can be slightly less efficient. Note: A fence is not tied to any single atomic variable. This means that a single fence can be used for multiple variables at once.

A release fence can take the place of a release operation in a happens-before relationship if that release fence is followed (on the same thread) by any atomic operation that stores a value observed by the acquire operation it's synchronizing with. Similarly, an acquire fence can take the place of any acquire operation if that acquire fence is preceded (on the same thread) by any atomic operation that loads a value stored by the release operation.

An happens-before relationship is created between a release fence and an acquire fence if any store after the release fence is observed by any load before the acquire fence.

A SeqCst fence is both a Release fence and an Acquire fence (just like AcqRel), but also part of the single total order of sequentially consistent operations. However, only the fence is part of the total order, but not necessarily the atomic operations before or after it. This means that unlike a release or acquire operation, a sequentially consistent operation cannot be split into a relaxed operation and a memory fence.

"},{"location":"languages/rust/macros.html","title":"Macros","text":"

Fundamentally, macros are a way of writing code that writes other code, which is known as metaprogramming.

Metaprogramming is useful for reducing the amount of code to be written and maintained, which is also one of the roles of functions. However, macros have some additional powers that functions don\u2019t.

A function signature must declare the number and type of parameters the function has. Macros, on the other hand, can take a variable number of parameters. Also, macros are expanded before the compiler interprets the meaning of the code, so a macro can, for example, implement a trait on a given type. A function can\u2019t, because it gets called at runtime and a trait needs to be implemented at compile time.

The downside to implementing a macro instead of a function is that macro definitions are more complex than function definitions because it's Rust code that writes Rust code. Due to this indirection, macro definitions are generally more difficult to read, understand, and maintain than function definitions.

Note: macros need to be defined and brought into scope before they are usable in a file, as opposed to functions that can be defined anywhere and be called anywhere.

"},{"location":"languages/rust/macros.html#declarative-macros-macro-by-example","title":"Declarative Macros (Macro-by-Example)","text":"

At their core, declarative macros allow to write something similar to a Rust match expression.

Macros compare a value to patterns that are associated with particular code: in this situation, the value is the literal Rust source code passed to the macro; the patterns are compared with the structure of that source code; and the code associated with each pattern, when matched, replaces the code passed to the macro. This all happens during compilation.

Declarative macros are defined using the macro_rules! construct.

Each macro has a name, and one or more rules.

Each rule has two parts: a matcher, describing the syntax that it matches, and a transcriber, describing the syntax that will replace a successfully matched invocation. Both the matcher and the transcriber must be surrounded by delimiters. Macros can expand to expressions, statements, items (including traits, impls, and foreign items), types, or patterns.

Rust
#[macro_export]\nmacro_rules! <name> {\n    ( <matcher> ) => {\n        <transcriber>\n    };\n}\n
"},{"location":"languages/rust/macros.html#transcribing","title":"Transcribing","text":"

When a macro is invoked, the macro expander looks up macro invocations by name, and tries each macro rule in turn. It transcribes the first successful match; if this results in an error, then future matches are not tried.

When matching, no lookahead is performed; if the compiler cannot unambiguously determine how to parse the macro invocation one token at a time, then it is an error.

In both the matcher and the transcriber, the $ token is used to invoke special behaviours from the macro engine. Tokens that aren't part of such an invocation are matched and transcribed literally, with one exception.

The exception is that the outer delimiters for the matcher will match any pair of delimiters. Thus, for instance, the matcher (()) will match {()} but not {{}}.

Note: The character $ cannot be matched or transcribed literally.

When forwarding a matched fragment to another macro-by-example, matchers in the second macro will see an opaque AST of the fragment type. The second macro can't use literal tokens to match the fragments in the matcher, only a fragment specifier of the same type. The ident, lifetime, and tt fragment types are an exception, and can be matched by literal tokens.

Rust
macro_rules! foo {\n    (3) => {}\n}\n\nmacro_rules! bar {\n    ($l:expr) => { foo!($l); }\n    // ERROR:           ^^ no rules expected this token in macro call\n}\n\nmacro_rules! baz {\n    ($l:tt) => { foo!($l); }\n}\n
"},{"location":"languages/rust/macros.html#metavariables","title":"Metavariables","text":"

In the matcher, $name:fragment matches a Rust syntax fragment of the kind specified and binds it to the metavariable $name.

Valid fragment specifiers are:

In the transcriber, metavariables are referred to simply by $name, since the fragment kind is specified in the matcher. Metavariables are replaced with the syntax element that matched them.

The keyword metavariable $crate can be used to refer to the current crate. Metavariables can be transcribed more than once or not at all.

"},{"location":"languages/rust/macros.html#repetitions","title":"Repetitions","text":"

In both the matcher and transcriber, repetitions are indicated by placing the tokens to be repeated inside $(\u2026), followed by a repetition operator, optionally with a separator token between. The separator token can be any token other than a delimiter or one of the repetition operators, but ; and , are the most common.

The repetition operators are:

Note: Since ? represents at most one occurrence, it cannot be used with a separator.

The repeated fragment both matches and transcribes to the specified number of the fragment, separated by the separator token. Metavariables are matched to every repetition of their corresponding fragment.

During transcription, additional restrictions apply to repetitions so that the compiler knows how to expand them properly:

  1. A metavariable must appear in exactly the same number, kind, and nesting order of repetitions in the transcriber as it did in the matcher.
  2. Each repetition in the transcriber must contain at least one metavariable to decide how many times to expand it. If multiple metavariables appear in the same repetition, they must be bound to the same number of fragments.
"},{"location":"languages/rust/macros.html#scoping-exporting-and-importing","title":"Scoping, Exporting, and Importing","text":"

Macros have two forms of scope: textual scope, and path-based scope. Textual scope is based on the order that things appear in source files, or even across multiple files, and is the default scoping. Path-based scope works exactly the same way that item scoping does. The scoping, exporting, and importing of macros is controlled largely by attributes.

When a macro is invoked by an unqualified identifier (not part of a multi-part path), it is first looked up in textual scoping. If this does not yield any results, then it is looked up in path-based scoping. If the macro's name is qualified with a path, then it is only looked up in path-based scoping.

Rust
use lazy_static::lazy_static; // path-based import.\n\n// local textual definition.\nmacro_rules! lazy_static {\n    (lazy) => {};\n}\n\nlazy_static!{lazy} // textual lookup finds local macro first.\nself::lazy_static!{} // path-based lookup ignores local macro, finds imported one.\n

Note: It is not an error to define a macro multiple times; the most recent declaration will shadow the previous one unless it has gone out of scope.

"},{"location":"languages/rust/macros.html#the-macro_use-attribute","title":"The macro_use attribute","text":"

The macro_use attribute has two purposes. First, it can be used to make a module's macro scope not end when the module is closed, by applying it to a module:

Rust
#[macro_use]\nmod inner {\n    macro_rules! m {\n        () => {};\n    }\n}\n\nm!();\n

Second, it can be used to import macros from another crate, by attaching it to an extern crate declaration appearing in the crate's root module. Macros imported this way are imported into the macro_use prelude, not textually, which means that they can be shadowed by any other name.

While macros imported by #[macro_use] can be used before the import statement, in case of a conflict, the last macro imported wins. Optionally, a list of macros to import can be specified using the MetaListIdents syntax; this is not supported when #[macro_use] is applied to a module.

Rust
# [macro_use(lazy_static)] // or #[macro_use] to import all macros.\nextern crate lazy_static;\n\nlazy_static!{}\nself::lazy_static!{} // Error: lazy_static is not defined in `self`\n

Note: Macros to be imported with #[macro_use] must be exported with #[macro_export].

"},{"location":"languages/rust/macros.html#the-macro_export-attribute","title":"The macro_export attribute","text":"

By default, a macro has no path-based scope. However, if it has the #[macro_export] attribute, then it is declared in the crate root scope and can be referred to normally.

Rust
self::m!();\nm!(); // OK: Path-based lookup finds m in the current module.\n\nmod inner {\n    super::m!();\n    crate::m!();\n}\n\nmod mac {\n    #[macro_export]\n    macro_rules! m {\n        () => {};\n    }\n}\n

Note: Macros labeled with #[macro_export] are always pub and can be referred to by other crates, either by path or by #[macro_use].

"},{"location":"languages/rust/macros.html#follow-set-ambiguity-restrictions","title":"Follow-set Ambiguity Restrictions","text":"

The parser used by the macro system is reasonably powerful, but it is limited in order to prevent ambiguity in current or future versions of the language.

In particular, in addition to the rule about ambiguous expansions, a nonterminal matched by a metavariable must be followed by a token which has been decided can be safely used after that kind of match.

The specific rules are:

All other fragment specifiers have no restrictions.

When repetitions are involved, then the rules apply to every possible number of expansions, taking separators into account. This means:

"},{"location":"languages/rust/rust.html","title":"Rust","text":""},{"location":"languages/rust/rust.html#basics","title":"Basics","text":"Rust
use <module>;  // bring a type into scope\n\nfn main() {  //program entry point\n    // code here\n}\n
"},{"location":"languages/rust/rust.html#standard-output","title":"Standard Output","text":"Rust
// macro (func have no \"!\")\nprintln!(\"Value: {}\", value);  // {} is a placeholder for a value or variable\nprintln!(\"Values: {1}, {0}\", value1, value2);  // use index to print values\n\nprintln!(\"Value {a}, {b}\", a = value1, b = value2);  // named parameters\nprintln!(\"Value {scoped_variable}\");  // reference a variable in scope (must not have any parameters)\n\nprintln!(\"Num: {:<total_digits>.<decimal_digits>}\", number);\nprintln!(\"Num: {:0<total>.<decimal>}\", number);  // prefix number with zeroes\n\nprintln!(\"{:b}\", 0b11011);  // print as bits\n\nprint!();\n
"},{"location":"languages/rust/rust.html#standard-input","title":"Standard Input","text":"Rust
use io;\n\nlet mut buffer = String::new();\n\nio::stdin()  // read line from stdin\n    .read_line(&mut buffer)  // put in into the string variable\n    .expect(\"Error Message\");  // in case of errors return an error message\n\nlet var: i32 = buffer.trim().parse()  // returns a Result enum\nlet var = buffer.trim().parse::<i32>()  // returns a Result enum\n

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.

"},{"location":"languages/rust/rust.html#variables-mutability","title":"Variables & Mutability","text":"

By default variables are immutable.

Rust
let var1 = value;  // immutable var init\nlet var2: Type = value;  // explicit type annotation\n\nlet mut var3 = value;  // mutable var init\nlet mut var4: Type = value;  // explicit type annotation\n\nconst CONSTANT_NAME: type = value;  // constant must have the type annotation\n
"},{"location":"languages/rust/rust.html#shadowing","title":"Shadowing","text":"

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.

Rust
let x: u32 = 10;\nlet x: i32 = 11;  // shadowing\n
"},{"location":"languages/rust/rust.html#data-types","title":"Data Types","text":""},{"location":"languages/rust/rust.html#integer-types","title":"Integer Types","text":"Length Signed Unsigned 8-bit i8 u8 16-bit i16 u16 32-bit i32 u32 64-bit i64 u64 128-bit i128 u128 architecture isize usize"},{"location":"languages/rust/rust.html#explicit-mathematical-operations-integers","title":"Explicit Mathematical Operations (Integers)","text":"Rust
i32::MAX.checked_add(value);  // Option<i32> => None if overflow\ni32::MAX.wrapping_add(value);  // i32 => Wrap around\ni32::MAX.saturating_add(value);  //  i32 => MIN <= x <= MAX (Clamp)\ni32::MAX.overflowing_add(value); // (i32, bool) => overflowed result and if overflowed\n

Note: analogous method exist for other mathematical operation

"},{"location":"languages/rust/rust.html#floating-point-types","title":"Floating-Point Types","text":"

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.

"},{"location":"languages/rust/rust.html#numeric-byte-literals","title":"Numeric & Byte Literals","text":"

Numeric Base Prefix:

Note: Number can have _ interposed for legibility (E.g: 1_000_u64)

Binary Literals:

"},{"location":"languages/rust/rust.html#numeric-operators","title":"Numeric Operators","text":"Operator Operation > Greater than >= Greater or Equal to < Less than <= Less or Equal to == Equals != Not Equals"},{"location":"languages/rust/rust.html#comparison-operators","title":"Comparison Operators","text":"Operator Operation + Addition - Subtraction * Multiplication / Division % Modulo"},{"location":"languages/rust/rust.html#boolean-types","title":"Boolean Types","text":"

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.

"},{"location":"languages/rust/rust.html#bitwise-operators","title":"Bitwise Operators","text":"Operator Operation & AND | OR && SHORT-CIRCUIT AND || SHORT-CIRCUIT OR ^ XOR ! NOT << LEFT SHIFT >> RIGHT SHIFT"},{"location":"languages/rust/rust.html#character-types","title":"Character Types","text":"

Rust's char type is the language's most primitive alphabetic type.

Rust's char type is four bytes in size and represents a Unicode Scalar Value: range from U+0000 to U+D7FF and U+E000 to U+10FFFF inclusive.

Rust
let c: char = 'C';  // SINGLE QUOTES\nlet c: char = '\\u{261D}';  // Unicode Code Point U+261D\nlet c: char = '\\x2A';  // ASCII for *\n\n\n'*'.is_alphabetic();  // false\n'\u03b2'.is_alphabetic(); // true\n'8'.to_digit(10);  // Some(8)\n'\\u{CA0}'.len_utf8();  // 3\nstd::char::from:digit(2, 10);  // Some(2)\n
"},{"location":"languages/rust/rust.html#string-types","title":"String Types","text":"Rust
let s = String::new();  // create empty string\nlet s = String::from(\"string literal\");  // construct string from literal\n\n// string literals\nlet s = \"a multiline\n    string literal\"; // includes whitespace and new lines\n\nlet s = \"single line \\\n    string literal\";  // the trailing \\ avoids the new line & trailing/leading whitespace\n\n// raw strings\nlet raw = r\"\\d+(\\.\\d+)*\"  // backslash and whitespace included verbatim\nlet raw = r#\"raw literal with explicit delimiters, allows double quotes (\") inside\"#;\n\n// byte strings\nlet byte_string = b\"some bite string\"  // &[u8] => slice og u8, equal to &[b'E', b'q', ...]\n\ns.push_str(\"\"); // appending string literals\n
"},{"location":"languages/rust/rust.html#tuple-types","title":"Tuple Types","text":"

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.

Rust
let tup: (i32, f64, u8) = (500, 6.4, 1);\nlet tup = (500, 6.4, 1);\n\nlet (x, y, z) = tup;  // tuple deconstruction (unpacking)\n\ntup.0 = value;  // member access & update (mut be mutable)\n
"},{"location":"languages/rust/rust.html#array-types","title":"Array Types","text":"

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.

Rust
let array = [0, 1, 2, 3, 4];\nlet array: [Type; length] = [...];\nlet array: [value; length];  // repeat expression (same as python's [value] * length)\n\nlet index: usize = <index_value>;  // indexes and ranges must be of type usize\narray[index] = value;  // member access and update (must be mutable)\n\nlet matrix = [\n    [0 ,1, 2],\n    [3, 4, 5]\n]\n\nlet matrix: [[Type, length]; length]; = [[...], [...], ...]\n\nmatrix[row][column];\n
"},{"location":"languages/rust/rust.html#slice-types-t-mut-t","title":"Slice Types (&[T], &mut [T])","text":"

Slices allows to reference a contiguous sequence of elements in a collection rather than the whole collection. Slices don't take ownership.

A mutable slice &mut [T] allows to read and modify elements, but can\u2019t be shared; a shared slice &[T] allows to share access among several readers, but doesn\u2019t allow to modify elements.

&String can be used in place of a &str (string slice) trough String Coercion. The &String gets converted to a &str that borrows the entire string. The reverse is not possible since the slice lacks some information about the String.

Note: When working with functions is easier to always expect a &str instead of a &String.

Rust
let s = String::from(\"string literal\");\nlet slice: &str = &s[start..end];\n\nlet a = [0, 1, 2, 3, 4, 5];\nlet slice: &[i32] =  &a[start..end];\n\nsequence[start..]  // slice to end of sequence\nsequence[..end]  // slice from start to end (excluded)\n
"},{"location":"languages/rust/rust.html#type-aliases","title":"Type Aliases","text":"Rust
type Alias = T;\n
"},{"location":"languages/rust/rust.html#functions","title":"Functions","text":"

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. 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.

Rust
  // parameters MUST have the Type annotation\nfn func(param: Type) {}\n\n  // -> specifies the return type\nfn func() -> Type {}\n\nfn func() {\n    value  // returns value\n}\n// same as\nfn func() {\n    return value;\n}\n\nfn func() {\n    return (value1, value2, ...);  // return multiple values with tuples\n}\n
"},{"location":"languages/rust/rust.html#control-flow","title":"Control Flow","text":""},{"location":"languages/rust/rust.html#if-else-if-else","title":"if, else-if, else","text":"Rust
if condition {\n    // [...]\n} else if condition {\n    // [...]\n} else {\n    // [...]\n}\n
"},{"location":"languages/rust/rust.html#let-if","title":"let if","text":"Rust
let var = if condition { value } else { value };  // returned types must be the same\n
"},{"location":"languages/rust/rust.html#if-let","title":"if-let","text":"Rust
if let <pattern> = <expr> {\n    <block1>\n} else {\n    <block2>\n}\n\n// same as\nmatch <expr> {\n    <pattern> => { block1 }\n    _ => { block2 }\n}\n
"},{"location":"languages/rust/rust.html#loop","title":"loop","text":"Rust
// loop's forever if not explicitly stopped (return or break)\nloop { }\n
"},{"location":"languages/rust/rust.html#while-while-let","title":"while, while-let","text":"Rust
while condition { }\n\nwhile let <pattern> {}\n
"},{"location":"languages/rust/rust.html#for","title":"for","text":"Rust
for item in sequence.iter() { }\nfor item in sequence.iter_mut() { }  // iterate over mutable items\n\nfor item in sequence { }  // consumes the values (moved into item)\nfor item in &sequence { }  // doesn't consumes the values (item is a reference)\nfor item in &mut sequence { }\n\n// for (i = start; i < end; i += 1)\nfor i in (start..end) { }\n
"},{"location":"languages/rust/rust.html#range","title":"Range","text":"Rust
..  // RangeFull\na ..  // RangeFrom { start: a }\n.. b  // RangeTo { end: b }\na .. b  // Range { start: a, end: b }\n..= b  // RangeToInclusive { end: b }\na ..= b  // RangeInclusive::new(a, b)\n
"},{"location":"languages/rust/rust.html#break-continue","title":"break & continue","text":"Rust
while <condition> {\n    // [...]\n\n    continue;  // jump to condition evaluation\n}\n\nlet loop_result = loop {\n    // [...]\n\n    break <loop-value>;\n}\n\n'outer: loop {\n    // [...]\n    loop {}\n\n    break 'outer;  // break labeled loop\n}\n\nlet loop_result = 'outer: loop {\n    // [...]\n    loop {}\n\n    break 'outer <loop-value>; // break labeled loop and return value\n}\n
"},{"location":"languages/rust/rust.html#ownership","title":"Ownership","text":"

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. None of the ownership features slow down your program while it's running.

"},{"location":"languages/rust/rust.html#stack-heap","title":"Stack & Heap","text":"

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. 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. 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.

Keeping track of what parts of code are using what data on the heap, minimizing the amount of duplicate data on the heap, and cleaning up unused data on the heap so you don't run out of space are all problems that ownership addresses.

"},{"location":"languages/rust/rust.html#ownership-rules","title":"Ownership Rules","text":""},{"location":"languages/rust/rust.html#moving-cloning-copying-data","title":"Moving, Cloning & Copying data","text":"

A \"shallow copy\" of a variable allocated on the heap causes the original variable goes out of scope and only the \"copy\" remains (MOVING). A \"deep copy\" (var.clone()) makes a copy of the data in the new variable without make the original fall out of scope (CLONING).

When a variable goes out of scope, Rust calls the special function drop, where the code to return/free the memory is located.

Rust has a special annotation called the Copy trait that it's placeable on types that are stored on the stack. If a type has the Copy trait, an older variable is still usable after assignment.

Copies happen implicitly, for example as part of an assignment y = x. The behavior of Copy is not overloadable; it is always a simple bit-wise copy. Cloning is an explicit action, x.clone(). The implementation of Clone can provide any type-specific behavior necessary to duplicate values safely.

Rust won't allow to annotate a type with the Copy trait if the type, or any of its parts, has implemented the Drop trait.

Rust
let s = String::new()\nlet t = s;  // MOVE, s is now uninitialized\nlet u = t.clone();  // deep copy, t is still valid\n\nlet n: i32 = 1;\nlet x = n;  // x holds a COPY of the VALUE of n\n
"},{"location":"languages/rust/rust.html#ownership-functions","title":"Ownership & Functions","text":"

The semantics for passing a value to a function are similar to those for assigning a value to a variable. Passing a variable to a function will move or copy, just as assignment does.

Rust
fn main() {\n    let s = String::from(\"hello\");  // s comes into scope\n\n    takes_ownership(s);             // s's value moves into the function and so is no longer valid here\n\n    let x = 5;                      // x comes into scope\n\n    makes_copy(x);                  // x would move into the function, but i32 is Copy, so it's okay to still use x afterward\n\n} // Here, x goes out of scope, then s. But because s's value was moved, nothing special happens.\n\nfn takes_ownership(some_string: String) { // some_string comes into scope\n    println!(\"{}\", some_string);\n} // Here, some_string goes out of scope and `drop` is called. The backing memory is freed.\n\nfn makes_copy(some_integer: i32) { // some_integer comes into scope\n    println!(\"{}\", some_integer);\n} // Here, some_integer goes out of scope. Nothing special happens.\n
"},{"location":"languages/rust/rust.html#return-values-scope","title":"Return Values & Scope","text":"

Returning values can also transfer ownership.

Rust
fn main() {\n    let s1 = gives_ownership();         // gives_ownership moves its return value into s1\n\n    let s2 = String::from(\"hello\");     // s2 comes into scope\n\n    let s3 = takes_and_gives_back(s2);  // s2 is moved into takes_and_gives_back, which also moves its return value into s3\n} // Here, s3 goes out of scope and is dropped. s2 goes out of scope but was moved, so nothing happens. s1 goes out of scope and is dropped.\n\nfn gives_ownership() -> String {             // gives_ownership will move its return value into the function that calls it\n\n    let some_string = String::from(\"hello\"); // some_string comes into scope\n\n    some_string                              // some_string is returned and moves out to the calling function\n}\n\n// takes_and_gives_back will take a String and return one\nfn takes_and_gives_back(a_string: String) -> String { // a_string comes into scope\n\n    a_string  // a_string is returned and moves out to the calling function\n}\n
"},{"location":"languages/rust/rust.html#references-raw-pointers-borrowing","title":"References, Raw Pointers & Borrowing","text":"

Reference types:

Raw Pointers types:

As long as there are shared references to a value, not even its owner can modify it, the value is locked down. Similarly, if there is a mutable reference to a value, it has exclusive access to the value; it's not possible to use the owner at all, until the mutable reference goes away.

Note: raw pointers can be used only in unsafe block. Rust doesn't track the pointed value

Mutable references have one big restriction: it's possible to 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. A data race is similar to a race condition and happens when these three behaviors occur:

Rust
fn borrow(var: &Type) {  // &Type indicates that the var is a reference\n    // here var cannot be modified\n} // when var goes out of scope it doesn't get dropped because the scope didn't own it\n\nborrow(&variable);  // &variable creates a reference to variable but does not take ownership\n\nfn borrow2(var: &mut Type) {\n    // here var can be modified\n}\n\n&variable;  // borrow a value from a variable (returns reference)\n*variable;  // dereference value (access value pointed by the reference)\n

The . operator can implicitly borrow or dereference a reference

Rust
let struct = Struct { field: /* [...] */ }\nlet ref = &struct;\n\nref.field  // implicit deref\n(*ref).field  // explicit deref\n\nlet mut vec = vec![/* */];\n\nv.sort()  // implicit mutable borrow\n(&mut vec).sort()  // explicit mutable borrow\n

Note: arithmetic expressions can \"see through\" one level of references. Note: comparison affect the final value of a reference chain. To compare references directly use std::ptr::eq

"},{"location":"languages/rust/rust.html#structs","title":"Structs","text":"

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. Then, inside curly brackets, define the names and types of the pieces of data, which we call fields.

Rust
struct Struct {\n    field: Type,\n    ...\n}\n\nstruct UnitStruct;  // no field, useful in generics\n\n{ x: Type, y: Type }  // anonymous struct\n

To use a struct after defining it, create an instance of that struct by specifying concrete values for each of the fields.

Rust
let mut var = Struct {\n    field: value,\n    ...\n};\n
"},{"location":"languages/rust/rust.html#field-init-shorthand","title":"Field Init Shorthand","text":"Rust
let mut var = Struct {\n    field,  // shortened form since func param is named as the struct's field\n    ...\n};\n\nvar.field = value;  // member access\n

Note: the entire instance must be mutable; Rust doesn't allow to mark only certain fields as mutable.

"},{"location":"languages/rust/rust.html#struct-update-syntax","title":"Struct Update Syntax","text":"Rust
let struct1 = Struct {\n    field1: value,\n    field2: value,\n    ...\n}\n// same as\nlet struct2 = Struct {\n    field1: other_value,\n    ..struct1  // all remaining fields have the same values of struct1\n}\n
"},{"location":"languages/rust/rust.html#tuple-structs","title":"Tuple Structs","text":"

Use Tuple Structs to create different types easily. To define a tuple struct, start with the struct keyword and the struct name followed by the types in the tuple.

Rust
struct Point(i32, i32, i32);\nstruct Color(i32, i32, i32);\n\nlet origin = Point(0, 0, 0);\n
"},{"location":"languages/rust/rust.html#struct-printing","title":"Struct Printing","text":"Rust
#[derive(Debug)]  // inherit the debug trait\nstruct Struct { }\n\nlet s: Struct = { /* valorization */};\nprintln!(\"{:?}\", s)  // debug output: { field: value, ... }\n
"},{"location":"languages/rust/rust.html#associated-functions-type-associated-functions-aka-methods","title":"Associated Functions & Type-Associated Functions (aka Methods)","text":"Rust
struct Struct { };\nimpl Struct\n{\n    fn associated_function(&self, arg: Type) -> Type { }\n    fn associated_function(&mut self, arg: Type) -> Type { }  // able to modify instance\n    fn type_associated_function(arg: Type) -> Type { }  // does not have self parameter\n}\n\nlet s: Struct = { /* valorization */};\ns.associated_function(arg);  // use struct method\n\nStruct::type_associated_function(arg);\n
"},{"location":"languages/rust/rust.html#associated-consts","title":"Associated Consts","text":"Rust
struct Struct {\n    const ASSOCIATED_CONST: Type = <value>;\n}\n\nStruct::ASSOCIATED_CONST;\n
"},{"location":"languages/rust/rust.html#traits","title":"Traits","text":"

A Trait is a collection of methods representing a set of behaviours necessary to accomplish some task. Traits can be used as generic types constraints and can be implemented by data types.

Rust
trait Trait {\n    fn method_signature(&self, param: Type) -> Type;\n    fn method_signature(&self, param: Type) -> Type {\n        // default implementation\n    }\n}\n\ntrait SubTrait: Trait { }  // must have impl blocks for all super traits\n//same as\ntrait SubTrait where Self: Trait\n\nimpl Trait for Struct {\n    fn method_signature(&self, param: Type) -> Type {\n        // specific implementation\n    }\n}\n
"},{"location":"languages/rust/rust.html#fully-qualified-method-calls","title":"Fully Qualified Method Calls","text":"Rust
value.method();\nType::method(value);\nTrait::method(value);\n<Type as Trait>::method(value);\n

Note: fully qualified method calls also works with associated functions

"},{"location":"languages/rust/rust.html#derive-traits","title":"Derive Traits","text":"

The Rust compiler is able to provide a basic implementation of a trait with the derive attribute.

Derivable Traits:

Rust
#[derive(Trait)]  // derive a trait for the struct\n#[derive(Trait, Trait, ...)]  // derive multiple traits\nstruct Struct {\n    // [...]\n}\n
"},{"location":"languages/rust/rust.html#trait-bounds","title":"Trait Bounds","text":"

Trait Bound are used to require a generic to implement specific traits and guarantee that a type will have the necessary behaviours.

Rust
fn generic_method<T: RequiredTrait>() {}\nfn generic_method<T: RequiredTrait + RequiredTrait>() {}  // multiple bounds\n// or\nfn generic_method<T, U>() \n    where T: RequiredTrait + RequiredTrait,\n          U: RequiredTrait + RequiredTrait\n{\n    // implementation\n}\n\n// returned must implement specified trait, retuned type can be only one\n// useful for closures or iterators\nfn generic_return() -> impl RequiredTrait { }\n\n// trait as parameter or return (syntactic sugar for trait bounds)\nfn method_signature(param: &impl Trait) -> Type {}\nfn method_signature(param: &(impl TraitOne + TraitTwo)) -> Type {}\n
"},{"location":"languages/rust/rust.html#trait-extensions","title":"Trait Extensions","text":"Rust
extern crate foo;\nuse foo::Foo;\n\n// define the methods to be added to the existing type\ntrait FooExt {\n    fn bar(&self);\n}\n\n// implement the extension methods\nimpl FooExt for Foo {\n    fn bar(&self) { .. }\n}\n
"},{"location":"languages/rust/rust.html#generic-structs-methods","title":"Generic Structs & Methods","text":"

Generic Data Types are abstract stand-ind for concrete data types or other properties. They can be used with structs, functions, methods, etc.

Rust accomplishes this by performing monomorphization of the code that is using generics at compile time. Monomorphization is the process of turning generic code into specific code by filling in the concrete types that are used when compiled. For this reason if a function as a trait as return type (trait bound), only a single type that implements the trait can be returned.

Rust
struct GenericStruct<T, U> {\n    T generic_field,\n    U generic_field,\n    ...\n}\n\nimpl<T, U> GenericStruct<T, U> {\n    fn generic_method<T>() -> Type { }\n    fn generic_method<U>() -> Type { }\n}\n\n// implementation for specific types\nimpl GenericStruct<Type, Type> {\n    fn method() -> Type { }\n}\n\n// implementation for specific traits \nimpl<T: Trait, U> GenericStruct<T, U> {/* ...*/}\n\n// implement a trait for all types with a specific trait (AKA blanket implementation)\nimpl<T: WantedTrait> ImplementedTrait for T {/* ...*/}\n\nfn generic_func<T>() -> Type { }\nfn generic_func<T>() -> &T { }  // T could be heap-based type, returning reference is always valid\n\nfn generic<T: Trait>() -> Type { }  // use generic constraint\n

Note: the calling code needs to import your new trait in addition to the external type

"},{"location":"languages/rust/rust.html#associated-types","title":"Associated Types","text":"

Associated types connect a type placeholder with a trait such that the trait method definitions can use these placeholder types in their signatures. The implementor of a trait will specify the concrete type to be used instead of the placeholder type for the particular implementation.

Rust
trait Iterator {\n    type Item;\n\n    fn next(&mut self) -> Option<Self::Item>;\n}\n

The type Item is a placeholder, and the next method\u2019s definition shows that it will return values of type Option<Self::Item>. Implementors of the Iterator trait will specify the concrete type for Item, and the next method will return an Option containing a value of that concrete type.

Note: if the type is generic then then they are called generic associated types

"},{"location":"languages/rust/rust.html#generic-traits-vs-associated-types","title":"Generic Traits vs Associated Types","text":"

The difference is that when a trait has a generic parameter, it can be implemented for a type multiple times, changing the concrete types of the generic type parameters each time. With associated types, it's not possible to implement the trait multiple times so annotations are not needed.

Associated types also become part of the trait\u2019s contract: implementors of the trait must provide a type to stand in for the associated type placeholder. Associated types often have a name that describes how the type will be used, and documenting the associated type in the API documentation is good practice.

"},{"location":"languages/rust/rust.html#trait-objects","title":"Trait Objects","text":"

A reference to a trait is called a Trait Object. Like any other reference, a trait object points to some value, it has a lifetime, and it can be either mut or shared. What makes a trait object different is that Rust usually doesn\u2019t know the type of the referent at compile time. So a trait object includes a little extra information about the referent\u2019s type.

In memory, a trait object is a fat pointer consisting of a pointer to the value, plus a pointer to a table representing that value\u2019s type.

Note: Rust automatically converts ordinary references into trait objects when needed

Rust
let trait_object = &mut dyn Trait = &mut source;\nlet trait_object: Box<dyn Trait> = Box::new(source);  // same for Rc<T>, Arc<T>, ...\n

This works differently from defining a struct or function that uses a generic type parameter with trait bounds. A generic type parameter can only be substituted with one concrete type at a time, whereas trait objects allow for multiple concrete types to fill in for the trait object at runtime.

Rust
fn func() -> Box<dyn Trait> { }  // return something that implements the specified trait\n

If homogeneous collections are needed, using generics and trait bounds is preferable because the definitions will be monomorphized at compile time to use the concrete types.

The code that results from monomorphization uses static dispatch, which is when the compiler knows what method will be called at compile time.

This is opposed to dynamic dispatch, which is when the compiler can't tell at compile time which method will be called. At runtime Rust uses the pointers inside the trait object to know which method to call. There is a runtime cost when this lookup happens that doesn't occur with static dispatch.

Dynamic dispatch also prevents the compiler from choosing to inline a method's code, which in turn prevents some optimizations.

It's only possible to make object-safe traits into trait objects. A trait is object safe if all the methods defined in the trait have the following properties:

"},{"location":"languages/rust/rust.html#lifetimes","title":"Lifetimes","text":"

Lifetime annotation indicates to the borrow checker that the lifetime of the returned value is as long as the lifetime of the referenced value. The annotation does not affect how long the references live.

In case of different lifetimes the complier will use the most restrictive.

Rust
// lifetime annotation syntax\nfn func<'a>(x: &'a Type, y: &'a Type) -> &'a Type { }\n\n// multiple lifetimes annotations\nfn func<'a, 'b>(x: &'a Type, y: &'b Type) -> &'a Type { }\n\n// struct lifetime annotation\nstruct Struct<'a> {\n    name: &'a str  // is borrowed, needs lifetime\n}\n\nimpl<'a> Struct<'a> { }\nimpl<'a, 'b> Struct<'a> { \n    fn method(&'a self, param: &'b Type) -> &'b Type {}\n}\n\n// static lifetime, same duration as entire program\n// can be coerced to more restrictive lifetime\nlet string: &'static str = \"...\";\n
"},{"location":"languages/rust/rust.html#lifetime-elision-rules","title":"Lifetime Elision Rules","text":"

The Lifetime Elision Rules are a set of rules for the compiler to analyze references lifetimes. They describe situations that do not require explicit lifetime annotations.

"},{"location":"languages/rust/rust.html#enums","title":"Enums","text":"Rust
// enum definition\nenum Enum\n{\n    Variant1,\n    Variant2(Type, ...),  // each variant can have different types (even structs and enums) and amounts of associated data\n    Variant3 { x: u8, y: u8 }  // c-like struct\n    ...\n}\n\n// value assignment\nlet e: Enum = Enum::Variant1;\nlet e: Enum = Enum::Variant2(arg, ...);  // variant w/ data\nlet e: Enum = Enum::Variant3 { x = 1, y = 0};\n\n// methods on enum\nimpl Enum\n{\n    fn method(&self) -> Type {\n        match self {\n            Enum::Variant1 => <expr>\n            Enum::Variant2(arg) => <expr>,\n            Enum::Variant3 { x = 1, y = 0} => <expr>;\n        }\n    }\n}\n
"},{"location":"languages/rust/rust.html#match-expressions","title":"Match Expressions","text":"

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 exhaustive for compilation.

Rust
enum Enum {\n    Variant1,\n    Variant2,\n    Variant3(Type),\n    ...\n}\n\n// match expression on enum\nfn match_variant(e: Enum) {\n    match e {\n        Enum::Variant1 => <expr>,\n        Enum::Variant2 => { /* code block */ },\n        Enum::Variant3(parm_name) => <expr>,\n        _ => ()  // () is unit value\n    }\n}\n
"},{"location":"languages/rust/rust.html#pattern-matching","title":"Pattern Matching","text":"Pattern Example Notes Literal 100 Match exact value or const name Range x..=y Match any value in range, including end Wildcard _ Match any value and ignore it ref Variable ref field Borrow reference of matched variable Variable count Match any value and copy it to variable Bind with syb-pattern variable @ <pattern> Match pattern and copy to variable Enum Some(value) Tuple (key, value) Array [first, second, third] Slice [first, .., last] Struct Point { x, y, .. } Reference &value Multiple Patterns 'a' \\| 'A' match, if let, while let only Guard Expression <pattern> if <condition> match only

Note: .. in slices matches any number of elements. .. in structs ignores all remaining fields

Rust
// unpack a struct into local variables\nlet Struct { local_1, local_2, local_3, .. } = source;\n\n// ...unpack a function argument that's a tuple\nfn distance_to((x, y): (f64, f64)) -> f64 { }\n\n// iterate over keys and values of a HashMap\nfor (key, value) in &hash_map { }\n\n// automatically dereference an argument to a closure\n// (handy because sometimes other code passes you a reference\n// when you'd rather have a copy)\nlet sum = numbers.fold(0, |a, &num| a + num);\n

Patterns that always match are special in Rust. They\u2019re called irrefutable patterns, and they\u2019re the only patterns allowed in let, in function arguments, after for, and in closure arguments.

A refutable pattern is one that might not match, like Ok(x). Refutable patterns can be used in match arms, because match is designed for them: if one pattern fails to match, it\u2019s clear what happens next.

Refutable patterns are also allowed in if let and while let expressions:

Rust
// handle just one enum variant specially\nif let Enum::VariantX(_, _) = source { }\n\n// run some code only if a table lookup succeeds\nif let Some(value) = hash_map.get(&key) { }\n\n// repeatedly try something until it succeeds\nwhile let Err(err) = fallible_func() { }\n\n// manually loop over an iterator\nwhile let Some(_) = lines.peek() { }\n
"},{"location":"languages/rust/rust.html#error-handling","title":"Error Handling","text":""},{"location":"languages/rust/rust.html#option-result","title":"Option & Result","text":"

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.

Result<T, E> is the type used for returning and propagating errors. It is an enum with the variants, Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value.

Rust
// std implementation\nenum Option<T> {\n    Some(T),\n    None\n}\n\nenum Result<T, E> {\n    Ok(T),\n    Err(E)\n}\n\nlet option: Option<T> = /* */;\n\noption.is_some();\noption.is_none();\n\noption.unwrap();  // get value of Some or panic\noption.unwrap_or(value);  // get value of Some or return a specified value\noption.unwrap_or_default(fallback);  // get value of Some or return the default value of T\n\nlet result: Result<T, E> = /* */;\n\nresult.is_ok();\nresult.is_err();\nresult.as_ref();  // returns Result<&T, &E>\nresult.as_mut();  // returns Result<&mut T, &mut E>\n\n// methods consuming the result\nresult.ok();  // returns Option<T>, discarding the error\nresult.err();  // returns Option<T>, discarding the error\nresult.unwrap();  // get value of Ok or panic if Err\nresult.unwrap_or(value);  // get value of OK or return a specified value\nresult.unwrap_or_default(fallback);  // get value of Ok or return the default value of T\nresult.unwrap_or_else(fallback_fn)\nresult.unwrap_err();  // get value of Err or panic if Ok\nresult.expect(message);  // write message to stderr if Err\n\nresult_or_option.expect(\"Error Message\");  // if Err or None panics with a custom error message\n\nfn returns_result() -> Result<T, E> { \n    let result = match may_return_err() {\n        Ok(value) => value,\n        Err(error) => return Err(error)  // return Err early\n    };\n\n    Ok(result)\n}\n// same as\nfn returns_result() -> Result<T, E> { \n    let result = may_return_err()?;  // error propagation\n    // result contains Err ot value of Ok\n\n    Ok(result)\n}\n

Ending an expression with ? will result in the unwrapped success (Ok) value, unless the result is Err, in which case Err is returned early from the enclosing function. ? can only be used in functions that return Result because of the early return of Err that it provides.

Note: When None is used the type of Option<T> must be specified, because the compiler can't infer the type that the Some variant will hold by looking only at a None value. Note: error values that have the ? operator called on them go through the from function, defined in the From trait in the standard library, which is used to convert errors from one type into another

"},{"location":"languages/rust/rust.html#multiple-error-types","title":"Multiple Error Types","text":"

When working with multiple error types is useful to return a \"generic error\" type. All the standard library error types can be represented by Box<dyn std::Error + Send + Sync + 'static>.

Rust
// convenience type aliases for the generic error\ntype GenericError = Box<dyn std::Error + Send + Sync + 'static>;\ntype GenericResult<T> = Result<T; GenericError>;\n

Note: the anyhow crate provides error and result types like GenericError with additional features

"},{"location":"languages/rust/rust.html#custom-error-types","title":"Custom Error Types","text":"Rust
use thiserror::Error;  // utility crate for custom errors\n\n#[derive(Error, Debug)]\n#[error(\"{message:} ({line:}, {column})\")]\npub struct JsonError {\n    message: String,\n    line: usize,\n    column: usize,\n}\n

Note: the thiserror crate provides utilities to create custom error types

"},{"location":"languages/rust/rust.html#collections","title":"Collections","text":""},{"location":"languages/rust/rust.html#vector","title":"Vector","text":"

Vectors allow to store more than one value in a single data structure that puts all the values next to each other in memory. Vectors can only store values of the same type. Like any other struct, a vector is freed when it goes out of scope. When the vector gets dropped, all of its contents are also dropped.

Rust
let v: Vec<Type> = Vec<Type>::new();  // empty vec init\nlet mut v: vec![item1, item2, ...];  // vec init (type inferred)\n\nv.push(item);  // add elements to vector\nv.pop();  // last item as Option<T> (vector must be mutable)\n\n// element access\nlet value = v.get(index);  // get method (returns Option<&T>)\nlet value = &v[index];  // index syntax  (returns reference, panic on index out of bounds)\n\n// iterate over mutable references to each element in a mutable vector in order to make changes to all the elements\nfor i in mut &v {\n    *i = value;  // dereference and modify value\n}\n

A vector can hold different types if those type are variants of the same enum. It's also possible to use trait objects.

Rust
enum Enum {\n    Int(i32),\n    Float(f64),\n    Text(String)\n}\n\nlet v = vec![\n    Enum::Int(2),\n    Enum::Float(3.14),\n    Enum::Text(String::from(\"text\"))\n];\n
"},{"location":"languages/rust/rust.html#hashmap","title":"HashMap","text":"

Stores data in key-value pairs.

Rust
use std::collections::HashMap;\n\nlet map: HashMap<K, V> = HashMap::new();\n\nlet value = map.get(key); // returns Option<&V>\nmap.inset(key, value);  // insert or override value\nmap.entry(key).or_insert(value); // insert if not existing\nmap.entry(key).and_modify(|value| { *value = <expr> });  // modify item based on current value\n
"},{"location":"languages/rust/rust.html#closures","title":"Closures","text":"

Rust's closures are anonymous functions that can be saved in a variable or passed as arguments to other functions. Unlike functions, closures can capture values from the scope in which they're defined.

Closures are usually short and relevant only within a narrow context rather than in any arbitrary scenario. Within these limited contexts, the compiler is reliably able to infer the types of the parameters and the return type, similar to how it's able to infer the types of most variables.

The first time a closure is called with an argument, the compiler infers the type of the parameter and the return type of the closure. Those types are then locked into the closure and a type error is returned if a different type is used with the same closure.

Rust
// closure definition\nlet closure = |param1, param2| <expr>;\nlet closure = |param1, param2| {/* multiple lines of code */};\nlet closure = |num: i32| = <expr>;\n\n// closure usage\nlet result = closure(arg1, arg2);\n
"},{"location":"languages/rust/rust.html#storing-closures-using-generic-parameters-and-the-fn-traits","title":"Storing Closures Using Generic Parameters and the Fn Traits","text":"

To make a struct that holds a closure, the type of the closure must be specified, because a struct definition needs to know the types of each of its fields. Each closure instance has its own unique anonymous type: that is, even if two closures have the same signature, their types are still considered different. To define structs, enums, or function parameters that use closures generics and trait bounds are used.

The Fn traits are provided by the standard library. All closures implement at least one of the traits: Fn, FnMut, or FnOnce.

Rust
struct ClosureStruct<T> where T: Fn(u32) -> u32 {\n    closure: T,\n}\n
"},{"location":"languages/rust/rust.html#capturing-the-environment-with-closures","title":"Capturing the Environment with Closures","text":"

When a closure captures a value from its environment, it uses memory to store the values for use in the closure body. Because functions are never allowed to capture their environment, defining and using functions will never incur this overhead.

Closures can capture values from their environment in three ways, which directly map to the three ways a function can take a parameter:

These are encoded in the three Fn traits as follows:

When a closure is created, Rust infers which trait to use based on how the closure uses the values from the environment. All closures implement FnOnce because they can all be called at least once. Closures that don't move the captured variables also implement FnMut, and closures that don't need mutable access to the captured variables also implement Fn.

To force the closure to take ownership of the values it uses in the environment, use the move keyword before the parameter list. This technique is mostly useful when passing a closure to a new thread to move the data so it's owned by the new thread.

Rust
let closure = move |param| <expr>;\n
"},{"location":"languages/rust/rust.html#function-pointers","title":"Function Pointers","text":"

Function pointer types, written using the fn keyword, refer to a function whose identity is not necessarily known at compile-time. They can be created via a coercion from both function items and non-capturing closures.

Rust
fn add_one(x: usize) -> usize {\n    x + 1\n}\n\nlet ptr: fn(usize) -> usize = add_one;\nassert_eq!(ptr(5), 6);\n\nlet clos: fn(usize) -> usize = |x| x + 5;\nassert_eq!(clos(5), 10);\n
"},{"location":"languages/rust/rust.html#iterators","title":"Iterators","text":"

The iterator pattern allows to perform some task on a sequence of items in turn. An iterator is responsible for the logic of iterating over each item and determining when the sequence has finished.

In Rust, iterators are lazy, meaning they have no effect until a call to methods that consume the iterator to use it up.

Rust
// iterator trait\npub trait Iterator {\n    type Item;\n\n    fn next(&mut self) -> Option<Self::Item>;\n\n    // methods with default implementations elided\n}\n

Calling the next method on an iterator changes internal state that the iterator uses to keep track of where it is in the sequence. In other words, this code consumes, or uses up, the iterator. Each call to next eats up an item from the iterator.

Methods that call next are called consuming adaptors, because calling them uses up the iterator.

Other methods defined on the Iterator trait, known as iterator adaptors, allow to change iterators into different kinds of iterators. It's possible to chain multiple calls to iterator adaptors to perform complex actions in a readable way. But because all iterators are lazy, a call one of the consuming adaptor methods is needed to get the results.

Rust
let iterator: = vec![1, 2, 3];\niterator\n    .map(|x| x + 1)  // iterator adapter\n    .filter(|x| x % 2 == 0)  // iterator adapter\n    .collect();  // consuming adapter\n
"},{"location":"languages/rust/rust.html#custom-iterators","title":"Custom Iterators","text":"Rust
struct Counter {\n    count: u32,\n}\n\nimpl Counter {\n    fn new() -> Counter {\n        Counter { count: 0 }\n    }\n}\n\nimpl Iterator for Counter {\n    type Item = u32;\n\n    fn next(&mut self) -> Option<Self::Item> {\n        if self.count < 5 {\n            self.count += 1;\n            Some(self.count)\n        } else {\n            None\n        }\n    }\n}\n
"},{"location":"languages/rust/rust.html#smart-pointers","title":"Smart Pointers","text":"

A pointer is a general concept for a variable that contains an address in memory. This address refers to, or \"points at\" some other data. The most common kind of pointer in Rust is a reference, which you learned about in Chapter 4. References are indicated by the & symbol and borrow the value they point to. They don't have any special capabilities other than referring to data. Also, they don`t have any overhead and are the kind of pointer used most often.

Smart pointers, on the other hand, are data structures that not only act like a pointer but also have additional metadata and capabilities. The different smart pointers defined in the standard library provide functionality beyond that provided by references.

In Rust, which uses the concept of ownership and borrowing, an additional difference between references and smart pointers is that references are pointers that only borrow data; in contrast, in many cases, smart pointers own the data they point to.

Smart pointers are usually implemented using structs. The characteristic distinguishing a smart pointer from a struct is that smart pointers implement the Deref and Drop traits. The Deref trait allows an instance of the smart pointer struct to behave like a reference so it's possible to write code that works with either references or smart pointers. The Drop trait allows to customize the code that is run when an instance of the smart pointer goes out of scope.

The most common smart pointers in the standard library are:

"},{"location":"languages/rust/rust.html#using-boxt-to-point-to-data-on-the-heap","title":"Using Box<T> to Point to Data on the Heap","text":"

The most straightforward smart pointer is Box<T>. Boxes allow to store data on the heap rather than the stack. What remains on the stack is the pointer to the heap data. Boxes don't have performance overhead, other than storing their data on the heap instead of on the stack. But they don't have many extra capabilities either.

Box<T> use cases:

Rust
let _box = Box::new(pointed_value);\n
"},{"location":"languages/rust/rust.html#deref-trait-deref-coercion","title":"Deref Trait & Deref Coercion","text":"

Implementing the Deref trait allows to customize the behavior of the dereference operator, *. By implementing Deref in such a way that a smart pointer can be treated like a regular reference.

Rust
struct CustomSmartPointer<T>(T);\n\nimpl<T> CustomSmartPointer<T> {\n    fn new(x: T) {\n        CustomSmartPointer(x)\n    }\n}\n\nimpl<T> Deref for CustomSmartPointer<T> {\n    type Target = T;\n\n    fn deref(&self) -> &Self::Target {\n        // return reference to value\n    }\n}\n\nlet s = CustomSmartPointer::new(value);\nlet v = *s;\n// same as\nlet v = *(s.deref());\n

Deref coercion is a convenience that Rust performs on arguments to functions and methods. It works only on types that implement the Deref trait and converts such a type into a reference to another type. Deref coercion was added to Rust so that programmers writing function and method calls don't need to add as many explicit references and dereferences with & and *.

Rust
fn hello(name: &str) {\n    println!(\"Hello {}\", name);\n}\n\nfn main() {\n    let name = Box::new(String::from(\"Rust\"));\n    hello(&name);  // Box<string> coerced to &str (Box -> String -> &str)\n}\n

When the Deref trait is defined for the types involved, Rust will analyze the types and use Deref::deref as many times as necessary to get a reference to match the parameter's type.

Similar to the Deref trait to override the * operator on immutable references, it's possible to use the DerefMut trait to override the * operator on mutable references.

Rust does deref coercion when it finds types and trait implementations in three cases:

"},{"location":"languages/rust/rust.html#drop-trait","title":"Drop Trait","text":"

Drop allows to customize what happens when a value is about to go out of scope. It-s possible to provide an implementation for the Drop trait on any type.

Rust
struct CustomSmartPointer<T>(T);\n\nimpl<T> Drop for CustomSmartPointer<T> {\n    fn drop(&mut self) {\n        // clean up memory\n    }\n}\n\nfn main() {\n    let var1 = CustomSmartPointer(value);  // dropped when var1 goes out of scope\n    let var2 = CustomSmartPointer(value);\n    drop(var2);  // dropped early by using std::mem::drop\n}\n

Rust automatically calls drop when the instances went go of scope. Variables are dropped in the reverse order of their creation.

"},{"location":"languages/rust/rust.html#rct-arct-multiple-ownership","title":"Rc<T>, Arc<T> & Multiple Ownership","text":"

Rust provides the reference-counted pointer types Rc<T> and Arc<T>. The Rc<T> and Arc<T> types are very similar; the only difference between them is that an Arc<T> is safe to share between threads directly (the name Arc is short for atomic reference count) whereas a plain Rc<T> uses faster non-thread-safe code to update its reference count.

Rust
use std::rc::Rc;\n\nlet s: Rc<String> = Rc::new(\"some string\".to_string());\nlet t: Rc<String> = s.clone();  // contains a new pointer to the value held by s\nlet u: Rc<String> = s.clone();  // contains a new pointer to the value held by s\n

Each of the Rc<T> pointers is referring to the same block of memory, which holds a reference count and space for the value. The usual ownership rules apply to the Rc<T> pointers themselves, and when the last extant Rc<T> is dropped, Rust drops the value as well.

Note: A value owned by an Rc<T> pointer is immutable.

"},{"location":"languages/rust/rust.html#refcellt-interior-mutability-pattern","title":"RefCell<T> & Interior Mutability Pattern","text":"

Interior mutability is a design pattern in Rust that allows to mutate data even when there are immutable references to that data; normally, this action is disallowed by the borrowing rules. To mutate data, the pattern uses unsafe code inside a data structure to bend Rust's usual rules that govern mutation and borrowing.

With references and Box<T>, the borrowing rules' invariants are enforced at compile time. With RefCell<T>, these invariants are enforced at runtime. With references, if these rules are broken, a compiler error is thrown. With RefCell<T> the program will panic and exit.

The advantages of checking the borrowing rules at compile time are that errors will be caught sooner in the development process, and there is no impact on runtime performance because all the analysis is completed beforehand. For those reasons, checking the borrowing rules at compile time is the best choice in the majority of cases, which is why this is Rust's default.

The advantage of checking the borrowing rules at runtime instead is that certain memory-safe scenarios are then allowed, whereas they are disallowed by the compile-time checks. Static analysis, like the Rust compiler, is inherently conservative.

Note: RefCell<T> is only for use in single-threaded scenarios and will cause a compile-time error if used it in a multithreaded context.

When creating immutable and mutable references, the & and &mut syntax is used, respectively. With RefCell<T>, the borrow and borrow_mut methods are ued, which are part of the safe API that belongs to RefCell<T>. The borrow method returns the smart pointer type Ref<T>, and borrow_mut returns the smart pointer type RefMut<T>. Both types implement Deref, so can be treated like regular references.

The RefCell<T> keeps track of how many Ref<T> and RefMut<T> smart pointers are currently active. Every time borrow is called, the RefCell<T> increases its count of how many immutable borrows are active. When a Ref<T> value goes out of scope, the count of immutable borrows goes down by one. Just like the compile-time borrowing rules, RefCell<T> allows to have many immutable borrows or one mutable borrow at any point in time.

A common way to use RefCell<T> is in combination with Rc<T>. Rc<T> allows to have multiple owners of some data, but it only gives immutable access to that data. By having a Rc<T> that holds a RefCell<T>, its' possible to get a value that can have multiple owners and that can mutate.

The standard library has other types that provide interior mutability:

"},{"location":"languages/rust/rust.html#reference-cycles-can-leak-memory","title":"Reference Cycles Can Leak Memory","text":"

Rust's memory safety guarantees make it difficult, but not impossible, to accidentally create memory that is never cleaned up (known as a memory leak). Rust allows memory leaks by using Rc<T> and RefCell<T>: it's possible to create references where items refer to each other in a cycle. This creates memory leaks because the reference count of each item in the cycle will never reach 0, and the values will never be dropped.

"},{"location":"languages/rust/rust.html#files","title":"Files","text":""},{"location":"languages/rust/rust.html#reading-files","title":"Reading Files","text":"Rust
use std::fs;\n\nlet contents: Vec<u8> = fs::read(\"path/to/file\").unwrap_or_default();\nlet contents: String = fs::read_to_string(\"path/to/file\").unwrap_or_default();\n\ncontents.lines(); // iterator over text lines\n
"},{"location":"languages/rust/rust.html#writing-files","title":"Writing Files","text":"Rust
use std::fs;\nuse std::io::Write;  // write trait\n// or\nuse std::io::prelude::*;\n\nlet contents: [u8] = /* */;\nlet contents = String::from(/* */);\n\nfs::write(\"path/to/file\", contents);\n\nlet mut file = fs::OpenOptions::new().append(true).open(\"path/to/file\").unwrap();\nfile.write(b\"appended text\");  // write wants an [u8]\n
"},{"location":"languages/rust/rust.html#external-code","title":"External Code","text":"

The extern keyword is used in two places in Rust:

extern is used in two different contexts within FFI. The first is in the form of external blocks, for declaring function interfaces that Rust code can call foreign code by.

Rust
#[link(name = \"my_c_library\")]\nextern \"C\" {\n    fn my_c_function(x: i32) -> bool;\n}\n

This code would attempt to link with libmy_c_library.so on unix-like systems and my_c_library.dll on Windows at runtime, and panic if it can't find something to link to. Rust code could then use my_c_function as if it were any other unsafe Rust function. Working with non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs.

The mirror use case of FFI is also done via the extern keyword:

Rust
#[no_mangle]\npub extern \"C\" fn callable_from_c(x: i32) -> bool {\n    x % 3 == 0\n}\n

If compiled as a dylib, the resulting .so could then be linked to from a C library, and the function could be used as if it was from any other library

"},{"location":"languages/rust/unit-tests.html","title":"Unit Tests","text":""},{"location":"languages/rust/unit-tests.html#test-functions","title":"Test Functions","text":"Rust
// module code here\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn test_func() {\n        //ARRANGE\n\n        // ACT\n\n        // ASSERT\n        assert!(bool, \"optional custom error message\");\n        assert_eq!(expected, actual, \"optional custom error message\");\n        assert_ne!(expected, actual, \"optional custom error message\");\n    }\n\n    #[test]\n    #[should_panic(\"optional custom error message\")]\n    fn test_func() {/* ... */}\n\n    #[test]\n    #[ignore]\n    fn test_func() {/* ... */}\n}\n
"},{"location":"languages/rust/unit-tests.html#controlling-how-tests-are-run","title":"Controlling How Tests Are Run","text":"Bash
cargo test -- --test-threads=<number>  # run tests in parallel (1 no parallelism)\ncargo test -- --show-output  # show content printed in stdout in each test\ncargo test <test_name>  # run only a specific test\ncargo test <partial_test_name>  # run only specific tests\ncargo test -- --ignored  # run tests annotated with #[ignore]\ncargo test --test  # run all integration tests\n
"},{"location":"languages/rust/unit-tests.html#test-organization","title":"Test Organization","text":"

Unit Tests:

Integration tests:

"},{"location":"languages/swift/swift.html","title":"Swift","text":""},{"location":"languages/swift/swift.html#basics","title":"Basics","text":""},{"location":"languages/swift/swift.html#macro","title":"Macro","text":"Swift
#if DEBUG\n\n// contents compiled only if in DEBUG build\n\n#endif\n
"},{"location":"languages/swift/swift.html#comments","title":"Comments","text":"Swift
// single line comment\n\n/*  \nmulti line comment\n*/\n
"},{"location":"languages/swift/swift.html#variables","title":"Variables","text":"Swift
var variable = value  // implicit variable init (auto-determine type)\nvar variable: Type = value  // explicit variable init\nvar variable: Type? = value  // explicit nullable variable init\n
"},{"location":"languages/swift/swift.html#constants","title":"Constants","text":"Swift
let CONSTANT = value  // constant init (value can be assigned at runtime)\n
"},{"location":"languages/swift/swift.html#console-output","title":"Console Output","text":"Swift
print()  // empty line\nprint(variable)\nprint(\"string\")\n
"},{"location":"languages/swift/swift.html#strings","title":"Strings","text":"Swift
var string \"Text: \\(<expr>)\"  // string interpolation\nvar string = \"Hello\" + \"There\"  // string concatenation\n\nvar multilineString = \"\"\"Use double quotes trice\nto make a string span multiple lines\"\"\"\n
"},{"location":"languages/swift/swift.html#array","title":"Array","text":"Swift
var array = [\"firstItem\", \"secondItem\", ...]\nvar array = [Type()]  // init empty homogeneous array\n\narray[index]  // value access\narray[index] = value  // value update\n\narray.append(item)  // add item to the end\narray.contains(item)  // membership check\narray.sort()  // in place sort\n\n\n// Heterogeneous Array\nvar list: Any = [\"string\", 47, ...]  // cannot access with [index]\nvar list: Any = []  // init empty heterogeneous array\n
"},{"location":"languages/swift/swift.html#tuple","title":"Tuple","text":"

A tuple type is a comma-separated list of types, enclosed in parentheses.

It's possible to use a tuple type as the return type of a function to enable the function to return a single tuple containing multiple values. It's possible to name the elements of a tuple type and use those names to refer to the values of the individual elements. An element name consists of an identifier followed immediately by a colon (:).

Swift
var tuple: (Type, Type) = (value, value)  // explicit type\nvar tuple = (value, value)  // implicit type\ntuple.0  // item access\n\n// named elements\nvar tuple = (name1: value1, name2: value2, ...)  // tuple init\ntuple = (value1, value2)  // names are inferred\ntuple.name1  // item access\n
"},{"location":"languages/swift/swift.html#tuple-decomposition","title":"Tuple Decomposition","text":"Swift
var tuple = (value1, value2)\nvar (var1, var2) = tuple  // var1 = value1, var2 = value2\n
"},{"location":"languages/swift/swift.html#type-identifier","title":"Type Identifier","text":"Swift
typealias Point = (Int, Int)\nvar origin: (0, 0)\n
"},{"location":"languages/swift/swift.html#dictionary","title":"Dictionary","text":"Swift
var dict = [\n    \"key\": \"value\",\n    ...\n]\n\nvar dict = [Type: Type]()  // init empty dict\n\ndict[key]  // value access\ndict[key] = value // value update\n
"},{"location":"languages/swift/swift.html#expressions-operators","title":"Expressions & Operators","text":""},{"location":"languages/swift/swift.html#primary-expressions","title":"Primary Expressions","text":"Syntax Operation x.m access to member m of object x (\".\" \u2192 member access operator) x(...) method invocation (\"()\" \u2192 method invocation operator) x[...] array access and indicization new T(...) object instantiation x! declare x as not nil"},{"location":"languages/swift/swift.html#unary-operators","title":"Unary Operators","text":"Operator Operation +x identity -x negation !x logic negation ~x binary negation ++x pre-increment --x pre-decrement x++ post-increment x-- post decrement (type)x explicit casting"},{"location":"languages/swift/swift.html#mathematical-operators","title":"Mathematical Operators","text":"Operator Operation x + y addition, string concatenation x - y subtraction x * y multiplication x / y integer division, always returns an int x % y modulo, remainder x << y left bit shift x >> y right bit shift"},{"location":"languages/swift/swift.html#relational-operators","title":"Relational Operators","text":"Operator Operation x <= y less or equal to x > y greater than x >= y greater or equal to x is T true if x is an object of type T x == y equality !x inequality"},{"location":"languages/swift/swift.html#logical-operators","title":"Logical Operators","text":"Operator Operation Name ~x bitwise NOT x & y bitwise AND x ^ y bitwise XOR x | y bitwise OR x && y evaluate y only if x is true x || y evaluate y only if x is false x ?? y evaluates to y only if x is nil, x otherwise nil coalescing x?.y stop if x == nil, evaluate x.y otherwise nil conditional"},{"location":"languages/swift/swift.html#assignment","title":"Assignment","text":"Operator Operation x += y x = x + y x -= y x = x - y x *= y x = x * y x /= y x = x / y x %= y x = x % y x <<= y x = x << y x >>= y x = x >> y x &= y x = x & y x |= y x = x x ^= y x = x ^ y x ??= y if (x == nil) {x = y}"},{"location":"languages/swift/swift.html#conditional-operator","title":"Conditional Operator","text":"

<condition> ? <return_if_condition_true> : <return_if_condition_false>;

"},{"location":"languages/swift/swift.html#nil-checks","title":"Nil Checks","text":"Swift
variable ?? value\n// same as\nif(variable == nil) { variable = value }\n
"},{"location":"languages/swift/swift.html#if-else","title":"If-Else","text":"Swift
if condition {\n    // code here\n} else if condition {\n    //code here\n} else {\n    // code here\n}\n\nif let var0 = var1 { /* statements */ }\n// same as\nlet var0 = var1\nif var0 != nil { /* statements */ }\n
"},{"location":"languages/swift/swift.html#switch","title":"Switch","text":"Swift
switch <value> {\n    case <pattern/key>:\n        // code here\n        break  // can be implicit\n\n    case key where <condition_on_key>:\n        // code here\n        break\n\n    default:\n        // code here\n        break\n}\n
"},{"location":"languages/swift/swift.html#loops","title":"Loops","text":""},{"location":"languages/swift/swift.html#for-loop","title":"For Loop","text":"Swift
// range based for\nfor i in start...end { /* statements */ }  // end included\nfor i in start..<end { /* statements */ }  // end excluded\nfor _ in start...end\n\nfor item in sequence {\n    // code here\n}\n\nfor (key, value) in dict {\n    // code here\n}\n
"},{"location":"languages/swift/swift.html#while-loop","title":"While Loop","text":"Swift
while condition {\n    // code here\n}\n\n// \"do\"..while\nrepeat {\n    // code here\n} while condition\n
"},{"location":"languages/swift/swift.html#functions","title":"Functions","text":"Swift
// \"void function\"\nfunc funcName(param: Type, ...) {\n    // code here\n}\n\nfunc funcName(param: Type = defaultValue, ...) -> Type {\n    //code here\n    return <expression>\n}\n\nfunc funcName(param: Type) -> Type {\n    <expression>  // implicit return\n}\n\n// func call MUST have parameter's names\nfuncName(param: value, ...)\n\n// multiple return values\nfunc funcMultipleParameters(param: Type) -> (retVal1: Type, retVal2: Type) {\n    //code here\n\n    return (<expression>, <expression>)\n}\n\nvar result = funcMultipleReturns(param: value)\nresult.retVal1  // access to tuple components\n\n// argument labels (only first label can be omitted)\nfunc funcWithLabels(_ param: Type, label param: Type, ...) -> Type { }\nfuncWithLabels(value, label: value, ...)\n
"},{"location":"languages/swift/swift.html#passing-functions-as-parameters","title":"Passing Functions as Parameters","text":"Swift
func f(param: Type) -> Type {}\nfunc g(f: (Type) -> Type) {}  // (Type) -> Type are the passed func input and output types\n
"},{"location":"languages/swift/swift.html#functions-returning-functions","title":"Functions Returning Functions","text":"Swift
func f() -> ((Type) -> Type) {\n    func g(param: Type) -> type {}\n\n    return g\n}\n
"},{"location":"languages/swift/swift.html#closure","title":"Closure ({ .. })","text":"

Closures are self-contained blocks of functionality that can be passed around and used in code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

Swift
{ (parameters: Type) -> Type in\n    // statements\n}\n\n{ parameters in return <expression> }  // type inference from context\n{ $0 > $1 }  // $<n> identifies the n-th argument, IN can be omitted if closure has only the body\n
"},{"location":"languages/swift/swift.html#enums","title":"Enums","text":""},{"location":"languages/swift/swift.html#enum-definition","title":"Enum Definition","text":"Swift
enum EnumName {\n    case key1\n    case key2\n    case ...\n}\n\nEnumName.key1 // key1\n
"},{"location":"languages/swift/swift.html#enum-with-raw-values","title":"Enum with Raw Values","text":"Swift
enum EnumName: Type {\n    case key1 = value\n    case key2 = value\n    case ...\n}\n\nEnumName.key1.rawValue  // value\n\nenum IntegerEnum: Int {\n    // the value of each case is one more then the previous case\n    case one = 1\n    case two, three, four\n    case ...\n}\n
"},{"location":"languages/swift/swift.html#matching-enumeration-values-with-a-switch-statement","title":"Matching Enumeration Values with a Switch Statement","text":"Swift
enum Rank: Int {\n    case ace = 1, two, three, four, five, six, seven, eight, nine, ten\n    case jack, queen, king\n\n    func getValue() -> String {\n        switch self {\n\n        case .jack:\n            return \"jack\"\n\n        case .queen:\n            return \"queen\"\n\n        case .king:\n            return \"king\"\n\n        default:\n            return String(self.rawValue)\n        }\n    }\n}\n\nRank.jack.getValue() // \"jack\"\nRank.jack.rawValue // 11\n
"},{"location":"languages/swift/swift.html#struct-value-type","title":"Struct (Value Type)","text":"Swift
struct StructName {\n    var attribute = value  // instance variable\n    private var _attribute: Type  // backing field for property\n\n    var property: Type {\n        get { return _attribute }\n\n        set { _attribute = newValue }  // newValue contains the passed value\n        // OR\n        set(param) { _attribute = param }\n    }\n\n    // constructor\n    init(param: Type) {\n        self.attribute = param  // attribute valorization\n    }\n\n    // de-initializer (free memory containing obj?)\n    deinit {\n        // empty the attributes\n    }\n\n    // overloading\n    func method() -> Type { }\n    func method(param: Type, ...) -> Type { }\n}\n\nvar structure = StructName()  // struct instantiation\n
"},{"location":"languages/swift/swift.html#classes-reference-type","title":"Classes (Reference Type)","text":""},{"location":"languages/swift/swift.html#class-definition-instantiation","title":"Class Definition & Instantiation","text":"Swift
class ClassName {\n    var attribute = value  // instance variable\n    private var _attribute: Type  // backing field for property\n\n    var property: Type {\n        get { return _attribute }\n\n        set { _attribute = newValue }  // newValue contains the passed value\n        // OR\n        set(param) { _attribute = param }\n    }\n\n    // constructor\n    init(param: Type) {\n        self.attribute = param  // attribute valorization\n    }\n\n    // de-initializer (free memory containing obj?)\n    deinit {\n        // empty the attributes\n    }\n\n    // overloading\n    func method() -> Type { }\n    func method(param: Type, ...) -> Type { }\n}\n\nvar obj = ClassName()  // obj instantiation\n
"},{"location":"languages/swift/swift.html#property-observers-willset-didset","title":"Property Observers willSet & didSet","text":"

Do actions before/after modifying a property value.

Note: willSet and didSet do not set the value of the property.

Swift
class ClassName {\n\n    var _attribute: Type\n\n    var property {\n        get { return _attribute }\n        set{ _attribute = newValue }\n\n        willSet {\n            // act before setting the property value\n        }\n\n        didSet {\n            // act after setting the property value\n        }\n    }\n}\n
"},{"location":"languages/swift/swift.html#inheritance","title":"Inheritance","text":"Swift
class Derived: SuperClass {\n\n    var attribute: Type\n\n    init(param1: Type, param2: Type) {\n        self.attribute = param1\n        super.init(param: param2 )  // superclass init (NEEDED)\n    }\n\n    // overriding\n    override func method() {}\n}\n
"},{"location":"languages/swift/swift.html#exception-handling","title":"Exception Handling","text":"Swift
guard let variable = <expression>\nelse {\n    /* statements */\n    // throw or return to exit code branch\n}\n\n\ndo {\n    try <throwing expression>\n} catch <pattern> {\n    // statements\n}\n
"},{"location":"linux/filesystem/file-links.html","title":"Symlink, Hardlink, Reflink","text":"

Unix files consist of two parts: the data part and the filename part. The data part is associated with something called an inode. The inode carries the map of where the data is, the file permissions, etc. for the data.

Text Only
                                           +------+ +------+\n                         .---------------> | data | | data | etc\n                        /                  +------+ +------+\n+--------------------------------+\n| permbits, etc | data addresses |\n+--------------inode-------------+\n

The filename part carries a name and an associated inode number.

Text Only
                                  +---------------------------+\n                 .--------------> | permbits, etc | addresses |\n                /                 +-----------inode-----------+\n+--------------------+\n| filename | inode # |\n+--------------------+\n
"},{"location":"linux/filesystem/file-links.html#hardlinks","title":"Hardlinks","text":"

More than one filename can reference the same inode number. These files are said to be hard linked together.

Text Only
+--------------------+\n| filename | inode # |\n+--------------------+\n                \\                 +---------------------------+\n                 >--------------> | permbits, etc | addresses |\n                /                 +------------inode----------+\n+---------------------+\n| othername | inode # |\n+---------------------+\n
"},{"location":"linux/filesystem/file-links.html#symlinks-aka-softlinks","title":"Symlinks (aka Softlinks)","text":"

Symlinks are a special file type whose data part carries a path to another file. Since it is a special file, the OS recognizes the data as a path, and redirects opens, reads, and writes so that, instead of accessing the data within the special file, they access the data in the file named by the data in the special file.

Text Only
+--------------------+\n| filename | inode # |\n+--------------------+\n              \\\n               \\     +---------------------------+\n                '--> | permbits, etc | addresses |\n                     +-----------inode-----------+\n                                     /\n                                    /\n                                   /\n .--------------------------------'\n(     +--------------------------+\n '--> |\"/path/to/some/other/file\"| \n      +----------data------------+\n                  /                     |\n .~ ~ ~ ~ ~ ~ ~ ~'                      |-- (redirected at open() time)\n(     +--------------------+            |\n '~~> | filename | inode # |\n      +--------------------+\n                   \\               +---------------------------+\n                    '------------> | permbits, etc | addresses |\n                                   +-----------inode-----------+\n                                                /\n                                               /\n .--------------------------------------------'\n(     +------+  +------+ \n '--> | data |  | data | etc.\n      +------+  +------+ \n

Now, the filename part of the file is stored in a special file of its own along with the filename parts of other files; this special file is called a directory.

"},{"location":"linux/filesystem/file-links.html#reflink","title":"Reflink","text":"

A Reflink is a type of shallow copy of file data that shares the blocks but otherwise the files are independent and any change to the file will not affect the other. This builds on the underlying copy-on-write mechanism. A reflink will effectively create only a separate metadata pointing to the shared blocks which is typically much faster than a deep copy of all blocks.

Text Only
+--------------------+\n| filename | inode # |\n+--------------------+\n            \\        +---------------------------+\n             '-----> | permbits, etc | addresses |\n                     +-----------inode-----------+\n                                   \\                +------+  +------+\n                                    >-------------> | data |  | data | etc.\n                                   /                +------+  +------+\n                     +---------------------------+\n             .-----> | permbits, etc | addresses |\n            /        +-----------inode-----------+\n+---------------------+\n| othername | inode # |\n+---------------------+\n

There are some constraints:

"},{"location":"linux/filesystem/file-links.html#directories","title":"Directories","text":"

The directory, as a file, is just an array of filename parts of other files.

When a directory is built, it is initially populated with the filename parts of two special files: the . and .. files.

The filename part for the . file is populated with the inode of the directory file in which the entry has been made: . is a hardlink to the file that implements the current directory.

The filename part for the .. file is populated with the inode of the directory file that contains the filename part of the current directory file: .. is a hardlink to the file that implements the immediate parent of the current directory.

The ln command knows how to build hardlinks and softlinks; the mkdir command knows how to build directories (the OS takes care of the above hardlinks).

There are restrictions on what can be hardlinked (both links must reside on the same filesystem, the source file must exist, etc.) that are not applicable to softlinks (source and target can be on separate file systems, source does not have to exist, etc.).

"},{"location":"linux/filesystem/procfs.html","title":"/proc Filesystem","text":"

The proc file system contains a hierarchy of special files that represent the current state of the kernel.

Files in the /proc directory contain information about the hardware and current processes running on the system. Files that have write permission can be modified to change the configuration of the kernel.

"},{"location":"linux/filesystem/procfs.html#top-level-files-within-proc","title":"Top-Level Files Within /proc","text":""},{"location":"linux/filesystem/procfs.html#process-directories-in-proc","title":"Process Directories in /proc","text":"

The /proc directory contains directories with numerical names. These directories are named after a program\u2019s process ID and contain information about that process. The owner and group of each process directory are set to the user running the process.

Each /proc/<pid> directory contains several files including:

"},{"location":"linux/filesystem/procfs.html#other-directories-in-proc","title":"Other Directories in /proc","text":"

Other directories within the /proc directory group similar information by topic. The following is a partial list of these directories:

"},{"location":"linux/filesystem/sysfs.html","title":"/sys Filesystem (sysfs)","text":""},{"location":"linux/filesystem/sysfs.html#sysfs-directories","title":"sysfs Directories","text":"

In addition to /proc, the kernel also exports information to another virtual file system called sysfs. sysfs is used by programs such as udev to access device and device driver information.

"},{"location":"linux/filesystem/sysfs.html#sysblock","title":"/sys/block","text":"

This directory contains entries for each block device in the system. Symbolic links point to the physical device that the device maps to in the physical device tree.

For example, attributes for the sda disks reside in the /sys/block/sda directory.

"},{"location":"linux/filesystem/sysfs.html#sysbus","title":"/sys/bus","text":"

This directory contains subdirectories for each physical bus type supported in the kernel. Each bus type has two subdirectories: devices and drivers.

The devices directory lists devices discovered on that type of bus. The drivers directory contains directories for each device driver registered with the bus type. Driver parameters can be viewed and manipulated.

"},{"location":"linux/filesystem/sysfs.html#sysclass","title":"/sys/class","text":"

This directory contains every device class registered with the kernel. Device classes describe a functional type of device. Examples include input devices, network devices, and block devices.

"},{"location":"linux/filesystem/sysfs.html#sysdevices","title":"/sys/devices","text":"

This directory contains the global device hierarchy of all devices on the system. This directory also contains a platform directory and a system directory.

The platform directory contains peripheral devices specific to a particular platform such as device controllers. The system directory contains non-peripheral devices such as CPUs and APICs.

"},{"location":"linux/filesystem/sysfs.html#sysfirmware","title":"/sys/firmware","text":"

This directory contains subdirectories with firmware objects and attributes.

"},{"location":"linux/filesystem/sysfs.html#sysmodule","title":"/sys/module","text":"

This directory contains subdirectories for each module that is loaded into the kernel.

"},{"location":"linux/filesystem/sysfs.html#syspower","title":"/sys/power","text":"

The system power state can be controlled from this directory. The disk attribute controls the method by which the system suspends to disk. The state attribute allows a process to enter a low power state.

"},{"location":"linux/init/open-rc.html","title":"OpenRC","text":"

OpenRC is a dependency-based init system for Unix-like systems that maintains compatibility with the system-provided init system, normally located in /sbin/init. OpenRC is Gentoo's native init system, although other init systems are available.

OpenRC will start necessary system services in the correct order at boot, manage them while the system is in use, and stop them at shutdown. It can manage daemons installed from the Gentoo repository, can optionally supervise the processes it launches, and has an the possibility to start processes in parallel - when possible - to shorten boot time.

"},{"location":"linux/init/open-rc.html#runlevels-services","title":"Runlevels & Services","text":"

OpenRC has a concept of runlevels. A runlevel is a collection of services that needs to be started. Instead of random numbers they are named, and users can create their own if needed.

The rc-status helper will print all currently active runlevels and the state of services in them:

Bash
Runlevel: default\n  modules                     [  started  ]\n  lvm                         [  started  ]\n

All runlevels are represented as folders in /etc/runlevels/ with symlinks to the actual service scripts.

Calling openrc with an argument will switch to that runlevel; this will start and stop services as needed.

"},{"location":"linux/init/open-rc.html#managing-runlevels","title":"Managing Runlevels","text":"

Managing runlevels is usually done through the rc-update helper, but could of course be done by hand if desired.

Bash
rc-update add <service> <runlevel>\nrc-update del <service> <runlevel>\nrc-update show <runlevel>\n

The default startup uses the runlevels sysinit, boot, and default, in that order. Shutdown uses the shutdown runlevel.

"},{"location":"linux/init/open-rc.html#managing-services","title":"Managing Services","text":"

Any service can, at any time, be started/stopped/restarted by executing with the rc-service helper:

Bash
rc-service <service> start\nrc-service <service> stop\nrc-service <service> restart\nrc-service <service> status\nrc-service <service> zap\n

Another, less preferred method, is to run the service script directly:

Bash
/etc/init.d/<service> start\n/etc/init.d/<service> stop\n/etc/init.d/<service> restart\n/etc/init.d/<service> status\n/etc/init.d/<service> zap\n

Note: the configuration for each service is in /etc/conf.d/<service>

There is a special command zap that makes OpenRC 'forget' that a service is started. This is mostly useful to reset a crashed service to stopped state without invoking the (possibly broken) stop function of the service script.

Calling openrc without any arguments will try to reset all services so that the current runlevel is satisfied.

"},{"location":"linux/init/systemd.html","title":"Systemd","text":"

systemd is a suite of basic building blocks for a Linux system. It provides a system and service manager that runs as PID 1 and starts the rest of the system.

systemd provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points, and implements an elaborate transactional dependency-based service control logic.

"},{"location":"misc/git.html","title":"Git","text":"

Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

"},{"location":"misc/git.html#terminology","title":"Terminology","text":"

Repository: collection of files (blobs) and directories (trees) managed by git Commit: snapshot of the entire repository and its metadata Head: pointer to the current commit Branch: timeline or collection of consecutive commits Remote: remote shared repository in which changes as synced Working Tree: current version of the repository on disk Index (Staging Area): collection of changes not yet committed Stash: collection of pseudo-commits not belonging to a specific branch

"},{"location":"misc/git.html#commands","title":"Commands","text":""},{"location":"misc/git.html#managing-configs","title":"Managing Configs","text":"

There are three git config sources/scopes:

  1. system: defined in git's installation folder and managed with --system
  2. global: defined in $HOME/.gitconfig or $XDG_CONFIG_HOME/git/config and managed with --global
  3. local: defined in .git/config and managed with --local

The applied config in each repository is the combination of all three scopes in order.

git config [--<scope>] <key> <value>: set git config key-value pair git config [--<scope>] --unset <key>: unset git config key-value pair git config [--<scope>] --list: list git config key-value pairs

"},{"location":"misc/git.html#tracking-files-making-changes","title":"Tracking Files & Making Changes","text":"

git status: shows the status of changes as untracked, modified, or staged

git add <files>: add files contents to the staging area git add -u|--update <files>: stage changes but ignore untracked files git add -p|--patch <files>: interactively stage chunks of files

git restore .: discard uncommitted changes git restore <file>: discard uncommitted changes to file git restore --staged: discard changes made to a file git restore --staged --worktree: unstage and discard changes made to a file git restore -p|--patch: interactively unstage chunks of files

git commit: save the snapshot to the project history git commit -m|--message \"message\": commit and provide a message git commit -a|--all: automatically notice any modified (but not new) files and commit git commit -v|--verbose: show unified diff between the HEAD commit and what would be committed git commit --amend: modify latest commit with the new changes git commit --no-verify: commit without executing hooks git commit --fixup <commit>: mark commit as correction to another git commit -s|--signoff: Add a Signed-off-by trailer by the committer at the end of the commit log message

"},{"location":"misc/git.html#managing-stashes","title":"Managing Stashes","text":"

git stash [push] [-m|--message]: add all changes to the stash (and provide message) git stash [push] -k|--keep-index: create a stash but leave files as they are git stash list list all stashes git stash show [<stash>]: show changes in the stash git stash pop: restore last stash git stash drop [<stash>]: remove a stash from the list git stash clear: remove all stashes

"},{"location":"misc/git.html#managing-remotes","title":"Managing Remotes","text":"

git remote: list remotes git remote -v|--verbose: list remotes names and URLs git remote show <remote>: inspect the remote

git remote add <remote> <url | path>: add a remote git remote remove <remote>: remove the specified remote git remote rename <old_name> <new_name>: rename a remote git remote set-url <name> <url>: change the URL for the remote git remote set-url --add <name> <url>: add another URL for the remote git remote set-url --add --push <name> <url>: add another push URL for the remote git remote set-url <name> <url>: change the URL for rhe remote git branch -u|--set-upstream-to=<remote>/<remote branch>: set up correspondence between local and remote branch

git push: send objects to default remote on current branch git push <remote> <branch>: send objects to remote git push <remote> <local branch>:<remote branch>: send objects to remote, and update remote reference

git push -f|--force: overwrite remote with local version git push --force-with-lease: overwrite remote with local version if remote has not been modified git push --force-with-lease --force-if--includes: will verify if updates from the remote that may have been implicitly updated in the background are integrated locally before allowing a forced update

git fetch [<remote>]: retrieve objects/references from a remote git pull: incorporate remote changes by merging, same as git fetch; git merge git pull --rebase: incorporate remote changes by rebasing git pull --ff: fast-forward (only update branch tip) remote changes, merge if not possible git pull --ff-only: fast-forward (only update branch tip) remote changes, error if not possible

git fetch|pull -p|--prune: remove any remote-tracking references that no longer exist on the remote git fetch|pull -t|--tags: retrieve all tags from the remote

git clone <url> [<folder_name>]: download repository and repo history from remote git clone --shallow: clone only repo files, not history of commits git clone --depth <depth>: clone only last <depth> commits

Note: for a in depth explanation of --force-if-includes see this

"},{"location":"misc/git.html#viewing-project-history","title":"Viewing Project History","text":"

git log [<rev>]: show history of changes git log -p|--patch: show history of changes and complete differences git log --stat --summary: show overview of the change git log --follow <file>: list version history fo file, including renames git log --all --graph --decorate: visualizes history as a DAG git log --oneline: compact log

git log -S<string>: Look for diffs that change the number of occurrences of the specified <string> git log -G<regex>: Look for diffs whose patch text contains added/removed lines that match <regex>

git log -L <start>,<end>:<file>: Trace the evolution of the line range given by <start>,<end>, within the <file> git log -L /<regex>/:<file>: Trace the evolution of the line range given by the function name regex <regex>, within the <file>

git shortlog: list commits by author git reflog [<rev>]: show record of when the tips of branches and other references were updated in the local repository

git show <commit>: show commit metadata and content git show --stat <commit>: show number of changes in commit

git blame <file>: show who last edited which line git blame -L <start>,<end> -- <file>: Annotate only the line range given by <start>,<end>, within the <file> git blame -L /<regex>/ -- <file>: Annotate only the range given by the function name regex <regex>, within the <file> git blame -w: Ignore whitespace when comparing the parent\u2019s version and the child\u2019s to find where the lines came from git blame -M: Detect moved or copied lines within a file. git blame -M -C [-C -C]: Detect moved or copied lines within a file (-M), from all modified files in the same commit (-C), in the commit that created the file (-C -C), in all commits (-C -C -C)

git diff <filename>: show difference since the last commit git diff <commit> <filename>: show differences in a file since a particular snapshot git diff <reference_1> <reference_2> <filename>: show differences in a file between two snapshots git diff --staged: show what is about to be committed git diff <first-branch>...<second-branch>: show content diff between two branches git diff -w|--ignore-all-space: show diff ignoring whitespace differences git diff --word-diff: show diff word-by-word instead of line-wise

git bisect start: start binary search through commit history, to find the first \"bad\" commit git bisect good: mark current commit as \"good\" git bisect bad: mark current commit as \"bad\" git bisect reset: conclude search and restore HEAD

"},{"location":"misc/git.html#managing-tags","title":"Managing Tags","text":"

Git supports two types of tags: lightweight and annotated.

A lightweight tag is very much like a branch that doesn't change: it's just a pointer to a specific commit.

Annotated tags, however, are stored as full objects in the Git database. They're checksummed; contain the tagger name, email, and date; have a tagging message; and can be signed. It's generally recommended creating annotated tags so it's possible to have all this information.

git tag: list existing tags git tag -l|--list <pattern>: list existing tags matching a wildcard or pattern

git tag <tag> [<commit_hash>]: create a lightweight tag on the commit git tag -a|--annotate <tag> [<commit_hash> -m <message>]: create am annotated tag on the commit git tag -f|--force <tag> [<commit_hash>]: update a tag if it exists git tag -s|--sign <tag> [<commit_hash>]: sign a tag

git push <remote> <tagname>: push a tag to the remote git push <remote> --tags: push commits and their tags (both types) to the remote

git tag -d|--delete <tagname>: delete a tag git push <remote> :refs/tags<tagname>:: remove a tag from the remote git push <remote> --delete <tagname>: remove a tag from the remote

git switch <tag>: checkout a tag - WARNING: will go into detached HEAD

"},{"location":"misc/git.html#branching-and-merging","title":"Branching And Merging","text":"

git branch: shows branches git branch -vv: show branch + last commit + remote status git branch --merged [--remote]: show branches (remote) that have been merged into current one (needs same history, merge squash/rebase break history) git branch: show list of all existing branches (* indicates current) git branch <branch-name>: create new branch git branch -d|--delete <branch-name>: delete specified branch git branch -m|--move <old_name> <new_name>: rename a branch without affecting the branch's history git switch -c|--create <branch-name>: create a new branch and switch to it git switch --orphan <branch-name>: create an new un-rooted branch from scratch git switch <branch-name>: change current branch (update HEAD) and update working directory

git merge <branch-name>: merges into current branch git merge --continue: continue previous merge after solving a merge conflict git rebase <branch>: rebase current branch commits onto another branch git rebase --onto <new-base> <old-base>: rebase a slice of commits from <old-base> onto <new-base> git rebase --onto <new-base> --root <old-base>: rebase a slice of commits from <old-base> onto <new-base>, including the root commit

git cherry-pick <commit>: bring in a commit from another branch git cherry-pick <commit>..<commit>: bring in a range of commits from another branch (first excluded) git cherry-pick <commit>^..<commit>: bring in a range of commits from another branch (first included)

"},{"location":"misc/git.html#worktrees","title":"Worktrees","text":"

A git repository can support multiple working trees, allowing to check out more than one branch at a time.

Additional worktrees are called \"linked worktrees\" as opposed to the \"main worktree\" prepared by git init or git clone. A repository has one main worktree (if it\u2019s not a bare repository) and zero or more linked worktrees.

git worktree list: show worktrees git worktree add <path> <commit>: create worktree at <path> and checkout <commit> git worktree add -b <branch> <path> <commit>: create worktree and branch at <path> git worktree remove <worktree>: remove a worktree

"},{"location":"misc/git.html#rewriting-history","title":"Rewriting History","text":"

git commit --amend: replace last commit by creating a new one (can add files or rewrite commit message) git commit --amend -m \"amended message\": replace last commit by creating a new one (can add files or rewrite commit message) git commit --amend --no-edit: replace last commit by creating a new one (can add files or rewrite commit message)

git reset <commit>: revert to specific commit but keep changes git reset --soft <commit>: revert to specific commit but keep changes and staged files git reset --hard <commit>: revert to specific commit and discard changes git reset <commit> <file>: revert <file> to specific commit

git clean: remove untracked files form the working tree git clean -d: remove untracked files recursively git clean --interactive: remove untracked files interactively

git restore --source <commit> <file>: revert file to commit version git restore <deleted-file>: recover deleted file if previously committed

git rebase -i|--interactive: modify (reword, edit, drop, squash, merge, ...) current branch commits git rebase -i|--interactive HEAD~<n>: modify (reword, edit, drop, squash, merge, ...) n commits git rebase -i|--interactive <commit>: modify (reword, edit, drop, squash, merge, ...) from commit to latest git rebase --autostash: automatically create a temporary stash entry before rebasing git rebase --autosquash: automatically apply \"squash!\" or \"fixup!\" or \"amend!\" commits

"},{"location":"misc/git.html#git-revisions","title":"Git Revisions","text":""},{"location":"misc/git.html#specifying-revisions","title":"Specifying Revisions","text":"

A revision parameter <rev> can take one of these forms:

"},{"location":"misc/git.html#specifying-ranges","title":"Specifying Ranges","text":"

A revision range can take one of these forms: