To regenerate api.pb.go run hack/protoc/protoc.sh gen_proto
ImageService defines the public APIs for managing images.
| Method Name | Request Type | Response Type | Description |
| ListImages | ListImagesRequest | ListImagesResponse | ListImages lists existing images. |
| ImageStatus | ImageStatusRequest | ImageStatusResponse | ImageStatus returns the status of the image. If the image is not present, returns a response with ImageStatusResponse.Image set to nil. |
| PullImage | PullImageRequest | PullImageResponse | PullImage pulls an image with authentication config. |
| RemoveImage | RemoveImageRequest | RemoveImageResponse | RemoveImage removes the image. This call is idempotent, and must not return an error if the image has already been removed. |
| ImageFsInfo | ImageFsInfoRequest | ImageFsInfoResponse | ImageFSInfo returns information of the filesystem that is used to store images. |
Runtime service defines the public APIs for remote container runtimes
| Method Name | Request Type | Response Type | Description |
| Version | VersionRequest | VersionResponse | Version returns the runtime name, runtime version, and runtime API version. |
| RunPodSandbox | RunPodSandboxRequest | RunPodSandboxResponse | RunPodSandbox creates and starts a pod-level sandbox. Runtimes must ensure the sandbox is in the ready state on success. |
| StopPodSandbox | StopPodSandboxRequest | StopPodSandboxResponse | StopPodSandbox stops any running process that is part of the sandbox and reclaims network resources (e.g., IP addresses) allocated to the sandbox. If there are any running containers in the sandbox, they must be forcibly terminated. This call is idempotent, and must not return an error if all relevant resources have already been reclaimed. kubelet will call StopPodSandbox at least once before calling RemovePodSandbox. It will also attempt to reclaim resources eagerly, as soon as a sandbox is not needed. Hence, multiple StopPodSandbox calls are expected. |
| RemovePodSandbox | RemovePodSandboxRequest | RemovePodSandboxResponse | RemovePodSandbox removes the sandbox. If there are any running containers in the sandbox, they must be forcibly terminated and removed. This call is idempotent, and must not return an error if the sandbox has already been removed. |
| PodSandboxStatus | PodSandboxStatusRequest | PodSandboxStatusResponse | PodSandboxStatus returns the status of the PodSandbox. If the PodSandbox is not present, returns an error. |
| ListPodSandbox | ListPodSandboxRequest | ListPodSandboxResponse | ListPodSandbox returns a list of PodSandboxes. |
| CreateContainer | CreateContainerRequest | CreateContainerResponse | CreateContainer creates a new container in specified PodSandbox |
| StartContainer | StartContainerRequest | StartContainerResponse | StartContainer starts the container. |
| StopContainer | StopContainerRequest | StopContainerResponse | StopContainer stops a running container with a grace period (i.e., timeout). This call is idempotent, and must not return an error if the container has already been stopped. TODO: what must the runtime do after the grace period is reached? |
| RemoveContainer | RemoveContainerRequest | RemoveContainerResponse | RemoveContainer removes the container. If the container is running, the container must be forcibly removed. This call is idempotent, and must not return an error if the container has already been removed. |
| ListContainers | ListContainersRequest | ListContainersResponse | ListContainers lists all containers by filters. |
| ContainerStatus | ContainerStatusRequest | ContainerStatusResponse | ContainerStatus returns status of the container. If the container is not present, returns an error. |
| UpdateContainerResources | UpdateContainerResourcesRequest | UpdateContainerResourcesResponse | UpdateContainerResources updates ContainerConfig of the container. |
| ReopenContainerLog | ReopenContainerLogRequest | ReopenContainerLogResponse | ReopenContainerLog asks runtime to reopen the stdout/stderr log file for the container. This is often called after the log file has been rotated. If the container is not running, container runtime can choose to either create a new log file and return nil, or return an error. Once it returns error, new container log file MUST NOT be created. |
| ExecSync | ExecSyncRequest | ExecSyncResponse | ExecSync runs a command in a container synchronously. |
| Exec | ExecRequest | ExecResponse | Exec prepares a streaming endpoint to execute a command in the container. |
| Attach | AttachRequest | AttachResponse | Attach prepares a streaming endpoint to attach to a running container. |
| PortForward | PortForwardRequest | PortForwardResponse | PortForward prepares a streaming endpoint to forward ports from a PodSandbox. |
| ContainerStats | ContainerStatsRequest | ContainerStatsResponse | ContainerStats returns stats of the container. If the container does not exist, the call returns an error. |
| ListContainerStats | ListContainerStatsRequest | ListContainerStatsResponse | ListContainerStats returns stats of all running containers. |
| UpdateRuntimeConfig | UpdateRuntimeConfigRequest | UpdateRuntimeConfigResponse | UpdateRuntimeConfig updates the runtime configuration based on the given request. |
| Status | StatusRequest | StatusResponse | Status returns the status of the runtime. |
| StartPodSandbox | StartPodSandboxRequest | StartPodSandboxResponse | StartPodSandbox restart a sandbox pod which was stopped by accident and we should reconfigure it with network plugin which will make sure it reacquire its original network configuration, like IP address. |
VolumeService defines the public APIs for managing volumes.
| Method Name | Request Type | Response Type | Description |
| RemoveVolume | RemoveVolumeRequest | RemoveVolumeResponse | RemoveVolume removes the volume. |
| Field | Type | Label | Description |
| container_id | string | ID of the container to which to attach. |
|
| stdin | bool | Whether to stream stdin. One of `stdin`, `stdout`, and `stderr` MUST be true. |
|
| tty | bool | Whether the process being attached is running in a TTY. This must match the TTY setting in the ContainerConfig. |
|
| stdout | bool | Whether to stream stdout. One of `stdin`, `stdout`, and `stderr` MUST be true. |
|
| stderr | bool | Whether to stream stderr. One of `stdin`, `stdout`, and `stderr` MUST be true. If `tty` is true, `stderr` MUST be false. Multiplexing is not supported in this case. The output of stdout and stderr will be combined to a single stream. |
| Field | Type | Label | Description |
| url | string | Fully qualified URL of the attach streaming server. |
AuthConfig contains authorization information for connecting to a registry.
| Field | Type | Label | Description |
| username | string |
|
|
| password | string |
|
|
| auth | string |
|
|
| server_address | string |
|
|
| identity_token | string | IdentityToken is used to authenticate the user and get an access token for the registry. |
|
| registry_token | string | RegistryToken is a bearer token to be sent to a registry |
Capability contains the container capabilities to add or drop
| Field | Type | Label | Description |
| add_capabilities | string | repeated | List of capabilities to add. |
| drop_capabilities | string | repeated | List of capabilities to drop. |
Container provides the runtime information for a container, such as ID, hash,
state of the container.
| Field | Type | Label | Description |
| id | string | ID of the container, used by the container runtime to identify a container. |
|
| pod_sandbox_id | string | ID of the sandbox to which this container belongs. |
|
| metadata | ContainerMetadata | Metadata of the container. |
|
| image | ImageSpec | Spec of the image. |
|
| image_ref | string | Reference to the image in use. For most runtimes, this should be an image ID. |
|
| state | ContainerState | State of the container. |
|
| created_at | int64 | Creation time of the container in nanoseconds. |
|
| labels | Container.LabelsEntry | repeated | Key-value pairs that may be used to scope and select individual resources. |
| annotations | Container.AnnotationsEntry | repeated | Unstructured key-value map holding arbitrary metadata. Annotations MUST NOT be altered by the runtime; the value of this field MUST be identical to that of the corresponding ContainerConfig used to instantiate this Container. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
ContainerAttributes provides basic information of the container.
| Field | Type | Label | Description |
| id | string | ID of the container. |
|
| metadata | ContainerMetadata | Metadata of the container. |
|
| labels | ContainerAttributes.LabelsEntry | repeated | Key-value pairs that may be used to scope and select individual resources. |
| annotations | ContainerAttributes.AnnotationsEntry | repeated | Unstructured key-value map holding arbitrary metadata. Annotations MUST NOT be altered by the runtime; the value of this field MUST be identical to that of the corresponding ContainerConfig used to instantiate the Container this status represents. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
ContainerConfig holds all the required and optional fields for creating a
container.
| Field | Type | Label | Description |
| metadata | ContainerMetadata | Metadata of the container. This information will uniquely identify the container, and the runtime should leverage this to ensure correct operation. The runtime may also use this information to improve UX, such as by constructing a readable name. |
|
| image | ImageSpec | Image to use. |
|
| command | string | repeated | Command to execute (i.e., entrypoint for docker) |
| args | string | repeated | Args for the Command (i.e., command for docker) |
| working_dir | string | Current working directory of the command. |
|
| envs | KeyValue | repeated | List of environment variable to set in the container. |
| mounts | Mount | repeated | Mounts for the container. |
| devices | Device | repeated | Devices for the container. |
| labels | ContainerConfig.LabelsEntry | repeated | Key-value pairs that may be used to scope and select individual resources. Label keys are of the form: label-key ::= prefixed-name | name prefixed-name ::= prefix '/' name prefix ::= DNS_SUBDOMAIN name ::= DNS_LABEL |
| annotations | ContainerConfig.AnnotationsEntry | repeated | Unstructured key-value map that may be used by the kubelet to store and retrieve arbitrary metadata. Annotations MUST NOT be altered by the runtime; the annotations stored here MUST be returned in the ContainerStatus associated with the container this ContainerConfig creates. In general, in order to preserve a well-defined interface between the kubelet and the container runtime, annotations SHOULD NOT influence runtime behaviour. |
| log_path | string | Path relative to PodSandboxConfig.LogDirectory for container to store
the log (STDOUT and STDERR) on the host.
E.g.,
PodSandboxConfig.LogDirectory = `/var/log/pods/ |
|
| stdin | bool | Variables for interactive containers, these have very specialized use-cases (e.g. debugging). TODO: Determine if we need to continue supporting these fields that are part of Kubernetes's Container Spec. |
|
| stdin_once | bool |
|
|
| tty | bool |
|
|
| linux | LinuxContainerConfig | Configuration specific to Linux containers. |
|
| windows | WindowsContainerConfig | Configuration specific to Windows containers. |
|
| net_priority | int64 | NetPriority of the container |
|
| quota_id | string | QuotaId of the container |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
ContainerFilter is used to filter containers.
All those fields are combined with 'AND'
| Field | Type | Label | Description |
| id | string | ID of the container. |
|
| state | ContainerStateValue | State of the container. |
|
| pod_sandbox_id | string | ID of the PodSandbox. |
|
| label_selector | ContainerFilter.LabelSelectorEntry | repeated | LabelSelector to select matches. Only api.MatchLabels is supported for now and the requirements are ANDed. MatchExpressions is not supported yet. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
ContainerMetadata holds all necessary information for building the container
name. The container runtime is encouraged to expose the metadata in its user
interface for better user experience. E.g., runtime can construct a unique
container name based on the metadata. Note that (name, attempt) is unique
within a sandbox for the entire lifetime of the sandbox.
| Field | Type | Label | Description |
| name | string | Name of the container. Same as the container name in the PodSpec. |
|
| attempt | uint32 | Attempt number of creating the container. Default: 0. |
ContainerStateValue is the wrapper of ContainerState.
| Field | Type | Label | Description |
| state | ContainerState | State of the container. |
ContainerStats provides the resource usage statistics for a container.
| Field | Type | Label | Description |
| attributes | ContainerAttributes | Information of the container. |
|
| cpu | CpuUsage | CPU usage gathered from the container. |
|
| memory | MemoryUsage | Memory usage gathered from the container. |
|
| writable_layer | FilesystemUsage | Usage of the writeable layer. |
ContainerStatsFilter is used to filter containers.
All those fields are combined with 'AND'
| Field | Type | Label | Description |
| id | string | ID of the container. |
|
| pod_sandbox_id | string | ID of the PodSandbox. |
|
| label_selector | ContainerStatsFilter.LabelSelectorEntry | repeated | LabelSelector to select matches. Only api.MatchLabels is supported for now and the requirements are ANDed. MatchExpressions is not supported yet. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| container_id | string | ID of the container for which to retrieve stats. |
| Field | Type | Label | Description |
| stats | ContainerStats | Stats of the container. |
ContainerStatus represents the status of a container.
| Field | Type | Label | Description |
| id | string | ID of the container. |
|
| metadata | ContainerMetadata | Metadata of the container. |
|
| state | ContainerState | Status of the container. |
|
| created_at | int64 | Creation time of the container in nanoseconds. |
|
| started_at | int64 | Start time of the container in nanoseconds. Default: 0 (not specified). |
|
| finished_at | int64 | Finish time of the container in nanoseconds. Default: 0 (not specified). |
|
| exit_code | int32 | Exit code of the container. Only required when finished_at != 0. Default: 0. |
|
| image | ImageSpec | Spec of the image. |
|
| image_ref | string | Reference to the image in use. For most runtimes, this should be an image ID |
|
| reason | string | Brief CamelCase string explaining why container is in its current state. |
|
| message | string | Human-readable message indicating details about why container is in its current state. |
|
| labels | ContainerStatus.LabelsEntry | repeated | Key-value pairs that may be used to scope and select individual resources. |
| annotations | ContainerStatus.AnnotationsEntry | repeated | Unstructured key-value map holding arbitrary metadata. Annotations MUST NOT be altered by the runtime; the value of this field MUST be identical to that of the corresponding ContainerConfig used to instantiate the Container this status represents. |
| mounts | Mount | repeated | Mounts for the container. |
| log_path | string | Log path of container. |
|
| volumes | ContainerStatus.VolumesEntry | repeated | Volumes of container |
| resources | LinuxContainerResources | Resources specification for the container |
|
| quota_id | string | QuotaId of the container |
|
| envs | KeyValue | repeated | List of environment variable to set in the container. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| key | string |
|
|
| value | Volume |
|
| Field | Type | Label | Description |
| container_id | string | ID of the container for which to retrieve status. |
|
| verbose | bool | Verbose indicates whether to return extra information about the container. |
| Field | Type | Label | Description |
| status | ContainerStatus | Status of the container. |
|
| info | ContainerStatusResponse.InfoEntry | repeated | Info is extra information of the Container. The key could be arbitrary string, and value should be in json format. The information could include anything useful for debug, e.g. pid for linux container based container runtime. It should only be returned non-empty when Verbose is true. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
CpuUsage provides the CPU usage information.
| Field | Type | Label | Description |
| timestamp | int64 | Timestamp in nanoseconds at which the information were collected. Must be > 0. |
|
| usage_core_nano_seconds | UInt64Value | Cumulative CPU usage (sum across all cores) since object creation. |
| Field | Type | Label | Description |
| pod_sandbox_id | string | ID of the PodSandbox in which the container should be created. |
|
| config | ContainerConfig | Config of the container. |
|
| sandbox_config | PodSandboxConfig | Config of the PodSandbox. This is the same config that was passed to RunPodSandboxRequest to create the PodSandbox. It is passed again here just for easy reference. The PodSandboxConfig is immutable and remains the same throughout the lifetime of the pod. |
| Field | Type | Label | Description |
| container_id | string | ID of the created container. |
DNSConfig specifies the DNS servers and search domains of a sandbox.
| Field | Type | Label | Description |
| servers | string | repeated | List of DNS servers of the cluster. |
| searches | string | repeated | List of DNS search domains of the cluster. |
| options | string | repeated | List of DNS options. See https://linux.die.net/man/5/resolv.conf for all available options. |
Device specifies a host device to mount into a container.
| Field | Type | Label | Description |
| container_path | string | Path of the device within the container. |
|
| host_path | string | Path of the device on the host. |
|
| permissions | string | Cgroups permissions of the device, candidates are one or more of * r - allows container to read from the specified device. * w - allows container to write to the specified device. * m - allows container to create device files that do not yet exist. |
| Field | Type | Label | Description |
| container_id | string | ID of the container in which to execute the command. |
|
| cmd | string | repeated | Command to execute. |
| tty | bool | Whether to exec the command in a TTY. |
|
| stdin | bool | Whether to stream stdin. One of `stdin`, `stdout`, and `stderr` MUST be true. |
|
| stdout | bool | Whether to stream stdout. One of `stdin`, `stdout`, and `stderr` MUST be true. |
|
| stderr | bool | Whether to stream stderr. One of `stdin`, `stdout`, and `stderr` MUST be true. If `tty` is true, `stderr` MUST be false. Multiplexing is not supported in this case. The output of stdout and stderr will be combined to a single stream. |
| Field | Type | Label | Description |
| url | string | Fully qualified URL of the exec streaming server. |
| Field | Type | Label | Description |
| container_id | string | ID of the container. |
|
| cmd | string | repeated | Command to execute. |
| timeout | int64 | Timeout in seconds to stop the command. Default: 0 (run forever). |
| Field | Type | Label | Description |
| stdout | bytes | Captured command stdout output. |
|
| stderr | bytes | Captured command stderr output. |
|
| exit_code | int32 | Exit code the command finished with. Default: 0 (success). |
FilesystemIdentifier uniquely identify the filesystem.
| Field | Type | Label | Description |
| mountpoint | string | Mountpoint of a filesystem. |
FilesystemUsage provides the filesystem usage information.
| Field | Type | Label | Description |
| timestamp | int64 | Timestamp in nanoseconds at which the information were collected. Must be > 0. |
|
| fs_id | FilesystemIdentifier | The unique identifier of the filesystem. |
|
| used_bytes | UInt64Value | UsedBytes represents the bytes used for images on the filesystem. This may differ from the total bytes used on the filesystem and may not equal CapacityBytes - AvailableBytes. |
|
| inodes_used | UInt64Value | InodesUsed represents the inodes used by the images. This may not equal InodesCapacity - InodesAvailable because the underlying filesystem may also be used for purposes other than storing images. |
Basic information about a container image.
| Field | Type | Label | Description |
| id | string | ID of the image. |
|
| repo_tags | string | repeated | Other names by which this image is known. |
| repo_digests | string | repeated | Digests by which this image is known. |
| size | uint64 | Size of the image in bytes. Must be > 0. |
|
| uid | Int64Value | UID that will run the command(s). This is used as a default if no user is specified when creating the container. UID and the following user name are mutually exclusive. |
|
| username | string | User name that will run the command(s). This is used if UID is not set and no user is specified when creating container. |
|
| volumes | Image.VolumesEntry | repeated | Volumes of image |
| Field | Type | Label | Description |
| key | string |
|
|
| value | Volume |
|
| Field | Type | Label | Description |
| image | ImageSpec | Spec of the image. |
| Field | Type | Label | Description |
| image_filesystems | FilesystemUsage | repeated | Information of image filesystem(s). |
ImageSpec is an internal representation of an image. Currently, it wraps the
value of a Container's Image field (e.g. imageID or imageDigest), but in the
future it will include more detailed information about the different image types.
| Field | Type | Label | Description |
| image | string |
|
| Field | Type | Label | Description |
| image | ImageSpec | Spec of the image. |
|
| verbose | bool | Verbose indicates whether to return extra information about the image. |
| Field | Type | Label | Description |
| image | Image | Status of the image. |
|
| info | ImageStatusResponse.InfoEntry | repeated | Info is extra information of the Image. The key could be arbitrary string, and value should be in json format. The information could include anything useful for debug, e.g. image config for oci image based container runtime. It should only be returned non-empty when Verbose is true. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
Int64Value is the wrapper of int64.
| Field | Type | Label | Description |
| value | int64 | The value. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
LinuxContainerConfig contains platform-specific configuration for
Linux-based containers.
| Field | Type | Label | Description |
| resources | LinuxContainerResources | Resources specification for the container. |
|
| security_context | LinuxContainerSecurityContext | LinuxContainerSecurityContext configuration for the container. |
LinuxContainerResources specifies Linux specific configuration for
resources.
TODO: Consider using Resources from opencontainers/runtime-spec/specs-go
directly.
| Field | Type | Label | Description |
| cpu_period | int64 | CPU CFS (Completely Fair Scheduler) period. Default: 0 (not specified). |
|
| cpu_quota | int64 | CPU CFS (Completely Fair Scheduler) quota. Default: 0 (not specified). |
|
| cpu_shares | int64 | CPU shares (relative weight vs. other containers). Default: 0 (not specified). |
|
| memory_limit_in_bytes | int64 | Memory limit in bytes. Default: 0 (not specified). |
|
| oom_score_adj | int64 | OOMScoreAdj adjusts the oom-killer score. Default: 0 (not specified). |
|
| cpuset_cpus | string | CpusetCpus constrains the allowed set of logical CPUs. Default: "" (not specified). |
|
| cpuset_mems | string | CpusetMems constrains the allowed set of memory nodes. Default: "" (not specified). |
|
| disk_quota | LinuxContainerResources.DiskQuotaEntry | repeated | DiskQuota constrains the disk |
| blkio_weight | uint32 | Block IO weight (relative weight vs. other containers) |
|
| blkio_weight_device | WeightDevice | repeated |
|
| blkio_device_read_bps | ThrottleDevice | repeated |
|
| blkio_device_write_bps | ThrottleDevice | repeated |
|
| blkio_device_read_IOps | ThrottleDevice | repeated |
|
| blkio_device_write_IOps | ThrottleDevice | repeated |
|
| kernel_memory | int64 | Kernel memory limit (in bytes) |
|
| memory_reservation | int64 | Memory soft limit (in bytes) |
|
| memory_swappiness | Int64Value | Tuning container memory swappiness behaviour |
|
| ulimits | Ulimit | repeated | List of ulimits to be set in the container |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
LinuxContainerSecurityContext holds linux security configuration that will be applied to a container.
| Field | Type | Label | Description |
| capabilities | Capability | Capabilities to add or drop. |
|
| privileged | bool | If set, run container in privileged mode. Privileged mode is incompatible with the following options. If privileged is set, the following features MAY have no effect: 1. capabilities 2. selinux_options 4. seccomp 5. apparmor Privileged mode implies the following specific options are applied: 1. All capabilities are added. 2. Sensitive paths, such as kernel module paths within sysfs, are not masked. 3. Any sysfs and procfs mounts are mounted RW. 4. Apparmor confinement is not applied. 5. Seccomp restrictions are not applied. 6. The device cgroup does not restrict access to any devices. 7. All devices from the host's /dev are available within the container. 8. SELinux restrictions are not applied (e.g. label=disabled). |
|
| namespace_options | NamespaceOption | Configurations for the container's namespaces. Only used if the container uses namespace for isolation. |
|
| selinux_options | SELinuxOption | SELinux context to be optionally applied. |
|
| run_as_user | Int64Value | UID to run the container process as. Only one of run_as_user and run_as_username can be specified at a time. |
|
| run_as_group | Int64Value | GID to run the container process as. run_as_group should only be specified when run_as_user or run_as_username is specified; otherwise, the runtime MUST error. |
|
| run_as_username | string | User name to run the container process as. If specified, the user MUST exist in the container image (i.e. in the /etc/passwd inside the image), and be resolved there by the runtime; otherwise, the runtime MUST error. |
|
| readonly_rootfs | bool | If set, the root filesystem of the container is read-only. |
|
| supplemental_groups | int64 | repeated | List of groups applied to the first process run in the container, in addition to the container's primary GID. |
| apparmor_profile | string | AppArmor profile for the container, candidate values are:
* runtime/default: equivalent to not specifying a profile.
* unconfined: no profiles are loaded
* localhost/ |
|
| seccomp_profile_path | string | Seccomp profile for the container, candidate values are:
* runtime/default: the default profile for the container runtime
* unconfined: unconfined profile, ie, no seccomp sandboxing
* localhost/ |
|
| no_new_privs | bool | no_new_privs defines if the flag for no_new_privs should be set on the container. |
LinuxPodSandboxConfig holds platform-specific configurations for Linux
host platforms and Linux-based containers.
| Field | Type | Label | Description |
| cgroup_parent | string | Parent cgroup of the PodSandbox. The cgroupfs style syntax will be used, but the container runtime can convert it to systemd semantics if needed. |
|
| security_context | LinuxSandboxSecurityContext | LinuxSandboxSecurityContext holds sandbox security attributes. |
|
| sysctls | LinuxPodSandboxConfig.SysctlsEntry | repeated | Sysctls holds linux sysctls config for the sandbox. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
LinuxSandboxStatus contains status specific to Linux sandboxes.
| Field | Type | Label | Description |
| namespaces | Namespace | Paths to the sandbox's namespaces. |
LinuxSandboxSecurityContext holds linux security configuration that will be
applied to a sandbox. Note that:
1) It does not apply to containers in the pods.
2) It may not be applicable to a PodSandbox which does not contain any running
process.
| Field | Type | Label | Description |
| namespace_options | NamespaceOption | Configurations for the sandbox's namespaces. This will be used only if the PodSandbox uses namespace for isolation. |
|
| selinux_options | SELinuxOption | Optional SELinux context to be applied. |
|
| run_as_user | Int64Value | UID to run sandbox processes as, when applicable. |
|
| run_as_group | Int64Value | GID to run sandbox processes as, when applicable. run_as_group should only be specified when run_as_user is specified; otherwise, the runtime MUST error. |
|
| readonly_rootfs | bool | If set, the root filesystem of the sandbox is read-only. |
|
| supplemental_groups | int64 | repeated | List of groups applied to the first process run in the sandbox, in addition to the sandbox's primary GID. |
| privileged | bool | Indicates whether the sandbox will be asked to run a privileged container. If a privileged container is to be executed within it, this MUST be true. This allows a sandbox to take additional security precautions if no privileged containers are expected to be run. |
|
| seccomp_profile_path | string | Seccomp profile for the sandbox, candidate values are:
* runtime/default: the default profile for the container runtime
* unconfined: unconfined profile, ie, no seccomp sandboxing
* localhost/ |
| Field | Type | Label | Description |
| filter | ContainerStatsFilter | Filter for the list request. |
| Field | Type | Label | Description |
| stats | ContainerStats | repeated | Stats of the container. |
| Field | Type | Label | Description |
| filter | ContainerFilter |
|
| Field | Type | Label | Description |
| containers | Container | repeated | List of containers. |
| Field | Type | Label | Description |
| filter | ImageFilter | Filter to list images. |
| Field | Type | Label | Description |
| images | Image | repeated | List of images. |
| Field | Type | Label | Description |
| filter | PodSandboxFilter | PodSandboxFilter to filter a list of PodSandboxes. |
| Field | Type | Label | Description |
| items | PodSandbox | repeated | List of PodSandboxes. |
MemoryUsage provides the memory usage information.
| Field | Type | Label | Description |
| timestamp | int64 | Timestamp in nanoseconds at which the information were collected. Must be > 0. |
|
| working_set_bytes | UInt64Value | The amount of working set memory in bytes. |
Mount specifies a host volume to mount into a container.
| Field | Type | Label | Description |
| container_path | string | Path of the mount within the container. |
|
| host_path | string | Path of the mount on the host. If the hostPath doesn't exist, then runtimes should report error. If the hostpath is a symbolic link, runtimes should follow the symlink and mount the real destination to container. |
|
| readonly | bool | If set, the mount is read-only. |
|
| selinux_relabel | bool | If set, the mount needs SELinux relabeling. |
|
| propagation | MountPropagation | Requested propagation mode. |
|
| name | string | Name of volume |
Namespace contains paths to the namespaces.
| Field | Type | Label | Description |
| options | NamespaceOption | Namespace options for Linux namespaces. |
NamespaceOption provides options for Linux namespaces.
| Field | Type | Label | Description |
| network | NamespaceMode | Network namespace for this container/sandbox. Note: There is currently no way to set CONTAINER scoped network in the Kubernetes API. Namespaces currently set by the kubelet: POD, NODE |
|
| pid | NamespaceMode | PID namespace for this container/sandbox. Note: The CRI default is POD, but the v1.PodSpec default is CONTAINER. The kubelet's runtime manager will set this to CONTAINER explicitly for v1 pods. Namespaces currently set by the kubelet: POD, CONTAINER, NODE |
|
| ipc | NamespaceMode | IPC namespace for this container/sandbox. Note: There is currently no way to set CONTAINER scoped IPC in the Kubernetes API. Namespaces currently set by the kubelet: POD, NODE |
| Field | Type | Label | Description |
| pod_cidr | string | CIDR to use for pod IP addresses. If the CIDR is empty, runtimes should omit it. |
PodSandbox contains minimal information about a sandbox.
| Field | Type | Label | Description |
| id | string | ID of the PodSandbox. |
|
| metadata | PodSandboxMetadata | Metadata of the PodSandbox. |
|
| state | PodSandboxState | State of the PodSandbox. |
|
| created_at | int64 | Creation timestamps of the PodSandbox in nanoseconds. Must be > 0. |
|
| labels | PodSandbox.LabelsEntry | repeated | Labels of the PodSandbox. |
| annotations | PodSandbox.AnnotationsEntry | repeated | Unstructured key-value map holding arbitrary metadata. Annotations MUST NOT be altered by the runtime; the value of this field MUST be identical to that of the corresponding PodSandboxConfig used to instantiate this PodSandbox. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
PodSandboxConfig holds all the required and optional fields for creating a
sandbox.
| Field | Type | Label | Description |
| metadata | PodSandboxMetadata | Metadata of the sandbox. This information will uniquely identify the sandbox, and the runtime should leverage this to ensure correct operation. The runtime may also use this information to improve UX, such as by constructing a readable name. |
|
| hostname | string | Hostname of the sandbox. |
|
| log_directory | string | Path to the directory on the host in which container log files are
stored.
By default the log of a container going into the LogDirectory will be
hooked up to STDOUT and STDERR. However, the LogDirectory may contain
binary log files with structured logging data from the individual
containers. For example, the files might be newline separated JSON
structured logs, systemd-journald journal files, gRPC trace files, etc.
E.g.,
PodSandboxConfig.LogDirectory = `/var/log/pods/ |
|
| dns_config | DNSConfig | DNS config for the sandbox. |
|
| port_mappings | PortMapping | repeated | Port mappings for the sandbox. |
| labels | PodSandboxConfig.LabelsEntry | repeated | Key-value pairs that may be used to scope and select individual resources. |
| annotations | PodSandboxConfig.AnnotationsEntry | repeated | Unstructured key-value map that may be set by the kubelet to store and retrieve arbitrary metadata. This will include any annotations set on a pod through the Kubernetes API. Annotations MUST NOT be altered by the runtime; the annotations stored here MUST be returned in the PodSandboxStatus associated with the pod this PodSandboxConfig creates. In general, in order to preserve a well-defined interface between the kubelet and the container runtime, annotations SHOULD NOT influence runtime behaviour. Annotations can also be useful for runtime authors to experiment with new features that are opaque to the Kubernetes APIs (both user-facing and the CRI). Whenever possible, however, runtime authors SHOULD consider proposing new typed fields for any new features instead. |
| linux | LinuxPodSandboxConfig | Optional configurations specific to Linux hosts. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
PodSandboxFilter is used to filter a list of PodSandboxes.
All those fields are combined with 'AND'
| Field | Type | Label | Description |
| id | string | ID of the sandbox. |
|
| state | PodSandboxStateValue | State of the sandbox. |
|
| label_selector | PodSandboxFilter.LabelSelectorEntry | repeated | LabelSelector to select matches. Only api.MatchLabels is supported for now and the requirements are ANDed. MatchExpressions is not supported yet. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
PodSandboxMetadata holds all necessary information for building the sandbox name.
The container runtime is encouraged to expose the metadata associated with the
PodSandbox in its user interface for better user experience. For example,
the runtime can construct a unique PodSandboxName based on the metadata.
| Field | Type | Label | Description |
| name | string | Pod name of the sandbox. Same as the pod name in the PodSpec. |
|
| uid | string | Pod UID of the sandbox. Same as the pod UID in the PodSpec. |
|
| namespace | string | Pod namespace of the sandbox. Same as the pod namespace in the PodSpec. |
|
| attempt | uint32 | Attempt number of creating the sandbox. Default: 0. |
PodSandboxNetworkStatus is the status of the network for a PodSandbox.
| Field | Type | Label | Description |
| ip | string | IP address of the PodSandbox. |
PodSandboxStateValue is the wrapper of PodSandboxState.
| Field | Type | Label | Description |
| state | PodSandboxState | State of the sandbox. |
PodSandboxStatus contains the status of the PodSandbox.
| Field | Type | Label | Description |
| id | string | ID of the sandbox. |
|
| metadata | PodSandboxMetadata | Metadata of the sandbox. |
|
| state | PodSandboxState | State of the sandbox. |
|
| created_at | int64 | Creation timestamp of the sandbox in nanoseconds. Must be > 0. |
|
| network | PodSandboxNetworkStatus | Network contains network status if network is handled by the runtime. |
|
| linux | LinuxPodSandboxStatus | Linux-specific status to a pod sandbox. |
|
| labels | PodSandboxStatus.LabelsEntry | repeated | Labels are key-value pairs that may be used to scope and select individual resources. |
| annotations | PodSandboxStatus.AnnotationsEntry | repeated | Unstructured key-value map holding arbitrary metadata. Annotations MUST NOT be altered by the runtime; the value of this field MUST be identical to that of the corresponding PodSandboxConfig used to instantiate the pod sandbox this status represents. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| pod_sandbox_id | string | ID of the PodSandbox for which to retrieve status. |
|
| verbose | bool | Verbose indicates whether to return extra information about the pod sandbox. |
| Field | Type | Label | Description |
| status | PodSandboxStatus | Status of the PodSandbox. |
|
| info | PodSandboxStatusResponse.InfoEntry | repeated | Info is extra information of the PodSandbox. The key could be arbitrary string, and value should be in json format. The information could include anything useful for debug, e.g. network namespace for linux container based container runtime. It should only be returned non-empty when Verbose is true. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| pod_sandbox_id | string | ID of the container to which to forward the port. |
|
| port | int32 | repeated | Port to forward. |
| Field | Type | Label | Description |
| url | string | Fully qualified URL of the port-forward streaming server. |
PortMapping specifies the port mapping configurations of a sandbox.
| Field | Type | Label | Description |
| protocol | Protocol | Protocol of the port mapping. |
|
| container_port | int32 | Port number within the container. Default: 0 (not specified). |
|
| host_port | int32 | Port number on the host. Default: 0 (not specified). |
|
| host_ip | string | Host IP. |
| Field | Type | Label | Description |
| image | ImageSpec | Spec of the image. |
|
| auth | AuthConfig | Authentication configuration for pulling the image. |
|
| sandbox_config | PodSandboxConfig | Config of the PodSandbox, which is used to pull image in PodSandbox context. |
| Field | Type | Label | Description |
| image_ref | string | Reference to the image in use. For most runtimes, this should be an image ID or digest. |
| Field | Type | Label | Description |
| container_id | string | ID of the container to remove. |
| Field | Type | Label | Description |
| image | ImageSpec | Spec of the image to remove. |
| Field | Type | Label | Description |
| pod_sandbox_id | string | ID of the PodSandbox to remove. |
| Field | Type | Label | Description |
| volume_name | string | Name of the volume to remove |
| Field | Type | Label | Description |
| container_id | string | ID of the container for which to reopen the log. |
| Field | Type | Label | Description |
| config | PodSandboxConfig | Configuration for creating a PodSandbox. |
| Field | Type | Label | Description |
| pod_sandbox_id | string | ID of the PodSandbox to run. |
RuntimeCondition contains condition information for the runtime.
There are 2 kinds of runtime conditions:
1. Required conditions: Conditions are required for kubelet to work
properly. If any required condition is unmet, the node will be not ready.
The required conditions include:
* RuntimeReady: RuntimeReady means the runtime is up and ready to accept
basic containers e.g. container only needs host network.
* NetworkReady: NetworkReady means the runtime network is up and ready to
accept containers which require container network.
2. Optional conditions: Conditions are informative to the user, but kubelet
will not rely on. Since condition type is an arbitrary string, all conditions
not required are optional. These conditions will be exposed to users to help
them understand the status of the system.
| Field | Type | Label | Description |
| type | string | Type of runtime condition. |
|
| status | bool | Status of the condition, one of true/false. Default: false. |
|
| reason | string | Brief CamelCase string containing reason for the condition's last transition. |
|
| message | string | Human-readable message indicating details about last transition. |
| Field | Type | Label | Description |
| network_config | NetworkConfig |
|
RuntimeStatus is information about the current status of the runtime.
| Field | Type | Label | Description |
| conditions | RuntimeCondition | repeated | List of current observed runtime conditions. |
SELinuxOption are the labels to be applied to the container.
| Field | Type | Label | Description |
| user | string |
|
|
| role | string |
|
|
| type | string |
|
|
| level | string |
|
| Field | Type | Label | Description |
| container_id | string | ID of the container to start. |
| Field | Type | Label | Description |
| pod_sandbox_id | string | ID of the PodSandbox to start. |
| Field | Type | Label | Description |
| verbose | bool | Verbose indicates whether to return extra information about the runtime. |
| Field | Type | Label | Description |
| status | RuntimeStatus | Status of the Runtime. |
|
| info | StatusResponse.InfoEntry | repeated | Info is extra information of the Runtime. The key could be arbitrary string, and value should be in json format. The information could include anything useful for debug, e.g. plugins used by the container runtime. It should only be returned non-empty when Verbose is true. |
| Field | Type | Label | Description |
| key | string |
|
|
| value | string |
|
| Field | Type | Label | Description |
| container_id | string | ID of the container to stop. |
|
| timeout | int64 | Timeout in seconds to wait for the container to stop before forcibly terminating it. Default: 0 (forcibly terminate the container immediately) |
| Field | Type | Label | Description |
| pod_sandbox_id | string | ID of the PodSandbox to stop. |
ThrottleDevice is a structure that holds device:rate_per_second pair
| Field | Type | Label | Description |
| path | string | Path of throttledevice. |
|
| rate | uint64 | Rate of throttledevice. |
UInt64Value is the wrapper of uint64.
| Field | Type | Label | Description |
| value | uint64 | The value. |
Ulimit is a human friendly version of Rlimit.
| Field | Type | Label | Description |
| name | string | Name of ulimit. |
|
| hard | int64 | Hard limit of ulimit. |
|
| soft | int64 | Soft limit of Ulimit. |
| Field | Type | Label | Description |
| container_id | string | ID of the container to update. |
|
| linux | LinuxContainerResources | Resource configuration specific to Linux containers. |
| Field | Type | Label | Description |
| runtime_config | RuntimeConfig |
|
| Field | Type | Label | Description |
| version | string | Version of the kubelet runtime API. |
| Field | Type | Label | Description |
| version | string | Version of the kubelet runtime API. |
|
| runtime_name | string | Name of the container runtime. |
|
| runtime_version | string | Version of the container runtime. The string must be semver-compatible. |
|
| runtime_api_version | string | API version of the container runtime. The string must be semver-compatible. |
WeightDevice is a structure that holds device:weight pair
| Field | Type | Label | Description |
| path | string | Path of weightdevice. |
|
| Weight | uint32 | Weight of weightdevice. |
WindowsContainerConfig contains platform-specific configuration for
Windows-based containers.
| Field | Type | Label | Description |
| resources | WindowsContainerResources | Resources specification for the container. |
WindowsContainerResources specifies Windows specific configuration for
resources.
| Field | Type | Label | Description |
| cpu_shares | int64 | CPU shares (relative weight vs. other containers). Default: 0 (not specified). |
|
| cpu_count | int64 | Number of CPUs available to the container. Default: 0 (not specified). |
|
| cpu_maximum | int64 | Specifies the portion of processor cycles that this container can use as a percentage times 100. |
|
| memory_limit_in_bytes | int64 | Memory limit in bytes. Default: 0 (not specified). |
| Name | Number | Description |
| CONTAINER_CREATED | 0 | |
| CONTAINER_RUNNING | 1 | |
| CONTAINER_EXITED | 2 | |
| CONTAINER_UNKNOWN | 3 |
| Name | Number | Description |
| PROPAGATION_PRIVATE | 0 | No mount propagation ("private" in Linux terminology). |
| PROPAGATION_HOST_TO_CONTAINER | 1 | Mounts get propagated from the host to the container ("rslave" in Linux). |
| PROPAGATION_BIDIRECTIONAL | 2 | Mounts get propagated from the host to the container and from the container to the host ("rshared" in Linux). |
A NamespaceMode describes the intended namespace configuration for each
of the namespaces (Network, PID, IPC) in NamespaceOption. Runtimes should
map these modes as appropriate for the technology underlying the runtime.
| Name | Number | Description |
| POD | 0 | A POD namespace is common to all containers in a pod. For example, a container with a PID namespace of POD expects to view all of the processes in all of the containers in the pod. |
| CONTAINER | 1 | A CONTAINER namespace is restricted to a single container. For example, a container with a PID namespace of CONTAINER expects to view only the processes in that container. |
| NODE | 2 | A NODE namespace is the namespace of the Kubernetes node. For example, a container with a PID namespace of NODE expects to view all of the processes on the host running the kubelet. |
| Name | Number | Description |
| SANDBOX_READY | 0 | |
| SANDBOX_NOTREADY | 1 |
| Name | Number | Description |
| TCP | 0 | |
| UDP | 1 |
| .proto Type | Notes | C++ Type | Java Type | Python Type |
| double | double | double | float | |
| float | float | float | float | |
| int32 | Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead. | int32 | int | int |
| int64 | Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead. | int64 | long | int/long |
| uint32 | Uses variable-length encoding. | uint32 | int | int/long |
| uint64 | Uses variable-length encoding. | uint64 | long | int/long |
| sint32 | Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s. | int32 | int | int |
| sint64 | Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s. | int64 | long | int/long |
| fixed32 | Always four bytes. More efficient than uint32 if values are often greater than 2^28. | uint32 | int | int |
| fixed64 | Always eight bytes. More efficient than uint64 if values are often greater than 2^56. | uint64 | long | int/long |
| sfixed32 | Always four bytes. | int32 | int | int |
| sfixed64 | Always eight bytes. | int64 | long | int/long |
| bool | bool | boolean | boolean | |
| string | A string must always contain UTF-8 encoded or 7-bit ASCII text. | string | String | str/unicode |
| bytes | May contain any arbitrary sequence of bytes. | string | ByteString | str |


{% load staticfiles %}
Here you can add your receipts and analyse your past expenses.
lista paragonow wprowadz paragon
Sign up


After 20 years of glory, Hotel Escober revives its famed legacy of comfort,elegance and impeeciable service.
With its richly historic past,Hotel Escober now fully becomes a part of the exciting and rapidly changing present with the addition of a modern,elegant luxuary ocean front hotel. The beauty of Cox's Bazar, the climate, the panoramic ocean views, the sandy beaches plus the rich culture and history along with the warmth of the sun is what attracts people here. And Hotel Escober provides you exactly just that with extraordinary comfort comfort, luxury and services. There is so much to discover and its all step away.


George Williams
koha-US member and Past Presidentwww.koha-us.org
USA - Kansas is in the middle.
I am the Next Search Catalog Coordinator at
Northeast Kansas Library System in Lawrence, KS.
117 NEKLS Libraries in the highlighted area.
NEKLS provides many services to all types of libraries in north east Kansas.
The 14 highlighted counties account for approximately 44% of the population of Kansas.
Next Search Catalog
(used to be called NExpress)
Next Search Catalog is only one of the services NEKLS provides.
51 of our member libraries participate in our shared catalog.
Using Koha since 2008.
Community Koha hosted by ByWater Solutions since 2011.
My life before Kansas
- Originally from Idaho.
- Latah County Library District
- Circulation Manager (2006-2016).
- University of Idaho
- TA and Lecturer (2002-2006).
- Boise Public Library
- Bookmobile Specialist (1997-2002).
- University of Idaho Library
- Student Employee (1996-1997).
- +Bus driver, Restaurant manager, Cook, Dishwasher, Sophisticated man about town.


--- layout: projects_default title: CMU nav: projects box: true summary: Research at CMU ---
I began working in CMU's HCII department as a Senior Software/Systems Engineer for the CHIMPS lab under Professor Jason Hong. The CHIMPS lab focuses on research involving ubiquitous computing and usable privacy and security solutions for users. I am working on several projects for the lab, using several different technologies. My main conerns here are ClearTerms, a crowd-sourced, machine learning algorithm for detecting the most important statement in terms and conditions, and another project (retricted per US DOD) dealing with controlling app's ability to access user's private data.


1. Challenge
-
Purpose: Create a program doing data mining
The program will:
-
Read from log of plane traffic leaving from an airport
-
Generate a ranking of the flights and airlines based on take-off time
4 files:
-
airlines.py: Description of class "Airline" (c.f. details later)
-
processRecords.py: Main program that processes data from input file to generate a report
-
report_Template.html: Template for the html report generated by the program (provided)
-
test_airlines.py: Unit tests (pytest) of your program (provided)
1.1. Description of input files
The input is a list of records of planes, with 1 record per line.
Syntax:
<date>, <time>,<code>, <airline>, <destination>, <take-off>
With: .Data in records
| Field | Description | Example |
|---|---|---|
<date> |
Date of the flight in format |
2015-08-21 |
<time> |
Planned departure time (hh:mm) |
13:10 |
<code> |
Code of the flight |
AF117 |
<airline> |
Name of the airline |
Air France |
<destination> |
Name of the destination airport |
Nagoya Intl Airport |
<take-off> |
Real Time of take off (hh:mm) |
19:25 |
Example:
2015-08-21, 10:20, AF117, Air France, Paris Ch. de Gaulle, 11:20
2015-08-21, 10:30, 9C8601, China Spring Airlines, Nagoya Intl Airport, 12:35
2015-08-21, 10:35, CA155, China International Airlines, Sendai, 13:30
1.2. Class Airline (airline.py)
4 attributes:
-
"name" (e.g. "Air France")
-
"code" made of 2 letters (e.g. "AF")
-
"flights": dictionary, key="code flight", value = list of take-off records
Example:{ 'AF123': [ {'date':"2018-02-29", 'time':"12:13", "delay":45}, {'date':"2018-02-30", 'time':"12:13", "delay":15} ], 'AF234': [ {'date':"2018-02-29", 'time':"15:25", "delay":-3}, ] }
A record is a dictionary with 3 keys: date, time (expected), delay -
"destination": dictionary with key = "code flight", value = "destination airport"
Example:{'AF123': "Paris Orly"}
delay
= <take-off> - <time> (measured in minutes)
We recommend to create a function get_delay to compute the delay (in minutes).
|
3 methods:
-
add_info: add flight information (dictionary) and store in attributes
flights
anddestination
.
Create flight if it does not exist
Prototype:add_info(self, info) → None # info is a dictionary
-
get_rating_flight: return tuple (% late, average delay) for a flight
Prototype:get_rating_flight(self, flight_code:str) → Tuple[int, int]
-
get_rating_airline: return tuple (% late, average delay) for airline
Prototype:get_rating_airline(self) → Tuple[int, int]
|
1.3. Main Program (processRecords.py)
1.3.1. Function read_flight_records
-
Input: input file name (string)
-
Output: list of take off records, each element is a dictionary with following keys:
date, time, code, airline, destination, and take-off
[
{
"date":"2018-02-29", "time":"15:25", "code":"MU123",
"airline":"China Eastern", "destination":"Bali", "take-off":"15:45"
},
{
"date":"2018-02-29", "time":"15:35", "code":"AF123",
"airline":"Air France", "destination":"Paris", "take-off":"15:50"
}
]
1.3.2. Function get_ratings_airlines
-
Input: list of landing records returned by
read_flight_records
-
Output: dictionary with key=airline name, value=Object of class Airline with all the records of that airline
{
"Air France":<Airline object>,
"China Eastern":<Airline object>
}
1.3.3. Function list_sorted_ratings
-
Input: dictionary returned by
get_ratings_airlines
-
Output: 2 lists sorted based on "% late" (lowest % first)
-
list of tuples (<airline>, <% late>, <average delay>) for each airline
-
list of tuples (<code>, <% late>, <average delay>) for each flight
-
| all the results shall be integers |
[("China Eastern", 10, 5), ("Air France", 11, 8), ...],
[("MU123", 10, 5), ("AF123", 11, 8), ...],
1.3.4. Function get_first_last_elem
-
Input:
-
<list_ranking>
-
<nb_elem>
(number of elements)
-
-
Output: 2 lists with first and last
<nb_elem>
elements
>>> get_first_last_elem(['a', 'b', 'c', 'd', 'e'], 2)
(['a','b'], ['e', 'd']) (1)
| 1 | Notice that the last elements shall be in reversed order (i.e. starting from last element) |
1.3.5. Main function
-
Parse arguments based on following usage:
processRecords.py <input file> [(-o|--output) <report file>] [-n <nb_ranking>]
default value of <nb_ranking>
is 10 -
Read data from the input file with function
read_flight_records
-
Create dictionary of airlines with function
get_ratings_airlines
-
Sort airlines and flights with function
list_sorted_ratings
-
Generate a report (by using function
get_first_last_elem
) with:-
List of <nb_ranking> best airlines based on chances to be late
-
List of <nb_ranking> best flights based on chances to be late
-
List of <nb_ranking> worse airlines based on chances to be late
-
List of <nb_ranking> worse flights based on chances to be late
-
2. Check your code
You can use the following code to test your program.
To run it you need first to install pytest
and then run:
python -m pytest -v test_airlines.py
#!python
##############
# HOW TO RUN #
##############
# 1. Install Pytest
"pip install pytest"
# 2. Run Tests
"pytest -v test_airlines.py"
# NOTE: if "pytest" is not found, run "python -m pytest ..."
##############
import pytest
from typing import Dict, List, Any
from airlines import Airline, get_delay
try:
from airlines import get_delay_2
except ImportError:
get_delay_2 = get_delay
import processRecords as rec
def test_delay():
assert get_delay("12:10", "12:45") == 35
assert get_delay("12:10", "11:45") == -25
assert get_delay("23:45", "00:45") == 60
assert get_delay("00:45", "23:45") == -60
# For alternate solution
assert get_delay_2("12:10", "12:45") == 35
assert get_delay_2("12:10", "11:45") == -25
assert get_delay_2("23:45", "00:45") == 60
assert get_delay_2("00:45", "23:45") == -60
# Test class "Airline"
class Test_Airline:
"""Test class 'Airline'"""
def test_01_init(self):
""" Test initialization of class Airline"""
sq = Airline("Singapore Airlines", "SQ")
assert sq.flights == {}
assert sq.destination == {}
assert sq.name == "Singapore Airlines"
assert sq.code == "SQ"
def add_info_SQ_MU(self):
"""Function to add records - to be used for other tests"""
sq = Airline("Singapore Airlines", "SQ")
mu = Airline("China Eastern", "MU")
sq.add_info(
{
"date": "2015-08-20",
"time": "08:05",
"code": "SQ827",
"destination": "Singapore",
"take-off": "09:08",
}
)
sq.add_info(
{
"date": "2015-08-21",
"time": "08:05",
"code": "SQ827",
"destination": "Singapore",
"take-off": "08:35",
}
)
mu.add_info(
{
"date": "2015-08-20",
"time": "08:20",
"code": "MU511",
"destination": "Osaka Kansai",
"take-off": "8:25",
}
)
mu.add_info(
{
"date": "2015-08-20",
"time": "08:30",
"code": "MU721",
"destination": "Seoul",
"take-off": "9:30",
}
)
return sq, mu
def test_02_add_info(self):
"""Add record to list of flights"""
sq, mu = self.add_info_SQ_MU()
assert sq.flights == {
"SQ827": [
{"date": "2015-08-20", "delay": 63, "time": "08:05"},
{"date": "2015-08-21", "delay": 30, "time": "08:05"},
]
}
assert sq.destination == {"SQ827": "Singapore"}
assert mu.flights == {
"MU511": [{"date": "2015-08-20", "delay": 5, "time": "08:20"}],
"MU721": [{"date": "2015-08-20", "delay": 60, "time": "08:30"}],
}
assert mu.destination == {"MU511": "Osaka Kansai", "MU721": "Seoul"}
def test_03_get_rating_flight(self):
"""Get the rating of a given flight"""
sq, mu = self.add_info_SQ_MU()
assert sq.get_rating_flight("SQ827") == (50, 46)
assert mu.get_rating_flight("MU511") == (0, 5)
def test_04_get_rating_airline(self):
"""Get the rating of the airline"""
sq, mu = self.add_info_SQ_MU()
assert sq.get_rating_airline() == (50, 46)
assert mu.get_rating_airline() == (50, 32)
# Test main program
class TestMain(object):
"""Test main program (processRecords.py)"""
def test_01_read_flight_records_robustness(self):
"""Read flight records from an unknown file"""
with pytest.raises(IOError):
rec.read_flight_records("unknown.txt")
def test_01_read_flight_records(self):
"""Read flight records from an existing file"""
records = rec.read_flight_records("mini_record.txt")
assert records == [
{
"code": "EK303",
"take-off": "0:41",
"destination": "Dubai",
"airline": "Emirates Airlines",
"time": "0:05",
"date": "2015-08-20",
},
{
"code": "MU553",
"take-off": "0:15",
"destination": "Paris Ch. de Gaulle",
"airline": "China Eastern Airlines",
"time": "0:05",
"date": "2015-08-20",
},
{
"code": "MU219",
"take-off": "0:45",
"destination": "Frankfurt",
"airline": "China Eastern Airlines",
"time": "0:05",
"date": "2015-08-20",
},
]
def test_02_get_ratings_flight(self):
"""Get rating of flight"""
af = Airline("Air France", "Air France")
af.add_info(
{
"date": "2015-08-24",
"time": "12:00",
"code": "AF117",
"destination": "CDG",
"take-off": "12:46",
}
)
assert af.get_rating_flight("Unknown") == (None, None)
assert af.get_rating_flight("AF117") == (100, 46)
af.add_info(
{
"date": "2015-08-24",
"time": "12:00",
"code": "AF117",
"destination": "CDG",
"take-off": "11:46",
}
)
assert af.get_rating_flight("AF117") == (50, 16)
def test_03_get_ratings_airline(self):
"""Get ratings of airlines based on the records"""
records = rec.read_flight_records("mini_record.txt")
airlines = rec.get_ratings_airlines(records)
assert airlines["Emirates Airlines"].__dict__ == {
"destination": {"EK303": "Dubai"},
"flights": {"EK303": [{"date": "2015-08-20", "delay": 36, "time": "0:05"}]},
"code": "EK",
"name": "Emirates Airlines",
}
assert airlines["China Eastern Airlines"].__dict__ == {
"destination": {"MU553": "Paris Ch. de Gaulle", "MU219": "Frankfurt"},
"flights": {
"MU553": [{"date": "2015-08-20", "delay": 10, "time": "0:05"}],
"MU219": [{"date": "2015-08-20", "delay": 40, "time": "0:05"}],
},
"code": "MU",
"name": "China Eastern Airlines",
}
def test_04_list_sorted_ratings(self):
"""Sort the airlines and flights based on the chances to be late"""
records = rec.read_flight_records("mini_record.txt")
airlines = rec.get_ratings_airlines(records)
rating_airlines, rating_flights = rec.list_sorted_ratings(airlines)
assert rating_airlines == [
("China Eastern Airlines", 50, 25),
("Emirates Airlines", 100, 36),
]
assert rating_flights == [
("MU553", 0, 10),
("EK303", 100, 36),
("MU219", 100, 40),
]
def test_05_get_first_last_elem(self):
"""Return lists with first/last <nb_elem> elements"""
first, last = rec.get_first_last_elem(["f", "e", "d", "c", "b", "a"], 0)
assert first == []
assert last == []
first, last = rec.get_first_last_elem(["f", "e", "d", "c", "b", "a"], 4)
assert first == ["f", "e", "d", "c"]
assert last == ["a", "b", "c", "d"]
rating_flights = [("AA", 100), ("ZZ", 2), ("CC", 3), ("dd", 400), ("EE", 3)]
first, last = rec.get_first_last_elem(rating_flights, 2)
assert first == [("AA", 100), ("ZZ", 2)]
assert last == [("EE", 3), ("dd", 400)]
if __name__ == "__main__":
pytest.main(args=["-v"])
3. Solution: Prototypes and Docstrings
Below is the the prototype of the functions and a suggestion of docstring.
3.1. airlines.py
def get_delay(expected: str, takeoff: str) -> int:
"""\
Measure the time difference in minutes between two times
delay = <take-off> - <expected>
Args:
expected: expected departure time (e.g. 23:45)
takeoff: real departure time (e.g. 23:55)
"""
class Airline:
"""Class describing an airline with records"""
def __init__(self, name, code):
"""Creation of an airline with records"""
self.name = name
self.code = code
self.flights = defaultdict(list) # So ".append(...)" will work automatically
self.destination = dict()
def add_info(self, record):
"""Add flight information, create flight if it does not exist
Args:
record(dict): dictionary with keys:
* 'date': date of the flight, stored as a string (e.g. "2018-02-30")
* 'time': expected take-off time, stored as a string (e.g. "15:30")
* 'code': code of flight (e.g. "MU123")
* 'destination'
* 'take-off': real take-off time, stored as a string
"""
def get_rating_flight(self, flight: str):
"""Get the rating of a given flight
Args:
flight: code of a flight
Returns:
('% late', 'average delay') for a flight, both int
"""
def get_rating_airline(self):
"""Get the rating of the airline
Returns:
('% late', 'average delay') for the airline, both int
"""
3.2. processRecords.py
def read_flight_records(file_path: str):
"""\
Read flight records from a given file and returns the list of take-off records.
Each element is a dict with keys: date, time, code, airline, destination, take-off
Args:
file_path: Path of file to read
Returns:
list of take off records
"""
def get_ratings_airlines(list_records):
"""From the list of records, create a dictionary with all Airlines
Args:
list_records(list): list of dict returned by read_flight_records
Returns:
dictionary "airlines_dic" with:
* key = airline name
* value = "Airline" object with all the records of that airline
"""
def list_sorted_ratings(airlines_dic):
"""Sort the airlines and flights based on the probability to be late
Args:
airlines_dic(dict): Dictionary with Airline objects
Returns:
rating_airlines(list): list of Airlines sorted by late probability (less late first)
rating_flights(list): list of flights sorted by late probability (less late first)
NOTE: Each element of the returned lists contains the following tuple:
(<airline|flight code>, <% late>, <average delay>)
"""
def get_first_last_elem(sorted_list, nb_elem: int):
"""Return lists with first/last <nb_elem> elements
Args:
sorted_list(list): list of elements
nb_elem(int): number of first/last elements
Return:
first(list): first nb_elem elements of sorted_list
last(list): last nb_elem elements of sorted_list in reverse order
"""
##=== MAIN PROGRAM ===##
if __name__ == "__main__":
# Main Program
description = """processRecords.py - Generating a report of airines and flights based on their delay"""
4. Solution: Algorithms
These are some simple hints to help you start: it provides the algorithm.
4.1. airlines.py / get_delay
This function takes 2 strings (e.g. "12:15" and "13:4") for respectively planned time and take-off. It returns a delay as integer.
First, we need to convert the strings into time (2 possibilities):
-
Using
datetime.datetime.strptime(<time>, "%H:%M")
to convert intodatetime
objects -
Calculating number of minutes in the day (i.e.
<HH> * 60 + <MM>
)
We will then calculate the difference.
We have 4 cases for the delay:
-
both times before midnight, take-off is after planned time
-
both times before midnight, take-off is before planned time
-
take-off is after midnight, planned time is before midnight
-
take-off is before midnight, planned time is after midnight
To cover all cases, we can:
-
Return
-1 * delay(take_off, planned)
if take-off is before planned time [cases 2 and 3] -
Return
difference - 1 day
if the difference is bigger than 12 hours [case 4] -
Return the difference otherwise [case 1]
4.2. airlines.py / Airline.add_info
We need to save the destination into self.destination
dictionary.
There are 2 possibilities:
-
Store only when necessary (i.e. check if
record["code"]
is already a key ofself.destination
) -
Store systematically (i.e. no check like in previous solution)
To store the dictionary with information we need to get 3 data
-
date: same as the one in
record
passed as argument -
time: same as the one in
record
passed as argument -
delay: computed by using function
get_delay
After creating the dictionary, append it to the list self.flights[record[code]]
.
|
To append the first element to a list, either
|
4.3. airlines.py / Airline.get_rating_flight
This function returns statistics on a given flight.
We need to consider the case where the flight is not found in self.flights : an example would be to return None, None .
|
We need to compute:
-
Percent of late flights (i.e. number of records with delay > 30 min / number of records for the flight)
-
Average of delay (i.e. total delay / number of records for the flight)
To do that, we need 2 numbers initiated to 0: nb_late
and total_delay
.
We loop each record and:
-
Increment
nb_late
by 1 if the delay is bigger than 30 minutes -
Increment
total_delay
by the delay
We finally return the integer values corresponding to:
-
nb_late
/ number of records for the flight * 100 -
total_delay
/ number of records for the flight
4.4. airlines.py / Airline.get_rating_flight
This function returns the same statistics for the airline on all its flights.
2 possibilities:
-
Re-use the method
get_rating_flight
for each flight of the airline -
Use similar algorithm of
get_rating_flight
with-
Loop for each flight of the airline
-
Divide
nb_late
andtotal_delay
by the total number of records for all the flights
-
4.5. processRecords.py / read_flight_records
We will first parse each line and split it into the elements to process
-
Solution #1: Using regular expression to ensure strict pattern matching
-
Solution #2: Using
<line>.split(",")
and stripping all spaces around each elementFor solution #2, we need to check the number of elements returned by the split to verify that we have as many elements as the keys.
We will create a dictionary with following keys:
record_keys = ["date", "time", "code", "airline", "destination", "take-off"]
We will match the extracted elements to record_keys
by:
-
Using
zip(<lis1>, <list2>)
function -
Using
dict(…)
on this zipped list to create a dictionary with key and value
|
The function
|
We will add the created dictionary to the list of records and will return this list.
4.6. processRecords.py / get_ratings_airlines
The purpose of this function is to create a dictionary with
-
key = airline name
-
value = "Airline" object with all the records of that airline
To do that, we can loop each element of list of record (the input) and
-
Create a new Airline if it does not exist in the dictionary (and store it in the dictionary)
-
Add the record in the Airline object stored in the dictionary
To create an Airline object, we need the airline code
that corresponds to the first 2 letters of the flight code.
For example, a flight code "AF123" would give the airline code "AF" .
|
4.7. processRecords.py / list_sorted_ratings
This function parse the dictionary created by get_rating_airlines
and returns 2 lists:
-
List of tuples
(<airline name>, <% late>, <average delay>)
sorted by `<% late>% (ascending order) for all airlines -
List of tuples
(<flight code>, <% late>, <average delay>)
sorted by `<% late>% (ascending order) for all flights of all airlines
We will do:
-
Create 2 empty lists (
rating_airlines
andrating_flights
) -
Loop on each airline
-
Use
<airline>.get_rating_airline
method to get the rating and append torating_airlines
-
Loop on each flight of the airline: use
<airline>.get_rating_flight
method to get the rating and append torating_flights
-
-
Sort
rating_airlines
andrating_flights
based on probability to be late
4.8. processRecords.py / get_first_last_elem
The purpose of this function is to return 2 lists:
-
First
nb_elem
elements ofsorted_list
-
Last
nb_elem
elements ofsorted_list
in reversed order
To do that, we can use the list index […:…]
and the <list>.reverse()
function.
4.9. processRecords.py / main function
For the arguments, we will use the module argparse
with its class argparse.ArgumentParser
.
We can then use arguments:
-
cmd.input_path
: path of file with data to parse withread_flight_records
-
cmd.nb_ranking
: number of elements to keep inget_first_last_elem
-
cmd.report_path
: path of HTML file to generate
We need to:
-
Call
read_flight_records
and store the result -
Use this result in
get_ratings_airlines
and store the result -
Use this result in
list_sorted_ratings
and store the resulting lists -
Use these two lists with
get_first_last_elem
to extractcmd.nb_ranking
best/worse elements (airlines and flights) -
Read the template
"report_Template.html"
and save its contentWe shall replace {
by{{
and}
by}}
in the<style>…</style>
blocks of the HTML template -
Generate the content of the report based on the template (see below)
-
Write the content in
cmd.report_path
# Prepare the report
report = dict()
# time
report["date"] = str(datetime.date.today())
report["time"] = str(datetime.datetime.now().time())[:8]
# rankings
def store_ranking(key, ranking):
str_info = "<b>{0}</b> ({1}%, avg={2} min)"
report[key] = "</li>\n<li>".join([str_info.format(*t) for t in ranking])
store_ranking("best_airlines", best_airlines)
store_ranking("worse_airlines", worse_airlines)
store_ranking("best_flights", best_flights)
store_ranking("worse_flights", worse_flights)
# Generate the report
report_content = template.format(**report)
5. Final Solution
The comments #tag::… and #end::… have been added to
extract code in the current HTML file. They are not useful in the final code
|
5.1. airlines.py
#!python
from collections import defaultdict
from datetime import datetime
# #-- CALCULATION OF TIME DELTA --##
# tag::header[]
# tag::get_delay[]
def get_delay(expected: str, takeoff: str) -> int:
"""\
Measure the time difference in minutes between two times
delay = <take-off> - <expected>
Args:
expected: expected departure time (e.g. 23:45)
takeoff: real departure time (e.g. 23:55)
"""
# end::header[]
time_fmt = "%H:%M"
# We convert with strptime and calculate the difference
t_real = datetime.strptime(takeoff, time_fmt)
t_exp = datetime.strptime(expected, time_fmt)
delta = t_real - t_exp
# If "takeoff < expected", we will call recursively and multiply by "-1"
if delta.days < 0:
return -1 * get_delay(takeoff, expected)
# If delta is bigger than half-day, we will return (delta - 1 day)
sec_in_day = 60 * 60 * 24
if delta.seconds > sec_in_day / 2:
seconds = delta.seconds - sec_in_day
else:
seconds = delta.seconds
return int(seconds / 60)
def get_delay_2(expected: str, takeoff: str) -> int:
"""\
Measure the time difference in minutes between two times
delay = <take-off> - <expected>
Args:
expected: expected departure time (e.g. 23:45)
takeoff: real departure time (e.g. 23:55)
"""
def min_in_time(hhmm: str):
t = hhmm.split(":")
return int(t[0]) * 60 + int(t[1])
# We convert by doing HH * 60 + MM and calculate the difference
# If "takeoff < expected", the result is we will have to deduct 1 day from delta
# However, we will calculate normally if delta is bigger than half-day
min_in_day = 60 * 24
delta = min_in_time(takeoff) - min_in_time(expected)
if delta < 0:
return -1 * get_delay_2(takeoff, expected)
elif delta > min_in_day / 2:
return delta - min_in_day
else:
return delta
# end::get_delay[]
# tag::header[]
class Airline:
"""Class describing an airline with records"""
def __init__(self, name, code):
"""Creation of an airline with records"""
self.name = name
self.code = code
self.flights = defaultdict(list) # So ".append(...)" will work automatically
self.destination = dict()
# tag::add_info[]
def add_info(self, record):
"""Add flight information, create flight if it does not exist
Args:
record(dict): dictionary with keys:
* 'date': date of the flight, stored as a string (e.g. "2018-02-30")
* 'time': expected take-off time, stored as a string (e.g. "15:30")
* 'code': code of flight (e.g. "MU123")
* 'destination'
* 'take-off': real take-off time, stored as a string
"""
# end::header[]
code = record["code"]
# Save destination
if code not in self.destination:
self.destination[code] = record["destination"]
# self.flights[code] = list() # mandatory if defaultdict(list) is not used
# Record to save in the list of records
# saved_record = {k: record[k] for k in ("date", "time")}
saved_record = {
"date": record["date"],
"time": record["time"],
"delay": get_delay(record["time"], record["take-off"]),
}
# Save record (NOTE: defaultdict ensure to initialize the list)
self.flights[code].append(saved_record)
# end::add_info[]
# tag::header[]
# tag::get_rating_flight[]
def get_rating_flight(self, flight: str):
"""Get the rating of a given flight
Args:
flight: code of a flight
Returns:
('% late', 'average delay') for a flight, both int
"""
# end::header[]
# Flight unknown
if flight not in self.flights:
return None, None
# Known flight: calculate number of flights late and total delay
nb_late, total_delay = 0.0, 0.0
for record in self.flights[flight]:
total_delay += record["delay"]
if record["delay"] > 30:
nb_late += 1
nb_flights = len(self.flights[flight])
percent = int(nb_late / nb_flights * 100)
average = int(total_delay / nb_flights)
return percent, average
# end::get_rating_flight[]
# tag::header[]
# tag::get_rating_airline[]
def get_rating_airline(self):
"""Get the rating of the airline
Returns:
('% late', 'average delay') for the airline, both int
"""
# end::header[]
# We could use the previous version to avoid duplicate code
# HOWEVER, get_rating_flight returns "int" so the result would be inexact
# We will do a copy of the code with a loop on "flight" [arghhh :( duplicate code!!]
nb_late, total_delay = 0.0, 0.0
nb_flights = 0
for records in self.flights.values():
nb_flights += len(records)
for record in records:
total_delay += record["delay"]
if record["delay"] > 30:
nb_late += 1
percent = int(nb_late / nb_flights * 100)
average = int(total_delay / nb_flights)
return percent, average
# end::get_rating_airline[]
5.2. processRecords.py
#!python
import airlines
import re, argparse, datetime
# tag::header[]
def read_flight_records(file_path: str):
"""\
Read flight records from a given file and returns the list of take-off records.
Each element is a dict with keys: date, time, code, airline, destination, take-off
Args:
file_path: Path of file to read
Returns:
list of take off records
"""
# end::header[]
list_records = list()
record_keys = ["date", "time", "code", "airline", "destination", "take-off"]
# We will extract each info and match it to "record_keys" by using zip(l1, l2)
# NOTE: zip transforms 2 list in a list of tuple; for example:
# zip([1, 2, 3], ["a", "b", "c"]) => [(1, "a"), (2, "b"), (3, "c")]
# Using "dict(...)" on this zipped list will create a dictionary with key and value
# 2 solutions to split line in elements
# Solution #1: Using regular expression to ensure strict pattern matching
pattern = (
r"^([\d\-]+),\s*([\d:]+),\s*([A-Z0-9]+),\s*([\w ]+),\s*(\w.+?),\s*([\d:]+)"
)
# Solution #2: using <line>.split(",") and stripping all spaces around each element
# We then need to check the number of elements in split result
try:
with open(file_path) as f:
for record in f:
# == Solution #1 (regex) ==
# if record.strip() == "":
# continue # Skip empty lines
# match_record = re.match(pattern, record)
# if match_record:
# record_dict = dict(zip(record_keys, match_record.groups()))
# list_records.append(record_dict)
# else:
# print(f"Following line of {file_path!r} does not match pattern: {record!r}")
# == Solution #2 (split) ==
if record.strip() == "":
continue # Skip empty lines
data = [d.strip() for d in record.split(",")]
# NOTE: we can also use regular expression
# data = re.split(r"\s*,\s*", record.rstrip())
if len(data) != len(record_keys):
print(
f"Following line of {file_path!r} has incorrect number of data: {record!r}"
)
else:
record_dict = dict(zip(record_keys, data))
list_records.append(record_dict)
except Exception as e:
raise IOError(f"Error while trying to read input file {file_path!r}: {e}")
return list_records
# tag::header[]
def get_ratings_airlines(list_records):
"""From the list of records, create a dictionary with all Airlines
Args:
list_records(list): list of dict returned by read_flight_records
Returns:
dictionary "airlines_dic" with:
* key = airline name
* value = "Airline" object with all the records of that airline
"""
# end::header[]
# We will loop each element of input list and
# * Create a new Airline if it does not exist in the dictionary
# * Add the record in the Airline object
airlines_dic = dict()
for record in list_records:
name = record["airline"]
# Create airline if required
if name not in airlines_dic:
code = record["code"][:2] # First 2 characters of flight
airlines_dic[name] = airlines.Airline(name, code)
# Add the record information
airlines_dic[name].add_info(record)
return airlines_dic
# tag::header[]
def list_sorted_ratings(airlines_dic):
"""Sort the airlines and flights based on the probability to be late
Args:
airlines_dic(dict): Dictionary with Airline objects
Returns:
rating_airlines(list): list of Airlines sorted by late probability (less late first)
rating_flights(list): list of flights sorted by late probability (less late first)
NOTE: Each element of the returned lists contains the following tuple:
(<airline|flight code>, <% late>, <average delay>)
"""
# end::header[]
rating_airlines = list()
rating_flights = list()
# Generate the lists
for name, airline in airlines_dic.items():
# Airline
rating_airline = airline.get_rating_airline()
# TODO: add code of Airline in the ranking
# name_code = f"{name} [{airline.code}]"
# rating_airlines.append((name_code, *rating_airline))
# NOTE: We add the name before the tuple by using "*args" to get elements of tuple
rating_airlines.append((name, *rating_airline))
# Flights
for flight in airline.flights.keys():
rating_flight = airline.get_rating_flight(flight)
# TODO: add destination of flight in the ranking
# code_dest = f"{flight} ({airline.destination[flight]})"
# rating_flights.append((code_dest, *rating_flight))
rating_flights.append((flight, *rating_flight))
# Sort the lists based on the probability to be late
def score_airline(t):
"""From tuple (% late, average delay) calculates a score
"% late" * 1000 + "average delay" to sort the airlines
"""
return t[1] * 1000 + t[2]
rating_airlines = sorted(rating_airlines, key=score_airline)
rating_flights = sorted(rating_flights, key=score_airline)
return rating_airlines, rating_flights
# tag::header[]
def get_first_last_elem(sorted_list, nb_elem: int):
"""Return lists with first/last <nb_elem> elements
Args:
sorted_list(list): list of elements
nb_elem(int): number of first/last elements
Return:
first(list): first nb_elem elements of sorted_list
last(list): last nb_elem elements of sorted_list in reverse order
"""
# end::header[]
if nb_elem < 1:
return [], []
else:
first_elements = sorted_list[:nb_elem]
last_elements = sorted_list[-nb_elem:]
last_elements.reverse()
return first_elements, last_elements
# tag::header[]
##=== MAIN PROGRAM ===##
# tag::main_function[]
if __name__ == "__main__":
# tag::argparse[]
# Main Program
description = """processRecords.py - Generating a report of airines and flights based on their delay"""
# end::header[]
# Parsing options and arguments
parser = argparse.ArgumentParser(description=description)
parser.add_argument("input_path")
parser.add_argument(
"-o",
"--output",
dest="report_path",
default="report_airlines.html",
help="Path of HTML report to generate",
)
parser.add_argument(
"-n",
dest="nb_ranking",
default=10,
type=int,
help="Number of best/worse airlines and flights",
)
cmd = parser.parse_args()
# end::argparse[]
# =DEBUG=#
# cmd = parser.parse_args(["list_records.txt"])
# Getting list of sorted elements
records = read_flight_records(cmd.input_path)
airlines_dic = get_ratings_airlines(records)
rating_airlines, rating_flights = list_sorted_ratings(airlines_dic)
# Generate list of best and worse <nb_ranking> airlines/flights
best_airlines, worse_airlines = get_first_last_elem(rating_airlines, cmd.nb_ranking)
best_flights, worse_flights = get_first_last_elem(rating_flights, cmd.nb_ranking)
# Retrieve template of report
try:
with open("report_Template.html") as f:
template = f.read()
# Replace single curly brackets by double ones in <STYLE> block
for block in re.findall(r"<style>.*?</style>", template, re.I | re.S):
updated_block = re.sub(r"([{}])\1*", r"\1" * 2, block)
template = template.replace(block, updated_block)
except Exception as e:
msg = f"Error while reading template 'report_Template.html' ({e})"
print(msg)
template = f"<html><body>{msg}</body></html>"
# tag::report_content[]
# Prepare the report
report = dict()
# time
report["date"] = str(datetime.date.today())
report["time"] = str(datetime.datetime.now().time())[:8]
# rankings
def store_ranking(key, ranking):
str_info = "<b>{0}</b> ({1}%, avg={2} min)"
report[key] = "</li>\n<li>".join([str_info.format(*t) for t in ranking])
store_ranking("best_airlines", best_airlines)
store_ranking("worse_airlines", worse_airlines)
store_ranking("best_flights", best_flights)
store_ranking("worse_flights", worse_flights)
# Generate the report
report_content = template.format(**report)
# end::report_content[]
try:
with open(cmd.report_path, "w") as f:
f.write(report_content)
except Exception as e:
print(f"Error while trying to write in '{cmd.report_path}' ({e})")
else:
print(f"Successfully wrote report {cmd.report_path!r}")
# end::main_function[]


This topic describes how to access metadata from music GDOs.
Using Music GDOs
Accessing Mood and Tempo Metadata
Accessing Enriched Music Metadata with the Link Module
Accessing Classical Music Metadata
Accessing Album Cover Art
© 2000 to present. Gracenote, Inc. All rights reserved.
How can we improve this documentation?


Back
How and why do you want the order changed?
You can continue without giving details if you prefer. If you enter details, {% if data['party'] == 'claimant' %}Mary Richards{%else%}Jan Clark{% endif %} will be able to see what you said and add their own comments.
Continue


cd socket
npm install
node app.js
Relax and play. Any time of day. Using equipment that is always there, near you.
Do you own a computer and another device with an internet browser? Then you are good to go!
Since this runs on your desktop computer, there are no problems with lag or high ping. It also doesn't cause any additional data usage!
Singleplayer, multiplayer, action, RPG, arcade, puzzle, racing, FPS, clicker... It's your call!
Unlimited play without any payments!