text:
#include "AppTask.h"
#include "AppConfig.h"
#include "AppEvent.h"
#include "LEDWidget.h"

#include "qrcodegen.h"

#include <app-common/zap-generated/attribute-id.h>
#include <app-common/zap-generated/attribute-type.h>
#include <app-common/zap-generated/cluster-id.h>
#include <app/clusters/identify-server/identify-server.h>
#include <app/clusters/network-commissioning/network-commissioning.h>
#include <app/server/OnboardingCodesUtil.h>
#include <app/server/Server.h>
#include <app/util/attribute-storage.h>

#include <assert.h>

#include <credentials/DeviceAttestationCredsProvider.h>
#include <credentials/examples/DeviceAttestationCredsExample.h>

#include <setup_payload/QRCodeSetupPayloadGenerator.h>
#include <setup_payload/SetupPayload.h>

#include <lib/support/CodeUtils.h>

#include <platform/CHIPDeviceLayer.h>
#include <platform/mt793x/NetworkCommissioningWiFiDriver.h>

#define FACTORY_RESET_TRIGGER_TIMEOUT 3000
#define FACTORY_RESET_CANCEL_WINDOW_TIMEOUT 3000
#define APP_TASK_STACK_SIZE (4096)
#define APP_TASK_PRIORITY 2
#define APP_EVENT_QUEUE_SIZE 10
#define EXAMPLE_VENDOR_ID 0xcafe

#ifdef portYIELD_FROM_ISR
#define OS_YIELD_FROM_ISR(yield) portYIELD_FROM_ISR(yield)
#elif portEND_SWITCHING_ISR
#define OS_YIELD_FROM_ISR(yield) portEND_SWITCHING_ISR(yield)
#else
#error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR"
#endif

namespace {

TimerHandle_t sFunctionTimer; // FreeRTOS app sw timer.
TaskHandle_t sAppTaskHandle;
QueueHandle_t sAppEventQueue;

LEDWidget sStatusLED;

bool sIsWiFiProvisioned = false;
bool sIsWiFiEnabled     = false;
bool sIsWiFiAttached    = false;

uint8_t sAppEventQueueBuffer[APP_EVENT_QUEUE_SIZE * sizeof(AppEvent)];
StaticQueue_t sAppEventQueueStruct;

StackType_t appStack[APP_TASK_STACK_SIZE * 2 / sizeof(StackType_t)];
StaticTask_t appTaskStruct;

#if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION
using namespace chip::DeviceLayer::NetworkCommissioning;
chip::app::Clusters::NetworkCommissioning::Instance sWiFiNetworkCommissioningInstance(0 /* Endpoint Id */,
                                                                                &GenioWiFiDriver::GetInstance());
#endif

} // namespace

using namespace chip::TLV;
using namespace ::chip::Credentials;
using namespace ::chip::DeviceLayer;

AppTask AppTask::sAppTask;

CHIP_ERROR AppTask::StartAppTask()
{
    sAppEventQueue = xQueueCreateStatic(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent), sAppEventQueueBuffer, &sAppEventQueueStruct);
    if (sAppEventQueue == NULL)
    {
        MT793X_LOG("Failed to allocate app event queue");
        appError(APP_ERROR_EVENT_QUEUE_FAILED);
    }

    // Start App task.
    sAppTaskHandle = xTaskCreateStatic(AppTaskMain, APP_TASK_NAME, ArraySize(appStack), NULL, 1, appStack, &appTaskStruct);
    if (sAppTaskHandle == nullptr)
        return APP_ERROR_CREATE_TASK_FAILED;

    return CHIP_NO_ERROR;
}

CHIP_ERROR AppTask::Init()
{
    CHIP_ERROR error = CHIP_NO_ERROR;

    // Wait for the WiFi to be initialized
    MT793X_LOG("APP: Wait WiFi Init");
    vTaskDelay(1000); // TODO
    MT793X_LOG("APP: Done WiFi Init");

#if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION
    sWiFiNetworkCommissioningInstance.Init();
#endif

    // Init ZCL Data Model and start server
    static chip::CommonCaseDeviceServerInitParams initParams;
    (void) initParams.InitializeStaticResourcesBeforeServerInit();
    chip::Server::GetInstance().Init(initParams);

    // Initialize device attestation config
    SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider());

    // Create FreeRTOS sw timer for Function Selection.
    sFunctionTimer = xTimerCreate("FnTmr",          // Just a text name, not used by the RTOS kernel
                                  1,                // == default timer period (mS)
                                  false,            // no timer reload (==one-shot)
                                  (void *) this,    // init timer id = app task obj context
                                  TimerEventHandler // timer callback handler
    );
    if (sFunctionTimer == NULL)
    {
        MT793X_LOG("funct timer create failed");
        appError(APP_ERROR_CREATE_TIMER_FAILED);
    }

    MT793X_LOG("Current Software Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING);

    sStatusLED.Init(LED_STATUS);

    ConfigurationMgr().LogDeviceConfig();

    // PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE));
    PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kSoftAP));

    return error;
}

void AppTask::AppTaskMain(void * pvParameter)
{
    AppEvent event;

    CHIP_ERROR error = sAppTask.Init();
    if (error != CHIP_NO_ERROR)
    {
        MT793X_LOG("AppTask.Init() failed");
        appError(error);
    }

    MT793X_LOG("AppTask started");

    while (true)
    {
        BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10));
        while (eventReceived == pdTRUE)
        {
            sAppTask.DispatchEvent(&event);
            eventReceived = xQueueReceive(sAppEventQueue, &event, 0);
        }

        // Collect connectivity and configuration state from the CHIP stack. Because
        // the CHIP event loop is being run in a separate task, the stack must be
        // locked while these values are queried.  However we use a non-blocking
        // lock request (TryLockCHIPStack()) to avoid blocking other UI activities
        // when the CHIP task is busy (e.g. with a long crypto operation).
        if (PlatformMgr().TryLockChipStack())
        {
            sIsWiFiProvisioned = ConnectivityMgr().IsWiFiStationProvisioned();
            sIsWiFiEnabled     = ConnectivityMgr().IsWiFiStationEnabled();
            sIsWiFiAttached    = ConnectivityMgr().IsWiFiStationConnected();

            PlatformMgr().UnlockChipStack();
        }

        // Update the status LED if factory reset has not been initiated.
        //
        // If system has "full connectivity", keep the LED On constantly.
        //
        // If thread and service provisioned, but not attached to the thread network
        // yet OR no connectivity to the service OR subscriptions are not fully
        // established THEN blink the LED Off for a short period of time.
        //
        // If the system has ble connection(s) uptill the stage above, THEN blink
        // the LEDs at an even rate of 100ms.
        //
        // Otherwise, blink the LED ON for a very short time.
        if (sAppTask.mFunction != kFunction_FactoryReset)
        {
            if (sIsWiFiProvisioned && sIsWiFiEnabled && !sIsWiFiAttached)
            {
                sStatusLED.Blink(950, 50);
            }
            else
            {
                sStatusLED.Blink(50, 950);
            }
        }
    }
}

void AppTask::ThermostatActionEventHandler(AppEvent * aEvent)
{
    bool initiated = false;
    int32_t actor;
    CHIP_ERROR err = CHIP_NO_ERROR;

    if (aEvent->Type == AppEvent::kEventType_Button)
    {
        MT793X_LOG("Button was pressed!");
        // TODO: Implement button functionnality
    }
}

void AppTask::ButtonTimerEventHandler(AppEvent * aEvent)
{
    if (aEvent->Type != AppEvent::kEventType_Timer || sAppTask.mFunctionTimerActive == false)
    {
        return;
    }

    switch (sAppTask.mFunction)
    {
    case kFunction_NoneSelected:
        break;

    case kFunction_Thermostat:
        // Start timer for user to cancel the facotry reset, if needed
        MT793X_LOG("Factory Reset Triggered.");
        MT793X_LOG("Release button within %ums to cancel.", FACTORY_RESET_CANCEL_WINDOW_TIMEOUT);
        sAppTask.StartTimer(FACTORY_RESET_CANCEL_WINDOW_TIMEOUT);
        sAppTask.mFunction = kFunction_FactoryReset;

        // Turn off all LEDs before starting blink to make sure blink is
        // co-ordinated.
        sStatusLED.Set(false);
        sStatusLED.Blink(500);
        break;

    case kFunction_FactoryReset:
        MT793X_LOG("Factory Reset Start.");
        // Actually trigger Factory Reset
        sAppTask.mFunction = kFunction_NoneSelected;
        ConfigurationMgr().InitiateFactoryReset();
        sStatusLED.Set(true);
        break;

    default:
        break;
    }
}

void AppTask::SingleButtonEventHandler(AppEvent * aEvent)
{
    if (aEvent->Type != AppEvent::kEventType_Button)
    {
        MT793X_LOG("A Non ButtonEvent received %d", aEvent->Type);
        return;
    }

    if (aEvent->ButtonEvent.Pressed)
    {
        if (sAppTask.mFunctionTimerActive == false)
        {
            /* Start the timer to detect how long Button has been pressed */
            MT793X_LOG("AppTask status LED on");
            sStatusLED.Set(true);
            sAppTask.mFunction = kFunction_Thermostat;
            sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT);
        }
        else
        {
            MT793X_LOG("AppTask function timer already started");
        }
    }
    else
    {
        /* Cancel the timer to detect how long Button has been pressed */
        sAppTask.CancelTimer();

        switch (sAppTask.mFunction)
        {
        case kFunction_Thermostat:
            MT793X_LOG("AppTask thermostat");
            AppEvent event;
            event.Type = AppEvent::kEventType_Button;
            ThermostatActionEventHandler(&event);
            break;
        case kFunction_FactoryReset:
            // factory reset cancelled, restore LED
            MT793X_LOG("AppTask factory reset cancelled");
            break;
        default:
            MT793X_LOG("not handled key release event, mFunction = %x", sAppTask.mFunction);
            break;
        }

        sStatusLED.Set(false);

        sAppTask.mFunction = kFunction_NoneSelected;
    }
}

void AppTask::ButtonHandler(const filogic_button_t & button)
{
    AppEvent button_event            = {};
    button_event.Type                = AppEvent::kEventType_Button;
    button_event.ButtonEvent.Pressed = button.press;
    button_event.Handler             = SingleButtonEventHandler;
    sAppTask.PostEvent(&button_event);
}

void AppTask::TimerEventHandler(TimerHandle_t xTimer)
{
    AppEvent event;
    event.Type               = AppEvent::kEventType_Timer;
    event.TimerEvent.Context = (void *) xTimer;
    event.Handler            = ButtonTimerEventHandler;
    sAppTask.PostEvent(&event);
}

void AppTask::CancelTimer()
{
    if (xTimerStop(sFunctionTimer, 0) == pdFAIL)
    {
        MT793X_LOG("app timer stop() failed");
        appError(APP_ERROR_STOP_TIMER_FAILED);
    }

    mFunctionTimerActive = false;
}

void AppTask::StartTimer(uint32_t aTimeoutInMs)
{
    if (xTimerIsTimerActive(sFunctionTimer))
    {
        MT793X_LOG("app timer already started!");
        CancelTimer();
    }

    // timer is not active, change its period to required value (== restart).
    // FreeRTOS- Block for a maximum of 100 ticks if the change period command
    // cannot immediately be sent to the timer command queue.
    if (xTimerChangePeriod(sFunctionTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS)
    {
        MT793X_LOG("app timer start() failed");
        appError(APP_ERROR_START_TIMER_FAILED);
    }

    mFunctionTimerActive = true;
}

void AppTask::PostEvent(const AppEvent * aEvent)
{
    if (sAppEventQueue != NULL)
    {
        BaseType_t status;
        if (xPortIsInsideInterrupt())
        {
            BaseType_t higherPrioTaskWoken;

            higherPrioTaskWoken = pdFALSE;
            status              = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken);
            OS_YIELD_FROM_ISR(higherPrioTaskWoken);
        }
        else
        {
            status = xQueueSend(sAppEventQueue, aEvent, 1);
        }

        if (!status)
            MT793X_LOG("Failed to post event to app task event queue");
    }
    else
    {
        MT793X_LOG("Event Queue is NULL should never happen");
    }
}

void AppTask::DispatchEvent(AppEvent * aEvent)
{
    if (aEvent->Handler)
    {
        aEvent->Handler(aEvent);
    }
    else
    {
        MT793X_LOG("Event received with no handler. Dropping event.");
    }
}


text:
package jetbrains.buildServer.clouds.vmware.connector;

import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ResourcePool;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import jetbrains.buildServer.clouds.vmware.connector.beans.FolderBean;
import jetbrains.buildServer.clouds.vmware.connector.beans.ResourcePoolBean;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Sergey.Pak
 *         Date: 2/6/2015
 *         Time: 5:37 PM
 */
public class VmwareUtils {
  private static final String FOLDER_TYPE = Folder.class.getSimpleName();
  private static final String RESPOOL_TYPE = ResourcePool.class.getSimpleName();
  private static final String SPEC_FOLDER = "vm";
  private static final String SPEC_RESPOOL = "Resources";

  static boolean isSpecial(@NotNull final ResourcePoolBean pool){
    return SPEC_RESPOOL.equals(pool.getName()) && pool.getParentMOR() != null && !RESPOOL_TYPE.equals(pool.getParentMOR().getType());
  }

  static boolean isSpecial(@NotNull final FolderBean folder){
    return SPEC_FOLDER.equals(folder.getName()) && folder.getParentMOR() != null && !FOLDER_TYPE.equals(folder.getParentMOR().getType());
  }

}

redpajama_set_name: RedPajamaGithub


text:
using base::JSONWriter;
using std::string;
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;

namespace {

AssertionResult DictionaryCreationAssertionFailure() {
  return AssertionFailure() << "FakeServer failed to create an entities "
                            << "dictionary.";
}

AssertionResult VerificationCountAssertionFailure(size_t actual_count,
                                                  size_t expected_count) {
  return AssertionFailure() << "Actual count: " << actual_count << "; "
                            << "Expected count: " << expected_count;
}

AssertionResult UnknownTypeAssertionFailure(const string& model_type) {
  return AssertionFailure() << "Verification not attempted. Unknown ModelType: "
                            << model_type;
}

// Caller maintains ownership of |entities|.
string ConvertFakeServerContentsToString(
    const base::DictionaryValue& entities) {
  string entities_str;
  if (!JSONWriter::WriteWithOptions(&entities,
                                    JSONWriter::OPTIONS_PRETTY_PRINT,
                                    &entities_str)) {
    entities_str = "Could not convert FakeServer contents to string.";
  }
  return "FakeServer contents:\n" + entities_str;
}

}  // namespace

namespace fake_server {

FakeServerVerifier::FakeServerVerifier(FakeServer* fake_server)
    : fake_server_(fake_server) { }

FakeServerVerifier::~FakeServerVerifier() {}

AssertionResult FakeServerVerifier::VerifyEntityCountByType(
    size_t expected_count,
    syncer::ModelType model_type) const {
  scoped_ptr<base::DictionaryValue> entities =
      fake_server_->GetEntitiesAsDictionaryValue();
  if (!entities.get()) {
    return DictionaryCreationAssertionFailure();
  }

  string model_type_string = ModelTypeToString(model_type);
  base::ListValue* entity_list = NULL;
  if (!entities->GetList(model_type_string, &entity_list)) {
    return UnknownTypeAssertionFailure(model_type_string);
  } else if  (expected_count != entity_list->GetSize()) {
    return VerificationCountAssertionFailure(entity_list->GetSize(),
                                             expected_count)
        << "\n\n"
        << ConvertFakeServerContentsToString(*entities);
  }

  return AssertionSuccess();
}

AssertionResult FakeServerVerifier::VerifyEntityCountByTypeAndName(
    size_t expected_count,
    syncer::ModelType model_type,
    const string& name) const {
  scoped_ptr<base::DictionaryValue> entities =
      fake_server_->GetEntitiesAsDictionaryValue();
  if (!entities.get()) {
    return DictionaryCreationAssertionFailure();
  }

  string model_type_string = ModelTypeToString(model_type);
  base::ListValue* entity_list = NULL;
  size_t actual_count = 0;
  if (entities->GetList(model_type_string, &entity_list)) {
    scoped_ptr<base::Value> name_value(new base::StringValue(name));
    for (base::ListValue::const_iterator it = entity_list->begin();
         it != entity_list->end(); ++it) {
      if (name_value->Equals(*it)) {
        actual_count++;
      }
    }
  }

  if (!entity_list) {
    return UnknownTypeAssertionFailure(model_type_string);
  } else if (actual_count != expected_count) {
    return VerificationCountAssertionFailure(actual_count, expected_count)
        << "; Name: "
        << name
        << "\n\n"
        << ConvertFakeServerContentsToString(*entities);
  }

  return AssertionSuccess();
}

}  // namespace fake_server


text:
var gulp    = require('gulp');
var collect = require('gulp-rev-collector');
var config  = require('../../config').collect;

/**
 * Replace all links to assets in files
 * from a manifest file
 */
gulp.task('rev:collect', function() {
  return gulp.src(config.src)
  .pipe(collect())
  .pipe(gulp.dest(config.dest));
});


text:
struct Node;

/// A base test fixture that includes a State object with a
/// builtin "cat" rule.
struct StateTestWithBuiltinRules : public testing::Test {
  StateTestWithBuiltinRules();
  Node* GetNode(const string& path);

  State state_;
};

void AssertParse(State* state, const char* input);

/// An implementation of DiskInterface that uses an in-memory representation
/// of disk state.  It also logs file accesses and directory creations
/// so it can be used by tests to verify disk access patterns.
struct VirtualFileSystem : public DiskInterface {
  /// "Create" a file with a given mtime and contents.
  void Create(const string& path, int time, const string& contents);

  // DiskInterface
  virtual int Stat(const string& path);
  virtual bool MakeDir(const string& path);
  virtual string ReadFile(const string& path, string* err);
  virtual int RemoveFile(const string& path);

  /// An entry for a single in-memory file.
  struct Entry {
    int mtime;
    string contents;
  };

  vector<string> directories_made_;
  vector<string> files_read_;
  typedef map<string, Entry> FileMap;
  FileMap files_;
  set<string> files_removed_;
};

#endif // NINJA_TEST_H_


text:
/*    */ package edu.drexel.cis.dragon.qa.filter;
/*    */
/*    */ import edu.drexel.cis.dragon.qa.query.QuestionQuery;
/*    */ import edu.drexel.cis.dragon.qa.system.Candidate;
/*    */ import java.util.ArrayList;
/*    */
/*    */ public abstract class AbstractFilter
/*    */   implements CandidateFilter
/*    */ {
/*    */   public ArrayList filter(QuestionQuery query, ArrayList list)
/*    */   {
/* 13 */     ArrayList finalList = new ArrayList();
/* 14 */     for (int i = 0; i < list.size(); i++) {
/* 15 */       Candidate curTerm = (Candidate)list.get(i);
/* 16 */       if (keep(query, curTerm))
/* 17 */         finalList.add(curTerm);
/*    */     }
/* 19 */     return finalList;
/*    */   }
/*    */ }

/* Location:           C:\dragontoolikt\dragontool.jar
 * Qualified Name:     dragon.qa.filter.AbstractFilter
 * JD-Core Version:    0.6.2
 */


text:
import {increment, decrement, reset} from './actions/counter';

import store from './store';

// 打印初始状态
console.log(store.getState());

// 每次 state 更新时,打印日志
// 注意 subscribe() 返回一个函数用来注销监听器
let unsubscribe = store.subscribe(() =>
    console.log(store.getState())
);

// 发起一系列 action
store.dispatch(increment());
store.dispatch(decrement());
store.dispatch(reset());

// 停止监听 state 更新
unsubscribe();


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link href="../../custom.fineuploader-5.0.8.css" rel="stylesheet">

    <title>Fine Uploader default UI with thumbnails</title>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.labservices.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** Base tracked resource type for all PATCH updates. */
@Fluent
public class TrackedResourceUpdate {
    /*
     * Resource tags.
     */
    @JsonProperty(value = "tags")
    private List<String> tags;

    /**
     * Get the tags property: Resource tags.
     *
     * @return the tags value.
     */
    public List<String> tags() {
        return this.tags;
    }

    /**
     * Set the tags property: Resource tags.
     *
     * @param tags the tags value to set.
     * @return the TrackedResourceUpdate object itself.
     */
    public TrackedResourceUpdate withTags(List<String> tags) {
        this.tags = tags;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
<?php

include 'src/SplClassLoader.php';

$classLoader = new SplClassLoader('Eu\\IctCollege\\Schedule', 'src');
$classLoader->register();

date_default_timezone_set('UTC');

use \Eu\IctCollege\Schedule\Readers\DatabaseReader;
use \Eu\IctCollege\Schedule\Readers\EduflexReader;
use \Eu\IctCollege\Schedule\Parsers\DatabaseParser;
use \Eu\IctCollege\Schedule\Parsers\RstParser;
use \Eu\IctCollege\Schedule\DatabaseFiller;
use \Eu\IctCollege\Schedule\Diff;

/*$parser = new RstParser();
$a = $parser->parse(file_get_contents('02.rst'), 2014, 2);
$b = $parser->parse(file_get_contents('Week 05.rst'), 2014, 2);

$diff = new Diff();
print_r($diff->diff($a, $b));*/

/*$reader = new DatabaseReader();
$output = $reader->read(2014, 2);

$parser = new DatabaseParser();*/

//print_r($parser->parse($output));

$url = "http://roosters.roc-teraa.nl/rooster_uitwisseling/ict-college/2P0/2015022320150417/";
//$url = 'http://roosters.roc-teraa.nl/rooster_uitwisseling/onderwijs-kinderopvang-college/2P0/2014012720140411/';

$reader = new EduflexReader();
$parsed = $reader->read($url);

//var_dump($parsed);exit();

$db = new \PDO('mysql:host=mysql01.01d.eu;dbname=mauris_live', 'mauris', '');

$filler = new DatabaseFiller($db, 1);
//$filler = new DatabaseFiller($db, 6);
$filler->fill($parsed);


text:
layout:     post
title:      "JavaScript Objects"
subtitle:   "The big words on JS Objects"
date:       2015-07-17 12:00:00
author:     "Suraj"
header-img: "img/747.jpg"
---

{% highlight javascript %}

var o;

// Both are identical
o = {};
o = Object.create(Object.prototype);
// Object.create creates an object with prototoype as Object.prototype.
// Its same as o.__proto__ = Object.prototype
// PS: typeof o.prototype === 'undefined' // true

o = Object.create(null);
// creates an object with null as its prototype

// Creating Objects with some properties.
o = Object.create(Object.prototype, {
	someProperty : {
		value: 12,
		enumerable: false, // should be shown in for..in loop or not
		writable: false,
		configurable: false,
		set: function(val){},
		get: function(){ return 10;}
	}
})

// creating objects using Constructor functions
function SomeConstructorFn (){
	this.someProperty = 12;
};

SomeConstructorFn.prototype.someFunction = function(){
	console.log('ping');
};

// PS: Every function has a prototype 'property'. Best practise is to add only
// the behaviours i.e. functions to a function's prototype.
// Doing this has one more benefit, all these behavious will be created once in
// memory and will be shared among all the child objects.

o = new SomeConstructorFn();
o = Object.create(SomeConstructorFn.prototype);
// but this will not have any initializations done in the constructor function
// typeof o.someProperty === 'undefined' // true
// typeof o.someFunction === 'undefined' // false

// so to fix this and get all the declerations made in SomeConstructorFn -
SomeConstructorFn.call(o);
// typeof o.someProperty === 'undefined' // false
// o.someProperty // 12

// Inheritence - Vanilla Flavour

// Child: Foo
function Foo() {

}

Foo.prototype = new SomeConstructorFn();

// Inheritence - Strawberry Flavour

function Foo() {
	// call super constructor to get all the initializations made
	// in SomeConstructorFn function.
	SomeConstructorFn.call(this);
}

Foo.prototype = Object.create(SomeConstructorFn.prototype);

// Both the above approach has one small glitch. Their constructor property
// is wrongly set.
o = new Foo();
o.constructor // SomeConstructorFn

// So to fix it,
Foo.prototype.constructor = Foo;

// PS: The instanceof operator tests presence of constructor.prototype
// in object's prototype 'chain'.

// true: Object.getPrototypeOf(o) === Foo.prototype
o instanceof Foo // true
// true: Object.getPrototypeOf(Foo.prototype) === SomeConstructorFn.prototype
o instanceof SomeConstructorFn // true
// true: Object.getPrototypeOf(SomeConstructorFn.prototype) === Object.prototype
o instanceof Object // true

// Inheritence - Orange Flavour
// By using node's util.inherits

// How util.inherit works??
// It inherits the prototype methods from one constructor into another
exports.inherits = function(ctor, superCtor) {
  // As an additional convenience, superConstructor will be accessible
  // through the constructor.super_ property.
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

function Foo(){
	// SomeConstructorFn.call(this); Not required, that's one of the benefit,
	// we need not use the ancestor's name.
}

 // copies all the behaviours-/ethods/functions from SomeConstructorFn
 // constructos's prototype; namely someFunction
util.inherits(Foo, SomeConstructorFn);

o = new Foo();
o.constructor // Foo

// A word on Mixins
// To inherit from multiple objects, mixins are a possibility.
// The mixin function would copy the functions and properties from the superclass prototype to
//  the subclass prototype,
// the mixin function needs to be supplied by the user. An example of a mixin
//  like function would be jQuery.extend()

function extend(destination, source) {
  for (var k in source) {
    if (source.hasOwnProperty(k)) {
      destination[k] = source[k];
    }
  }
  return destination;
}

extend(Foo.prototype, SomeConstructorFn);

// References -
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
// https://developer.mozilla.org/en-US/docs/Glossary/Mixin
// http://bob.yexley.net/dry-javascript-with-mixins/
{% endhighlight %}


text:
{% load menu_tags %}

    {% for child in children %}

{{ child.get_menu_title }}

    {% endfor %}


text:
package com.haulmont.cuba.security.entity;

import com.haulmont.cuba.core.entity.BaseUuidEntity;
import com.haulmont.cuba.core.entity.Creatable;
import com.haulmont.cuba.core.entity.annotation.SystemLevel;

import javax.persistence.*;
import java.util.Date;

/**
 * User access groups hierarchy.
 */
@Entity(name = "sec$GroupHierarchy")
@Table(name = "SEC_GROUP_HIERARCHY")
@SystemLevel
public class GroupHierarchy extends BaseUuidEntity implements Creatable {

    private static final long serialVersionUID = 8106113488822530560L;

    @Column(name = "CREATE_TS")
    private Date createTs;

    @Column(name = "CREATED_BY", length = 50)
    private String createdBy;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "GROUP_ID")
    private Group group;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "PARENT_ID")
    private Group parent;

    @Column(name = "HIERARCHY_LEVEL")
    private Integer level;

    @Override
    public Date getCreateTs() {
        return createTs;
    }

    @Override
    public void setCreateTs(Date createTs) {
        this.createTs = createTs;
    }

    @Override
    public String getCreatedBy() {
        return createdBy;
    }

    @Override
    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public Group getParent() {
        return parent;
    }

    public void setParent(Group parent) {
        this.parent = parent;
    }
}


text:
//
//  EMStockListViewController.h
//  EMStock
//
//  Created by flora on 14-9-15.
//  Copyright (c) 2014年 flora. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "MSViewController.h"
#import "MSScrollableList.h"

NSString *const MSScrollableListCellSelectedNotification;
NSString *const MSScrollableListCellHighlightedNotification;

@interface MSScrollableListViewController : MSViewController <UITableViewDelegate, UITableViewDataSource>
{
    UIEdgeInsets _contentInsets;

    UIView       *_backgroundView;
    UITableView  *_titleTableView;
    UITableView  *_contentTableView;
    UIScrollView *_contentScrollView;

    UIView *_titleHeaderView;
    UIView *_contentHeaderView;

    UIView *_emptyView;

    //行情数据左右滚动提示视图
    UILabel *_scrollTipImageViewLeft;
    UILabel *_scrollTipImageViewRight;

    //数据模块,负责数据的收发、数据绘制解析等工作
    MSScrollableList *_scrollableList;

    NSMutableArray *_operationArray;
}

@property (nonatomic, strong, readonly) MSScrollableList *scrollableList;

- (instancetype)init;

/**
 *请求返回数据后加载数据
 *读取缓存数据后加载数据
 */
- (void)reloadDataSource;

@end


text:
const general = require('./general');
const boolean = require('./boolean');
const math = require('./math');
const list = require('./list');
const string = require('./string');

module.exports = Object.assign(
  {},
  general,
  boolean,
  math,
  list,
  string
);


text:
package gregex

import (
	"regexp"
	"sync"
)

var (
	regexMu = sync.RWMutex{}
	// Cache for regex object.
	// TODO There's no expiring logic for this map.
	regexMap = make(map[string]*regexp.Regexp)
)

// getRegexp returns *regexp.Regexp object with given <pattern>.
// It uses cache to enhance the performance for compiling regular expression pattern,
// which means, it will return the same *regexp.Regexp object with the same regular
// expression pattern.
func getRegexp(pattern string) (*regexp.Regexp, error) {
	if r := getCache(pattern); r != nil {
		return r, nil
	}
	if r, err := regexp.Compile(pattern); err == nil {
		setCache(pattern, r)
		return r, nil
	} else {
		return nil, err
	}
}

// getCache returns *regexp.Regexp object from cache by given <pattern>, for internal usage.
func getCache(pattern string) (regex *regexp.Regexp) {
	regexMu.RLock()
	regex = regexMap[pattern]
	regexMu.RUnlock()
	return
}

// setCache stores *regexp.Regexp object into cache, for internal usage.
func setCache(pattern string, regex *regexp.Regexp) {
	regexMu.Lock()
	regexMap[pattern] = regex
	regexMu.Unlock()
}


text:
from nose.tools import eq_, ok_
import pods
import pandas as pd
import numpy as np

test_user = 'opendsi.sheffield@gmail.com'

if pods.google.gspread_available:
    class Test_drive:
        def __init__(self):
            pass

        @classmethod
        def setup_class(cls):
            cls.drive = pods.google.drive()
            cls.resource_one = pods.google.resource(name='Test file', mime_type=pods.google.sheet_mime)
            cls.resource_two = pods.google.resource(name='Test file 2', mime_type=pods.google.sheet_mime)
            cls.sheet = pods.google.sheet()

        @classmethod
        def teardown_class(cls):
            cls.resource_one.delete(empty_bin=True)
            cls.resource_two.delete(empty_bin=True)
            cls.sheet.resource.delete(empty_bin=True)

        # Google drive tests
        def test_other_credentials(self):
            # Test opening drive by sharing credentials
            d = pods.google.drive(credentials=self.drive.credentials)

        def test_existing_service(self):
            # Test opening drive with existing service
            d = pods.google.drive(service=self.drive.service, http=self.drive.http)

        def resource_listed(self, resource):
            resources = self.drive.ls()
            found_resource = False
            for r in resources:
                if resource._id == r._id:
                    found_resource = True
            ok_(found_resource, msg="Resource not found in listing")

        def resource_not_listed(self, resource):
            resources = self.drive.ls()
            found_resource = False
            for r in resources:
                if resource._id == r._id:
                    found_resource = True
            ok_(not found_resource, msg="Resource found in listing")

        def share_listed(self, resource, user, status):
            shares = resource.share_list()
            found_share = False
            for s in shares:
                if s[0] == user:
                    eq_(s[1], status, msg="User share status incorrect")
                    found_share=True
            ok_(found_share, msg="Share not found in listing")

        def share_not_listed(self, resource, user):
            shares = resource.share_list()
            found_share = False
            for s in shares:
                if s[0] == user:
                    found_share=True
            ok_(not found_share, msg="Share found in listing")

        def test_ls(self):
            """Test that ls is working."""
            self.resource_listed(self.resource_one)
            self.resource_listed(self.resource_two)
            self.resource_listed(self.sheet.resource)

        def test_create_sheet(self):
            """Test codes ability to create sheets from existing resource."""
            s = pods.google.sheet(resource=self.resource_one)

        def test_delete(self):
            # Test that a file can be deleted and undeleted (using trash)
            self.resource_one.delete()
            self.resource_not_listed(self.resource_one)
            self.resource_one.undelete()
            self.resource_listed(self.resource_one)

        def test_share(self):
            """Test that resource can be shared."""
            self.resource_one.share(test_user)
            self.share_listed(self.resource_one, test_user, 'writer')
            self.resource_one.share_delete(test_user)
            self.share_not_listed(self.resource_one, test_user)

        def test_share_modify(self):
            """Test that sharing status can be changed."""
            self.resource_two.share(test_user)
            self.share_listed(self.resource_two, test_user, 'writer')
            self.resource_two.share_modify(test_user, 'reader')
            self.share_listed(self.resource_two, test_user, 'reader')

        def test_name_change(self):
            """Test that the name of the file on google drive can be changed."""
            new_name = "Testing Name 2"
            self.resource_one.update_name(new_name)
            eq_(new_name, self.resource_one.get_name(), msg="Name change has failed to take effect")

        def test_mime_type(self):
            "Test that mime_type of file is correct."
            eq_(self.sheet.resource.get_mime_type(), pods.google.sheet_mime, msg="Mime type of google spread sheet does not match expectation.")

    class Test_sheet():
        """Class for testing google spreadsheet functionality."""

        @classmethod
        def setup_class(cls):
            cls.col_indent = 3
            cls.header = 4
            pods.datasets.override_manual_authorize=True
            cls.sheet_one = pods.google.sheet()
            cls.resource = pods.google.resource(drive=cls.sheet_one.resource.drive, mime_type=pods.google.sheet_mime)
            cls.sheet_two = pods.google.sheet(resource=cls.resource)
            cls.data = pods.datasets.movie_body_count()

            cls.sheet_two.write(cls.data['Y'])
            cls.sheet_two.resource.share(['lawrennd@gmail.com', 'N.Lawrence@sheffield.ac.uk'])

            cls.sheet_three = pods.google.sheet(col_indent=cls.col_indent, header=cls.header)
            cls.sheet_three.write(cls.data['Y'])

            cls.data_two = pd.DataFrame([[0.2, 'cat', 12], ['orange', 'barley', np.nan], [12, 11, 2.3], [2.3, 'egg', 'plant'], ['Sheffield', 'United', 'FC'], ['Sheffield', 'Wednesday', 'FC']], columns = ['dog', 'flea', 'cat'], index = ['a', 'b', 'c', 'd', 'e', 'f'])
            cls.update_sheet = pods.google.sheet(col_indent=cls.col_indent, header=cls.header)
            cls.update_sheet.write(cls.data_two)

            cls.update_sheet_two = pods.google.sheet()
            cls.update_sheet_two.write(cls.data_two)

            cls.update_sheet_three = pods.google.sheet()
            cls.update_sheet_three.write(cls.data_two)

            cls.update_sheet_four = pods.google.sheet()
            cls.update_sheet_four.write(cls.data_two)

        @classmethod
        def teardown_class(cls):
            """Delete of the sheets created for the tests."""
            cls.sheet_one.resource.delete(empty_bin=True)
            cls.sheet_two.resource.delete(empty_bin=True)
            cls.sheet_three.resource.delete(empty_bin=True)
            cls.update_sheet.resource.delete(empty_bin=True)
            cls.update_sheet_two.resource.delete(empty_bin=True)
            cls.update_sheet_three.resource.delete(empty_bin=True)
            cls.update_sheet_four.resource.delete(empty_bin=True)

        def read_sheet(self, sheet, df):
            """Test reading."""
            df2 = sheet.read()
            eq_(df2.shape[0], df.shape[0], "Rows of read data frame do not match.")
            eq_(df2.shape[1], df.shape[1], "Columns of read data frame do not match.")
            for column in df.columns:
                if column not in df2.columns:
                    ok_(False, "Missing column " + str(column) + " in downloaded frame.")
            for index in df.index:
                if index not in df2.index:
                    ok_(False, "Missing index " + str(index) + " in downloaded frame.")

        def test_read(self):
            """Test reading."""
            print("Test reading of sheet started at origin.")
            self.read_sheet(self.sheet_two, self.data['Y'])

        def test_read_indented(self):
            """Test reading of indented and headered sheet."""
            print("Test reading of sheet offset from origin.")
            self.read_sheet(self.sheet_three, self.data['Y'])

        def test_drop(self):
            """Test reading."""
            print("Test dropping of rows from sheet.")
            data_three = self.data_two.drop(['c', 'e'])
            self.update_sheet.update(data_three)
            self.read_sheet(self.update_sheet, data_three)

        def test_drop_swap(self):
            """Test reading."""
            print("Test dropping and replacing with other rows.")
            data_three = self.data_two.drop(['c', 'e'])
            data_three.loc['barry'] = ['bat', 'ball', np.nan]
            data_three.loc['sid'] = ['bart', 'simpson', 'naff']
            self.update_sheet_two.update(data_three)
            self.read_sheet(self.update_sheet_two, data_three)

        def test_add(self):
            """Test reading."""
            print("Test adding of rows to sheet.")
            data_three = self.data_two.copy()
            data_three.loc['barry'] = ['bat', 'ball', np.nan]
            data_three.loc['sid'] = ['bart', 'simpson', 'naff']
            self.update_sheet_three.update(data_three)
            self.read_sheet(self.update_sheet_three, data_three)

        def test_update(self):
            """Test reading."""
            print("Test adding of rows to sheet.")
            data_three = self.data_two.copy()
            data_three['flea']['f'] = 'United'
            data_three['dog']['e'] = 23.2
            self.update_sheet_four.update(data_three)
            self.read_sheet(self.update_sheet_four, data_three)


text:
package com.scratchpad.document;

public class MarkdownDocument implements Document
{
    private static MarkdownDocument nullInstance;
    String title;
    String markdown;

    public static MarkdownDocument getInstance(String title, String markdown)
    {
        MarkdownDocument markdownDocument = new MarkdownDocument(title, markdown);
        return markdownDocument;
    }

    public static MarkdownDocument getDefaultInstance()
    {
        if (null == nullInstance)
        {
            nullInstance = new MarkdownDocument("", "");
        }
        return nullInstance;
    }

    @Override
    public String getTitle()
    {
        return title;
    }

    @Override
    public String getContent()
    {
        return markdown;
    }

    MarkdownDocument(String title, String markdown)
    {
        this.title = title;
        this.markdown = markdown;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.fop.render.java2d.Java2DRenderer (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.fop.render.java2d.Java2DRenderer

Packages that use Java2DRenderer

org.apache.fop.render.awt
AWT Renderer used for displaying rendered pages in Java applications.

org.apache.fop.render.bitmap
Bitmap Renderer which creates TIFF and PNG images from rendered pages.

org.apache.fop.render.print
Renderer which prints rendered pages directly to a printer.

org.apache.fop.render.svg
SVG (Structured Vector Graphics) Renderer

Uses of Java2DRenderer in org.apache.fop.render.awt

Subclasses of Java2DRenderer in org.apache.fop.render.awt

 class
AWTRenderer

          The AWTRender outputs the pages generated by the layout engine to a Swing
 window.

Uses of Java2DRenderer in org.apache.fop.render.bitmap

Subclasses of Java2DRenderer in org.apache.fop.render.bitmap

 class
PNGRenderer

          PNG Renderer This class actually does not render itself, instead it extends
 org.apache.fop.render.java2D.Java2DRenderer and just encode
 rendering results into PNG format using Batik's image codec

 class
TIFFRenderer

 This class represents renderer to TIFF (Tagged Image File Format) format.

Uses of Java2DRenderer in org.apache.fop.render.print

Subclasses of Java2DRenderer in org.apache.fop.render.print

 class
PageableRenderer

          Renderer that prints through java.awt.PrintJob.

 class
PrintRenderer

          Renderer that prints through java.awt.PrintJob.

Uses of Java2DRenderer in org.apache.fop.render.svg

Subclasses of Java2DRenderer in org.apache.fop.render.svg

 class
SVGRenderer

 This renderer generates SVG (Scalable Vector Graphics) format.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.


text:
The **[Spriter Data API](https://github.com/Thinksquirrel-Software/spriterdapi-unity)** is an object model in C# that follows the SCML (Spriter Character Markup Language) specification. It abstracts reading from an SCML file, allowing developers to easily integrate Spriter into their own applications.

For more information about Spriter, please visit <http://brashmonkey.com/spriter.htm>

This version of the API is written for the Unity game engine (<http://unity3d.com>).

This repository includes the ex2D implementation of the Data API.

### Requirements

**[Spriter Data API](https://github.com/Thinksquirrel-Software/spriterdapi-unity)**

**[ex2D](http://www.ex-dev.com/ex2d/)**

### Installation

Place the contents of this repository in the Assets folder of your Unity project.

### Acknowledgments

Special thanks to:

* The ex2D devs for guidance in the atlas creation process.

### License

The Spriter Data API is licensed under the [MIT License](https://github.com/Thinksquirrel-Software/spriterdapi-unity-ngui/blob/master/LICENSE.txt).


text:
package org.synote.player.client;

public class TranscriptSynpoint
{
	private static final long serialVersionUID = 1L;

	private String id;
	private int startIndex;
	private int endIndex;
	private int startTime;
	private int endTime;

	protected TranscriptSynpoint()
	{
		// This constructor is needed for GWT RPC.
	}

	public TranscriptSynpoint(int startIndex, int endIndex, int startTime, int endTime)
	{
		this(null, startIndex, endIndex, startTime, endTime);
	}

	public TranscriptSynpoint(String id, int startIndex, int endIndex, int startTime, int endTime)
	{
		this.id = id;
		this.startIndex = startIndex;
		this.endIndex = endIndex;
		this.startTime = startTime;
		this.endTime = endTime;
	}

	public String getId()
	{
		return id;
	}

	public int getStartIndex()
	{
		return startIndex;
	}

	public void setStartIndex(int startIndex)
	{
		this.startIndex = startIndex;
	}

	public int getEndIndex()
	{
		return endIndex;
	}

	public void setEndIndex(int endIndex)
	{
		this.endIndex = endIndex;
	}

	public int getStartTime()
	{
		return startTime;
	}

	public void setStartTime(int startTime)
	{
		this.startTime = startTime;
	}

	public int getEndTime()
	{
		return endTime;
	}

	public void setEndTime(int endTime)
	{
		this.endTime = endTime;
	}
}


text:
class AddSubdomainIdToPetition < ActiveRecord::Migration
  def change
    add_column :petitions, :subdomain_id, :integer
  end
end


text:
'use strict';

function pad(str, padWith, upToLength) {
  var padding = '';
  var targetLength = upToLength - str.length;
  /* istanbul ignore next */
  while (padding.length < targetLength) {
    padding += padWith;
  }
  return padding;
}

function padLeft(str, padWith, upToLength) {
  var padding = pad(str, padWith, upToLength);
  return padding + str;
}

function padRight(str, padWith, upToLength) {
  var padding = pad(str, padWith, upToLength);
  return str + padding;
}

function stringLexCompare(a, b) {

  var aLen = a.length;
  var bLen = b.length;

  var i;
  for (i = 0; i < aLen; i++) {
    if (i === bLen) {
      // b is shorter substring of a
      return 1;
    }
    var aChar = a.charAt(i);
    var bChar = b.charAt(i);
    if (aChar !== bChar) {
      return aChar < bChar ? -1 : 1;
    }
  }

  if (aLen < bLen) {
    // a is shorter substring of b
    return -1;
  }

  return 0;
}

/*
 * returns the decimal form for the given integer, i.e. writes
 * out all the digits (in base-10) instead of using scientific notation
 */
function intToDecimalForm(int) {

  var isNeg = int < 0;
  var result = '';

  do {
    var remainder = isNeg ? -Math.ceil(int % 10) : Math.floor(int % 10);

    result = remainder + result;
    int = isNeg ? Math.ceil(int / 10) : Math.floor(int / 10);
  } while (int);

  if (isNeg && result !== '0') {
    result = '-' + result;
  }

  return result;
}

export {
  padLeft,
  padRight,
  stringLexCompare,
  intToDecimalForm
};


text:
<?php

namespace OpCacheGUITest\Mocks\Presentation;

use OpCacheGUI\Presentation\Template;

class TemplateMock extends Template
{
    public function render($template, array $data = [])
    {
    }

    /**
     * @param string $key
     * @param string $value
     */
    public function set($key, $value)
    {
        $this->variables[$key] = $value;
    }
}


text:
using AllReady.Areas.Admin.Models;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AllReady.Areas.Admin.Features.Activities
{
    public class DeleteActivityCommand : IRequest
    {
        public int ActivityId {get; set;}
    }
}


text:
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fcontext-stack44  #-}
module Games.Chaos2010.Database.Colours where
import Games.Chaos2010.Database.Fields
import Database.HaskellDB.DBLayout

type Colours =
     Record
       (HCons (LVPair Name (Expr String))
          (HCons (LVPair Red (Expr Int))
             (HCons (LVPair Green (Expr Int))
                (HCons (LVPair Blue (Expr Int)) HNil))))

colours :: Table Colours
colours = baseTable "colours"


text:
namespace pythonic
{

  namespace __builtin__
  {

    namespace details
    {
      template <class Iterator0, class... Iterators>
      auto zip(size_t n, Iterator0 first, Iterators... iters)
          -> types::list<decltype(types::make_tuple(*first, *iters...))>
      {
        types::list<decltype(types::make_tuple(*first, *iters...))> out =
            types::empty_list();
        out.reserve(n);
        for (size_t i = 0; i < n; ++i, ++first, utils::fwd(++iters...))
          out.push_back(types::make_tuple(*first, *iters...));
        return out;
      }
    }

    template <class List0, class... Lists>
    auto zip(List0 &&s0, Lists &&... lists)
        -> types::list<decltype(types::make_tuple(*s0.begin(),
                                                  *lists.begin()...))>
    {
      size_t n =
          min(len(std::forward<List0>(s0)), len(std::forward<Lists>(lists))...);
      return details::zip(n, s0.begin(), lists.begin()...);
    }

    types::empty_list zip()
    {
      return types::empty_list();
    }

    DEFINE_FUNCTOR(pythonic::__builtin__, zip);
  }
}

#endif


text:
"""
    test.apis
    {{ "~" * "test.apis"|count }}

    :author: {{ cookiecutter.author }}
    :copyright: (c) {{ cookiecutter.copyright }}
    :license: {{ cookiecutter.license }}, see LICENSE for more details.

    templated from https://github.com/ryanolson/cookiecutter-webapp
"""
from flask import Blueprint
from {{ cookiecutter.app_name }} import api

class SecureAPI(api.BaseAPI):

    @api.secure_endpoint()
    def index(self):
        return {
            "secret": "shhhhhh, keep this quiet",
        }

class SecureResource(api.BaseResource):

    @api.secure_endpoint()
    def get(self):
        return {
            "secret": "shhhhhh, keep this quiet",
        }

def classy_api(app):
    """Create an Flask-Classy-based API on app"""
    bp = api.v1.create_blueprint('test', url_prefix='/api/tests')
    SecureAPI.register(bp)
    api.register_blueprint(app, bp)

def restful_api(app):
    """Create an Flask-RESTful-based API on app"""
    api_ext = app.extensions['classy_api']
    api_ext.add_resource(api.v1.TodosResource, '/api/tests/todos', endpoint='todos_api')
    api_ext.add_resource(api.v1.TodoResource, '/api/tests/todos/<int:id>', endpoint='todo_api')
    api_ext.add_resource(SecureResource, '/api/tests/secure', endpoint='secure')


text:
""":mod:`config` module contains configuration functions and classes for :mod:`latest` package.

:mod:`latest` is configurable both programmatically and through a configuration file.

Configurations are contained in a :class:`_Config` object. Constructor (:code:`__init__` method) of this class
accepts the optional keyword argument :code:`config_file` to specify the location of the configuration file.
If no configuration file is specified, defaults are set in code.
A default configuration object (:code:`config`) is defined in this module and can be imported to be used elsewhere.
I suggest an import statement like

.. code::

    from latest.config import config as Config

so that you can think of it as a class with many static attributes and methods.
To create an alternate configuration object you can use the public function :code:`create_config(config_file=None)`.

Configuration file is found by default (:code:`config` looks for this location)
in :code:`~/.latest/latest.cfg` but one can use his own configuration files.
The formatting of a configuration file must be :code:`ini` format.

Useful sections of a configuration file are:

    * general
    * lang

The section *lang* of a configuration file is where one can define its own syntax.
Available options in `lang` section are:

    * `pyexpr_entry`: the regex indicating the start of a python expression block.
    * `pyexpr_exit`: the regex indicating the end of a python expression block.
    * `env_entry`: the regex indicating the start of a `latest` environment.
    * `env_exit`: the regex indicating the end of a `latest` environment.

"""

import os
try:
    import configparser
except ImportError:
    import ConfigParser as configparser

from .util import path, getopt

_BASE_DIR = path('~/.latest/')
_CONFIG_FILE = os.path.join(_BASE_DIR, 'latest.cfg')
_TEMPLATES_DIR = os.path.join(_BASE_DIR, 'templates/')

class _Config(object):

    _OPTIONS = (
        # section, key, default
        ('general', 'templates_dir', _TEMPLATES_DIR),
        ('general', 'join', str()),
        ('lang', 'pyexpr_entry', r'\{\$'),
        ('lang', 'pyexpr_exit', r'\$\}'),
        ('lang', 'opts_entry', r'\['),
        ('lang', 'opts_exit', r'\]'),
        ('lang', 'str_pyexpr_entry', r'\\latest'),
        ('lang', 'str_pyexpr_exit', None),
        ('lang', 'env_entry', r'\\begin\{latest\}'),
        ('lang', 'env_exit', r'\\end\{latest\}'))

    def __init__(self, config_file=None):
        if config_file:
            self.read(config_file)
        else:
            self.set_defaults()

    def set_defaults(self):
        for _, key, default in self._OPTIONS:
            setattr(self, key, default)

    def read(self, filename):

        config_file = path(filename)
        if not hasattr(self, 'config_files'):
            self.config_files = list()
        self.config_files.append(config_file)

        parser = configparser.RawConfigParser()
        parser.read(config_file)
        for section, key, default in self._OPTIONS:
            value = getopt(parser, section, key, default)
            setattr(self, key, value)

def create_config(config_file=None):
    return _Config(config_file)

config = _Config(config_file=_CONFIG_FILE)


text:
package org.apache.ignite.internal.processors.hadoop.taskexecutor.external.communication;

import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.processors.hadoop.message.HadoopMessage;
import org.apache.ignite.internal.util.nio.GridNioFilterAdapter;
import org.apache.ignite.internal.util.nio.GridNioFuture;
import org.apache.ignite.internal.util.nio.GridNioSession;
import org.apache.ignite.marshaller.Marshaller;

/**
 * Serialization filter.
 */
public class HadoopMarshallerFilter extends GridNioFilterAdapter {
    /** Marshaller. */
    private Marshaller marshaller;

    /**
     * @param marshaller Marshaller to use.
     */
    public HadoopMarshallerFilter(Marshaller marshaller) {
        super("HadoopMarshallerFilter");

        this.marshaller = marshaller;
    }

    /** {@inheritDoc} */
    @Override public void onSessionOpened(GridNioSession ses) throws IgniteCheckedException {
        proceedSessionOpened(ses);
    }

    /** {@inheritDoc} */
    @Override public void onSessionClosed(GridNioSession ses) throws IgniteCheckedException {
        proceedSessionClosed(ses);
    }

    /** {@inheritDoc} */
    @Override public void onExceptionCaught(GridNioSession ses, IgniteCheckedException ex) throws IgniteCheckedException {
        proceedExceptionCaught(ses, ex);
    }

    /** {@inheritDoc} */
    @Override public GridNioFuture<?> onSessionWrite(GridNioSession ses, Object msg) throws IgniteCheckedException {
        assert msg instanceof HadoopMessage : "Invalid message type: " + msg;

        return proceedSessionWrite(ses, marshaller.marshal(msg));
    }

    @Override public void onMessageReceived(GridNioSession ses, Object msg) throws IgniteCheckedException {
        assert msg instanceof byte[];

        // Always unmarshal with system classloader.
        proceedMessageReceived(ses, marshaller.unmarshal((byte[])msg, null));
    }

    /** {@inheritDoc} */
    @Override public GridNioFuture<Boolean> onSessionClose(GridNioSession ses) throws IgniteCheckedException {
        return proceedSessionClose(ses);
    }

    /** {@inheritDoc} */
    @Override public void onSessionIdleTimeout(GridNioSession ses) throws IgniteCheckedException {
        proceedSessionIdleTimeout(ses);
    }

    /** {@inheritDoc} */
    @Override public void onSessionWriteTimeout(GridNioSession ses) throws IgniteCheckedException {
        proceedSessionWriteTimeout(ses);
    }
}


text:
import { Callback } from 'ffi'

import { VCXInternalError } from '../errors'
import { initRustAPI, rustAPI } from '../rustlib'
import { createFFICallbackPromise } from '../utils/ffi-helpers'
import { IInitVCXOptions } from './common'

/**
 * Initializes VCX with config file.
 * An example config file is at libvcx/sample_config/config.json
 *
 * Example:
 * ```
 * await initVcx('/home/username/vcxconfig.json')
 * ```
 */
export async function initVcx (configPath: string, options: IInitVCXOptions = {}): Promise<void> {
  initRustAPI(options.libVCXPath)
  let rc = null
  try {
    return await createFFICallbackPromise<void>(
      (resolve, reject, cb) => {
        rc = rustAPI().vcx_init(0, configPath, cb)
        if (rc) {
          reject(rc)
        }
      },
      (resolve, reject) => Callback(
        'void',
        ['uint32', 'uint32'],
        (xhandle: number, err: number) => {
          if (err) {
            reject(err)
            return
          }
          resolve()
        })
    )
  } catch (err) {
    throw new VCXInternalError(err)
  }
}

/**
 * Initializes VCX with config file.
 * An example config file is at libvcx/sample_config/config.json
 *
 * Example:
 * ```
 * config = {
 *   "agency_did": "VsKV7grR1BUE29mG2Fm2kX",
 *   "agency_verkey": "Hezce2UWMZ3wUhVkh2LfKSs8nDzWwzs2Win7EzNN3YaR",
 *   "agency_endpoint": "http://localhost:8080",
 *   "genesis_path":"/var/lib/indy/verity-staging/pool_transactions_genesis",
 *   "institution_name": "institution",
 *   "institution_logo_url": "http://robohash.org/234",
 *   "institution_did": "EwsFhWVoc3Fwqzrwe998aQ",
 *   "institution_verkey": "8brs38hPDkw5yhtzyk2tz7zkp8ijTyWnER165zDQbpK6",
 *   "remote_to_sdk_did": "EtfeMFytvYTKnWwqTScp9D",
 *   "remote_to_sdk_verkey": "8a7hZDyJK1nNCizRCKMr4H4QbDm8Gg2vcbDRab8SVfsi",
 *   "sdk_to_remote_did": "KacwZ2ndG6396KXJ9NDDw6",
 *   "sdk_to_remote_verkey": "B8LgZGxEPcpTJfZkeqXuKNLihM1Awm8yidqsNwYi5QGc"
 *  }
 * await initVcxWithConfig('/home/username/vcxconfig.json')
 * ```
 */
export async function initVcxWithConfig (config: string, options: IInitVCXOptions = {}): Promise<void> {
  initRustAPI(options.libVCXPath)
  let rc = null
  try {
    return await createFFICallbackPromise<void>(
      (resolve, reject, cb) => {
        rc = rustAPI().vcx_init_with_config(0, config, cb)
        if (rc) {
          reject(rc)
        }
      },
      (resolve, reject) => Callback(
        'void',
        ['uint32', 'uint32'],
        (xhandle: number, err: number) => {
          if (err) {
            reject(err)
            return
          }
          resolve()
        })
    )
  } catch (err) {
    throw new VCXInternalError(err)
  }
}

export function initMinimal (config: string): number {
  return rustAPI().vcx_init_minimal(config)
}


text:
#mobile-check {
  width: 100%;
  height: 0;
  visibility: hidden;
  float: none;
}

.rbblockgallery {
  position: relative;
}

.rbblockgallery div[class^='rb-column'], .rbblockgallery div[class*='rb-column'] {
  height: 100%;
}

.rbblockgallery div[class^='rb-column'] .rbblockgallery-item, .rbblockgallery div[class*='rb-column'] .rbblockgallery-item {
  position: relative;
  margin-bottom: 30px;
  overflow: hidden;
  background: gray;
}

.rbblockgallery div[class^='rb-column'] .rbblockgallery-item img, .rbblockgallery div[class*='rb-column'] .rbblockgallery-item img {
  width: 100%;
  height: auto;
}

.rbblockgallery div[class^='rb-column'] .cropToV img, .rbblockgallery div[class^='rb-column'] cropToH img, .rbblockgallery div[class*='rb-column'] .cropToV img, .rbblockgallery div[class*='rb-column'] cropToH img {
  display: block;
  position: absolute;
}

.rbblockgallery div[class^='rb-column'] .cropToV img, .rbblockgallery div[class*='rb-column'] .cropToV img {
  left: 50%;
  height: 100%;
  width: auto;
  max-width: none;
  -webkit-transform: translateX(-50%);
      -ms-transform: translateX(-50%);
          transform: translateX(-50%);
}

.rbblockgallery div[class^='rb-column'] .cropToH img, .rbblockgallery div[class*='rb-column'] .cropToH img {
  top: 50%;
  width: 100%;
  height: auto;
  max-height: none;
  -webkit-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
          transform: translateY(-50%);
}

/* Small Devices, Tablets */
@media only screen and (max-width: 768px) {
  #mobile-check {
    float: left;
  }
}

/*# sourceMappingURL=rb-block-gallery.css.map */


text:
from django.conf.urls import url
from django.urls import path

from . import accounting_views, \
    alias_views, \
    cloud_views, \
    ec2_views, \
    group_views, \
    job_views, \
    server_views, \
    settings_views, \
    user_views, \
    vm_views

urlpatterns = [

    path('',                                       cloud_views.status),

    path('accounting/apel/',                       accounting_views.apel),

    path('alias/add/',                             alias_views.add),
    path('alias/list/',                            alias_views.alias_list),
    path('alias/update/',                          alias_views.update),
    path('alias/delete/',                          alias_views.delete),

    path('cloud/add/',                             cloud_views.add),
    path('cloud/delete/',                          cloud_views.delete),
    path('cloud/list/',                            cloud_views.cloud_list),
    path('cloud/status/',                          cloud_views.status),
    path('cloud/status/plot',                      cloud_views.request_ts_data),
    path('cloud/update/',                          cloud_views.update),
    path('cloud/metadata-add/',                    cloud_views.metadata_add),
    path('cloud/metadata-collation/',              cloud_views.metadata_collation),
    path('cloud/metadata-delete/',                 cloud_views.metadata_delete),
    path('cloud/metadata-fetch/',                  cloud_views.metadata_fetch),
    path('cloud/metadata-list/',                   cloud_views.metadata_list),
    path('cloud/metadata-new/',                    cloud_views.metadata_new),
    path('cloud/metadata-query/',                  cloud_views.metadata_query),
    path('cloud/metadata-update/',                 cloud_views.metadata_update),

    path('ec2/images/',                            ec2_views.images),
    path('ec2/instance-types/',                    ec2_views.instance_types),

    path('group/add/',                             group_views.add),
    path('group/defaults/',                        group_views.defaults),
    path('group/delete/',                          group_views.delete),
    path('group/list/',                            group_views.group_list),
    path('group/update/',                          group_views.update),
    path('group/metadata-add/',                    group_views.metadata_add),
    path('group/metadata-delete/',                 group_views.metadata_delete),
    path('group/metadata-fetch/',                  group_views.metadata_fetch),
    path('group/metadata-list/',                   group_views.metadata_list),
    path('group/metadata-new/',                    group_views.metadata_new),
    path('group/metadata-query/',                  group_views.metadata_query),
    path('group/metadata-update/',                 group_views.metadata_update),

    path('job/list/',                              job_views.job_list),
##  path('job/modify/',                            job_views.modify),

    path('server/config/',                         server_views.configuration),

##  path('settings/preferences/',                  settings_views.preferences),
    path('settings/prepare/',                      settings_views.prepare),
    path('settings/log-out/',                      settings_views.log_out),

    path('user/add/',                              user_views.add),
    path('user/delete/',                           user_views.delete),
    path('user/list/',                             user_views.user_list),
    path('user/settings/',                         user_views.settings),
    path('user/update/',                           user_views.update),

    path('vm/foreign/',                            vm_views.foreign),
    path('vm/list/',                               vm_views.vm_list),
    path('vm/update/',                             vm_views.update),

]


text:
/**
 * This example shows how to align button text to the right. By default, buttons are sized
 * to the width of the text inside them, but this behavior can be overridden by giving the
 * button a fixed width. In such a case the alignment of the text can be controlled using
 * the `textAlign` config.
 */
Ext.define('KitchenSink.view.button.RightTextButtons', {
    extend: 'Ext.Container',
    xtype: 'right-text-buttons',
    layout: 'vbox',

    initComponent: function() {
        Ext.apply(this, {
            width: 680,
            items: [{
                xtype: 'checkbox',
                boxLabel: 'disabled',
                margin: '0 0 0 10',
                listeners: {
                    change: this.toggleDisabled,
                    scope: this
                }
            }, {
                xtype: 'container',
                layout: {
                    type: 'table',
                    columns: 4,
                    tdAttrs: { style: 'padding: 5px 10px;' }
                },
                defaults: {
                    width: 150,
                    textAlign: 'right'
                },

                items: [{
                    xtype: 'component',
                    html: 'Text Only'
                }, {
                    xtype: 'button',
                    text: 'Small'
                }, {
                    xtype: 'button',
                    text: 'Medium',
                    scale: 'medium'
                }, {
                    xtype: 'button',
                    text: 'Large',
                    scale: 'large'
                }, {
                    xtype: 'component',
                    html: 'Icon Only'
                }, {
                    iconCls: 'button-home-small',
                    xtype: 'button'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-medium',
                    scale: 'medium'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-large',
                    scale: 'large'
                }, {
                    xtype: 'component',
                    html: 'Icon and Text (left)'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-small',
                    text: 'Small'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-medium',
                    text: 'Medium',
                    scale: 'medium'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-large',
                    text: 'Large',
                    scale: 'large'
                }, {
                    xtype: 'component',
                    html: 'Icon and Text (top)'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-small',
                    text: 'Small',
                    iconAlign: 'top'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-medium',
                    text: 'Medium',
                    scale: 'medium',
                    iconAlign: 'top'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-large',
                    text: 'Large',
                    scale: 'large',
                    iconAlign: 'top'
                }, {
                    xtype: 'component',
                    html: 'Icon and Text (right)'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-small',
                    text: 'Small',
                    iconAlign: 'right'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-medium',
                    text: 'Medium',
                    scale: 'medium',
                    iconAlign: 'right'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-large',
                    text: 'Large',
                    scale: 'large',
                    iconAlign: 'right'
                }, {
                    xtype: 'component',
                    html: 'Icon and Text (bottom)'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-small',
                    text: 'Small',
                    iconAlign: 'bottom'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-medium',
                    text: 'Medium',
                    scale: 'medium',
                    iconAlign: 'bottom'
                }, {
                    xtype: 'button',
                    iconCls: 'button-home-large',
                    text: 'Large',
                    scale: 'large',
                    iconAlign: 'bottom'
                }]
            }]
        });
        this.callParent();
    },

    toggleDisabled: function(checkbox, newValue, oldValue) {
        var toggleFn = newValue ? 'disable' : 'enable';

        Ext.each(this.query('button'), function(item) {
            item[toggleFn]();
        });
    }

});


text:
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.db.models import Count
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from sunlightapi import sunlight
from citizendialer3000.forms import CallForm
from citizendialer3000.models import Campaign, Contact, Call
import json
import re
import tablib

KEY_PREFIX = getattr(settings, 'CD3000_KEY_PREFIX', 'CD3000')
TIMEOUT = getattr(settings, 'CD3000_CACHE_TIMEOUT', 60 * 10) # 10 minutes
ZIPCODE_RE = re.compile(r'^\d{5}$')

sunlight.apikey = getattr(settings, 'CD3000_SUNLIGHTAPI_KEY')

def callcampaign_list(request):
    """ Displays all publicly available campaigns.

        Context:
            campaigns   - query set of public campaigns

        Template:
            citizendialer3000/campaign_list.html
    """

    data = {'campaigns': Campaign.objects.filter(is_public=True)}
    return render_to_response('citizendialer3000/campaign_list.html', data,
                              context_instance=RequestContext(request))

def callcampaign_detail(request, slug):
    """ Display summary info and zipcode search box for campaign
        specified by slug.

        If a zipcode query string paramter is present, contacts will be pulled
        from the Sunlight Labs Congress API. The zipcode will be stored in the
        user session for use later in the process.

        Context:
            campaign    - the current campaign
            contacts    - list of contacts, if zipcode has been provided
            zipcode     - if provided

        Template:
            citizendialer3000/campaign_detail.html
    """

    campaign = get_object_or_404(Campaign, slug=slug)
    if not campaign.is_public:
        return HttpResponseRedirect(reverse('call_list'))

    data = {
        'campaign': campaign,
        'called': request.session.get("%s.called" % campaign.slug, []),
    }

    if campaign.is_complete:
        # campaign is complete, show the wrapup message
        # include final results if you want to show them
        contacts = campaign.contacts.all().annotate(Count("calls")).order_by('-calls__count')
        data['contacts'] = contacts

    elif 'zipcode' in request.GET:

        zipcode = request.GET['zipcode']
        request.session['cd3000_zipcode'] = zipcode

        if not ZIPCODE_RE.match(zipcode):
            return HttpResponseForbidden('invalid zipcode')

        # get bioguide_ids from cache or sunlight api
        key = "%s_ZIPCODE_%s" % (KEY_PREFIX, zipcode)
        bids = cache.get(key)
        if bids is None:
            mocs = sunlight.legislators.allForZip(zipcode)
            bids = [moc.bioguide_id for moc in mocs]
            cache.set(key, bids, TIMEOUT)

        contacts = Contact.objects.filter(campaign=campaign, bioguide_id__in=bids).annotate(Count("calls"))

        if request.is_ajax():
            # send back JSON response on ajax call
            content = json.dumps({
                'zipcode': zipcode,
                'contacts': [c.as_dict() for c in contacts],
            })
            return HttpResponse(content, mimetype='application/json')

        else:
            data['zipcode'] = zipcode
            data['contacts'] = contacts

    return render_to_response('citizendialer3000/campaign_detail.html', data,
                              context_instance=RequestContext(request))

def contact_detail(request, slug, bioguide_id):
    """ Show call script and response form for a particular contact. Response
        form values are stored in the user session so we can prepopulate
        the form on the next call.

        Context:
            campaign    - the campaign
            contact     - the contact
            form        - the response form

        Template:
            citizendialer3000/contact_detail.html
    """

    campaign = get_object_or_404(Campaign, slug=slug)

    if campaign.is_complete:
        return HttpResponseRedirect(reverse('callcampaign_detail', args=[slug]))
    elif not campaign.is_public:
        return HttpResponseRedirect(reverse('callcampaign_list'))

    contact = get_object_or_404(Contact, campaign=campaign, bioguide_id=bioguide_id)

    if request.method == 'POST':

        call = Call(contact=contact)
        form = CallForm(request.POST, instance=call)

        request.session.set_expiry(0)
        request.session['cd3000_firstname'] = request.POST.get('caller_first_name', None)
        request.session['cd3000_lastname'] = request.POST.get('caller_last_name', None)
        request.session['cd3000_email'] = request.POST.get('caller_email', None)

        if form.is_valid():

            form.save()

            # add list of called to session
            session_key = "%s.called" % campaign.slug
            called = request.session.get(session_key, [])
            called.append(contact.bioguide_id)
            request.session[session_key] = called

            return HttpResponseRedirect(reverse('call_complete', args=[slug]))

        else:
            #### generate error message from form errors?
            messages.error(request, 'Whoops, something went wrong.')

    else:
        form = CallForm(initial={
            'position': contact.position,
            'caller_first_name': request.session.get('cd3000_firstname', None),
            'caller_last_name': request.session.get('cd3000_lastname', None),
            'caller_email': request.session.get('cd3000_email', None),
            'caller_zipcode': request.session.get('cd3000_zipcode', None),
        })

    data = {
        'campaign': campaign,
        'contact': contact,
        'form': form,
    }

    return render_to_response('citizendialer3000/contact_detail.html', data,
                              context_instance=RequestContext(request))

def complete(request, slug):
    """ The "thanks" page after response form submission.

        Context:
            campaign    - the campaign
            zipcode     - the zipcode of the caller
            first_name  - the first name of the caller
            last_name   - the last name of the caller
            email       - email address of the caller

        Template:
            citizendialer3000/complete.html
    """

    data = {
        'campaign': get_object_or_404(Campaign, slug=slug),
        'zipcode': request.session.get('cd3000_zipcode', None),
        'first_name': request.session.get('cd3000_firstname', None),
        'last_name': request.session.get('cd3000_lastname', None),
        'email': request.session.get('cd3000_email', None),
    }
    return render_to_response('citizendialer3000/complete.html', data)

@login_required
def results(request, slug):
    """ A staff-only results page.

        Context:
            campaign    - the campaign
            calls       - all calls associated with the campaign

        Template:
            citizendialer3000/results.html
    """

    if not request.user.is_staff:
        return HttpResponseForbidden('You are not allowed to view this page')

    campaign = get_object_or_404(Campaign, slug=slug)
    data = {
        'campaign': campaign,
        'calls': Call.objects.filter(contact__campaign=campaign),
    }
    return render_to_response('citizendialer3000/results.html', data)

@login_required
def results_calls(request, slug):
    """ Return a CSV of calls.
    """

    if not request.user.is_staff:
        return HttpResponseForbidden('You are not allowed to view this page')

    campaign = get_object_or_404(Campaign, slug=slug)
    calls = Call.objects.filter(contact__campaign=campaign).select_related()

    data = tablib.Dataset(headers=[
        'contact','bioguide_id','position','first_name','last_name',
        'zipcode','email','notes','timestamp'])

    for call in calls:
        data.append((
            call.contact.full_name(),
            call.contact.bioguide_id,
            call.get_position_display(),
            call.caller_first_name.encode('ascii', 'replace'),
            call.caller_last_name.encode('ascii', 'replace'),
            call.caller_zipcode.encode('ascii', 'replace'),
            call.caller_email.encode('ascii', 'replace'),
            call.notes.encode('ascii', 'replace'),
            call.timestamp,
        ))

    return HttpResponse(data.csv, mimetype='text/csv')

@login_required
def results_summary(request, slug):
    """ Return a CSV of calls.
    """

    if not request.user.is_staff:
        return HttpResponseForbidden('You are not allowed to view this page')

    campaign = get_object_or_404(Campaign, slug=slug)
    contacts = campaign.contacts.all().annotate(Count("calls")).order_by('-calls__count')

    data = tablib.Dataset(headers=[
        'call_count','title','first','last','bioguide_id','state','party','phone'])

    for contact in contacts:
        data.append((
            contact.calls__count,
            contact.title,
            contact.first_name,
            contact.last_name,
            contact.bioguide_id,
            contact.state,
            contact.party,
            contact.phone,
        ))

    return HttpResponse(data.csv, mimetype='text/csv')


text:
package net.sourceforge.plantuml.eps;

public class PostScriptCommandMacro implements PostScriptCommand {

	final private String name;
	final private PostScriptData data = new PostScriptData();

	public PostScriptCommandMacro(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void add(PostScriptCommand cmd) {
		data.add(cmd);
	}

	public String toPostString() {
		return name;
	}

	public String getPostStringDefinition() {
		final StringBuilder sb = new StringBuilder();
		sb.append("/" + name + " {\n");
		sb.append(data.toPostString());
		sb.append("} def\n");
		return sb.toString();
	}

	@Override
	public int hashCode() {
		return data.toPostString().hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		final PostScriptCommandMacro other = (PostScriptCommandMacro) obj;
		return this.data.toPostString().equals(other.data.toPostString());
	}

}


text:
/* This source file is part of the Tomviz project, https://tomviz.org/.
   It is released under the 3-Clause BSD License, see "LICENSE". */

#ifndef tomvizH5ReadWrite_h
#define tomvizH5ReadWrite_h

#include <memory>
#include <string>
#include <vector>

namespace h5 {

class H5ReadWrite
{
public:
  /**
   * Enumeration of the open modes.
   */
  enum class OpenMode
  {
    ReadOnly,
    WriteOnly,
    ReadWrite
  };

  /**
   * Open an HDF5 file for reading.
   * @param fileName the file to open for reading.
   */
  explicit H5ReadWrite(const std::string& fileName,
                       OpenMode mode = OpenMode::ReadOnly);

  /** Closes the file and destroys the H5ReadWrite */
  ~H5ReadWrite();

  /** Get the currently opened file */
  std::string fileName() const;

  /** Explicitly close the file if one is open */
  void close();

  /** Copy constructor is disabled */
  H5ReadWrite(const H5ReadWrite&) = delete;

  /** Assignment operator is disabled */
  H5ReadWrite& operator=(const H5ReadWrite&) = delete;

  /** Enumeration of the data types */
  enum class DataType
  {
    Int8,
    Int16,
    Int32,
    Int64,
    UInt8,
    UInt16,
    UInt32,
    UInt64,
    Float,
    Double,
    String,
    None = -1
  };

  /** Get a string representation of the enum DataType */
  static std::string dataTypeToString(const DataType& type);

  /**
   * Get the children of a path.
   * @param ok If used, set to true on success and false on failure.
   * @return A vector of the names of the children.
   */
  std::vector<std::string> children(const std::string& path,
                                    bool* ok = nullptr);

  /**
   * Check if a given path has at least one attribute.
   * @param path The path to the attribute.
   * @return True if the path has an attribute, false if it does not,
   *         or if an error occurred.
   */
  bool hasAttribute(const std::string& path);

  /**
   * Check if a given path has an attribute with a given name.
   * @param path The path to the attribute.
   * @param name The name of the attribute.
   * @return True if the path has the attribute, false if it does not,
   *         or if an error occurred.
   */
  bool hasAttribute(const std::string& path, const std::string& name);

  /**
   * Get an attribute's type.
   * @param path The path to the attribute.
   * @param name The name of the attribute.
   * @return The datatype of the attribute, or DataType::None on failure.
   */
  DataType attributeType(const std::string& path, const std::string& name);

  /**
   * Read an attribute and interpret it as type T. If T is not
   * the correct type of the attribute, an error will occur.
   * @param path The path to the attribute.
   * @param name The name of the attribute.
   * @ok If used, set to true on success and false on failure.
   * @return The attribute.
   */
  template <typename T>
  T attribute(const std::string& path, const std::string& name,
              bool* ok = nullptr);

  /**
   * Check if a given path is a data set.
   * @return True if the path is a data set, false if it is not, or if
   *         an error occurred.
   */
  bool isDataSet(const std::string& path);

  /**
   * Check if the given path is a group.
   * @return True if the path is a group, false if it is not, or if
   *              an error occurred.
   */
  bool isGroup(const std::string& path);

  /**
   * Get the paths to all of the data sets in the file, or under a
   * specified path. Note that all soft/external links are currently
   * ignored.
   * @param path The path for which to get the data sets. Defaults
   *             to getting the paths for the whole file.
   * @return A vector of strings of the paths to the data sets.
   */
  std::vector<std::string> allDataSets(const std::string& path = "");

  /**
   * Get a data set's type. An error will occur if @p path is not a dataset.
   * @param path The path to the data set.
   * @return The datatype of the attribute, or DataType::None on failure.
   */
  DataType dataType(const std::string& path);

  /**
   * Get the number of dimensions of a data set.
   * @param path The path to the data set.
   * @return The number of dimensions, or a negative number on failure.
   */
  int dimensionCount(const std::string& path);

  /**
   * Get the dimensions of a data set.
   * @param path The path to the data set.
   * @return A vector of the dimensions, or an empty vector on failure.
   */
  std::vector<int> getDimensions(const std::string& path);

  /**
   * Read a 1-dimensional data set and interpret it as type T. If @p path
   * is not a data set, @p path is not a 1-dimensional data set, or T is
   * not the correct type of the data set, an error will occur.
   * @param path The path to the data set.
   * @return A vector of the data, or an empty vector on failure.
   */
  template <typename T>
  std::vector<T> readData(const std::string& path);

  /**
   * Read a multi-dimensional data set and interpret it as type T. If
   * @p path is not a data set, or T is not the correct type of the
   * data set, an error will occur.
   * @param path The path to the data set.
   * @param dimensions Will be set to the dimensions of the data set.
   * @return A vector of the data, or an empty vector on failure.
   */
  template <typename T>
  std::vector<T> readData(const std::string& path,
                          std::vector<int>& dimensions);

  /**
   * Read a multi-dimensional data set and interpret it as type T. If
   * @p path is not a data set, or T is not the correct type of the
   * data set, an error will occur.
   * @param path The path to the data set.
   * @param data A pointer to a block of memory with a size large enough
   *             to hold the data (size >= dim1 * dim2 * dim3...). This
   *             will be set to the data read from the data set.
   * @return True on success, false on failure.
   */
  template <typename T>
  bool readData(const std::string& path, T* data);

  /**
   * Read a multi-dimensional data set and itnerpret it as type @p type.
   * If @p path is not a data set, or @p type is not the correct type
   * of the data set, an error will occur.
   * @param path The path to the data set.
   * @param type The type of the data set.
   * @param data A pointer to a block of memory with a size large enough
   *             to hold the data (size >= dim1 * dim2 * dim3...). This
   *             will be set to the data read from the data set.
   * @param strides The strides that will be applied when reading the
   *                data. If used, ensure that the dimensions of @p data
   *                are all divided by the strides with integer division
   *                (i. e., dims[i] /= strides[i]).
   * @param start The start of the block of data to be read. If used,
   *              must have a length of ndims. If unspecified, the
   *              origin will be used.
   * @param counts The number of data elements to be read. If used,
   *               must have a length of ndims. If unspecified,
   *               as much data will be read as possible.
   * @return True on success, false on failure.
   */
  bool readData(const std::string& path, const DataType& type, void* data,
                int* strides = nullptr, size_t* start = nullptr,
                size_t* counts = nullptr);

  /**
   * Write data to a specified path.
   * @param path The path where the data will be written.
   * @param name The name of the data.
   * @param dimensions The dimensions of the data.
   * @param data The data to write.
   * @return True on success, false on failure.
   */
  template <typename T>
  bool writeData(const std::string& path, const std::string& name,
                 const std::vector<int>& dimensions,
                 const std::vector<T>& data);

  /**
   * Write data to a specified path.
   * @param path The path where the data will be written.
   * @param name The name of the data.
   * @param dimensions The dimensions of the data.
   * @param data The data to write.
   * @return True on success, false on failure.
   */
  template <typename T>
  bool writeData(const std::string& path, const std::string& name,
                 const std::vector<int>& dimensions, const T* data);

  /**
   * Write data to a specified path.
   * @param path The path where the data will be written.
   * @param name The name of the data.
   * @param dimensions The dimensions of the data.
   * @param type The type of data to write.
   * @param data The data to write.
   * @return True on success, false on failure.
   */
  bool writeData(const std::string& path, const std::string& name,
                 const std::vector<int>& dimensions, const DataType& type,
                 const void* data);

  /**
   * Set an attribute on a specified path.
   * @param path The path where the attribute will be written.
   * @param name The name of the attribute.
   * @param value The value of the attribute.
   * @return True on success, false on failure.
   */
  template <typename T>
  bool setAttribute(const std::string& path, const std::string& name, T value);

  /**
   * Create a group.
   * @param path The path to the group that will be created.
   * @return True on success, false on failure.
   */
  bool createGroup(const std::string& path);

  /**
   * Create a soft link.
   * @param target The target object that the new soft link will point to.
   * @param path The location of the new soft link.
   * @return True on success, false on failure.
   */
  bool createSoftLink(const std::string& target, const std::string& path);

  /**
   * Check if a path is a soft link.
   * @param path The path to the object that will be checked.
   * @return True if the path is a soft link, false if it is not, or
   *         if an error occurred.
   */
  bool isSoftLink(const std::string& path);

private:
  class H5ReadWriteImpl;
  std::unique_ptr<H5ReadWriteImpl> m_impl;
};

template <typename T>
bool H5ReadWrite::writeData(const std::string& path, const std::string& name,
                            const std::vector<int>& dims,
                            const std::vector<T>& data)
{
  return writeData(path, name, dims, data.data());
}

} // namespace h5

#endif // tomvizH5ReadWrite_h