text:
describe('Working with Functions', function() {

  // Make a function that fullfills the description

  it('returning a number', function() {
    // Create a function called sum that recives 4 arguments and return the
    // sum of all of them

    assert.equal(sum.length, 4);
    assert.equal(sum(1,2,3,4), 10);
  })

  it('returning a string', function() {
    // Create a function called shout that appends two exclamation marks at the end

    assert.equal(shout.length, 1);
    assert.equal(shout('Hohoho'), 'Hohoho!!');
  })

  it('returning a function', function() {
    // Create a function called sum that acepts only one parameter and return
    // another function that as well takes only one parameter and sums both
    // numbers
    // Example of usage:
    // var sum = sum(3);
    // var result = sum(5);
    //  -> result should be 8
    // Note: This is what makes "currying" a function posible
    var result;

    assert.equal(sum.length, 1);
    sum = sum(3);
    assert.isFunction(sum);
    assert.equal(sum.length, 1);
    result = sum(5);
    assert.equal(result, 8);
  })

  it('passing a function as a parameter', function() {
    // Create a function that recieves the fullName of a person and a function
    // and executes the function with the fullName of the person.
    // Example of usage:
    // speak('Jhon Doe', yellAtHim) -> 'Jhon Doe!!!'
    // speak('Jhon Doe', salutation) -> 'Hi Jhon Doe!'
    // Note: This is the basic construction for all "callbacks"

    var yellAtHim = function(fullName) {
      return fullName+'!!!';
    };

    var salutation = function(fullName) {
      return 'Hi ' + fullName + '!';
    }

    assert.equal(speak.length, 2);
    assert.equal(speak('Jhon Doe', yellAtHim), 'Jhon Doe!!!');
    assert.equal(speak('Jhon Doe', salutation), 'Hi Jhon Doe!');
  })

  it('variable declaration inside functions', function() {
    // Modify the function to make the test pass
    // Note: This behavior can be hard to diggest at first; this behavior is
    //       known as "variable hoisting"

    var fnWithVariable = function() {
      nonExistedVar;
      var nonExistedVar = 7;
    }

    assert.throw(fnWithVariable, ReferenceError);
  })

  it('scope in functions', function() {
    // Modify the assertion to make the test pass

    var context = function() {
      return this;
    }

    assert.deepEqual(context(), context);
  })
})


text:
Produce, consume queue
--SKIPIF--
<?php
require __DIR__ . '/integration-tests-check.php';
--FILE--
<?php
require __DIR__ . '/integration-tests-check.php';

$delivered = 0;

$conf = new RdKafka\Conf();
if (RD_KAFKA_VERSION >= 0x090000 && false !== getenv('TEST_KAFKA_BROKER_VERSION')) {
    $conf->set('broker.version.fallback', getenv('TEST_KAFKA_BROKER_VERSION'));
}
$conf->setErrorCb(function ($producer, $err, $errstr) {
    printf("%s: %s\n", rd_kafka_err2str($err), $errstr);
    exit;
});
$conf->setDrMsgCb(function ($producer, $msg) use (&$delivered) {
    if ($msg->err) {
        throw new Exception("Message delivery failed: " . $msg->errstr());
    }
    $delivered++;
});
$conf->set('metadata.broker.list', getenv('TEST_KAFKA_BROKERS'));

$producer = new RdKafka\Producer($conf);

$topicNames = [
    sprintf("test_rdkafka_0_%s", uniqid()),
    sprintf("test_rdkafka_1_%s", uniqid()),
];

$topics = array_map(function ($topicName) use ($producer) {
    return $producer->newTopic($topicName);
}, $topicNames);

if (!$producer->getMetadata(false, reset($topics), 10*1000)) {
    echo "Failed to get metadata, is broker down?\n";
}

for ($i = 0; $i < 10; $i++) {
    $topics[$i%2]->produce(0, 0, "message $i");
    $producer->poll(0);
}

while ($producer->getOutQLen()) {
    $producer->poll(50);
}

printf("%d messages delivered\n", $delivered);

$conf = new RdKafka\Conf();
// Required to detect actual reaching of partition EOF for both topics
$conf->set('enable.partition.eof', 'true');
if (RD_KAFKA_VERSION >= 0x090000 && false !== getenv('TEST_KAFKA_BROKER_VERSION')) {
    $conf->set('broker.version.fallback', getenv('TEST_KAFKA_BROKER_VERSION'));
}
$conf->setErrorCb(function ($producer, $err, $errstr) {
    printf("%s: %s\n", rd_kafka_err2str($err), $errstr);
    exit;
});

$conf->set('metadata.broker.list', getenv('TEST_KAFKA_BROKERS'));

$consumer = new RdKafka\Consumer($conf);

$queue = $consumer->newQueue();

array_walk($topicNames, function ($topicName) use ($consumer, $queue) {
    $topic = $consumer->newTopic($topicName);
    $topic->consumeQueueStart(0, RD_KAFKA_OFFSET_BEGINNING, $queue);
});

$messages = [];
$receivedTopicEofs = [];

while (count($receivedTopicEofs) < 2) {
    $msg = $queue->consume(15000);
    if (!$msg) {
        // Still waiting for messages
        continue;
    }

    if (RD_KAFKA_RESP_ERR__PARTITION_EOF === $msg->err) {
        // Reached actual EOF
        $receivedTopicEofs[$msg->topic_name] = true;
        continue;
    }

    if (RD_KAFKA_RESP_ERR_NO_ERROR !== $msg->err) {
        throw new Exception($msg->errstr(), $msg->err);
    }

    $messages[] = sprintf("Got message: %s from %s", $msg->payload, $msg->topic_name);
}

sort($messages);
echo implode("\n", $messages), "\n";

--EXPECTF--
10 messages delivered
Got message: message 0 from test_rdkafka_0_%s
Got message: message 1 from test_rdkafka_1_%s
Got message: message 2 from test_rdkafka_0_%s
Got message: message 3 from test_rdkafka_1_%s
Got message: message 4 from test_rdkafka_0_%s
Got message: message 5 from test_rdkafka_1_%s
Got message: message 6 from test_rdkafka_0_%s
Got message: message 7 from test_rdkafka_1_%s
Got message: message 8 from test_rdkafka_0_%s
Got message: message 9 from test_rdkafka_1_%s

redpajama_set_name: RedPajamaGithub


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     Der Code wurde von einer Vorlage generiert.
//
//     Manuelle Änderungen an dieser Datei führen möglicherweise zu unerwartetem Verhalten der Anwendung.
//     Manuelle Änderungen an dieser Datei werden überschrieben, wenn der Code neu generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Moody.EntityFrameworkSample.DatabaseFirstSample
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class DotaEntities : DbContext
    {
        public DotaEntities()
            : base("name=DotaEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Game> Games { get; set; }
        public virtual DbSet<Hero> Heroes { get; set; }
        public virtual DbSet<RoleType> RoleTypes { get; set; }
    }
}


text:
PEGASUS_USING_PEGASUS;

SNMPIndicationProvider::SNMPIndicationProvider() throw()
{
}

SNMPIndicationProvider::~SNMPIndicationProvider() throw()
{
}

void SNMPIndicationProvider::initialize(CIMOMHandle& cimom)
{
    // save cimom handle
    _cimom = cimom;
}

void SNMPIndicationProvider::terminate()
{
    delete this;
}

void SNMPIndicationProvider::enableIndications(
    IndicationResponseHandler& handler)
{
    handler.processing();

    //Indication
    CIMInstance cimInstance(
        PEGASUS_NAMESPACENAME_INTEROP.getString() +
            ":cycHostAdapterDiscovered");

    cimInstance.addProperty(CIMProperty("cycHostAdapterNumber", Uint32(101)));
    cimInstance.addProperty(
        CIMProperty("cycHostAdapterID", String("HP-NU-123")));
    cimInstance.addProperty(CIMProperty("cycManagerID", String("HP-NU-456")));

    CIMIndication cimIndication(cimInstance);

    handler.deliver(cimIndication);
}

void SNMPIndicationProvider::disableIndications()
{
    //handler.complete();
}

void SNMPIndicationProvider::createSubscription(
    const OperationContext& context,
    const CIMObjectPath& subscriptionName,
    const Array<CIMObjectPath>& classNames,
    const CIMPropertyList& propertyList,
    const Uint16 repeatNotificationPolicy)
{
}

void SNMPIndicationProvider::modifySubscription(
    const OperationContext& context,
    const CIMObjectPath& subscriptionName,
    const Array<CIMObjectPath>& classNames,
    const CIMPropertyList& propertyList,
    const Uint16 repeatNotificationPolicy)
{
}

void SNMPIndicationProvider::deleteSubscription(
    const OperationContext& context,
    const CIMObjectPath& subscriptionName,
    const Array<CIMObjectPath>& classNames)
{
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Halma</title>

Canvas Halma

Moves count: 0

<canvas id="mycanvas" width="500" height="500"></canvas>


text:
<?php declare(strict_types=1);

namespace Symplify\ControllerAutowire\Tests\DependencyInjection\Compiler\RegisterControllersPassSource;

class SomeController
{
}


text:
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

#endif // MAINWINDOW_H


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>ViennaCL - The Vienna Computing Library: sparse_matrix_adapted_iterator< SCALARTYPE, is_iterator1 > Class Template Reference</title>

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

ViennaCL - The Vienna Computing Library
    1.3.1

Main Page

Namespaces

Data Structures

Files

Data Structures

Class Hierarchy

Data Fields

viennacl

tools

sparse_matrix_adapted_iterator

Public Types |
Public Member Functions

sparse_matrix_adapted_iterator< SCALARTYPE, is_iterator1 > Class Template Reference

A non-const iterator for sparse matrices of type std::vector<std::map<unsigned int, SCALARTYPE> >
 More...

#include <adapter.hpp>

Public Types

typedef self_type 	iterator1

typedef self_type 	iterator2

typedef std::size_t 	size_type

Public Member Functions

 	sparse_matrix_adapted_iterator (std::vector< std::map< unsigned int, SCALARTYPE > > &mat, int i, int j)

SCALARTYPE & 	operator* (void)

self_type & 	operator++ (void)

self_type & 	operator++ (int)

self_type 	operator+= (size_type offset)

bool 	operator== (self_type const &other) const

bool 	operator!= (self_type const &other) const

size_type 	index1 () const

size_type 	index2 () const

sparse_matrix_adapted_iterator

< SCALARTYPE,!is_iterator1 > 	begin () const

sparse_matrix_adapted_iterator

< SCALARTYPE,!is_iterator1 > 	end () const

Detailed Description

template<typename SCALARTYPE, bool is_iterator1>

class viennacl::tools::sparse_matrix_adapted_iterator< SCALARTYPE, is_iterator1 >

A non-const iterator for sparse matrices of type std::vector<std::map<unsigned int, SCALARTYPE> >

The iterator behaves like ublas iterators. Attention: Iteration along first columns and then rows via .begin() is untested! Reverse iterators are missing!

Template Parameters:

SCALARTYPE	either float or double

is_iterator1	if true, this iterator iterates along increasing row indices, otherwise along increasiong column indices

Member Typedef Documentation

          typedef self_type iterator1

          typedef self_type iterator2

          typedef std::size_t size_type

Constructor & Destructor Documentation

          sparse_matrix_adapted_iterator
          (
          std::vector< std::map< unsigned int, SCALARTYPE > > &
          mat,

          int
          i,

          int
          j

          )
          	 [inline]

Member Function Documentation

          sparse_matrix_adapted_iterator<SCALARTYPE, !is_iterator1> begin
          (
          	)
           const [inline]

          sparse_matrix_adapted_iterator<SCALARTYPE, !is_iterator1> end
          (
          	)
           const [inline]

          size_type index1
          (
          	)
           const [inline]

          size_type index2
          (
          	)
           const [inline]

          bool operator!=
          (
          self_type const &
          other	)
           const [inline]

          SCALARTYPE& operator*
          (
          void
          	)
           [inline]

          self_type& operator++
          (
          void
          	)
           [inline]

          self_type& operator++
          (
          int
          	)
           [inline]

          self_type operator+=
          (
          size_type
          offset	)
           [inline]

          bool operator==
          (
          self_type const &
          other	)
           const [inline]

The documentation for this class was generated from the following file:

viennacl/tools/adapter.hpp

<address class="footer">
Generated on Thu Aug 9 2012 19:49:13 for ViennaCL - The Vienna Computing Library by

 1.7.6.1
</address>


text:
package calico.plugins.examplePlugin;

import org.apache.log4j.Logger;

import calico.Calico;
import calico.CalicoOptions;
import calico.components.menus.CanvasMenuBar;
import calico.components.menus.CanvasStatusBar;
import calico.events.CalicoEventHandler;
import calico.events.CalicoEventListener;
import calico.networking.Networking;
import calico.networking.PacketHandler;
import calico.networking.netstuff.CalicoPacket;
import calico.plugins.CalicoPlugin;
import calico.plugins.examplePlugin.components.buttons.CreateCustomScrapButton;
import calico.plugins.examplePlugin.controllers.CustomScrapController;
import calico.plugins.examplePlugin.iconsets.CalicoIconManager;

public class ExamplePlugin extends CalicoPlugin
	implements CalicoEventListener
{
	//the logger for this plugin
	public static Logger logger = Logger.getLogger(ExamplePlugin.class.getName());

	public ExamplePlugin()
	{
		super();
		PluginInfo.name = "ExamplePlugin";
		calico.plugins.examplePlugin.iconsets.CalicoIconManager.setIconTheme(this.getClass(), CalicoOptions.core.icontheme);
	}

	public void onPluginStart()
	{
		// Register for events that this plugin will perform
		for (Integer event : this.getNetworkCommands())
			CalicoEventHandler.getInstance().addListener(event.intValue(), this, CalicoEventHandler.ACTION_PERFORMER_LISTENER);

		CanvasStatusBar.addMenuButtonRightAligned(CreateCustomScrapButton.class);

		//Add an additional voice to the bubble menu
		//CGroup.registerPieMenuButton(SaveToPaletteButton.class);

		//Register to the events I am interested in from Calico's core events
		//Example: CalicoEventHandler.getInstance().addListener(NetworkCommand.VIEWING_SINGLE_CANVAS, this, CalicoEventHandler.PASSIVE_LISTENER);

	}

	public void onPluginEnd()
	{
		// do nothing
	}

	@Override
	public Class<?> getNetworkCommandsClass()
	{
		return ExamplePluginNetworkCommands.class;
	}

	@Override
	/**
	 * Plugin specific commands can be defined
	 * in the example plugin network commands class
	 */
	public void handleCalicoEvent(int event, CalicoPacket p) {
		switch (event) {
			case ExamplePluginNetworkCommands.CUSTOM_SCRAP_CREATE:
				CUSTOM_SCRAP_CREATE(p);
				break;
		}
	}

	/*************************************************
	 * UI ENTRY POINTS
	 * The user interface calls those methods
	 * which create the command packets to send
	 * to the network
	 *************************************************/

	public static void UI_send_command(int com, Object... params){
		//Create the packet
		CalicoPacket p;
		if(params!=null){
			p=CalicoPacket.getPacket(com, params);
		}
		else{
			p=CalicoPacket.getPacket(com);
		}

		p.rewind();
		//Send the packet locally
		PacketHandler.receive(p);

		//Send the packet to the network (server)
//		Networking.send(p);
	}

	/*************************************************
	 * COMMANDS
	 * This is where the actual commands are
	 * received and processed by the different
	 * controllers
	 *************************************************/
	private void CUSTOM_SCRAP_CREATE(CalicoPacket p) {
		p.rewind();
		p.getInt();
		long new_uuid=p.getLong();
		long cuuid=p.getLong();
		int x=p.getInt();
		int y=p.getInt();

		CustomScrapController.create_custom_scrap(new_uuid, cuuid, x, y);

	}
}


text:
@interface NSArray (HOFC)

- (NSArray *)map:(id (^)(id obj))block
           class:(Class)aClass;
- (NSArray *)filter:(BOOL (^)(id obj))block
              class:(Class)aClass;
- (id)reduce:(id)initial
       block:(id (^)(id obj1, id obj2))block
       class:(Class)aClass;
- (NSArray *)flatMap:(id (^)(id obj))block
               class:(Class)aClass;
- (BOOL)contains:(BOOL (^)(id obj))block
           class:(Class)aClass;
- (void)forEach:(void (^)(id obj))block
          class:(Class)aClass;

@end


text:
package vprExplorer;

import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;

public final class Settings {
	public static enum service { _REMOTE, _LOCAL_SERVER, _FILE};
	private GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
	private String user = "";
	private char[] password;
	private Dimension screensize;

	service servicetype;
	int port = 3030;

	public Settings() {
		int screenwidth = gd.getDisplayMode().getWidth();
		int screenheight = gd.getDisplayMode().getHeight();

		screensize = new Dimension(screenwidth, screenheight);
	}

	public Dimension getScreenDimensions() {
		return screensize;
	}

	public int getScreenWidth() {
		return (int) screensize.getWidth();
	}

	public int getScreenHeight() {
		return (int) screensize.getHeight();
	}

	public void setService(service ser) {
		servicetype = ser;
	}

	public service getService() {
		return servicetype;
	}

	public void setPort(int portnum) {
		port = portnum;
	}

	public void setPassword(char[] pwd) {
		password = pwd;
	}

	public char[] getPassword() {
		return password;
	}

	public int getPort() {
		return port;
	}

	public void setPorttoLocalDefault() {
		port = 3030;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

}


text:
package net.javacrumbs.shedlock.spring.aop;

import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.core.annotation.AliasFor;
import org.springframework.scheduling.annotation.Scheduled;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

public class SpringLockConfigurationExtractorTest extends AbstractSpringLockConfigurationExtractorTest {

    @SchedulerLock(name = "lockName", lockAtMostFor = "100")
    public void annotatedMethod() {

    }

    @SchedulerLock(name = "lockName", lockAtMostFor = "${placeholder}")
    public void annotatedMethodWithString() {

    }

    @SchedulerLock(name = "lockName", lockAtMostFor = "PT1S")
    public void annotatedMethodWithDurationString() {

    }

    @SchedulerLock(name = "${name}")
    public void annotatedMethodWithNameVariable() {

    }

    @SchedulerLock(name = "lockName")
    public void annotatedMethodWithoutLockAtMostFor() {

    }

    @SchedulerLock(name = "lockName", lockAtLeastFor = "0")
    public void annotatedMethodWithZeroGracePeriod() {

    }

    @SchedulerLock(name = "lockName", lockAtLeastFor = "10")
    public void annotatedMethodWithPositiveGracePeriod() {

    }

    @SchedulerLock(name = "lockName", lockAtLeastFor = "10ms")
    public void annotatedMethodWithPositiveGracePeriodWithString() {

    }

    @SchedulerLock(name = "lockName", lockAtLeastFor = "-1s")
    public void annotatedMethodWithNegativeGracePeriod() {

    }

    @ScheduledLocked(name = "lockName1")
    public void composedAnnotation() {

    }

    public void methodWithoutAnnotation() {

    }

    @Target(METHOD)
    @Retention(RUNTIME)
    @Documented
    @Scheduled
    @SchedulerLock
    public @interface ScheduledLocked {
        @AliasFor(annotation = Scheduled.class, attribute = "cron")
        String cron() default "";

        @AliasFor(annotation = SchedulerLock.class, attribute = "lockAtMostFor")
        String lockAtMostFor() default "20";

        @AliasFor(annotation = SchedulerLock.class, attribute = "name")
        String name();
    }
}


text:
package workQ

import (
	"sync"
	"testing"
	"time"
)

type sleepWorkerQueue struct {
	queue WorkQ
	in    chan sleepWorker
	out   chan sleepWorker
}

func newSleepWorkerQueue() sleepWorkerQueue {
	queue := NewWorkQ()
	in := make(chan sleepWorker)
	go func() {
		wrappedIn := queue.In()
		defer close(wrappedIn)
		for worker := range in {
			wrappedIn <- worker
		}
	}()
	out := make(chan sleepWorker)
	go func() {
		wrappedOut := queue.Out()
		defer close(out)
		for worker := range wrappedOut {
			sleepWorker, ok := worker.(sleepWorker)
			if !ok {
				panic("WAT!?!?!")
			}
			out <- sleepWorker
		}
	}()
	return sleepWorkerQueue{
		queue: queue,
		in:    in,
		out:   out,
	}
}

func (b *sleepWorkerQueue) Out() <-chan sleepWorker {
	return b.out
}

func (b *sleepWorkerQueue) In() chan<- sleepWorker {
	return b.in
}

type sleepWorker struct {
	Number int
}

func (b sleepWorker) Work() {
	time.Sleep(time.Millisecond * time.Duration(b.Number%50))
}

func _TestBasicUsage(t *testing.T) {
	queue := NewWorkQ()
	in := queue.In()
	sleepWorker := sleepWorker{1}
	in <- sleepWorker
	worker := <-queue.Out()
	if worker == nil || worker != sleepWorker {
		t.Fatal("Couldn't get a single element through")
	}
}

func TestBasic50kWorkers(t *testing.T) {
	queue := NewWorkQ()
	in := queue.In()
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		for i := 1; i < 50000; i++ {
			sleepWorker := sleepWorker{i}
			in <- sleepWorker
		}
		close(in)
		wg.Done()
	}()
	go func() {
		i := 1
		for worker := range queue.Out() {
			sleepWorker, ok := worker.(sleepWorker)
			if !ok || sleepWorker.Number != i {
				t.Errorf("something went wrong for i: %d and worker: %v", i, sleepWorker)
			}
			i++
		}
		wg.Done()
	}()
	wg.Wait()
}

func TestSleepWorkerQueueWrapper50K(t *testing.T) {
	queue := newSleepWorkerQueue()
	in := queue.In()
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		for i := 1; i < 50000; i++ {
			sleepWorker := sleepWorker{i}
			in <- sleepWorker
		}
		close(in)
		wg.Done()
	}()
	go func() {
		i := 1
		for worker := range queue.Out() {
			if worker.Number != i {
				t.Errorf("something went wrong for i: %d and worker: %v", i, worker)
			}
			i++
		}
		wg.Done()
	}()
	wg.Wait()
}


text:
#include "xenia/kernel/xboxkrnl/xboxkrnl_module.h"

#include <gflags/gflags.h>

#include <vector>

#include "xenia/base/clock.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/emulator.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/user_module.h"
#include "xenia/kernel/xboxkrnl/xboxkrnl_private.h"

namespace xe {
namespace kernel {
namespace xboxkrnl {

XboxkrnlModule::XboxkrnlModule(Emulator* emulator, KernelState* kernel_state)
    : KernelModule(kernel_state, "xe:\\xboxkrnl.exe"),
      timestamp_timer_(nullptr) {
  RegisterExportTable(export_resolver_);

  // Register all exported functions.
  RegisterAudioExports(export_resolver_, kernel_state_);
  RegisterAudioXmaExports(export_resolver_, kernel_state_);
  RegisterCryptExports(export_resolver_, kernel_state_);
  RegisterDebugExports(export_resolver_, kernel_state_);
  RegisterErrorExports(export_resolver_, kernel_state_);
  RegisterHalExports(export_resolver_, kernel_state_);
  RegisterIoExports(export_resolver_, kernel_state_);
  RegisterMemoryExports(export_resolver_, kernel_state_);
  RegisterMiscExports(export_resolver_, kernel_state_);
  RegisterModuleExports(export_resolver_, kernel_state_);
  RegisterObExports(export_resolver_, kernel_state_);
  RegisterRtlExports(export_resolver_, kernel_state_);
  RegisterStringExports(export_resolver_, kernel_state_);
  RegisterThreadingExports(export_resolver_, kernel_state_);
  RegisterUsbcamExports(export_resolver_, kernel_state_);
  RegisterVideoExports(export_resolver_, kernel_state_);

  // KeDebugMonitorData (?*)
  // Set to a valid value when a remote debugger is attached.
  // Offset 0x18 is a 4b pointer to a handler function that seems to take two
  // arguments. If we wanted to see what would happen we could fake that.
  uint32_t pKeDebugMonitorData = memory_->SystemHeapAlloc(256);
  auto lpKeDebugMonitorData = memory_->TranslateVirtual(pKeDebugMonitorData);
  export_resolver_->SetVariableMapping(
      "xboxkrnl.exe", ordinals::KeDebugMonitorData, pKeDebugMonitorData);
  xe::store_and_swap<uint32_t>(lpKeDebugMonitorData, 0);

  // KeCertMonitorData (?*)
  // Always set to zero, ignored.
  uint32_t pKeCertMonitorData = memory_->SystemHeapAlloc(4);
  auto lpKeCertMonitorData = memory_->TranslateVirtual(pKeCertMonitorData);
  export_resolver_->SetVariableMapping(
      "xboxkrnl.exe", ordinals::KeCertMonitorData, pKeCertMonitorData);
  xe::store_and_swap<uint32_t>(lpKeCertMonitorData, 0);

  // XboxHardwareInfo (XboxHardwareInfo_t, 16b)
  // flags       cpu#  ?     ?     ?     ?           ?       ?
  // 0x00000000, 0x06, 0x00, 0x00, 0x00, 0x00000000, 0x0000, 0x0000
  // Games seem to check if bit 26 (0x20) is set, which at least for xbox1
  // was whether an HDD was present. Not sure what the other flags are.
  //
  // aomega08 says the value is 0x02000817, bit 27: debug mode on.
  // When that is set, though, allocs crash in weird ways.
  uint32_t pXboxHardwareInfo = memory_->SystemHeapAlloc(16);
  auto lpXboxHardwareInfo = memory_->TranslateVirtual(pXboxHardwareInfo);
  export_resolver_->SetVariableMapping(
      "xboxkrnl.exe", ordinals::XboxHardwareInfo, pXboxHardwareInfo);
  xe::store_and_swap<uint32_t>(lpXboxHardwareInfo + 0, 0);    // flags
  xe::store_and_swap<uint8_t>(lpXboxHardwareInfo + 4, 0x06);  // cpu count
  // Remaining 11b are zeroes?

  // XexExecutableModuleHandle (?**)
  // Games try to dereference this to get a pointer to some module struct.
  // So far it seems like it's just in loader code, and only used to look up
  // the XexHeaderBase for use by RtlImageXexHeaderField.
  // We fake it so that the address passed to that looks legit.
  // 0x80100FFC <- pointer to structure
  // 0x80101000 <- our module structure
  // 0x80101058 <- pointer to xex header
  // 0x80101100 <- xex header base
  uint32_t ppXexExecutableModuleHandle = memory_->SystemHeapAlloc(4);
  export_resolver_->SetVariableMapping("xboxkrnl.exe",
                                       ordinals::XexExecutableModuleHandle,
                                       ppXexExecutableModuleHandle);

  // ExLoadedCommandLine (char*)
  // The name of the xex. Not sure this is ever really used on real devices.
  // Perhaps it's how swap disc/etc data is sent?
  // Always set to "default.xex" (with quotes) for now.
  uint32_t pExLoadedCommandLine = memory_->SystemHeapAlloc(1024);
  auto lpExLoadedCommandLine = memory_->TranslateVirtual(pExLoadedCommandLine);
  export_resolver_->SetVariableMapping(
      "xboxkrnl.exe", ordinals::ExLoadedCommandLine, pExLoadedCommandLine);
  char command_line[] = "\"default.xex\"";
  std::memcpy(lpExLoadedCommandLine, command_line,
              xe::countof(command_line) + 1);

  // XboxKrnlVersion (8b)
  // Kernel version, looks like 2b.2b.2b.2b.
  // I've only seen games check >=, so we just fake something here.
  uint32_t pXboxKrnlVersion = memory_->SystemHeapAlloc(8);
  auto lpXboxKrnlVersion = memory_->TranslateVirtual(pXboxKrnlVersion);
  export_resolver_->SetVariableMapping(
      "xboxkrnl.exe", ordinals::XboxKrnlVersion, pXboxKrnlVersion);
  xe::store_and_swap<uint16_t>(lpXboxKrnlVersion + 0, 2);
  xe::store_and_swap<uint16_t>(lpXboxKrnlVersion + 2, 0xFFFF);
  xe::store_and_swap<uint16_t>(lpXboxKrnlVersion + 4, 0xFFFF);
  xe::store_and_swap<uint8_t>(lpXboxKrnlVersion + 6, 0x80);
  xe::store_and_swap<uint8_t>(lpXboxKrnlVersion + 7, 0x00);

  // KeTimeStampBundle (ad)
  // This must be updated during execution, at 1ms intevals.
  // We setup a system timer here to do that.
  uint32_t pKeTimeStampBundle = memory_->SystemHeapAlloc(24);
  auto lpKeTimeStampBundle = memory_->TranslateVirtual(pKeTimeStampBundle);
  export_resolver_->SetVariableMapping(
      "xboxkrnl.exe", ordinals::KeTimeStampBundle, pKeTimeStampBundle);
  xe::store_and_swap<uint64_t>(lpKeTimeStampBundle + 0, 0);
  xe::store_and_swap<uint64_t>(lpKeTimeStampBundle + 8, 0);
  xe::store_and_swap<uint32_t>(lpKeTimeStampBundle + 16,
                               Clock::QueryGuestUptimeMillis());
  xe::store_and_swap<uint32_t>(lpKeTimeStampBundle + 20, 0);
  timestamp_timer_ = xe::threading::HighResolutionTimer::CreateRepeating(
      std::chrono::milliseconds(1), [lpKeTimeStampBundle]() {
        xe::store_and_swap<uint32_t>(lpKeTimeStampBundle + 16,
                                     Clock::QueryGuestUptimeMillis());
      });
}

std::vector<xe::cpu::Export*> xboxkrnl_exports(4096);

xe::cpu::Export* RegisterExport_xboxkrnl(xe::cpu::Export* export_entry) {
  assert_true(export_entry->ordinal < xboxkrnl_exports.size());
  xboxkrnl_exports[export_entry->ordinal] = export_entry;
  return export_entry;
}

void XboxkrnlModule::RegisterExportTable(
    xe::cpu::ExportResolver* export_resolver) {
  assert_not_null(export_resolver);

// Build the export table used for resolution.
#include "xenia/kernel/util/export_table_pre.inc"
  static xe::cpu::Export xboxkrnl_export_table[] = {
#include "xenia/kernel/xboxkrnl/xboxkrnl_table.inc"
  };
#include "xenia/kernel/util/export_table_post.inc"
  for (size_t i = 0; i < xe::countof(xboxkrnl_export_table); ++i) {
    auto& export_entry = xboxkrnl_export_table[i];
    assert_true(export_entry.ordinal < xboxkrnl_exports.size());
    if (!xboxkrnl_exports[export_entry.ordinal]) {
      xboxkrnl_exports[export_entry.ordinal] = &export_entry;
    }
  }
  export_resolver->RegisterTable("xboxkrnl.exe", &xboxkrnl_exports);
}

XboxkrnlModule::~XboxkrnlModule() = default;

}  // namespace xboxkrnl
}  // namespace kernel
}  // namespace xe


text:
Given two lists determine if the first list is contained within the second
list, if the second list is contained within the first list, if both lists are
contained within each other or if none of these are true.

Specifically, a list A is a sublist of list B if by dropping 0 or more elements
from the front of B and 0 or more elements from the back of B you get a list
that's completely equal to A.

Examples:

 * A = [1, 2, 3], B = [1, 2, 3, 4, 5], A is a sublist of B
 * A = [3, 4, 5], B = [1, 2, 3, 4, 5], A is a sublist of B
 * A = [3, 4], B = [1, 2, 3, 4, 5], A is a sublist of B
 * A = [1, 2, 3], B = [1, 2, 3], A is equal to B
 * A = [1, 2, 3, 4, 5], B = [2, 3, 4], A is a superlist of B
 * A = [1, 2, 4], B = [1, 2, 3, 4, 5], A is not a superlist of, sublist of or equal to B

## Setup

Go through the setup instructions for Javascript to install the necessary
dependencies:

[https://exercism.io/tracks/javascript/installation](https://exercism.io/tracks/javascript/installation)

## Requirements

Please `cd` into exercise directory before running all below commands.

Install assignment dependencies:

```bash
$ npm install
```

## Making the test suite pass

Execute the tests with:

```bash
$ npm test
```

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing `xtest` to
`test`.

## Submitting Solutions

Once you have a solution ready, you can submit it using:

```bash
exercism submit sublist.js
```

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have
completed the exercise.


text:
#include "Interaction.hpp"
#include "FirstOrderType1RTest.hpp"
#include "SSLH.hpp"

#define CPPUNIT_ASSERT_NOT_EQUAL(message, alpha, omega)      \
            if ((alpha) == (omega)) CPPUNIT_FAIL(message);

// test suite registration
CPPUNIT_TEST_SUITE_REGISTRATION(FirstOrderType1RTest);

void FirstOrderType1RTest::setUp()
{
}

void FirstOrderType1RTest::tearDown()
{
}

// data constructor
void FirstOrderType1RTest::testBuildFirstOrderType1R1()
{
  std::cout << "======================================" <<std::endl;
  std::cout << "=== FirstOrderType1R tests start ...== " <<std::endl;
  std::cout << "======================================" <<std::endl;
  std::cout << "--> Test: constructor 1 " <<std::endl;

  SP::FirstOrderType1R R1(new FirstOrderType1R("TestPlugin:hT1", "TestPlugin:gT1"));

  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R1b : ", R1->getType() == RELATION::FirstOrder, true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R1c : ", R1->getSubType() == RELATION::Type1R, true);
  //  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R1d : ", R1->gethName()=="TestPlugin:hT1", true);
  //  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R1e : ", R1->getgName()=="TestPlugin:gT1", true);
  std::string plugin = "TestPlugin" + SSLH::getSharedLibraryExtension();
  R1->setComputeJachxFunction(plugin, "Jh0T1");
  R1->setComputeJacglambdaFunction(plugin, "Jg0T1");
  //  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R1e : ", R1->getJachName(0)=="TestPlugin:Jh0T1", true);
  //  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R1g : ", R1->getJacgName(0)=="TestPlugin:Jg0T1", true);
  std::cout << "--> Constructor1 test ended with success." <<std::endl;
}

void FirstOrderType1RTest::testBuildFirstOrderType1R2()
{
  std::cout << "--> Test: constructor data (2)." <<std::endl;
  SP::FirstOrderType1R R2(new FirstOrderType1R("TestPlugin:hT1", "TestPlugin:gT1", "TestPlugin:Jh0T1", "TestPlugin:Jg0T1"));
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R2b : ", R2->getType() == RELATION::FirstOrder, true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R2c : ", R2->getSubType() == RELATION::Type1R, true);
  //  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R2d : ", R2->gethName()=="TestPlugin:hT1", true);
  //  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R2e : ", R2->getgName()=="TestPlugin:gT1", true);
  //  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R2e : ", R2->getJachName(0)=="TestPlugin:Jh0T1", true);
  //  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildFirstOrderType1R2g : ", R2->getJacgName(0)=="TestPlugin:Jg0T1", true);
  std::cout << "--> Constructor2 test ended with success." <<std::endl;
}

void FirstOrderType1RTest::End()
{
  std::cout << "==========================================" <<std::endl;
  std::cout << " ===== End of FirstOrderType1R Tests ===== " <<std::endl;
  std::cout << "==========================================" <<std::endl;
}


text:
.class public interface abstract Lnet/clickdev/music/widgets/ShowHideMasterLayout$OnMasterVisibilityChangedListener;
.super Ljava/lang/Object;
.source "ShowHideMasterLayout.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lnet/clickdev/music/widgets/ShowHideMasterLayout;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "OnMasterVisibilityChangedListener"
.end annotation

# virtual methods
.method public abstract onMasterVisibilityChanged(Z)V
.end method


text:
import React from 'react'

import Alignment from './Children/Alignment'
import Flex from './Children/Flex'
import FlexAdditional from './Children/FlexAdditional'
import FlexPercent from './Children/FlexPercent'
import FlexResponsive from './Children/FlexResponsive'
import Offsets from './Children/Offsets'
import Ordering from './Children/Ordering'

const Children = () => (

Children

    <Flex />
    <FlexPercent />
    <FlexResponsive />
    <FlexAdditional />
    <Ordering />
    <Offsets />
    <Alignment />

)

export default Children


text:
// TensorFlow implementation of the ClassifierInterface.

#ifndef TENSORFLOW_SERVING_SERVABLES_TENSORFLOW_CLASSIFIER_H_
#define TENSORFLOW_SERVING_SERVABLES_TENSORFLOW_CLASSIFIER_H_

#include <memory>

#include "absl/types/optional.h"
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/threadpool_options.h"
#include "tensorflow_serving/apis/classifier.h"

namespace tensorflow {
namespace serving {

// Create a new ClassifierInterface backed by a TensorFlow SavedModel.
// Requires that the default SignatureDef be compatible with classification.
Status CreateClassifierFromSavedModelBundle(
    const RunOptions& run_options, std::unique_ptr<SavedModelBundle> bundle,
    std::unique_ptr<ClassifierInterface>* service);

// Create a new ClassifierInterface backed by a TensorFlow Session using the
// specified SignatureDef. Does not take ownership of the Session.
// Useful in contexts where we need to avoid copying, e.g. if created per
// request. The caller must ensure that the session and signature live at least
// as long as the service.
Status CreateFlyweightTensorFlowClassifier(
    const RunOptions& run_options, Session* session,
    const SignatureDef* signature,
    std::unique_ptr<ClassifierInterface>* service);

// Similar to the above function, but with an additional 'thread_pool_options'.
Status CreateFlyweightTensorFlowClassifier(
    const RunOptions& run_options, Session* session,
    const SignatureDef* signature,
    const thread::ThreadPoolOptions& thread_pool_options,
    std::unique_ptr<ClassifierInterface>* service);

// Get a classification signature from the meta_graph_def that's either:
// 1) The signature that model_spec explicitly specifies to use.
// 2) The default serving signature.
// If neither exist, or there were other issues, an error status is returned.
Status GetClassificationSignatureDef(const ModelSpec& model_spec,
                                     const MetaGraphDef& meta_graph_def,
                                     SignatureDef* signature);

// Validate a SignatureDef to make sure it's compatible with classification.
// Populate the input and output tensor names, if the args are not nullptr.
//
// NOTE: output_tensor_names may already have elements in it (e.g. when building
// a full list of outputs from multiple signatures), and this function will just
// append to the vector.
Status PreProcessClassification(const SignatureDef& signature,
                                string* input_tensor_name,
                                std::vector<string>* output_tensor_names);

// Validate all results and populate a ClassificationResult.
Status PostProcessClassificationResult(
    const SignatureDef& signature, int num_examples,
    const std::vector<string>& output_tensor_names,
    const std::vector<Tensor>& output_tensors, ClassificationResult* result);

// Creates SavedModelTensorflowClassifier and runs Classification on it.
Status RunClassify(const RunOptions& run_options,
                   const MetaGraphDef& meta_graph_def,
                   const absl::optional<int64_t>& servable_version,
                   Session* session, const ClassificationRequest& request,
                   ClassificationResponse* response,
                   const thread::ThreadPoolOptions& thread_pool_options =
                       thread::ThreadPoolOptions());

}  // namespace serving
}  // namespace tensorflow

#endif  // TENSORFLOW_SERVING_SERVABLES_TENSORFLOW_CLASSIFIER_H_


text:
[![Luacheck](https://github.com/lunarmodules/LDoc/workflows/Luacheck/badge.svg)](https://github.com/lunarmodules/LDoc/actions)

Copyright (C) 2011-2012 Steve Donovan.

## Rationale

This project grew out of the documentation needs of
[Penlight](https://github.com/lunarmodules/Penlight) (and not always getting satisfaction
with LuaDoc) and depends on Penlight itself. (This allowed me to _not_ write a lot of code.)

The [API documentation](https://lunarmodules.github.io/Penlight/) of Penlight
is an example of a project using plain LuaDoc markup processed using LDoc.

LDoc is intended to be compatible with [LuaDoc](https://keplerproject.github.io/luadoc/) and
thus follows the pattern set by the various *Doc tools:

    --- Summary ends with a period.
    -- Some description, can be over several lines.
    -- @param p1 first parameter
    -- @param p2 second parameter
    -- @return a string value
    -- @see second_fun
    function mod1.first_fun(p1,p2)
    end

Tags such as `see` and `usage` are supported, and generally the names of functions and
modules can be inferred from the code.

LDoc is designed to give better diagnostics: if a `@see` reference cannot be found, then the
line number of the reference is given.  LDoc knows about modules which do not use `module()`
- this is important since this function has become deprecated in Lua 5.2. And you can avoid
having to embed HTML in commments by using Markdown.

LDoc will also work with Lua C extension code, and provides some convenient shortcuts.

An example showing the support for named sections and 'classes' is the [Winapi
documentation](https://stevedonovan.github.io/winapi/api.html); this is generated from
[winapi.l.c](https://github.com/stevedonovan/winapi/blob/master/winapi.l.c).

## Installation

This is straightforward; the only external dependency is
[Penlight](https://github.com/lunarmodules/Penlight), which in turn needs
[LuaFileSystem](https://keplerproject.github.io/luafilesystem/). These are already present
in [Lua for Windows](https://github.com/rjpcomputing/luaforwindows), and Penlight is also available through [LuaRocks](https://luarocks.org/) as `luarocks install
penlight`.

Unpack the sources somewhere and make an alias to `ldoc.lua` on your path. That is, either
an executable script called 'ldoc' like so:

    lua /path/to/ldoc/ldoc.lua $*

Or a batch file called 'ldoc.bat':

    @echo off
    lua \path\to\ldoc\ldoc.lua %*


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Plato - server/token/TokenValidator.js</title>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <link href="../../assets/css/vendor/morris.css" rel="stylesheet">
  <link href="../../assets/css/vendor/bootstrap.css" rel="stylesheet">
  <link href="../../assets/css/vendor/font-awesome.css" rel="stylesheet">
  <link href="../../assets/css/vendor/codemirror.css" rel="stylesheet">
  <link href="../../assets/css/plato.css" rel="stylesheet">
  <link href="../../assets/css/plato-file.css" rel="stylesheet">

    Plato on Github

        Report Home

server/token/TokenValidator.js

Maintainability

78.50

Lines of code

35

Difficulty

8.18

Estimated Errors

0.12

Function weight

By Complexity

By SLOC

    <textarea id="file-source" class="col-md-12">/*global require, module*/
(function () {
  'use strict';

  // Modules in use
  var Token = require('./Token');
  var Q = require('q');

  /**
    Validate a token candidate with collection from database

    If the token are valid ('find' encounter more than zero)

    return the promise as resolved
  */
  var validateCandidate = function (tokenCandidate) {
    var deferred = Q.defer();

    Token.getUserEmail(tokenCandidate)
      .then(function (userMail) {
        if (!!userMail) {
          deferred.resolve();
        }
      })
      .catch(function (error) {
        deferred.reject(error);
      });

    return deferred.promise;
  };

  // Export the module as singleton the token validation Type
  module.exports = {
    validateToken: validateCandidate
  };
}());</textarea>

.


text:
class CEntity;
extern Fvector get_valid_position(const CEntity* entity, const Fvector& actual_position);

// âîçâðàùàåò true, åñëè îáúåêò entity íàõîäèòñÿ íà íîäå
extern bool object_position_valid(const CEntity* entity);

IC Fvector random_position(const Fvector& center, float R) {
    Fvector v;
    v = center;
    v.x += ::Random.randF(-R, R);
    v.z += ::Random.randF(-R, R);

    return v;
}

IC bool from_right(float ty, float cy) { return ((angle_normalize_signed(ty - cy) > 0)); }

IC bool is_angle_between(float yaw, float yaw_from, float yaw_to) {
    float diff = angle_difference(yaw_from, yaw_to);
    R_ASSERT(diff < PI);

    if ((angle_difference(yaw, yaw_from) < diff) && (angle_difference(yaw, yaw_to) < diff))
        return true;
    else
        return false;
}

IC void velocity_lerp(float& _cur, float _target, float _accel, float _dt) {
    if (fsimilar(_cur, _target))
        return;

    if (_target > _cur) {
        _cur += _accel * _dt;
        if (_cur > _target)
            _cur = _target;
    } else {
        _cur -= _accel * _dt;
        if (_cur < 0)
            _cur = 0.f;
    }
}

IC void def_lerp(float& _cur, float _target, float _vel, float _dt) {
    if (fsimilar(_cur, _target))
        return;

    if (_target > _cur) {
        _cur += _vel * _dt;
        if (_cur > _target)
            _cur = _target;
    } else {
        _cur -= _vel * _dt;
        if (_cur < _target)
            _cur = _target;
    }
}

IC u32 time() { return Device.dwTimeGlobal; }

//////////////////////////////////////////////////////////////////////////
// bone routines
//////////////////////////////////////////////////////////////////////////
extern Fvector get_bone_position(CObject* object, LPCSTR bone_name);

Fvector get_head_position(CObject* object);

//////////////////////////////////////////////////////////////////////////
// LTX routines
//////////////////////////////////////////////////////////////////////////
IC void read_delay(LPCSTR section, LPCSTR name, u32& delay_min, u32& delay_max) {
    LPCSTR delay = pSettings->r_string(section, name);
    string128 tempst;

    if (_GetItemCount(delay) == 2) {
        delay_min = u32(atoi(_GetItem(delay, 0, tempst)));
        delay_max = u32(atoi(_GetItem(delay, 1, tempst)));
    } else {
        delay_min = 0;
        delay_max = u32(atoi(delay));
    }
}

IC void read_distance(LPCSTR section, LPCSTR name, float& dist_min, float& dist_max) {
    LPCSTR dist = pSettings->r_string(section, name);
    string128 tempst;

    VERIFY(_GetItemCount(dist) == 2);

    dist_min = float(atof(_GetItem(dist, 0, tempst)));
    dist_max = float(atof(_GetItem(dist, 1, tempst)));
}


text:
// (C) Copyright 2006 Douglas Gregor <doug.gregor -at- gmail.com>

// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Douglas Gregor
#ifndef BOOST_MPI_PYTHON_SKELETON_AND_CONTENT_HPP
#define BOOST_MPI_PYTHON_SKELETON_AND_CONTENT_HPP

/** @file skeleton_and_content.hpp
 *
 *  This file reflects the skeleton/content facilities into Python.
 */
#include <boost/python.hpp>
#include <boost/mpi.hpp>
#include <boost/function/function1.hpp>
#define BOOST_MPI_PYTHON_FORWARD_ONLY
#include <boost/mpi/python.hpp>
#include <boost/mpi/python/serialize.hpp>

namespace boost { namespace mpi { namespace python {

/**
 * INTERNAL ONLY
 *
 * This @c content class is a wrapper around the C++ "content"
 * retrieved from get_content. This wrapper is only needed to store a
 * copy of the Python object on which get_content() was called.
 */
class content : public boost::mpi::content
{
  typedef boost::mpi::content inherited;

 public:
  content(const inherited& base, boost::python::object object)
    : inherited(base), object(object) { }

  inherited&       base()       { return *this; }
  const inherited& base() const { return *this; }

  boost::python::object object;
};

/**
 * INTERNAL ONLY
 *
 * A class specific to the Python bindings that mimics the behavior of
 * the skeleton_proxy<T> template. In the case of Python skeletons, we
 * only need to know the object (and its type) to transmit the
 * skeleton. This is the only user-visible skeleton proxy type,
 * although instantiations of its derived classes (@c
 * skeleton_proxy<T>) will be returned from the Python skeleton()
 * function.
 */
class skeleton_proxy_base
{
public:
  skeleton_proxy_base(const boost::python::object& object) : object(object) { }

  boost::python::object object;
};

/**
 * INTERNAL ONLY
 *
 * The templated @c skeleton_proxy class represents a skeleton proxy
 * in Python. The only data is stored in the @c skeleton_proxy_base
 * class (which is the type actually exposed as @c skeleton_proxy in
 * Python). However, the type of @c skeleton_proxy<T> is important for
 * (de-)serialization of @c skeleton_proxy<T>'s for transmission.
 */
template<typename T>
class skeleton_proxy : public skeleton_proxy_base
{
 public:
  skeleton_proxy(const boost::python::object& object)
    : skeleton_proxy_base(object) { }
};

namespace detail {
  using boost::python::object;
  using boost::python::extract;

  extern BOOST_MPI_DECL boost::python::object skeleton_proxy_base_type;

  template<typename T>
  struct skeleton_saver
  {
    void
    operator()(packed_oarchive& ar, const object& obj, const unsigned int)
    {
      packed_skeleton_oarchive pso(ar);
      pso << extract<T&>(obj.attr("object"))();
    }
  };

  template<typename T>
  struct skeleton_loader
  {
    void
    operator()(packed_iarchive& ar, object& obj, const unsigned int)
    {
      packed_skeleton_iarchive psi(ar);
      extract<skeleton_proxy<T>&> proxy(obj);
      if (!proxy.check())
        obj = object(skeleton_proxy<T>(object(T())));

      psi >> extract<T&>(obj.attr("object"))();
    }
  };

  /**
   * The @c skeleton_content_handler structure contains all of the
   * information required to extract a skeleton and content from a
   * Python object with a certain C++ type.
   */
  struct skeleton_content_handler {
    function1<object, const object&> get_skeleton_proxy;
    function1<content, const object&> get_content;
  };

  /**
   * A function object that extracts the skeleton from of a Python
   * object, which is actually a wrapped C++ object of type T.
   */
  template<typename T>
  struct do_get_skeleton_proxy
  {
    object operator()(object value) {
      return object(skeleton_proxy<T>(value));
    }
  };

  /**
   * A function object that extracts the content of a Python object,
   * which is actually a wrapped C++ object of type T.
   */
  template<typename T>
  struct do_get_content
  {
    content operator()(object value_obj) {
      T& value = extract<T&>(value_obj)();
      return content(boost::mpi::get_content(value), value_obj);
    }
  };

  /**
   * Determine if a skeleton and content handler for @p type has
   * already been registered.
   */
  BOOST_MPI_PYTHON_DECL bool
  skeleton_and_content_handler_registered(PyTypeObject* type);

  /**
   * Register a skeleton/content handler with a particular Python type
   * (which actually wraps a C++ type).
   */
  BOOST_MPI_PYTHON_DECL void
  register_skeleton_and_content_handler(PyTypeObject*,
                                        const skeleton_content_handler&);
} // end namespace detail

template<typename T>
void register_skeleton_and_content(const T& value, PyTypeObject* type)
{
  using boost::python::detail::direct_serialization_table;
  using boost::python::detail::get_direct_serialization_table;
  using namespace boost::python;

  // Determine the type
  if (!type)
    type = object(value).ptr()->ob_type;

  // Don't re-register the same type.
  if (detail::skeleton_and_content_handler_registered(type))
    return;

  // Register the skeleton proxy type
  {
    boost::python::scope proxy_scope(detail::skeleton_proxy_base_type);
    std::string name("skeleton_proxy<");
    name += typeid(T).name();
    name += ">";
    class_<skeleton_proxy<T>, bases<skeleton_proxy_base> >(name.c_str(),
                                                           no_init);
  }

  // Register the saver and loader for the associated skeleton and
  // proxy, to allow (de-)serialization of skeletons via the proxy.
  direct_serialization_table<packed_iarchive, packed_oarchive>& table =
    get_direct_serialization_table<packed_iarchive, packed_oarchive>();
  table.register_type(detail::skeleton_saver<T>(),
                      detail::skeleton_loader<T>(),
                      skeleton_proxy<T>(object(value)));

  // Register the rest of the skeleton/content mechanism, including
  // handlers that extract a skeleton proxy from a Python object and
  // extract the content from a Python object.
  detail::skeleton_content_handler handler;
  handler.get_skeleton_proxy = detail::do_get_skeleton_proxy<T>();
  handler.get_content = detail::do_get_content<T>();
  detail::register_skeleton_and_content_handler(type, handler);
}

} } } // end namespace boost::mpi::python

#endif // BOOST_MPI_PYTHON_SKELETON_AND_CONTENT_HPP


text:
package com.google.bigtable.admin.v2;

import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
@Generated("by gapic-generator-java")
public class AppProfileName implements ResourceName {
  private static final PathTemplate PROJECT_INSTANCE_APP_PROFILE =
      PathTemplate.createWithoutUrlEncoding(
          "projects/{project}/instances/{instance}/appProfiles/{app_profile}");
  private volatile Map<String, String> fieldValuesMap;
  private final String project;
  private final String instance;
  private final String appProfile;

  @Deprecated
  protected AppProfileName() {
    project = null;
    instance = null;
    appProfile = null;
  }

  private AppProfileName(Builder builder) {
    project = Preconditions.checkNotNull(builder.getProject());
    instance = Preconditions.checkNotNull(builder.getInstance());
    appProfile = Preconditions.checkNotNull(builder.getAppProfile());
  }

  public String getProject() {
    return project;
  }

  public String getInstance() {
    return instance;
  }

  public String getAppProfile() {
    return appProfile;
  }

  public static Builder newBuilder() {
    return new Builder();
  }

  public Builder toBuilder() {
    return new Builder(this);
  }

  public static AppProfileName of(String project, String instance, String appProfile) {
    return newBuilder().setProject(project).setInstance(instance).setAppProfile(appProfile).build();
  }

  public static String format(String project, String instance, String appProfile) {
    return newBuilder()
        .setProject(project)
        .setInstance(instance)
        .setAppProfile(appProfile)
        .build()
        .toString();
  }

  public static AppProfileName parse(String formattedString) {
    if (formattedString.isEmpty()) {
      return null;
    }
    Map<String, String> matchMap =
        PROJECT_INSTANCE_APP_PROFILE.validatedMatch(
            formattedString, "AppProfileName.parse: formattedString not in valid format");
    return of(matchMap.get("project"), matchMap.get("instance"), matchMap.get("app_profile"));
  }

  public static List<AppProfileName> parseList(List<String> formattedStrings) {
    List<AppProfileName> list = new ArrayList<>(formattedStrings.size());
    for (String formattedString : formattedStrings) {
      list.add(parse(formattedString));
    }
    return list;
  }

  public static List<String> toStringList(List<AppProfileName> values) {
    List<String> list = new ArrayList<>(values.size());
    for (AppProfileName value : values) {
      if (value == null) {
        list.add("");
      } else {
        list.add(value.toString());
      }
    }
    return list;
  }

  public static boolean isParsableFrom(String formattedString) {
    return PROJECT_INSTANCE_APP_PROFILE.matches(formattedString);
  }

  @Override
  public Map<String, String> getFieldValuesMap() {
    if (fieldValuesMap == null) {
      synchronized (this) {
        if (fieldValuesMap == null) {
          ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
          if (project != null) {
            fieldMapBuilder.put("project", project);
          }
          if (instance != null) {
            fieldMapBuilder.put("instance", instance);
          }
          if (appProfile != null) {
            fieldMapBuilder.put("app_profile", appProfile);
          }
          fieldValuesMap = fieldMapBuilder.build();
        }
      }
    }
    return fieldValuesMap;
  }

  public String getFieldValue(String fieldName) {
    return getFieldValuesMap().get(fieldName);
  }

  @Override
  public String toString() {
    return PROJECT_INSTANCE_APP_PROFILE.instantiate(
        "project", project, "instance", instance, "app_profile", appProfile);
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o != null || getClass() == o.getClass()) {
      AppProfileName that = ((AppProfileName) o);
      return Objects.equals(this.project, that.project)
          && Objects.equals(this.instance, that.instance)
          && Objects.equals(this.appProfile, that.appProfile);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int h = 1;
    h *= 1000003;
    h ^= Objects.hashCode(project);
    h *= 1000003;
    h ^= Objects.hashCode(instance);
    h *= 1000003;
    h ^= Objects.hashCode(appProfile);
    return h;
  }

  /** Builder for projects/{project}/instances/{instance}/appProfiles/{app_profile}. */
  public static class Builder {
    private String project;
    private String instance;
    private String appProfile;

    protected Builder() {}

    public String getProject() {
      return project;
    }

    public String getInstance() {
      return instance;
    }

    public String getAppProfile() {
      return appProfile;
    }

    public Builder setProject(String project) {
      this.project = project;
      return this;
    }

    public Builder setInstance(String instance) {
      this.instance = instance;
      return this;
    }

    public Builder setAppProfile(String appProfile) {
      this.appProfile = appProfile;
      return this;
    }

    private Builder(AppProfileName appProfileName) {
      this.project = appProfileName.project;
      this.instance = appProfileName.instance;
      this.appProfile = appProfileName.appProfile;
    }

    public AppProfileName build() {
      return new AppProfileName(this);
    }
  }
}


text:
(function() {
  var Dates, HTML, Swag, Utils,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  if (typeof window !== "undefined" && window !== null) {
    window.Swag = Swag = {};
  } else if (typeof module !== "undefined" && module !== null) {
    module.exports = Swag = {};
  }

  Swag.helpers = {};

  Swag.addHelper = function(name, helper) {
    return Swag.helpers[name] = helper;
  };

  Swag.registerHelpers = function(localHandlebars) {
    var helper, name, _ref, _results;
    if (localHandlebars) {
      Swag.Handlebars = localHandlebars;
    } else {
      if (typeof window !== "undefined" && window !== null) {
        if (window.Ember != null) {
          Swag.Handlebars = Ember.Handlebars;
        } else {
          Swag.Handlebars = window.Handlebars;
        }
      } else if (typeof module !== "undefined" && module !== null) {
        Swag.Handlebars = require('handlebars');
      }
    }
    Swag.registerHelper = function(name, helper) {
      if ((typeof window !== "undefined" && window !== null) && window.Ember) {
        return Swag.Handlebars.helper(name, helper);
      } else {
        return Swag.Handlebars.registerHelper(name, helper);
      }
    };
    _ref = Swag.helpers;
    _results = [];
    for (name in _ref) {
      helper = _ref[name];
      _results.push(Swag.registerHelper(name, helper));
    }
    return _results;
  };

  Swag.Config = {
    partialsPath: ''
  };

  Utils = {};

  Utils.toString = Object.prototype.toString;

  Utils.isUndefined = function(value) {
    return value === 'undefined' || Utils.toString.call(value) === '[object Function]' || (value.hash != null);
  };

  Utils.safeString = function(str) {
    return new Swag.Handlebars.SafeString(str);
  };

  Utils.trim = function(str) {
    var trim;
    trim = /\S/.test("\xA0") ? /^[\s\xA0]+|[\s\xA0]+$/g : /^\s+|\s+$/g;
    return str.toString().replace(trim, '');
  };

  Swag.addHelper('lowercase', function(str) {
    return str.toLowerCase();
  });

  Swag.addHelper('uppercase', function(str) {
    return str.toUpperCase();
  });

  Swag.addHelper('capitalizeFirst', function(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  });

  Swag.addHelper('capitalizeEach', function(str) {
    return str.replace(/\w\S*/g, function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1);
    });
  });

  Swag.addHelper('titleize', function(str) {
    var capitalize, title, word, words;
    title = str.replace(/[ \-_]+/g, ' ');
    words = title.match(/\w+/g);
    capitalize = function(word) {
      return word.charAt(0).toUpperCase() + word.slice(1);
    };
    return ((function() {
      var _i, _len, _results;
      _results = [];
      for (_i = 0, _len = words.length; _i < _len; _i++) {
        word = words[_i];
        _results.push(capitalize(word));
      }
      return _results;
    })()).join(' ');
  });

  Swag.addHelper('sentence', function(str) {
    return str.replace(/((?:\S[^\.\?\!]*)[\.\?\!]*)/g, function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
  });

  Swag.addHelper('reverse', function(str) {
    return str.split('').reverse().join('');
  });

  Swag.addHelper('truncate', function(str, length, omission) {
    if (Utils.isUndefined(omission)) {
      omission = '';
    }
    if (str.length > length) {
      return str.substring(0, length - omission.length) + omission;
    } else {
      return str;
    }
  });

  Swag.addHelper('center', function(str, spaces) {
    var i, space;
    space = '';
    i = 0;
    while (i < spaces) {
      space += ' ';
      i++;
    }
    return "" + space + str + space;
  });

  Swag.addHelper('newLineToBr', function(str) {
    return str.replace(/\r?\n|\r/g, '
');
  });

  Swag.addHelper('first', function(array, count) {
    if (Utils.isUndefined(count)) {
      return array[0];
    } else {
      return array.slice(0, count);
    }
  });

  Swag.addHelper('withFirst', function(array, count, options) {
    var item, result;
    if (Utils.isUndefined(count)) {
      options = count;
      return options.fn(array[0]);
    } else {
      array = array.slice(0, count);
      result = '';
      for (item in array) {
        result += options.fn(array[item]);
      }
      return result;
    }
  });

  Swag.addHelper('last', function(array, count) {
    if (Utils.isUndefined(count)) {
      return array[array.length - 1];
    } else {
      return array.slice(-count);
    }
  });

  Swag.addHelper('withLast', function(array, count, options) {
    var item, result;
    if (Utils.isUndefined(count)) {
      options = count;
      return options.fn(array[array.length - 1]);
    } else {
      array = array.slice(-count);
      result = '';
      for (item in array) {
        result += options.fn(array[item]);
      }
      return result;
    }
  });

  Swag.addHelper('after', function(array, count) {
    return array.slice(count);
  });

  Swag.addHelper('withAfter', function(array, count, options) {
    var item, result;
    array = array.slice(count);
    result = '';
    for (item in array) {
      result += options.fn(array[item]);
    }
    return result;
  });

  Swag.addHelper('before', function(array, count) {
    return array.slice(0, -count);
  });

  Swag.addHelper('withBefore', function(array, count, options) {
    var item, result;
    array = array.slice(0, -count);
    result = '';
    for (item in array) {
      result += options.fn(array[item]);
    }
    return result;
  });

  Swag.addHelper('join', function(array, separator) {
    return array.join(Utils.isUndefined(separator) ? ' ' : separator);
  });

  Swag.addHelper('sort', function(array, field) {
    if (Utils.isUndefined(field)) {
      return array.sort();
    } else {
      return array.sort(function(a, b) {
        return a[field] > b[field];
      });
    }
  });

  Swag.addHelper('withSort', function(array, field, options) {
    var item, result, _i, _len;
    result = '';
    if (Utils.isUndefined(field)) {
      options = field;
      array = array.sort();
      for (_i = 0, _len = array.length; _i < _len; _i++) {
        item = array[_i];
        result += options.fn(item);
      }
    } else {
      array = array.sort(function(a, b) {
        return a[field] > b[field];
      });
      for (item in array) {
        result += options.fn(array[item]);
      }
    }
    return result;
  });

  Swag.addHelper('length', function(array) {
    return array.length;
  });

  Swag.addHelper('lengthEqual', function(array, length, options) {
    if (array.length === length) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('empty', function(array, options) {
    if (array.length <= 0) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('any', function(array, options) {
    if (array.length > 0) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('inArray', function(array, value, options) {
    if (__indexOf.call(array, value) >= 0) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('eachIndex', function(array, options) {
    var index, result, value, _i, _len;
    result = '';
    for (index = _i = 0, _len = array.length; _i < _len; index = ++_i) {
      value = array[index];
      result += options.fn({
        item: value,
        index: index
      });
    }
    return result;
  });

  Swag.addHelper('eachProperty', function(obj, options) {
    var key, result, value;
    result = '';
    for (key in obj) {
      value = obj[key];
      result += options.fn({
        key: key,
        value: value
      });
    }
    return result;
  });

  Swag.addHelper('add', function(value, addition) {
    return value + addition;
  });

  Swag.addHelper('subtract', function(value, substraction) {
    return value - substraction;
  });

  Swag.addHelper('divide', function(value, divisor) {
    return value / divisor;
  });

  Swag.addHelper('multiply', function(value, multiplier) {
    return value * multiplier;
  });

  Swag.addHelper('floor', function(value) {
    return Math.floor(value);
  });

  Swag.addHelper('ceil', function(value) {
    return Math.ceil(value);
  });

  Swag.addHelper('round', function(value) {
    return Math.round(value);
  });

  Swag.addHelper('toFixed', function(number, digits) {
    if (Utils.isUndefined(digits)) {
      digits = 0;
    }
    return number.toFixed(digits);
  });

  Swag.addHelper('toPrecision', function(number, precision) {
    if (Utils.isUndefined(precision)) {
      precision = 1;
    }
    return number.toPrecision(precision);
  });

  Swag.addHelper('toExponential', function(number, fractions) {
    if (Utils.isUndefined(fractions)) {
      fractions = 0;
    }
    return number.toExponential(fractions);
  });

  Swag.addHelper('toInt', function(number) {
    return parseInt(number, 10);
  });

  Swag.addHelper('toFloat', function(number) {
    return parseFloat(number);
  });

  Swag.addHelper('digitGrouping', function(number, separator) {
    if (Utils.isUndefined(separator)) {
      separator = ',';
    }
    return number.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + separator);
  });

  Swag.addHelper('is', function(value, test, options) {
    if (value === test) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('isnt', function(value, test, options) {
    if (value !== test) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('gt', function(value, test, options) {
    if (value > test) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('gte', function(value, test, options) {
    if (value >= test) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('lt', function(value, test, options) {
    if (value < test) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('lte', function(value, test, options) {
    if (value <= test) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('or', function(testA, testB, options) {
    if (testA || testB) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Swag.addHelper('and', function(testA, testB, options) {
    if (testA && testB) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  });

  Dates = {};

  Dates.padNumber = function(num, count, padCharacter) {
    var lenDiff, padding;
    if (typeof padCharacter === 'undefined') {
      padCharacter = '0';
    }
    lenDiff = count - String(num).length;
    padding = '';
    if (lenDiff > 0) {
      while (lenDiff--) {
        padding += padCharacter;
      }
    }
    return padding + num;
  };

  Dates.dayOfYear = function(date) {
    var oneJan;
    oneJan = new Date(date.getFullYear(), 0, 1);
    return Math.ceil((date - oneJan) / 86400000);
  };

  Dates.weekOfYear = function(date) {
    var oneJan;
    oneJan = new Date(date.getFullYear(), 0, 1);
    return Math.ceil((((date - oneJan) / 86400000) + oneJan.getDay() + 1) / 7);
  };

  Dates.isoWeekOfYear = function(date) {
    var dayDiff, dayNr, jan4, target;
    target = new Date(date.valueOf());
    dayNr = (date.getDay() + 6) % 7;
    target.setDate(target.getDate() - dayNr + 3);
    jan4 = new Date(target.getFullYear(), 0, 4);
    dayDiff = (target - jan4) / 86400000;
    return 1 + Math.ceil(dayDiff / 7);
  };

  Dates.tweleveHour = function(date) {
    if (date.getHours() > 12) {
      return date.getHours() - 12;
    } else {
      return date.getHours();
    }
  };

  Dates.timeZoneOffset = function(date) {
    var hoursDiff, result;
    hoursDiff = -date.getTimezoneOffset() / 60;
    result = Dates.padNumber(Math.abs(hoursDiff), 4);
    return (hoursDiff > 0 ? '+' : '-') + result;
  };

  Dates.format = function(date, format) {
    return format.replace(Dates.formats, function(m, p) {
      switch (p) {
        case 'a':
          return Dates.abbreviatedWeekdays[date.getDay()];
        case 'A':
          return Dates.fullWeekdays[date.getDay()];
        case 'b':
          return Dates.abbreviatedMonths[date.getMonth()];
        case 'B':
          return Dates.fullMonths[date.getMonth()];
        case 'c':
          return date.toLocaleString();
        case 'C':
          return Math.round(date.getFullYear() / 100);
        case 'd':
          return Dates.padNumber(date.getDate(), 2);
        case 'D':
          return Dates.format(date, '%m/%d/%y');
        case 'e':
          return Dates.padNumber(date.getDate(), 2, ' ');
        case 'F':
          return Dates.format(date, '%Y-%m-%d');
        case 'h':
          return Dates.format(date, '%b');
        case 'H':
          return Dates.padNumber(date.getHours(), 2);
        case 'I':
          return Dates.padNumber(Dates.tweleveHour(date), 2);
        case 'j':
          return Dates.padNumber(Dates.dayOfYear(date), 3);
        case 'k':
          return Dates.padNumber(date.getHours(), 2, ' ');
        case 'l':
          return Dates.padNumber(Dates.tweleveHour(date), 2, ' ');
        case 'L':
          return Dates.padNumber(date.getMilliseconds(), 3);
        case 'm':
          return Dates.padNumber(date.getMonth() + 1, 2);
        case 'M':
          return Dates.padNumber(date.getMinutes(), 2);
        case 'n':
          return '\n';
        case 'p':
          if (date.getHours() > 11) {
            return 'PM';
          } else {
            return 'AM';
          }
        case 'P':
          return Dates.format(date, '%p').toLowerCase();
        case 'r':
          return Dates.format(date, '%I:%M:%S %p');
        case 'R':
          return Dates.format(date, '%H:%M');
        case 's':
          return date.getTime() / 1000;
        case 'S':
          return Dates.padNumber(date.getSeconds(), 2);
        case 't':
          return '\t';
        case 'T':
          return Dates.format(date, '%H:%M:%S');
        case 'u':
          if (date.getDay() === 0) {
            return 7;
          } else {
            return date.getDay();
          }
        case 'U':
          return Dates.padNumber(Dates.weekOfYear(date), 2);
        case 'v':
          return Dates.format(date, '%e-%b-%Y');
        case 'V':
          return Dates.padNumber(Dates.isoWeekOfYear(date), 2);
        case 'W':
          return Dates.padNumber(Dates.weekOfYear(date), 2);
        case 'w':
          return Dates.padNumber(date.getDay(), 2);
        case 'x':
          return date.toLocaleDateString();
        case 'X':
          return date.toLocaleTimeString();
        case 'y':
          return String(date.getFullYear()).substring(2);
        case 'Y':
          return date.getFullYear();
        case 'z':
          return Dates.timeZoneOffset(date);
        default:
          return match;
      }
    });
  };

  Dates.formats = /%(a|A|b|B|c|C|d|D|e|F|h|H|I|j|k|l|L|m|M|n|p|P|r|R|s|S|t|T|u|U|v|V|W|w|x|X|y|Y|z)/g;

  Dates.abbreviatedWeekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'];

  Dates.fullWeekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

  Dates.abbreviatedMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

  Dates.fullMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

  Swag.addHelper('formatDate', function(date, format) {
    date = new Date(date);
    return Dates.format(date, format);
  });

  Swag.addHelper('now', function(format) {
    var date;
    date = new Date();
    if (Utils.isUndefined(format)) {
      return date;
    } else {
      return Dates.format(date, format);
    }
  });

  Swag.addHelper('timeago', function(date) {
    var interval, seconds;
    date = new Date(date);
    seconds = Math.floor((new Date() - date) / 1000);
    interval = Math.floor(seconds / 31536000);
    if (interval > 1) {
      return "" + interval + " years ago";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
      return "" + interval + " months ago";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
      return "" + interval + " days ago";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
      return "" + interval + " hours ago";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
      return "" + interval + " minutes ago";
    }
    if (Math.floor(seconds) === 0) {
      return 'Just now';
    } else {
      return Math.floor(seconds) + ' seconds ago';
    }
  });

  Swag.addHelper('inflect', function(count, singular, plural, include) {
    var word;
    word = count > 1 || count === 0 ? plural : singular;
    if (Utils.isUndefined(include) || include === false) {
      return word;
    } else {
      return "" + count + " " + word;
    }
  });

  Swag.addHelper('ordinalize', function(value) {
    var normal, _ref;
    normal = Math.abs(Math.round(value));
    if (_ref = normal % 100, __indexOf.call([11, 12, 13], _ref) >= 0) {
      return "" + value + "th";
    } else {
      switch (normal % 10) {
        case 1:
          return "" + value + "st";
        case 2:
          return "" + value + "nd";
        case 3:
          return "" + value + "rd";
        default:
          return "" + value + "th";
      }
    }
  });

  HTML = {};

  HTML.parseAttributes = function(hash) {
    return Object.keys(hash).map(function(key) {
      return "" + key + "=\"" + hash[key] + "\"";
    }).join(' ');
  };

  Swag.addHelper('ul', function(context, options) {
    return ("
") + context.map(function(item) {
      return "
" + (options.fn(item)) + "
";
    }).join('\n') + "
";
  });

  Swag.addHelper('ol', function(context, options) {
    return ("
") + context.map(function(item) {
      return "
" + (options.fn(item)) + "
";
    }).join('\n') + "
";
  });

  Swag.addHelper('br', function(count, options) {
    var br, i;
    br = '
';
    if (!Utils.isUndefined(count)) {
      i = 0;
      while (i < count - 1) {
        br += '
';
        i++;
      }
    }
    return Utils.safeString(br);
  });

  Swag.addHelper('log', function(value) {
    return console.log(value);
  });

  Swag.addHelper('debug', function(value) {
    console.log('Context: ', this);
    if (!Utils.isUndefined(value)) {
      console.log('Value: ', value);
    }
    return console.log('-----------------------------------------------');
  });

  Swag.addHelper('default', function(value, defaultValue) {
    return value != null ? value : defaultValue;
  });

  Swag.addHelper('partial', function(name, data) {
    var partial;
    partial = Swag.Config.partialsPath + name;
    data = Utils.isUndefined(data) ? {} : data;
    if (Swag.Handlebars.partials[name] == null) {
      Swag.Handlebars.registerPartial(name, require(partial));
    }
    return Utils.safeString(Swag.Handlebars.partials[name](data));
  });

}).call(this);


text:
module AasmHistory
  module Persistance
    class ActiveRecordCreator
      def initialize object, state, previous_state
        @object = object
        @state = state
        @previous_state = previous_state
      end

      def create
        klass.create! attributes
      end

      def klass
        @klass ||= AASM::StateMachine[@object.class].config.history_class.constantize
      end

      def attributes
        {state: @state, previous_state: @previous_state, stateable: @object}
      end
    end
  end
end


text:
package org.gradle.api.internal.artifacts.ivyservice.modulecache;

import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.CacheLockingManager;
import org.gradle.api.internal.artifacts.ivyservice.IvyXmlModuleDescriptorWriter;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ModuleComponentRepository;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.IvyXmlModuleDescriptorParser;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.ResolverStrategy;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.result.ComponentIdentifierSerializer;
import org.gradle.cache.PersistentIndexedCache;
import org.gradle.internal.component.external.model.ModuleComponentResolveMetaData;
import org.gradle.internal.hash.HashValue;
import org.gradle.internal.resource.local.LocallyAvailableResource;
import org.gradle.internal.resource.local.PathKeyFileStore;
import org.gradle.internal.serialize.Decoder;
import org.gradle.internal.serialize.Encoder;
import org.gradle.internal.serialize.Serializer;
import org.gradle.util.BuildCommencedTimeProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultModuleMetaDataCache implements ModuleMetaDataCache {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultModuleMetaDataCache.class);

    private final BuildCommencedTimeProvider timeProvider;
    private final CacheLockingManager cacheLockingManager;

    private final ModuleDescriptorStore moduleDescriptorStore;
    private PersistentIndexedCache<RevisionKey, ModuleDescriptorCacheEntry> cache;

    public DefaultModuleMetaDataCache(BuildCommencedTimeProvider timeProvider, CacheLockingManager cacheLockingManager, ResolverStrategy resolverStrategy) {
        this.timeProvider = timeProvider;
        this.cacheLockingManager = cacheLockingManager;

        moduleDescriptorStore = new ModuleDescriptorStore(new PathKeyFileStore(cacheLockingManager.createMetaDataStore()), new IvyXmlModuleDescriptorWriter(), new IvyXmlModuleDescriptorParser(resolverStrategy));
    }

    private PersistentIndexedCache<RevisionKey, ModuleDescriptorCacheEntry> getCache() {
        if (cache == null) {
            cache = initCache();
        }
        return cache;
    }

    private PersistentIndexedCache<RevisionKey, ModuleDescriptorCacheEntry> initCache() {
        return cacheLockingManager.createCache("module-metadata", new RevisionKeySerializer(), new ModuleDescriptorCacheEntrySerializer());
    }

    public CachedMetaData getCachedModuleDescriptor(ModuleComponentRepository repository, ModuleComponentIdentifier componentId) {
        ModuleDescriptorCacheEntry entry = getCache().get(createKey(repository, componentId));
        if (entry == null) {
            return null;
        }
        if (entry.isMissing()) {
            return new DefaultCachedMetaData(entry, null, timeProvider);
        }
        ModuleDescriptor descriptor = moduleDescriptorStore.getModuleDescriptor(repository, componentId);
        if (descriptor == null) {
            // Descriptor file has been deleted - ignore the entry
            return null;
        }
        return new DefaultCachedMetaData(entry, entry.createMetaData(componentId, descriptor), timeProvider);
    }

    public CachedMetaData cacheMissing(ModuleComponentRepository repository, ModuleComponentIdentifier id) {
        LOGGER.debug("Recording absence of module descriptor in cache: {} [changing = {}]", id, false);
        ModuleDescriptorCacheEntry entry = ModuleDescriptorCacheEntry.forMissingModule(timeProvider.getCurrentTime());
        getCache().put(createKey(repository, id), entry);
        return new DefaultCachedMetaData(entry, null, timeProvider);
    }

    public CachedMetaData cacheMetaData(ModuleComponentRepository repository, ModuleComponentResolveMetaData metaData) {
        ModuleDescriptor moduleDescriptor = metaData.getDescriptor();
        LOGGER.debug("Recording module descriptor in cache: {} [changing = {}]", moduleDescriptor.getModuleRevisionId(), metaData.isChanging());
        LocallyAvailableResource resource = moduleDescriptorStore.putModuleDescriptor(repository, metaData.getComponentId(), moduleDescriptor);
        ModuleDescriptorCacheEntry entry = createEntry(metaData, resource.getSha1());
        getCache().put(createKey(repository, metaData.getComponentId()), entry);
        return new DefaultCachedMetaData(entry, null, timeProvider);
    }

    private RevisionKey createKey(ModuleComponentRepository repository, ModuleComponentIdentifier id) {
        return new RevisionKey(repository.getId(), id);
    }

    private ModuleDescriptorCacheEntry createEntry(ModuleComponentResolveMetaData metaData, HashValue moduleDescriptorHash) {
        return ModuleDescriptorCacheEntry.forMetaData(metaData, timeProvider.getCurrentTime(), moduleDescriptorHash.asBigInteger());
    }

    private static class RevisionKey {
        private final String repositoryId;
        private final ModuleComponentIdentifier componentId;

        private RevisionKey(String repositoryId, ModuleComponentIdentifier componentId) {
            this.repositoryId = repositoryId;
            this.componentId = componentId;
        }

        @Override
        public boolean equals(Object o) {
            if (o == null || !(o instanceof RevisionKey)) {
                return false;
            }
            RevisionKey other = (RevisionKey) o;
            return repositoryId.equals(other.repositoryId) && componentId.equals(other.componentId);
        }

        @Override
        public int hashCode() {
            return repositoryId.hashCode() ^ componentId.hashCode();
        }
    }

    private static class RevisionKeySerializer implements Serializer<RevisionKey> {
        private final ComponentIdentifierSerializer componentIdSerializer = new ComponentIdentifierSerializer();

        public void write(Encoder encoder, RevisionKey value) throws Exception {
            encoder.writeString(value.repositoryId);
            componentIdSerializer.write(encoder, value.componentId);
        }

        public RevisionKey read(Decoder decoder) throws Exception {
            String resolverId = decoder.readString();
            ModuleComponentIdentifier identifier = (ModuleComponentIdentifier) componentIdSerializer.read(decoder);
            return new RevisionKey(resolverId, identifier);
        }
    }
}


text:
import Block = require('./Block');
import BlockType = require('./BlockType');
import IBlockSpec = require('./IBlockSpec');
import IfBlock = require('./IfBlock');
import RepeaterBlock = require('./RepeaterBlock');
import View = require('./View');

export function fromSpec(view: View, spec: IBlockSpec): Block {

    var block: Block;
    if (spec.type === BlockType.Element || spec.type === BlockType.Text || spec.type === BlockType.View) {
        block = new Block(view, null);
        block.template = processTemplate(block, [spec]);
    } else {
        block = createBlock(view, null, spec);
        block.template = processTemplate(block, spec.children);
    }

    return block;
}

function createBlock(view: View, parent: Block, spec: IBlockSpec): Block {

    var block: Block;
    switch (spec.type) {
        case BlockType.Block:
            block = new Block(view, parent);
            break;
        case BlockType.IfBlock:
            block = new IfBlock(view, parent, spec.source);
            break;
        case BlockType.RepeaterBlock:
            block = new RepeaterBlock(view, parent, spec.source, spec.iterator, spec.children);
            break;
    }

    return block;
}

export function processTemplate(parent: Block, template: IBlockSpec[]): IBlockSpec[] {

    return template.map(function (spec) {

        if (spec.type === BlockType.Element) {
            if (spec.children) {
                // allow two repeaters to share the same blockTemplate
                spec = {
                    type: BlockType.Element,
                    tag: spec.tag,
                    attr: spec.attr,
                    binding: spec.binding,
                    // children has to be unique per repeater since blocks
                    // are processed into comments
                    children: processTemplate(parent, spec.children)
                };
            }
        } else if (spec.type === BlockType.Block || spec.type === BlockType.IfBlock || spec.type === BlockType.RepeaterBlock) {
            var block = createBlock(parent.view, parent, spec);
            if (spec.type !== BlockType.RepeaterBlock) {
                block.template = processTemplate(block, spec.children);
            }
            parent.children.push(block);
            spec = {
                type: BlockType.Comment,
                owner: block,
                value: 'block'
            };
        }
        return spec;
    });
}


text:
#include <dart/dart.hpp>
#include <pybind11/pybind11.h>

namespace py = pybind11;

namespace dart {
namespace python {

void ConstraintSolver(py::module& m)
{
  ::py::class_<
      dart::constraint::ConstraintSolver,
      std::shared_ptr<dart::constraint::ConstraintSolver>>(
      m, "ConstraintSolver")
      .def(
          "addSkeleton",
          +[](dart::constraint::ConstraintSolver* self,
              const dart::dynamics::SkeletonPtr& skeleton) {
            self->addSkeleton(skeleton);
          },
          ::py::arg("skeleton"))
      .def(
          "addSkeletons",
          +[](dart::constraint::ConstraintSolver* self,
              const std::vector<dart::dynamics::SkeletonPtr>& skeletons) {
            self->addSkeletons(skeletons);
          },
          ::py::arg("skeletons"))
      .def(
          "removeSkeleton",
          +[](dart::constraint::ConstraintSolver* self,
              const dart::dynamics::SkeletonPtr& skeleton) {
            self->removeSkeleton(skeleton);
          },
          ::py::arg("skeleton"))
      .def(
          "removeSkeletons",
          +[](dart::constraint::ConstraintSolver* self,
              const std::vector<dart::dynamics::SkeletonPtr>& skeletons) {
            self->removeSkeletons(skeletons);
          },
          ::py::arg("skeletons"))
      .def(
          "removeAllSkeletons",
          +[](dart::constraint::ConstraintSolver* self) {
            self->removeAllSkeletons();
          })
      .def(
          "addConstraint",
          +[](dart::constraint::ConstraintSolver* self,
              const dart::constraint::ConstraintBasePtr& constraint) {
            self->addConstraint(constraint);
          },
          ::py::arg("constraint"))
      .def(
          "removeConstraint",
          +[](dart::constraint::ConstraintSolver* self,
              const dart::constraint::ConstraintBasePtr& constraint) {
            self->removeConstraint(constraint);
          },
          ::py::arg("constraint"))
      .def(
          "removeAllConstraints",
          +[](dart::constraint::ConstraintSolver* self) {
            self->removeAllConstraints();
          })
      .def(
          "getNumConstraints",
          +[](const dart::constraint::ConstraintSolver* self) -> bool {
            return self->getNumConstraints();
          })
      .def(
          "getConstraint",
          +[](dart::constraint::ConstraintSolver* self,
              std::size_t index) -> constraint::ConstraintBasePtr {
            return self->getConstraint(index);
          },
          ::py::arg("index"))
      .def(
          "getNumConstraints",
          +[](const dart::constraint::ConstraintSolver* self) -> bool {
            return self->getNumConstraints();
          })
      .def(
          "getConstraint",
          +[](dart::constraint::ConstraintSolver* self,
              std::size_t index) -> constraint::ConstraintBasePtr {
            return self->getConstraint(index);
          },
          ::py::arg("index"))
      .def(
          "clearLastCollisionResult",
          +[](dart::constraint::ConstraintSolver* self) {
            self->clearLastCollisionResult();
          })
      .def(
          "setTimeStep",
          +[](dart::constraint::ConstraintSolver* self, double _timeStep) {
            self->setTimeStep(_timeStep);
          },
          ::py::arg("timeStep"))
      .def(
          "getTimeStep",
          +[](const dart::constraint::ConstraintSolver* self) -> double {
            return self->getTimeStep();
          })
      .def(
          "setCollisionDetector",
          +[](dart::constraint::ConstraintSolver* self,
              const std::shared_ptr<dart::collision::CollisionDetector>&
                  collisionDetector) {
            self->setCollisionDetector(collisionDetector);
          },
          ::py::arg("collisionDetector"))
      .def(
          "getCollisionDetector",
          +[](dart::constraint::ConstraintSolver* self)
              -> dart::collision::CollisionDetectorPtr {
            return self->getCollisionDetector();
          })
      .def(
          "getCollisionDetector",
          +[](const dart::constraint::ConstraintSolver* self)
              -> dart::collision::ConstCollisionDetectorPtr {
            return self->getCollisionDetector();
          })
      .def(
          "getCollisionGroup",
          +[](dart::constraint::ConstraintSolver* self)
              -> dart::collision::CollisionGroupPtr {
            return self->getCollisionGroup();
          })
      .def(
          "getCollisionGroup",
          +[](const dart::constraint::ConstraintSolver* self)
              -> dart::collision::ConstCollisionGroupPtr {
            return self->getCollisionGroup();
          })
      .def(
          "getCollisionOption",
          +[](dart::constraint::ConstraintSolver* self)
              -> dart::collision::CollisionOption& {
            return self->getCollisionOption();
          },
          "Returns collision option that is used for collision checkings in "
          "this ConstraintSolver to generate contact constraints.")
      .def(
          "getCollisionOption",
          +[](const dart::constraint::ConstraintSolver* self)
              -> const dart::collision::CollisionOption& {
            return self->getCollisionOption();
          },
          "Returns collision option that is used for collision checkings in "
          "this ConstraintSolver to generate contact constraints.")
      .def(
          "solve",
          +[](dart::constraint::ConstraintSolver* self) { self->solve(); });
}

} // namespace python
} // namespace dart