<|start_filename|>gpgpu/cuda/examples/simple-kernel/program1.cu<|end_filename|>
// From PTT

// (單一區塊, 單一執行緒)

#include <cuda.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

////////////////////////////////////////
// 向量加法的運算核心 (GPU)
// 函式前加 __global__ 即為核心
// 核心只傳回 void
////////////////////////////////////////

__global__ void gpu_add(float* c, float* a, float* b, int n){
    for (int k=0; k<n; k++) {
        c[k] = a[k]+b[k];
    }
}

////////////////////////////////////////
// 向量加法的一般函式 (Host)
////////////////////////////////////////

void host_add(float* c, float* a, float* b, int n){
    for (int k=0; k<n; k++) {
        c[k] = a[k]+b[k];
    }
}


////////////////////////////////////////
// 計算誤差用的函式
////////////////////////////////////////

double diff(float* a, float* b, int n){
    double s=0, r=0;
    for (int k=0; k<n; k++) {
        double w=a[k]-b[k];
        s += w*w;
        r += a[k]*a[k];
    }
    return sqrt(s/r); //相對誤差
}

////////////////////////////////////////
// 時間函數 (傳回單位:千分之一秒)
////////////////////////////////////////

double ms_time(){
    return (double)clock()/CLOCKS_PER_SEC*1000.0;
}

////////////////////////////////////////
// 主程式
////////////////////////////////////////

int main(){
    // 設定向量大小
    int n = 1024*1024;
    int size = n*sizeof(float);

    // 網格與區塊設定
    int grid  = 1;  // gridDim  (每個網格具有的區塊數)
    int block = 1;  // blockDim (每個區塊具有的執行緒數)

    // 設定呼叫次數 (測量平均效能)
    int loop=100;

    // 配置主機記憶體
    float *a,*b,*c,*d;
    a = (float*)malloc(size);
    b = (float*)malloc(size);
    c = (float*)malloc(size);
    d = (float*)malloc(size);

    // 設定亂數的輸入向量
    srand(time(0));

    for (int k=0; k<n; k++) {
        a[k] = (float)rand()/RAND_MAX*2-1;
        b[k] = (float)rand()/RAND_MAX*2-1;
    }

    // 配置顯示卡記憶體
    float  *ga,*gb,*gc;
    cudaMalloc((void**)&ga, size);
    cudaMalloc((void**)&gb, size);
    cudaMalloc((void**)&gc, size);

    // 載入向量 a,b 到顯示卡記憶體中
    cudaMemcpy(ga, a, size, cudaMemcpyHostToDevice);
    cudaMemcpy(gb, b, size, cudaMemcpyHostToDevice);

    ////////////////////////////////////////
    // part 1 : 測量精確度
    ////////////////////////////////////////

    // 呼叫核心來運算 (GPU)
    gpu_add<<<grid, block>>>(gc, ga, gb, n);

    // 呼叫一般函數來運算 (Host)
    host_add(d, a, b, n);

    // 把計算結果存回主機
    cudaMemcpy(c, gc, size, cudaMemcpyDeviceToHost);

    // 比較兩者差異
    printf("vector add N(%d) elements, diff = %g\n", n, diff(c,d,n));



    ////////////////////////////////////////
    // part 2 : 測量效能
    ////////////////////////////////////////

    // 測量 GPU 核心效能
    double gpu_dt = ms_time();
    for (int w=0; w<loop; w++) {
        gpu_add<<<grid, block>>>(gc, ga, gb, n);
        cudaThreadSynchronize();    //避免核心執行不完全
    }
    gpu_dt = (ms_time()-gpu_dt)/loop;   //平均時間


    // 測量 Host 函數效能
    double host_dt = ms_time();
    for (int w=0; w<loop; w++) {
        host_add(d, a, b, n);
    }
    host_dt = (ms_time()-host_dt)/loop; //平均時間


    // 輸出平均執行時間
    printf("host time: %g ms\n", host_dt);
    printf("gpu  time: %g ms\n", gpu_dt);


    // 釋放主機記憶體
    free(a);
    free(b);
    free(c);
    free(d);

    // 釋放顯示卡記憶體
    cudaFree(ga);
    cudaFree(gb);
    cudaFree(gc);

    return 0;
}


// vector add N(1048576) elements, diff = 0
// host time: 3.4024 ms
// gpu  time: 120.62 ms


<|start_filename|>gpgpu/opencl/examples/example2.cpp<|end_filename|>
// $(CXX) -Wall -Wextra -std=c++14 -O3 -lOpenCL

#include <CL/cl.hpp>

#include <iostream>
#include <fstream>  // need by ifstream
#include <vector>

// pick up device type from compiler command line or from the default type
#ifndef DEVICE
    #define DEVICE CL_DEVICE_TYPE_DEFAULT
#endif

std::string loadProgram(std::string input) {
    std::ifstream stream(input.c_str());
    if (!stream.is_open()) {
        std::cout << "Cannot open file: " << input << std::endl;
        exit(1);
    }

    return std::string(std::istreambuf_iterator<char>(stream),
                       std::istreambuf_iterator<char>());
}

int main(int argc, char *argv[]) {

    std::vector<int> a = {1, 2, 3, 4, 5};
    std::vector<int> b = {2, 3, 4, 5, 6};
    std::vector<int> c(5, 0);

    ////////////////////////////////////////
    // OpenCL
    ////////////////////////////////////////

    // Create a context
    cl::Context context(DEVICE);

    // Load in kernel source, creating a program object for the context
    cl::Program program(context, loadProgram("cl_add.cl"), true);     // true to build ...

    // Create the kernel functor
    cl::make_kernel<cl::Buffer, cl::Buffer, cl::Buffer> cl_add(program, "cl_add");

    // Get the command queue
    cl::CommandQueue queue(context);

    cl::Buffer g_a = cl::Buffer(context, a.begin(), a.end(), true);     // readOnly = True
    cl::Buffer g_b = cl::Buffer(context, b.begin(), b.end(), true);     // readOnly = True
    cl::Buffer g_c = cl::Buffer(context, c.begin(), c.end(), false);    // readOnly = False

    cl_add(
        cl::EnqueueArgs(
                queue,
                cl::NDRange(a.size())),
        g_a,
        g_b,
        g_c);

    queue.flush();
    queue.finish();

    cl::copy(queue, g_c, c.begin(), c.end());   // get result

    ////////////////////////////////////////
    // Output
    ////////////////////////////////////////

    for (size_t i = 0; i < c.size(); i++) {
        std::cout << c[i] << std::endl;
    }

    return 0;
}


<|start_filename|>programming-language/cases/cpp/examples/virtual-and-cast-2.cpp<|end_filename|>
#include <iostream>

template<class T>
class Base {
public:
    virtual void f() {
        std::cout << "Base    (Virtual)" << std::endl;
    }

    void g() {
        std::cout << "Base    (Non-Virutal)" << std::endl;
    }

    void h() {
        // simulated dynamic binding
        // use this instead of virtual function to avoid the cost of dynamic polymorphism
        // no virtual table is needed for this function
        static_cast<T*>(this)->g();
    }
};

class Derived : public Base<Derived> {  // CRTP (curiously recurring template pattern) (F-bound polymorphism)
public:
    void f() {
        std::cout << "Derived (Virtual)" << std::endl;
    }

    void g() {
        std::cout << "Derived (Non-Virtual)" << std::endl;
    }
};

template<class T>
T& func(T& tmp) {

    // call Derived for virtual
    // call Base for non-virtual

    tmp.f();    // virtual
    tmp.g();    // non-virtual
    tmp.h();    // non-virtual

    return tmp;
}

int main() {

    Derived foo;

    std::cout << "===== Derived" << std::endl;

    foo.f();    // Derived
    foo.g();    // Derived
    foo.h();    // Derived

    std::cout << "===== Derived with static_cast<Derived::Base>" << std::endl;

    static_cast<Derived::Base>(foo).f();     // Base
    static_cast<Derived::Base>(foo).g();     // Base
    static_cast<Derived::Base>(foo).h();     // Derived

    std::cout << "===== Derived with static_cast<Derived::Base&>" << std::endl;

    static_cast<Derived::Base&>(foo).f();    // Derived
    static_cast<Derived::Base&>(foo).g();    // Base
    static_cast<Derived::Base&>(foo).h();    // Derived

    std::cout << "===== Derived with func1(T&)" << std::endl;

    Derived& bar = func(foo);

    std::cout << "===== Derived with T func1(T&)" << std::endl;

    bar.f();    // Derived
    bar.g();    // Derived
    bar.h();    // Derived

    return 0;
}


<|start_filename|>programming-language/cases/rust/examples/kernel_module/01_hello/Makefile<|end_filename|>
########################################
# Rust Setting
########################################

CARGO  ?= $(shell which cargo)

# http://clang.llvm.org/docs/CrossCompilation.html#target-triple
# http://llvm.org/docs/doxygen/html/Triple_8h_source.html
# <arch><sub>-<vendor>-<sys>-<abi>
TRIPLE := x86_64-unknown-none-gnu

########################################
# Linux Kernel Module Setting
########################################

KERNEL_VERSION    := $(shell uname -r)
KERNEL_BUILD_PATH := /lib/modules/$(KERNEL_VERSION)/build

# Name of this kernel module
KERNEL_MODULE     := hello

# Object Files
rust-target       := ${KERNEL_MODULE}_rust.o    # build by Cargo
obj-m             += ${KERNEL_MODULE}.o         # tell kbuild which files to build
${KERNEL_MODULE}-objs := src/module.o ${rust-target}    # let them link together

########################################
# Rules
########################################

all:
	$(CARGO) rustc --release --verbose $(CARGOFLAGS) --target="$(TRIPLE)" -- --emit obj -o $(rust-target)
	$(MAKE) -C $(KERNEL_BUILD_PATH) M=$(CURDIR) modules
	cp "$(KERNEL_MODULE).ko" "$(KERNEL_MODULE).stripped.ko" && strip "$(KERNEL_MODULE).stripped.ko"

clean:
	$(MAKE) -C $(KERNEL_BUILD_PATH) M=$(CURDIR) clean
	$(CARGO) clean
	rm -f *.d *.rlib


<|start_filename|>programming-language/cases/cpp/examples/parallel.cpp<|end_filename|>
#include <iostream>             // cout, endl
#include <vector>               // vector
#include <random>               // random_device, mt19937, normal_distribution
#include <chrono>               // high_resolution_clock
#include <parallel/algorithm>   // sort, for_each

int main() {

    // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution

    std::random_device rd;
    std::mt19937 gen(rd());

    // values near the mean are the most likely
    // standard deviation affects the dispersion of generated values from the mean
    std::normal_distribution<> d(5, 2);

    std::vector<int> x(9000000, 42);


    for (auto i = 0; i < 10; ++i) {
        // normal version
        auto start = std::chrono::high_resolution_clock::now();

        for_each(x.begin(), x.end(), [&](auto& i){ i = d(gen); });
        sort(x.begin(), x.end());

        auto end = std::chrono::high_resolution_clock::now();
        auto diff = end - start;
        std::cout << "[Normal  ] Time: "
                  << diff.count() << " ticks"
                  << " | "
                  << std::chrono::duration_cast<std::chrono::seconds>(diff).count() << " s" << std::endl;
    }

    for (auto i = 0; i < 10; ++i) {
        // parallel version
        auto start = std::chrono::high_resolution_clock::now();

        __gnu_parallel::for_each(x.begin(), x.end(), [&](auto& i){ i = d(gen); });
        __gnu_parallel::sort(x.begin(), x.end());

        auto end = std::chrono::high_resolution_clock::now();
        auto diff = end - start;
        std::cout << "[Parallel] Time: "
                  << diff.count() << " ticks"
                  << " | "
                  << std::chrono::duration_cast<std::chrono::seconds>(diff).count() << " s" << std::endl;
    }

    return 0;
}


<|start_filename|>programming-language/jit/examples/basic-mmap-mprotect.cpp<|end_filename|>
#include <string.h>     // memcpy
#include <sys/mman.h>   // mmap
#include <iostream>     // perror

const size_t SIZE = 1024;
typedef long (*JittedFunc)(long);

// Allocates RW memory of given size and returns a pointer to it.
// On failure, prints out the error and returns NULL.
void* alloc_writable_memory(size_t size) {
    auto ptr = mmap(0,
                    size,
                    PROT_READ | PROT_WRITE,
                    MAP_PRIVATE | MAP_ANONYMOUS,
                    -1,
                    0);
    if (ptr == (void*)-1) {
        perror("mmap");
        return nullptr;
    }
    return ptr;
}

// Allocates RWX memory of given size and returns a pointer to it. On failure,
// prints out the error and returns NULL.
void* alloc_executable_memory(size_t size) {
    auto ptr = mmap(0,
                    size,
                    PROT_READ | PROT_WRITE | PROT_EXEC,
                    MAP_PRIVATE | MAP_ANONYMOUS,
                    -1,
                    0);
    if (ptr == (void*)-1) {
        perror("mmap");
        return nullptr;
    }
    return ptr;
}

// Sets a RX permission on the given memory, which must be page-aligned.
// Returns 0 on success. On failure, prints out the error and returns -1.
int make_memory_executable(void* m, size_t size) {
    if (mprotect(m, size, PROT_READ | PROT_EXEC) == -1) {
        perror("mprotect");
        return -1;
    }
    return 0;
}

void emit_code_into_memory(unsigned char* m) {
    unsigned char code[] = {
        0x48, 0x89, 0xf8,                   // mov %rdi, %rax
        0x48, 0x83, 0xc0, 0x04,             // add $4, %rax
        0xc3                                // ret
    };
    memcpy(m, code, sizeof(code));
}

// Allocates RW memory,
// emits the code into it and sets it to RX before executing.
void emit_to_rw_run_from_rx() {
    void* m = alloc_writable_memory(SIZE);
    emit_code_into_memory(static_cast<unsigned char*>(m));
    make_memory_executable(m, SIZE);

    JittedFunc func = reinterpret_cast<JittedFunc>(m);
    int result = func(2);
    printf("result = %d\n", result);
}

// Allocates RWX memory directly.
void run_from_rwx() {
    void* m = alloc_executable_memory(SIZE);
    emit_code_into_memory(static_cast<unsigned char*>(m));

    JittedFunc func = reinterpret_cast<JittedFunc>(m);
    int result = func(2);
    printf("result = %d\n", result);
}

int main() {
    run_from_rwx();             // not safe
    emit_to_rw_run_from_rx();   // safer
    return 0;
}


<|start_filename|>programming-language/cases/cpp/examples/thread.cpp<|end_filename|>
// clang++ -std=c++14 -Wall -Wextra -lpthread

#include <iostream> // cout, endl
#include <thread>   // thread
#include <future>   // async, promise, packaged_task

void f1() {
    std::cout << "f1 !!!" << std::endl;
}

void f2(int n) {
    std::cout << "f2 !!!" << std::endl;
}

void f3(int &n) {
    ++n;
    std::cout << "f3 !!!" << std::endl;
}

auto f4(int &n) {
    ++n;
    std::cout << "f4 !!!" << std::endl;
    return n;
}

void f5(int &n, std::promise<int> promise) {
    ++n;
    std::cout << "f5 !!!" << std::endl;
    promise.set_value(n);
}

int main() {

    const auto n = std::thread::hardware_concurrency();
    std::cout << n << " concurrent threads are supported.\n";

    ////////////////////////////////////////
    // Invoke Each Thread
    ////////////////////////////////////////

    {
        std::thread t(f1);                      // no parameter
        t.join();
    }

    {
        std::thread t(f2, 1);                   // pass by value
        t.join();
    }

    {
        int data = 42;
        std::cout << "before: " << data << std::endl;
        std::thread t(f3, std::ref(data));      // pass by reference, need std::ref
        t.join();
        std::cout << "after:  " << data << std::endl;
    }

    {
        int data = 42;
        std::cout << "before: " << data << std::endl;
        std::thread t(f4, std::ref(data));
        std::thread new_t(std::move(t));        // new_t is now running f4(), t is no longer a thread
        new_t.join();
        std::cout << "after:  " << data << std::endl;
    }

    ////////////////////////////////////////
    // Async & Future
    ////////////////////////////////////////

    {
        int data = 42;
        // explicitly use std::launch::async to force program use thread
        auto future = std::async(std::launch::async, &f4, std::ref(data));
        future.wait();
        std::cout << "result from future: " << future.get() << std::endl;
    }

    ////////////////////////////////////////
    // Promise
    ////////////////////////////////////////

    {
        int data = 42;
        std::promise<int> myPromise;
        auto future = myPromise.get_future();
        std::thread t(f5, std::ref(data), std::move(myPromise));
        future.wait();
        std::cout << "future.get(): " << future.get() << std::endl;
        t.join();
    }

    ////////////////////////////////////////
    // packaged_task
    ////////////////////////////////////////

    {
        // future from a packaged_task
        std::packaged_task<int(int, int)> task([=](int a, int b){ return a+b; }); // wrap the function
        std::future<int> future = task.get_future();    // get a future
        std::thread(std::move(task), 42, 56).detach();  // launch on a thread
        future.wait();
        std::cout << "future.get(): " << future.get() << std::endl;
    }

    {
        std::packaged_task<int(int, int)> task([=](int a, int b){ return a+b; }); // wrap the function
        std::future<int> future = task.get_future();    // get a future
        task(42, 56);   // launch on same thread, this will block
        std::cout << "future.get(): " << future.get() << std::endl;

        task.reset();                   // re-use same task object
        future = task.get_future();     // re-get the future
        std::thread(std::move(task), 43, 57).detach();  // launch on another thread
        future.wait();
        std::cout << "future.get(): " << future.get() << std::endl;
    }

    return 0;
}


<|start_filename|>programming-language/cases/cpp/examples/virtual.cpp<|end_filename|>
#include <iostream>

class Base {
public:
    void func() { std::cout << "Base\n"; }
};

class Derived1 : public Base {
public:
    virtual void func() { printf("Derived1\n"); }
};

class Derived2 : public Derived1 {
public:
    void func() { printf("Derived2\n"); }    // already virtual since Derived1
};

int main() {
    auto derived1 = Derived1 {};
    auto derived2 = Derived2 {};
    auto d1b    = static_cast<Base&>    (derived1);
    auto d2d1   = static_cast<Derived1&>(derived2);
    auto pd1b   = static_cast<Base*>    (&derived1);
    auto pd2d1  = static_cast<Derived1*>(&derived2);

    d1b.func();     // Base
    d2d1.func();    // Derived1
    pd1b->func();   // Base
    pd2d1->func();  // Derived2
}


<|start_filename|>programming-language/cases/cpp/examples/virtual-base-class.cpp<|end_filename|>
#include <iostream>

class MyClass {
public:
    MyClass();
    MyClass(int n);                         // default ctor
    MyClass(MyClass&);                      // copy ctor (@_@)
    MyClass(const MyClass&);                // copy ctor (const)
    MyClass(MyClass&&);                     // move ctor
    MyClass& operator=(MyClass&);           // copy assignment (@_@)
    MyClass& operator=(const MyClass&);     // copy assignment (const)
    MyClass& operator=(MyClass&&);          // move assignment
    MyClass& operator=(int);                // literal assignment
    ~MyClass();                             // dtor

    int data = 42;
    const int origin = 42;
};

MyClass::MyClass() {
    std::cout << "[default ctor] MyClass() "
              << "[" << this << "] "
              << this->data << std::endl;
}

MyClass::~MyClass() {
    std::cout << "[dtor        ] ~MyClass() "
              << "[" << this << "] " << this->origin << " | " << this->data
              << std::endl;
}

class A : public MyClass {};
class B : public MyClass {};
class C : public MyClass {};
class D : public A, public B, public C {
public:
    void func() {
        A::data = 1;
        B::data = 2;
        C::data = 3;
        std::cout << A::data << " "
                  << B::data << " "
                  << C::data << " "
                  << std::endl;
    }
};

class VA : virtual public MyClass {};
class VB : public virtual MyClass {};
class VC : public MyClass {};
class VD : VA, VB, VC {
public:
    void func() {
        VA::data = 1;
        VB::data = 2;
        VC::data = 3;
        std::cout << VA::data << " "
                  << VB::data << " "
                  << VC::data << " "
                  << std::endl;
    }
};


int main() {
    std::cout << "=== non-virtual base" << std::endl;
    {
        auto x = D {};
        x.func();
    }
    std::cout << "=== tow virtual base and one non-virtual base" << std::endl;
    {
        auto y = VD {};
        y.func();
    }
    return 0;
}


<|start_filename|>programming-language/cases/python/examples/cpython/01-hello-world/04_hellomodule.c<|end_filename|>
#include <Python.h>
#include <structmember.h>   // PyMemberDef, T_INT

////////////////////////////////////////
// New Type
////////////////////////////////////////

typedef struct {
    PyObject_HEAD   // macro for every type in Python
    // Type-specific fields go here
    int life;
} LifeObject;

// Members

static PyMemberDef Life_members[] = {
    {"life", T_INT, offsetof(LifeObject, life), 0, "number of life"},
    {NULL}
};

static int LifeObject_init(LifeObject *self, PyObject *args, PyObject *kwds) {
    self->life = 42;

    // "|" : remaining arguments in the Python argument list are optional
    // "i" : convert a plain C int to a Python integer object.
    if (!PyArg_ParseTuple(args, "|i", &(self->life)))
        return 0;

    return 0;
}

static PyTypeObject LifeType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "hello.Life",               // tp_name, for printing, "<module>.<name>"
    sizeof(LifeObject),         // tp_basicsize, for allocation
    0,                          // tp_itemsize, for allocation

    // Methods to implement standard operations

    0,                          // tp_dealloc
    0,                          // tp_print
    0,                          // tp_getattr
    0,                          // tp_setattr
    0,                          // tp_as_async, formerly known as tp_compare (Python 2) or tp_reserved (Python 3)
    0,                          // tp_repr

    // Methods for standard classes

    0,                          // tp_as_number
    0,                          // tp_as_sequence
    0,                          // tp_as_mapping

    // More standard operations (here for binary compatibility)

    0,                          // tp_hash
    0,                          // tp_call
    0,                          // tp_str
    0,                          // tp_getattro
    0,                          // tp_setattro

    ////////////////////////////////////////

    0,                          // tp_as_buffer, functions to access object as input/output buffer
    Py_TPFLAGS_DEFAULT,         // tp_flags, flags to define presence of optional/expanded features
    "Life Object",              // tp_doc, docstring

    ////////////////////////////////////////

    0,                          // tp_traverse, assigned meaning in release 2.0, call function for all accessible objects
    0,                          // tp_clear, delete references to contained objects
    0,                          // tp_richcompare, assigned meaning in release 2.1, rich comparisons
    0,                          // tp_weaklistoffset, weak reference enabler
    0,                          // tp_iter, iterators
    0,                          // tp_iternext, iterators

    // Attribute descriptor and subclassing stuff

    0,                          // tp_methods
    Life_members,               // tp_members
    0,                          // tp_getset
    0,                          // tp_base
    0,                          // tp_dict
    0,                          // tp_descr_get
    0,                          // tp_descr_set
    0,                          // tp_dictoffset
    (initproc)LifeObject_init,  // tp_init
    0,                          // tp_alloc
    PyType_GenericNew,          // tp_new
    0,                          // tp_free, low-level free-memory routine
    0,                          // tp_is_gc, for PyObject_IS_GC
    0,                          // tp_bases
    0,                          // tp_mro, method resolution order
    0,                          // tp_cache
    0,                          // tp_subclasses
    0,                          // tp_weaklist
    0,                          // tp_del

    0,                          // tp_version_tag, type attribute cache version tag. Added in version 2.6
    0,                          // tp_finalize
};

////////////////////////////////////////
// Methods
////////////////////////////////////////

static PyObject* hello_world(PyObject *self, PyObject *args) {
    return Py_BuildValue("s", "Hello World");
}

////////////////////////////////////////
// Module Definition
////////////////////////////////////////

PyDoc_STRVAR(module_doc, "Simple 'Hello World' Module");

static PyMethodDef methods[] = {
    { "hello_world", hello_world, METH_VARARGS, "Say hello." },
    {NULL, NULL},
};

static PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT,  // PyModuleDef_HEAD_INIT
    "hello",    // module name
    module_doc, // docstring
    0,          // size of per-module area
    methods,    // methods (table of module-level functions)
    NULL,       // array of slot definitions
    NULL,       // traverse function for GC
    NULL,       // clear function for GC
    NULL        // deallocation function
};

PyMODINIT_FUNC PyInit_hello(void) {

    // Types

    if (PyType_Ready(&LifeType) < 0)
        return NULL;

    // Module

    PyObject *m = PyModule_Create(&moduledef);

    // Types

    if (m == NULL)
        return NULL;

    Py_INCREF(&LifeType);
    PyModule_AddObject(m, "Life", (PyObject *)&LifeType);

    return m;
}

////////////////////////////////////////
// Examples
////////////////////////////////////////

// >>> import hello
// >>> hello.hello_world()
// 'Hello World'
// >>> hello.Life
// <class 'hello.Life'>
// >>> hello.Life().life
// 42
// >>> hello.Life(10).life
// 10


<|start_filename|>programming-language/cases/cpp/examples/rvo.cpp<|end_filename|>
// clang++ -std=c++14 -Wall -Wextra

#include <iostream>

class MyClass {
public:
    MyClass(int n);                         // default ctor
    MyClass(MyClass&);                      // copy ctor (@_@)
    MyClass(const MyClass&);                // copy ctor (const)
    MyClass(MyClass&&);                     // move ctor
    MyClass& operator=(MyClass&);           // copy assignment (@_@)
    MyClass& operator=(const MyClass&);     // copy assignment (const)
    MyClass& operator=(MyClass&&);          // move assignment
    ~MyClass();                             // dtor
    MyClass operator+(const MyClass&) const;    // operator+
    MyClass& operator+=(const MyClass&);        // operator+=

    int data = 42;
    const int origin = 42;
};

MyClass::MyClass(int n) : data(n), origin(n) {
    std::cout << "[default ctor] MyClass() "
              << "[" << this << "] "
              << this->data << std::endl;
}

MyClass::MyClass(MyClass&) {
    std::cout << "[copy ctor   ] MyClass(MyClass&)" << std::endl;
}

MyClass::MyClass(const MyClass&) {
    std::cout << "[copy ctor c ] MyClass(const MyClass&)" << std::endl;
}

MyClass::MyClass(MyClass&&) {
    std::cout << "[move ctor   ] MyClass(MyClass&&)" << std::endl;
}

MyClass& MyClass::operator=(MyClass&) {
    std::cout << "[copy assign ] operator=(MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(const MyClass&) {
    std::cout << "[copy assign ] operator=(const MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(MyClass&&) {
    std::cout << "[move assign ] operator=(MyClass&&)" << std::endl;
    return *this;
}

MyClass::~MyClass() {
    std::cout << "[dtor        ] ~MyClass() "
              << "[" << this << "] " << this->origin << " | " << this->data
              << std::endl;
}

MyClass MyClass::operator+(const MyClass& rhs) const {
    std::cout << "[operator add] operator+(const MyClass&) const "
              << "[" << this << "] " << this->data
              << " + "
              << "[" << &rhs << "] " << rhs.data << std::endl;
    MyClass tmp(this->data + rhs.data);
    return tmp;
}

MyClass& MyClass::operator+=(const MyClass& rhs) {
    std::cout << "[operator add] operator+=(const MyClass&) "
              << "[" << this << "] " << this->data
              << " + "
              << "[" << &rhs << "] " << rhs.data << std::endl;
    this->data += rhs.data;
    return *this;
}

auto f1(int n) {
    std::cout << "===== f1 start =====" << std::endl;
    if (n < 1) {
        ////////////////////////////////////////
        // version 1, NRVO
        //
        // auto tmp = MyClass(n);
        //
        ////////////////////////////////////////
        // version 2, NRVO for const local

        const  auto tmp = MyClass(n);

        ////////////////////////////////////////
        std::cout << "===== f1 end   =====" << std::endl;
        return tmp;
    } else {
        ////////////////////////////////////////
        // version 1, default ctor
        //
        // auto tmp = MyClass(n) + f1(n-1);   // will call "default ctor" here, and "dtor" later
        //
        ////////////////////////////////////////
        // version 2, NRVO

        auto tmp = MyClass(n);
        tmp += f1(n-1);

        ////////////////////////////////////////
        std::cout << "===== f1 end   =====" << std::endl;
        return tmp;
    }
}

auto f2(int n) {
    std::cout << "===== f2 start =====" << std::endl;
    auto tmp = f1(n);
    // auto tmp2 = tmp + tmp;   // will call "default ctor" here, and "dtor" later
    tmp += tmp;
    std::cout << "===== f2 end   =====" << std::endl;
    return tmp;
}

int main(int argc, char *argv[]) {

    auto x = f2(5);
    std::cout << "[" << &x << "]" << std::endl;
    std::cout << x.data << std::endl;

    return 0;
}


<|start_filename|>build-system/examples/meson/10_subprojects/src/main.c<|end_filename|>
#include <stdio.h>
#include "proj1.h"
#include "proj2.h"

int main() {
    func1();
    func2();
}


<|start_filename|>programming-language/cases/rust/examples/kernel_module/00_c_module/hello.c<|end_filename|>
#include <linux/module.h>

static int hello_init(void)
{
	printk(KERN_INFO "Hello\n");
	return 0;
}

static void hello_exit(void)
{
	printk(KERN_INFO "Goodbye\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");


<|start_filename|>programming-language/cases/python/examples/cpython/01-hello-world/03_hellomodule.c<|end_filename|>
#include <Python.h>

////////////////////////////////////////
// Methods
////////////////////////////////////////

static PyObject* hello_world(PyObject *self, PyObject *args) {
    return Py_BuildValue("s", "Hello World");
}

////////////////////////////////////////
// Module Definition
////////////////////////////////////////

PyDoc_STRVAR(module_doc, "Simple 'Hello World' Module");

static PyMethodDef methods[] = {
    { "hello_world", hello_world, METH_VARARGS, "Say hello." },
    {NULL, NULL},
};

static PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT,  // PyModuleDef_HEAD_INIT
    "hello",    // module name
    module_doc, // docstring
    0,          // size of per-module area
    methods,    // methods (table of module-level functions)
    NULL,       // array of slot definitions
    NULL,       // traverse function for GC
    NULL,       // clear function for GC
    NULL        // deallocation function
};

PyMODINIT_FUNC PyInit_hello(void) {
    return PyModule_Create(&moduledef);
}

////////////////////////////////////////


<|start_filename|>parallel/mpi/examples/Makefile<|end_filename|>
CC=mpicc
CFLAGS=-Wall -Wextra -O3
BIN_DIR=bin

%: %.c prepare
	$(CC) $(CFLAGS) $< -o $(BIN_DIR)/$@

prepare:
	mkdir -p $(BIN_DIR)


<|start_filename|>programming-language/cases/cpp/examples/smart-pointer.cpp<|end_filename|>
#include <memory>       // smart pointer
#include <iostream>
#include <array>


class MyClass {
public:
    MyClass();      // default ctor
    ~MyClass();     // dtor
};

MyClass::MyClass() {
    std::cout << "[default ctor] MyClass()" << std::endl;
}

MyClass::~MyClass() {
    std::cout << "[dtor        ] ~MyClass()" << std::endl;
}


MyClass func1() {   // allocate on Stack, will be RVO to caller stack
    auto foo = MyClass();
    std::cout << &foo << std::endl;
    return foo;
}

MyClass* func2() {  // need explicit delete, or it will have memory leak
    auto foo = new MyClass();
    std::cout << foo << std::endl;
    return foo;
}

auto func3() {      // unique_ptr, delete object automatically when there is no owner
    auto foo = std::make_unique<MyClass>();     // make_unique is C++14
    std::cout << foo.get() << std::endl;
    return foo;
}

auto func4() {      // shared_ptr, delete object automatically when there is no sharer
    auto foo = std::make_shared<MyClass>();     // make_shared is C++11
    std::cout << foo.get() << std::endl;
    return foo;
}

template<typename T>
void share_with_you(std::shared_ptr<T> ptr) {
    std::cout << "Share Count: " << ptr.use_count() << std::endl;
}


int main() {

    std::cout << "=== Allocate on Stack ===" << std::endl;
    {
        auto foo = func1();
        std::cout << &foo << std::endl;
    }

    std::cout << "=== Allocate on Heap (without explicit delete) ===" << std::endl;
    {
        auto foo = func2();
        std::cout << foo << std::endl;
    }

    std::cout << "=== Allocate on Heap (unique_ptr) ===" << std::endl;
    {
        auto foo = func3();
        std::cout << foo.get() << std::endl;
    }

    std::cout << "=== Allocate on Heap (shared_ptr) ===" << std::endl;
    {
        auto foo = func4();
        std::cout << foo.get() << std::endl;
        std::cout << "Share Count: " << foo.use_count() << std::endl;
        share_with_you(foo);
        std::cout << "Share Count: " << foo.use_count() << std::endl;
    }
    std::cout << "=== Allocate on Heap (return shared_ptr, assign weak_ptr) ===" << std::endl;
    {
        std::weak_ptr<MyClass> foo = func4();   // this will not keep the object
        std::cout << foo.use_count() << std::endl;
        auto ptr = foo.lock();
        if (ptr == nullptr) {   // or foo.expired()
            std::cout << "I don't have object :(" << std::endl;
        }
    }

    std::cout << "=== shared_ptr and array ===" << std::endl;
    {
        std::shared_ptr<MyClass> foo(new MyClass[3],
                                     [](MyClass* ptr){ delete [] ptr; });
    }
    std::cout << "=== shared_ptr and array ===" << std::endl;
    {
        auto foo = std::make_shared<std::array<MyClass, 3>>();
    }

    return 0;
}


<|start_filename|>programming-language/cases/cpp/examples/copy-elision.cpp<|end_filename|>
#include <iostream>
#include <memory>

class MyClass {
public:
    constexpr MyClass(){};
    MyClass(int n);                         // default ctor
    MyClass(MyClass&);                      // copy ctor (@_@)
    MyClass(const MyClass&);                // copy ctor (const)
    MyClass(MyClass&&);                     // move ctor
    MyClass& operator=(MyClass&);           // copy assignment (@_@)
    MyClass& operator=(const MyClass&);     // copy assignment (const)
    MyClass& operator=(MyClass&&);          // move assignment
    ~MyClass();                             // dtor

    int data = 42;
    const int origin = 42;
};

MyClass::MyClass(int n) : data(n), origin(n) {
    std::cout << "[default ctor] MyClass() "
              << "[" << this << "] "
              << this->data << std::endl;
}

MyClass::MyClass(MyClass&) {
    std::cout << "[copy ctor   ] MyClass(MyClass&)" << std::endl;
}

MyClass::MyClass(const MyClass&) {
    std::cout << "[copy ctor c ] MyClass(const MyClass&)" << std::endl;
}

MyClass::MyClass(MyClass&&) {
    std::cout << "[move ctor   ] MyClass(MyClass&&)" << std::endl;
}

MyClass& MyClass::operator=(MyClass&) {
    std::cout << "[copy assign ] operator=(MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(const MyClass&) {
    std::cout << "[copy assign ] operator=(const MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(MyClass&&) {
    std::cout << "[move assign ] operator=(MyClass&&)" << std::endl;
    return *this;
}

MyClass::~MyClass() {
    std::cout << "[dtor        ] ~MyClass() "
              << "[" << this << "] " << this->origin << " | " << this->data
              << std::endl;
}


////////////////////////////////////////

MyClass f() { return MyClass { 42 }; }

MyClass g() {
    // copy elision when initializing from a temporary, spec in C++17
    MyClass x = MyClass { 42 };
    return x;   // NRVO or move, not guaranteed in C++17
}

void h(MyClass foo) {
    std::cout << foo.data << '\n';
}

int main() {
    {   // copy elision
        // prvalue of same type, spec in C++17
        // result: default -> dtor
        auto x = MyClass ( MyClass ( MyClass ( 42 ) ) );
    }
    std::cout << "=====" << '\n';
    {   // copy elision
        // prvalue of same type, spec in C++17
        // result: default -> dtor
        auto x = MyClass { MyClass { MyClass { 42 } } };
    }
    std::cout << "=====" << '\n';
    {   // copy elision
        // prvalue and return type is same type, spec in C++17
        // result: default -> dtor
        auto x = f();
    }
    std::cout << "=====" << '\n';
    {   // copy elision
        // result: default -> dtor
        auto x = g();
    }
    std::cout << "=====" << '\n';
    {   // copy elision
        // prvalue and return type is same type, spec in C++17
        // result: default -> dtor
        auto x = new MyClass(f());
        delete x;
    }
    std::cout << "=====" << '\n';
    {   // copy elision
        // prvalue and return type is same type, spec in C++17
        // result: default -> dtor
        auto x = new MyClass{f()};
        delete x;
    }
    std::cout << "=====" << '\n';
    {   // copy elision
        // result: default -> dtor
        h(g());
    }

    return 0;
}


<|start_filename|>programming-language/cases/cpp/examples/lambda-simple.cpp<|end_filename|>
#include <iostream>

class MyClass {
public:
    constexpr MyClass(){};
    MyClass(int n);                         // default ctor
    MyClass(MyClass&);                      // copy ctor (@_@)
    MyClass(const MyClass&);                // copy ctor (const)
    MyClass(MyClass&&);                     // move ctor
    MyClass& operator=(MyClass&);           // copy assignment (@_@)
    MyClass& operator=(const MyClass&);     // copy assignment (const)
    MyClass& operator=(MyClass&&);          // move assignment
    MyClass& operator=(int);                // literal assignment
    ~MyClass();                             // dtor

    void func(MyClass& i, MyClass& j);

    int data = 42;
};

MyClass::MyClass(int n) : data(n) {
    std::cout << "[default ctor] MyClass() "
              << "[" << this << "] "
              << this->data << std::endl;
}

MyClass::MyClass(MyClass& rhs) {
    std::cout << "[copy ctor   ] MyClass(MyClass&)" << std::endl;
    this->data = rhs.data;
    this->data = rhs.data;
}

MyClass::MyClass(const MyClass& rhs) {
    std::cout << "[copy ctor c ] MyClass(const MyClass&)" << std::endl;
    this->data = rhs.data;
    this->data = rhs.data;
}

MyClass::MyClass(MyClass&&) {
    std::cout << "[move ctor   ] MyClass(MyClass&&)" << std::endl;
}

MyClass& MyClass::operator=(MyClass&) {
    std::cout << "[copy assign ] operator=(MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(const MyClass&) {
    std::cout << "[copy assign ] operator=(const MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(MyClass&&) {
    std::cout << "[move assign ] operator=(MyClass&&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(int) {
    std::cout << "[literal     ] operator=(int)" << std::endl;
    return *this;
}

MyClass::~MyClass() {
    std::cout << "[dtor        ] ~MyClass() "
              << "[" << this << "] " << this->data
              << std::endl;
}


////////////////////////////////////////

std::ostream &operator<<(std::ostream &os, MyClass const& m) {
    return os << m.data;
}

void MyClass::func(MyClass& i, MyClass& j)
{
    std::cout << "=====" << '\n';
    // ok: by-reference capture default
    [&]     { std::cout << i << " " << j << '\n'; }();

    std::cout << "=====" << '\n';
    // ok: by-copy capture default
    [=]     { std::cout << i << " " << j << '\n'; }();

    std::cout << "=====" << '\n';
    // ok: by-reference capture, except i is captured by copy
    [&, i]  { std::cout << i << " " << j << '\n'; }();

    std::cout << "=====" << '\n';
    // ok: by-copy capture, except i is captured by reference
    [=, &i] { std::cout << i << " " << j << '\n'; }();

    std::cout << "=====" << '\n';
    // error: '&' cannot precede a capture when the capture default is '&'
    //        (by-reference capture when by-reference is the default)
    // [&, &i]{ std::cout << i << " " << j << '\n'; };

    std::cout << "=====" << '\n';
    // error: 'this' cannot be explicitly captured when the capture default is '='
    //        (this when = is the default)
    // [=, this]{ std::cout << i << '\n' };

    std::cout << "=====" << '\n';
    // ok: captures the enclosing MyClass by copy (C++17)
    [=, *this]  { std::cout << i << " " << j << " " << this->data << '\n'; }();

    std::cout << "=====" << '\n';
    // ok: captures the enclosing MyClass by copy (C++17)
    [&, *this]  { std::cout << i << " " << j << " " << this->data << '\n'; }();

    std::cout << "=====" << '\n';
    // ok: captures the enclosing MyClass by reference
    [&, this]   { std::cout << i << " " << j << " " << this->data << '\n'; }();

    std::cout << "=====" << '\n';
    // error: i repeated
    // [i, i]{ std::cout << i << '\n' };

    std::cout << "=====" << '\n';
    // error: "this" repeated (C++17)
    // [this, *this]{ std::cout << this->data << '\n' };
}

int main() {
    auto x = MyClass { 42 };
    auto a = MyClass { 1 };
    auto b = MyClass { 2 };
    x.func(a, b);
    return 0;
}


<|start_filename|>Makefile<|end_filename|>
BASEDIR=.
OUTPUTDIR=$(BASEDIR)/_build/html/
GITHUB_REPO_SLUG=wdv4758h/notes
GITHUB_REMOTE_NAME=origin
GITHUB_PAGES_BRANCH=gh-pages
# 以上參數請根據需求自行替換
GITHUB_COMMIT_MSG=$(shell git --no-pager log --format=%s -n 1)

sphinx:
	# 使用 README.rst 作為 index.rst
	mv README.rst index.rst

	# 用 Sphinx 編出網頁
	sphinx-build -T -E -b readthedocs -d _build/doctrees-readthedocs -D language=zh_TW . _build/html

push:
	# 為 Travis CI 設定 git 的 user.name 和 user.email
	# 沒設定 email 的話，GitHub 上面看到的 Author 會是 Unknown
	git config --global user.name "wdv4758h - Travis"
	git config --global user.email <EMAIL>

	# 將 Sphinx output dir 的內容 commit 到 GitHub Pages 用的 branch，準備 push 上去
	# user site 的 branch 是 master，project site 的 branch 是 gh-pages
	ghp-import -n -r $(GITHUB_REMOTE_NAME) -b $(GITHUB_PAGES_BRANCH) -m "$(GITHUB_COMMIT_MSG)" $(OUTPUTDIR)

	# 將剛剛的 commit push 到 GitHub 上相同的 branch
	@if [ -z ${GH_TOKEN} ]; then echo "GH_TOKEN is unset"; else echo "GH_TOKEN is set"; fi
	@git push -fq https://${GH_TOKEN}@github.com/$(GITHUB_REPO_SLUG).git $(GITHUB_PAGES_BRANCH):$(GITHUB_PAGES_BRANCH) > /dev/null
	# 用 @ 可以讓 Travis CI 不要顯示這行在 log 上，這樣別人就不會看到你的 GitHub Personal Access Token 了，也就是這裡用的 GH_TOKEN

travis: sphinx push


<|start_filename|>programming-language/cases/rust/examples/kernel_module/freebsd/hello_fsm.c<|end_filename|>
#include <sys/param.h>
#include <sys/module.h>
#include <sys/kernel.h>
#include <sys/systm.h>

// The function called at load/unload
static int event_handler(struct module *module, int event, void *arg) {
        int err = 0;    // Error, 0 for normal return status
        switch (event) {
        case MOD_LOAD:
                uprintf("simple module: Hello\n");
                break;
        case MOD_UNLOAD:
                uprintf("simple module: Goodbye\n");
                break;
        default:
                err = EOPNOTSUPP;   // Error, Operation Not Supported
                break;
        }

        return(err);
}

// The second argument of DECLARE_MODULE
static moduledata_t hello_conf = {
    "hello",         // module name
     event_handler,  // event handler
     NULL            // extra data
};

DECLARE_MODULE(hello_fsm, hello_conf, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);


<|start_filename|>programming-language/cases/python/examples/cpython/01-hello-world/Makefile<|end_filename|>
CC=clang
PYTHON_VERSION=$(shell python --version | grep -o '[[:digit:]]\.[[:digit:]]')
CFLAGS=-Wall -Wextra -O3 -fPIC --shared -I /usr/include/python$(PYTHON_VERSION)m/

all: 01_hellomodule 02_hellomodule 03_hellomodule 04_hellomodule

%: %.c
	$(CC) $(CFLAGS) $< -o hello.so


<|start_filename|>programming-language/cases/rust/examples/kernel_module/freebsd/Makefile<|end_filename|>
# It is important to make sure you include the <bsd.kmod.mk> makefile
# after declaring the KMOD and SRCS variables

MAKEOBJDIR = .

# Declare Name of kernel module
KMOD    =  hello_fsm

# Enumerate Source files for kernel module
SRCS    =  hello_fsm.c

# Include kernel module makefile
.include <bsd.kmod.mk>


<|start_filename|>programming-language/cases/cpp/examples/virtual-and-cast.cpp<|end_filename|>
#include <iostream>

class Base {
public:
    virtual void f() {
        std::cout << "Base    (Virtual)" << std::endl;
    }

    void g() {
        std::cout << "Base    (Non-Virutal)" << std::endl;
    }
};

class Derived : public Base {
public:
    void f() {
        std::cout << "Derived (Virtual)" << std::endl;
    }

    void g() {
        std::cout << "Derived (Non-Virtual)" << std::endl;
    }
};

Base& func(Base& tmp) {

    // call Derived for virtual
    // call Base for non-virtual

    tmp.f();    // virtual
    tmp.g();    // non-virtual

    return tmp;
}

int main() {

    Derived foo;

    std::cout << "===== Derived" << std::endl;

    foo.f();    // Derived
    foo.g();    // Derived

    std::cout << "===== Derived with static_cast<Base>" << std::endl;

    static_cast<Base>(foo).f();     // Base
    static_cast<Base>(foo).g();     // Base

    std::cout << "===== Derived with static_cast<Base&>" << std::endl;

    static_cast<Base&>(foo).f();    // Derived
    static_cast<Base&>(foo).g();    // Base

    std::cout << "===== Derived with func1(Base&)" << std::endl;

    Derived& bar = static_cast<Derived&>(func(foo));

    std::cout << "===== Derived with static_cast<Derived&>(func1(Base&))" << std::endl;

    bar.f();    // Derived
    bar.g();    // Derived

    return 0;
}


<|start_filename|>programming-language/cases/cpp/examples/perfect-forwarding.cpp<|end_filename|>
#include <iostream>
#include <memory>
#include <vector>

class MyClass {
public:
    constexpr MyClass(){};
    MyClass(int n);                         // default ctor
    MyClass(MyClass&);                      // copy ctor (@_@)
    MyClass(const MyClass&);                // copy ctor (const)
    MyClass(MyClass&&);                     // move ctor
    MyClass& operator=(MyClass&);           // copy assignment (@_@)
    MyClass& operator=(const MyClass&);     // copy assignment (const)
    MyClass& operator=(MyClass&&);          // move assignment
    MyClass& operator=(int);                // literal assignment
    ~MyClass();                             // dtor

    int data = 42;
    const int origin = 42;
};

MyClass::MyClass(int n) : data(n), origin(n) {
    std::cout << "[default ctor] MyClass() "
              << "[" << this << "] "
              << this->data << std::endl;
}

MyClass::MyClass(MyClass&) {
    std::cout << "[copy ctor   ] MyClass(MyClass&)" << std::endl;
}

MyClass::MyClass(const MyClass&) {
    std::cout << "[copy ctor c ] MyClass(const MyClass&)" << std::endl;
}

MyClass::MyClass(MyClass&&) {
    std::cout << "[move ctor   ] MyClass(MyClass&&)" << std::endl;
}

MyClass& MyClass::operator=(MyClass&) {
    std::cout << "[copy assign ] operator=(MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(const MyClass&) {
    std::cout << "[copy assign ] operator=(const MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(MyClass&&) {
    std::cout << "[move assign ] operator=(MyClass&&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(int) {
    std::cout << "[literal     ] operator=(int)" << std::endl;
    return *this;
}

MyClass::~MyClass() {
    std::cout << "[dtor        ] ~MyClass() "
              << "[" << this << "] " << this->origin << " | " << this->data
              << std::endl;
}


////////////////////////////////////////

template<typename T>
void func(std::vector<MyClass>& v, T&& value) {
    v.emplace_back(std::forward<T>(value));
}

template<typename T>
void func2(std::vector<MyClass>& v, T&& value) {
    v[0] = std::forward<T>(value);
}

int main() {
    std::vector<MyClass> v;
    v.reserve(10);
    std::cout << "=== x" << std::endl;
    auto x = MyClass{3};
    func(v, x);
    func2(v, x);
    std::cout << "=== MyClass" << std::endl;
    func(v, MyClass{2});
    func2(v, MyClass{2});
    std::cout << "=== 1" << std::endl;
    func(v, 1);
    func2(v, 1);
    std::cout << "===" << std::endl;
    return 0;
}


<|start_filename|>programming-language/cases/rust/examples/kernel_module/00_c_module/Makefile<|end_filename|>
KERNEL_VERSION    := $(shell uname -r)
KERNEL_BUILD_PATH := /lib/modules/$(KERNEL_VERSION)/build

# Name of this kernel module
KERNEL_MODULE     := hello

obj-m             += $(KERNEL_MODULE).o     # Tell kbuild which files to build

all:
	$(MAKE) -C $(KERNEL_BUILD_PATH) M=$(PWD) modules

clean:
	$(MAKE) -C $(KERNEL_BUILD_PATH) M=$(PWD) clean


<|start_filename|>build-system/examples/meson/10_subprojects/subprojects/proj1/src/test1.c<|end_filename|>
#include <stdio.h>
#include "proj1.h"

void func1() {
    printf("test output for func1\n");
}


<|start_filename|>build-system/examples/meson/10_subprojects/subprojects/proj1/include/proj1.h<|end_filename|>
#include <stdio.h>

void func1();


<|start_filename|>programming-language/cases/cpp/examples/ctor-dtor.cpp<|end_filename|>
// clang++ -std=c++14 -Wall -Wextra ctor-dtor.cpp

#include <iostream>

class MyClass {
public:
    MyClass();                              // default ctor
    MyClass(MyClass&);                      // copy ctor (@_@)
    MyClass(const MyClass&);                // copy ctor (const)
    MyClass(MyClass&&);                     // move ctor
    MyClass& operator=(MyClass&);           // copy assignment (@_@)
    MyClass& operator=(const MyClass&);     // copy assignment (const)
    MyClass& operator=(MyClass&&);          // move assignment
    ~MyClass();                             // dtor
};

MyClass::MyClass() {
    std::cout << "[default ctor] MyClass()" << std::endl;
}

MyClass::MyClass(MyClass&) {
    std::cout << "[copy ctor   ] MyClass(MyClass&)" << std::endl;
}

MyClass::MyClass(const MyClass&) {
    std::cout << "[copy ctor c ] MyClass(const MyClass&)" << std::endl;
}

MyClass::MyClass(MyClass&&) {
    std::cout << "[move ctor   ] MyClass(MyClass&&)" << std::endl;
}

MyClass& MyClass::operator=(MyClass&) {
    std::cout << "[copy assign ] operator=(MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(const MyClass&) {
    std::cout << "[copy assign ] operator=(const MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(MyClass&&) {
    std::cout << "[move assign ] operator=(MyClass&&)" << std::endl;
    return *this;
}

MyClass::~MyClass() {
    std::cout << "[dtor        ] ~MyClass()" << std::endl;
}

auto f1() {
    return MyClass();
}

auto f2() {
    auto x = MyClass();
    int y = 0;
    std::cout << "returned local variable address: " << &x << std::endl;
    std::cout << "normal   local variable address: " << &y << std::endl;
    return x;
}

auto f3() {
    const auto x = MyClass();
    int y = 0;
    std::cout << "returned local variable address: " << &x << std::endl;
    std::cout << "normal   local variable address: " << &y << std::endl;
    return x;
}

auto f4() {
    auto x = MyClass();
    int y = 0;
    std::cout << "returned local variable address: " << &x << std::endl;
    std::cout << "normal   local variable address: " << &y << std::endl;
    return std::move(x);
}

auto f5() {
    const auto x = MyClass();
    int y = 0;
    std::cout << "returned local variable address: " << &x << std::endl;
    std::cout << "normal   local variable address: " << &y << std::endl;
    return std::move(x);
}

void line(const char* data = "") {
    static unsigned int counter = 0;
    std::cout << std::endl << "========== Case " << ++counter << " | " << data << std::endl;
}


int main(int argc, char *argv[]) {

    ////////////////////////////////////////

    line("nothing");

    {
        MyClass x;
    }

    line("prvalue");

    {
        MyClass x = MyClass();
    }

    line("prvalue");

    {
        const MyClass x = MyClass();
    }

    line("prvalue");

    {
        auto x = MyClass();
    }

    line("prvalue");

    {
        const auto x = MyClass();
    }

    ////////////////////////////////////////

    line("lvalue");

    {
        const auto x = MyClass();
        MyClass y(x);
    }

    line("lvalue");

    {
        const auto x = MyClass();
        const MyClass y(x);
    }

    line("lvalue");

    {
        const auto x = MyClass();
        auto y(x);
    }

    line("lvalue");

    {
        const auto x = MyClass();
        const auto y(x);
    }

    line("lvalue, move const won't effect");

    {
        const auto x = MyClass();
        auto y(std::move(x));
    }

    line("lvalue, move const won't effect");

    {
        const auto x = MyClass();
        const auto y(std::move(x));
    }

    line("prvalue");

    {
        const auto y((MyClass()));
    }

    ////////////////////////////////////////

    line("lvalue");

    {
        auto x = MyClass();
        MyClass y(x);
    }

    line("lvalue");

    {
        auto x = MyClass();
        const MyClass y(x);
    }

    line("lvalue");

    {
        auto x = MyClass();
        auto y(x);
    }

    line("lvalue");

    {
        auto x = MyClass();
        const auto y(x);
    }

    line("lvalue to xvalue");

    {
        auto x = MyClass();
        auto y(std::move(x));
    }

    line("lvalue to xvalue");

    {
        auto x = MyClass();
        const auto y(std::move(x));
    }

    line("prvalue");

    {
        auto y((MyClass()));
    }

    line("lvalue to xvalue");

    {
        auto x = MyClass();
        const auto y = std::move(x);
    }

    line("lvalue");

    {
        auto x = MyClass();
        const auto y = x;
    }

    ////////////////////////////////////////

    line("lvalue");

    {
        auto x = MyClass();
        auto y = MyClass();
        x = y;
    }

    line("prvalue");

    {
        auto x = MyClass();
        x = MyClass();
    }

    line("lvalue to xvalue");

    {
        auto x = MyClass();
        auto y = MyClass();
        y = std::move(x);
    }

    ////////////////////////////////////////

    line("lvalue");

    {
        const auto x = MyClass();
        auto y = MyClass();
        y = x;
    }

    line("lvalue, move const won't effect");

    {
        const auto x = MyClass();
        auto y = MyClass();
        y = std::move(x);
    }

    ////////////////////////////////////////

    line("[RVO] return prvalue");

    {
        const auto x = f1();
    }

    line("[NRVO] return local lvalue");

    {
        const auto x = f2();
        std::cout << "caller         variable address: " << &x << std::endl;
    }

    line("[NRVO] return local const lvalue");

    {
        const auto x = f3();
        std::cout << "caller         variable address: " << &x << std::endl;
    }

    line("return move local lvalue, don't do this");

    {
        const auto x = f4();
        std::cout << "caller         variable address: " << &x << std::endl;
    }

    line("return move local const lvalue, move const won't effect, don't do this");

    {
        const auto x = f5();
        std::cout << "caller         variable address: " << &x << std::endl;
    }

    ////////////////////////////////////////

    return 0;
}


<|start_filename|>programming-language/cases/cpp/examples/vector-emplace.cpp<|end_filename|>
#include <iostream>
#include <vector>

using namespace std;

class MyClass {
public:
    constexpr MyClass(){};
    MyClass(int n);                         // default ctor
    MyClass(MyClass&);                      // copy ctor (@_@)
    MyClass(const MyClass&);                // copy ctor (const)
    MyClass(MyClass&&);                     // move ctor
    MyClass& operator=(MyClass&);           // copy assignment (@_@)
    MyClass& operator=(const MyClass&);     // copy assignment (const)
    MyClass& operator=(MyClass&&);          // move assignment
    ~MyClass();                             // dtor

    int data = 42;
    const int origin = 42;
};

MyClass::MyClass(int n) : data(n), origin(n) {
    std::cout << "[default ctor] MyClass() "
              << "[" << this << "] "
              << this->data << std::endl;
}

MyClass::MyClass(MyClass&) {
    std::cout << "[copy ctor   ] MyClass(MyClass&)" << std::endl;
}

MyClass::MyClass(const MyClass& other)
    : data(other.data), origin(other.origin) {
    std::cout << "[copy ctor c ] MyClass(const MyClass&)" << std::endl;
}

MyClass::MyClass(MyClass&&) {
    std::cout << "[move ctor   ] MyClass(MyClass&&)" << std::endl;
}

MyClass& MyClass::operator=(MyClass&) {
    std::cout << "[copy assign ] operator=(MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(const MyClass&) {
    std::cout << "[copy assign ] operator=(const MyClass&)" << std::endl;
    return *this;
}

MyClass& MyClass::operator=(MyClass&&) {
    std::cout << "[move assign ] operator=(MyClass&&)" << std::endl;
    return *this;
}

MyClass::~MyClass() {
    std::cout << "[dtor        ] ~MyClass() "
              << "[" << this << "] " << this->origin << " | " << this->data
              << std::endl;
}


////////////////////////////////////////

vector<MyClass> double_values (const vector<MyClass>& v)
{
    std::cout << "=== start double ===" << '\n';
    vector<MyClass> new_values;
    new_values.reserve(v.size());
    for (auto itr = v.begin(), end_itr = v.end(); itr != end_itr; ++itr )
    {
        new_values.emplace_back(2 * itr->data);
    }
    std::cout << "=== end double ===" << '\n';
    return new_values;
}

int main()
{
    vector<MyClass> v;
    std::cout << "=== start initial ===" << '\n';
    for ( int i = 0; i < 10; i++ )
    {
        v.emplace_back(i);  // vector will keep resizing
    }

    for (auto& i: v) {
        std::cout << i.data << " ";
    }
    std::cout << '\n';

    std::cout << "=== end initial  ===" << '\n';
    std::cout << "=== call double ===" << '\n';
    v = double_values(v);
    std::cout << "=== end ===" << '\n';
}


<|start_filename|>programming-language/cases/cpp/examples/design-pattern/abstract-factory/abstract-factory.cpp<|end_filename|>
#include <iostream>

////////////////////////////////////////

class Door {
public:
    virtual void description();
    ~Door() {}
};

class DoorFittingExpert {
public:
    virtual void description();
    ~DoorFittingExpert() {}
};

template<typename Door, typename Expert>
class DoorAbstractFactory {
public:
    Door new_door() { return Door {}; }
    Expert new_expert() { return Expert {}; }
};

////////////////////////////////////////

class WoodenDoor : public Door {
public:
    void description() override { std::cout << "A wooden door!" << '\n'; }
    ~WoodenDoor() {}
};

class IronDoor : public Door {
public:
    void description() override { std::cout << "A iron door!" << '\n'; }
    ~IronDoor() {}
};

////////////////////////////////////////

class Carpenter : public DoorFittingExpert {
public:
    void description() override { std::cout << "I can only fit wooden door!" << '\n'; }
    ~Carpenter() {}
};

class Welder : public DoorFittingExpert {
public:
    void description() override { std::cout << "I can only fit iron door!" << '\n'; }
    ~Welder() {}
};

////////////////////////////////////////

using WoodenDoorFactory = DoorAbstractFactory<WoodenDoor, Carpenter>;
using IronDoorFactory = DoorAbstractFactory<IronDoor, Welder>;


int main() {
    {
        auto factory = WoodenDoorFactory();
        auto door = factory.new_door();
        auto expert = factory.new_expert();
        door.description();
        expert.description();
    }
    {
        auto factory = IronDoorFactory();
        auto door = factory.new_door();
        auto expert = factory.new_expert();
        door.description();
        expert.description();
    }
    {
        auto factory = WoodenDoorFactory();
        auto door   = factory.new_door();
        auto expert = factory.new_expert();
        auto pdoor   = static_cast<Door*>             (&door);
        auto pexpert = static_cast<DoorFittingExpert*>(&expert);
        pdoor->description();
        pexpert->description();
    }
    {
        auto factory = IronDoorFactory();
        auto door   = factory.new_door();
        auto expert = factory.new_expert();
        auto pdoor   = static_cast<Door*>             (&door);
        auto pexpert = static_cast<DoorFittingExpert*>(&expert);
        pdoor->description();
        pexpert->description();
    }
    return 0;
}



<|start_filename|>build-system/examples/meson/10_subprojects/subprojects/proj2/src/test2.c<|end_filename|>
#include <stdio.h>
#include "proj2.h"

void func2() {
    printf("test output for func2\n");
}
