text:
Updating a Kops Cluster
========================

Sometime refer to as "Day 2" problems.  The other part of the lifecycle after
cluster creations.  This is where most of the Kubernetes cluster's lifecycle will
reside in.

# Updating instance size
The most common operation to perform is updating the instance size to be
larger or smaller.  This is an easy operation.

Lets say you have a `dev` cluster.

The following paths all starts from the root of this repository.

Open and edit the file: `./clusters/aws/kops/clusters/dev/values.yaml`

Lets say that you want to update the `onDemandGroup1` group.

## Update the configuration file
Search or scroll down in the file until you find the group settings for `onDemandGroup1`

```
...
onDemandGroup1:
  # CoreOS: https://github.com/kubernetes/kops/blob/06b0111251ab87861e57dbf5f8d36f02e84af04d/docs/images.md#coreos
  image:<PHONE_NUMBER>73/CoreOS-stable-2023.5.0-hvm
  machineType: t3.large
  maxSize: 10
  minSize: 1
...
```

Update the `machineType` value to the new instance type you want it to be.

## Apply changes
After this change, we have to apply these changes

Run a dry run to see what it will change:
```
cd clusters/aws/kops
./kops.sh --name dev --update true --dry-run true
```

Apply the changes:
```
./kops.sh --name dev --update true --dry-run false
```

## Roll the nodes
When we applied the changes, Kops changed the AWS configuration of the Launch
Configuration of the ASG group.  This does not touch the current nodes that
are running.  When a new node starts, it will use the new configuration but the
current node will stay as is.

For this reason, we have to "roll" the nodes.  This means that we will have to
terminate and let the system launch new nodes.

Roll the nodes:
```
./kops.sh --name dev --rolling-update true --dry-run false --cloudonly true
```

This will select nodes that needs updating and turn them off one by one until they
are all updated.

## Commit back the changes

Now that we have made the changes, we want to commit back these changes to our
repository.

Another Git flow we could have used was after we made the config changes, we could
have started a new branch, commit the changes to that branch, and then opened a
pull request for these changes.  With the Pull Request, we would solicit feedback
from our peers on what they think about this change.  If everyone says it is ok,
we could merge and apply the changes and roll the nodes.

repository: ManagedKube/kubernetes-ops

gha_language: HCL

repo_name: ManagedKube/kubernetes-ops


text:
# Quick reference on Git
Check out this great and comprehensive [tutorial](https://git-scm.com/book/en/v2).

Alternatively, here's another [great website](https://learngitbranching.js.org/) to learn `git` in a learning-by-doing approach.

license: MIT

repository: nicrie/PythonModuleoftheMonth

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: nicrie/PythonModuleoftheMonth


text:
---
layout: default
---

# 1996-08-18 - Re: Drive the SF Central Freeway, have your license plate

## Header Data

From: snow<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: 48cff3f0954c986dd249bcaf45036e6187f6fc1d8917c7ddd7e430812a389020

Message ID<EMAIL_ADDRESS>Reply To<EMAIL_ADDRESS>UTC Datetime: 1996-08-18 21:14:15 UTC

Raw Date: Mon, 19 Aug 1996 05:14:15 +0800

## Raw message

```
{% raw  %}From: snow<EMAIL_ADDRESS>Date: Mon, 19 Aug 1996 05:14:15 +0800
To<EMAIL_ADDRESS>Subject: Re: Drive the SF Central Freeway, have your license plate
In-Reply-To<EMAIL_ADDRESS>Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

On Sat, 17 Aug 1996, Bob Jonkman wrote:
> > >At 21:55 8/8/96, i am not a number! wrote:
> > >>CBS radio news this morning: 80,000 commuters traveling the
> > >>central f'way in SF will have information mailed to them
> > >>regarding the quake retrofit How?  Their license plates have
> > >>been photographed.
> > At 10:45 PM 8/8/96 -0700, Lucky wrote:
> > >You *are* making this up, right? Please say you did.
> to get your drivers license or car registration renewed...
> Big Brother is not only watching, he's recording your location
> and destination, measuring your distance travelled, and charging
> you for the privilege of driving...

     No, you are paying to use the road. You allowed to purchase the land
to build your own road, and probably could even charge to use it. Assuming
of course that you could _afford_ to.

Petro, Christopher C.
<EMAIL_ADDRESS><prefered for any non-list stuff>
<EMAIL_ADDRESS>

{% endraw %}
```

## Thread

+ Return to [August 1996](/archive/1996/08)

+ Return to "[Bob Jonkman <bjonkman@sobac.com>](/authors/bob_jonkman_bjonkman_at_sobac_com_)"
+ Return to "[snow <snow@smoke.suba.com>](/authors/snow_snow_at_smoke_suba_com_)"

+ 1996-08-18 (Sun, 18 Aug 1996 19:54:02 +0800) - [Re: Drive the SF Central Freeway, have your license plate](/archive/1996/08/4caaa5c831abe1f948dda81411bea4b8c2ac41cc998811f873b638f929b6c4f2) - _Bob Jonkman<EMAIL_ADDRESS>  + 1996-08-18 (Mon, 19 Aug 1996 05:14:15 +0800) - Re: Drive the SF Central Freeway, have your license plate - _snow<EMAIL_ADDRESS>

gha_license_id: MIT


text:
## Introduction

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**The directory structure of simulator (模拟器的目录结构)**

```
dpdp_competition
	│  main.py  模拟器的主程序
	│  main_algorithm.py  算法的主程序
	│  readme.md  文档说明
	│
	│─algorithm  存放算法代码的文件夹
	│  │  algorithm_demo.py  算法示例代码
	│  │
	│  └─data_interaction  算法与模拟器交互数据的文件夹
	│
	├─benchmark  测试集
	│
	└─src 存放模拟器代码的文件夹
		├─common  常用类
		│      dispatch_result.py
		│      factory.py
		│      input_info.py
		│      node.py
		│      order.py
		│      route.py
		│      stack.py
		│      vehicle.py
		│
		├─conf  配置文件
		│      configs.py
		│
		├─simulator  模拟器
		│      history.py
		│      simulate_api.py
		│      simulate_environment.py
		│      vehicle_simulator.py
		│
		└─utils  常用工具
		       checker.py
		       evaluator.py
		       input_utils.py
		       json_tools.py
		       logging_engine.py
		       log_utils.py
		       tools.py
```

**Run the simulator（启动模拟器）**

```
# cd dpdp_competition
python main.py
```

## Requirements

* python >= 3.6
* simpy

## Quick Start
### Interaction Between algorithm and simulator

Firstly, the simulator reads the selected test instance which can be modified in Configs.py. Then, the simulator performs simulation at a fixed interval of 10 minutes until all orders in the instance are completed.

In each round of simulation, the simulator outputs the vehicle and order data required by the algorithm to the algorithm/data_interaction folder in JSON format. Next, it calls the main program of the algorithm prefixed with "main_algorithm", e.g. main_algorithm.py, main_algorithm.java, e.t.c. When the algorithm runs, it starts to read JSON files, dispatch orders, output the dispatch result to the algorithm/data_interaction folder in JSON format and print string "SUCCESS" to the console as the flag for the simulator to determine whether the algorithm is successfully returned. If the successful returned flag of the algorithm is obtained, the simulator would read the output JSON files and do the verification. After passing the verification, it continues to simulate.

The running time of the algorithm is limited to 10 minutes. If the algorithm times out, the simulator will exit.

Note: Pathes of folders and files mentioned above are illustrated in the Introduction section.

启动模拟器后，模拟器首先读取选定测试例，测试例的选择可在Configs.py中修改，接着按照固定时间间隔10min来进行模拟，直到完成测试例中的所有订单。

每轮次模拟中，模拟器把算法需要的数据通过JSON文件的形式输出至algorithm/data_interaction文件夹中，接着调用算法主程序（以main_algorithm作为前缀的文件，例如main_algorithm.py, main_algorithm.java等）。当算法成功启动后，会读取JSON文件、派单、把派单结果通过json文件的形式输出至algorithm/data_interaction文件夹中，并且输出"SUCCESS"字符串至**控制台【非日志】**，作为模拟器判断算法是否成功返回的标识。如果成功获取到算法成功返回的标识，模拟器会读取算法输出的JSON文件，并进行校验，通过校验后，继续进行模拟仿真。

**当前算法每次运行时长限定为10分钟，超时模拟器将主动退出。**

注：上面提到的路径和文件名详见Introduction部分的“模拟器的目录结构”

### Main Process (from algorithm perspective)

+ [Read the input json files](#Read the input json files)
+ [Dispatch orders](#Dispatch orders)
+ [Output required json files](#Output required json files)

### Read the input json files

The simulator outputs the latest vehicle information in "vehicle_info.json", order items to be allocated in "unallocated_order_items.json" and ongoing order items in "ongoing_order_items.json". The details of these files are in the following.

Three concepts are explained here:

1. Item, which is the smallest unit in an order. For example, if an order contains 2 standard pallets and 1 small pallets, there are 3 items included: item 1 of one standard pallet, item 2 of one standard pallet and item 3 of 1 small pallet.
2. Item status, 0 means initialization; 1 means the item is generated; 3 means the item has been loaded; 4 means the item is delivered.
3. Order status, which is the minimum value of all corresponding items statuses. For example, an order contains two items, namely, item 1 of 1 small pallet and item 2 of 1 box. The status of item 1 is 3 and item 2 is 2, the order status is 2.

模拟器会输出当前最新的车辆信息"vehicle_info.json"、未分配物料信息"unallocated_order_items.json"和已装货物料信息"ongoing_order_items.json"至algorithm/data_interaction文件夹中，下面具体介绍这三个JSON文件。

这里解释三个概念：
 	1. 物料，物料是订单不可切分的最小单元，例如一个订单含有2个标准板, 1个小板，那么其对应的物料有3个, 分别是标准板物料1，标准板物料2和小板物料3；
 	2. 物料的状态，0：初始化状态，1：物料已经生成，2：物料已经装车，3：物料已经送达；
 	3. 订单的状态，取其包含所有物料状态的最小值，例如一个订单包含两个物料，分别是小板物料1和箱子物料2，其中小板物料1的状态为3，箱子物料2的状态为2，那么订单的状态为2

+ **vehicle_info.json**

  Example:

```
[
  {
    "id": "V_1",
    "operation_time": 24,
    "capacity": 15,
    "gps_id": "G_1",
    "update_time":<PHONE_NUMBER>.0,
    "cur_factory_id": "f6faef4b36e743328800b961aced4a2c",
    "arrive_time_at_current_factory":<PHONE_NUMBER>.0,
    "leave_time_at_current_factory":<PHONE_NUMBER>.0,
    "carrying_items": [
      "2218470047-1",
      "2218470047-2"
    ],
    "destination": {
      "factory_id": "b6dd694ae05541dba369a2a759d2c2b9",
      "delivery_item_list": [
        "2218470047-2",
        "2218470047-1"
      ],
      "pickup_item_list": [],
      "arrive_time":<PHONE_NUMBER>.0,
      "leave_time":<PHONE_NUMBER>.0
    }
  },
  {
    "id": "V_2",
    "operation_time": 24,
    "capacity": 15,
    "gps_id": "G_2",
    "update_time":<PHONE_NUMBER>.0,
    "cur_factory_id": "5e2e9efa5ade4984bb18af66028bc0c8",
    "arrive_time_at_current_factory":<PHONE_NUMBER>.0,
    "leave_time_at_current_factory":<PHONE_NUMBER>.0,
    "carrying_items": [],
    "destination": null
  },
  ...
]
```

| Column                         | Description                                                  | Type              |
| ------------------------------ | ------------------------------------------------------------ | ----------------- |
| id                             | id of vehicle, 车牌号                                        | str               |
| operation_time                 | operation time of vehicle(unit: hour), 车辆的运营时长        | int               |
| capacity                       | capacity of vehicle (unit: standard pallet, 单位: 标准栈板)  | int               |
| update_time                    | Update time of the current position and status of the vehicle(unit: unix timestamp).
车辆当前位置和状态的更新时间 | int               |
| cur_factory_id                 | the factory id where the vehicle is currently located. If the vehicle currently is not in any factory, the value is "".
车辆当前所在的工厂, 如果当前不在任何工厂则为""。 | str               |
| arrive_time_at_current_factory | The time when the vehicle arrives at the current factory(unit: unix timestamp).
车辆到达当前所在工厂的时间 | int               |
| leave_time_at_current_factory  | The time when the vehicle leaves the current factory(unit: unix timestamp).
车辆离开当前所在工厂的时间 | int               |
| carrying_items                 | List of items loaded on the vehicle, in the order of loading.
车辆当前载的物料编号列表，顺序为装货顺序 | [str1, str2, ...] |
| destination                    | Current destination of the vehicle. Once determined, the destination cannot be changed until the vehicle has arrived. The destination is None when the vehicle is parked.
当前车辆的目的地, 目的地一旦确定不可更改, 直到车辆到达目的地节点，如果当前车辆处于停车状态，目的地为空 | dict              |

Notes： if vehicle v is in the factory f1, the destination is f2, then the route plan {f3, f2} violates the destination invariant constraint, while {f2, f3} does not

+ **unallocated_order_items.json**
  Example：

```
[
  {
    "id": "1436011625-1",
    "type": "HALF_PALLET",
    "order_id": "1436011625",
    "demand": 0.5,
    "pickup_factory_id": "7b84670cf4164cccba22ebb17a2c290a",
    "delivery_factory_id": "7fb0acc4e2634440ba26a7ebc0040dc2",
    "creation_time":<PHONE_NUMBER>,
    "committed_completion_time":<PHONE_NUMBER>,
    "load_time": 120,
    "unload_time": 120,
    "delivery_state": 1
  },
  {
    "id": "1446161669-1",
    "type": "PALLET",
    "order_id": "1446161669",
    "demand": 1,
    "pickup_factory_id": "2445d4bd004c457d95957d6ecf77f759",
    "delivery_factory_id": "9f1a09c368584eba9e7f10a53d55caae",
    "creation_time":<PHONE_NUMBER>,
    "committed_completion_time":<PHONE_NUMBER>,
    "load_time": 240,
    "unload_time": 240,
    "delivery_state": 1
  },
```

| Column                    | Description                                                  | Type   |
| ------------------------- | ------------------------------------------------------------ | ------ |
| id                        | id of item, 物料编号                                         | str    |
| type                      | pallet type, e,g, standard pallet, small pallet and box
物料对应托盘类型 | str    |
| order_id                  | id of order, 订单编号                                        | str    |
| demand                    | total standard pallet amount                                 | double |
| pickup_factory_id         | id of pickup factory, 取货地                                 | str    |
| delivery_factory_id       | id of delivery factory, 送货地                               | str    |
| creation_time             | creation time of the corresponding order(unit: unix timestamp), 所属订单的创建时间 | int    |
| committed_completion_time | committed completion time of the corresponding order(unit: unix timestamp), 所属订单的承诺送达时间 | int    |
| load_time                 | loading time of item(unit: second), 该物料的装载时间         | int    |
| unload_time               | unloading time of item(unit: second), 该物料的卸货时间       | int    |
| delivery_state            | Item status, 0 means initialization; 1 means the item is generated; 2 means the item has been loaded; 3 means the item is delivered. | int    |

+ **ongoing_order_items.json**
  Example：

```
[
  {
    "id": "0003480001-1",
    "type": "HALF_PALLET",
    "order_id": "0003480001",
    "demand": 0.5,
    "pickup_factory_id": "2445d4bd004c457d95957d6ecf77f759",
    "delivery_factory_id": "b6dd694ae05541dba369a2a759d2c2b9",
    "creation_time":<PHONE_NUMBER>,
    "committed_completion_time":<PHONE_NUMBER>,
    "load_time": 120,
    "unload_time": 120,
    "delivery_state": 2
  },
  {
    "id": "0012230002-1",
    "type": "PALLET",
    "order_id": "0012230002",
    "demand": 1,
    "pickup_factory_id": "2445d4bd004c457d95957d6ecf77f759",
    "delivery_factory_id": "9f1a09c368584eba9e7f10a53d55caae",
    "creation_time":<PHONE_NUMBER>,
    "committed_completion_time":<PHONE_NUMBER>,
    "load_time": 240,
    "unload_time": 240,
    "delivery_state": 2
  },
  ...
]

```

### Dispatch orders

1. When the vehicle $v$ arrives at the factory $f$, the pickup and delivery list of $v$ in $f$ will be generated immediately. The vehicle can only be loaded and unloaded according to the list. We can only change the pickup and delivery items of $v$ in $f$ when the corresponding pickup and delivery list is not generated.
2. Algorithm can reallocate the item to different vehicles as long as this item is not not displayed on the  pickup and delivery list.
3. Considering that the input is the items, the algorithm needs to pay attention to the order splitting constraint. If the order does not exceed the vehicle's capacity (vehicles are homogeneous), the order cannot be split.
4. The algorithm can control the order release. For example, if order A is generated at $t_1$, the algorithm can delay the allocation until $t_2 <= t_1 + 4h$. Note: If an order has been generated for more than 4 hours but is still not dispatched, the simulator will exit.
5. The traveling distance and time required for the algorithm can be obtained only from the distance and time matrix between factories in the benchmark. Do not calculate the distance and time based on the longitude and latitude. If the vehicle $v$ is in transit,  $v$ must have a destination factory $f$, and the simulator will give the estimated time for $v$ to arrive at $f$. The algorithm can plan the route of vehicle $v$ based on the destination $f$.
6. Assume that the simulator sends the latest status information of all vehicles to the algorithm at $t_1$, and the algorithm returns the dispatching result at $t_2$. If the algorithm runs for a long time, the status of vehicles will change greatly after pasing  the time interval $[t_1, t_2]$. As a result, the dispatching result is inconsistent with the actual situation, which affects the running of vehicles. Currently, the running time of the algorithm is limited to 10 minutes.

1. 车辆$v$到达工厂$f$, 就会立刻生成$v$在$f$的取送货清单，此时车辆只能按照清单进行装卸操作，不可以加塞和减少；如果清单未生成，即$v$未到达$f$, 则$v$在$f$的装卸物料可以改变
2. 物料只要未在取送货清单上出现都可以重新分配车辆
3. 考虑到输入的是订单包含物料的信息，算法需要注意订单切分约束，订单未超过车辆载重的(车辆是同质的)，不可以进行切分
4. 算法可以控制订单的释放，例如，$t_1$时刻生成订单A，算法可以不用立即分配，延迟到$t_2 <= t_1 + 4h$再分配。注意如果一个订单已经生成超过4小时，但是算法依旧未分配，模拟器会自动退出
5. 算法计算需要的距离和时间，仅可通过benchmark中工厂之间的距离和时间矩阵进行获取，不要通过经纬度自行计算。如果车辆$v$在运行途中，那么该车一定会有一个目的地工厂$f$，而且模拟器会给出$v$预计到达$f$的时间，后续算法规划$v$的路径可以基于目的地$f$进行计算
6. 假设模拟器将$t_1$时刻的最新车辆位置和装载情况传给算法，算法在$t_2$时刻回传派单结果，如果算法运行时间过长，那么经过$[t_1, t_2]$车辆的状态会发生很大改变，导致派单结果与实际不符，从而影响实际车辆的运行，目前模拟器限制算法的运行时长为10min

### Output required json files

The algorithm needs to output two json files including "output_destination.json" and "output_route.json". The details of these files are in the following.

+ **output_destination.json**

  Example

```
{
  "V_1": {
    "factory_id": "2445d4bd004c457d95957d6ecf77f759",
    "lng": 116.5841,
    "lat": 40.2869,
    "delivery_item_list": [],
    "pickup_item_list": [
      "0003480001-1"
    ],
    "arrive_time":<PHONE_NUMBER>.0,
    "leave_time": 0
  },
  "V_2": {
    "factory_id": "9f1a09c368584eba9e7f10a53d55caae",
    "lng": 116.6309,
    "lat": 40.2304,
    "delivery_item_list": [
      "0013570003-1"
    ],
    "pickup_item_list": [],
    "arrive_time":<PHONE_NUMBER>.0,
    "leave_time": 0
  },
  "V_3": null,
  ...
}
```

+ **output_route.json**

  Example

```
{
  "V_1": [
    {
      "factory_id": "b6dd694ae05541dba369a2a759d2c2b9",
      "lng": 116.6264,
      "lat": 40.2253,
      "delivery_item_list": [
        "0003480001-1"
      ],
      "pickup_item_list": [],
      "arrive_time": 0,
      "leave_time": 0
    },
    {
      "factory_id": "2445d4bd004c457d95957d6ecf77f759",
      "lng": 116.5841,
      "lat": 40.2869,
      "delivery_item_list": [],
      "pickup_item_list": [
        "0012230002-1"
      ],
      "arrive_time": 0,
      "leave_time": 0
    },
    {
      "factory_id": "9f1a09c368584eba9e7f10a53d55caae",
      "lng": 116.6309,
      "lat": 40.2304,
      "delivery_item_list": [
        "0012230002-1"
      ],
      "pickup_item_list": [],
      "arrive_time": 0,
      "leave_time": 0
    }
  ],
  "V_2": [
    {
      "factory_id": "2445d4bd004c457d95957d6ecf77f759",
      "lng": 116.5841,
      "lat": 40.2869,
      "delivery_item_list": [],
      "pickup_item_list": [
        "0033520004-1",
        "0033520004-2",
        "0033520004-3"
      ],
      "arrive_time": 0,
      "leave_time": 0
    },
    {
      "factory_id": "b6dd694ae05541dba369a2a759d2c2b9",
      "lng": 116.6264,
      "lat": 40.2253,
      "delivery_item_list": [
        "0033520004-3",
        "0033520004-2",
        "0033520004-1"
      ],
      "pickup_item_list": [],
      "arrive_time": 0,
      "leave_time": 0
    }
  ],
  "V_3": [],
  ...
}
```

| Column             | Description                                                  | Type              |
| ------------------ | ------------------------------------------------------------ | ----------------- |
| factory_id         | id of factory, 节点对应的工厂id                              | str               |
| lng                | longitude, 节点对应工厂的经度                                | double            |
| lat                | latitude, 节点对应工厂的纬度                                 | double            |
| delivery_item_list | List of items unloaded from the vehicle, (Given the length of delivery_item_list is n, the unloading sequence is delivery_item_list[0], delivery_item_list[1], ..., delivery_item_list[n-1]
送货物料清单 | [str1, str2, ...] |
| pickup_item_list   | list of items loaded on the vehicle (Given the length of pickup_item_list is n, the loading sequence is pickup_item_list[0], pickup_item_list[1], ..., pickup_item_list[n-1])
 取货物料清单 | [str3, str4, ...] |
| arrive_time        | time to reach the node(unit: unix timestamp), 到达节点的时间 | int               |
| leave_time         | time to leave the node(unit: unix timestamp), 离开节点的时间 | int               |

## Submission

**To be continued**

After the online submission of the HUAWEI CLOUD competition platform is open, we will complete the submission process document as soon as possible

## License

The MIT License(MIT)

repository: huawei-noah/xingtian

gha_language: Python

repo_name: huawei-noah/xingtian


text:
---
layout: post
title:  "Walking around in Ranikhet and Majkhali"
date:   2021-07-04 03:52:38
categories: Travel
hidden: true
tags: [Travel, Backpacking, RoadTrip, Himalayas, Photoblog, WeekendDiaries]
image:
  background: witewall_3.png
---

In every walk with nature one receives far more than he seeks...

The COVID restrictions were lifted and the itch to travel had started yet again. We started to plan the trip to Valley of flowers yet again but like always the valley was still not opened for tourists due to COVID. I had previously visited Ranikhet but wanted to do the ever famous Ranikhet walks which are famous since the bygone British era. On this trip, we visited three cities Chiliyanaula, Ranikhet and Majkhali.

> An old post office on the way

Ranikhet is a cantonment area, home for Naga and Kumaon regiment and has a lot of heritage bungalows, pathways and churches from the colonial era. We started our journey at around 7:00 am from Ramnagar and reached Ranikhet by noon. We had already booked an Airbnb in Haidakhan temple premises so it was a 2 km walk from the place where the bus dropped us. On this trip, we wilfully wanted to walk as much as possible as the joy of enjoying the beauty of the city is in absorbing it leisurely. The charming and majestic views of the pine trees, lush green forests, are best enjoyed slowly. Ranikhet has all the things from lofty Himalayan views (which we missed due to the clouds and fog) to peace-inducing flora and fauna to unwind and relax a corporate brain.

> Our AirBNB in Haidakhan Temple Premises

> Blossoming flowers in Monsoon

> Night view from the AirBNB

On day one we visited the Haidakhan Babaji's temple and Thandi Sadak in the evening. In this walk, we saw a lot of pine, oak, rhododendron and deodar trees in the hills. The temple premise hosted a lot of different flowers, a lot of which I had never seen before in my life. I was quite elated to see this unknown fauna since I had found a newfound love for houseplants during the lockdown. The next day we woke up early and went on the proper walking city tour. We took the below path for our walking trail for covering the city.

> Ranikhet walks

> Ranikhet Walks

> Rani Jheel

> Old Church

> Ranikhet walks : Cantt Area

> Jhula Devi Temple

From Haidakhan temple we took the following Path Haidakhan Temple ->  KRC -> St Bonaventure Catholic Church -> Hotel Meghdoot -> Jhula Devi Temple -> Nehru Trek Route -> Rani Jheel -> Haidakhan Temple. The total walk was around 20+ km and very enjoyable. We did not go to Chaubatia Gardens from Jhula Devi temple as there was a possibility of rain, but you can do it easily from the temple. The Temple had so many bells that it is something to notice and ponder over, this place has a calm environment and a sense of spiritual peace to it. The best part was the discovery of the Nehru Path hiking route that started a bit before the Jhula Devi Temple. It is a very beautiful, pristine and peaceful route to the main market. This hiking route has resting seats as they have in hikes in Germany or England and old British Bungalows. It felt that we were transported back to the 1960s Scottish countryside.

> Ranikhet Walks : Nehru Path Hike

> Ranikhet Walks : Old house

In the evening we went to Majkhali. I wanted to visit this place as it has the best views of Major Garhwal Himalayan ranges, peaks such as Nanda Devi Massif, Nanda Ghunti, Trishul, Panchachuli, Mrigthuni, Nanda Kot. But sadly due to the rainy season, the view was obstructed by clouds and mist. Nevertheless, Majkhali surprised us with the fantastic valley and sunset views and probably the best food on a trip.

> View from Majkhali Cottage

> This Place had the best food in Majkhali + Nice views

> Pristine hills

> Majkhali Walks : Going to the top

> Majkhali Walks : View of the terrace farms

> Majkhali Walks : Small Temple on top of a hill

> Majkhali Walks : View from the top

> Majkhali Walks : Other Cottages

> Majkhali Walks : View of a surrounding village

> Majkhali Walks : Sunset Scenes

> Dinner at yak and yeti inn

> Food Scenes

> Coming Back, Old Kumaoni House on the way

This trip aimed to unwind and recharge and the pictures would confirm that we must say we were more than successful in doing that.

Happy Travelling, till we meet again.

license: ISC


text:
---
layout: default
---

# 1995-11-28 - [NOISE, sorta] Re: Inexpensive Crypto Boxes...

## Header Data

From: Mike Fletcher<EMAIL_ADDRESS>To: Jim Choate<EMAIL_ADDRESS>Message Hash: cf8697974f0bc1732e64967b5e2ba79bd39a53c4f3f294cca7a3b6235762fda9

Message ID: \<9511281504.AA26594@outland\>

Reply To<EMAIL_ADDRESS>UTC Datetime: 1995-11-28 15:21:18 UTC

Raw Date: Tue, 28 Nov 1995 23:21:18 +0800

## Raw message

```
{% raw  %}From: Mike Fletcher<EMAIL_ADDRESS>Date: Tue, 28 Nov 1995 23:21:18 +0800
To: Jim Choate<EMAIL_ADDRESS>Subject: [NOISE, sorta] Re: Inexpensive Crypto Boxes...
In-Reply-To<EMAIL_ADDRESS>Message-ID: <9511281504.AA26594@outland>
MIME-Version: 1.0
Content-Type: text/plain

	Hi fellow PSX owner!  Tried WipEouT yet? :)

> The new Sony Play Station is operating under a stripped down Unix.
> Considering the speed that these boxes are designed to run at it seems a
> natural for somebody to come up with a crypto workbench on ROM to install in
> one of these babies. Could program one of the game controller ports as a
> serial port and hook it to a Linux box (for example).

	For those who don't know, the PSX is a CD based gaming console
released (in the US) in Sept by Sony.  It's a MIPS R3000/25MHz processor
with some SGI-designed polygon chips, 2x CD-ROM, 1M RAM, 2M video RAM.

	  What would be
_really_ spiffy would be for Sony (or a 3rd party) to put out a "hack disk"
(for lack of a better name) that would have a bare bones kernel that you
could then download stuff from another platform (gcc cross-compiled from
your linux box for example).  Like that'll happen.

	The line between toy and real machine is getting more and
more fuzzy (we use a box here at work with the same processor to compile
for an AT&T telephony switch (which tells you how sad the AT&T product
is :) :))).  How long until the NSA tries a Chinese Lottery attack hidden
inside a Nintendo cart?

	Ah well, I've rambled enough.

---
Fletch                                                     __`'/|
<EMAIL_ADDRESS>"Lisa, in this house we obey the       \ o.O'    ______
404 713-0414(w)      Laws of Thermodynamics!" H. Simpson   =(___)= -| Ack. |
404 315-7264(h) PGP Print: 8D8736A8FC59B2E6 8E675B341E378E43  U      ------

{% endraw %}
```

## Thread

+ Return to [November 1995](/archive/1995/11)

+ Return to "[Jim Choate <ravage@einstein.ssz.com>](/authors/jim_choate_ravage_at_einstein_ssz_com_)"
+ Return to "[Mike Fletcher <fletch@ain.bls.com>](/authors/mike_fletcher_fletch_at_ain_bls_com_)"
+ Return to "[Simon Spero <ses@tipper.oit.unc.edu>](/authors/simon_spero_ses_at_tipper_oit_unc_edu_)"

+ 1995-11-28 (Tue, 28 Nov 1995 12:59:42 +0800) - [Inexpensive Crypto Boxes...](/archive/1995/11/7bbfd10b8545abdee6c379c83872afd7c7e8ce16cfd32dba99ec504fbbf51f7a) - _Jim Choate<EMAIL_ADDRESS>  + 1995-11-28 (Tue, 28 Nov 1995 15:48:27 +0800) - [Re: Inexpensive Crypto Boxes...](/archive/1995/11/287e339e7246fb5263263bb5d1781fe3605d7a101957a916129ec34d76cd2616) - _Simon Spero<EMAIL_ADDRESS>  + 1995-11-28 (Tue, 28 Nov 1995 23:21:18 +0800) - [NOISE, sorta] Re: Inexpensive Crypto Boxes... - _Mike Fletcher<EMAIL_ADDRESS>


text:
!not-ready-for-release!

#### Version Number
${version-number}

#### Breaking Changes
- The image now runs Python 3.8 due to Python 2 packages no longer being available in openSUSE Tumbleweed.

#### New Features
- The image is now based on [openSUSE Tumbleweed](https://get.opensuse.org/tumbleweed/).
The release notes for openSUSE Tumbleweed can be found [here](https://doc.opensuse.org/release-notes/x86_64/openSUSE/Tumbleweed/).

#### Known Issues
- None

repository: CAFapi/opensuse-jeptalon-image

branch_name: refs/heads/develop

gha_language: Dockerfile

repo_name: CAFapi/opensuse-jeptalon-image


text:
# Computer Systems Performance, Analysis Techniques for Experimental Design, Measurements Simulation and Modeling

A simulation model of a multiprogram computer that has two processors, two system disks and K user disks for which it is determined by analysis and simulation:
- resource utilization,
- flow through resources,
- the average number of jobs in each of the resources of this system,
- system response time (average duration of one cycle, from when the process enters the processor order, until it comes to that order the next time) for K from 2 to 6
- critical resource in the system.

## Structure

Repository is organized as following:
- `doc` directory contains assignment as well as solution document(s)
- `source` directory contains code

repository: srfunksensei/PRS

repo_name: srfunksensei/PRS


text:
---
number: 540
title: Responsive Design Techniques
date:<PHONE_NUMBER>589
url: https://traffic.libsyn.com/syntax/Syntax_-_540.mp3
---

In this episode of Syntax, Wes and Scott talk through some modern responsive design techniques that you may not have heard of, or haven't had a chance to use yet.

## Linode  - Sponsor

Whether you’re working on a personal project or managing enterprise infrastructure, you deserve simple, affordable, and accessible cloud computing solutions that allow you to take your project to the next level. Simplify your cloud infrastructure with Linode’s Linux virtual machines and develop, deploy, and scale your modern applications faster and easier. Get started on Linode today with a $100 in free credit for listeners of Syntax. You can find all the details at [linode.com/syntax](https://linode.com/syntax). Linode has 11 global data centers and provides 24/7/365 human support with no tiers or hand-offs regardless of your plan size. In addition to shared and dedicated compute instances, you can use your $100 in credit on S3-compatible object storage, Managed Kubernetes, and more. Visit [linode.com/syntax](https://linode.com/syntax) and click on the “Create Free Account” button to get started.

## LogRocket - Sponsor

LogRocket lets you replay what users do on your site, helping you reproduce bugs and fix issues faster. It's an exception tracker, a session re-player and a performance monitor. Get 14 days free at [logrocket.com/syntax](https://logrocket.com/syntax).

## Freshbooks - Sponsor

Get a 30 day free trial of Freshbooks at [freshbooks.com/syntax](https://freshbooks.com/syntax)

## Show Notes

* **[00:47](#t=00:47)** Clean Talk
* **[03:55](#t=03:55)** The menu of responsive design
* [Syntax 154 with Sara Soueidan](https://syntax.fm/show/154/svgs-with-sara-soueidan)
* **[06:52](#t=06:52)** Responsive design basics
* **[11:54](#t=11:54)** What should you build for first in 2022?
* **[16:15](#t=16:15)** Shrink and grow until it looks bad
* **[21:36](#t=21:36)** Menus in responsive
* **[23:43](#t=23:43)** Sponsor: Linode
* **[24:13](#t=24:13)** Grid systems
* **[28:08](#t=28:08)** Grid and Flexbox
* [CSS Grid Course](https://cssgrid.io)
* [Flexbox Course](https://flexbox.io)
* [Can I Use](https://caniuse.com)
* **[35:02](#t=35:02)** Sponsor: LogRocket
* **[36:00](#t=36:00)** Container queries
* **[45:56](#t=45:56)** FitText
* **[49:12](#t=49:12)** How do you test these types of things?
* **[51:15](#t=51:15)** Future techniques coming
* **[53:28](#t=53:28)** Sponsor: Freshbooks
* **[53:56](#t=53:56)** SIIIIICK ××× PIIIICKS ×××

## ××× SIIIIICK ××× PIIIICKS ×××

* Scott: [Lutron Light switches](https://amzn.to/3Te5juj)
* Wes: [Sunco Lighting BR30](https://amzn.to/3UeDV0t)

## Shameless Plugs

* Scott: [LevelUp Tutorials](https://leveluptutorials.com/)
* Wes: [Wes Bos Tutorials](https://wesbos.com/courses)

## Tweet us your tasty treats

* [Scott's Instagram](https://www.instagram.com/stolinski/)
* [LevelUpTutorials Instagram](https://www.instagram.com/LevelUpTutorials/)
* [Wes' Instagram](https://www.instagram.com/wesbos/)
* [Wes' Twitter](https://twitter.com/wesbos)
* [Wes' Facebook](https://www.facebook.com/wesbos.developer)
* [Scott's Twitter](https://twitter.com/stolinski)
* Make sure to include [@SyntaxFM](https://twitter.com/SyntaxFM) in your tweets

repository: barrymcgee/Syntax

path: /shows/540 - Tasty.md

filename: 540 - Tasty.md

gha_language: JavaScript

repo_name: barrymcgee/Syntax


text:
# Directavel

Directavel helps using [Directus](https://directus.io/) as an administrative backend for [Laravel](http://laravel.com).
It provides some commands to programmatically define and version Directus collections, and sync them without touching your data tables.

## Installation

Directavel requires [PHP](https://php.net) 8.0+, [Laravel](https://laravel.com/) 10.x+ and [Directus](https://directus.io/) 9.x+.
To get the latest version, simply require the project using [Composer](https://getcomposer.org):

```bash
composer require 7ute/directavel
```

Once installed, if you are not using automatic package discovery, then you need to register the `SevenUte\Directavel\DirectavelServiceProvider` service provider in your `config/app.php`.
You can also alias the facade:

```php
        'Directavel' => SevenUte\Directavel\Facades\Directavel::class,
```

Directus must be installed and bootstraped, and the migrations must have been run already.
You can bootstrap it by running the following **in the directus project directory** :
```bash
npx directus bootstrap
npx directus database migrate:latest
```

## Configuration

To customize the directus configuration, you first must publish the config.

```bash
$ php artisan vendor:publish
```

This will create a `config/directavel.php` file in your app that you can modify to set your configuration.
Make sure you check for changes to the original config file in this package between releases.

## Collections

Each collection is defined by a PHP file named after the table we want to configure.
The collections sits at the path set in the `directavel.collections_path_pattern` config entry.

A configuration files is composed as following :

```php

// database/directus/collections/some_table.php

/**
 * That file will help generating a `some_table`
 * entry in the `directus_collections` table
 * with only the collection column filled.
 **/
return [
    /** The other columns of this `directus_collection` entry. */
    'attributes' => [],

    /** Each field will be its own row in the `directus_fields` table */
    'fields' => [],

    /**
     * The relationships that are not set in the fields
     * can be defined here. They will be inserted at
     * the end of the `directus_relations` table.
     **/
    'relations' => [],
]
```

To see an example, check the [sample.php](https://github.com/7ute/Directavel/blob/master/database/directus/collections/sample.php) file in this package.
You can also refer to the [DirectusFields](https://github.com/7ute/Directavel/blob/master/src/Models/DirectusFields.php) model for a list of available fields and some typing for your IDE, and the [DirectusCollections](https://github.com/7ute/Directavel/blob/master/src/Models/DirectusCollections.php) and [DirectusRelations](https://github.com/7ute/Directavel/blob/master/src/Models/DirectusRelations.php) for the available columns.

## Presets
The general presets can be defined in a file at the path set in the `directavel.presets_path` config entry.
Some default config for the `directus_activity`, `directus_presets` and `directus_users` views are included in the [presets.php](https://github.com/7ute/Directavel/blob/master/database/directus/presets.php) file of this project.

## Usage
Once the collections are configured, you can use the facade in a migration, or use the command to trigger a full refresh of Directus collections / fields without touching your non-directus data tables.

> **Warning**
> All your existing Activityn Collections, Fields, Presets, Relations and Revisions might be wiped, depending on your settings in the config file.

### Commands

- `php artisan directavel:sync`: Update the admin user, settings and presets, and synchronises the collections and fields
- `php artisan directavel:cache:clear`: Clears Directus inner cache

### Facade

```php
use SevenUte\Directavel\Facades\Directavel;

Directavel::updateProjectAdmin()
    ->updateProjectPresets()
    ->updateThemeCss()
    ->synchronizeDatabase()
    ->clearCache();
```
- `updateProjectAdmin`: Updates the Directus admin user ;
- `updateProjectLog`: Updates the Directus logo ;
- `updateProjectPresets`: Reload the non-user presets from the file defined in the `directus.presets_path` config ;
- `updateThemeCss`: Applies the theme color and extra CSS ;
- `synchronizeDatabase`: Loads the collections, fields and relations into the directus tables, wiping those set in the `directus.wipe` config before ;
- `clearCache`: Clears Directus collection cache to prevent "inexistant field" errors ;
- `loadTailwindThemeColors`: Reloads the Tailwind theme colors ;
- `loadCurrentAdminId`: Reloads the Directus admin user ID.

## Tests
This package is tested with [Pest](https://pestphp.com/). To run the tests, use `composer tests`.

## Contributions
Pull requests are welcome. Pull requests with tests are even more welcome.

## Security
If you discover a security vulnerability within this package, please send an e-mail to Julien Cauvin at<EMAIL_ADDRESS>All security vulnerabilities will be promptly addressed.

## License
Directavel is licensed under [The MIT License (MIT)](LICENSE).


text:
C'punks,

When I wrote:

    >>If you are stopped by the police, you are required to
    >>identify yourself if asked.

Chris Hibbert responded:

    This is not true.  If you're driving a car you are
    required to have a license.  If you're just walking
    around, you're not required to have a name, or to tell
    it.

Nope, *this* is wrong.  In most jurisdictions, you do not have to
provide *physical ID* if you are not in a car, but you do have to
identify yourself AND give some account as to what you are up to.

    A cop has to have a probable cause to arrest you, and
    not giving your name doesn't provide it.

/Au contraire/, you are "interfering with an investigation" or
"obstructing justice" or whatever it's called in the particular
jurisdiction.

    If you're surly, a cop can take you in, ...

Nonsense.  Where do you non-lawyers get this stuff?  Surly, rude,
impolite, etc. are all protected speech.  (Threatening *ACTS* or
physical resistance, however, is another thing.)

    ... Just say "Officer, someone is waiting for me.  May I
    go now?"

Just say "no"?  I *guarantee* this won't work.  If you are asking
permission ("May I go?"), aren't you ceding to the officer the
legal right to say "no"? If you believe you don't have to
interact with the nice man, why not just turn your back and walk
away without a word?  (I wouldn't advise it.)

    This has been tested in court.  There was a black lawyer
    several years ago who liked to walk a lot.  He lived in
    one of the fashionable neighborhoods in LA, and
    occasionally got picked up because he "looked like he
    didn't belong there".  He sued them and won in court
    every time, and got the police to leave him alone.  [No,
    I don't have references.]

A little knowledge is a dangerous thing.  The gentleman in
question was not a lawyer.  He was a black man who was dressed
and coiffured in dreadlocks and Rasta man clothes.  He did not
live in Beverly Hills nor Belaire, but he did like to take long
walks in those neighborhoods in the middle of the night.

He was arrested for not identifying himself with an "official"
ID.  When he sued, the court issued a temporary injunction
against the police for requiring *documentary* identification.
The right of the police to require a person to identify himself
was never in question.  I'm not sure what the disposition of this
particular case was, but that's irrelevant, as it only went to
the issue of documentary ID.  (If memory serves, there was an
interesting result of this case.  The California legislature
attempted to pass, or passed, a law that required to showing of
official identification if demanded by a police officer.  I don't
know how this law ended up, unfortunately.)

 S a n d y

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

{% endraw %}
```

## Thread

+ Return to [September 1994](/archive/1994/09)

+ Return to "[Chris Hibbert <hibbert@netcom.com>](/authors/chris_hibbert_hibbert_at_netcom_com_)"
+ Return to "[Sandy Sandfort <sandfort@crl.com>](/authors/sandy_sandfort_sandfort_at_crl_com_)"

+ 1994-09-11 (Sun, 11 Sep 94 16:55:32 PDT) - PRIVACY REGULATIONS - _Sandy Sandfort<EMAIL_ADDRESS>  + 1994-09-12 (Mon, 12 Sep 94 00:20:30 PDT) - [Re: PRIVACY REGULATIONS](/archive/1994/09/891c2ae2df2e8057e847b4bff212311fdd397f8f9fdb2a8c98e5503813ea1d7c) - _Chris Hibbert<EMAIL_ADDRESS>


text:
---
layout: default
---

# 1996-07-25 - FW: Schelling Points, Rights, and Game Theory--Part II

## Header Data

From: Blanc Weber<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: 4a21870b12512ba5b2606c88d45400160975c7cb1116c619e07fb81c39f37c58

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1996-07-25 03:55:58 UTC

Raw Date: Thu, 25 Jul 1996 11:55:58 +0800

## Raw message

```
{% raw  %}From: Blanc Weber<EMAIL_ADDRESS>Date: Thu, 25 Jul 1996 11:55:58 +0800
To<EMAIL_ADDRESS>Subject: FW: Schelling Points, Rights, and Game Theory--Part II
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

From<EMAIL_ADDRESS>
>...certainly a Schelling point or evolutionary game
>theory interpretation of what we call "rights" is superior to an
appeal-to-God or "natural rights" interpretation.
........................................................................
.................

So there is the "game theory" interpretation of "rights" as would be
understood by an individual within a group of 2 or more, or a "society"
of many individuals, and then there is the interpretation of how anyone
might interpret the concept even if they were not a member of any
society but lived totally alone in the wilderness?

I don't know why these would be categorized as being part of a "game" -
evolutionary or otherwise.   A game is something that is evaluated
somewhat outside the context of our regular life - a diversion, an
accessory, even if it also can be taken seriously or if it can become a
career for some people.   It is not given the same significance as other
practical pursuits like medicine or engineering, which are intended to
have definite, practical, beneficial results.

Any person normally posseses some ability to determine the propriety to
themselves of certain things in existence:  they  have some measure of
ability to make judgements over what is "right" or "wrong" for humankind
similar to themselves.   Most people develop some sensitivity to the
difference between that which is destructive to the goals & values of
living things versus that which is supportive of them;  most everyone is
expected to improve the ability to think  about these things as they
grow up, even if they don't hold formal arguments with anyone else about
it.

But people's minds work on overtime and just because they can make
judgements, they therefore do make judgements, and furthermore they
intend that everyone else should accept these same conclusions - they go
into "global mode", expecting that their perspective will be
incontestably valid over all.

But I wouldn't think that they imagine themselves to be playing a game.
I think they're quite serious about it, and "rightly" so, as the
consequences of these decisions have major effects upon the quality of
their life and happiness.  I think  that to think of these concepts in
terms of game theory is to miss the place of significance which these
decisions have in the life of conscious, self-determining beings like
ourselves; that it doesn't do justice to the need to achieve
correspondence with the facts of life & molecular physics.

Or,  what's the Prize for these Olympics (and who cares)?

    ..
Blanc

~ Blanc

{% endraw %}
```

## Thread

+ Return to [July 1996](/archive/1996/07)

+ Return to "[Blanc Weber <blancw@microsoft.com>](/authors/blanc_weber_blancw_at_microsoft_com_)"

+ 1996-07-25 (Thu, 25 Jul 1996 11:55:58 +0800) - FW: Schelling Points, Rights, and Game Theory--Part II - _Blanc Weber<EMAIL_ADDRESS>


text:
PEP: 580 Title: The C call protocol Author: Jeroen Demeyer
<EMAIL_ADDRESS>BDFL-Delegate: Petr Viktorin Status: Rejected
Type: Standards Track Content-Type: text/x-rst Created: 14-Jun-2018
Python-Version: 3.8 Post-History: 20-Jun-2018, 22-Jun-2018, 16-Jul-2018

Rejection Notice
================

This PEP is rejected in favor of PEP 590, which proposes a simpler
public C API for callable objects.

Abstract
========

A new \"C call\" protocol is proposed. It is meant for classes
representing functions or methods which need to implement fast calling.
The goal is to generalize all existing optimizations for built-in
functions to arbitrary extension types.

In the reference implementation, this new protocol is used for the
existing classes `builtin_function_or_method` and `method_descriptor`.
However, in the future, more classes may implement it.

**NOTE**: This PEP deals only with the Python/C API, it does not affect
the Python language or standard library.

Motivation
==========

The standard function/method classes `builtin_function_or_method` and
`method_descriptor` allow very efficiently calling C code. However, they
are not subclassable, making them unsuitable for many applications: for
example, they offer limited introspection support (signatures only using
`__text_signature__`, no arbitrary `__qualname__`, no
`inspect.getfile()`). It\'s also not possible to store additional data
to implement something like `functools.partial` or
`functools.lru_cache`. So, there are many reasons why users would want
to implement custom function/method classes (in a duck-typing sense) in
C. Unfortunately, such custom classes are necessarily slower than the
standard CPython function classes: the bytecode interpreter has various
optimizations which are specific to instances of
`builtin_function_or_method`, `method_descriptor`, `method` and
`function`.

This PEP also allows to simplify existing code: checks for
`builtin_function_or_method` and `method_descriptor` could be replaced
by simply checking for and using the C call protocol. Future PEPs may
implement the C call protocol for more classes, enabling even further
simplifications.

We also design the C call protocol such that it can easily be extended
with new features in the future.

For more background and motivation, see PEP 579.

Overview
========

Currently, CPython has multiple optimizations for fast calling for a few
specific function classes. A good example is the implementation of the
opcode `CALL_FUNCTION`, which has the following structure ([see the
actual
code](https://github.com/python/cpython/blob/7a2368063f25746d4008a74aca0dc0b82f86ff7b/Python/ceval.c#L4592)):

    if (PyCFunction_Check(func)) {
        return _PyCFunction_FastCallKeywords(func, stack, nargs, kwnames);
    }
    else if (Py_TYPE(func) == &PyMethodDescr_Type) {
        return _PyMethodDescr_FastCallKeywords(func, stack, nargs, kwnames);
    }
    else {
        if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
            /* ... */
        }
        if (PyFunction_Check(func)) {
            return _PyFunction_FastCallKeywords(func, stack, nargs, kwnames);
        }
        else {
            return _PyObject_FastCallKeywords(func, stack, nargs, kwnames);
        }
    }

Calling instances of these special-cased classes using the `tp_call`
slot is slower than using the optimizations. The basic idea of this PEP
is to enable such optimizations for user C code, both as caller and as
callee.

The existing class `builtin_function_or_method` and a few others use a
`PyMethodDef` structure for describing the underlying C function and its
signature. The first concrete change is that this is replaced by a new
structure `PyCCallDef`. This stores some of the same information as a
`PyMethodDef`, but with one important addition: the \"parent\" of the
function (the class or module where it is defined). Note that
`PyMethodDef` arrays are still used to construct functions/methods but
no longer for calling them.

Second, we want that every class can use such a `PyCCallDef` for
optimizing calls, so the `PyTypeObject` structure gains a
`tp_ccalloffset` field giving an offset to a `PyCCallDef *` in the
object structure and a flag `Py_TPFLAGS_HAVE_CCALL` indicating that
`tp_ccalloffset` is valid.

Third, since we want to deal efficiently with unbound and bound methods
too (as opposed to only plain functions), we need to handle `__self__`
in the protocol: after the `PyCCallDef *` in the object structure, there
is a `PyObject *self` field. These two fields together are referred to
as a `PyCCallRoot` structure.

The new protocol for efficiently calling objects using these new
structures is called the \"C call protocol\".

**NOTE**: In this PEP, the phrases \"unbound method\" and \"bound
method\" refer to generic behavior, not to specific classes. For
example, an unbound method gets turned into a bound method after
applying `__get__`.

New data structures
===================

The `PyTypeObject` structure gains a new field
`Py_ssize_t tp_ccalloffset` and a new flag `Py_TPFLAGS_HAVE_CCALL`. If
this flag is set, then `tp_ccalloffset` is assumed to be a valid offset
inside the object structure (similar to `tp_dictoffset` and
`tp_weaklistoffset`). It must be a strictly positive integer. At that
offset, a `PyCCallRoot` structure appears:

    typedef struct {
        const PyCCallDef *cr_ccall;
        PyObject         *cr_self;  /* __self__ argument for methods */
    } PyCCallRoot;

The `PyCCallDef` structure contains everything needed to describe how
the function can be called:

    typedef struct {
        uint32_t  cc_flags;
        PyCFunc   cc_func;    /* C function to call */
        PyObject *cc_parent;  /* class or module */
    } PyCCallDef;

The reason for putting `__self__` outside of `PyCCallDef` is that
`PyCCallDef` is not meant to be changed after creating the function. A
single `PyCCallDef` can be shared by an unbound method and multiple
bound methods. This wouldn\'t work if we would put `__self__` inside
that structure.

**NOTE**: unlike `tp_dictoffset` we do not allow negative numbers for
`tp_ccalloffset` to mean counting from the end. There does not seem to
be a use case for it and it would only complicate the implementation.

Parent
------

The `cc_parent` field (accessed for example by a `__parent__` or
`__objclass__` descriptor from Python code) can be any Python object, or
NULL. Custom classes are free to set `cc_parent` to whatever they want.
It is only used by the C call protocol if the `CCALL_OBJCLASS` flag is
set.

For methods of extension types, `cc_parent` points to the class that
defines the method (which may be a superclass of `type(self)`). This is
currently non-trivial to retrieve from a method\'s code. In the future,
this can be used to access the module state via the defining class. See
the rationale of PEP 573 for details.

When the flag `CCALL_OBJCLASS` is set (as it will be for methods of
extension types), `cc_parent` is used for type checks like the
following:

    >>> list.append({}, "x")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: descriptor 'append' requires a 'list' object but received a 'dict'

For functions of modules, `cc_parent` is set to the module. Currently,
this is exactly the same as `__self__`. However, using `__self__` for
the module is a quirk of the current implementation: in the future, we
want to allow functions which use `__self__` in the normal way, for
implementing methods. Such functions can still use `cc_parent` instead
to refer to the module.

The parent would also typically be used to implement `__qualname__`. The
new C API function `PyCCall_GenericGetQualname()` does exactly that.

Using tp\_print
---------------

We propose to replace the existing unused field `tp_print` by
`tp_ccalloffset`. Since `Py_TPFLAGS_HAVE_CCALL` would *not* be added to
`Py_TPFLAGS_DEFAULT`, this ensures full backwards compatibility for
existing extension modules setting `tp_print`. It also means that we can
require that `tp_ccalloffset` is a valid offset when
`Py_TPFLAGS_HAVE_CCALL` is specified: we do not need to check
`tp_ccalloffset != 0`. In future Python versions, we may decide that
`tp_print` becomes `tp_ccalloffset` unconditionally, drop the
`Py_TPFLAGS_HAVE_CCALL` flag and instead check for
`tp_ccalloffset != 0`.

**NOTE**: the exact layout of `PyTypeObject` is not part of the stable
ABI ([^1]). Therefore, changing the `tp_print` field from a `printfunc`
(a function pointer) to a `Py_ssize_t` should not be a problem, even if
this changes the memory layout of the `PyTypeObject` structure.
Moreover, on all systems for which binaries are commonly built (Windows,
Linux, macOS), the size of `printfunc` and `Py_ssize_t` are the same, so
the issue of binary compatibility will not come up anyway.

The C call protocol
===================

We say that a class implements the C call protocol if it has the
`Py_TPFLAGS_HAVE_CCALL` flag set (as explained above, it must then set
`tp_ccalloffset > 0`). Such a class must implement `__call__` as
described in this section (in practice, this just means setting
`tp_call` to `PyCCall_Call`).

The `cc_func` field is a C function pointer, which plays the same role
as the existing `ml_meth` field of `PyMethodDef`. Its precise signature
depends on flags. The subset of flags influencing the signature of
`cc_func` is given by the bitmask `CCALL_SIGNATURE`. Below are the
possible values for `cc_flags & CCALL_SIGNATURE` together with the
arguments that the C function takes. The return value is always
`PyObject *`. The following are analogous to the existing `PyMethodDef`
signature flags:

-   `CCALL_VARARGS`: `cc_func(PyObject *self, PyObject *args)`
-   `CCALL_VARARGS | CCALL_KEYWORDS`:
    `cc_func(PyObject *self, PyObject *args, PyObject *kwds)` (`kwds` is
    either `NULL` or a dict; this dict must not be modified by the
    callee)
-   `CCALL_FASTCALL`:
    `cc_func(PyObject *self, PyObject *const *args, Py_ssize_t nargs)`
-   `CCALL_FASTCALL | CCALL_KEYWORDS`:
    `cc_func(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)`
    (`kwnames` is either `NULL` or a non-empty tuple of keyword names)
-   `CCALL_NOARGS`: `cc_func(PyObject *self, PyObject *unused)` (second
    argument is always `NULL`)
-   `CCALL_O`: `cc_func(PyObject *self, PyObject *arg)`

The flag `CCALL_DEFARG` may be combined with any of these. If so, the C
function takes an additional argument as first argument before `self`,
namely a const pointer to the `PyCCallDef` structure used for this call.
For example, we have the following signature:

-   `CCALL_DEFARG | CCALL_VARARGS`:
    `cc_func(const PyCCallDef *def, PyObject *self, PyObject *args)`

One exception is `CCALL_DEFARG | CCALL_NOARGS`: the `unused` argument is
dropped, so the signature becomes

-   `CCALL_DEFARG | CCALL_NOARGS`:
    `cc_func(const PyCCallDef *def, PyObject *self)`

**NOTE**: unlike the existing `METH_...` flags, the `CCALL_...`
constants do not necessarily represent single bits. So checking
`if (cc_flags & CCALL_VARARGS)` is not a valid way for checking the
signature. There are also no guarantees of binary compatibility for
these flags between Python versions. This allows the implementation to
choose the most efficient numerical values of the flags. In the
reference implementation, the legal values for
`cc_flags & CCALL_SIGNATURE` form exactly the interval \[0, ..., 11\].
This means that the compiler can easily optimize a `switch` statement
for those cases using a computed goto.

Checking \_\_objclass\_\_
-------------------------

If the `CCALL_OBJCLASS` flag is set and if `cr_self` is NULL (this is
the case for unbound methods of extension types), then a type check is
done: the function must be called with at least one positional argument
and the first (typically called `self`) must be an instance of
`cc_parent` (which must be a class). If not, a `TypeError` is raised.

Self slicing
------------

If `cr_self` is not NULL or if the flag `CCALL_SELFARG` is not set in
`cc_flags`, then the argument passed as `self` is simply `cr_self`.

If `cr_self` is NULL and the flag `CCALL_SELFARG` is set, then the first
positional argument is removed from `args` and instead passed as `self`
argument to the C function. Effectively, the first positional argument
is treated as `__self__`. If there are no positional arguments,
`TypeError` is raised.

This process is called \"self slicing\" and a function is said to have
self slicing if `cr_self` is NULL and `CCALL_SELFARG` is set.

Note that a `CCALL_NOARGS` function with self slicing effectively has
one argument, namely `self`. Analogously, a `CCALL_O` function with self
slicing has two arguments.

Descriptor behavior
-------------------

Classes supporting the C call protocol must implement the descriptor
protocol in a specific way.

This is required for an efficient implementation of bound methods: if
other code can make assumptions on what `__get__` does, it enables
optimizations which would not be possible otherwise. In particular, we
want to allow sharing the `PyCCallDef` structure between bound and
unbound methods. We also need a correct implementation of
`_PyObject_GetMethod` which is used by the `LOAD_METHOD`/`CALL_METHOD`
optimization.

First of all, if `func` supports the C call protocol, then
`func.__set__` and `func.__delete__` must not be implemented.

Second, `func.__get__` must behave as follows:

-   If `cr_self` is not NULL, then `__get__` must be a no-op in the
    sense that `func.__get__(obj, cls)(*args, **kwds)` behaves exactly
    the same as `func(*args, **kwds)`. It is also allowed for `__get__`
    to be not implemented at all.
-   If `cr_self` is NULL, then `func.__get__(obj, cls)(*args, **kwds)`
    (with `obj` not None) must be equivalent to
    `func(obj, *args, **kwds)`. In particular, `__get__` must be
    implemented in this case. This is unrelated to [self
    slicing](#self-slicing): `obj` may be passed as `self` argument to
    the C function or it may be the first positional argument.
-   If `cr_self` is NULL, then `func.__get__(None, cls)(*args, **kwds)`
    must be equivalent to `func(*args, **kwds)`.

There are no restrictions on the object `func.__get__(obj, cls)`. The
latter is not required to implement the C call protocol for example. We
only specify what `func.__get__(obj, cls).__call__` does.

For classes that do not care about `__self__` and `__get__` at all, the
easiest solution is to assign `cr_self = Py_None` (or any other non-NULL
value).

The \_\_name\_\_ attribute
--------------------------

The C call protocol requires that the function has a `__name__`
attribute which is of type `str` (not a subclass).

Furthermore, the object returned by `__name__` must be stored somewhere;
it cannot be a temporary object. This is required because
`PyEval_GetFuncName` uses a borrowed reference to the `__name__`
attribute (see also[^2]).

Generic API functions
---------------------

This section lists the new public API functions or macros dealing with
the C call protocol.

-   `int PyCCall_Check(PyObject *op)`: return true if `op` implements
    the C call protocol.

All the functions and macros below apply to any instance supporting the
C call protocol. In other words, `PyCCall_Check(func)` must be true.

-   `PyObject *PyCCall_Call(PyObject *func, PyObject *args, PyObject *kwds)`:
    call `func` with positional arguments `args` and keyword arguments
    `kwds` (`kwds` may be NULL). This function is meant to be put in the
    `tp_call` slot.
-   `PyObject *PyCCall_FastCall(PyObject *func, PyObject *const *args, Py_ssize_t nargs, PyObject *kwds)`:
    call `func` with `nargs` positional arguments given by `args[0]`,
    ..., `args[nargs-1]`. The parameter `kwds` can be NULL (no keyword
    arguments), a dict with `name:value` items or a tuple with keyword
    names. In the latter case, the keyword values are stored in the
    `args` array, starting at `args[nargs]`.

Macros to access the `PyCCallRoot` and `PyCCallDef` structures:

-   `const PyCCallRoot *PyCCall_CCALLROOT(PyObject *func)`: pointer to
    the `PyCCallRoot` structure inside `func`.
-   `const PyCCallDef *PyCCall_CCALLDEF(PyObject *func)`: shorthand for
    `PyCCall_CCALLROOT(func)->cr_ccall`.
-   `uint32_t PyCCall_FLAGS(PyObject *func)`: shorthand for
    `PyCCall_CCALLROOT(func)->cr_ccall->cc_flags`.
-   `PyObject *PyCCall_SELF(PyOject *func)`: shorthand for
    `PyCCall_CCALLROOT(func)->cr_self`.

Generic getters, meant to be put into the `tp_getset` array:

-   `PyObject *PyCCall_GenericGetParent(PyObject *func, void *closure)`:
    return `cc_parent`. Raise `AttributeError` if `cc_parent` is NULL.
-   `PyObject *PyCCall_GenericGetQualname(PyObject *func, void *closure)`:
    return a string suitable for using as `__qualname__`. This uses the
    `__qualname__` of `cc_parent` if possible. It also uses the
    `__name__` attribute.

Profiling
---------

The profiling events `c_call`, `c_return` and `c_exception` are only
generated when calling actual instances of `builtin_function_or_method`
or `method_descriptor`. This is done for simplicity and also for
backwards compatibility (such that the profile function does not receive
objects that it does not recognize). In a future PEP, we may extend
C-level profiling to arbitrary classes implementing the C call protocol.

Changes to built-in functions and methods
=========================================

The reference implementation of this PEP changes the existing classes
`builtin_function_or_method` and `method_descriptor` to use the C call
protocol. In fact, those two classes are almost merged: the
implementation becomes very similar, but they remain separate classes
(mostly for backwards compatibility). The `PyCCallDef` structure is
simply stored as part of the object structure. Both classes use
`PyCFunctionObject` as object structure. This is the new layout for both
classes:

::: {#PyCFunctionObject}
    typedef struct {
        PyObject_HEAD
        PyCCallDef  *m_ccall;
        PyObject    *m_self;         /* Passed as 'self' arg to the C function */
        PyCCallDef   _ccalldef;      /* Storage for m_ccall */
        PyObject    *m_name;         /* __name__; str object (not NULL) */
        PyObject    *m_module;       /* __module__; can be anything */
        const char  *m_doc;          /* __text_signature__ and __doc__ */
        PyObject    *m_weakreflist;  /* List of weak references */
    } PyCFunctionObject;
:::

For functions of a module and for unbound methods of extension types,
`m_ccall` points to the `_ccalldef` field. For bound methods, `m_ccall`
points to the `PyCCallDef` of the unbound method.

**NOTE**: the new layout of `method_descriptor` changes it such that it
no longer starts with `PyDescr_COMMON`. This is purely an implementation
detail and it should cause few (if any) compatibility problems.

C API functions
---------------

The following function is added (also to the stable ABI[^3]):

-   `PyObject * PyCFunction_ClsNew(PyTypeObject *cls, PyMethodDef *ml, PyObject *self, PyObject *module, PyObject *parent)`:
    create a new object with object structure `PyCFunctionObject` and
    class `cls`. The entries of the `PyMethodDef` structure are used to
    construct the new object, but the pointer to the `PyMethodDef`
    structure is not stored. The flags for the C call protocol are
    automatically determined in terms of `ml->ml_flags`, `self` and
    `parent`.

The existing functions `PyCFunction_New`, `PyCFunction_NewEx` and
`PyDescr_NewMethod` are implemented in terms of `PyCFunction_ClsNew`.

The undocumented functions `PyCFunction_GetFlags` and
`PyCFunction_GET_FLAGS` are deprecated. They are still artificially
supported by storing the original `METH_...` flags in a bitfield inside
`cc_flags`. Despite the fact that `PyCFunction_GetFlags` is technically
part of the stable ABI[^4], it is highly unlikely to be used that way:
first of all, it is not even documented. Second, the flag
`METH_FASTCALL` is not part of the stable ABI but it is very common
(because of Argument Clinic). So, if one cannot support `METH_FASTCALL`,
it is hard to imagine a use case for `PyCFunction_GetFlags`. The fact
that `PyCFunction_GET_FLAGS` and `PyCFunction_GetFlags` are not used at
all by CPython outside of `Objects/call.c` further shows that these
functions are not particularly useful.

Inheritance
===========

Extension types inherit the type flag `Py_TPFLAGS_HAVE_CCALL` and the
value `tp_ccalloffset` from the base class, provided that they implement
`tp_call` and `tp_descr_get` the same way as the base class. Heap types
never inherit the C call protocol because that would not be safe (heap
types can be changed dynamically).

Performance
===========

This PEP should not impact the performance of existing code (in the
positive or negative sense). It is meant to allow efficient new code to
be written, not to make existing code faster.

Here are a few pointers to the `python-dev` mailing list where
performance improvements are discussed:

-   <https://mail.python.org/pipermail/python-dev/2018-July/154571.html>
-   <https://mail.python.org/pipermail/python-dev/2018-July/154740.html>
-   <https://mail.python.org/pipermail/python-dev/2018-July/154775.html>
-   <https://mail.python.org/pipermail/python-dev/2019-April/156954.html>

Stable ABI
==========

The function `PyCFunction_ClsNew` is added to the stable ABI[^5].

None of the functions, structures or constants dealing with the C call
protocol are added to the stable ABI.

There are two reasons for this: first of all, the most useful feature of
the C call protocol is probably the `METH_FASTCALL` calling convention.
Given that this is not even part of the public API (see also PEP 579,
issue 6), it would be strange to add anything else from the C call
protocol to the stable ABI.

Second, we want the C call protocol to be extensible in the future. By
not adding anything to the stable ABI, we are free to do that without
restrictions.

Backwards compatibility
=======================

There is no difference at all for the Python interface, nor for the
documented C API (in the sense that all functions remain supported with
the same functionality).

The only potential breakage is with C code which accesses the internals
of `PyCFunctionObject` and `PyMethodDescrObject`. We expect very few
problems because of this.

Rationale
=========

Why is this better than PEP 575?
--------------------------------

One of the major complaints of PEP 575 was that is was coupling
functionality (the calling and introspection protocol) with the class
hierarchy: a class could only benefit from the new features if it was a
subclass of `base_function`. It may be difficult for existing classes to
do that because they may have other constraints on the layout of the C
object structure, coming from an existing base class or implementation
details. For example, `functools.lru_cache` cannot implement PEP 575
as-is.

It also complicated the implementation precisely because changes were
needed both in the implementation details and in the class hierarchy.

The current PEP does not have these problems.

Why store the function pointer in the instance?
-----------------------------------------------

The actual information needed for calling an object is stored in the
instance (in the `PyCCallDef` structure) instead of the class. This is
different from the `tp_call` slot or earlier attempts at implementing a
`tp_fastcall` slot[^6].

The main use case is built-in functions and methods. For those, the C
function to be called does depend on the instance.

Note that the current protocol makes it easy to support the case where
the same C function is called for all instances: just use a single
static `PyCCallDef` structure for every instance.

Why CCALL\_OBJCLASS?
--------------------

The flag `CCALL_OBJCLASS` is meant to support various cases where the
class of a `self` argument must be checked, such as:

    >>> list.append({}, None)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: append() requires a 'list' object but received a 'dict'

    >>> list.__len__({})
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: descriptor '__len__' requires a 'list' object but received a 'dict'

    >>> float.__dict__["fromhex"](list, "0xff")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: descriptor 'fromhex' for type 'float' doesn't apply to type 'list'

In the reference implementation, only the first of these uses the new
code. The other examples show that these kind of checks appear in
multiple places, so it makes sense to add generic support for them.

Why CCALL\_SELFARG?
-------------------

The flag `CCALL_SELFARG` and the concept of self slicing are needed to
support methods: the C function should not care whether it is called as
unbound method or as bound method. In both cases, there should be a
`self` argument and this is simply the first positional argument of an
unbound method call.

For example, `list.append` is a `METH_O` method. Both the calls
`list.append([], 42)` and `[].append(42)` should translate to the C call
`list_append([], 42)`.

Thanks to the proposed C call protocol, we can support this in such a
way that both the unbound and the bound method share a `PyCCallDef`
structure (with the `CCALL_SELFARG` flag set).

So, `CCALL_SELFARG` has two advantages: there is no extra layer of
indirection for calling methods and constructing bound methods does not
require setting up a `PyCCallDef` structure.

Another minor advantage is that we could make the error messages for a
wrong call signature more uniform between Python methods and built-in
methods. In the following example, Python is undecided whether a method
takes 1 or 2 arguments:

    >>> class List(list):
    ...     def myappend(self, item):
    ...         self.append(item)
    >>> List().myappend(1, 2)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: myappend() takes 2 positional arguments but 3 were given
    >>> List().append(1, 2)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: append() takes exactly one argument (2 given)

It is currently impossible for `PyCFunction_Call` to know the actual
number of user-visible arguments since it cannot distinguish at runtime
between a function (without `self` argument) and a bound method (with
`self` argument). The `CCALL_SELFARG` flag makes this difference
explicit.

Why CCALL\_DEFARG?
------------------

The flag `CCALL_DEFARG` gives the callee access to the `PyCCallDef *`.
There are various use cases for this:

1.  The callee can use the `cc_parent` field, which is useful for
    PEP 573.
2.  Applications are free to extend the `PyCCallDef` structure with
    user-defined fields, which can then be accessed analogously.
3.  In the case where the `PyCCallDef` structure is part of the object
    structure (this is true for example for
    [PyCFunctionObject](#PyCFunctionObject)), an appropriate offset can
    be subtracted from the `PyCCallDef` pointer to get a pointer to the
    callable object defining that `PyCCallDef`.

An earlier version of this PEP defined a flag `CCALL_FUNCARG` instead of
`CCALL_DEFARG` which would pass the callable object to the callee. This
had similar use cases, but there was some ambiguity for bound methods:
should the \"callable object\" be the bound method object or the
original function wrapped by the method? By passing the `PyCCallDef *`
instead, this ambiguity is gone since the bound method uses the
`PyCCallDef *` from the wrapped function.

Replacing tp\_print
-------------------

We repurpose `tp_print` as `tp_ccalloffset` because this makes it easier
for external projects to backport the C call protocol to earlier Python
versions. In particular, the Cython project has shown interest in doing
that (see
<https://mail.python.org/pipermail/python-dev/2018-June/153927.html>).

Alternative suggestions
=======================

PEP 576 is an alternative approach to solving the same problem as this
PEP. See
<https://mail.python.org/pipermail/python-dev/2018-July/154238.html> for
comments on the difference between PEP 576 and PEP 580.

Discussion
==========

Links to threads on the `python-dev` mailing list where this PEP has
been discussed:

-   <https://mail.python.org/pipermail/python-dev/2018-June/153938.html>
-   <https://mail.python.org/pipermail/python-dev/2018-June/153984.html>
-   <https://mail.python.org/pipermail/python-dev/2018-July/154238.html>
-   <https://mail.python.org/pipermail/python-dev/2018-July/154470.html>
-   <https://mail.python.org/pipermail/python-dev/2018-July/154571.html>
-   <https://mail.python.org/pipermail/python-dev/2018-September/155166.html>
-   <https://mail.python.org/pipermail/python-dev/2018-October/155403.html>
-   <https://mail.python.org/pipermail/python-dev/2019-March/156853.html>
-   <https://mail.python.org/pipermail/python-dev/2019-March/156879.html>

Reference implementation
========================

The reference implementation can be found at
<https://github.com/jdemeyer/cpython/tree/pep580>

For an example of using the C call protocol, the following branch
implements `functools.lru_cache` using PEP 580:
<https://github.com/jdemeyer/cpython/tree/lru580>

References
==========

Copyright
=========

This document has been placed in the public domain.

###

> Local Variables: mode: indented-text indent-tabs-mode: nil
> sentence-end-double-space: t fill-column: 70 coding: utf-8 End:

[^1]: Löwis, PEP 384 -- Defining a Stable ABI,
    <https://www.python.org/dev/peps/pep-0384/>

[^2]: Bad C API,
    <https://pythoncapi.readthedocs.io/bad_api.html#bad-c-api>

[^3]: Löwis, PEP 384 -- Defining a Stable ABI,
    <https://www.python.org/dev/peps/pep-0384/>

[^4]: Löwis, PEP 384 -- Defining a Stable ABI,
    <https://www.python.org/dev/peps/pep-0384/>

[^5]: Löwis, PEP 384 -- Defining a Stable ABI,
    <https://www.python.org/dev/peps/pep-0384/>

[^6]: Add tp\_fastcall to PyTypeObject: support FASTCALL calling
    convention for all callable objects,
    <https://bugs.python.org/issue29259>

repository: erdal-pb/opep

repo_name: erdal-pb/opep


text:
# Twitter Function Image

This function exemplifies an authentication in Twitter API and get latest tweets of an account.

## Requirements

- IronFunctions API
- Configure a [Twitter App](https://apps.twitter.com/) and [configure Customer Access and Access Token](https://dev.twitter.com/oauth/overview/application-owner-access-tokens).

## Development

### Building image locally

```
# SET BELOW TO YOUR DOCKER HUB USERNAME
USERNAME=YOUR_DOCKER_HUB_USERNAME

# build it
./build.sh
```

### Publishing to DockerHub

```
# tagging
docker run --rm -v "$PWD":/app treeder/bump patch
docker tag $USERNAME/func-twitter:latest $USERNAME/func-twitter:`cat VERSION`

# pushing to docker hub
docker push $USERNAME/func-twitter
```

### Testing image

```
./test.sh
```

## Running it on IronFunctions

### Let's define some environment variables

```
# Set your Function server address
# Eg. <IP_ADDRESS>:8080
FUNCAPI=YOUR_FUNCTIONS_ADDRESS

CUSTOMER_KEY="XXXXXX"
CUSTOMER_SECRET="XXXXXX"
ACCESS_TOKEN="XXXXXX"
ACCESS_SECRET="XXXXXX"
```

### Running with IronFunctions

With this command we are going to create an application with name `twitter`.

```
curl -X POST --data '{
    "app": {
        "name": "twitter",
        "config": {
            "CUSTOMER_KEY": "'$CUSTOMER_KEY'",
            "CUSTOMER_SECRET": "'$CUSTOMER_SECRET'",
            "ACCESS_TOKEN": "'$ACCESS_TOKEN'",
            "ACCESS_SECRET": "'$ACCESS_SECRET'"
        }
    }
}' http://$FUNCAPI/v1/apps
```

Now, we can create our route

```
curl -X POST --data '{
    "route": {
        "image": "'$USERNAME'/func-twitter",
        "path": "/tweets",
    }
}' http://$FUNCAPI/v1/apps/twitter/routes
```

#### Testing function

Now that we created our IronFunction route, let's test our new route

```
curl -X POST --data '{"username": "getiron"}' http://$FUNCAPI/r/twitter/tweets
```

repository: treeder/functions

gha_language: Go

repo_name: treeder/functions


text:
[< Previous](../sum-of-distances-in-tree "Sum of Distances in Tree")

[Next >](../rectangle-overlap "Rectangle Overlap")

## [835. Image Overlap (Medium)](https://leetcode.com/problems/image-overlap "图像重叠")

You are given two images img1 and img2 both of size n x n, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)

We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image.  After, the overlap of this translation is the number of positions that have a 1 in both images.

(Note also that a translation does not include any kind of rotation.)

What is the largest possible overlap?

Example 1:

Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
Explanation: We slide img1 to right by 1 unit and down by 1 unit.

The number of positions that have a 1 in both images is 3. (Shown in red)

Example 2:

Input: img1 = [[1]], img2 = [[1]]
Output: 1

Example 3:

Input: img1 = [[0]], img2 = [[0]]
Output: 0

Constraints:

n == img1.length

n == img1[i].length

n == img2.length

n == img2[i].length

1 <= n <= 30

img1[i][j] is 0 or 1.

img2[i][j] is 0 or 1.

### Related Topics
  [[Array](../../tag/array/README.md)]

repository: rohini-raja/leetcode

repo_name: rohini-raja/leetcode


text:
---
category: post
layout: post
title: "Market Size"
image_url: http://farm1.staticflickr.com/53/155918164_cb8dd42438_b.jpg
image_credit: Thomas Hawk
image_credit_url: http://www.flickr.com/photos/thomashawk
series: business plans
tags: [investor deck, markets, startups, investors]
meta_description: Market size is arguablly the most important thing when deciding to build a business.  Market size is an incredibly important metric for measuring the opportunity of a startup.

In order to identify and calculate market size you need to first identify the customers you cater to. If you are b2b startup, who are you selling to? Who will sign off on the purchase.  Market sizes can be calculated using a top-down and bottoms-up approach. Both of these methods though are estimates. This is important to keep in mind while pitching.

Calculating Total Addressable Market
----------------------------------------------------
The TAM is calculated using a top down approach. This method is used for understanding how many users there are in the world which can use this product.

Let's say we are selling baby food online. The TAM would be the total number of internet users who have babies. There are [2.2 Billion internet users](http://www.internetworldstats.com/stats.htm). Current birth rates sit around [20 per 1,000 people](http://www.indexmundi.com/g/g.aspx?c=xx&v=25). So out of 2.2 Billion internet users, 2% have had babies in the past year. This makes our total addressable market at 44 Million people.

This calculation used unit market share. Rather than calculating units, you could also calculate dollar market share. Dollar market share is the total amount of money waiting to be captured.

Calculating Serviceable Available Market
---------------------------------------------------------
The SAM represents how much of the TAM you can actually serve. It is used as the bridge between how many users there are and how many users would actually use your product or service. If you are selling baby food online, how many people would actually purchase baby food online? The result of this calculation will be your SAM.

Calculating Share of Market
----------------------------------------
The SOM is used to figure out how much of the market isn't captured. This takes a lot of competitive analysis and hopefully some of the metrics are available to you. You need to understand who the incumbents are and how much market share they control. Take into consideration the countries they serve and their sales and distribution channels.

Once you understand the current market, you take the SAM and subtract the already served market from it. This result is the Share of Market you can capture. The importance of share of market cannot be overstated. In order to have a strong forecast for what you can actually accomplish you need to understand the competitive landscape and how much of it your competition have already captured.

Assumptions, Good Data, and New Markets
---------------------------------------------------------------
Remember, these calculations are estimates. Calculated guesses as to how large the opportunity is. When pitching these numbers realize you will be challenged on your assumptions. The data you use should be rock solid and unquestionable. If you use rock solid data, ney-sayers will only be able to challenge your assumptions and not the data you base your assumptions on.

Don't pitch investors with the concept of being in a "new" market. Although it seems venture capitalists should be investing in new markets, there is actually too much risk involved. If you were to tell this to a hedge fund manager, he would laugh you out of the room. The purpose of an limited partner putting money into a venture capital fund is to invest in emerging markets. The venture capitalists as investors though are still trying to back there bets and invest in opportunities which are known.

If you think you are in a new market, which hasn't been defined, it is your responsibility as an entrepreneur to demonstrate how you fit into current markets.

Is Our Market Large Enough to Obtain Capital?
-------------------------------------------------------------
Just because you have a [hard problem to solve][1] with paying users, doesn't mean it can be a venture backed business. Venture capitalists require really large markets in order to make profits. Although you could be sitting on an easy $50mm or $100mm per year opportunity, venture capital will have no problem telling you no.

In order to get venture backing consumer markets should be at least 1B potential users. With the amount of users available to you, you can get a lot of people using your products. A lot of people means a lot of eyes to see ads.

Business markets (B2B), by definition, won't have the same size of opportunity as consumer-based businesses. Those business however make up for it in average sale price. The cost of having a direct sales or direct marketing team however needs to be cost effective.

Your market size is the most important part of your investor slide deck. Make sure the answer to your market-size question is data backed and rock solid.

[1]: /2012/02/solving-hard-problems/

gha_language: HTML


text:
api-bench
=========

Hacked together utility to get some basic metrics. Pretty specific to the purpose it was designed for. Work in progress.

Usage information available via `bin\api-bench --help`.

```shell
$ bin/api-bench --help

Usage: api-bench <uri> [options]

uri     URI to run benchmark against

Options:
   -r, --requests     Number of requests  [100]
   -c, --concurrent   Concurrent requests  [1]
   -v, --verbose      Output each request time  [false]
   -m, --method       HTTP method  [GET]
   -H, --header       Specify HTTP headers to use on the requests, can be specified multiple times
   -s, --script       Execution script that the benchmark will follow
   -o, --output       Destination file for output, uses stdout if not specified
```

### TODO

* Support request bodies (via a file path perhaps)
* Implement output file
* Implement execution script

repository: crallen/api-bench

repo_name: crallen/api-bench


text:
# Read: Class 13

# Readings: Linear Regressions

## What is Linear Regression?

Linear regression is a basic and commonly used type of predictive analysis.  The overall idea of regression is to examine two things: (1) does a set of predictor variables do a good job in predicting an outcome (dependent) variable?  (2) Which variables in particular are significant predictors of the outcome variable, and in what way do they–indicated by the magnitude and sign of the beta estimates–impact the outcome variable?  These regression estimates are used to explain the relationship between one dependent variable and one or more independent variables.  The simplest form of the regression equation with one dependent and one independent variable is defined by the formula y = c + b*x, where y = estimated dependent variable score, c = constant, b = regression coefficient, and x = score on the independent variable.

Naming the Variables.  There are many names for a regression’s dependent variable.  It may be called an outcome variable, criterion variable, endogenous variable, or regressand.  The independent variables can be called exogenous variables, predictor variables, or regressors.

Three major uses for regression analysis are (1) determining the strength of predictors, (2) forecasting an effect, and (3) trend forecasting.

First, the regression might be used to identify the strength of the effect that the independent variable(s) have on a dependent variable.  Typical questions are what is the strength of relationship between dose and effect, sales and marketing spending, or age and income.

Second, it can be used to forecast effects or impact of changes.  That is, the regression analysis helps us to understand how much the dependent variable changes with a change in one or more independent variables.  A typical question is, “how much additional sales income do I get for each additional $1000 spent on marketing?”

Third, regression analysis predicts trends and future values.  The regression analysis can be used to get point estimates.  A typical question is, “what will the price of gold be in 6 months?”

# Types of Linear Regression

- Simple linear regression
1 dependent variable (interval or ratio), 1 independent variable (interval or ratio or dichotomous)

- Multiple linear regression
1 dependent variable (interval or ratio) , 2+ independent variables (interval or ratio or dichotomous)

- Logistic regression
1 dependent variable (dichotomous), 2+ independent variable(s) (interval or ratio or dichotomous)

- Ordinal regression
1 dependent variable (ordinal), 1+ independent variable(s) (nominal or dichotomous)

- Multinomial regression
1 dependent variable (nominal), 1+ independent variable(s) (interval or ratio or dichotomous)

- Discriminant analysis
1 dependent variable (nominal), 1+ independent variable(s) (interval or ratio)

# Sources / Bookmarks

https://www.statisticssolutions.com/what-is-linear-regression/

https://bigdata-madesimple.com/how-to-run-linear-regression-in-python-scikit-learn/

https://realpython.com/linear-regression-in-python/

https://towardsdatascience.com/train-test-split-and-cross-validation-in-python-80b61beca4b6


text:
# CommonHelpers

This is a cross platform `netstandard2.0` helper library containing a wide range of helper classes and data generation code that I used to write over and over, every day, while creating sample apps for developers.

Due to the number of "File > New" projects I create every day, this package has saved me a *significant* amount of time (the `SampleDataService` alone is a game changer).

## Releases

| NuGet.org (recommended) | GitHub Releases (all releases) |
|-----------|----------------------|
| [![#](https://img.shields.io/nuget/v/CommonHelpers.svg)](https://www.nuget.org/packages/CommonHelpers/) | [Releases Page](https://github.com/LanceMcCarthy/CommonHelpers/releases/) |

## Features

### Extensions

Extensions for commonly used objects like; `string`, `DateTime`, and `enum`. As well as handy methods for `File`, `Exception` and `Color` objects. There's also the `HttpClientExtensions` where you can get download progress insights and a helper method to POST image data.

For example, you can quickly get easing function values using the `EasingExtensions`. Here's a screenshot of the `myFloatValue.BackEaseIn()` example.

![easing demo](https://user-images.githubusercontent.com/3520532/163871294-9be04ecd-8dcb-49ca-967b-7f1ff8e091b1.png)

### Collections

Special collection types that help in special scenarios (e.g. `ObservableQueue` and `ObservableRangeCollection`).

### Common

This folder has some of the most used classes. For example, `BindableBase`, `ViewModelBase`, `JsonHelper` to name a few.

### MVVM

Platform agnostic MVVM classes like `DelegateCommand` and `RelayCommand`.

### Services

To make testing UI controls easier by quickly providing well formatted data from offline sample data and online API endpoints. This is really useful for quickly testing *Load On Demand* scenarios.

* `BingImageService`
* `ComicVineApiService`
* `SampleDataService`
* `XkcdApiService`

> The **ComicVineService** requires an API Key, but a key is free. All other services do not require an API key, new-up the class and start using it right away.

## Examples

### Sample Data Service
This is my most frequently used service. You can easily spin up data for Lists, Charts, DataGrids and more with a single method.

```C#
BarSeriesData.AddRange(SampleDataService.Current.GenerateCategoricalData());
ScatterSeriesData.AddRange(SampleDataService.Current.GenerateScatterPointData());
LineSeriesData.AddRange(SampleDataService.Current.GenerateDateTimeMinuteData());
SplineAreaSeriesData.AddRange(SampleDataService.Current.GenerateDateTimeDayData());

People.AddRange(SampleDataService.Current.GeneratePeopleData());
Employees.AddRange(SampleDataService.Current.GenerateEmployeeData(true));

Products.AddRange(SampleDataService.Current.GenerateProductData());
Categories.AddRange(SampleDataService.Current.GenerateCategoryData());
```
![Sample Data Service](https://user-images.githubusercontent.com/3520532/41983551-7254db84-79fc-11e8-89b0-347b25054fb3.png)

### BingImageService

Easily fetch the Bing Image of Day.

```C#
using (var bingImageService = new BingImageService())
{
    var result = await bingImageService.GetBingImageOfTheDayAsync();
    image.Source = new UriImageSource{Uri = result};
}
```
![Bing ImageService](https://user-images.githubusercontent.com/3520532/41982158-b3ffeea6-79f8-11e8-81a5-abe23142cd75.png)

### xkcd API Service

Getting today's comic by calling `GetNewestComic` or get any comic by using `GetComicAsync(comicNumber)`.

```C#
var xkcdService = new XkcdApiService();

// to fetch a comic, get the latest or pass a specific comic ID
XkcdComic xkcdComic;

if (lastXkcdComicNumber == 0)
{
    xkcdComic = await xkcdService.GetNewestComicAsync();
}
else
{
    xkcdComic = await xkcdService.GetComicAsync(lastXkcdComicNumber - 1);
}

lastXkcdComicNumber = xkcdComic.Num;

// This is an `ObservableQueue` (located in CommonHelpers.Collections)
XkcdComics.Enqueue(xkcdComic);

```
![xkcd Image Service](https://user-images.githubusercontent.com/3520532/41982114-99259568-79f8-11e8-8eaa-f76695130b55.png)

### ComicVineApiService

The ComicVine API is the only service in which you'll need an API key. You pass the key and a unique string name for your app to the constructor. Now you have access to thousands of items like Characters, Videos and more from the service.

```C#
var comicVineService = new ComicVineApiService(ApiKeys.ComicVineApiKey, ApiKeys.UniqueUserAgentString);

var apiResult = await comicVineService.GetCharactersAsync(CurrentCharactersCount);
CurrentCharactersCount = apiResult.Offset + apiResult.NumberOfPageResults;
TotalCharactersCount = apiResult.NumberOfTotalResults;

var characters = apiResult.Results;
```
![ComicVine API Service](https://user-images.githubusercontent.com/3520532/41982141-a83cb3e2-79f8-11e8-8207-e6bbbe590d25.png)

repository: LanceMcCarthy/CommonHelpers

branch_name: refs/heads/main

gha_language: C#

repo_name: LanceMcCarthy/CommonHelpers


text:
# [890. Find and Replace Pattern][enTitle]

**Medium**

You have a list of  *words*  and a  *pattern* , and you want to know which words in  *words*  matches the pattern.

A word matches the pattern if there exists a permutation of letters  *p*  so that after replacing every letter  *x*  in the pattern with  *p(x)* , we get the desired word.

( *Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.* )

Return a list of the words in  *words*  that match the given pattern.

You may return the answer in any order.

**Example 1:**

```
Input:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
Output: ["mee","aqq"]
Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}.
"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation,
since a and b map to the same letter.
```

**Note:**

-  *1 <= words.length <= 50*
-  *1 <= pattern.length = words[i].length <= 20*

# [890. 查找和替换模式][cnTitle]

**中等**

你有一个单词列表  *words*  和一个模式  *pattern* ，你想知道  *words*  中的哪些单词与模式匹配。

如果存在字母的排列  *p*  ，使得将模式中的每个字母  *x*  替换为  *p(x)*  之后，我们就得到了所需的单词，那么单词与模式是匹配的。

 *（回想一下，字母的排列是从字母到字母的双射：每个字母映射到另一个字母，没有两个字母映射到同一个字母。）*

返回  *words*  中与给定模式匹配的单词列表。

你可以按任何顺序返回答案。

**示例：**

```
输入：words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
输出：["mee","aqq"]
解释："mee" 与模式匹配，因为存在排列 {a -> m, b -> e, ...}。
"ccc" 与模式不匹配，因为 {a -> c, b -> c, ...} 不是排列。
因为 a 和 b 映射到同一个字母。
```

**提示：**

-  *1 <= words.length <= 50*
-  *1 <= pattern.length = words[i].length <= 20*

# 算法思路

# 测试用例
```
890. Find and Replace Pattern 890. 查找和替换模式 Medium
```

[enTitle]: https://leetcode.com/problems/find-and-replace-pattern/
[cnTitle]: https://leetcode-cn.com/problems/find-and-replace-pattern/

repository: philippzhang/leetcodeLearnJava

gha_language: Java

repo_name: philippzhang/leetcodeLearnJava