text:
//
//  Material.hpp
//  FracRndr
//
//  Created by Charles-Felix on 5/25/16.
//  Copyright © 2016 Charles-Felix. All rights reserved.
//

#ifndef Material_hpp
#define Material_hpp

#include "Ray.hpp"
#include "RenderPrimitve.hpp"
#include "Sampler.hpp"

namespace Fr {
    class Material
    {
    public:
        DEF_SHARED_PTR_TYPES(Material);

        virtual bool scatter(const Ray & r, const HitRecord & rec, C3f & attenuation, Ray & ray_scattered) = 0;
    };

    class Lambertian : public Material
    {
    public:

        Lambertian(const C3f & albedo=C3f(.5f,.5f,.5f)) : m_albedo(albedo) {}
        virtual bool scatter(const Ray & r, const HitRecord & rec, C3f & attenuation, Ray & ray_scattered);
    private:
        C3f m_albedo;
        static Sampler s_sampler;
    };

    class SimpleMetal : public Material
    {
    public:

        SimpleMetal(const C3f & albedo=C3f(.5f,.5f,.5f), float roughness=0.f):
        m_albedo(albedo), m_roughness(roughness) {}
        virtual bool scatter(const Ray & r, const HitRecord & rec, C3f & attenuation, Ray & ray_scattered);
    private:
        C3f m_albedo;
        float m_roughness;
        static Sampler s_sampler;
    };

    class Glass : public Material
    {
    public:

        Glass(float refraction_index, float roughness=0.f):
        m_refraction_index(refraction_index), m_roughness(roughness) {}
        virtual bool scatter(const Ray & r, const HitRecord & rec, C3f & attenuation, Ray & ray_scattered);
    private:
        float m_refraction_index;
        float m_roughness;
        static Sampler s_sampler;
    };

};
#endif /* Material_hpp */


text:
/*
 * ChatType.cpp
 *
 *  Created on: 2015年12月21日
 *      Author: moss
 */

#include "ChatType.h"
#include "UsrInfo.h"
#include "MyParseKey.h"
#include <khala/NodeManager.h>
//#include"DAO/UsrInfoDao.h"
ChatType::ChatType() {

}

ChatType::~ChatType() {

}
bool ChatType::onLoginCheckMsg(khala::InfoNodePtr& infoNodePtr,
		Json::Value& msg, khala::Timestamp time) {
	std::string name = msg[KEY_LOGIN_NAME].asString();
	std::string passwd = msg[KEY_PASSWD].asString();
	/*
	UsrInfoResult res = UsrInfoDao::getInstance().queryUsrInfo(name, passwd);
	if (!res.isSuccess()) {
		Json::Value res;
		res[MSG_TYPE] = LOGIN_TYPE;
		res["result"] = "false";
		res["data"] = "login failure,err account!";
		Json::FastWriter jwriter;
		std::string sendStr = jwriter.write(res);
		infoNodePtr->send(sendStr);
		return false;
	}
	UsrInfoDo usrInfoDo = res.getUsrInfoDo();
	infoNodePtr->setId(usrInfoDo.id);*/
	return true;
}
bool ChatType::onLoginSuccessMsg(khala::InfoNodePtr& infoNodePtr,
		Json::Value& msg, khala::Timestamp time) {
	std::string name = msg[KEY_LOGIN_NAME].asString();
	infoNodePtr->setExtraContext(new UsrInfo(name));
	Json::Value res;
	res[MSG_TYPE] = LOGIN_TYPE;
	res["result"] = "true";
	res["data"] = "login success!";
	res["name"] = name;
	Json::FastWriter jwriter;
	std::string sendStr = jwriter.write(res);
	infoNodePtr->send(sendStr);
	return true;
}
bool ChatType::onLoginFailureMsg(khala::InfoNodePtr& infoNodePtr,
		Json::Value& msg, khala::Timestamp time) {
	Json::Value res;
	res[MSG_TYPE] = LOGIN_TYPE;
	res["result"] = "false";
	res["data"] = "login failure,logined id!";
	Json::FastWriter jwriter;
	std::string sendStr = jwriter.write(res);
	infoNodePtr->send(sendStr);
	return true;
}
bool ChatType::onLogoutMsg(khala::InfoNodePtr& infoNodePtr, Json::Value& msg,
		khala::Timestamp time) {
	Json::Value res;
	res[MSG_TYPE] = LOGOUT_TYPE;
	res["result"] = "true";
	res["data"] = "logout success!";
	Json::FastWriter jwriter;
	std::string sendStr = jwriter.write(res);
	infoNodePtr->send(sendStr);
	return true;
}
void ChatType::releaseConnNode(khala::InfoNodePtr& infoNodePtr,
		khala::Timestamp time) {
	UsrInfo* usrInfo = boost::any_cast<UsrInfo*>(
			infoNodePtr->getExtraContext());
	if (usrInfo != 0) {
		delete usrInfo;
		usrInfo = 0;
	}
}

const std::string& ChatType::getObjectTypeName() {
	static std::string typeStr(MY_CHAT_TYPE);
	return typeStr;
}
void ChatType::setRegisterMsg(khala::RegisterHandler& handler) {
	NodeType::setRegisterMsg(handler);
	handler.setRegisterMsg(CHAT_FRIENDS,
			boost::bind(&ChatType::onCurrFriends, this, _1, _2, _3));
	handler.setRegisterMsg(CHAT_SEND,
			boost::bind(&ChatType::onSendMsg, this, _1, _2, _3));
}
bool ChatType::onCurrFriends(khala::InfoNodePtr& infoNodePtr, Json::Value& msg,
		khala::Timestamp time) {
	Json::Value res;
	res[MSG_TYPE] = CHAT_FRIENDS;
	res["result"] = "true";
	khala::NodeManager* nodeManager = getNodeManager();
	std::vector<uint> currIds = nodeManager->getNodeIDs(
			infoNodePtr->getNodeType());
	for (std::vector<uint>::iterator it = currIds.begin(); it != currIds.end();
			++it) {
		khala::InfoNodePtr usrInfoNode;
		if (nodeManager->find(*it, usrInfoNode)) {
			Json::Value usrJs;
			usrJs[KEY_ID] = *it;
			UsrInfo* usrInfo = boost::any_cast<UsrInfo*>(
					usrInfoNode->getExtraContext());
			usrJs["name"] = usrInfo->getName();
			res["data"].append(usrJs);
		}
	}
	Json::FastWriter jwriter;
	std::string sendStr = jwriter.write(res);
	infoNodePtr->send(sendStr);
	return true;
}
bool ChatType::onSendMsg(khala::InfoNodePtr& infoNodePtr, Json::Value& msg,
		khala::Timestamp time) {
	Json::FastWriter jwriter1;
	std::string sendStr1 = jwriter1.write(msg);
	Json::Value res;
	res[MSG_TYPE] = CHAT_SEND;
	uint friendId = msg[KEY_FRIEND_ID].asUInt();
	std::string sendMsg = msg[CHAT_MSG].asString();
	res[FRIEND_NAME] = msg[FRIEND_NAME].asString();
	res[CHAT_MSG] = sendMsg;
	khala::InfoNodePtr friendNodePtr;
	if (this->getNodeManager()->find(friendId, friendNodePtr)) {
		Json::Value sendJs;
		sendJs[MSG_TYPE] = CHAT_REV;
		sendJs[CHAT_MSG] = sendMsg;
		UsrInfo* usrInfo = boost::any_cast<UsrInfo*>(
				infoNodePtr->getExtraContext());
		if (usrInfo == 0) {
			return false;
		}
		sendJs[SEND_NAME] = usrInfo->getName();
		sendJs[KEY_FRIEND_ID] = infoNodePtr->getId();
		Json::FastWriter jwriter;
		std::string sendStr = jwriter.write(sendJs);
		friendNodePtr->send(sendStr);

		res["result"] = "true";
	} else {
		res["result"] = "false";
	}
	Json::FastWriter jwriter;
	std::string sendStr = jwriter.write(res);
	infoNodePtr->send(sendStr);
	return true;
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import, print_function
import sys
sys.path.insert(0, '..')
try:
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen
import argparse
import string
import itertools

UNIDATA = 'ftp://ftp.unicode.org/Public/UNIDATA/NamesList.txt'

MAX_CODE = 0x7f

PRINTABLE_SET = set(string.printable)

def format_name(name):
    if ',' in name:
        return itertools.chain(*(format_name(subname) for subname in name.split(',')))
    name = name.upper().strip()
    if '(' in name:
        name = name[:name.find('(')].strip()
    name = name.replace(' ', '_').replace('-', '_')
    if set(name).issubset(PRINTABLE_SET):
        return [name]
    else:
        return []

def print_name(name, char):
    for name in format_name(name):
        print('{} = {!r}'.format(name, char))

def parse_unicode_names(text, max_code=MAX_CODE, min_code=0):
    code = -1
    for line in text.splitlines():
        if line[0].startswith('0'):
            code, name = line.split(None, 1)
            code = int(code, 16)
            if code > max_code:
                break
            char = chr(code)
            if code >= min_code and name == name.upper():
                for name in format_name(name):
                    yield (name, char)
        elif code >= min_code and line.startswith('\t= '):
            name = line[3:].strip()
            for name in format_name(name):
                yield (name, char)

def main():
    response = urlopen(UNIDATA)
    text = response.read()
    print('class UnicodeAsciiKeys(object):')
    for name, char in parse_unicode_names(text):
        print('    {} = {!r}'.format(name, char))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=
        '''Parse unicode names & write as `UnicodeAsciiKeys` class.'''
    )
    parser.parse_args()
    main()


text:
module StarsRenderer

  def render_stars(rating)
    p 'ratinggg ==========> ', rating
    do_render_stars(rating, self)
  end

private
  def do_render_stars(rating,template)
    @template = template
    content_tag :div, "&nbsp", :class => "stars rating_#{round_rating(rating).to_s.gsub(".", "_")}"
  end

  def method_missing(*args, &block)
    @template.send(*args, &block)
  end

  def round_rating(rating)
    (rating * 2.0).round / 2.0
  end

end
ActionView::Base.send(:include,StarsRenderer)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="?android:attr/toastFrameBackground">

    <TextView
        android:id="@android:id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:textAppearance="@style/TextAppearance.Toast"
        android:textColor="@color/bright_foreground_dark"
        android:shadowColor="#BB000000"
        android:shadowRadius="2.75"
        />

</LinearLayout>


text:
#pragma once
#include <aws/medialive/MediaLive_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace MediaLive
{
namespace Model
{
  enum class Eac3PhaseControl
  {
    NOT_SET,
    NO_SHIFT,
    SHIFT_90_DEGREES
  };

namespace Eac3PhaseControlMapper
{
AWS_MEDIALIVE_API Eac3PhaseControl GetEac3PhaseControlForName(const Aws::String& name);

AWS_MEDIALIVE_API Aws::String GetNameForEac3PhaseControl(Eac3PhaseControl value);
} // namespace Eac3PhaseControlMapper
} // namespace Model
} // namespace MediaLive
} // namespace Aws


text:
require 'rails_helper'

describe 'inviting accepted submissions', :include_background_job_helpers, type: :feature do
  let(:setting) { FactoryBot.build(:setting, available_spots: 2) }
  let!(:user) { FactoryBot.create(:user) }
  let(:confirmation_days) { Setting.get.days_to_confirm_invitation.days }

  before do
    ActionMailer::Base.deliveries.clear
    allow(Setting).to receive(:get).and_return(setting)
  end

  describe 'sending invitation emails' do
    let!(:accepted_submission) do
      FactoryBot.create(
        :submission,
        :with_rates,
        invitation_token: nil,
        rates_num: setting.required_rates_num,
        rates_val: 1
      )
    end

    let!(:rejected_submission) do
      FactoryBot.create(
        :submission,
        rejected: true
      )
    end

    it 'sends only one invitation email to each accepted submission and one bad news email to each ' \
      "submission which didn't get accepted" do
      allow(Setting).to receive(:registration_period?).and_return(false)

      login_as(user, scope: :user)
      visit submissions_results_path
      click_link('Send')

      execute_background_jobs

      expect(ActionMailer::Base.deliveries.count).to eq(2)
      expect(setting.invitation_process_started).to be true
      expect(accepted_submission.reload.invitation_token).not_to be_nil
      expect(rejected_submission.reload.bad_news_sent_at).not_to be_nil
    end

    it "doesn't send invitation emails if the registration open" do
      allow(Setting).to receive(:registration_period?).and_return(true)

      login_as(user, scope: :user)
      visit submissions_results_path
      click_link('Send')

      execute_background_jobs

      expect(ActionMailer::Base.deliveries.count).to eq(0)
      expect(accepted_submission.reload.invitation_token).to be_nil
    end

    it 'does not send any emails after clicking the button for the second time' do
      allow(Setting).to receive(:registration_period?).and_return(false)

      login_as(user, scope: :user)
      visit submissions_results_path
      click_link('Send')

      execute_background_jobs

      expect {
        visit submissions_results_path
        click_link('Send')
        execute_background_jobs
      }.not_to(change { ActionMailer::Base.deliveries.count })
    end
  end

  describe 'confirming invitations' do
    it 'confirms submission' do
      invited_submission = FactoryBot.create(
        :submission,
        :with_rates,
        invitation_token: 'xxx',
        invitation_token_created_at: Time.zone.now,
        invitation_confirmed: false,
        rates_num: setting.required_rates_num,
        rates_val: 1
      )

      visit submissions_confirm_invitation_path(invitation_token: invited_submission.invitation_token)
      expect(invited_submission.reload.invitation_confirmed).to be true
      expect(page).to have_text('confirmed')
    end

    it "doesn't confirm submission with expired invitation token" do
      invited_submission = FactoryBot.create(
        :submission,
        :with_rates,
        invitation_token: 'zzz',
        invitation_token_created_at: confirmation_days.ago - 1,
        invitation_confirmed: false,
        rates_num: setting.required_rates_num,
        rates_val: 1
      )

      visit submissions_confirm_invitation_path(invitation_token: invited_submission.invitation_token)
      expect(invited_submission.reload.invitation_confirmed).to be false
      expect(page).to have_text('expired')
    end

    it 'show correct info when invitation is already confirmed but token expired' do
      confirmed_submission = FactoryBot.create(
        :submission,
        :with_rates,
        invitation_token: 'yyy',
        invitation_token_created_at: confirmation_days.ago - 1,
        invitation_confirmed: true,
        rates_num: setting.required_rates_num,
        rates_val: 1
      )

      visit submissions_confirm_invitation_path(invitation_token: confirmed_submission.invitation_token)
      expect(page).to have_text('confirmed')
    end
  end

  describe 'handling exceptions' do
    it 'missing invitation token' do
      visit submissions_confirm_invitation_path
      expect(page).to have_text('Something went wrong')
    end

    it 'submission not found' do
      visit submissions_confirm_invitation_path('uuu')
      expect(page).to have_text('Something went wrong')
    end
  end

  context 'when the accepted list is empty' do
    it "makes `Send` link inactive" do
      login_as(user, scope: :user)
      visit submissions_results_path
      expect(page).not_to have_selector('a', text: 'Send')
    end
  end
end


text:
package macro
import scala.language.experimental.macros
import scala.reflect.macros._

object Provider {
	def tree(args: Any) = macro treeImpl
	def treeImpl(c: Context)(args: c.Expr[Any]) = c.universe.reify(args.splice)
}


text:
Golang RESTful Client for HanLP

We have moved to https://github.com/hankcs/gohanlp


text:
/*can@2.2.5#compute/compute*/
/* jshint maxdepth:7*/

// # can.compute
//
// `can.compute` allows creation of observable values
// from the result of a funciton. Any time an observable
// value that the function depends on changes, the
// function automatically updates. This enables creating
// observable data that relies on other sources, potentially
// multiple different ones. For instance, a `can.compute` is
// able to:
// - Combine a first and last name into a full name and update when either changes
// - Calculate the absolute value of an observable number, updating any time the observable number does
// - Specify complicated behavior for getting and setting a value, as well as how to handle changes

steal('can/util', 'can/util/bind', 'can/util/batch', 'can/compute/proto_compute.js', function (can, bind) {

	// ## Reading Helpers
	//
	// The following methods are used to call a function that relies on
	// observable data and to track the observable events which should
	// be listened to when changes occur.
	// To do this, [`can.__reading(observable, event)`](#can-__reading) is called to
	// "broadcast" the corresponding event on each read.
	//
	// ### Observed
	//
	// An "Observed" is an object of observable objects and events that
	// a function relies on. These objects and events must be listened to
	// in order to determine when to check a function for updates.
	// This looks like the following:
	//
	//     {
	//       "map1|first": {obj: map, event: "first"},
	//       "map1|last" : {obj: map, event: "last"}
	//     }
	//
	// Each object-event pair is mapped so no duplicates will be listed.

	can.compute = function (getterSetter, context, eventName, bindOnce) {

		var internalCompute = new can.Compute(getterSetter, context, eventName, bindOnce);

		var compute = function(val) {
			if(arguments.length) {
				return internalCompute.set(val);
			}

			return internalCompute.get();
		};

		compute.bind = can.proxy(internalCompute.bind, internalCompute);
		compute.unbind = can.proxy(internalCompute.unbind, internalCompute);
		compute.isComputed = internalCompute.isComputed;
		compute.clone = function(ctx) {
			if(typeof getterSetter === 'function') {
				context = ctx;
			}

			return can.compute(getterSetter, context, ctx, bindOnce);
		};

		compute.computeInstance = internalCompute;

		return compute;
	};
	// Instead of calculating whether anything is listening every time,
	// use a function to do nothing (which may be overwritten)
	var k = function () {};
	// A list of temporarily bound computes
	var computes, unbindComputes = function () {
			for (var i = 0, len = computes.length; i < len; i++) {
				computes[i].unbind('change', k);
			}
			computes = null;
		};
	// Binds computes for a moment to retain their value and prevent caching
	can.compute.temporarilyBind = function (compute) {
		compute.bind('change', k);
		if (!computes) {
			computes = [];
			setTimeout(unbindComputes, 10);
		}
		computes.push(compute);
	};

	// Whether a compute is truthy
	can.compute.truthy = function (compute) {
		return can.compute(function () {
			var res = compute();
			if (typeof res === 'function') {
				res = res();
			}
			return !!res;
		});
	};
	can.compute.async = function(initialValue, asyncComputer, context){
		return can.compute(initialValue, {
			fn: asyncComputer,
			context: context
		});
	};

	can.compute.read = can.Compute.read;

	can.compute.set = can.Compute.set;

	return can.compute;
});


text: {{pageNotFoundText}}


text:
package com.phloc.commons.idfactory;

import javax.annotation.Nonnull;

import com.phloc.commons.hash.HashCodeGenerator;
import com.phloc.commons.string.ToStringGenerator;

/**
 * An {@link IStringIDFactory} implementation that uses a constant prefix and a
 * long supplied from {@link GlobalIDFactory#getNewPersistentLongID()} to create
 * unique IDs.
 *
 * @author Philip Helger
 */
public final class StringIDFromGlobalPersistentLongIDFactory implements IStringIDFactory
{
  private final String m_sPrefix;

  public StringIDFromGlobalPersistentLongIDFactory ()
  {
    this (GlobalIDFactory.DEFAULT_PREFIX);
  }

  public StringIDFromGlobalPersistentLongIDFactory (@Nonnull final String sPrefix)
  {
    if (sPrefix == null)
      throw new NullPointerException ("prefix");
    m_sPrefix = sPrefix;
  }

  @Nonnull
  public String getPrefix ()
  {
    return m_sPrefix;
  }

  @Nonnull
  public String getNewID ()
  {
    return m_sPrefix + Long.toString (GlobalIDFactory.getNewPersistentLongID ());
  }

  @Override
  public boolean equals (final Object o)
  {
    if (o == this)
      return true;
    if (!(o instanceof StringIDFromGlobalPersistentLongIDFactory))
      return false;
    final StringIDFromGlobalPersistentLongIDFactory rhs = (StringIDFromGlobalPersistentLongIDFactory) o;
    return m_sPrefix.equals (rhs.m_sPrefix);
  }

  @Override
  public int hashCode ()
  {
    return new HashCodeGenerator (this).append (m_sPrefix).getHashCode ();
  }

  @Override
  public String toString ()
  {
    return new ToStringGenerator (this).append ("prefix", m_sPrefix).toString ();
  }
}


text:
import logging
import sys

from setuptools import find_packages
from setuptools import setup

logging.basicConfig()

VERSION = '0.1.0'
DESCRIPTION = 'Session level dynamic decorators for django.'

def runtests():
    """Run django tests."""
    import django
    from django.conf import settings
    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            },
        },
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.messages',
            'dynamicdecorators',
        ),
        MIDDLEWARE=(
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.common.CommonMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
            'dynamicdecorators.middleware.dynamicdecorators_middleware',
        ),
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [],
                'APP_DIRS': True,
                'OPTIONS': {
                    'context_processors': [
                        'django.template.context_processors.debug',
                        'django.template.context_processors.request',
                        'django.contrib.auth.context_processors.auth',
                        'django.contrib.messages.context_processors.messages',
                    ],
                },
            },
        ],

        ROOT_URLCONF='dynamicdecorators.urls',
        DYNAMIC_DECORATORS=(),
    )
    if hasattr(django, 'setup'):
        # django >= 1.7
        django.setup()
    # This need to be imported after the settings has been configured
    try:
        from django.test.runner import DiscoverRunner
    except ImportError:
        # Django < 1.8
        from django.test.simple import DjangoTestSuiteRunner as DiscoverRunner

    test_runner = DiscoverRunner(verbosity=1, interactive=False)
    failures = test_runner.run_tests([])
    sys.exit(failures)

setup(
    name='django-dynamic-decorators',
    version=VERSION,
    description=DESCRIPTION,
    url='https://github.com/huseyinyilmaz/django-dynamic-decorators',
    author='Huseyin Yilmaz',
    author_email='yilmazhuseyin@gmail.com',
    packages=find_packages(),
    py_modules=['dynamicdecorators'],
    include_package_data=True,
    zip_safe=False,
    test_suite='setup.runtests',
    tests_require=[
        'Django>=1.8.0',
        'six',
    ]
)


text: export const helper = { testNumber: 1 };


text:
namespace Connect4
{
    ///
    /// Represents a piece which has been placed on a <see cref="Board"/>
    ///
    public enum Checker {
        /// Represents an empty space
        None,
        /// Represents a black piece. Black has first move.
        Black,
        /// Represents a red piece. Red moves second.
        Red
    }

    ///
    /// Represents the current state of a <see cref="Game"/>
    ///
    public enum GameState {
        /// The game is currently being played
        InProgress,
        ///
        BlackWins,
        ///
        RedWins,
        ///
        Tie
    }
}


text:
/**
 * Created by huangjian on 2017/4/21.
 */
import React from 'react'
import { Row, Col } from 'antd'
import {
  SimpleLineChart,
  BarChart,
  RadialBarChart,
  RadarChart
} from 'components/Recharts'
import CustomCard from 'components/CustomCard'

class ChartsGallery extends React.Component {
  render () {
    return (

        <Row gutter={16}>
          <Col className='gutter-row' md={24}>

              <CustomCard title='基础线形图'>
                <SimpleLineChart />
              </CustomCard>

          </Col>
        </Row>
        <Row gutter={16}>
          <Col className='gutter-row' md={24}>

              <CustomCard title='基础线形图'>
                <BarChart />
              </CustomCard>

          </Col>
        </Row>
        <Row gutter={16}>
          <Col className='gutter-row' md={12}>

              <CustomCard title='基础线形图'>
                <RadialBarChart />
              </CustomCard>

          </Col>
          <Col className='gutter-row' md={12}>

              <CustomCard title='基础线形图'>
                <RadarChart />
              </CustomCard>

          </Col>
        </Row>

    )
  }
}

export default ChartsGallery


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Haplosporidium ecdyonuri Weiser

### Remarks
null


text:
package com.xjeffrose.xio.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

public class IdleDisconnectHandler extends IdleStateHandler {
  public IdleDisconnectHandler(
      int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
    super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
  }

  @Override
  protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
    //    ctx.channel().close();
    ctx.fireUserEventTriggered(evt);
  }
}


text:
<?php

use webvimark\modules\UserManagement\UserManagementModule;

/**
 * @var yii\web\View $this
 * @var webvimark\modules\UserManagement\models\User $model
 */

$this->title = UserManagementModule::t('back', 'User creation');
$this->params['breadcrumbs'][] = ['label' => UserManagementModule::t('back', 'Users'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= $this->title ?>

                                        <?= $this->render('_form', compact('model')) ?>


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Underscore.js: Chaining</title>
	<script src="../scripts/underscore.js"></script>
</head>
<body>
	<script src="chaining.js">
	</script>
</body>
</html>


text: require "rack/json_schema"


text:
<?php

/*
 * This file is part of the Active Collab Insight.
 *
 * (c) A51 doo <info@activecollab.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace ActiveCollab\Insight\Metric;

use ActiveCollab\DateValue\DateValue;
use ActiveCollab\DateValue\DateValueInterface;

/**
 * @package ActiveCollab\Insight\Metric
 */
class Arpu extends Metric implements ArpuInterface
{
    /**
     * {@inheritdoc}
     */
    public function getOnDay(DateValueInterface $day = null): int
    {
        if (empty($day)) {
            $day = new DateValue();
        }

        if ($paid_account = $this->insight->accounts->countPaid($day)) {
            return ceil($this->insight->mrr->getOnDay($day) / $paid_account);
        }

        return 0;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<view class="org.ql.app.alert.AlertController$RecycleListView"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/select_dialog_listview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="5dip"
    android:paddingTop="5dip"
    android:cacheColorHint="@null"
    android:background="@null"
    android:divider="@drawable/ql_alert_dialog_divider"
    android:listSelector="@drawable/ql_alert_listview_selected"
    android:scrollbars="vertical" />


text:
cask "facebook-ios-sdk" do
  version "4.34.0"
  sha256 "508cd08b77ba9d1593a4831957be670631686ff877db035fe4e138c4673ccefd"

  url "https://origincache.facebook.com/developers/resources/?id=FacebookSDKs-iOS-#{version}.zip"
  name "Facebook SDK for iOS"
  homepage "https://developers.facebook.com/docs/ios"

  artifact "AccountKit.framework", target: "#{ENV["HOME"]}/Documents/FacebookSDK/AccountKit.framework"
  artifact "AccountKitStrings.bundle", target: "#{ENV["HOME"]}/Documents/FacebookSDK/AccountKitStrings.bundle"
  artifact "Bolts.framework", target: "#{ENV["HOME"]}/Documents/FacebookSDK/Bolts.framework"
  artifact "DocSets", target: "#{ENV["HOME"]}/Documents/FacebookSDK/DocSets"
  artifact "FacebookSDKStrings.bundle", target: "#{ENV["HOME"]}/Documents/FacebookSDK/FacebookSDKStrings.bundle"
  artifact "FBNotifications.framework", target: "#{ENV["HOME"]}/Documents/FacebookSDK/FBNotifications.framework"
  artifact "FBSDKCoreKit.framework", target: "#{ENV["HOME"]}/Documents/FacebookSDK/FBSDKCoreKit.framework"
  artifact "FBSDKLoginKit.framework", target: "#{ENV["HOME"]}/Documents/FacebookSDK/FBSDKLoginKit.framework"
  artifact "FBSDKMessengerShareKit.framework",
           target: "#{ENV["HOME"]}/Documents/FacebookSDK/FBSDKMessengerShareKit.framework"
  artifact "FBSDKPlacesKit.framework", target: "#{ENV["HOME"]}/Documents/FacebookSDK/FBSDKPlacesKit.framework"
  artifact "FBSDKShareKit.framework", target: "#{ENV["HOME"]}/Documents/FacebookSDK/FBSDKShareKit.framework"
  artifact "Samples", target: "#{ENV["HOME"]}/Documents/FacebookSDK/Samples"

  preflight do
    system_command "/bin/mkdir", args: ["-p", "--", "#{ENV["HOME"]}/Documents/FacebookSDK"]
  end
end


text:
module Azure::DataMigration::Mgmt::V2018_07_15_preview
  module Models
    #
    # Defines values for ProjectSourcePlatform
    #
    module ProjectSourcePlatform
      SQL = "SQL"
      MySQL = "MySQL"
      PostgreSql = "PostgreSql"
      MongoDb = "MongoDb"
      Unknown = "Unknown"
    end
  end
end


text:
<title>Demons & Wizards : Touched by the Crimson King (2005) - críticas y revisiones de heavy metal en PandemoniuM</title>
<meta content="Rubén Béjar" http-equiv="content-owner">
<link href="../../common/pstyle.css" type="text/css" rel="stylesheet">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Demons & Wizards : Touched by the Crimson King (2005)

Rubén Béjar

http://www.demons-wizards.com

1. Crimson King   5:47

2. Beneath These Waves   5:12

3. Terror Train   4:46

4. Seize the Day   5:22

5. The Gunslinger   5:15

6. Love's Tragedy Asunder   5:28

7. Wicked Witch   3:32

8. Dorian   6:36

9. Down Where I Am   4:54

10. Immigrant Song (Led Zeppelin Cover)   2:28

7.4/10

De nuevo juntos, Hansi Kürsch, cantante de Blind Guardian y Jon Schaffer, guitarrista
y líder de Iced Earth, colaboran en el último lanzamiento de su proyecto Demons & Wizards,
titulado "Touched by the Crimson King". Con referencias literarias, como el Crimson King
de la serie de la torre oscura de Stephen King o al retrato de Dorian Grey de Oscar Wilde,
éste se puede definir como un disco conceptual de temática bastante oscura.

El disco empieza como se puede esperar: uno de los característicos riffs rápidos y fuertemente
muteados de la guitarra de Schaffer, y un coro más del estilo de Blind Guardian, delinean
"Crimson King" entre la velocidad, la fuerza, la épica y la melodía, que son la suma de
lo mejor de ambos protagonistas. "Beneath these waves" mantiene la fuerza, aunque reduce
el tempo, y destaca la melodía en el estribillo. El doble bombo rescata la contundencia
en "Terror train", tema más lúgubre que los primeros, con algunos coros pero menos melódico
que los anteriores. A partir de aquí el disco pierde mucho y apenas ofrece algunos elementos
de interés: "Seize the day" es un tema lento, previsible y carente de fuerza o emoción.
"The gunslinger" arranca despacio, en acústico, pero pronto explota gracias al doble bombo,
a la fuerte distorsión de la guitarra de Schaffer, y a un estribillo que podría haber
firmado Blind Guardian en su último disco. "Love's tragedy asunder" es una balada, en un
estilo que D&W ya explotaron en su primer disco, con partes acústica y otras distorsionadas
alternadas, donde la melodía se fundamenta en la voz de Hansi Kürsch.
"Wicked witch" es otra balada, completamente acústica, melódica y con bastantes coros, pero
sin brillo. "Dorian" recupera la distorsión, pero sobre un riff repetitivo y poco original que no conduce
adecuadamente al estribillo, que además no está bien resuelto. La segunda parte de la canción,
lenta y monótona, tampoco logra mantener el interés del oyente al no dar la sensación de
que la canción lleva a alguna parte. "Down where I am" es otra balada más, de nuevo con parte
acústica y distorsionada, un poco más interesante que las anteriores, pero que al sumarse a éstas,
hace demasiados minutos acústicos en  un disco que debería ser de heavy metal.
El disco lo termina una versión de un tema de Led Zeppelin, "Inmigrant Song", llamativo y bien
realizado.

Aunque siempre es difícil hacer una crítica negativa a dos personajes tan conocidos y con
tantos discos buenos en su haber como Hansi Kürsch y Jon Schaffer, este disco es peor que el
anterior, y no mejora los defectos de éste: las progresiones de acordes y
las melodías siguen siendo previsibles, la guitarra es contundente pero poco original, y además
añade pegas nuevas, como la gran cantidad de minutos lentos del disco: éste se desequilibra y
acaba por resultar aburrido a tramos. Si además resulta que este disco no tiene ningún tema
realmente muy bueno (en el anterior había dos canciones fantásticas) la conclusión no puede
ser demasiado buena: una oportunidad desperdiciada para dos grandes nombres del metal que deberían
ser capaces de hacer algo mucho más grande.

- Crítica escrita por Rubén Béjar -


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit978d3a68f46c83dfef3f9e0a3f52f347::getLoader();


text:
<title>Frames - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Stack.html#Stack" title="Stack">
<link rel="next" href="Backtrace.html#Backtrace" title="Backtrace">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

<link rel="stylesheet" type="text/css" href="../cs.css">

Next: Backtrace,
Up: Stack

8.1 Stack Frames

The call stack is divided up into contiguous pieces called <dfn>stack
frames</dfn>, or <dfn>frames</dfn> for short; each frame is the data associated
with one call to one function.  The frame contains the arguments given
to the function, the function's local variables, and the address at
which the function is executing.

When your program is started, the stack has only one frame, that of the
function main.  This is called the <dfn>initial</dfn> frame or the
<dfn>outermost</dfn> frame.  Each time a function is called, a new frame is
made.  Each time a function returns, the frame for that function invocation
is eliminated.  If a function is recursive, there can be many frames for
the same function.  The frame for the function in which execution is
actually occurring is called the <dfn>innermost</dfn> frame.  This is the most
recently created of all the stack frames that still exist.

Inside your program, stack frames are identified by their addresses.  A
stack frame consists of many bytes, each of which has its own address; each
kind of computer has a convention for choosing one byte whose
address serves as the address of the frame.  Usually this address is kept
in a register called the <dfn>frame pointer register</dfn>
(see $fp) while execution is going on in that frame.

gdb assigns numbers to all existing stack frames, starting with
zero for the innermost frame, one for the frame that called it,
and so on upward.  These numbers do not really exist in your program;
they are assigned by gdb to give you a way of designating stack
frames in gdb commands.

Some compilers provide a way to compile functions so that they operate
without stack frames.  (For example, the gcc option

     ‘<samp>-fomit-frame-pointer</samp>’

generates functions without a frame.)
This is occasionally done with heavily used library functions to save
the frame setup time.  gdb has limited facilities for dealing
with these function invocations.  If the innermost function invocation
has no stack frame, gdb nevertheless regards it as though
it had a separate frame, which is numbered zero as usual, allowing
correct tracing of the function call chain.  However, gdb has
no provision for frameless functions elsewhere in the stack.

frame <var>args</var>
The frame command allows you to move from one stack frame to another,
and to print the stack frame you select.  <var>args</var> may be either the
address of the frame or the stack frame number.  Without an argument,
frame prints the current stack frame.

select-frame
The select-frame command allows you to move from one stack frame
to another without printing the frame.  This is the silent version of
frame.


text:
require 'dustbag'

Dir[File.join(File.dirname(__FILE__), 'shared_examples/**/*.rb')].each { |file| require file }

require "codeclimate-test-reporter"
CodeClimate::TestReporter.start

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
     expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end


text:
package net.digitalid.utility.property.map;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import net.digitalid.utility.annotations.generics.Unspecifiable;
import net.digitalid.utility.annotations.method.CallSuper;
import net.digitalid.utility.annotations.method.Impure;
import net.digitalid.utility.annotations.method.Pure;
import net.digitalid.utility.annotations.ownership.Capturable;
import net.digitalid.utility.annotations.ownership.Captured;
import net.digitalid.utility.annotations.ownership.NonCapturable;
import net.digitalid.utility.annotations.ownership.NonCaptured;
import net.digitalid.utility.annotations.parameter.Unmodified;
import net.digitalid.utility.annotations.type.ThreadSafe;
import net.digitalid.utility.collections.map.FreezableMap;
import net.digitalid.utility.collections.map.ReadOnlyMap;
import net.digitalid.utility.contracts.Validate;
import net.digitalid.utility.freezable.annotations.NonFrozen;
import net.digitalid.utility.generator.annotations.generators.GenerateBuilder;
import net.digitalid.utility.generator.annotations.generators.GenerateSubclass;
import net.digitalid.utility.validation.annotations.lock.LockNotHeldByCurrentThread;
import net.digitalid.utility.validation.annotations.type.Mutable;
import net.digitalid.utility.validation.annotations.value.Valid;

/**
 * This writable property stores a map of key-value pairs in volatile memory.
 *
 * Important: Make sure that {@code FREEZABLE_MAP} is a sub-type of {@code READONLY_MAP}!
 * Unfortunately, this cannot be enforced with the limited Java generics.
 *
 * @invariant !get().keySet().containsNull() : "None of the keys may be null.";
 * @invariant !get().values().containsNull() : "None of the values may be null.";
 * @invariant get().keySet().matchAll(getKeyValidator()) : "Each key has to be valid.";
 * @invariant get().values().matchAll(getValueValidator()) : "Each value has to be valid.";
 */
@ThreadSafe
@GenerateBuilder
@GenerateSubclass
@Mutable(ReadOnlyVolatileMapProperty.class)
public abstract class WritableVolatileMapProperty<@Unspecifiable KEY, @Unspecifiable VALUE, @Unspecifiable READONLY_MAP extends ReadOnlyMap<@Nonnull @Valid("key") KEY, @Nonnull @Valid VALUE>, @Unspecifiable FREEZABLE_MAP extends FreezableMap<@Nonnull @Valid("key") KEY, @Nonnull @Valid VALUE>> extends WritableMapPropertyImplementation<KEY, VALUE, READONLY_MAP, RuntimeException, RuntimeException, VolatileMapObserver<KEY, VALUE, READONLY_MAP>, ReadOnlyVolatileMapProperty<KEY, VALUE, READONLY_MAP>> implements ReadOnlyVolatileMapProperty<KEY, VALUE, READONLY_MAP> {

    /* -------------------------------------------------- Map -------------------------------------------------- */

    @Pure
    protected abstract @Nonnull @NonFrozen FREEZABLE_MAP getMap();

    @Pure
    @Override
    @SuppressWarnings("unchecked")
    public @Nonnull @NonFrozen READONLY_MAP get() {
        return (READONLY_MAP) getMap();
    }

    /* -------------------------------------------------- Getter -------------------------------------------------- */

    @Pure
    @Override
    public @NonCapturable @Nullable @Valid VALUE get(@NonCaptured @Unmodified @Nonnull @Valid("key") KEY key) {
        return getMap().get(key);
    }

    /* -------------------------------------------------- Operations -------------------------------------------------- */

    @Impure
    @Override
    @LockNotHeldByCurrentThread
    public boolean add(@Captured @Nonnull @Valid("key") KEY key, @Captured @Nonnull @Valid VALUE value) {
        lock.lock();
        try {
            if (getMap().containsKey(key)) {
                return false;
            } else {
                getMap().put(key, value);
                notifyObservers(key, value, true);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

    @Impure
    @Override
    @LockNotHeldByCurrentThread
    public @Capturable @Nullable @Valid VALUE remove(@NonCaptured @Unmodified @Nonnull @Valid("key") KEY key) {
        lock.lock();
        try {
            final @Nullable VALUE value = getMap().remove(key);
            if (value != null) { notifyObservers(key, value, false); }
            return value;
        } finally {
            lock.unlock();
        }
    }

    /* -------------------------------------------------- Validate -------------------------------------------------- */

    @Pure
    @Override
    @CallSuper
    public void validate() {
        super.validate();
        Validate.that(!get().keySet().containsNull()).orThrow("None of the keys may be null.");
        Validate.that(!get().values().containsNull()).orThrow("None of the values may be null.");
        Validate.that(get().keySet().matchAll(getKeyValidator())).orThrow("Each key has to be valid.");
        Validate.that(get().values().matchAll(getValueValidator())).orThrow("Each value has to be valid.");
    }

}


text:
/**
 * jQuery.spModal - A Modal Window System.
 *
 * This plugin requires:
 *      1. jQuery >= 2.1.3
 *      2. jQuery.ui >= 1.11.4
 *
 * @author  Gonzalo Chumillas <gchumillas@email.com>
 * @license https://github.com/soloproyectos/jquery.modal/blob/master/LICENSE MIT License
 * @link    https://github.com/soloproyectos/jquery.modal
 */
(function ($) {
    /**
     * Sends a POST request.
     *
     * This function uses internally the $.post function and accepts the same parameters. More info:
     * https://api.jquery.com/jquery.post/
     *
     * Example:
     * ```JavaScript
     * var req = new $.spModalRequestPostClass('test.php');
     * var obj = req.send();
     * obj.always(function () {
     *     console.log('This function is always executed, even when the request fails.');
     * }).done(function () {
     *     console.log('This function is executed on success requests.');
     * }).fail(function () {
     *     console.log('This function is executed on failed requests.');
     * });
     * ```
     *
     * @param {String} url    URL
     * @param {Object} data   Parameters (not required)
     * @param {String} type   Expected document type (not required)
     *
     * @extends {$.spModalRequestClass}
     */
    $.spModalRequestPostClass = function (url, data, type) {
        // calls the parent constructor
        $.spModalRequestClass.call(this, 'post', url, data, type);
    };
    $.spModalRequestPostClass.prototype = Object.create($.spModalRequestClass.prototype);
})(jQuery);


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//*********************************************************

using System;
using Windows.UI;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;

namespace MaterialCreator
{
    public class ColorToSolidColorBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is Color color)
            {
                return new SolidColorBrush(color);
            }

            return new SolidColorBrush();
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}


text:
<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook V4.4//EN"
 "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"
[
     <!ENTITY % local SYSTEM "local.ent">
     %local;
     <!ENTITY % entities SYSTEM "entities.ent">
     %entities;
     <!ENTITY % idcommon SYSTEM "common/common.ent">
     %idcommon;
]>
<refentry id="bib1">
 <refentryinfo>
  <productname>YAZ</productname>
  <productnumber>&version;</productnumber>
  <orgname>Index Data</orgname>
 </refentryinfo>

 <refmeta>
  <refentrytitle>Bib-1 Attribute Set</refentrytitle>
  <manvolnum>7</manvolnum>
  <refmiscinfo class="manual">Conventions and miscellaneous</refmiscinfo>
 </refmeta>

 <refnamediv>
  <refname>bib1-attr</refname>
  <refpurpose>Bib-1 Attribute Set</refpurpose>
 </refnamediv>

 <refsect1><title>DESCRIPTION</title>
  <para>
   This reference entry lists the Bib-1 attribute set types and values.
  </para>
 </refsect1>

 <refsect1><title>TYPES</title>
  <para>
   The Bib-1 attribute set defines six attribute types: Use (1), Relation (2),
   Position (3), Structure (4), Truncation (5) and Completeness (6).
  </para>
 </refsect1>

 <refsect1><title>USE (1)</title>
  <para>
   <screen>
    1     Personal-name
    2     Corporate-name
    3     Conference-name
    4     Title
    5     Title-series
    6     Title-uniform
    7     ISBN
    8     ISSN
    9     LC-card-number
    10    BNB-card-number
    11    BGF-number
    12    Local-number
    13    Dewey-classification
    14    UDC-classification
    15    Bliss-classification
    16    LC-call-number
    17    NLM-call-number
    18    NAL-call-number
    19    MOS-call-number
    20    Local-classification
    21    Subject-heading
    22    Subject-Rameau
    23    BDI-index-subject
    24    INSPEC-subject
    25    MESH-subject
    26    PA-subject
    27    LC-subject-heading
    28    RVM-subject-heading
    29    Local-subject-index
    30    Date
    31    Date-of-publication
    32    Date-of-acquisition
    33    Title-key
    34    Title-collective
    35    Title-parallel
    36    Title-cover
    37    Title-added-title-page
    38    Title-caption
    39    Title-running
    40    Title-spine
    41    Title-other-variant
    42    Title-former
    43    Title-abbreviated
    44    Title-expanded
    45    Subject-precis
    46    Subject-rswk
    47    Subject-subdivision
    48    Number-natl-biblio
    49    Number-legal-deposit
    50    Number-govt-pub
    51    Number-music-publisher
    52    Number-db
    53    Number-local-call
    54    Code-language
    55    Code-geographic
    56    Code-institution
    57    Name-and-title
    58    Name-geographic
    59    Place-publication
    60    CODEN
    61    Microform-generation
    62    Abstract
    63    Note
    1000  Author-title
    1001  Record-type
    1002  Name
    1003  Author
    1004  Author-name-personal
    1005  Author-name-corporate
    1006  Author-name-conference
    1007  Identifier-standard
    1008  Subject-LC-childrens
    1009  Subject-name-personal
    1010  Body-of-text
    1011  Date/time-added-to-db
    1012  Date/time-last-modified
    1013  Authority/format-id
    1014  Concept-text
    1015  Concept-reference
    1016  Any
    1017  Server-choice
    1018  Publisher
    1019  Record-source
    1020  Editor
    1021  Bib-level
    1022  Geographic-class
    1023  Indexed-by
    1024  Map-scale
    1025  Music-key
    1026  Related-periodical
    1027  Report-number
    1028  Stock-number
    1030  Thematic-number
    1031  Material-type
    1032  Doc-id
    1033  Host-item
    1034  Content-type
    1035  Anywhere
    1036  Author-Title-Subject
   </screen>
  </para>
 </refsect1>

 <refsect1><title>RELATION (2)</title>
  <para>
   <screen>
    1 Less than
    2 Less than or equal
    3 Equal
    4 Greater or equal
    5 Greater than
    6 Not equal
    100 Phonetic
    101 Stem
    102 Relevance
    103 AlwaysMatches
   </screen>
  </para>
 </refsect1>

 <refsect1><title>POSITION (3)</title>
  <para>
   <screen>
    1 First in field
    2 First in subfield
    3 Any position in field
   </screen>
  </para>
 </refsect1>

 <refsect1><title>STRUCTURE (4)</title>
  <para>
   <screen>
    1 Phrase
    2 Word
    3 Key
    4 Year
    5 Date (normalized)
    6 Word list
    100 Date (un-normalized)
    101 Name (normalized)
    102 Name (un-normalized)
    103 Structure
    104 Urx
    105 Free-form-text
    106 Document-text
    107 Local-number
    108 String
    109 Numeric-string
   </screen>
  </para>
 </refsect1>

 <refsect1><title>TRUNCATION (5)</title>
  <para>
   <screen>
    1 Right truncation
    2 Left truncation
    3 Left and right truncation
    100 Do not truncate
    101 Process # in search term  . regular #=.*
    102 RegExpr-1
    103 RegExpr-2
    104 Process # ?n . regular: #=., ?n=.{0,n} or ?=.* Z39.58
   </screen>
   </para>
  <para>
    Thw 105-106 truncation attributes below are only supported by
    Index Data's Zebra server.
    <screen>
    105 Process * ! regular: *=.*, !=. and right truncate
    106 Process * ! regular: *=.*, !=.
   </screen>
  </para>
 </refsect1>

 <refsect1><title>COMPLETENESS (6)</title>
  <para>
   <screen>
    1 Incomplete subfield
    2 Complete subfield
    3 Complete field
   </screen>
  </para>
 </refsect1>

 <refsect1><title>SORTING (7)</title>
  <para>
   <screen>
    1 ascending
    2 descending
   </screen>
  </para>
  <para>
    Type 7 is an Index Data extension to RPN queries that allows
    embedding a sort critieria into a query.
  </para>
 </refsect1>

 <refsect1><title>SEE ALSO</title>
  <para>
   <ulink url="&url.z39.50.attset.bib1;">Bib-1 Attribute Set</ulink>
  </para>
  <para>
   <ulink url="http://www.loc.gov/z3950/agency/bib1.html">Attibute
    Set Bib-1 Semantics</ulink>.
  </para>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: nxml
nxml-child-indent: 1
End:
-->


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _assert = require('assert');

var _assert2 = _interopRequireDefault(_assert);

var _objectToGetParams = require('./utils/objectToGetParams');

var _objectToGetParams2 = _interopRequireDefault(_objectToGetParams);

var _createShareButton = require('./utils/createShareButton');

var _createShareButton2 = _interopRequireDefault(_createShareButton);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function twitterLink(url, _ref) {
  var title = _ref.title,
      via = _ref.via,
      _ref$hashtags = _ref.hashtags,
      hashtags = _ref$hashtags === undefined ? [] : _ref$hashtags;

  (0, _assert2.default)(url, 'twitter.url');
  (0, _assert2.default)(Array.isArray(hashtags), 'twitter.hashtags is not an array');

  return 'https://twitter.com/share' + (0, _objectToGetParams2.default)({
    url: url,
    text: title,
    via: via,
    hashtags: hashtags.join(',')
  });
}

var TwitterShareButton = (0, _createShareButton2.default)('twitter', twitterLink, function (props) {
  return {
    hashtags: props.hashtags,
    title: props.title,
    via: props.via
  };
}, {
  hashtags: _propTypes2.default.arrayOf(_propTypes2.default.string),
  title: _propTypes2.default.string,
  via: _propTypes2.default.string
}, {
  windowWidth: 550,
  windowHeight: 400
});

exports.default = TwitterShareButton;


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:padding="@dimen/widget_margin">

    <FrameLayout
        android:id="@+id/widget"
        android:layout_width="match_parent"
        android:layout_height="@dimen/abc_action_bar_default_height_material"
        android:background="@color/colorPrimary">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"
            android:layout_gravity="center"
            android:text="@string/title_widget_recent_notes"/>
<!--        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/app_name"
            android:layout_gravity="center"
            android:src="@drawable/ic_logo"
            />-->
    </FrameLayout>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/colorPrimaryLight">
        <ListView
            android:id="@+id/widget_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:divider="@null"
            android:dividerHeight="0dp"
            tools:listitem="@layout/widget_recent_notes_list_item"/>
        <TextView
            android:id="@+id/widget_empty"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:fontFamily="sans-serif-condensed"
            android:textAppearance="?android:textAppearanceLargeInverse"
            android:text="@string/empty_notes_list"/>
    </FrameLayout>

</LinearLayout>


text:
layout: post
title: Measuring program performance with perf(1)
categories: Programming
---

In my new internship I am working on optimizing some software.
But before starting making changes to the source code, I need to make sure that I am optimizing important parts.
Imagine for a moment that I spend days making one part of a program go 10x faster (!!), only to realize later that it is responsible for 1% of the total run time.
How much would I have saved?
The answer is not much: the new run time would be 99% + (1% / 10) = 99.1% of the original run time.
In other words, only 1.01 times faster.
Not so impressing now, is it?

This post will introduce one method to measure how the program is spending its time.
This is known as *profiling* the code.
I learnt a lot of techniques from my colleagues, but also a lot comes from [Chandler Carruth's talk at CppCon 2015](https://www.youtube.com/watch?v=nXaxk27zwlk).
Go watch it if you want more information than what I expose here.

## Sample program to profile

For those experiments we will need a small program to profile.
I wrote a simple program (see below) that computes the Fibonacci sequence and displays it.
I know that this is not optimal in any way, but we will see how.

```cpp
#include <vector>
#include <iostream>

#include <benchmark/benchmark.h>

static void Benchmark_Fibonacci(benchmark::State& state) {
    const int N = 200;
    for (auto _ : state) {
        std::vector<int> v;

        v.push_back(1);
        v.push_back(2);

        for (int i = 1; i < N; i++) {
            v.push_back(v[i] + v[i - 1]);
        }

        benchmark::DoNotOptimize(&v);
        benchmark::ClobberMemory();
    }
}
BENCHMARK(Benchmark_Fibonacci);

BENCHMARK_MAIN();
```

We can now build this program using `g++ benchmark.cpp -o fibo && ./benchmark`.
No output is produced, but the suite is computed, so it is time to measure what takes some time.

Now that this is done, we can run the program with the perf utility (found in `linux-tools`).
We will run it with the `-g` option to record call graph information:
We need to run it as root because the access to performance counter are disabled by default on Linux.
Normal users can be given access to this, but this is out of the scope of this article.

```bash
$ sudo perf record -g ./benchmark
$ sudo perf report -g 'graph,0.5,caller'
```

You should now be presented with an interactive window in which you can see how much time your program spent in each function.

One nice trick in the code above is the use of the functions `DoNotOptimize` and `ClobberMemory`.
Those twp functions basically tell the compiler to ignore the fact that the results of the computation are not used anywhere.
Otherwise, most optimizers will delete the code of our benchmark, as it does not create side effect.

For those of you who are curious, you can implement it yourself using the following code:

```cpp
void DoNotOptimize(void *p)
{
    volatile asm("" : : "g"(p) : "memory");
}

void ClobberMemory(void)
{
    volatile asm("" : : : "memory");
}
```

Basically those two lines of code are used to create fake zones where the results of the benchmark *might* be used.
The compiler is also disallowed to optimize those parts by the use of the `volatile` keyword.
For more detail on this, see the talk I linked above or GCC's documentation on inline assembly.

There is a lot to be said on how to interpret perf's output and optimize your code, but I just wanted to share what I learnt last week.
The rest will be for another post!


text:
@interface UIViewController (NavigationWithBuilder)

+ (instancetype)pushBasedViewController:(UIViewController *)baseViewController
                                builder:(BuilderBlock)block;

+ (instancetype)presentBasedViewController:(UIViewController *)baseViewController
                                   builder:(BuilderBlock)block;

@end


text:
module.exports = function(RED) {

    function LogstashInputIrcNode(config) {
        RED.nodes.createNode(this, config);
        var node = this;

        this.on("close", function() {
        });
    }
    RED.nodes.registerType("ls-in-irc", LogstashInputIrcNode);
};


text:
require 'bundler'
Bundler.require

module Project
  def self.root
    @root ||= Pathname(File.expand_path("../..", __FILE__))
  end

  def self.env
    @env ||= (ENV["RACK_ENV"] || "development")
  end

  def self.redis
    @redis ||= (
      url = URI(ENV['REDISTOGO_URL'] || "redis://127.0.0.1:6379")

      base_settings = {
        host: url.host,
        port: url.port,
        db: url.path[1..-1],
        password: url.password
      }

      Redis::Namespace.new("grocery:#{env}", redis: Redis.new(base_settings))
    )
  end

  def self.config
    config_file = Pathname.new File.join(root, "config", "local_settings.yml")

    if config_file.file?
      YAML.load(ERB.new(config_file.read).result)[env]
    else
      ENV
    end
  end
end

require_relative 'project/app'
require_relative 'project/list'


text:
package org.cleartk.util.treebank;

/**
 *

 * Copyright (c) 2007-2008, Regents of the University of Colorado

 * All rights reserved.
 *
 *
 * @author Philip Ogren
 *
 */
public interface TreebankObject {
  public String getText();
}


text:
from __future__ import absolute_import, division, print_function
import copy
import numpy as np
from scipy.ndimage import map_coordinates
from scipy.ndimage import spline_filter
from scipy.ndimage import shift
from astropy.io import fits
import fermipy.utils as utils
import fermipy.wcs_utils as wcs_utils

class MapInterpolator(object):
    """Object that can efficiently generate source maps by
    interpolation of a map object."""

    def __init__(self, data, pix_ref, shape_out, rebin):

        self._data = data
        self._data_spline = []
        for i in range(data.shape[0]):
            self._data_spline += [spline_filter(self._data[i], order=2)]

        self._axes = []
        for i in range(data.ndim):
            self._axes += [np.arange(0, data.shape[i], dtype=float)]

        #self._coords = np.meshgrid(*self._axes[1:], indexing='ij')
        self._rebin = rebin

        # Shape of global output array
        self._shape_out = shape_out

        self._shape = np.array(self.data.shape)
        for i in range(1, self.data.ndim):
            self._shape[i] = int(self._shape[i] / self.rebin)
        self._shape = tuple(self._shape)

        # Reference pixel coordinates
        self._pix_ref = pix_ref

    @property
    def data(self):
        return self._data

    @property
    def shape(self):
        return self._shape

    @property
    def shape_out(self):
        return self._shape_out

    @property
    def rebin(self):
        return self._rebin

    @property
    def ndim(self):
        return self._data.ndim

    def get_offsets(self, pix):
        """Get offset of the first pixel in each dimension in the
        global coordinate system.

        Parameters
        ----------
        pix : `~numpy.ndarray`
            Pixel coordinates in global coordinate system.
        """

        idx = []
        for i in range(self.ndim):

            if i == 0:
                idx += [0]
            else:
                npix1 = int(self.shape[i])
                pix0 = int(pix[i - 1]) - npix1 // 2
                idx += [pix0]

        return idx

    def shift_to_coords(self, pix, fill_value=np.nan):
        """Create a new map that is shifted to the pixel coordinates
        ``pix``."""

        pix_offset = self.get_offsets(pix)
        dpix = np.zeros(len(self.shape) - 1)
        for i in range(len(self.shape) - 1):
            x = self.rebin * (pix[i] - pix_offset[i + 1]
                              ) + (self.rebin - 1.0) / 2.
            dpix[i] = x - self._pix_ref[i]

        pos = [pix_offset[i] + self.shape[i] // 2
               for i in range(self.data.ndim)]
        s0, s1 = utils.overlap_slices(self.shape_out, self.shape, pos)

        k = np.zeros(self.data.shape)
        for i in range(k.shape[0]):
            k[i] = shift(self._data_spline[i], dpix, cval=np.nan,
                         order=2, prefilter=False)

        for i in range(1, len(self.shape)):
            k = utils.sum_bins(k, i, self.rebin)

        k0 = np.ones(self.shape_out) * fill_value

        if k[s1].size == 0 or k0[s0].size == 0:
            return k0
        k0[s0] = k[s1]
        return k0

class SourceMapCache(object):
    """Object generates source maps by interpolation of map
    templates."""

    def __init__(self, m0, m1):
        self._m0 = m0
        self._m1 = m1

    def create_map(self, pix):
        """Create a new map with reference pixel coordinates shifted
        to the pixel coordinates ``pix``.

        Parameters
        ----------
        pix : `~numpy.ndarray`
            Reference pixel of new map.

        Returns
        -------
        out_map : `~numpy.ndarray`
            The shifted map.
        """
        k0 = self._m0.shift_to_coords(pix)
        k1 = self._m1.shift_to_coords(pix)

        k0[np.isfinite(k1)] = k1[np.isfinite(k1)]
        k0[~np.isfinite(k0)] = 0
        return k0

    @classmethod
    def create(cls, psf, exp, spatial_model, spatial_width, shape_out, cdelt,
               rebin=4):

        npix = shape_out[1]
        pad_pix = npix // 2

        xpix = (npix + pad_pix - 1.0) / 2.
        ypix = (npix + pad_pix - 1.0) / 2.
        pix_ref = np.array([ypix, xpix])

        k0 = make_srcmap(psf, exp, spatial_model, spatial_width,
                         npix=npix + pad_pix,
                         xpix=xpix, ypix=ypix,
                         cdelt=cdelt)

        m0 = MapInterpolator(k0, pix_ref, shape_out, 1)

        npix1 = max(10, int(0.5 / cdelt)) * rebin
        xpix1 = (npix1 - 1.0) / 2.
        ypix1 = (npix1 - 1.0) / 2.
        pix_ref = np.array([ypix1, xpix1])

        k1 = make_srcmap(psf, exp, spatial_model, spatial_width,
                         npix=npix1,
                         xpix=xpix1, ypix=ypix1,
                         cdelt=cdelt / rebin)

        m1 = MapInterpolator(k1, pix_ref, shape_out, rebin)

        return cls(m0, m1)

def make_srcmap_old(psf, spatial_model, sigma, npix=500, xpix=0.0, ypix=0.0,
                    cdelt=0.01, rebin=1, psf_scale_fn=None):
    """Compute the source map for a given spatial model.

    Parameters
    ----------
    psf : `~fermipy.irfs.PSFModel`
    spatial_model : str
        Spatial model.
    sigma : float
        Spatial size parameter for extended models.
    xpix : float
        Source position in pixel coordinates in X dimension.
    ypix : float
        Source position in pixel coordinates in Y dimension.
    rebin : int
        Factor by which the original map will be oversampled in the
        spatial dimension when computing the model.
    psf_scale_fn : callable
        Function that evaluates the PSF scaling function.
        Argument is energy in MeV.
    """
    if rebin > 1:
        npix = npix * rebin
        xpix = xpix * rebin + (rebin - 1.0) / 2.
        ypix = ypix * rebin + (rebin - 1.0) / 2.
        cdelt = cdelt / rebin

    if spatial_model == 'RadialGaussian':
        k = utils.make_cgauss_kernel(psf, sigma, npix, cdelt,
                                     xpix, ypix, psf_scale_fn)
    elif spatial_model == 'RadialDisk':
        k = utils.make_cdisk_kernel(psf, sigma, npix, cdelt,
                                    xpix, ypix, psf_scale_fn)
    elif spatial_model == 'PointSource':
        k = utils.make_psf_kernel(psf, npix, cdelt,
                                  xpix, ypix, psf_scale_fn)
    else:
        raise Exception('Unsupported spatial model: %s', spatial_model)

    if rebin > 1:
        k = utils.sum_bins(k, 1, rebin)
        k = utils.sum_bins(k, 2, rebin)

    k *= psf.exp[:, np.newaxis, np.newaxis] * np.radians(cdelt) ** 2
    return k

def make_srcmap(psf, exp, spatial_model, sigma, npix=(500,500), xpix=0.0, ypix=0.0,
                cdelt=0.01, psf_scale_fn=None, klims=None, sparse=False):
    """Compute the source map for a given spatial model.

    Parameters
    ----------
    psf : `~fermipy.irfs.PSFModel`

    exp : `~numpy.ndarray`
        Array of exposures.

    spatial_model : str
        Spatial model.

    sigma : float
        Spatial size parameter for extended models.

    npix : tuple
        Number of of map bins in the x and y direction

    xpix : float
        Source position in pixel coordinates in X dimension.

    ypix : float
        Source position in pixel coordinates in Y dimension.

    psf_scale_fn : callable
        Function that evaluates the PSF scaling function.
        Argument is energy in MeV.

    klims : tuple
        Indices of lower and upper range of energy.

    sparse : bool
        Skip pixels in which the source amplitude is small.

    """
    if spatial_model == 'RadialGaussian':
        k = utils.make_radial_kernel(psf, utils.convolve2d_gauss,
                                     sigma / 1.5095921854516636, npix, cdelt,
                                     xpix, ypix, psf_scale_fn, klims=klims,
                                     sparse=sparse)
    elif spatial_model == 'RadialDisk':
        k = utils.make_radial_kernel(psf, utils.convolve2d_disk,
                                     sigma / 0.8246211251235321, npix, cdelt,
                                     xpix, ypix, psf_scale_fn, klims=klims,
                                     sparse=sparse)
    elif spatial_model == 'PointSource':
        k = utils.make_radial_kernel(psf, None, None, npix, cdelt,
                                     xpix, ypix, psf_scale_fn, klims=klims,
                                     sparse=sparse)
    else:
        raise Exception('Unsupported spatial model: %s', spatial_model)

    if klims is not None:
        exp = exp[klims[0]:klims[1] + 1, ...]

    k *= exp[:, np.newaxis, np.newaxis] * np.radians(cdelt) ** 2
    return k

def make_cgauss_mapcube(skydir, psf, sigma, outfile, npix=500, cdelt=0.01,
                        rebin=1):
    energies = psf.energies
    nebin = len(energies)

    k = utils.make_cgauss_kernel(psf, sigma, npix * rebin, cdelt / rebin)

    if rebin > 1:
        k = utils.rebin_map(k, nebin, npix, rebin)
    w = wcs_utils.create_wcs(skydir, cdelt=cdelt,
                             crpix=npix / 2. + 0.5, naxis=3)

    w.wcs.crpix[2] = 1
    w.wcs.crval[2] = 10 ** energies[0]
    w.wcs.cdelt[2] = energies[1] - energies[0]
    w.wcs.ctype[2] = 'Energy'

    ecol = fits.Column(name='Energy', format='D', array=10 ** energies)
    hdu_energies = fits.BinTableHDU.from_columns([ecol], name='ENERGIES')

    hdu_image = fits.PrimaryHDU(np.zeros((nebin, npix, npix)),
                                header=w.to_header())

    hdu_image.data[...] = k

    hdu_image.header['CUNIT3'] = 'MeV'

    with fits.HDUList([hdu_image, hdu_energies]) as hdulist:
        hdulist.writeto(outfile, overwrite=True)

def make_psf_mapcube(skydir, psf, outfile, npix=500, cdelt=0.01, rebin=1):
    energies = psf.energies
    nebin = len(energies)

    k = utils.make_psf_kernel(psf, npix * rebin, cdelt / rebin)

    if rebin > 1:
        k = utils.rebin_map(k, nebin, npix, rebin)
    w = wcs_utils.create_wcs(skydir, cdelt=cdelt,
                             crpix=npix / 2. + 0.5, naxis=3)

    w.wcs.crpix[2] = 1
    w.wcs.crval[2] = 10 ** energies[0]
    w.wcs.cdelt[2] = energies[1] - energies[0]
    w.wcs.ctype[2] = 'Energy'

    ecol = fits.Column(name='Energy', format='D', array=10 ** energies)
    hdu_energies = fits.BinTableHDU.from_columns([ecol], name='ENERGIES')

    hdu_image = fits.PrimaryHDU(np.zeros((nebin, npix, npix)),
                                header=w.to_header())

    hdu_image.data[...] = k

    hdu_image.header['CUNIT3'] = 'MeV'

    with fits.HDUList([hdu_image, hdu_energies]) as hdulist:
        hdulist.writeto(outfile, overwrite=True)

def make_gaussian_spatial_map(skydir, sigma, outfile, cdelt=None, npix=None):

    if cdelt is None:
        cdelt = sigma / 10.

    if npix is None:
        npix = int(np.ceil((6.0 * (sigma + cdelt)) / cdelt))

    w = wcs_utils.create_wcs(skydir, cdelt=cdelt, crpix=npix / 2. + 0.5)
    hdu_image = fits.PrimaryHDU(np.zeros((npix, npix)),
                                header=w.to_header())

    hdu_image.data[:, :] = utils.make_gaussian_kernel(sigma, npix=npix,
                                                      cdelt=cdelt)
    with fits.HDUList([hdu_image]) as hdulist:
        hdulist.writeto(outfile, overwrite=True)

def make_disk_spatial_map(skydir, radius, outfile, cdelt=None, npix=None):

    if cdelt is None:
        cdelt = radius / 10.

    if npix is None:
        npix = int(np.ceil((2.0 * (radius + cdelt)) / cdelt))

    w = wcs_utils.create_wcs(skydir, cdelt=cdelt, crpix=npix / 2. + 0.5)
    hdu_image = fits.PrimaryHDU(np.zeros((npix, npix)),
                                header=w.to_header())

    hdu_image.data[:, :] = utils.make_disk_kernel(radius, npix=npix,
                                                  cdelt=cdelt)
    with fits.HDUList([hdu_image]) as hdulist:
        hdulist.writeto(outfile, overwrite=True)

def delete_source_map(srcmap_file, names, logger=None):
    """Delete a map from a binned analysis source map file if it exists.

    Parameters
    ----------
    srcmap_file : str
       Path to the source map file.

    names : list
       List of HDU keys of source maps to be deleted.

    """
    with fits.open(srcmap_file) as hdulist:
        hdunames = [hdu.name.upper() for hdu in hdulist]

        if not isinstance(names, list):
            names = [names]

        for name in names:
            if not name.upper() in hdunames:
                continue
            del hdulist[name.upper()]

        hdulist.writeto(srcmap_file, overwrite=True)

def update_source_maps(srcmap_file, srcmaps, logger=None):

    with fits.open(srcmap_file) as hdulist:
        hdunames = [hdu.name.upper() for hdu in hdulist]

        for name, data in srcmaps.items():

            if not name.upper() in hdunames:

                for hdu in hdulist[1:]:
                    if hdu.header['XTENSION'] == 'IMAGE':
                        break

                newhdu = fits.ImageHDU(data, hdu.header, name=name)
                newhdu.header['EXTNAME'] = name
                hdulist.append(newhdu)

            if logger is not None:
                logger.debug('Updating source map for %s' % name)

            hdulist[name].data[...] = data

        hdulist.writeto(srcmap_file, overwrite=True)


text:
struct evaluateFeatureDetectorRetval {
    struct KeyPointArray keypoints1, keypoints2;
    float repeatability;
    int correspCount;
};

// KeyPointsFilter
struct KeyPointsFilterPtr {
    void *ptr;

    inline cv::KeyPointsFilter * operator->() { return static_cast<cv::KeyPointsFilter *>(ptr); }
    inline KeyPointsFilterPtr(cv::KeyPointsFilter *ptr) { this->ptr = ptr; }
    inline cv::KeyPointsFilter & operator*() { return *static_cast<cv::KeyPointsFilter *>(this->ptr); }
};

extern "C"
struct KeyPointsFilterPtr KeyPointsFilter_ctor();

extern "C"
void KeyPointsFilter_dtor(struct KeyPointsFilterPtr ptr);

extern "C"
struct KeyPointArray KeyPointsFilter_runByImageBorder(struct KeyPointArray keypoints,
                                                      struct SizeWrapper imageSize, int borderSize);

extern "C"
struct KeyPointArray KeyPointsFilter_runByKeypointSize(struct KeyPointArray keypoints,
                                                       float minSize, float maxSize);

extern "C"
struct KeyPointArray KeyPointsFilter_runByPixelsMask(struct KeyPointArray keypoints,
                                                     struct TensorWrapper mask);

extern "C"
struct KeyPointArray KeyPointsFilter_removeDuplicated(struct KeyPointArray keypoints);

extern "C"
struct KeyPointArray KeyPointsFilter_retainBest(struct KeyPointArray keypoints, int npoints);

// Feature2D

struct Feature2DPtr {
    void *ptr;

    inline cv::Feature2D * operator->() { return static_cast<cv::Feature2D *>(ptr); }
    inline Feature2DPtr(cv::Feature2D *ptr) { this->ptr = ptr; }
    inline cv::Feature2D & operator*() { return *static_cast<cv::Feature2D *>(this->ptr); }
};

extern "C"
struct KeyPointArray Feature2D_detect(
        struct Feature2DPtr ptr, struct TensorWrapper image, struct TensorWrapper mask);

extern "C"
struct TensorPlusKeyPointArray Feature2D_compute(struct Feature2DPtr ptr, struct TensorWrapper image,
                        struct KeyPointArray keypoints, struct TensorWrapper descriptors);

extern "C"
struct TensorPlusKeyPointArray Feature2D_detectAndCompute(struct Feature2DPtr ptr, struct TensorWrapper image,
                        struct TensorWrapper mask,
                        struct TensorWrapper descriptors, bool useProvidedKeypoints);

extern "C"
int Feature2D_descriptorSize(struct Feature2DPtr ptr);

extern "C"
int Feature2D_descriptorType(struct Feature2DPtr ptr);

extern "C"
int Feature2D_defaultNorm(struct Feature2DPtr ptr);

extern "C"
bool Feature2D_empty(struct Feature2DPtr ptr);

// BRISK

struct BRISKPtr {
    void *ptr;
    inline cv::BRISK * operator->() { return static_cast<cv::BRISK *>(ptr); }
    inline BRISKPtr(cv::BRISK *ptr) { this->ptr = ptr; }
    inline cv::BRISK & operator*() { return *static_cast<cv::BRISK *>(this->ptr); }
};

extern "C"
struct BRISKPtr BRISK_ctor(int thresh, int octaves, float patternScale);

extern "C"
struct BRISKPtr BRISK_ctor2(struct TensorWrapper radiusList, struct TensorWrapper numberList,
                            float dMax, float dMin, struct TensorWrapper indexChange);

// ORB

struct ORBPtr {
    void *ptr;
    inline cv::ORB * operator->() { return static_cast<cv::ORB *>(ptr); }
    inline ORBPtr(cv::ORB *ptr) { this->ptr = ptr; }
    inline cv::ORB & operator*() { return *static_cast<cv::ORB *>(this->ptr); }
};

extern "C"
struct ORBPtr ORB_ctor(int nfeatures, float scaleFactor, int nlevels, int edgeThreshold, int firstLevel,
                       int WTA_K, int scoreType, int patchSize, int fastThreshold);

extern "C"
void ORB_setMaxFeatures(struct ORBPtr ptr, int maxFeatures);

extern "C"
int ORB_getMaxFeatures(struct ORBPtr ptr);

extern "C"
void ORB_setScaleFactor(struct ORBPtr ptr, int scaleFactor);

extern "C"
double ORB_getScaleFactor(struct ORBPtr ptr);

extern "C"
void ORB_setNLevels(struct ORBPtr ptr, int nlevels);

extern "C"
int ORB_getNLevels(struct ORBPtr ptr);

extern "C"
void ORB_setEdgeThreshold(struct ORBPtr ptr, int edgeThreshold);

extern "C"
int ORB_getEdgeThreshold(struct ORBPtr ptr);

extern "C"
void ORB_setFirstLevel(struct ORBPtr ptr, int firstLevel);

extern "C"
int ORB_getFirstLevel(struct ORBPtr ptr);

extern "C"
void ORB_setWTA_K(struct ORBPtr ptr, int wta_k);

extern "C"
int ORB_getWTA_K(struct ORBPtr ptr);

extern "C"
void ORB_setScoreType(struct ORBPtr ptr, int scoreType);

extern "C"
int ORB_getScoreType(struct ORBPtr ptr);

extern "C"
void ORB_setPatchSize(struct ORBPtr ptr, int patchSize);

extern "C"
int ORB_getPatchSize(struct ORBPtr ptr);

extern "C"
void ORB_setFastThreshold(struct ORBPtr ptr, int fastThreshold);

extern "C"
int ORB_getFastThreshold(struct ORBPtr ptr);

// MSER

struct MSERPtr {
    void *ptr;
    inline cv::MSER * operator->() { return static_cast<cv::MSER *>(ptr); }
    inline MSERPtr(cv::MSER *ptr) { this->ptr = ptr; }
    inline cv::MSER & operator*() { return *static_cast<cv::MSER *>(this->ptr); }
};

extern "C"
struct MSERPtr MSER_ctor(int _delta, int _min_area, int _max_area, double _max_variation, double _min_diversity,
                         int _max_evolution, double _area_threshold, double _min_margin, int _edge_blur_size);

extern "C"
struct TensorArray MSER_detectRegions(struct MSERPtr ptr,
                                      struct TensorWrapper image, struct TensorWrapper bboxes);

extern "C"
void MSER_setDelta(struct MSERPtr ptr, int delta);

extern "C"
int MSER_getDelta(struct MSERPtr ptr);

extern "C"
void MSER_setMinArea(struct MSERPtr ptr, int minArea);

extern "C"
int MSER_getMinArea(struct MSERPtr ptr);

extern "C"
void MSER_setMaxArea(struct MSERPtr ptr, int MaxArea);

extern "C"
int MSER_getMaxArea(struct MSERPtr ptr);

extern "C"
void MSER_setPass2Only(struct MSERPtr ptr, bool Pass2Only);

extern "C"
bool MSER_getPass2Only(struct MSERPtr ptr);

// functions

extern "C"
struct KeyPointArray FAST(
        struct TensorWrapper image, int threshold, bool nonmaxSuppression);

extern "C"
struct KeyPointArray FAST_type(
        struct TensorWrapper image, int threshold, bool nonmaxSuppression, int type);

extern "C"
struct KeyPointArray AGAST(struct TensorWrapper image, int threshold, bool nonmaxSuppression);

extern "C"
struct KeyPointArray AGAST_type(struct TensorWrapper image, int threshold, bool nonmaxSuppression, int type);

// FastFeatureDetector

struct FastFeatureDetectorPtr {
    void *ptr;
    inline cv::FastFeatureDetector * operator->() { return static_cast<cv::FastFeatureDetector *>(ptr); }
    inline FastFeatureDetectorPtr(cv::FastFeatureDetector *ptr) { this->ptr = ptr; }
    inline cv::FastFeatureDetector & operator*() { return *static_cast<cv::FastFeatureDetector *>(this->ptr); }
};

extern "C"
struct FastFeatureDetectorPtr FastFeatureDetector_ctor(
        int threshold, bool nonmaxSuppression, int type);

extern "C"
void FastFeatureDetector_setThreshold(struct FastFeatureDetectorPtr ptr, int val);

extern "C"
int FastFeatureDetector_getThreshold(struct FastFeatureDetectorPtr ptr);

extern "C"
void FastFeatureDetector_setNonmaxSuppression(struct FastFeatureDetectorPtr ptr, bool val);

extern "C"
bool FastFeatureDetector_getNonmaxSuppression(struct FastFeatureDetectorPtr ptr);

extern "C"
void FastFeatureDetector_setType(struct FastFeatureDetectorPtr ptr, int val);

extern "C"
int FastFeatureDetector_getType(struct FastFeatureDetectorPtr ptr);

// AgastFeatureDetector

struct AgastFeatureDetectorPtr {
    void *ptr;
    inline cv::AgastFeatureDetector * operator->() { return static_cast<cv::AgastFeatureDetector *>(ptr); }
    inline AgastFeatureDetectorPtr(cv::AgastFeatureDetector *ptr) { this->ptr = ptr; }
    inline cv::AgastFeatureDetector & operator*() { return *static_cast<cv::AgastFeatureDetector *>(this->ptr); }
};

extern "C"
struct AgastFeatureDetectorPtr AgastFeatureDetector_ctor(
        int threshold, bool nonmaxSuppression, int type);

extern "C"
void AgastFeatureDetector_setThreshold(struct AgastFeatureDetectorPtr ptr, int val);

extern "C"
int AgastFeatureDetector_getThreshold(struct AgastFeatureDetectorPtr ptr);

extern "C"
void AgastFeatureDetector_setNonmaxSuppression(struct AgastFeatureDetectorPtr ptr, bool val);

extern "C"
bool AgastFeatureDetector_getNonmaxSuppression(struct AgastFeatureDetectorPtr ptr);

extern "C"
void AgastFeatureDetector_setType(struct AgastFeatureDetectorPtr ptr, int val);

extern "C"
int AgastFeatureDetector_getType(struct AgastFeatureDetectorPtr ptr);

// GFTTDetector

struct GFTTDetectorPtr {
    void *ptr;
    inline cv::GFTTDetector * operator->() { return static_cast<cv::GFTTDetector *>(ptr); }
    inline GFTTDetectorPtr(cv::GFTTDetector *ptr) { this->ptr = ptr; }
    inline cv::GFTTDetector & operator*() { return *static_cast<cv::GFTTDetector *>(this->ptr); }
};

extern "C"
struct GFTTDetectorPtr GFTTDetector_ctor(
        int maxCorners, double qualityLevel, double minDistance,
        int blockSize, bool useHarrisDetector, double k);

extern "C"
void GFTTDetector_setMaxFeatures(struct GFTTDetectorPtr ptr, int val);

extern "C"
int GFTTDetector_getMaxFeatures(struct GFTTDetectorPtr ptr);

extern "C"
void GFTTDetector_setQualityLevel(struct GFTTDetectorPtr ptr, double val);

extern "C"
double GFTTDetector_getQualityLevel(struct GFTTDetectorPtr ptr);

extern "C"
void GFTTDetector_setMinDistance(struct GFTTDetectorPtr ptr, double val);

extern "C"
double GFTTDetector_getMinDistance(struct GFTTDetectorPtr ptr);

extern "C"
void GFTTDetector_setBlockSize(struct GFTTDetectorPtr ptr, int val);

extern "C"
int GFTTDetector_getBlockSize(struct GFTTDetectorPtr ptr);

extern "C"
void GFTTDetector_setHarrisDetector(struct GFTTDetectorPtr ptr, bool val);

extern "C"
bool GFTTDetector_getHarrisDetector(struct GFTTDetectorPtr ptr);

extern "C"
void GFTTDetector_setK(struct GFTTDetectorPtr ptr, double val);

extern "C"
double GFTTDetector_getK(struct GFTTDetectorPtr ptr);

// SimpleBlobDetector

struct SimpleBlobDetectorPtr {
    void *ptr;
    inline cv::SimpleBlobDetector * operator->() { return static_cast<cv::SimpleBlobDetector *>(ptr); }
    inline SimpleBlobDetectorPtr(cv::SimpleBlobDetector *ptr) { this->ptr = ptr; }
    inline cv::SimpleBlobDetector & operator*() { return *static_cast<cv::SimpleBlobDetector *>(this->ptr); }
};

extern "C"
cv::SimpleBlobDetector::Params SimpleBlobDetector_Params_default();

extern "C"
struct SimpleBlobDetectorPtr SimpleBlobDetector_ctor(cv::SimpleBlobDetector::Params params);

extern "C"
cv::SimpleBlobDetector::Params SimpleBlobDetector_Params_default();

extern "C"
struct SimpleBlobDetectorPtr SimpleBlobDetector_ctor(cv::SimpleBlobDetector::Params params);

// KAZE

struct KAZEPtr {
    void *ptr;
    inline cv::KAZE * operator->() { return static_cast<cv::KAZE *>(ptr); }
    inline KAZEPtr(cv::KAZE *ptr) { this->ptr = ptr; }
    inline cv::KAZE & operator*() { return *static_cast<cv::KAZE *>(this->ptr); }
};

extern "C"
struct KAZEPtr KAZE_ctor(
        bool extended, bool upright, float threshold,
        int nOctaves, int nOctaveLayers, int diffusivity);

extern "C"
void KAZE_setExtended(struct KAZEPtr ptr, bool val);

extern "C"
bool KAZE_getExtended(struct KAZEPtr ptr);

extern "C"
void KAZE_setUpright(struct KAZEPtr ptr, bool val);

extern "C"
bool KAZE_getUpright(struct KAZEPtr ptr);

extern "C"
void KAZE_setThreshold(struct KAZEPtr ptr, double val);

extern "C"
double KAZE_getThreshold(struct KAZEPtr ptr);

extern "C"
void KAZE_setNOctaves(struct KAZEPtr ptr, int val);

extern "C"
int KAZE_getNOctaves(struct KAZEPtr ptr);

extern "C"
void KAZE_setNOctaveLayers(struct KAZEPtr ptr, int val);

extern "C"
int KAZE_getNOctaveLayers(struct KAZEPtr ptr);

extern "C"
void KAZE_setDiffusivity(struct KAZEPtr ptr, int val);

extern "C"
int KAZE_getDiffusivity(struct KAZEPtr ptr);

// AKAZE

struct AKAZEPtr {
    void *ptr;
    inline cv::AKAZE * operator->() { return static_cast<cv::AKAZE *>(ptr); }
    inline AKAZEPtr(cv::AKAZE *ptr) { this->ptr = ptr; }
    inline cv::AKAZE & operator*() { return *static_cast<cv::AKAZE *>(this->ptr); }
};

extern "C"
struct AKAZEPtr AKAZE_ctor(
        int descriptor_type, int descriptor_size, int descriptor_channels,
        float threshold, int nOctaves, int nOctaveLayers, int diffusivity);

extern "C"
void AKAZE_setDescriptorType(struct AKAZEPtr ptr, int val);

extern "C"
int AKAZE_getDescriptorType(struct AKAZEPtr ptr);

extern "C"
void AKAZE_setDescriptorSize(struct AKAZEPtr ptr, int val);

extern "C"
int AKAZE_getDescriptorSize(struct AKAZEPtr ptr);

extern "C"
void AKAZE_setDescriptorChannels(struct AKAZEPtr ptr, int val);

extern "C"
int AKAZE_getDescriptorChannels(struct AKAZEPtr ptr);

extern "C"
void AKAZE_setThreshold(struct AKAZEPtr ptr, double val);

extern "C"
double AKAZE_getThreshold(struct AKAZEPtr ptr);

extern "C"
void AKAZE_setNOctaves(struct AKAZEPtr ptr, int val);

extern "C"
int AKAZE_getNOctaves(struct AKAZEPtr ptr);

extern "C"
void AKAZE_setNOctaveLayers(struct AKAZEPtr ptr, int val);

extern "C"
int AKAZE_getNOctaveLayers(struct AKAZEPtr ptr);

extern "C"
void AKAZE_setDiffusivity(struct AKAZEPtr ptr, int val);

extern "C"
int AKAZE_getDiffusivity(struct AKAZEPtr ptr);

// DescriptorMatcher

struct DescriptorMatcherPtr {
    void *ptr;
    inline cv::DescriptorMatcher * operator->() { return static_cast<cv::DescriptorMatcher *>(ptr); }
    inline DescriptorMatcherPtr(cv::DescriptorMatcher *ptr) { this->ptr = ptr; }
    inline cv::DescriptorMatcher & operator*() { return *static_cast<cv::DescriptorMatcher *>(this->ptr); }
};

extern "C"
struct DescriptorMatcherPtr DescriptorMatcher_ctor(const char *descriptorMatcherType);

extern "C"
void DescriptorMatcher_add(struct DescriptorMatcherPtr ptr, struct TensorArray descriptors);

extern "C"
struct TensorArray DescriptorMatcher_getTrainDescriptors(struct DescriptorMatcherPtr ptr);

extern "C"
void DescriptorMatcher_clear(struct DescriptorMatcherPtr ptr);

extern "C"
bool DescriptorMatcher_empty(struct DescriptorMatcherPtr ptr);

extern "C"
bool DescriptorMatcher_isMaskSupported(struct DescriptorMatcherPtr ptr);

extern "C"
void DescriptorMatcher_train(struct DescriptorMatcherPtr ptr);

extern "C"
struct DMatchArray DescriptorMatcher_match(struct DescriptorMatcherPtr ptr,
                                           struct TensorWrapper queryDescriptors, struct TensorWrapper mask);

extern "C"
struct DMatchArray DescriptorMatcher_match_trainDescriptors(struct DescriptorMatcherPtr ptr,
                                                            struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors,
                                                            struct TensorWrapper mask);

extern "C"
struct DMatchArrayOfArrays DescriptorMatcher_knnMatch(struct DescriptorMatcherPtr ptr,
                                                      struct TensorWrapper queryDescriptors, int k,
                                                      struct TensorWrapper mask, bool compactResult);

extern "C"
struct DMatchArrayOfArrays DescriptorMatcher_knnMatch_trainDescriptors(struct DescriptorMatcherPtr ptr,
                                                                       struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors,
                                                                       int k, struct TensorWrapper mask, bool compactResult);

// BFMatcher

struct BFMatcherPtr {
    void *ptr;
    inline cv::BFMatcher * operator->() { return static_cast<cv::BFMatcher *>(ptr); }
    inline BFMatcherPtr(cv::BFMatcher *ptr) { this->ptr = ptr; }
    inline cv::BFMatcher & operator*() { return *static_cast<cv::BFMatcher *>(this->ptr); }
};

extern "C"
struct BFMatcherPtr BFMatcher_ctor(int normType, bool crossCheck);

// FlannBasedMatcher

struct FlannBasedMatcherPtr {
    void *ptr;
    inline cv::FlannBasedMatcher * operator->() { return static_cast<cv::FlannBasedMatcher *>(ptr); }
    inline FlannBasedMatcherPtr(cv::FlannBasedMatcher *ptr) { this->ptr = ptr; }
    inline cv::FlannBasedMatcher & operator*() { return *static_cast<cv::FlannBasedMatcher *>(this->ptr); }
};

extern "C"
struct FlannBasedMatcherPtr FlannBasedMatcher_ctor(
        struct IndexParamsPtr indexParams, struct SearchParamsPtr searchParams);

// functions

extern "C"
struct TensorWrapper drawKeypoints(
        struct TensorWrapper image, struct KeyPointArray keypoints, struct TensorWrapper outImage,
        struct ScalarWrapper color, int flags);

extern "C"
struct TensorWrapper drawMatches(
        struct TensorWrapper img1, struct KeyPointArray keypoints1,
        struct TensorWrapper img2, struct KeyPointArray keypoints2,
        struct DMatchArray matches1to2, struct TensorWrapper outImg,
        struct ScalarWrapper matchColor, struct ScalarWrapper singlePointColor,
        struct TensorWrapper matchesMask, int flags);

extern "C"
struct TensorWrapper drawMatchesKnn(
        struct TensorWrapper img1, struct KeyPointArray keypoints1,
        struct TensorWrapper img2, struct KeyPointArray keypoints2,
        struct DMatchArrayOfArrays matches1to2, struct TensorWrapper outImg,
        struct ScalarWrapper matchColor, struct ScalarWrapper singlePointColor,
        struct TensorArray matchesMask, int flags);

extern "C"
struct evaluateFeatureDetectorRetval evaluateFeatureDetector(
        struct TensorWrapper img1, struct TensorWrapper img2, struct TensorWrapper H1to2,
        struct Feature2DPtr fdetector);

extern "C"
struct TensorWrapper computeRecallPrecisionCurve(
        struct DMatchArrayOfArrays matches1to2, struct TensorArray correctMatches1to2Mask);

extern "C"
float getRecall(struct TensorWrapper recallPrecisionCurve, float l_precision);

extern "C"
int getNearestPoint(struct TensorWrapper recallPrecisionCurve, float l_precision);

// BOWTrainer

struct BOWTrainerPtr {
    void *ptr;
    inline cv::BOWTrainer * operator->() { return static_cast<cv::BOWTrainer *>(ptr); }
    inline BOWTrainerPtr(cv::BOWTrainer *ptr) { this->ptr = ptr; }
    inline cv::BOWTrainer & operator*() { return *static_cast<cv::BOWTrainer *>(this->ptr); }
};

extern "C"
void BOWTrainer_dtor(struct BOWTrainerPtr ptr);

extern "C"
void BOWTrainer_add(struct BOWTrainerPtr ptr, struct TensorWrapper descriptors);

extern "C"
struct TensorArray BOWTrainer_getDescriptors(struct BOWTrainerPtr ptr);

extern "C"
int BOWTrainer_descriptorsCount(struct BOWTrainerPtr ptr);

extern "C"
void BOWTrainer_clear(struct BOWTrainerPtr ptr);

extern "C"
struct TensorWrapper BOWTrainer_cluster(struct BOWTrainerPtr ptr);

extern "C"
struct TensorWrapper BOWTrainer_cluster_descriptors(struct BOWTrainerPtr ptr, struct TensorWrapper descriptors);

// BOWKMeansTrainer

struct BOWKMeansTrainerPtr {
    void *ptr;
    inline cv::BOWKMeansTrainer * operator->() { return static_cast<cv::BOWKMeansTrainer *>(ptr); }
    inline BOWKMeansTrainerPtr(cv::BOWKMeansTrainer *ptr) { this->ptr = ptr; }
    inline cv::BOWKMeansTrainer & operator*() { return *static_cast<cv::BOWKMeansTrainer *>(this->ptr); }
};

extern "C"
struct BOWKMeansTrainerPtr BOWKMeansTrainer_ctor(
        int clusterCount, struct TermCriteriaWrapper termcrit,
        int attempts, int flags);

// BOWImgDescriptorExtractor

struct BOWImgDescriptorExtractorPtr {
    void *ptr;
    inline cv::BOWImgDescriptorExtractor * operator->() { return static_cast<cv::BOWImgDescriptorExtractor *>(ptr); }
    inline BOWImgDescriptorExtractorPtr(cv::BOWImgDescriptorExtractor *ptr) { this->ptr = ptr; }
    inline cv::BOWImgDescriptorExtractor & operator*() { return *static_cast<cv::BOWImgDescriptorExtractor *>(this->ptr); }
};

extern "C"
struct BOWImgDescriptorExtractorPtr BOWImgDescriptorExtractor_ctor(
        struct Feature2DPtr dextractor, struct DescriptorMatcherPtr dmatcher);

extern "C"
void BOWImgDescriptorExtractor_dtor(struct BOWImgDescriptorExtractorPtr ptr);

extern "C"
void BOWImgDescriptorExtractor_setVocabulary(
        struct BOWImgDescriptorExtractorPtr ptr, struct TensorWrapper vocabulary);

extern "C"
struct TensorWrapper BOWImgDescriptorExtractor_getVocabulary(struct BOWImgDescriptorExtractorPtr ptr);

extern "C"
struct TensorWrapper BOWImgDescriptorExtractor_compute(
        struct BOWImgDescriptorExtractorPtr ptr, struct TensorWrapper image,
        struct KeyPointArray keypoints, struct TensorWrapper imgDescriptor);

extern "C"
int BOWImgDescriptorExtractor_descriptorSize(struct BOWImgDescriptorExtractorPtr ptr);

extern "C"
int BOWImgDescriptorExtractor_descriptorType(struct BOWImgDescriptorExtractorPtr ptr);


text:
machineip=
hostname=`hostname`

#Functions:
function install_kubernetes(){
    echo Running the Kubernetes installer...

    # Update apt and get dependencies
    sudo apt-get update
    sudo apt-get install -y unzip curl wget

    # Install docker and K8s
    curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
    sudo tee /etc/apt/sources.list.d/kubernetes.list <<EOF >/dev/null
    deb http://apt.kubernetes.io/ kubernetes-xenial main
EOF
    sudo apt-get update
    # Install docker if you don't have it already.
    sudo apt-get install -y docker.io
    sudo apt-get install -y --allow-unauthenticated kubelet kubeadm kubectl kubernetes-cni

    #Install JSON Parser for patching kube-proxy
    sudo apt-get install -y jq
}

function get_machine_ip(){
    ifconfig | grep -oP "inet addr:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | grep -oP "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | sort | tail -n 1 | head -n 1
}

function setup_k8s_master(){
    #sudo kubeadm init --apiserver-advertise-address=$machineip
    sudo kubeadm init --apiserver-advertise-address=$machineip
    sudo kubectl create --kubeconfig=/etc/kubernetes/admin.conf -f https://git.io/weave-kube
}

function update_hosts(){
    sudo sed -i "/$hostname/ s/.*/$machineip\t$hostname/g" /etc/hosts
}

function patch_kube_proxy(){
    sudo kubectl --kubeconfig=/etc/kubernetes/admin.conf -n kube-system get ds -l 'component=kube-proxy' -o json | \
        jq '.items[0].spec.template.spec.containers[0].command |= .+ ["--proxy-mode=userspace"]' | \
        sudo kubectl apply --kubeconfig=/etc/kubernetes/admin.conf -f - && sudo kubectl --kubeconfig=/etc/kubernetes/admin.conf -n kube-system delete pods -l 'component=kube-proxy'
}

function download_specs(){

    specurl="https://api.github.com/repos/openebs/openebs/contents/k8s/demo/specs"
    mapfile -t downloadurls < <(curl -sS $specurl | grep "download_url" | awk '{print $2}' | tr -d '",')

    #Create demo directory and download specs
    mkdir -p /home/ubuntu/demo/k8s/spec
    cd /home/ubuntu/demo/k8s/spec

    length=${#downloadurls[@]}
    for ((i = 0; i != length; i++)); do
        if [ -z "${downloadurls[i]##*yaml*}" ] ;then
            wget "${downloadurls[i]}"
        fi
    done

}

#Code
#Get the ip of the machine
machineip=`get_machine_ip`

#Install Kubernetes components
echo Installing Kubernetes on Master...
install_kubernetes

#Update the host file of the master.
echo Updating the host file...
update_hosts

#Create the Cluster
echo Setting up the Master using IPAddress: $machineip
setup_k8s_master

#Patching kube-proxy to run with --proxy-mode=userspace
echo Patching the kube-proxy for CNI Networks...
patch_kube_proxy

#Download the specs for the demo
echo Downloading samples for demo...
download_specs