text:
namespace boost { namespace process { namespace detail { namespace posix {

inline int execvpe(const char* filename, char * const arg_list[], char* env[])
{
#if defined(__GLIBC__)
    return ::execvpe(filename, arg_list, env);
#else
    //use my own implementation
    std::string fn = filename;
    if ((fn.find('/') == std::string::npos) && ::access(fn.c_str(), X_OK))
    {
        auto e = ::environ;
        while ((*e != nullptr) && !boost::starts_with(*e, "PATH="))
            e++;

        if (e != nullptr)
        {
            std::vector<std::string> path;
            boost::split(path, *e, boost::is_any_of(":"));

            for (const std::string & pp : path)
            {
                auto p = pp + "/" + filename;
                if (!::access(p.c_str(), X_OK))
                {
                    fn = p;
                    break;
                }
            }
        }
    }
    return ::execve(fn.c_str(), arg_list, env);
#endif
}

template<typename Executor>
struct on_setup_t
{
    Executor & exec;
    on_setup_t(Executor & exec) : exec(exec) {};
    template<typename T>
    void operator()(T & t) const
    {
        if (!exec.error())
            t.on_setup(exec);
    }
};

template<typename Executor>
struct on_error_t
{
    Executor & exec;
    const std::error_code & error;
    on_error_t(Executor & exec, const std::error_code & error) : exec(exec), error(error) {};
    template<typename T>
    void operator()(T & t) const
    {
        t.on_error(exec, error);
    }
};

template<typename Executor>
struct on_success_t
{
    Executor & exec;
    on_success_t(Executor & exec) : exec(exec) {};
    template<typename T>
    void operator()(T & t) const {t.on_success(exec);}
};

template<typename Executor>
struct on_fork_error_t
{
    Executor & exec;
    const std::error_code & error;
    on_fork_error_t(Executor & exec, const std::error_code & error) : exec(exec), error(error) {};

    template<typename T>
    void operator()(T & t) const
    {
        t.on_fork_error(exec, error);
    }
};

template<typename Executor>
struct on_exec_setup_t
{
    Executor & exec;
    on_exec_setup_t(Executor & exec) : exec(exec) {};

    template<typename T>
    void operator()(T & t) const
    {
        t.on_exec_setup(exec);
    }
};

template<typename Executor>
struct on_exec_error_t
{
    Executor & exec;
    const std::error_code &ec;
    on_exec_error_t(Executor & exec, const std::error_code & error) : exec(exec), ec(error) {};

    template<typename T>
    void operator()(T & t) const
    {
        t.on_exec_error(exec, ec);
    }
};

template<typename Executor>
struct on_fork_success_t
{
    Executor & exec;
    on_fork_success_t(Executor & exec) : exec(exec) {};

    template<typename T>
    void operator()(T & t) const
    {
        t.on_fork_success(exec);
    }
};

template<typename Executor> on_setup_t  <Executor> call_on_setup  (Executor & exec) {return exec;}
template<typename Executor> on_error_t  <Executor> call_on_error  (Executor & exec, const std::error_code & ec)
{
    return on_error_t<Executor> (exec, ec);
}
template<typename Executor> on_success_t<Executor> call_on_success(Executor & exec) {return exec;}

template<typename Executor> on_fork_error_t  <Executor> call_on_fork_error  (Executor & exec, const std::error_code & ec)
{
    return on_fork_error_t<Executor> (exec, ec);
}

template<typename Executor> on_exec_setup_t  <Executor> call_on_exec_setup  (Executor & exec) {return exec;}
template<typename Executor> on_exec_error_t  <Executor> call_on_exec_error  (Executor & exec, const std::error_code & ec)
{
    return on_exec_error_t<Executor> (exec, ec);
}

template<typename Sequence>
class executor
{
    template<typename HasHandler, typename UseVFork>
    void internal_error_handle(const std::error_code&, const char*, HasHandler, boost::mpl::true_, UseVFork) {}

    int _pipe_sink = -1;

    void write_error(const std::error_code & ec, const char * msg)
    {
        //I am the child
        int len = ec.value();
        ::write(_pipe_sink, &len, sizeof(int));

        len = std::strlen(msg) + 1;
        ::write(_pipe_sink, &len, sizeof(int));
        ::write(_pipe_sink, msg, len);
    }

    void internal_error_handle(const std::error_code &ec, const char* msg, boost::mpl::true_ , boost::mpl::false_, boost::mpl::false_)
    {
        if (this->pid == 0) //on the fork.
            write_error(ec, msg);
        else
        {
            this->_ec  = ec;
            this->_msg = msg;
        }
    }
    void internal_error_handle(const std::error_code &ec, const char* msg, boost::mpl::false_, boost::mpl::false_, boost::mpl::false_)
    {
        if (this->pid == 0)
            write_error(ec, msg);
        else
            throw process_error(ec, msg);
    }

    void internal_error_handle(const std::error_code &ec, const char* msg, boost::mpl::true_ , boost::mpl::false_, boost::mpl::true_)
    {
        this->_ec  = ec;
        this->_msg = msg;
    }
    void internal_error_handle(const std::error_code &ec, const char* msg, boost::mpl::false_, boost::mpl::false_, boost::mpl::true_)
    {
        if (this->pid == 0)
        {
            this->_ec  = ec;
            this->_msg = msg;
        }
        else
            throw process_error(ec, msg);
    }

    void check_error(boost::mpl::true_) {};
    void check_error(boost::mpl::false_)
    {
        if (_ec)
            throw process_error(_ec, _msg);
    }

    typedef typename ::boost::process::detail::has_error_handler<Sequence>::type has_error_handler;
    typedef typename ::boost::process::detail::has_ignore_error <Sequence>::type has_ignore_error;
    typedef typename ::boost::process::detail::posix::shall_use_vfork<Sequence>::type shall_use_vfork;

    inline child invoke(boost::mpl::true_ , boost::mpl::true_ );
    inline child invoke(boost::mpl::false_, boost::mpl::true_ );
    inline child invoke(boost::mpl::true_ , boost::mpl::false_ );
    inline child invoke(boost::mpl::false_, boost::mpl::false_ );
    void _write_error(int sink)
    {
        int data[2] = {_ec.value(),static_cast<int>(_msg.size())};
        while (::write(sink, &data[0], sizeof(int) *2) == -1)
        {
            auto err = errno;

            if (err == EBADF)
                return;
            else if ((err != EINTR) && (err != EAGAIN))
                break;
        }
        while (::write(sink, &_msg.front(), _msg.size()) == -1)
        {
            auto err = errno;

            if (err == EBADF)
                return;
            else if ((err != EINTR) && (err != EAGAIN))
                break;
        }
    }

    void _read_error(int source)
    {
        int data[2];

        _ec.clear();
        int count = 0;
        while ((count = ::read(source, &data[0], sizeof(int) *2 ) ) == -1)
        {
            //actually, this should block until it's read.
            auto err = errno;
            if ((err != EAGAIN ) && (err != EINTR))
                set_error(std::error_code(err, std::system_category()), "Error read pipe");
        }
        if (count == 0)
            return  ;

        std::error_code ec(data[0], std::system_category());
        std::string msg(data[1], ' ');

        while (::read(source, &msg.front(), msg.size() ) == -1)
        {
            //actually, this should block until it's read.
            auto err = errno;
            if ((err == EBADF) || (err == EPERM))//that should occur on success, therefore return.
                return;
                //EAGAIN not yet forked, EINTR interrupted, i.e. try again
            else if ((err != EAGAIN ) && (err != EINTR))
            {
                ::close(source);
                set_error(std::error_code(err, std::system_category()), "Error read pipe");
            }
        }
        ::close(source);
        set_error(ec, std::move(msg));
    }

    std::error_code _ec;
    std::string _msg;
public:
    executor(Sequence & seq) : seq(seq)
    {
    }

    child operator()()
    {
        return invoke(has_ignore_error(), shall_use_vfork());
    }

    Sequence & seq;
    const char * exe      = nullptr;
    char *const* cmd_line = nullptr;
    bool cmd_style = false;
    char **env      = ::environ;
    pid_t pid = -1;
    std::shared_ptr<std::atomic<int>> exit_status = std::make_shared<std::atomic<int>>(still_active);

    const std::error_code & error() const {return _ec;}

    void set_error(const std::error_code &ec, const char* msg)
    {
        internal_error_handle(ec, msg, has_error_handler(), has_ignore_error(), shall_use_vfork());
    }
    void set_error(const std::error_code &ec, const std::string &msg) {set_error(ec, msg.c_str());};

};

template<typename Sequence>
child executor<Sequence>::invoke(boost::mpl::true_, boost::mpl::false_) //ignore errors
{
    boost::fusion::for_each(seq, call_on_setup(*this));
    if (_ec)
        return child();

    this->pid = ::fork();
    if (pid == -1)
    {
        auto ec = boost::process::detail::get_last_error();
        boost::fusion::for_each(seq, call_on_fork_error(*this, ec));
        return child();
    }
    else if (pid == 0)
    {
        boost::fusion::for_each(seq, call_on_exec_setup(*this));
        if (cmd_style)
            ::boost::process::detail::posix::execvpe(exe, cmd_line, env);
        else
            ::execve(exe, cmd_line, env);
        auto ec = boost::process::detail::get_last_error();
        boost::fusion::for_each(seq, call_on_exec_error(*this, ec));
        _exit(EXIT_FAILURE);
    }

    child c(child_handle(pid), exit_status);

    boost::fusion::for_each(seq, call_on_success(*this));

    return c;
}

template<typename Sequence>
child executor<Sequence>::invoke(boost::mpl::false_, boost::mpl::false_)
{
    int p[2];
    if (::pipe(p)  == -1)
    {
        set_error(::boost::process::detail::get_last_error(), "pipe(2) failed");
        return child();
    }
    if (::fcntl(p[1], F_SETFD, FD_CLOEXEC) == -1)
    {
        auto err = ::boost::process::detail::get_last_error();
        ::close(p[0]);
        ::close(p[1]);
        set_error(err, "fcntl(2) failed");
        return child();
    }
    _ec.clear();
    boost::fusion::for_each(seq, call_on_setup(*this));

    if (_ec)
    {
        boost::fusion::for_each(seq, call_on_error(*this, _ec));
        return child();
    }

    this->pid = ::fork();
    if (pid == -1)
    {
        _ec = boost::process::detail::get_last_error();
        _msg = "fork() failed";
        boost::fusion::for_each(seq, call_on_fork_error(*this, _ec));
        boost::fusion::for_each(seq, call_on_error(*this, _ec));

        return child();
    }
    else if (pid == 0)
    {
        _pipe_sink = p[1];
        ::close(p[0]);

        boost::fusion::for_each(seq, call_on_exec_setup(*this));
        if (cmd_style)
            ::boost::process::detail::posix::execvpe(exe, cmd_line, env);
        else
            ::execve(exe, cmd_line, env);
        _ec = boost::process::detail::get_last_error();
        _msg = "execve failed";
        boost::fusion::for_each(seq, call_on_exec_error(*this, _ec));

        _write_error(p[1]);

        _exit(EXIT_FAILURE);
        return child();
    }

    child c(child_handle(pid), exit_status);

    ::close(p[1]);
    _read_error(p[0]);

    if (_ec)
    {
        boost::fusion::for_each(seq, call_on_error(*this, _ec));
        return child();
    }
    else
        boost::fusion::for_each(seq, call_on_success(*this));

    if (_ec)
    {
        boost::fusion::for_each(seq, call_on_error(*this, _ec));
        return child();
    }

    return c;
}

#if BOOST_POSIX_HAS_VFORK

template<typename Sequence>
child executor<Sequence>::invoke(boost::mpl::true_, boost::mpl::true_) //ignore errors
{
    boost::fusion::for_each(seq, call_on_setup(*this));
    if (_ec)
        return child();
    this->pid = ::vfork();
    if (pid == -1)
    {
        auto ec = boost::process::detail::get_last_error();
        boost::fusion::for_each(seq, call_on_fork_error(*this, ec));
        return child();
    }
    else if (pid == 0)
    {
        boost::fusion::for_each(seq, call_on_exec_setup(*this));
        ::execve(exe, cmd_line, env);
        auto ec = boost::process::detail::get_last_error();
        boost::fusion::for_each(seq, call_on_exec_error(*this, ec));
        _exit(EXIT_FAILURE);
    }
    child c(child_handle(pid), exit_status);

    boost::fusion::for_each(seq, call_on_success(*this));

    return c;
}

template<typename Sequence>
child executor<Sequence>::invoke(boost::mpl::false_, boost::mpl::true_)
{
    boost::fusion::for_each(seq, call_on_setup(*this));

    if (_ec)
    {
        boost::fusion::for_each(seq, call_on_error(*this, _ec));
        return child();
    }
    _ec.clear();

    this->pid = ::vfork();
    if (pid == -1)
    {
        _ec = boost::process::detail::get_last_error();
        _msg = "fork() failed";
        boost::fusion::for_each(seq, call_on_fork_error(*this, _ec));
        boost::fusion::for_each(seq, call_on_error(*this, _ec));

        return child();
    }
    else if (pid == 0)
    {
        boost::fusion::for_each(seq, call_on_exec_setup(*this));

        if (cmd_style)
            ::boost::process::detail::posix::execvpe(exe, cmd_line, env);
        else
            ::execve(exe, cmd_line, env);

        _ec = boost::process::detail::get_last_error();
        _msg = "execve failed";
        boost::fusion::for_each(seq, call_on_exec_error(*this, _ec));

        _exit(EXIT_FAILURE);
        return child();
    }
    child c(child_handle(pid), exit_status);

    check_error(has_error_handler());

    if (_ec)
    {
        boost::fusion::for_each(seq, call_on_error(*this, _ec));
        return child();
    }
    else
        boost::fusion::for_each(seq, call_on_success(*this));

    if (_ec)
    {
        boost::fusion::for_each(seq, call_on_error(*this, _ec));
        return child();
    }

    return c;
}

#endif

template<typename Char, typename Tup>
inline executor<Tup> make_executor(Tup & tup)
{
    return executor<Tup>(tup);
}

}}}}

#endif


text:
/* Author: Ryu Woon Jung (Leon) */

//
// *********     broadcastPing Example      *********
//
//
// Available Dynamixel model on this example : All models using Protocol 2.0
// This example is designed for using a Dynamixel PRO 54-200, and an USB2DYNAMIXEL.
// To use another Dynamixel model, such as X series, see their details in E-Manual(emanual.robotis.com) and edit below "#define"d variables yourself.
// Be sure that Dynamixel PRO properties are already set as %% ID : 1 / Baudnum : 1 (Baudrate : 57600)
//

#if defined(__linux__) || defined(__APPLE__)
#include <fcntl.h>
#include <termios.h>
#define STDIN_FILENO 0
#elif defined(_WIN32) || defined(_WIN64)
#include <conio.h>
#endif

#include <stdio.h>
#include "dynamixel_sdk.h"                                  // Uses Dynamixel SDK library

// Protocol version
#define PROTOCOL_VERSION                2.0                 // See which protocol version is used in the Dynamixel

// Default setting
#define BAUDRATE                        57600
#define DEVICENAME                      "/dev/ttyUSB0"      // Check which port is being used on your controller
                                                            // ex) Windows: "COM1"   Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"

int getch()
{
#if defined(__linux__) || defined(__APPLE__)
  struct termios oldt, newt;
  int ch;
  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  ch = getchar();
  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  return ch;
#elif defined(_WIN32) || defined(_WIN64)
  return _getch();
#endif
}

int kbhit(void)
{
#if defined(__linux__) || defined(__APPLE__)
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if (ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
#elif defined(_WIN32) || defined(_WIN64)
  return _kbhit();
#endif
}

int main()
{
  // Initialize PortHandler Structs
  // Set the port path
  // Get methods and members of PortHandlerLinux or PortHandlerWindows
  int port_num = portHandler(DEVICENAME);

  // Initialize PacketHandler Structs
  packetHandler();

  int dxl_comm_result = COMM_TX_FAIL; // Communication result
  int id;

  // Open port
  if (openPort(port_num))
  {
    printf("Succeeded to open the port!\n");
  }
  else
  {
    printf("Failed to open the port!\n");
    printf("Press any key to terminate...\n");
    getch();
    return 0;
  }

  // Set port baudrate
  if (setBaudRate(port_num, BAUDRATE))
  {
    printf("Succeeded to change the baudrate!\n");
  }
  else
  {
    printf("Failed to change the baudrate!\n");
    printf("Press any key to terminate...\n");
    getch();
    return 0;
  }

  // Try to broadcast ping the Dynamixel
  broadcastPing(port_num, PROTOCOL_VERSION);
  if ((dxl_comm_result = getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
    printf("%s\n", getTxRxResult(PROTOCOL_VERSION, dxl_comm_result));

  printf("Detected Dynamixel : \n");
  for (id = 0; id < MAX_ID; id++)
  {
    if (getBroadcastPingResult(port_num, PROTOCOL_VERSION, id))
      printf("[ID:%03d]\n", id);
  }

  // Close port
  closePort(port_num);

  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
namespace seed
{
    class PhysicsListener : public b2ContactListener
    {
    public:

        PhysicsListener();
        virtual ~PhysicsListener();

        void Init(View* in_view, BodyMap* in_bodyMap);

        //  b2ContactListener
        // Called when two fixtures begin to touch
        virtual void BeginContact(b2Contact* contact);

        // Called when two fixtures cease to touch
        virtual void EndContact(b2Contact* contact);

    private:

        // view we call for callbacks
        View*       m_view;

        // Map of bodies to match collisions with Nodes
        BodyMap*    m_bodies;

        Node*           GetNodeFromPhysicsBody(PhysicsBody* in_body);
        PhysicsBody*    GetPhysicsBodyFromB2Body(b2Body* in_body);

    };
}


text:
import numpy as np
import matplotlib.pyplot as plt
import glob
import re
import sqlite3
import helper
import addline

def plotWeakScaling(allsize=1000000,allgraphtype='SOFTWARE',alladditionalwhere=' AND total_time>0 ',suffix='',basesize=100000, title=''):
	fig = plt.figure()
	ax = fig.add_subplot(111)
	#addline.addWeakScaling(axis=ax, algorithm='dynamic_nobarrier', optimistic='1', size=basesize, graphtype=allgraphtype, hostnamelike='e%',colorindex=0,linelabel='DynNoBarrier')
	addline.addWeakScaling(axis=ax, algorithm='bitset', optimistic='1', size=basesize, graphtype=allgraphtype, hostnamelike='e%',colorindex=0,linelabel='Node-Lookup')
	addline.addWeakScaling(axis=ax, algorithm='worksteal', optimistic='1', size=basesize, graphtype=allgraphtype, hostnamelike='e%',colorindex=1,linelabel='Worksteal')
	addline.addWeakScaling(axis=ax, algorithm='locallist', optimistic='1', size=basesize, graphtype=allgraphtype, hostnamelike='e%',colorindex=2,linelabel='Scatter-Gather')
	ax.plot([1,24],[1,1],'r--')
	ax.legend(loc='upper right')
	ax.minorticks_on()

	filename = helper.plotdir + 'weakscaling_gt' + allgraphtype + '_n' + str(allsize)

	plt.title('Speedup vs. Number of Threads',fontsize=helper.fontsize_label)
	if(title!=''):
		plt.suptitle(title,fontsize=helper.fontsize_title)
	elif(suffix==''):
		plt.suptitle('Weak Scaling for ' + allgraphtype + ' Graph (' + str(allsize) + 'nodes)',fontsize=helper.fontsize_title)
	else:
		plt.suptitle('Weak Scaling for ' + allgraphtype + ' Graph (' + str(allsize) + 'nodes, ' + suffix + ')',fontsize=helper.fontsize_title)

	if(suffix!=''):
		filename = filename + '_' + suffix

	filename = filename + '.pdf'

	plt.savefig(filename, format='pdf',bbox_inches='tight',dpi=1000)
	print "File written to:\t", filename
	if(helper.show):
		plt.show()

############################################################
# Call Plotting functions
############################################################
plotWeakScaling(allsize=1000000,allgraphtype='SOFTWARE',title='Weak scaling for Software graph (basesize 100k nodes)') # software graph
plotWeakScaling(allsize=1000000,allgraphtype='RANDOMLIN8',suffix='deg8',title='Weak scaling for Random graph (basesize 100k nodes, degree 8)') # degree 8
plotWeakScaling(allsize=1000000,allgraphtype='RANDOMLIN16',suffix='deg16',title='Weak scaling for Random graph (basesize 100k nodes, degree 16)') # degree 16
plotWeakScaling(allsize=1000000,allgraphtype='RANDOMLIN32',suffix='deg32',title='Weak scaling for Random graph (basesize 100k nodes, degree 32)') # degree 32
# degree 64 has incomplete data


text:
Helping people send others a compliment through social channels.

## Resources

* [Google Drive](https://drive.google.com/drive/folders/0B3UW6L02gf94elNtNWNZd2xzaVU)

* [Github](https://github.com/enspiral-craftworks/project-positive/blob/gh-pages/index.html)

* [http://project-positive.org.nz/](http://project-positive.org.nz/)

* Hashtags: #projectpositivenz #chainofpositivity #nationalcomplimentsday #21daysofkindness (#projectpositivenz OR #chainofpositivity OR #nationalcomplimentsday OR #21daysofkindness)

* Colours: Green is R 166  G 207  B 59 (A6CF3B), Yellow is R 254  G 230  B 0 (FEE600)

* Run Python server: python -m SimpleHTTPServer

---

* [Facebook](https://www.facebook.com/heyawesome)

* [Facebook developers ares for displaying feed](https://developers.facebook.com/docs/plugins/page-plugin)

---

* [Twitter](https://www.twitter.com/projectposnz)

* [Twitter developers area for displaying hashtag feed](https://twitter.com/settings/widgets/696444575154462720)

* [Advanced display options for twitter feed](https://dev.twitter.com/web/embedded-timelines#customization)

---

* [Instagram](https://www.instagram.com/projectpositivenz)

* [Instafeed docs](http://instafeedjs.com/)

* [Instafeed multiple hashtags hack](https://github.com/stevenschobert/instafeed.js/issues/12)


text:
var AWS = require('aws-sdk'); //Provided by lambda (no need to install)

var async = require('async');
var gm = require('gm')
.subClass({ imageMagick: true }); // Enable ImageMagick integration.
var util = require('util');
var fs   = require("fs");
var path = require("path");

// get reference to S3 client
var s3 = new AWS.S3();

exports.handler = function(event, context) {

  // Load config.json
  var configPath = path.resolve(__dirname, "config.json");
  var config = JSON.parse(fs.readFileSync(configPath, { encoding: "utf8" }));

  // Read options from the event.
  console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
  var srcBucket = event.Records[0].s3.bucket.name;
  var srcKey    = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
  var dstBucket = config.dstBucket; //from config.json
  var dstKey    = srcKey;

  // Sanity check: validate that source and destination are different buckets.
  if (srcBucket == dstBucket) {
    console.error("Destination bucket must not match source bucket.");
    return;
  }

  var thumbs = config.thumbs; // From config.json

  var thumbs2 = thumbs; // Take a copy to iterate, but leave original alone

  for (var i=0,  tot=thumbs2.length; i < tot; i++) {

    async.waterfall(
      [

        function download(next) {
          // Download the image from S3 into a buffer.
          s3.getObject(
            {
              Bucket: srcBucket,
              Key: srcKey
            },
            next
          );
        },

        function getFormat(response, next) {
          gm(response.Body).format(function (err, format) {
            // console.log('Format: '+ format);
            next(null, format, response);
          });
        },

        function transform(imageType, response, next) {

          // console.log('imageType: '+ imageType);
          var current_thumb = thumbs.pop();

          if(current_thumb.type=='thumbnail'){

            if (typeof current_thumb.geometry == 'undefined') current_thumb.geometry = '960x540';

            console.log('Thumbnail '+ current_thumb.geometry);

            gm(response.Body)
            .autoOrient()
            .noProfile()
            .command('convert')
            .out('-quality', 95)
            .out('-gravity', 'center')
            .out('-resize', current_thumb.geometry+'^')
            .out('-crop', current_thumb.geometry+'+0+0')
            .toBuffer(imageType, function(err, buffer) {
              if (err) {
                next(err);
              } else {
                next(null, response.ContentType, buffer, current_thumb.folder);
              }
            });

          } else if(current_thumb.type=='resize'){

            if (typeof current_thumb.width == 'undefined') current_thumb.width = null;
            if (typeof current_thumb.height == 'undefined') current_thumb.height = null;

            console.log('Resize '+ current_thumb.width + 'x' + current_thumb.height);

            gm(response.Body)
            .resize(current_thumb.width, current_thumb.height)
            .toBuffer(imageType, function(err, buffer) {
              if (err) {
                next(err);
              } else {
                next(null, response.ContentType, buffer, current_thumb.folder);
              }
            });
          }

        },

        function upload(contentType, data, folder, next) {
          // Stream the transformed image to a different S3 bucket.
          console.log('Uploading '+ folder + '/' + dstKey);
          s3.putObject(
            {
              Bucket: dstBucket,
              Key: folder + '/' + dstKey,
              Body: data,
              ContentType: contentType
            },
            next
          );
        }

      ],

      function (err) {

        if (err) {
          console.error(
            'Unable to resize ' + srcBucket + '/' + srcKey +
            ' and upload to ' + dstBucket + '/' + dstKey +
            ' due to an error: ' + err
          );
        } else {
          console.log(
            'Successfully resized ' + srcBucket + '/' + srcKey +
            ' and uploaded to ' + dstBucket + '/' + dstKey
          );
        }

        //callback(null, "message");
      }
    );

  }

};


text:
static const int ddLogLevel = LOG_LEVEL_DEBUG;
#else
static const int ddLogLevel = LOG_LEVEL_WARN;
#endif

@interface FourEdPodcastManager ()

@property (nonatomic, strong) LjsFetchRequestFactory *fac;
- (void) populateWithRaces;
- (void) populateWithRoles;
- (void) populateWithClasses;
- (void) populateWithPlayers;
- (void) populateWithPodcasts;
- (void) populateWithCriticalHit;

- (DndCharacter *) characterWithName:(NSString *) characterName
                   andKeysForPodcast:(NSString *) aPodcast
                              player:(NSString *) aPlayer
                                role:(NSString *) aRole
                               class:(NSString *) aClass
                                race:(NSString *) aRace;

@end

@implementation FourEdPodcastManager

@synthesize context;
@synthesize fac;

#pragma mark Memory Management

- (id) init {
 //  [self doesNotRecognizeSelector:_cmd];
  return nil;
}

- (id) initWithContext:(NSManagedObjectContext *)aContext {
  self = [super init];
  if (self) {
    self.context = aContext;
    self.fac = [LjsFetchRequestFactory new];
    [self populateWithRaces];
    [self populateWithRoles];
    [self populateWithClasses];
    [self populateWithPlayers];
    [self populateWithPodcasts];
    [self populateWithCriticalHit];
  }
  return self;
}

- (void) populateWithRaces {
  NSArray *races = [NSArray arrayWithObjects:@"Half-Orc", @"Half-Elf",
                    @"Eladrin", @"Human", @"Elf", nil];
  __weak NSManagedObjectContext *weakCon = self.context;
  [races mapc:^(NSString *name, NSUInteger idx, BOOL *stop) {
    DndRace *race = (DndRace *)[DndRace insertInManagedObjectContext:weakCon];
    race.displayName = name;
    race.key = [[name lowercaseString] makeKeyword];
  }];
  [self saveContext:self.context];
}

- (void) populateWithRoles {
  NSArray *roles = [NSArray arrayWithObjects:@"Striker", @"Leader",
                    @"Defender", @"Controller", nil];
  __weak NSManagedObjectContext *weakCon = self.context;
  [roles mapc:^(NSString *name, NSUInteger idx, BOOL *stop) {
    DndRole *role = (DndRole *)[DndRole insertInManagedObjectContext:weakCon];
    role.displayName = name;
    role.key = [[name lowercaseString] makeKeyword];
  }];
  [self saveContext:self.context];
}

- (void) populateWithClasses {
  NSArray *classes = [NSArray arrayWithObjects:@"Sword Mage", @"Warlock",
                    @"Artificer", @"Fighter", @"Ranger", nil];
  __weak NSManagedObjectContext *weakCon = self.context;
  [classes mapc:^(NSString *name, NSUInteger idx, BOOL *stop) {
    DndClass *charClass = (DndClass *)[DndClass insertInManagedObjectContext:weakCon];
    charClass.displayName = name;
    charClass.key = [[name lowercaseString] makeKeyword];
  }];
  [self saveContext:self.context];
}

- (void) populateWithPlayers {
  NSArray *players = [NSArray arrayWithObjects:@"Stephen", @"Rob",
                      @"Matthew", @"Brian", @"Adriana", nil];
  __weak NSManagedObjectContext *weakCon = self.context;
  [players mapc:^(NSString *name, NSUInteger idx, BOOL *stop) {
    DndPlayer *player = (DndPlayer *)[DndPlayer insertInManagedObjectContext:weakCon];
    player.firstName = name;
    player.key = [[name lowercaseString] makeKeyword];
  }];
  [self saveContext:self.context];
}

- (void) populateWithPodcasts {
  NSArray *podcasts = [NSArray arrayWithObjects:@"Critical Hit", @"Crimison Bastards", nil];
  __weak NSManagedObjectContext *weakCon = self.context;
  [podcasts mapc:^(NSString *name, NSUInteger idx, BOOL *stop) {
    DndPodcast *podcast = (DndPodcast *)[DndPodcast insertInManagedObjectContext:weakCon];
    podcast.displayName = name;
    podcast.key = [[[name lowercaseString] makeKeyword] stringByReplacingOccurrencesOfString:@" "
                                                                                withString:@"-"];
  }];
  [self saveContext:self.context];
}

- (DndCharacter *) characterWithName:(NSString *) aCharacterName
                   andKeysForPodcast:(NSString *) aPodcast
                              player:(NSString *) aPlayer
                                role:(NSString *) aRole
                               class:(NSString *) aClass
                                race:(NSString *) aRace {
  NSError *error = nil;
  NSFetchRequest *req;
  NSArray *fetched;

  // get podcast
  error = nil;
  req = [NSFetchRequest fetchRequestWithEntityName:[DndPodcast entityName]];
  req.predicate = [self.fac predicateForKey:aPodcast];
  fetched = [self.context executeFetchRequest:req error:&error];
  DndPodcast *podcast = [fetched first];

  // get matthew
  error = nil;
  req = [NSFetchRequest fetchRequestWithEntityName:[DndPlayer entityName]];
  req.predicate = [self.fac predicateForKey:aPlayer];
  fetched = [self.context executeFetchRequest:req error:&error];
  DndPlayer *player = [fetched first];
  player.podcast = podcast;

  error = nil;
  req = [NSFetchRequest fetchRequestWithEntityName:[DndRole entityName]];
  req.predicate = [self.fac predicateForKey:aRole];
  fetched = [self.context executeFetchRequest:req error:&error];
  DndRole *role = [fetched first];

  error = nil;
  req = [NSFetchRequest fetchRequestWithEntityName:[DndClass entityName]];
  req.predicate = [self.fac predicateForKey:aClass];
  fetched = [self.context executeFetchRequest:req error:&error];
  DndClass *charClass = [fetched first];

  error = nil;
  req = [NSFetchRequest fetchRequestWithEntityName:[DndRace entityName]];
  req.predicate = [self.fac predicateForKey:aRace];
  fetched = [self.context executeFetchRequest:req error:&error];
  DndRace *race = [fetched first];

  DndCharacter *character = (DndCharacter *)[DndCharacter insertInManagedObjectContext:self.context];
  character.name = aCharacterName;
  character.key = [[aCharacterName lowercaseString] makeKeyword];
  character.player = player;
  character.role = role;
  character.charClass = charClass;
  character.race = race;
  [self saveContext:self.context];
  return character;

}

- (void) populateWithCriticalHit {
  [self characterWithName:@"Torque"
        andKeysForPodcast:@":critical-hit"
                   player:@":matthew"
                     role:@":defender"
                    class:@":fighter"
                     race:@":half-orc"];

  [self characterWithName:@"Orem"
        andKeysForPodcast:@":critical-hit"
                   player:@":stephen"
                     role:@":stricker"
                    class:@":sword-mage"
                     race:@":eladrin"];

  [self characterWithName:@"Randis"
        andKeysForPodcast:@":critical-hit"
                   player:@":brian"
                     role:@":controller"
                    class:@":artificer"
                     race:@":human"];

  [self characterWithName:@"Ket"
        andKeysForPodcast:@":critical-hit"
                   player:@":rob"
                     role:@":controller"
                    class:@":warlock"
                     race:@":half-elf"];

  [self characterWithName:@"Trell"
        andKeysForPodcast:@":critical-hit"
                   player:@":adriana"
                     role:@":stricker"
                    class:@":ranger"
                     race:@":elf"];
  [self saveContext:self.context];
}

- (void) saveContext:(NSManagedObjectContext *)aContext {
  NSError *error = nil;
  if (aContext != nil) {
    if ([aContext hasChanges] && ![aContext save:&error]) {
      // Replace this implementation with code to handle the error appropriately.
      // abort() causes the application to generate a crash log and terminate.
      // You should not use this function in a shipping application, although it
      // may be useful during development.
      DDLogFatal(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
    }
  }
}

@end


text:
        Operator

      <os-select ng-model="queryLocal.currFilter.op"
        list="queryLocal.currFilter.ops" display-prop="desc"
        placeholder="{{'queries.select_op' | translate}}"
        on-change="onOpSelect">
      </os-select>

        Condition Value

          <os-select ng-model="queryLocal.currFilter.value"
            list="queryLocal.currFilter.field.pvs"
            placeholder="{{'queries.select_cond_value' | translate}}">
          </os-select>

          <os-select multiple
            ng-model="queryLocal.currFilter.value"
            list="queryLocal.currFilter.field.pvs"
            placeholder="{{'queries.select_cond_values' | translate}}">
          </os-select>

          <os-tags tags="queryLocal.currFilter.value"
            placeholder="{{'queries.specify_multiple_cond' | translate}}">
          </os-tags>

          <input class="form-control" placeholder="{{'queries.range_min' | translate}}"
            type="text" os-query-date-picker="{{global.queryDateFmt}}"
            ng-model="queryLocal.currFilter.value[0]">
          and
          <input class="form-control" placeholder="{{'queries.range_max' | translate}}"
            type="text" os-query-date-picker="{{global.queryDateFmt}}"
            ng-model="queryLocal.currFilter.value[1]">

          <input class="form-control" placeholder="{{'queries.range_min' | translate}}"
            type="text" ng-model="queryLocal.currFilter.value[0]">
          and
          <input class="form-control" placeholder="{{'queries.range_max' | translate}}"
            type="text" ng-model="queryLocal.currFilter.value[1]">

          <input type="hidden"
            os-lookup opts="queryLocal.currFilter.field.lookupProps"
            placeholder="{{'queries.select_cond_value' | translate}}"
            ng-model="queryLocal.currFilter.value">
          </input>

          <input type="hidden"
            os-lookup opts="queryLocal.currFilter.field.lookupProps" multiple
            placeholder="{{'queries.select_cond_values' | translate}}"
            ng-model="queryLocal.currFilter.value">
          </input>

        <input ng-switch-when="datePicker" class="form-control"
          placeholder="{{'queries.select_date' | translate}}"
          type="text" os-query-date-picker="{{global.queryDateFmt}}"
          ng-model="queryLocal.currFilter.value"></input>
        <input ng-switch-default class="form-control"
          placeholder="{{'queries.specify_cond' | translate}}"
          type="text" ng-model="queryLocal.currFilter.value">
        </input>

        <input type="checkbox" ng-model="queryLocal.currFilter.parameterized"
          ng-checked="queryLocal.currFilter.parameterized">
          Parameterized Filter

      <button class="btn btn-success" ng-disabled="disableAddEditFilterBtn()"
        ng-click="addFilter()" ng-if="!queryLocal.currFilter.id" translate="common.buttons.add">
        Add
      </button>
      <button class="btn btn-success" ng-disabled="disableAddEditFilterBtn()"
        ng-click="editFilter()" ng-if="queryLocal.currFilter.id" translate="common.buttons.edit">
        Edit
      </button>
      <button class="btn btn-default" ng-click="cancelFilter()" translate="common.buttons.cancel">
        Cancel
      </button>


text:
package com.jcwhatever.pvs.api.stats;

import javax.annotation.Nullable;
import java.util.List;
import java.util.UUID;

/**
 * Manages statistics data storage and statistic types.
 */
public interface IStatsManager {

    /**
     * Register a statistic type.
     *
     * @param type  The statistic type.
     */
    void registerType(StatType type);

    /**
     * Get available statistic types.
     */
    List<StatType> getTypes();

    /**
     * Get a statistic type by name.
     *
     * @param name  The name of the statistic.
     */
    @Nullable
    StatType getType(String name);

    /**
     * Get statistics for an arena.
     *
     * @param arenaId  The ID of the arena.
     */
    IArenaStats getArenaStats(UUID arenaId);

    /**
     * Create a new statistics filter.
     */
    IStatsFilter createFilter();
}


text:
import numpy as np
import heapq

from algorithm import BaseAlgorithm

'''
baseClass for an algorithm

author :Alexis Fossart
date :  08/10/2017

Abstract base class used to represent an algorithm
'''

class NaiveAlgorithm(BaseAlgorithm):

    @staticmethod
    def execute(query, inverted_file, number_of_results):
        '''
        we do a niave search in the corpus
        the score of each documents are added to create the final score for the search
        :param query: the query you want to look up
        :param inverted_file: the inverted file representing your corpus
        :param number_of_results: the desired number of results
        :return: the documents containing all of the terms in the query
        '''
        searched_terms = query.split()

        mapping_documents_scores = dict()

        # for each document returned by the parrallel scan we keep its score
        for (doc_id, score) in inverted_file.parallel_scan(searched_terms):
            if doc_id not in mapping_documents_scores:
                mapping_documents_scores[doc_id] = []
            mapping_documents_scores[doc_id].append(score)

        if len(mapping_documents_scores) == 0:
            return None

        results = []

        kept = []

        for(doc_id, scores) in mapping_documents_scores.items():
            if 0 not in scores:
                kept.append(doc_id)

        # for each document we push it and its score to a heapq
        for doc_id in kept:
            heapq.heappush(results, (np.sum(mapping_documents_scores[doc_id]), doc_id))

        # to use heapq we had to inverse doc_id and score in the tuples so we reverse them back during return
        return [(t[1], t[0]) for t in heapq.nlargest(number_of_results, results)]


text:
#ifndef __BTRFS_FREE_SPACE_CACHE_H__
#define __BTRFS_FREE_SPACE_CACHE_H__

#include "kerncompat.h"
#include "ctree.h"
#include "rbtree.h"

struct btrfs_free_space {
	struct rb_node offset_index;
	u64 offset;
	u64 bytes;
	unsigned long *bitmap;
	struct list_head list;
};

struct btrfs_free_space_ctl {
	struct rb_root free_space_offset;
	u64 free_space;
	int extents_thresh;
	int free_extents;
	int total_bitmaps;
	int unit;
	u64 start;
	void *private;
	u32 sectorsize;
};

int load_free_space_cache(struct btrfs_fs_info *fs_info,
			  struct btrfs_block_group_cache *block_group);

void __btrfs_remove_free_space_cache(struct btrfs_free_space_ctl *ctl);
void btrfs_remove_free_space_cache(struct btrfs_block_group_cache
				     *block_group);
void btrfs_dump_free_space(struct btrfs_block_group_cache *block_group,
			   u64 bytes);
struct btrfs_free_space *
btrfs_find_free_space(struct btrfs_free_space_ctl *ctl, u64 offset, u64 bytes);
int btrfs_init_free_space_ctl(struct btrfs_block_group_cache *block_group,
			      int sectorsize);
void unlink_free_space(struct btrfs_free_space_ctl *ctl,
		       struct btrfs_free_space *info);
int btrfs_add_free_space(struct btrfs_free_space_ctl *ctl, u64 offset,
			 u64 bytes);
#endif


text:
<!DOCTYPE HTML>

   <meta charset="UTF-8">
   <link href="/favicon.png" rel="icon" type="image/x-icon" />
   <title>Wheel Server Test Page</title>

Wheel Server

Yet another toy HTTP server

Learning how wheels work by reinventing the wheel

Copyright © Bing Lu 2014


text:
<?php

abstract class InstallControllerConsole
{
	/**
	 * @var array List of installer steps
	 */
	protected static $steps = array('process');

	protected static $instances = array();

	/**
	 * @var string Current step
	 */
	public $step;

	/**
	 * @var array List of errors
	 */
	public $errors = array();

	/**
	 * @var InstallController
	 */
	public $controller;

	/**
	 * @var InstallSession
	 */
	public $session;

	/**
	 * @var InstallLanguages
	 */
	public $language;

	/**
	 * @var InstallAbstractModel
	 */
	public $model;

	/**
	 * Validate current step
	 */
	abstract public function validate();

	final public static function execute($argc, $argv)
	{
		if (!($argc-1))
		{
			$available_arguments = Datas::getInstance()->getArgs();
			echo 'Arguments available:'."\n";
			foreach ($available_arguments as $key => $arg)
			{
				$name = isset($arg['name']) ? $arg['name'] : $key;
				echo '--'.$name."\t".(isset($arg['help']) ? $arg['help'] : '').(isset($arg['default']) ? "\t".'(Default: '.$arg['default'].')' : '')."\n";
			}
			exit;
		}

		$errors = Datas::getInstance()->getAndCheckArgs($argv);
		if (Datas::getInstance()->show_license)
		{
			echo strip_tags(file_get_contents(_PS_INSTALL_PATH_.'theme/views/license_content.phtml'));
			exit;
		}

		if ($errors !== true)
		{
			if (count($errors))
				foreach ($errors as $error)
					echo $error."\n";
			exit;
		}

		// Include all controllers
		foreach (self::$steps as $step)
		{
			if (!file_exists(_PS_INSTALL_CONTROLLERS_PATH_.'console/'.$step.'.php'))
				throw new PrestashopInstallerException("Controller file 'console/{$step}.php' not found");

			require_once _PS_INSTALL_CONTROLLERS_PATH_.'console/'.$step.'.php';
			$classname = 'InstallControllerConsole'.$step;
			self::$instances[$step] = new $classname($step);
		}

		$datas = Datas::getInstance();

		/* redefine HTTP_HOST  */
		$_SERVER['HTTP_HOST'] = $datas->http_host;

		@date_default_timezone_set($datas->timezone);

		if (!$current_step = $datas->step)
			return false;

		self::$instances[$current_step]->process();
	}

	final public function __construct($step)
	{
		$this->step = $step;
		$this->datas = Datas::getInstance();

		// Set current language
		$this->language = InstallLanguages::getInstance();
		if (!$this->datas->language)
			die('No language defined');
		$this->language->setLanguage($this->datas->language);

		$this->init();
	}

	/**
	 * Initialize model
	 */
	public function init()
	{
	}

	public function printErrors()
	{
		$errors = $this->model_install->getErrors();
		if (count($errors))
		{
			if (!is_array($errors))
				$errors = array($errors);
			echo 'Errors :'."\n";
			foreach ($errors as $error_process)
				foreach ($error_process as $error)
					echo $error."\n";
			die;
		}
	}

	/**
	 * Get translated string
	 *
	 * @param string $str String to translate
	 * @param ... All other params will be used with sprintf
	 * @return string
	 */
	public function l($str)
	{
		$args = func_get_args();
		return call_user_func_array(array($this->language, 'l'), $args);
	}

	public function process()
	{
	}
}


text:
const {describe, it} = global;

import {expect} from 'chai';
import sinon from 'sinon';
import {spy} from 'sinon';
import actions from '../todo';

/**
 * Test suite for all actions
 */

describe('Actions', () => {
  describe('Closecard', () => {
    it('should get FINISH COUNT and its value 1', () => {
      const LocalState = {set: spy(), get: sinon.stub()};
      actions.closecard({LocalState},'some',true);
      var args = LocalState.set.args[1][0];
      expect(args).to.be.equal('FINISHCOUNT');
      args = LocalState.set.args[1][1];
      expect(args).to.be.equal(1);
    });
  });
  describe('Closecard', () => {
    it('should get FINISH', () => {
      const LocalState = {set: spy(), get: sinon.stub()};
      actions.closecard({LocalState},'some',true);
      const args = LocalState.set.args[0][0];
      expect(args).to.be.equal('FINISH');
    });
  });
  describe('Delete all', () => {
    it('should get Name as empty', () => {
      const LocalState = {set: spy(), get: sinon.stub()};
      actions.delall({LocalState});
      var args = LocalState.set.args[0][0];
      expect(args).to.be.equal('NAME');
      args = LocalState.set.args[0][1];
      expect(args.length).to.be.equal(0);
    });
    it('should get ALL COUNT as empty', () => {
      const LocalState = {set: spy(), get: sinon.stub()};
      actions.delall({LocalState});
      var args = LocalState.set.args[1][0];
      expect(args).to.be.equal('ALLCOUNT');
      args = LocalState.set.args[1][1];
      expect(args).to.be.equal(0);
    });
    it('should get FINISH COUNT as empty', () => {
      const LocalState = {set: spy(), get: sinon.stub()};
      actions.delall({LocalState});
      var args = LocalState.set.args[2][0];
      expect(args).to.be.equal('FINISHCOUNT');
      args = LocalState.set.args[2][1];
      expect(args).to.be.equal(0);
    });
  });
});


text:
class CdsAdvice < AccessBrowserV2
  include Singleton
  def initialize
    super
    add_verify(CucumberLabel.new("Priority"), VerifyContainsText.new, AccessHtmlElement.new(:id, "cds_advice-undefined"))
    add_verify(CucumberLabel.new("Title"), VerifyText.new, AccessHtmlElement.new(:id, "cds_advice-title"))
    add_verify(CucumberLabel.new("Details"), VerifyText.new, AccessHtmlElement.new(:id, "cds_advice-details"))
    add_verify(CucumberLabel.new("Type"), VerifyText.new, AccessHtmlElement.new(:id, "cds_advice-typeText"))
  end
end

#Validate columns in the Applet expanded view
Then(/^the CDS Advice expanded columns are$/) do |table|
  cols = CdsAdvice.instance
  driver = TestSupport.driver
  cols.wait_until_element_present("Priority", 10)
  elements = driver.find_elements(:xpath, "//*[@id='data-grid-cds_advice']/thead/tr/th")
  expect(elements.length).to_not eq(0)
  expect(elements.length).to eq(table.rows.length)
  table.rows.each do |column_name|
    header = cols.static_dom_element_exists?(column_name[0])
    p "#{column_name[0]} was not found" unless header
    expect(header).to be_true
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">

	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	</bean>
</beans>


text:
layout: post
title: jam tangan
date: 2011-01-17 10:36:56.000000000 +07:00
type: post
published: true
status: publish
categories:
- uncategorized
tags:
- jam tangan
- postaday2011
- swiss army
meta:
  _edit_last: '7761285'
  geo_latitude: '-8.588990'
  geo_longitude: '116.130400'
  geo_accuracy: '206'
  geo_address: mataram
  geo_public: '1'
author:
  login: pdft
  email: padfoot.tgz@gmail.com
  display_name: piko
  first_name: herpiko
  last_name: dwi aguno
---

jam tangan penting bagi saya. ini bukan tentang waktu atau penampilan. sama sekali bukan.

kemarin saya bepergian agak jauh dan lupa mengenakan jam tangan. ini sangat jarang terjadi dan rasanya waktu itu benar-benar tidak enak. kalau saya sedang kikuk di depan orang atau menghindari percakapan, jam tangan adalah solusinya. saya bisa pura2 melihat jam sekilas dan pura2 sedang menunggu sesuatu, dan tingkah ndak guna ini benar-benar membuat saya rileks.

kalau jam tangan ndak ada, duh saya jadi bingung dan serba kikuk, bingung mau ngomong apa biar ndak bengong mulu.

*btw, postaday memaksa saya untuk banyak cerita. yasudahlah, lagi pula orang bilang terbuka itu bagus.


text:
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ConcatWithSpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            if (!$tokens[$index]->equals('.')) {
                continue;
            }

            $this->fixWhiteSpaceAroundConcatToken($tokens, $index, 1);
            $this->fixWhiteSpaceAroundConcatToken($tokens, $index, -1);
        }

        return $tokens->generateCode();
    }

    /**
     * @param Tokens $tokens
     * @param int    $index  Index of concat token
     * @param int    $offset 1 or -1
     */
    private function fixWhiteSpaceAroundConcatToken(Tokens $tokens, $index, $offset)
    {
        $offsetIndex = $index + $offset;

        if (!$tokens[$offsetIndex]->isWhitespace()) {
            $tokens->insertAt($index + (1 === $offset ?: 0), new Token(array(T_WHITESPACE, ' ')));

            return;
        }

        if (false !== strpos($tokens[$offsetIndex]->getContent(), "\n")) {
            return;
        }

        if ($tokens[$index + $offset * 2]->isComment()) {
            return;
        }

        $tokens[$offsetIndex]->setContent(' ');
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Concatenation should be used with at least one whitespace around.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the ConcatWithoutSpacesFixer
        return -10;
    }
}


text:
ca-grande-prairie-transit-bus-parser
====================================

Parser for Grande Prairie Transit Bus data


text:
exports.setup = function (svc) {
    var assert = require('chai').assert;
    return (
        describe("Parsing Tests", function () {
            beforeEach(function (done) {
                this.service = svc;
                done();
            });

            it("Callback#Basic parse", function (done) {
                var service = this.service;

                service.parse("search index=_internal | head 1", function (err, parse) {
                    assert.ok(!err);
                    assert.ok(parse);
                    assert.ok(parse.commands.length > 0);
                    done();
                });
            });

            it("Callback#Parse error", function (done) {
                var service = this.service;

                service.parse("ABCXYZ", function (err, parse) {
                    assert.ok(err);
                    assert.strictEqual(err.status, 400);
                    done();
                });
            });
        })
    );
};

if (module.id === __filename && module.parent.id.includes('mocha')) {
    var splunkjs = require('../../index');
    var options = require('../cmdline');

    var cmdline = options.create().parse(process.argv);

    // If there is no command line, we should return
    if (!cmdline) {
        throw new Error("Error in parsing command line parameters");
    }

    var svc = new splunkjs.Service({
        scheme: cmdline.opts.scheme,
        host: cmdline.opts.host,
        port: cmdline.opts.port,
        username: cmdline.opts.username,
        password: cmdline.opts.password,
        version: cmdline.opts.version
    });

    // Exports tests on a successful login
    module.exports = new Promise((resolve, reject) => {
        svc.login(function (err, success) {
            if (err || !success) {
                throw new Error("Login failed - not running tests", err || "");
            }
            return resolve(exports.setup(svc));
        });
    });
}


text:
package org.hibernate.test.annotations.cascade.multicircle.nonjpa.sequence;

@javax.persistence.Entity
public class B extends AbstractEntity {
    private static final long serialVersionUID = 325417243L;

    @javax.persistence.OneToMany(mappedBy = "b")
	@org.hibernate.annotations.Cascade({
			org.hibernate.annotations.CascadeType.PERSIST,
			org.hibernate.annotations.CascadeType.SAVE_UPDATE,
			org.hibernate.annotations.CascadeType.MERGE,
			org.hibernate.annotations.CascadeType.REFRESH
	})
    private java.util.Set<G> gCollection = new java.util.HashSet<G>();

	@javax.persistence.ManyToOne(optional = false)
	@org.hibernate.annotations.Cascade({
			org.hibernate.annotations.CascadeType.PERSIST,
			org.hibernate.annotations.CascadeType.SAVE_UPDATE,
			org.hibernate.annotations.CascadeType.MERGE,
			org.hibernate.annotations.CascadeType.REFRESH
	})
	private C c;

	@javax.persistence.ManyToOne(optional = false)
	@org.hibernate.annotations.Cascade({
			org.hibernate.annotations.CascadeType.PERSIST,
			org.hibernate.annotations.CascadeType.SAVE_UPDATE,
			org.hibernate.annotations.CascadeType.MERGE,
			org.hibernate.annotations.CascadeType.REFRESH
	})
    private D d;

    public java.util.Set<G> getGCollection() {
        return gCollection;
    }

    public void setGCollection(
        java.util.Set<G> parameter) {
        this.gCollection = parameter;
    }

    public C getC() {
        return c;
    }

    public void setC(C parameter) {
        this.c = parameter;
    }

	public D getD() {
		return d;
	}

	public void setD(D parameter) {
		this.d = parameter;
	}

}


text:
import argparse
import pathlib
import shutil
import sys

_script_dir = pathlib.Path(__file__).parent.resolve(strict=True)
sys.path.append(str(_script_dir.parent))

from package_assembly_utils import (  # noqa: E402
    PackageVariant,
    copy_repo_relative_to_dir,
    gen_file_from_template,
    load_json_config,
)

def get_pod_config_file(package_variant: PackageVariant):
    """
    Gets the pod configuration file path for the given package variant.
    """
    if package_variant == PackageVariant.Full:
        return _script_dir / "onnxruntime-c.config.json"
    elif package_variant == PackageVariant.Mobile:
        return _script_dir / "onnxruntime-mobile-c.config.json"
    elif package_variant == PackageVariant.Test:
        return _script_dir / "onnxruntime-test-c.config.json"
    else:
        raise ValueError(f"Unhandled package variant: {package_variant}")

def assemble_c_pod_package(
    staging_dir: pathlib.Path,
    pod_version: str,
    framework_info_file: pathlib.Path,
    public_headers_dir: pathlib.Path,
    framework_dir: pathlib.Path,
    package_variant: PackageVariant,
):
    """
    Assembles the files for the C/C++ pod package in a staging directory.

    :param staging_dir Path to the staging directory for the C/C++ pod files.
    :param pod_version C/C++ pod version.
    :param framework_info_file Path to the framework_info.json file containing additional values for the podspec.
    :param public_headers_dir Path to the public headers directory to include in the pod.
    :param framework_dir Path to the onnxruntime framework directory to include in the pod.
    :param package_variant The pod package variant.
    :return Tuple of (package name, path to the podspec file).
    """
    staging_dir = staging_dir.resolve()
    framework_info_file = framework_info_file.resolve(strict=True)
    public_headers_dir = public_headers_dir.resolve(strict=True)
    framework_dir = framework_dir.resolve(strict=True)

    framework_info = load_json_config(framework_info_file)
    pod_config = load_json_config(get_pod_config_file(package_variant))

    pod_name = pod_config["name"]

    print(f"Assembling files in staging directory: {staging_dir}")
    if staging_dir.exists():
        print("Warning: staging directory already exists", file=sys.stderr)

    # copy the necessary files to the staging directory
    shutil.copytree(framework_dir, staging_dir / framework_dir.name, dirs_exist_ok=True)
    shutil.copytree(public_headers_dir, staging_dir / public_headers_dir.name, dirs_exist_ok=True)
    copy_repo_relative_to_dir(["LICENSE"], staging_dir)

    # generate the podspec file from the template
    variable_substitutions = {
        "DESCRIPTION": pod_config["description"],
        "IOS_DEPLOYMENT_TARGET": framework_info["IOS_DEPLOYMENT_TARGET"],
        "LICENSE_FILE": "LICENSE",
        "NAME": pod_name,
        "ORT_C_FRAMEWORK": framework_dir.name,
        "ORT_C_HEADERS_DIR": public_headers_dir.name,
        "SUMMARY": pod_config["summary"],
        "VERSION": pod_version,
        "WEAK_FRAMEWORK": framework_info["WEAK_FRAMEWORK"],
    }

    podspec_template = _script_dir / "c.podspec.template"
    podspec = staging_dir / f"{pod_name}.podspec"

    gen_file_from_template(podspec_template, podspec, variable_substitutions)

    return pod_name, podspec

def parse_args():
    parser = argparse.ArgumentParser(
        description="""
        Assembles the files for the C/C++ pod package in a staging directory.
        This directory can be validated (e.g., with `pod lib lint`) and then zipped to create a package for release.
    """
    )

    parser.add_argument(
        "--staging-dir",
        type=pathlib.Path,
        default=pathlib.Path("./c-staging"),
        help="Path to the staging directory for the C/C++ pod files.",
    )
    parser.add_argument("--pod-version", required=True, help="C/C++ pod version.")
    parser.add_argument(
        "--framework-info-file",
        type=pathlib.Path,
        required=True,
        help="Path to the framework_info.json file containing additional values for the podspec. "
        "This file should be generated by CMake in the build directory.",
    )
    parser.add_argument(
        "--public-headers-dir",
        type=pathlib.Path,
        required=True,
        help="Path to the public headers directory to include in the pod.",
    )
    parser.add_argument(
        "--framework-dir",
        type=pathlib.Path,
        required=True,
        help="Path to the onnxruntime framework directory to include in the pod.",
    )
    parser.add_argument(
        "--variant", choices=PackageVariant.all_variant_names(), required=True, help="Pod package variant."
    )

    return parser.parse_args()

def main():
    args = parse_args()

    assemble_c_pod_package(
        staging_dir=args.staging_dir,
        pod_version=args.pod_version,
        framework_info_file=args.framework_info_file,
        public_headers_dir=args.public_headers_dir,
        framework_dir=args.framework_dir,
        package_variant=PackageVariant[args.variant],
    )

    return 0

if __name__ == "__main__":
    sys.exit(main())


text:
$.extend($.fn.validatebox.methods, {
    remove: function (jq, newposition) {
        return jq.each(function () {
            $(this).removeClass("validatebox-text validatebox-invalid").unbind('focus').unbind('blur');
        });
    },
    reduce: function (jq, newposition) {
        return jq.each(function () {
            var opt = $(this).data().validatebox.options;
            $(this).addClass("validatebox-text").validatebox(opt);
        });
    },
    onEnterDown: function (jq, handler) {
        var obj = jq.parent().find(".easyui-validatebox.validatebox-text");
        var keydownHandler = function () {
            var enterDownFunction = function (e) {
                if (e.keyCode == 13) {
                    var text = jq.val();
                    handler(text);
                }
            }
            obj.off('keydown', enterDownFunction);
            obj.on('keydown', enterDownFunction);
        };
        keydownHandler();
    }
});


text:
require 'spec_helper'

RSpec.describe Pastel::AliasImporter, '.import' do
  let(:color) { spy(:color, alias_color: true) }
  let(:output) { StringIO.new }

  subject(:importer) { described_class.new(color, output) }

  it "imports aliases from environment" do
    color_aliases = "funky=red,base=bright_yellow"
    allow(ENV).to receive(:[]).with('PASTEL_COLORS_ALIASES').
      and_return(color_aliases)

    importer.import

    expect(color).to have_received(:alias_color).twice
  end

  it "fails to import incorrectly formatted colors" do
    color_aliases = "funky red,base=bright_yellow"
    allow(ENV).to receive(:[]).with('PASTEL_COLORS_ALIASES').
      and_return(color_aliases)

    importer.import

    output.rewind
    expect(output.string).to eq("Bad color mapping `funky red`\n")
    expect(color).to have_received(:alias_color).with(:base, :bright_yellow)
  end
end


text:
var duplexer = require('duplexer');
var Writable = require('stream').Writable;

module.exports = function(counter) {
    var countries = {};
    var capturer = Writable({objectMode: true});
    capturer._write = function(chunk, enc, next) {
        countries[chunk.country] = (countries[chunk.country] || 0) + 1;
        next();
    }
    capturer.on('finish', function() { counter.setCounts(countries); })
    return duplexer(capturer, counter);
};

/*
officjal solution:
var duplexer = require('duplexer2');
var through = require('through2').obj;

module.exports = function (counter) {
    var counts = {};
    var input = through(write, end);
    return duplexer({objectMode: true}, input, counter);

    function write (row, _, next) {
        counts[row.country] = (counts[row.country] || 0) + 1;
        next();
    }
    function end (done) {
        counter.setCounts(counts);
        done();
    }
};
*/


text:
/*INSERT INTO resource (name, display_name, description, is_public)
VALUES
('index', 'Index controller', 'Index controller desc', true),
('index:index', 'Index index action', 'Index index action desc', true),
('session', 'Session controller', 'Session controller desc', true),
('session:login', 'Login action', 'Login action desc', true),
('session:logout', 'Logout action', 'Logout action desc', true),
('user', 'User controller', 'User controller desc', false),
('user:index', 'User list', 'User list desc', false),
('user:create', 'User create', 'User create desc', false);*/

INSERT INTO "user" (name, email, crypt_hash, password_salt, active)
VALUES
('Administrator', 'admin@vgpg.icmc.usp.br', 'cab17e949435af0ae503188a64ce6a0d741d22a0', '9eb71ab7420eb452a22787ca4fab501b', true);

INSERT INTO "group" (name, is_admin, locked)
VALUES
('Admin', true, true),
('User', false, true);

INSERT INTO "user_group" (user_id, group_id)
VALUES
(1, 1);
/*
INSERT INTO "group_resource" (group_id, resource_id, type)
VALUES
(2, 6, true);*/


text:
////class ABCD {
////    constructor(private x: number, public y: number, private [|{| "isWriteAccess": true, "isDefinition": true |}z|]: number) {
////    }
////
////    func() {
////        return this.[|z|];
////    }
////}

verify.singleReferenceGroup("(property) ABCD.z: number");


text:
package com.taoswork.tallybook.module.elevator.def.sheets;

import com.taoswork.tallybook.module.base.BaseSheet;

/**
 * Created by Gao Yuan on 2016/3/9.
 */
public class AnnualMaintenance extends BaseSheet {
}


text:
#pragma once

#include "CoreMinimal.h"
#include "VoxelMinimal.h"
#include "EditorViewportClient.h"

class AVoxelWorld;
class FVoxelEditorToolsPanel;
class SVoxelDataAssetEditorViewport;
class FPreviewScene;
class UVoxelDataAsset;

class FVoxelDataAssetEditorViewportClient : public FEditorViewportClient, public TSharedFromThis<FVoxelDataAssetEditorViewportClient>
{
public:
	static TSharedRef<FVoxelDataAssetEditorViewportClient> Create(
		AVoxelWorld& VoxelWorld,
		UVoxelDataAsset& DataAsset,
		FVoxelEditorToolsPanel& Panel,
		FPreviewScene& PreviewScene,
		SVoxelDataAssetEditorViewport& DataAssetEditorViewport);

	//~ Begin FEditorViewportClient interface
	virtual void Tick(float DeltaSeconds) override;
	virtual void Draw(const FSceneView* View, FPrimitiveDrawInterface* PDI) override;
	virtual void Draw(FViewport* Viewport, FCanvas* Canvas) override;
	virtual bool InputKey(FViewport* Viewport, int32 ControllerId, FKey Key, EInputEvent Event, float AmountDepressed = 1.f, bool bGamepad = false) override;
	virtual bool InputAxis(FViewport* Viewport, int32 ControllerId, FKey Key, float Delta, float DeltaTime, int32 NumSamples, bool bGamepad) override;
	virtual void ProcessClick(class FSceneView& View, class HHitProxy* HitProxy, FKey Key, EInputEvent Event, uint32 HitX, uint32 HitY) override;
	virtual int32 GetCameraSpeedSetting() const override;
	virtual void SetCameraSpeedSetting(int32 SpeedSetting) override;
	virtual void MouseMove(FViewport* Viewport, int32 x, int32 y) override;
	virtual void UpdateMouseDelta() override;
	//~ End FEditorViewportClient interface

	bool IsShowGridToggled();
	void ToggleShowGrid();

private:
	AVoxelWorld& VoxelWorld;
	UVoxelDataAsset& DataAsset;
	FVoxelEditorToolsPanel& Panel;

	bool bShowGrid = false;
	bool bShowFloor = false;
	bool bMousePressed = false;

	FVoxelDataAssetEditorViewportClient(
		AVoxelWorld& VoxelWorld,
		UVoxelDataAsset& DataAsset,
		FVoxelEditorToolsPanel& Panel,
		FPreviewScene& InPreviewScene,
		SVoxelDataAssetEditorViewport& DataAssetEditorViewport);

	void ScheduleUpdateThumbnail();
	void UpdateThumbnail();
};


text:
#import <Cocoa/Cocoa.h>

@interface NewDocWindowController : NSWindowController
{
    NSArray* rootObjectTypes;
    NSString* rootObjectType;

    int wStage;
    int hStage;

    int centeredStageOrigin;
}

@property (nonatomic,retain) NSArray* rootObjectTypes;
@property (nonatomic,retain) NSString* rootObjectType;
@property (nonatomic,assign) int wStage;
@property (nonatomic,assign) int hStage;
@property (nonatomic,assign) int centeredStageOrigin;

- (IBAction)acceptSheet:(id)sender;
- (IBAction)cancelSheet:(id)sender;

@end


text:
/*--------------------------------------------------------*\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: https://hprose.com                     |
|                                                          |
|  DoubleConverter.cs                                      |
|                                                          |
|  hprose DoubleConverter class for C#.                    |
|                                                          |
|  LastModified: Feb 21, 2019                              |
|  Author: Ma Bingyao <andot@hprose.com>                   |
|                                                          |
\*________________________________________________________*/

using System;
using System.Numerics;

namespace Hprose.IO.Converters {
    internal static class DoubleConverter {
        static DoubleConverter() {
            Converter<bool, double>.convert = Convert.ToDouble;
            Converter<char, double>.convert = Convert.ToDouble;
            Converter<byte, double>.convert = Convert.ToDouble;
            Converter<sbyte, double>.convert = Convert.ToDouble;
            Converter<short, double>.convert = Convert.ToDouble;
            Converter<ushort, double>.convert = Convert.ToDouble;
            Converter<int, double>.convert = Convert.ToDouble;
            Converter<uint, double>.convert = Convert.ToDouble;
            Converter<long, double>.convert = Convert.ToDouble;
            Converter<ulong, double>.convert = Convert.ToDouble;
            Converter<float, double>.convert = Convert.ToDouble;
            Converter<decimal, double>.convert = Convert.ToDouble;
#if !NET35_CF
            Converter<DateTime, double>.convert = Convert.ToDouble;
#endif
            Converter<BigInteger, double>.convert = (value) => (double)value;
        }
        internal static void Initialize() { }
    }
}


text:
from __future__ import unicode_literals

import django.contrib.postgres.indexes
import django.contrib.postgres.search
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('opendebates', '0001_squashed_0041_auto_20170331_1023'),
    ]

    operations = [
        migrations.AddField(
            model_name='submission',
            name='search_vector',
            field=django.contrib.postgres.search.SearchVectorField(null=True),
        ),
        migrations.AddIndex(
            model_name='submission',
            index=django.contrib.postgres.indexes.GinIndex(fields=[b'search_vector'], name='opendebates_search__dd5129_gin'),
        ),
    ]


text:
#include "polycode/core/PolyUWPCore.h"
#include "polycode/core/PolyBasicFileProvider.h"
#include <ppltasks.h>

using namespace concurrency;
using namespace Polycode;

using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Storage;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

UWPCore::UWPCore(PolycodeView *view, int xRes, int yRes, bool fullScreen, bool vSync, int aaLevel, int anisotropyLevel, int frameRate, int monitorIndex, bool retinaSupport)
	: Core(xRes, yRes, fullScreen, vSync, aaLevel, anisotropyLevel, frameRate, monitorIndex) {

	m_Window = view->window;
	m_eglWindow = view->eglWindow;

	mEglDisplay = view->mEglDisplay;
	mEglContext = view->mEglContext;
	mEglSurface = view->mEglSurface;

	LARGE_INTEGER li;
	QueryPerformanceFrequency(&li);
	pcFreq = double(li.QuadPart) / 1000.0;

	lastMouseY = 0;
	lastMouseX = 0;

	fileProviders.push_back(new BasicFileProvider());

	renderer = new Renderer(this);

	renderer->setBackingResolutionScale(1.0, 1.0);

	graphicsInterface = new OpenGLGraphicsInterface(this);
	renderer->setGraphicsInterface(this, graphicsInterface);
	setVideoMode(xRes, yRes, fullScreen, vSync, aaLevel, anisotropyLevel, retinaSupport);

	getSoundManager()->setAudioInterface(new XAudio2AudioInterface(this));

}

UWPCore::~UWPCore() {

}

void UWPCore::checkEvents() {

	eventMutex.lock();

	UWPEvent event;
	for (int i = 0; i < systemInputEvents.size(); i++) {
		event = systemInputEvents[i];
		switch (event.eventGroup) {
		case UWPEvent::INPUT_EVENT:
			switch (event.eventCode) {
			case InputEvent::EVENT_MOUSEMOVE:
				input->setDeltaPosition(lastMouseX - event.mouseX, lastMouseY - event.mouseY);
				lastMouseX = event.mouseX;
				lastMouseY = event.mouseY;
				input->setMousePosition(event.mouseX, event.mouseY, getTicks());
				break;
			case InputEvent::EVENT_MOUSEDOWN:
				input->mousePosition.x = event.mouseX;
				input->mousePosition.y = event.mouseY;
				input->setMouseButtonState(event.mouseButton, true, getTicks());
				break;
			case InputEvent::EVENT_MOUSEWHEEL_UP:
				input->mouseWheelUp(getTicks());
				break;
			case InputEvent::EVENT_MOUSEWHEEL_DOWN:
				input->mouseWheelDown(getTicks());
				break;
			case InputEvent::EVENT_MOUSEUP:
				input->setMouseButtonState(event.mouseButton, false, getTicks());
				break;
			case InputEvent::EVENT_KEYDOWN:
				if (!checkSpecialKeyEvents(event.keyCode))
					input->setKeyState(event.keyCode, true, getTicks());
				break;
			case InputEvent::EVENT_KEYUP:
				input->setKeyState(event.keyCode, false, getTicks());
				break;
			case InputEvent::EVENT_TOUCHES_BEGAN:
				input->touchesBegan(event.touch, event.touches, getTicks());
				break;
			case InputEvent::EVENT_TOUCHES_ENDED:
				input->touchesEnded(event.touch, event.touches, getTicks());
				break;
			case InputEvent::EVENT_TOUCHES_MOVED:
				input->touchesMoved(event.touch, event.touches, getTicks());
				break;
			}
			break;
		case UWPEvent::SYSTEM_FOCUS_EVENT:
			switch (event.eventCode) {
			case Core::EVENT_LOST_FOCUS:
				loseFocus();
				break;
			case Core::EVENT_GAINED_FOCUS:
				gainFocus();
				break;
			}
			break;
		}
	}

	systemInputEvents.clear();
	eventMutex.unlock();

}

bool UWPCore::systemUpdate() {
	if (!running) {
		return false;
	}
	doSleep();
	updateCore();

	checkEvents();
	return running;
}

void UWPCore::setCursor(int cursorType) {

}

void launchThread(Threaded *target) {
	target->runThread();
	target->scheduledForRemoval = true;
}

void UWPCore::createThread(Threaded * target) {
	Core::createThread(target);
	std::thread *thread = new std::thread(launchThread, target);

}

void UWPCore::copyStringToClipboard(const String& str) {

}

String UWPCore::getClipboardString() {
	return "";
}

void UWPCore::createFolder(const String& folderPath) {

}

void UWPCore::copyDiskItem(const String& itemPath, const String& destItemPath) {

}

void UWPCore::moveDiskItem(const String& itemPath, const String& destItemPath) {

}

void UWPCore::removeDiskItem(const String& itemPath) {

}

String UWPCore::openFolderPicker() {
	return "";
}

std::vector<String> UWPCore::openFilePicker(std::vector<CoreFileExtension> extensions, bool allowMultiple) {
	std::vector<String> ret;
	return ret;
}

String UWPCore::saveFilePicker(std::vector<CoreFileExtension> extensions) {
	return "";
}

void UWPCore::handleVideoModeChange(VideoModeChangeInfo *modeInfo) {
	if (eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext) == EGL_FALSE)
	{
		assert(false);
	}
}

void UWPCore::flushRenderContext() {
	eglSwapBuffers(mEglDisplay, mEglSurface);
}

void UWPCore::openURL(String url) {

}

unsigned int UWPCore::getTicks() {
	LARGE_INTEGER li;
	QueryPerformanceCounter(&li);
	return (unsigned int)(li.QuadPart / pcFreq);
	return 0;
}

String UWPCore::executeExternalCommand(String command, String args, String inDirectory) {
	return "";
}

void wtoc(char* Dest, const WCHAR* Source)
{
	int i = 0;
	while (Source[i] != '\0') {
		Dest[i] = (char)Source[i];
		++i;
	}
	Dest[i] = 0;
}
void ctow(WCHAR* Dest, const char* Source)
{
	int i = 0;
	while (Source[i] != '\0') {
		Dest[i] = (WCHAR)Source[i];
		++i;
	}
	Dest[i] = 0;
}

bool UWPCore::systemParseFolder(const Polycode::String& pathString, bool showHidden, std::vector<OSFileEntry> &targetVector) {

	WIN32_FIND_DATA findFileData;

	WCHAR curDir[4096];
	GetCurrentDirectory(4096, curDir);

	WCHAR tmp[4096];
	memset(tmp, 0, sizeof(WCHAR) * 4096);
	ctow(tmp, pathString.c_str());

	WIN32_FILE_ATTRIBUTE_DATA fileData;

	GetFileAttributesEx(tmp, GetFileExInfoStandard, &fileData);

	if (!(fileData.dwFileAttributes != INVALID_FILE_ATTRIBUTES &&
		(fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))) {
		return true;
	}

	SetCurrentDirectory(tmp);

	HANDLE hFind = FindFirstFileEx(L"*", FindExInfoStandard, &findFileData, FindExSearchNameMatch, NULL, 0);
	if (hFind == INVALID_HANDLE_VALUE) {
		SetCurrentDirectory(curDir);
		return true;
	}

	do {
		String fname(findFileData.cFileName);

		if ((fname.c_str()[0] != '.' || (fname.c_str()[0] == '.'  && showHidden)) && fname != "..") {
			if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
				targetVector.push_back(OSFileEntry(pathString, fname, OSFileEntry::TYPE_FOLDER));
			}
			else {
				targetVector.push_back(OSFileEntry(pathString, fname, OSFileEntry::TYPE_FILE));
			}
		}
	} while (FindNextFile(hFind, &findFileData));
	FindClose(hFind);
	SetCurrentDirectory(curDir);

	return true;
}

void UWPCore::handleSystemEvent(UWPEvent systemEvent) {
	eventMutex.lock();
	systemInputEvents.push_back(systemEvent);
	eventMutex.unlock();
}

void Core::getScreenInfo(int *width, int *height, int *hz) {

}

void UWPCore::setDeviceSize(Number x, Number y) {
	deviceWidth = x;
	deviceHeight = y;

	renderer->setBackingResolutionScale(xRes/deviceWidth, yRes/deviceHeight);
}

Number UWPCore::getBackingXRes() {
	return deviceWidth;
}

Number UWPCore::getBackingYRes() {
	return deviceHeight;
}


text:
from fastapi import FastAPI, Security
from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase
from fastapi.testclient import TestClient

app = FastAPI()

security = HTTPBase(scheme="Other")

@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}

client = TestClient(app)

openapi_schema = {
    "openapi": "3.0.2",
    "info": {"title": "FastAPI", "version": "0.1.0"},
    "paths": {
        "/users/me": {
            "get": {
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        "content": {"application/json": {"schema": {}}},
                    }
                },
                "summary": "Read Current User",
                "operationId": "read_current_user_users_me_get",
                "security": [{"HTTPBase": []}],
            }
        }
    },
    "components": {
        "securitySchemes": {"HTTPBase": {"type": "http", "scheme": "Other"}}
    },
}

def test_openapi_schema():
    response = client.get("/openapi.json")
    assert response.status_code == 200, response.text
    assert response.json() == openapi_schema

def test_security_http_base():
    response = client.get("/users/me", headers={"Authorization": "Other foobar"})
    assert response.status_code == 200, response.text
    assert response.json() == {"scheme": "Other", "credentials": "foobar"}

def test_security_http_base_no_credentials():
    response = client.get("/users/me")
    assert response.status_code == 403, response.text
    assert response.json() == {"detail": "Not authenticated"}


text:
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/
/**********************************************************\
 *                                                        *
 * IntUnserializer.java                                   *
 *                                                        *
 * int unserializer class for Java.                       *
 *                                                        *
 * LastModified: Apr 17, 2016                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

package hprose.io.unserialize;

import static hprose.io.HproseTags.TagDouble;
import static hprose.io.HproseTags.TagEmpty;
import static hprose.io.HproseTags.TagFalse;
import static hprose.io.HproseTags.TagInteger;
import static hprose.io.HproseTags.TagLong;
import static hprose.io.HproseTags.TagNull;
import static hprose.io.HproseTags.TagRef;
import static hprose.io.HproseTags.TagSemicolon;
import static hprose.io.HproseTags.TagString;
import static hprose.io.HproseTags.TagTrue;
import static hprose.io.HproseTags.TagUTF8Char;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;

public final class IntUnserializer implements Unserializer {

    public final static IntUnserializer instance = new IntUnserializer();

    final static int read(Reader reader, ByteBuffer buffer, int tag) throws IOException {
        switch (tag) {
            case TagLong: return ValueReader.readInt(buffer, TagSemicolon);
            case TagDouble: return Double.valueOf(ValueReader.readDouble(buffer)).intValue();
            case TagEmpty: return 0;
            case TagTrue: return 1;
            case TagFalse: return 0;
            case TagUTF8Char: return Integer.parseInt(ValueReader.readUTF8Char(buffer));
            case TagString: return Integer.parseInt(StringUnserializer.readString(reader, buffer));
            case TagRef: return Integer.parseInt(reader.readRef(buffer, String.class));
            default: throw ValueReader.castError(reader.tagToString(tag), int.class);
        }
    }

    final static int read(Reader reader, InputStream stream, int tag) throws IOException {
        switch (tag) {
            case TagLong: return ValueReader.readInt(stream, TagSemicolon);
            case TagDouble: return Double.valueOf(ValueReader.readDouble(stream)).intValue();
            case TagEmpty: return 0;
            case TagTrue: return 1;
            case TagFalse: return 0;
            case TagUTF8Char: return Integer.parseInt(ValueReader.readUTF8Char(stream));
            case TagString: return Integer.parseInt(StringUnserializer.readString(reader, stream));
            case TagRef: return Integer.parseInt(reader.readRef(stream, String.class));
            default: throw ValueReader.castError(reader.tagToString(tag), int.class);
        }
    }

    public final static int read(Reader reader, ByteBuffer buffer) throws IOException {
        int tag = buffer.get();
        if (tag >= '0' && tag <= '9') return (tag - '0');
        if (tag == TagInteger) return ValueReader.readInt(buffer, TagSemicolon);
        if (tag == TagNull) return 0;
        return read(reader, buffer, tag);
    }

    public final static int read(Reader reader, InputStream stream) throws IOException {
        int tag = stream.read();
        if (tag >= '0' && tag <= '9') return (tag - '0');
        if (tag == TagInteger) return ValueReader.readInt(stream, TagSemicolon);
        if (tag == TagNull) return 0;
        return read(reader, stream, tag);
    }

    public final Object read(Reader reader, ByteBuffer buffer, Class<?> cls, Type type) throws IOException {
        return read(reader, buffer);
    }

    public final Object read(Reader reader, InputStream stream, Class<?> cls, Type type) throws IOException {
        return read(reader, stream);
    }

}


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#include "compiler.h"
#include "board.h"
#include "conf_board.h"
#include "conf_clock.h"
#include "ioport.h"

/**
 * \addtogroup sam4cms_db_group
 * @{
 */

/**
 * \brief Set peripheral mode for IOPORT pins.
 * It will configure port mode and disable pin mode (but enable peripheral).
 * \param port IOPORT port to configure
 * \param masks IOPORT pin masks to configure
 * \param mode Mode masks to configure for the specified pin (\ref ioport_modes)
 */
#define ioport_set_port_peripheral_mode(port, masks, mode) \
	do {\
		ioport_set_port_mode(port, masks, mode);\
		ioport_disable_port(port, masks);\
	} while (0)

/**
 * \brief Set peripheral mode for one single IOPORT pin.
 * It will configure port mode and disable pin mode (but enable peripheral).
 * \param pin IOPORT pin to configure
 * \param mode Mode masks to configure for the specified pin (\ref ioport_modes)
 */
#define ioport_set_pin_peripheral_mode(pin, mode) \
	do {\
		ioport_set_pin_mode(pin, mode);\
		ioport_disable_pin(pin);\
	} while (0)

/**
 * \brief Set input mode for one single IOPORT pin.
 * It will configure port mode and disable pin mode (but enable peripheral).
 * \param pin IOPORT pin to configure
 * \param mode Mode masks to configure for the specified pin (\ref ioport_modes)
 * \param sense Sense for interrupt detection (\ref ioport_sense)
 */
#define ioport_set_pin_input_mode(pin, mode, sense) \
	do {\
		ioport_set_pin_dir(pin, IOPORT_DIR_INPUT);\
		ioport_set_pin_mode(pin, mode);\
		ioport_set_pin_sense_mode(pin, sense);\
	} while (0)

void board_init(void)
{
#ifndef CONF_BOARD_KEEP_WATCHDOG_AT_INIT
	/* Disable the watchdog */
	WDT->WDT_MR = WDT_MR_WDDIS;
#endif

	/* GPIO has been deprecated, the old code just keeps it for compatibility.
	 * In new designs IOPORT is used instead.
	 * Here IOPORT must be initialized for others to use before setting up IO.
	 */
	ioport_init();

#ifdef CONFIG_CPCLK_ENABLE
	/* Configure the pins connected to LEDs as output and set their
	 * default initial state to high (LEDs off).
	 */
	ioport_set_pin_dir(LED4_GPIO, IOPORT_DIR_OUTPUT);
	ioport_set_pin_level(LED4_GPIO, LED4_INACTIVE_LEVEL);
#else
#warning Please enable CONFIG_CPCLK_ENABLE in conf_clock.h to use LEDs (PIOC).
#endif

	/* Configure UART0 pins */
#ifdef CONF_BOARD_UART_CONSOLE
	ioport_set_pin_peripheral_mode(PIO_PB4_IDX, IOPORT_MODE_MUX_A);
	ioport_set_pin_peripheral_mode(PIO_PB5_IDX, IOPORT_MODE_MUX_A);
#endif

	/* Configure SPI pins */
#ifdef CONF_BOARD_SPI0
	ioport_set_pin_peripheral_mode(SPI0_MISO_GPIO, SPI0_MISO_FLAGS);
	ioport_set_pin_peripheral_mode(SPI0_MOSI_GPIO, SPI0_MOSI_FLAGS);
	ioport_set_pin_peripheral_mode(SPI0_SPCK_GPIO, SPI0_SPCK_FLAGS);

#ifdef CONF_BOARD_SPI0_NPCS1
	ioport_set_pin_peripheral_mode(SPI0_NPCS1_GPIO, SPI0_NPCS1_FLAGS);
#endif
#ifdef CONF_BOARD_SPI0_NPCS3
	ioport_set_pin_peripheral_mode(SPI0_NPCS3_GPIO, SPI0_NPCS3_FLAGS);
#endif
#endif

	/* Configure TWI pins */
#if defined(CONF_BOARD_TWI0) || defined(CONF_BOARD_AT30TSE)
	ioport_set_pin_peripheral_mode(TWIO_DATA_GPIO, TWIO_DATA_FLAG);
	ioport_set_pin_peripheral_mode(TWIO_CLK_GPIO, TWIO_CLK_FLAG);
#endif
}

/* @} */


text:
@implementation OCDTesterWindow

+ (BOOL)autosavesInPlace {
	return YES;
}

- (void)windowControllerDidLoadNib:(NSWindowController *)windowController {
	[super windowControllerDidLoadNib:windowController];
	[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(windowDidResize:) name:NSWindowDidResizeNotification object:windowController.window];
}

- (void)dealloc {
	[NSNotificationCenter.defaultCenter removeObserver:self name:NSWindowDidResizeNotification object:nil];
}

- (void)windowDidResize:(NSNotification *)notification {
	self.frameTextField.stringValue = [NSString stringWithFormat:@"%.0f x %.0f", NSWidth([notification.object frame]), NSHeight([notification.object frame])];
}

- (NSString *)windowNibName {
	return @"OCDTesterWindow";
}

- (NSString *)displayName {
	return @"Compulsion Tester";
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError {
	if (outError)
		*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:nil];

	return YES;
}

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
	if (outError)
		*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:nil];

	return nil;
}

@end


text:
package monocle

import cats.Eq
import cats.implicits._
import cats.data.OneAnd
import cats.free.Cofree
import cats.laws.discipline.arbitrary._
import org.scalacheck.Arbitrary._
import org.scalacheck.rng.Seed
import org.scalacheck.{Arbitrary, Cogen}

private[monocle] trait ScalaVersionSpecificTestInstances {
  implicit def streamCofreeEq[A](implicit A: Eq[A]): Eq[Cofree[Stream, A]] =
    Eq.instance((a, b) => A.eqv(a.head, b.head) && a.tail === b.tail)

  implicit def function1Eq[A, B](implicit A: Arbitrary[A], B: Eq[B]) =
    new Eq[A => B] {
      val samples      = Stream.continually(A.arbitrary.sample).flatten
      val samplesCount = 50

      override def eqv(f: A => B, g: A => B) =
        samples.take(samplesCount).forall(a => B.eqv(f(a), g(a)))
    }

  implicit def streamCoGen[A: Cogen]: Cogen[Stream[A]] = Cogen[List[A]].contramap[Stream[A]](_.toList)

  implicit def cogenStreamCofree[A](implicit A: Cogen[A]): Cogen[Cofree[Stream, A]] =
    Cogen[Cofree[Stream, A]]((seed: Seed, t: Cofree[Stream, A]) =>
      Cogen[(A, Stream[Cofree[Stream, A]])].perturb(seed, (t.head, t.tail.value))
    )

  implicit def optionCofreeArbitrary[A](implicit A: Arbitrary[A]): Arbitrary[Cofree[Option, A]] =
    Arbitrary(
      Arbitrary
        .arbitrary[OneAnd[List, A]]
        .map(xs => monocle.std.cofree.cofreeToStream.reverseGet(xs.copy(tail = xs.tail.toStream)))
    )
}


text:
namespace {

class DstCfgDummy : public DummyConfig {
public:
    DstCfgDummy() : useCashAddr(false) {}
    void SetCashAddrEncoding(bool b) override { useCashAddr = b; }
    bool UseCashAddrEncoding() const override { return useCashAddr; }

private:
    bool useCashAddr;
};

} // anon ns

BOOST_FIXTURE_TEST_SUITE(dstencode_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(test_addresses) {
    std::vector<uint8_t> hash = {118, 160, 64,  83,  189, 160, 168,
                                 139, 218, 81,  119, 184, 106, 21,
                                 195, 178, 159, 85,  152, 115};

    const CTxDestination dstKey = CKeyID(uint160(hash));
    const CTxDestination dstScript = CScriptID(uint160(hash));

    std::string cashaddr_pubkey =
        "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a";
    std::string cashaddr_script =
        "bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq";
    std::string base58_pubkey = "1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu";
    std::string base58_script = "3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC";
    std::string bitpay_pubkey = "CTH8H8Zj6DSnXFBKQeDG28ogAS92iS16Bp";
    std::string bitpay_script = "HHLN6S9BcP1JLSrMhgD5qe57iVEMFMLCBT";

    const CChainParams &params = Params(CBaseChainParams::MAIN);
    DstCfgDummy cfg;

    // Check encoding
    cfg.SetCashAddrEncoding(true);
    BOOST_CHECK_EQUAL(cashaddr_pubkey, EncodeDestination(dstKey, params, cfg));
    BOOST_CHECK_EQUAL(cashaddr_script,
                      EncodeDestination(dstScript, params, cfg));
    cfg.SetCashAddrEncoding(false);
    BOOST_CHECK_EQUAL(base58_pubkey, EncodeDestination(dstKey, params, cfg));
    BOOST_CHECK_EQUAL(base58_script, EncodeDestination(dstScript, params, cfg));

    BOOST_CHECK_EQUAL(bitpay_pubkey, EncodeBitpayAddr(dstKey));
    BOOST_CHECK_EQUAL(bitpay_script, EncodeBitpayAddr(dstScript));

    // Check decoding
    BOOST_CHECK(dstKey == DecodeDestination(cashaddr_pubkey, params));
    BOOST_CHECK(dstScript == DecodeDestination(cashaddr_script, params));
    BOOST_CHECK(dstKey == DecodeDestination(base58_pubkey, params));
    BOOST_CHECK(dstScript == DecodeDestination(base58_script, params));

    BOOST_CHECK(dstKey == DecodeDestination(bitpay_pubkey, params));
    BOOST_CHECK(dstScript == DecodeDestination(bitpay_script, params));

    // Validation
    BOOST_CHECK(IsValidDestinationString(cashaddr_pubkey, params));
    BOOST_CHECK(IsValidDestinationString(cashaddr_script, params));
    BOOST_CHECK(IsValidDestinationString(base58_pubkey, params));
    BOOST_CHECK(IsValidDestinationString(base58_script, params));
    BOOST_CHECK(IsValidDestinationString(bitpay_pubkey, params));
    BOOST_CHECK(IsValidDestinationString(bitpay_script, params));
    BOOST_CHECK(!IsValidDestinationString("notvalid", params));
}

BOOST_AUTO_TEST_SUITE_END()


text:
'use strict';

(function (module) {
  var vows = require('vows'),
    assert = require('assert');

  var CSVStorage = require('../storage/csv');

  var testContent = "Bill McKnight, Male, 16/03/77\n" +
    "Paul Robinson, Male, 15/01/85\n" +
    "Gemma Lane, Female, 20/11/91\n" +
    "Sarah Stone, Female, 20/09/80\n" +
    "Wes Jackson, Male, 14/08/74";

  var storageFilePath = 'addressbook.csv';

  vows.describe('storage.csv.CSVStorage').addBatch({
    '._loadFile()': {
      topic: function () {
        return new CSVStorage(storageFilePath);
      },

      'we get the content': function (storage) {
        var response = storage._loadFile();
        var type = typeof response;

        assert.equal(type, 'string');
      }
    },

    '._parseFileContent()': {
      topic: function () {
        var storage = new CSVStorage(storageFilePath);

        return storage._parseFileContent(testContent);
      },

      'we get an array of arrays': function (parsed) {
        assert.isArray(parsed);
        parsed.forEach(function(subArray) {
          assert.isArray(subArray);
          assert.equal(subArray.length, 3);
        });
      },

      'array has the correct length': function (parsed) {
        assert.equal(parsed.length, 5);
      }
    },
    '._parseLine()': {
      topic: function () { return 0 / 0 },

      'we get a value which': {
        'is not a number': function (topic) {
          assert.isNaN (topic);
        },
        'is not equal to itself': function (topic) {
          assert.notEqual (topic, topic);
        }
      }
    }
  }).export(module);

})(module);


text:
/**
 * Created by akersten on 8/19/17.
 */

import {EAlignment} from "./properties/EAlignment";
import {EBiome} from "./properties/EBiome";
import {EBiomeIntensity} from "./properties/EBiomeIntensity";
import {EDanger} from "./properties/EDanger";
import {ELuck} from "./properties/ELuck";
import {EPopulationDensity} from "./properties/EPopulationDensity";
import {ESpirit} from "./properties/ESpirit";
import {ETemperature} from "./properties/ETemperature";
/**
 * A region of the world.
 */
export class Region {

    constructor() {

    }

    alignment : EAlignment;
    biome : EBiome;
    biomeIntensity : EBiomeIntensity;
    danger : EDanger;
    luck : ELuck;
    populationDensity : EPopulationDensity;
    spirit: ESpirit;
    temperature: ETemperature;

}


text:
cms834
======

Educational Google Glass application for CMS.634/834


text:
function listener(e) {
    var root = /firefox|trident/i.test(navigator.userAgent) ? document.documentElement : document.body
        var easeInOutCubic = function(t, b, c, d) {
            if ((t/=d/2) < 1) return c/2*t*t*t + b
                return c/2*((t-=2)*t*t + 2) + b
        }
    var startTime
    var startPos = root.scrollTop
    var id = /[^#]+$/.exec(this.href)[0]
    var endPos = document.getElementById(id).getBoundingClientRect().top
    var maxScroll = root.scrollHeight - window.innerHeight
    var scrollEndValue = startPos + endPos < maxScroll ? endPos : maxScroll - startPos
    var duration = 500
    var scroll = function(timestamp) {
        startTime = startTime || timestamp
            var elapsed = timestamp - startTime
            var progress = easeInOutCubic(elapsed, startPos, scrollEndValue, duration)
            root.scrollTop = progress
            elapsed < duration && requestAnimationFrame(scroll)
    }
    requestAnimationFrame(scroll)
        setTimeout(function() {window.location.hash = id;}, duration)
        e.preventDefault()
}

function updateClickListeners() {
    "use strict"

    var links = document.querySelectorAll("a")
    var i = links.length

    while (i--) {
        if (links.item(i).className.match(/\bsmooth-scroll\b/)) {
            links.item(i).addEventListener("click", listener)
        } else {
            links.item(i).removeEventListener("click", listener)
        }
    }
}

if (document.readyState == "complete" || document.readyState == "loaded" || document.readyState == "interactive") {
    updateClickListeners();
} else {
    document.addEventListener("DOMContentLoaded", updateClickListeners)
}
window.addEventListener("resize", updateClickListeners)


text:
package org.openqa.selenium.remote.html5;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import org.openqa.selenium.html5.AppCacheEntry;
import org.openqa.selenium.html5.AppCacheStatus;
import org.openqa.selenium.html5.AppCacheType;
import org.openqa.selenium.html5.ApplicationCache;
import org.openqa.selenium.remote.AugmenterProvider;
import org.openqa.selenium.remote.DriverCommand;
import org.openqa.selenium.remote.ExecuteMethod;
import org.openqa.selenium.remote.InterfaceImplementation;

import com.google.common.collect.Lists;

public class AddApplicationCache implements AugmenterProvider {

  public Class<?> getDescribedInterface() {
    return ApplicationCache.class;
  }

  public InterfaceImplementation getImplementation(Object value) {
    return new InterfaceImplementation() {

      public Object invoke(ExecuteMethod executeMethod, Method method, Object... args) {
        if ("getAppCache".equals(method.getName())) {
          List<Object> result = (List<Object>) executeMethod.execute(DriverCommand.GET_APP_CACHE,
              null);
          List<AppCacheEntry> toReturn = Lists.newArrayList();
          for (Object obj : result) {
            Map<String, String> map = (Map<String, String>) obj;
            AppCacheEntry entry = new AppCacheEntry(AppCacheType.valueOf(map.get("type")),
                map.get("url"), map.get("mimeType"));
            toReturn.add(entry);
          }
          return toReturn;
        } else if ("getAppCacheStatus".equals(method.getName())) {
          String result = (String) executeMethod.execute(DriverCommand.GET_APP_CACHE_STATUS, null);
          return AppCacheStatus.valueOf(result);
        }
        return null;
      }
    };
  }

}


text:
import { ElementRef, Renderer, AfterViewInit } from "@angular/core";
export declare class FocusDirective implements AfterViewInit {
    private el;
    private renderer;
    value: string;
    constructor(el: ElementRef, renderer: Renderer);
    ngAfterViewInit(): void;
}


text:
namespace Apache.Ignite.Core.Impl.Common
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// Concurrent dictionary with CopyOnWrite mechanism inside.
    /// Good for frequent reads / infrequent writes scenarios.
    /// </summary>
    public class CopyOnWriteConcurrentDictionary<TKey, TValue>
    {
        /** */
        private volatile Dictionary<TKey, TValue> _dict = new Dictionary<TKey, TValue>();

        /// <summary>
        /// Gets the value associated with the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="val">The value.</param>
        /// <returns>true if the dictionary contains an element with the specified key; otherwise, false.</returns>
        public bool TryGetValue(TKey key, out TValue val)
        {
            return _dict.TryGetValue(key, out val);
        }

        /// <summary>
        /// Adds a key/value pair if the key does not already exist.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="valueFactory">The function used to generate a value for the key.</param>
        /// <returns>The value for the key.</returns>
        public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
        {
            lock (this)
            {
                TValue res;

                if (_dict.TryGetValue(key, out res))
                    return res;

                var dict0 = new Dictionary<TKey, TValue>(_dict);

                res = valueFactory(key);

                dict0[key] = res;

                _dict = dict0;

                return res;
            }
        }
    }
}