text:
if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.5)
   message(FATAL_ERROR "CMake >= 2.6.0 required")
endif()
cmake_policy(PUSH)
cmake_policy(VERSION 2.6)
#----------------------------------------------------------------
# Generated CMake target import file.
#----------------------------------------------------------------

# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)

# Protect against multiple inclusion, which would fail when already imported targets are added once more.
set(_targetsDefined)
set(_targetsNotDefined)
set(_expectedTargets)
foreach(_expectedTarget bellesip)
  list(APPEND _expectedTargets ${_expectedTarget})
  if(NOT TARGET ${_expectedTarget})
    list(APPEND _targetsNotDefined ${_expectedTarget})
  endif()
  if(TARGET ${_expectedTarget})
    list(APPEND _targetsDefined ${_expectedTarget})
  endif()
endforeach()
if("${_targetsDefined}" STREQUAL "${_expectedTargets}")
  set(CMAKE_IMPORT_FILE_VERSION)
  cmake_policy(POP)
  return()
endif()
if(NOT "${_targetsDefined}" STREQUAL "")
  message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_targetsDefined}\nTargets not yet defined: ${_targetsNotDefined}\n")
endif()
unset(_targetsDefined)
unset(_targetsNotDefined)
unset(_expectedTargets)

# Compute the installation prefix relative to this file.
get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH)
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)

# Create imported target bellesip
add_library(bellesip STATIC IMPORTED)

set_target_properties(bellesip PROPERTIES
  INTERFACE_INCLUDE_DIRECTORIES "/Users/macbookpro/Documents/Tutor/Linphone/belledonn/linphone-iphone/liblinphone-sdk/x86_64-apple-darwin.ios/include"
  INTERFACE_LINK_LIBRARIES "/Users/macbookpro/Documents/Tutor/Linphone/belledonn/linphone-iphone/liblinphone-sdk/x86_64-apple-darwin.ios/lib/libantlr3c.a;pthread;dl;resolv;/Users/macbookpro/Documents/Tutor/Linphone/belledonn/linphone-iphone/liblinphone-sdk/x86_64-apple-darwin.ios/lib/libpolarssl.a"
)

if(CMAKE_VERSION VERSION_LESS 2.8.12)
  message(FATAL_ERROR "This file relies on consumers using CMake 2.8.12 or greater.")
endif()

# Load information for each installed configuration.
get_filename_component(_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
file(GLOB CONFIG_FILES "${_DIR}/BelleSIPTargets-*.cmake")
foreach(f ${CONFIG_FILES})
  include(${f})
endforeach()

# Cleanup temporary variables.
set(_IMPORT_PREFIX)

# Loop over all imported files and verify that they actually exist
foreach(target ${_IMPORT_CHECK_TARGETS} )
  foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} )
    if(NOT EXISTS "${file}" )
      message(FATAL_ERROR "The imported target \"${target}\" references the file
   \"${file}\"
but this file does not exist.  Possible reasons include:
* The file was deleted, renamed, or moved to another location.
* An install or uninstall procedure did not complete successfully.
* The installation package was faulty and contained
   \"${CMAKE_CURRENT_LIST_FILE}\"
but not all the files it references.
")
    endif()
  endforeach()
  unset(_IMPORT_CHECK_FILES_FOR_${target})
endforeach()
unset(_IMPORT_CHECK_TARGETS)

# This file does not depend on other imported targets which have
# been exported from the same project but in a separate export set.

# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)
cmake_policy(POP)


text:
define(['altair/facades/declare',
        './_Base',
        'lodash',
        'altair/Lifecycle',
        'altair/plugins/node!consolidate',
        'altair/plugins/node!ejs'
], function (declare,
             _Base,
             _,
             Lifecycle,
             consolidate,
             ejs) {

    return declare([_Base, Lifecycle], {

        startup: function () {

            return this.inherited(arguments);

        },

        canRender: function (ext) {
            return _.has(consolidate, ext);
        },

        render: function (path, context, options) {

            var dfd = new this.Deferred(),
                ext = path.split('.').pop();

            if(!consolidate[ext]) {
                dfd.reject(new Error('Could not find valid renderer for extension ' + ext + ' in consolidate. Make sure to run npm install {{render-library}}'));
                return dfd;
            }

            consolidate[ext](path, context, function (err, results) {
                if(err) {
                    dfd.reject(err);
                } else {
                    dfd.resolve(results);
                }
            });

            return dfd;

        }
    });

});

redpajama_set_name: RedPajamaGithub


text:
console.log('init broadway');

var broadway = require('broadway');
// var prettyjson = require('prettyjson');

var app = new broadway.App({
    delimiter: '.', // event name splitter
});

app.use(require('minioc-broadway'), { rootdir: __dirname });
app.use('./config');
app.use('./components');
app.use('./subdomains');
app.use('./routes');

app.init(function (err) {
    // console.log(prettyjson.render(app));
    app.log.info('init');
    if (err) {
        console.log(err);
    } else {
        setTimeout(function() { app.emit('ready'); }, 0);
    }
});

console.log('xxx:', app.minioc.get('xxx'));

// define shortcuts for accessing minioc services
['service', 'server'].forEach( function(s) {
    app.__defineGetter__(s,  function() { return app.minioc.get(s); });
} );

// TODO: find a way to automate this.
['service', 'server', 'measurement'].forEach( function(s) {
    Object.defineProperty(
        app,
        s,
        {
            get: function() { return app.minioc.get(s); },
            set: undefined,
        }
    );
});

app.on('ping', function() { app.log.info('ping received'); });

module.exports = exports = app;


text:
/*
 *  This file is part of the Heritrix web crawler (crawler.archive.org).
 *
 *  Licensed to the Internet Archive (IA) by one or more individual
 *  contributors.
 *
 *  The IA licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.archive.crawler.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.logging.Logger;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.commons.httpclient.URIException;
import org.apache.commons.io.FileUtils;
import org.archive.crawler.datamodel.UriUniqFilter;
import org.archive.modules.CrawlURI;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
import org.archive.util.TmpDirTestCase;

import com.sleepycat.je.DatabaseException;

/**
 * Test BdbUriUniqFilter.
 * @author stack
 */
public class BdbUriUniqFilterTest extends TmpDirTestCase
implements UriUniqFilter.CrawlUriReceiver {
    private Logger logger =
        Logger.getLogger(BdbUriUniqFilterTest.class.getName());

    private UriUniqFilter filter = null;
    private File bdbDir = null;

    /**
     * Set to true if we visited received.
     */
    private boolean received = false;

	protected void setUp() throws Exception {
		super.setUp();
        // Remove any bdb that already exists.
        this.bdbDir = new File(getTmpDir(), this.getClass().getName());
        if (this.bdbDir.exists()) {
        	FileUtils.deleteDirectory(bdbDir);
        }
		this.filter = new BdbUriUniqFilter(bdbDir, 50);
		this.filter.setDestination(this);
    }

	protected void tearDown() throws Exception {
		super.tearDown();
        ((BdbUriUniqFilter)this.filter).close();
        // if (this.bdbDir.exists()) {
        //    FileUtils.deleteDir(bdbDir);
        // }
	}

    public void testAdding() throws URIException {
    	this.filter.add(this.getUri(),
            new CrawlURI(UURIFactory.getInstance(this.getUri())));
        this.filter.addNow(this.getUri(),
            new CrawlURI(UURIFactory.getInstance(this.getUri())));
        this.filter.addForce(this.getUri(),
            new CrawlURI(UURIFactory.getInstance(this.getUri())));
        // Should only have add 'this' once.
        assertTrue("Count is off", this.filter.count() == 1);
    }

    public void testCreateKey() {
        String url = "dns:archive.org";
        long fingerprint = BdbUriUniqFilter.createKey(url);
        assertTrue("Fingerprint wrong " + url,
            fingerprint == 8812917769287344085L);
        url = "http://archive.org/index.html";
        fingerprint = BdbUriUniqFilter.createKey(url);
        assertTrue("Fingerprint wrong " + url,
            fingerprint == 6613237167064754714L);
    }

    /**
     * Verify that two URIs which gave colliding hashes, when previously
     * the last 40bits of the composite did not sufficiently vary with certain
     * inputs, no longer collide.
     */
    public void testCreateKeyCollisions() {
        HashSet<Long> fingerprints = new HashSet<Long>();
        fingerprints.add(new Long(BdbUriUniqFilter
                .createKey("dns:mail.daps.dla.mil")));
        fingerprints.add(new Long(BdbUriUniqFilter
                .createKey("dns:militaryreview.army.mil")));
        assertEquals("colliding fingerprints",2,fingerprints.size());
    }

    /**
     * Time import of recovery log.
     * REMOVE
     * @throws IOException
     * @throws DatabaseException
     */
    public void testWriting()
    throws IOException, DatabaseException {
        long maxcount = 1000;
        // Look for a system property to override default max count.
        String key = this.getClass().getName() + ".maxcount";
        String maxcountStr = System.getProperty(key);
        logger.info("Looking for override system property " + key);
        if (maxcountStr != null && maxcountStr.length() > 0) {
        	maxcount = Long.parseLong(maxcountStr);
        }
        runTestWriting(maxcount);
    }

    protected void runTestWriting(long max)
    throws DatabaseException, URIException {
        long start = System.currentTimeMillis();
        ArrayList<UURI> list = new ArrayList<UURI>(1000);
        int count = 0;
        for (; count < max; count++) {
            UURI u = UURIFactory.getInstance("http://www" +
                count + ".archive.org/" + count + "/index.html");
            this.filter.add(u.toString(), new CrawlURI(u));
            if (count > 0 && ((count % 100) == 0)) {
                list.add(u);
            }
            if (count > 0 && ((count % 100000) == 0)) {
                this.logger.info("Added " + count + " in " +
                    (System.currentTimeMillis() - start) +
                    " misses " +
                    ((BdbUriUniqFilter)this.filter).getCacheMisses() +
                    " diff of misses " +
                    ((BdbUriUniqFilter)this.filter).getLastCacheMissDiff());
            }
        }
        this.logger.info("Added " + count + " in " +
            (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        for (Iterator<UURI> i = list.iterator(); i.hasNext();) {
            UURI uuri = i.next();
            this.filter.add(uuri.toString(), new CrawlURI(uuri));
        }
        this.logger.info("Added random " + list.size() + " in " +
                (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        for (Iterator<UURI> i = list.iterator(); i.hasNext();) {
            UURI uuri = i.next();
            this.filter.add(uuri.toString(), new CrawlURI(uuri));
        }
        this.logger.info("Deleted random " + list.size() + " in " +
            (System.currentTimeMillis() - start));
        // Looks like delete doesn't work.
        assertTrue("Count is off: " + this.filter.count(),
            this.filter.count() == max);
    }

    public void testNote() {
    	this.filter.note(this.getUri());
        assertFalse("Receiver was called", this.received);
    }

    public void testForgetOnEmpty() throws URIException {
        this.filter.forget(this.getUri(),
            new CrawlURI(UURIFactory.getInstance(getUri())));
        assertEquals("Didn't forget", 0, this.filter.count());
    }

    // TODO: Add testForget when non-empty

	public void receive(CrawlURI item) {
		this.received = true;
	}

	public String getUri() {
		return "http://www.archive.org";
	}

    /**
     * return the suite of tests for MemQueueTest
     *
     * @return the suite of test
     */
    public static Test suite() {
        return new TestSuite(BdbUriUniqFilterTest.class);
    }

    public static void main(String[] args) {
    	junit.textui.TestRunner.run(suite());
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.elsol.user.cheerup">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/todak"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/MyMaterialTheme">
        <activity
            android:name="com.elsol.user.cheerup.Activity.MainActivity"
            android:label=""
            android:theme="@style/MyMaterialTheme" />
        <activity android:name="com.elsol.user.cheerup.Activity.LoginActivity" />
        <activity android:name="com.elsol.user.cheerup.Activity.JoinMemberActivity" />
        <activity android:name="com.elsol.user.cheerup.Activity.TutorialActivity" />
        <activity android:name="com.elsol.user.cheerup.Activity.LoadingActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.elsol.user.cheerup.Activity.CardDetail_Activity" />
    </application>

</manifest>


text:
import App from "../app";
import {pubsub} from "../helpers/subscriptionManager";
import * as Classes from "../classes";
import uuid from "uuid";

App.on("addTask", ({taskInput, simulatorId, cb}) => {
  let simId = taskInput.simulatorId || simulatorId;
  const input = {...taskInput, simulatorId: simId};
  const task = new Classes.Task({...input, id: null});
  App.tasks.push(task);
  cb && cb(task.id);
  // Execute the pre-macros
  taskInput.preMacros &&
    taskInput.preMacros.length > 0 &&
    App.handleEvent(
      {simulatorId: task.simulatorId, macros: taskInput.preMacros},
      "triggerMacros",
    );

  pubsub.publish("notify", {
    id: uuid.v4(),
    simulatorId: task.simulatorId,
    type: "Tasks",
    station: task.station,
    title: `New Task`,
    body: `${task.values.name || task.definition}`,
    color: "info",
    relevantCards: ["Tasks", "tasks"],
  });
  pubsub.publish("widgetNotify", {
    widget: "tasks",
    simulatorId: task.simulatorId,
    station: task.station,
  });
  pubsub.publish(
    "tasksUpdate",
    App.tasks.filter(s => s.simulatorId === task.simulatorId),
  );
});

App.on("verifyTask", ({taskId, dismiss}) => {
  const task = App.tasks.find(t => t.id === taskId);
  if (task) {
    task.verify(dismiss);

    let publish = false;
    // Find any task reports that have assigned this task
    App.taskReports.forEach(t =>
      t.tasks.forEach(reportTask => {
        if (reportTask.assigned === taskId) {
          reportTask.verify();
          publish = true;
        }
      }),
    );
    if (publish) {
      pubsub.publish("taskReportUpdate", App.taskReports);
    }
    pubsub.publish(
      "tasksUpdate",
      App.tasks.filter(s => s.simulatorId === task.simulatorId),
    );
  }
});

App.on("dismissVerifiedTasks", ({simulatorId}) => {
  const tasks = App.tasks.filter(t => t.simulatorId === simulatorId);
  if (tasks.length > 0) {
    tasks.forEach(t => {
      if (t.verified) t.dismiss();
    });
    pubsub.publish("tasksUpdate", tasks);
  }
});

App.on("requestTaskVerify", ({id}) => {
  const task = App.tasks.find(t => t.id === id);
  task.requestVerify();
  pubsub.publish(
    "tasksUpdate",
    App.tasks.filter(s => s.simulatorId === task.simulatorId),
  );
  pubsub.publish("notify", {
    id: uuid.v4(),
    simulatorId: task.simulatorId,
    type: "Tasks",
    station: "Core",
    title: `Task Verification`,
    body: `${task.station} - ${task.values.name || task.definition}`,
    color: "info",
  });
  App.handleEvent(
    {
      simulatorId: task.simulatorId,
      component: "TasksCore",
      title: `Task Verification`,
      body: `${task.station} - ${task.values.name || task.definition}`,
      color: "info",
    },
    "addCoreFeed",
  );
});

App.on("denyTaskVerify", ({id}) => {
  const task = App.tasks.find(t => t.id === id);
  task.denyVerify();
  pubsub.publish(
    "tasksUpdate",
    App.tasks.filter(s => s.simulatorId === task.simulatorId),
  );
  pubsub.publish("notify", {
    id: uuid.v4(),
    simulatorId: task.simulatorId,
    type: "Tasks",
    station: task.station,
    title: `Task Verification Failed`,
    body: task.values.name || task.definition,
    color: "warning",
    relevantCards: ["Tasks", "tasks"],
  });
});

App.on("addTaskTemplate", ({id = uuid.v4(), definition, cb}) => {
  App.taskTemplates.push(new Classes.TaskTemplate({id, definition}));
  pubsub.publish("taskTemplatesUpdate", App.taskTemplates);
  cb(id);
});

App.on("removeTaskTemplate", ({id}) => {
  App.taskTemplates = App.taskTemplates.filter(t => t.id !== id);
  pubsub.publish("taskTemplatesUpdate", App.taskTemplates);
});

App.on("renameTaskTemplate", ({id, name}) => {
  const task = App.taskTemplates.find(t => t.id === id);
  task && task.rename(name);
  pubsub.publish("taskTemplatesUpdate", App.taskTemplates);
});

App.on("setTaskTemplateValues", ({id, values}) => {
  const task = App.taskTemplates.find(t => t.id === id);
  task && task.setValues(values);
  pubsub.publish("taskTemplatesUpdate", App.taskTemplates);
});

App.on("setTaskTemplateReportTypes", ({id, reportTypes}) => {
  const task = App.taskTemplates.find(t => t.id === id);
  task && task.setReportTypes(reportTypes);
  pubsub.publish("taskTemplatesUpdate", App.taskTemplates);
});

App.on("setTaskTemplateMacros", ({id, macros}) => {
  const task = App.taskTemplates.find(t => t.id === id);
  task && task.setMacros(macros);
  pubsub.publish("taskTemplatesUpdate", App.taskTemplates);
});
App.on("setTaskTemplatePreMacros", ({id, macros}) => {
  const task = App.taskTemplates.find(t => t.id === id);
  task && task.setPreMacros(macros);
  pubsub.publish("taskTemplatesUpdate", App.taskTemplates);
});


text:
#include "safeclib_private.h"
#include "safe_mem_constraint.h"
#include "safe_mem_lib.h"

/**
 * NAME
 *    memcmp16_s
 *
 * SYNOPSIS
 *    #include "safe_mem_lib.h"
 *    errno_t
 *    memcmp16_s(const uint16_t *dest, rsize_t dmax,
 *               const uint16_t *src,  rsize_t smax, int *diff)
 *
 * DESCRIPTION
 *    Compares memory until they differ, and their difference is
 *    returned in diff.  If the block of memory is the same, diff=0.
 *
 * EXTENSION TO
 *    ISO/IEC JTC1 SC22 WG14 N1172, Programming languages, environments
 *    and system software interfaces, Extensions to the C Library,
 *    Part I: Bounds-checking interfaces
 *
 *  INPUT PARAMETERS
 *    dest      pointer to memory to compare against
 *
 *    dmax      maximum length of dest, in uint16_t
 *
 *    src       pointer to the source memory to compare with dest
 *
 *    smax      maximum length of src, in uint16_t
 *
 *    *diff     pointer to the diff which is an integer greater
 *              than, equal to or less than zero according to
 *              whether the object pointed to by dest is
 *              greater than, equal to or less than the object
 *              pointed to by src.
 *
 *  OUTPUT PARAMETERS
 *    none
 *
 * RUNTIME CONSTRAINTS
 *    Neither dest nor src shall be a null pointer.
 *    Neither dmax nor smax shall be zero.
 *    dmax shall not be greater than RSIZE_MAX_MEM.
 *    smax shall not be greater than dmax.
 *
 * RETURN VALUE
 *    EOK        successful operation
 *    ESNULLP    NULL pointer
 *    ESZEROL    zero length
 *    ESLEMAX    length exceeds max limit
 *
 * ALSO SEE
 *    memcmp_s(), memcmp32_s()
 *
 */
errno_t
memcmp16_s (const uint16_t *dest, rsize_t dmax,
            const uint16_t *src,  rsize_t smax, int *diff)
{

    const uint16_t *dp;
    const uint16_t *sp;

    dp = dest;
    sp = src;

    /*
     * must be able to return the diff
     */
    if (diff == NULL) {
        invoke_safe_mem_constraint_handler("memcmp16_s: diff is null",
                   NULL, ESNULLP);
        return (RCNEGATE(ESNULLP));
    }
    *diff = -1;  /* default diff */

    if (dp == NULL) {
        invoke_safe_mem_constraint_handler("memcmp16_s: dest is null",
                   NULL, ESNULLP);
        return (RCNEGATE(ESNULLP));
    }

    if (sp == NULL) {
        invoke_safe_mem_constraint_handler("memcmp16_s: src is null",
                   NULL, ESNULLP);
        return (RCNEGATE(ESNULLP));
    }

    if (dmax == 0) {
        invoke_safe_mem_constraint_handler("memcmp16_s: dmax is 0",
                   NULL, ESZEROL);
        return (RCNEGATE(ESZEROL));
    }

    if (dmax > RSIZE_MAX_MEM16) {
        invoke_safe_mem_constraint_handler("memcmp16_s: dmax exceeds max",
                   NULL, ESLEMAX);
        return (RCNEGATE(ESLEMAX));
    }

    if (smax == 0) {
        invoke_safe_mem_constraint_handler("memcmp16_s: smax is 0",
                   NULL, ESZEROL);
        return (RCNEGATE(ESZEROL));
    }

    if (smax > dmax) {
       invoke_safe_mem_constraint_handler("memcmp16_s: smax exceeds dmax",
                  NULL, ESLEMAX);
       return (RCNEGATE(ESLEMAX));
    }

    /*
     * no need to compare the same memory
     */
    if (dp == sp) {
        *diff = 0;
        return (RCNEGATE(EOK));
    }

    /*
     * now compare sp to dp
     */
    *diff = 0;
    while (dmax != 0 && smax != 0) {
        if (*dp != *sp) {
            *diff = *dp - *sp;
            break;
        }

        dmax--;
        smax--;

        dp++;
        sp++;
    }

    return (RCNEGATE(EOK));
}
EXPORT_SYMBOL(memcmp16_s);


text:
package com.furnaghan.home.component.clock.system;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.furnaghan.home.component.Configuration;
import io.dropwizard.util.Duration;

import javax.validation.constraints.NotNull;

public class SystemClockConfiguration implements Configuration {

    @NotNull
    @JsonProperty
    private Duration frequency = Duration.seconds(1);

    public Duration getFrequency() {
        return frequency;
    }
}


text:
$moduleName = 'Lability';
$repoRoot = (Resolve-Path "$PSScriptRoot\..\..\..\..").Path;
Import-Module (Join-Path -Path $RepoRoot -ChildPath "$moduleName.psm1") -Force;

Describe 'Src\Private\Assert-BitLockerFDV' {

    InModuleScope $moduleName {

        Mock Set-ItemProperty { }

        It "Calls 'Set-ItemProperty' when BitLocker is enabled on the system" {
            $fdvDenyWriteAccess = $true;
            Assert-BitLockerFDV;

            Assert-MockCalled Set-ItemProperty -Scope It -Times 1
        }

        It "It does not call 'Set-ItemProperty' when BitLocker is not enabled on the system" {
            $fdvDenyWriteAccess = $false;
            Assert-BitLockerFDV;

            Assert-MockCalled Set-ItemProperty -Scope It -Times 0
        }

    } #end InModuleScope
} #end Describe


text:
<!DOCTYPE html>

    <title>gh-1385</title>

content


text:
package org.openapitools.client.api

import argonaut._
import argonaut.EncodeJson._
import argonaut.DecodeJson._

import org.http4s.{EntityDecoder, EntityEncoder}
import org.http4s.argonaut._
import org.joda.time.DateTime

import UnlabeledLoadStatistics._

case class UnlabeledLoadStatistics (
  `class`: Option[String])

object UnlabeledLoadStatistics {
  import DateTimeCodecs._

  implicit val UnlabeledLoadStatisticsCodecJson: CodecJson[UnlabeledLoadStatistics] = CodecJson.derive[UnlabeledLoadStatistics]
  implicit val UnlabeledLoadStatisticsDecoder: EntityDecoder[UnlabeledLoadStatistics] = jsonOf[UnlabeledLoadStatistics]
  implicit val UnlabeledLoadStatisticsEncoder: EntityEncoder[UnlabeledLoadStatistics] = jsonEncoderOf[UnlabeledLoadStatistics]
}


text:
<?php

namespace RawPHP\RawGuard\Tests;

use RawPHP\RawGuard\Role;

/**
 * Role tests.
 *
 * @category  PHP
 * @package   RawPHP/RawGuard/Tests
 * @author    Tom Kaczocha <tom@rawphp.org>
 * @copyright 2014 Tom Kaczocha
 * @license   http://rawphp.org/license.txt MIT
 * @link      http://rawphp.org/
 */
class RoleTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Role
     */
    public $role;

    /**
     * Setup before each test.
     */
    public function setUp( )
    {
        parent::setUp( );

        $this->role = new Role( );
    }

    /**
     * Cleanup after each test.
     */
    public function tearDown( )
    {
        parent::tearDown( );

        $this->role = NULL;
    }

    /**
     * Test role instantiated correctly.
     */
    public function testRoleInstantiation( )
    {
        $this->assertNotNull( $this->role );
    }

    /**
     * Test initialising the role.
     *
     * @global array $config configuration array
     */
    public function testInitRole( )
    {
        global $config;

        $roles = array_values( $config[ 'roles' ] );

        $this->role->init( $roles[ 1 ] );

        $this->assertEquals( 'admin', $this->role->getName( ) );

        $caps = $this->role->getCaps( );

        $this->assertEquals( 'add_users', $caps[ 0 ] );
        $this->assertEquals( 'delete_users', $caps[ 1 ] );
    }
}


text:
package com.breezee.prj.sodexo.service;

import com.breezee.common.IServiceLayer;
import com.breezee.prj.sodexo.domain.MesshallInfo;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import java.util.List;

/**
 * Created by Silence on 2016/2/13.
 */
@Path("/messhall")
public interface IMesshallService extends IServiceLayer<MesshallInfo> {

    @Path("/list/all")
    @GET
    List<MesshallInfo> findAll();
}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>__SECTION__ | Node.js __VERSION__ Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/hljs.css">
  <link rel="canonical" href="https://nodejs.org/api/__FILENAME__.html">

          Node.js

      __GTOC__

Node.js __VERSION__ Documentation

              Index

              View on single page

              View as JSON

            __ALTDOCS__
            __EDIT_ON_GITHUB__

Table of Contents

        __TOC__

        __CONTENT__


text:
Before you can generate code coverage report by JaCoCo tool,
you need to get data about what lines of code were executed
during testing. These information are collected by JaCoCo
agent and stored in JaCoCo exec files. All you need to do
is run the tests with `jacoco` maven profile.

```
mvn test -Ptests,extra-tests,jacoco
```

## Generate JaCoCo reports

```
mvn verify -Pjacoco-generate-report -DskipTests
```

For generating JaCoCo reports only run the maven build
with profile `jacoco-generate-report` as it is shown
in the example above. After the command was executed,
in directory `target/jacoco-report` you can find
reports in HTML and XML formats.

## Merge JaCoCo exec files to one

Since ActiveMQ Artemis is divided into several modules,
exec files are generated for each module separately.
If you need to merge them together to have all data
in one place, you can do it by command below.

```
mvn jacoco:merge -N -Pjacoco
```


text:
package jodd.proxetta.data;

public @interface FooAnn {
}


text:
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var User = require('../models/user');

passport.use(new BasicStrategy(
  function (username, password, callback) {
    User.findOne({username: username}, function (err, user) {
      if (err) {
        return callback(err);
      };

      if (!user) {
        return callback(null, false);
      }

      user.verifyPassword(password, function (err, isMatch) {
        if (err) {
          return callback(err);
        };

        if (!isMatch) {
          return callback(null, false);
        }

        return callback(null, user);
      });
    });
  }
));

exports.isAuthenticated = passport.authenticate(
  'basic',
  {session: false});


text:
@implementation FindByExampleResponse

- (id) initFromDictionary:(NSDictionary *)dict{
    self = [super initFromDictionary:dict];
    if(self){
        _result = [[EntityManager sharedInstance] deserializeObject:[dict objectForKey:@"result"]]; ;
    }

    return self;
}

- (NSDictionary*) toDictionary:(BOOL)isShell{
    NSMutableDictionary* dict = [super toDictionary:NO];
    [dict setObject:[self remoteClassName] forKey:@"cn"];

    if(!isShell){
        [dict setObject:_result forKey:@"result"];
    }
    return dict;
}

- (NSString*) remoteClassName{
    return @"com.percero.agents.sync.vo.FindByExampleResponse";
}

@end


text:
package com.yahoo.ycsb.db;

import com.ceph.rados.Rados;
import com.ceph.rados.IoCTX;
import com.ceph.rados.jna.RadosObjectInfo;
import com.ceph.rados.ReadOp;
import com.ceph.rados.ReadOp.ReadResult;
import com.ceph.rados.exceptions.RadosException;

import com.yahoo.ycsb.ByteIterator;
import com.yahoo.ycsb.DB;
import com.yahoo.ycsb.DBException;
import com.yahoo.ycsb.Status;
import com.yahoo.ycsb.StringByteIterator;

import java.io.File;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;

import org.json.JSONObject;

/**
 * YCSB binding for RADOS of Ceph.
 *
 * See {@code rados/README.md} for details.
 */
public class RadosClient extends DB {

  private Rados rados;
  private IoCTX ioctx;

  public static final String CONFIG_FILE_PROPERTY = "rados.configfile";
  public static final String CONFIG_FILE_DEFAULT = "/etc/ceph/ceph.conf";
  public static final String ID_PROPERTY = "rados.id";
  public static final String ID_DEFAULT = "admin";
  public static final String POOL_PROPERTY = "rados.pool";
  public static final String POOL_DEFAULT = "data";

  private boolean isInited = false;

  public void init() throws DBException {
    Properties props = getProperties();

    String configfile = props.getProperty(CONFIG_FILE_PROPERTY);
    if (configfile == null) {
      configfile = CONFIG_FILE_DEFAULT;
    }

    String id = props.getProperty(ID_PROPERTY);
    if (id == null) {
      id = ID_DEFAULT;
    }

    String pool = props.getProperty(POOL_PROPERTY);
    if (pool == null) {
      pool = POOL_DEFAULT;
    }

    // try {
    // } catch (UnsatisfiedLinkError e) {
    //   throw new DBException("RADOS library is not loaded.");
    // }

    rados = new Rados(id);
    try {
      rados.confReadFile(new File(configfile));
      rados.connect();
      ioctx = rados.ioCtxCreate(pool);
    } catch (RadosException e) {
      throw new DBException(e.getMessage() + ": " + e.getReturnValue());
    }

    isInited = true;
  }

  public void cleanup() throws DBException {
    if (isInited) {
      rados.shutDown();
      rados.ioCtxDestroy(ioctx);
      isInited = false;
    }
  }

  @Override
  public Status read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
    byte[] buffer;

    try {
      RadosObjectInfo info = ioctx.stat(key);
      buffer = new byte[(int)info.getSize()];

      ReadOp rop = ioctx.readOpCreate();
      ReadResult readResult = rop.queueRead(0, info.getSize());
      // TODO: more size than byte length possible;
      // rop.operate(key, Rados.OPERATION_NOFLAG); // for rados-java 0.3.0
      rop.operate(key, 0);
      // readResult.raiseExceptionOnError("Error ReadOP(%d)", readResult.getRVal()); // for rados-java 0.3.0
      if (readResult.getRVal() < 0) {
        throw new RadosException("Error ReadOP", readResult.getRVal());
      }
      if (info.getSize() != readResult.getBytesRead()) {
        return new Status("ERROR", "Error the object size read");
      }
      readResult.getBuffer().get(buffer);
    } catch (RadosException e) {
      return new Status("ERROR-" + e.getReturnValue(), e.getMessage());
    }

    JSONObject json = new JSONObject(new String(buffer, java.nio.charset.StandardCharsets.UTF_8));
    Set<String> fieldsToReturn = (fields == null ? json.keySet() : fields);

    for (String name : fieldsToReturn) {
      result.put(name, new StringByteIterator(json.getString(name)));
    }

    return result.isEmpty() ? Status.ERROR : Status.OK;
  }

  @Override
  public Status insert(String table, String key, HashMap<String, ByteIterator> values) {
    JSONObject json = new JSONObject();
    for (final Entry<String, ByteIterator> e : values.entrySet()) {
      json.put(e.getKey(), e.getValue().toString());
    }

    try {
      ioctx.write(key, json.toString());
    } catch (RadosException e) {
      return new Status("ERROR-" + e.getReturnValue(), e.getMessage());
    }
    return Status.OK;
  }

  @Override
  public Status delete(String table, String key) {
    try {
      ioctx.remove(key);
    } catch (RadosException e) {
      return new Status("ERROR-" + e.getReturnValue(), e.getMessage());
    }
    return Status.OK;
  }

  @Override
  public Status update(String table, String key, HashMap<String, ByteIterator> values) {
    Status rtn = delete(table, key);
    if (rtn.equals(Status.OK)) {
      return insert(table, key, values);
    }
    return rtn;
  }

  @Override
  public Status scan(String table, String startkey, int recordcount, Set<String> fields,
      Vector<HashMap<String, ByteIterator>> result) {
    return Status.NOT_IMPLEMENTED;
  }
}


text:
title: Decision Theory and Software Design
date: 12:23 03/16/2021
highlight:
    theme: monokai
taxonomy:
    category: blog
    tag: [decision theory, heurisics, software design]
---

For a discipline supposedly rooted in rationale and logic, it's surprising there isn't a greater emphasis placed on decision theory. All too often, critical decisions are led by heuristics rather than formal methods.

![butterfly](butterfly.svg)

===

### Background

Recently I'd been working on a software project that had made an idiosyncratic choice in terms of the domain language. It wasn't apparent to me why the choice had been made in favour of this language, given its applicability to the problem context felt aberrant at best.

From an outsider's perspective, there were evidently more appropriate choices that could've been made in retrospect, so it perplexed me as to how this foregone decision had been made in the first place. It led me to consider the decision process that cultivated this sub-optimal outcome.

My intention isn't in admonishing poor design choices, but rather to better understand the factors that influence said choices. It goes without saying that fundamental decisions on language or architecture are critical to the overall success of a project.

Hence, it's equally important in recognising the merits of optimal decision-making. This naturally drew me into the field of Decision Theory, and how I might best learn to make informed software decisions myself.

### Extinction by Instinct

My initial suspicions were consequent on working with the language directly. The more I dove into the project, the better I understood its impracticality. That's not to say the language is intrinsically "flawed", rather it's ill-suited to the task at hand. The longer I spent hacking away, bending it to work, the more I felt I was trying to "fit a square peg into a round hole".

Likewise too, the better I understood the domain, the better I could reason why other programming languages were more widely popular in this context. Giving into speculation, why had this esoteric choice been made?

The answer I learnt was plainly,

> _It's the language that's always been used_

On face value, this is a sensible decision. Everyone is competent in this language and every other internal project has been completed in this language too. What's more, the language is supported in this new domain so it should be easy to reuse familiar tools and patterns.

And indeed, things do work. Just. Not optimally, but just well enough that the difficulty in doing so can be justified. Therein lies the difference between two styles of decision-making; satisficing vs maximising.

The choice of language was a satisficing decision, rooted in reaching a pragmatic solution that had the consensus of the team. Rather than exerting effort in evaluating the wider unknowns of the problem domain to formulate an informed if not, idealised decision.

### Prevalence of Heuristics in Software Development

This no-frills decision-making strategy evokes the mantra of _"move fast and break things"_.

In fact, by and large, the software industry revolves around this hypothesis. Agile sprints, rapid iteration, minimal viable products .etc. The jargon practically promotes satisficing with every sip of the kool-aid.

Paradoxically then, this mindset is grounded moreso in intuition than reason or logic. So why the dichotomy?

I think this can be explained by our own innate dispositions. As with any decision, it's human behaviour to seek the most convenient conclusion by the principle of least effort (i.e. _"path of least resistance"_). Moreover, most decisions in day-to-day life are also inconsequential, hence it's only economical to lean on heuristics. However, in our routine, this can become habitual - sometimes to our detriment.

This is evidenced most acutely by the complex decisions that must be concluded in software design. In these circumstances, our rationality is in fact, _bounded_. Our time, cognitive capacity and autonomy are limited. These constraints exert pressures on our ability to _maximise_ our decisions. It follows then, that we seek to compromise with a bias for our own utility.

Unfortunately, software doesn't forget, and it never forgives. A compromised start inevitably leads to a compromised end. Hence why perfect software doesn't exist, it's simply infeasible to develop perfect software based on pure rational decisions in the real world.

### Recognising Heuristics in Decision Processing

With that doom and gloom summarily described, is it worth simply conceding to heuristic-based decision processing?

I could never acquisce to that approach. Anecdotally, it's always been my experience that software entrophy begets software entrophy. Sometimes dubbed "software rot" or rather benignly "technical debt", in any case it only propagates decay. David Thomas, in his book, "The Pragmatic Programmer" applies the analogy of the [Broken Window Theory](https://en.wikipedia.org/wiki/Broken_windows_theory#:~:text=The%20broken%20windows%20theory%20is,and%20disorder%2C%20including%20serious%20crimes.) to illustrate the effects entrophy can have on a project,

> _"Don't leave "broken windows" (bad designs, wrong decisions, or poor code) unrepaired. Fix each one as soon as it is discovered. If there is insufficient time to fix it properly, then board it up. Perhaps you can comment out the data instead. Take some action to prevent further damage and to show that you're on top of the situation"_

> _"We've seen clean, functional systems deteriorate pretty quickly once windows start breaking. There are other factors that can contribute to software rot [...] but neglect accelerates the rot faster than any other factor"_

> _"One broken window - a badly designed piece of code, a poor management decision that the team must live with for the duration of the project - is all it takes to start the decline"_

His advice is prescriptive. Do not tolerate broken windows, and to highlight his words verbatim, _"bad designs"_ and _"wrong decisions"_. Whilst these are sound words, it doesn't afford any insight as to how to mitigate the likelihood of broken windows occurring from the onset.

This leaves us with an uncomfortable catch-22 of sorts. If it's indeed impossible to make utterly rational decisions, and heuristics are a crutch, how can we write good software?

First and foremost, the easiest means of minimising poor decisions is a self-awareness of our own cognitive biases. Biases aren't inherently "bad" but rather, they can lead us astray towards inferior outcomes. Returning to my opening remarks about the choice of programming language being maladaptive, it's obvious that there are heuristics at play.

The observation on the pervasive use of the language for every contingency strongly suggests an ingrained sense of "status quo bias". This "anchoring" around the language sustains a self-reinforcing feedback loop, that only affirms the established norm.

This central tenet engenders other adverse cognitive biases that only serve to augment the dominant thought, rather than negate it.

#### Information Cascade

An information cascade can explain the adoption of the familiar language over other (more optimal) alternatives. In simple terms, it occurs when we, as individuals, decide to select the _same_ choices as made by others prior. In lieu of our own independent decision, we instead place our favour in the inference of our peers' actions.

This desire for conformity can _cascade_ poor choices, as everyone jumps on the same bandwagon so to speak. This groupthink entrenches the decision, as the desire for consensus outweighs critical evaluation. Usually the outcome of which drifts towards a more moderate option. This in turn, is a manifestation of the _"Compromise Effect"_ where we assume the most middling choice carries the most benefit.

This evokes the adage,

> _"nobody ever got fired for buying IBM"_

#### Escalation of Commitment

With a compromised decision established, collective attention is placed squarely on the decided choice. Moreover, there's typically little scope afforded to deliberating information that doesn't bear relevance to this choice. In fact, this common-information bias can compound attempts to dislodge a prevailing norm, despite new evidence that might arise to contradict it.

Even in scenarios where the original choice is self-evidently unfavourable, its justification is founded upon the cumulative investment thus far accrued. Irrationally, even when its future detrimental cost outweighs its expected benefit.

This _"sunk cost"_ intransigence deters new ideas from being proposed, and unfortunately only encourages _"confirmation bias"_ in seeking to substantiate what is now perceived to be a tenuous decision.

#### Establishment of Convention

When the desire for group cohesiveness takes precedence, cognitive inertia to change can embedded itself surreptitiously. From which a tendency in favour of _omission_ (inaction) over _commission_ (action) can take hold. This _"Omission Bias"_ as its termed, again reinforces the collective norm.

With convention too comes a predisposition to favour familiarity as a heuristic, of which the _"Einstellung Effect"_ is perhaps the best illustration. It describes our inclination to solve a given problem in a familiar manner, despite more appropriate methods being available.

This succinctly portrays my observations on the misguided strategy of employing a familiar language, without critical evaluation of its appropriateness to the problem domain. Furthermore, it's maladaption to the given problem is exacerbated by _"functional fixedness"_; the inhibition to adjust the use of the language in a dissimilar context.

This cognitive bias is closely related to the _"Law of the Instrument"_ or _"Maslow's Hammer"_, which similarly describes the over-reliance on a familiar tool, despite its shortcomings. To quote Maslow himself,

> _"I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail."_

### Dissenting Opinion

In the face of these ingrained biases, it can be difficult to affect change, or even at the very least, voice an opinion contrary to the norm.

No matter how high up the totem pole, our autonomy in shifting an established belief is predicated on our ability to convince others. Without endorsement, ideas cannot establish, let alone flourish.

Unfortunately, in proposing an idea in direct confrontation of an entrenched norm, there is little chance it will overcome inertia, however advantageous it may be. In scenarios such as these, it can be demoralising when ideas don't find credence.

Contrary to seeking approval by traditional consensus, oftentimes the more opportune approach is the realist one. In the words of Grace Hopper,

> _"It's easier to ask for forgiveness than it is to get permission"_

Going ahead and furtively building a prototype (i.e. trojan horse) to demonstrate an idea is a more effective strategy. Especially if it ameliorates a common group inconvenience, i.e. directly appeal to the _"Principle of Least Effort"_. With any luck it can potentially catalyse an idea and undermine faith in the norm.

### Conclusion

I hope this exploration highlighted the causality heuristics incur in software decision-making. It's nigh impossible to eliminate biases completely, much less in convincing others to recognise them in the first place. However, at least with some awareness it may be possible to assuage their impact.

That said, even after thoroughly considering my own arguments, it's difficult not to have a sense of fatalism. No matter how ardent we are to espouse the virtues of making informed decisions, it always comes across self-satisfying.

> The road to hell is paved with good intentions

Business priorities, feature creep, tight deadlines can quickly undue any sincere efforts towards this aim.

I feel as though I'm touching upon Martin Fowler's comments in his article, [Is High Quality Software Worth the Cost?](https://martinfowler.com/articles/is-quality-worth-cost.html) He approaches a similar argument from a different perspective than mine; namely, the "trade-off between software quality and cost".

He broadly claims that there should be a greater emphasis placed on maintaining and enhancing internal quality of software, despite extra effort or imposition that may cause in the short-term. His reasons for this are sound. Whilst initial progress may be slighter, it profoundly reduces the cost of future change.

I agree with his sentiment, and I would also expand upon it with my own remarks on involving a decision-making strategy,

> Producing quality decisions _produces_ quality software

Finally, as to him, I feel as though I'm concluding on the same point. Despite having a valid justification for formal decision-making approaches and creating high quality software, it's a struggle convincing others to the same end.


text:
define({
  "serviceUrl": "Setare URL serviciu:",
  "minIntSpacingLabel": "Dimensiune minimă grilă",
  "lineOpacityLabel": "Opacitate linie",
  "labelOpacityLabel": "Opacitate etichetă",
  "centerLabelOpacityLabel": "Opacitate etichetă centrală",
  "gridZonePlacementLabel": "Plasare etichetă pentru zona grilă",
  "verticalLineLabels": "Etichete linii verticale",
  "styleHeaderLabel": "Stil",
  "indexHeaderLabel": "Componenta grilei",
  "colorHeaderLabel": "Culoare",
  "fontSizeHeaderLabel": "Dimensiune font",
  "lineWidthHeaderLabel": "Grosime linie",
  "horizontalLabel": "Orizontal",
  "verticalLabel": "Vertical",
  "upperLeftLabel": "Stânga sus",
  "upperRightLabel": "Dreapta sus",
  "lowerLeftLabel": "Stânga jos",
  "lowerRightLabel": "Dreapta jos",
  "centerLabel": "Centru",
  "errorMessage": "Pagina de configurare conține erori. Corectați înainte de salvare.",
  "checkBoxLabel": "Afișare caroiaj dacă widget-ul este închis",
  "checkBoxLabelDashboard": "Grilă de afișare",
  "gzd": "Indicator de zonă a grilei (GZD)",
  "gsid": "Identificarea pătratului de grilă de 100.000 metri (GSID)",
  "grid10k": "Linii de grilă de 10.000 metri",
  "grid1k": "Linii de grilă de 1.000 metri",
  "grid100m": "Linii de grilă de 100 metri",
  "grid10m": "Linii de grilă de 10 metri",
  "switchBasemap": "Schimbare hartă fundal"
});


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

<title>main.habitivity.activities</title>
<meta name="date" content="2017-12-04">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package main.habitivity.activities

Class Summary

Class
Description

AddEvent

TODO MOVE LOCATION HANDLING INTO ANOTHER CLASS

AddHabitActivity

BaseActivity

BaseActivity exposes the HabitApplication class which can be
 used to resolve dependencies

EditHabit

EventDetailsNonEditable

FindFriendsActivity

Followers

Following

FollowRequest

HabitApplication

This class exposes dependencies to the rest of the system.

HabitEventDetailsActivity

HabitHistoryActivity

HabitivityMain

HabitListActivity

JustHabitDetails

LoginUser

MapsActivity

An activity that displays a map showing the place at the device's current location.

RequestList

SplashScreen

TodaysHabits

This activity displays the habits scheduled for the current day

UserInformationActivity

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
PHP
===

Overview
--------

The ObjectRocket API is a REST based HTTP API. The API can be used in
addition to and along side the MongoDB driver to access an
ObjectRocket instance. The API expects a HTTP POST with a document
and an API key. The document can be the document to write to the
database, or it can be a query object in the form of the query's
predicate. JSON and HTTP toolkits are needed to work with
ObjectRocket easily. The following PHP examples are written in PHP
5.3.5 using Eclipse and the examples use the built in json_encode and
json_decode JSON methods and the built in curl toolkit.

The following is a PHP 5.3.5 example that performs an ObjectRocket
API call and display the results of the call. The API operations on
the rest of this page will be slimmed down snippets that assume the
rest of the following example's code is in place.

.. code-block:: php

   try{
   // The name of your database.
   $db="mydb0";
   // The name of your collection or table.
   $collection="mycol0";
   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/db/".$db."/collection/".$collection."/add";
   // Print the URL.
   print_r("URL: \n".$url."\n\n");
   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";
   // Define the document parameter.
   $document = json_encode(array("first_name" => "Chuck"));
       // Print the json encoded document.
       print_r("Document: \n".$document."\n\n");

       // Define the HTTP POST parameters.
       $params="api_key=".$apiKey."&doc=".$document;

       // Print the HTTP POSt parameters.
       print_r("HTTP POST parameters: \n".$params."\n\n");

       // Initialize curl.
       $ch = curl_init( $url );

       // Configure curl options.
           $options = array(
               CURLOPT_RETURNTRANSFER => true,
               CURLOPT_POST => 1,
               CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
               CURLOPT_POSTFIELDS => $params
           );

           // Set curl options.
           curl_setopt_array( $ch, $options );

           // Execute the post and get results.
           $result = curl_exec($ch);

           // Close curl.
           curl_close($ch);

           // Print the result string.
           print_r("Post result: \n".$result."\n\n");

           // Decode string response into an object.
           $jsonResult = json_decode($result);

           // Print various properties of the returned object.
           print_r("Return code: \n".$jsonResult->rc."\n\n");

           print_r("First_name: \n".$jsonResult->data->first_name."\n\n");

           print_r("OID: \n".$jsonResult->data->_id->{'$oid'});

       } catch (Exception $e){
           print_r("Exception caught: \n".$e);

       }

The following is the console output of the above example::

   URL:
   https://api.objectrocket.com/db/mydb0/collection/mycol0/add

   Document:
   {"first_name":"Chuck"}

   HTTP POST parameters:
   api_key=abcd1234&doc={"first_name":"Chuck"}

   Post result:
   {
       "data": {
           "first_name": "Chuck",
           "_id": {
               "$oid": "50a9715b5b33522297000002"
           }
       },
       "rc": 0
   }

   Return code:
   0

   First_name:
   Chuck

   OID:
   50a9715b5b33522297000002

The API returns a JSON formatted string with a return code and the
data requested or if the operation fails, a JSON formatted string
with a return code and a message detailing the cause of the failure.
The following is an example return of a successful call:

.. code-block:: json

   {
       rc: 0,
       data: data_payload
   }

In the case of an error the format is:

.. code-block:: json

   {
       rc: 1,
       msg: returned_message
   }

MongoDB Document Manipulation and Retrieval Operations
------------------------------------------------------

ADD
^^^

The Add API operation inserts a document into the given collection
(COLLECTION_NAME) in the given database (DB_NAME). If the insert is
successful, the object is returned with a primary key (_id). The add
api operation is analogous to the save MongoDB method. The following
are details about the Add API operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.
:DOCUMENT: - The JSON document that you are adding to the given collection.
:DB_NAME: - The name of the database that contains the collection that you are inserting the document into.
:COLLECTION_NAME: - The name of the collection or table that you are inserting the document into.

POST URL::

   https://api.objectrocket.com/db/DB_NAME/collection/COLLECTION_NAME/add

POST Parameter::

   api_key=API_KEY&doc=DOCUMENT

Example
~~~~~~~
.. code-block:: php

   // The name of your database.
   $db="mydb0";

   // The name of your collection or table.
   $collection="mycol0";

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/db/".$db."/collection/".$collection."/add";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the document parameter.
   $document = json_encode(array("first_name" => "Chuck",
                                   "last_name" => "Smith",
                                   "age" => 35));

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey."&doc=".$document;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
      "data": {
        "first_name": "Chuck",
        "last_name": "Smith",
        "age": 35,
        "_id": {
          "$oid": "50876f83cb72593131000000"
        }
      },
      "rc": 0
   }

GET
^^^

The Get API operation returns a set of the document(s) that meet the
given document query (QUERY) from the given collection
(COLLECTION_NAME) in the given database (DB_NAME). The get operation
is analogous to the find MongoDB method. The following are details
about the Get API operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.
:QUERY: - A query predicate in the form of a JSON document.
:DB_NAME: - The name of the database that contains the collection that you are retrieving documents from.
:COLLECTION_NAME: - The name of the collection or table that you are retrieving documents from.

POST URL::

   https://api.objectrocket.com/db/DB_NAME/collection/COLLECTION_NAME/get

POST Parameter::

   api_key=API_KEY&doc=QUERY

Example
~~~~~~~
.. code-block:: php

   // The name of your database.
   $db="mydb0";

   // The name of your collection or table.
   $collection="mycol0";

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/db/".$db."/collection/".$collection."/get";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the document parameter.
   $document = json_encode(array("first_name" => "Chuck"));

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey."&doc=".$document;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
      "data": [
        {
          "last_name": "Smith",
          "first_name": "Chuck",
          "_id": {
            "$oid": "50876f83cb72593131000000"
          },
          "age": 35
        }
      ],
      "rc": 0
   }

Example
~~~~~~~
.. code-block:: php

   // The name of your database.
   $db="mydb0";

   // The name of your collection or table.
   $collection="mycol0";

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/db/".$db."/collection/".$collection."/get";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the document parameter.
   $document = json_encode(array("age" => array('$lt' => 40)));

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey."&doc=".$document;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
      "data": [
        {
          "last_name": "Rockefeller",
          "middle_ini": "D",
          "age": 33,
          "_id": {
            "$oid": "5087760e845eb56e8b000000"
          },
          "first_name": "John"
        },
        {
          "last_name": "Welch",
          "first_name": "Jack",
          "_id": {
            "$oid": "508776985b33524256000000"
          },
          "age": 33,
          "married": true
        }
      ],
      "rc": 0
   }

UPDATE
^^^^^^

The Update API operation will update the first document in the given
collection (COLLECTION_NAME) in the given database (DB_NAME) that
matches the given query predicate (QUERY) and set all of that
document's values to that which are specified in the set
(NEW_DOCUMENT) clause. Fields that are omitted in the set operation
will be removed from the updated document. If successful, the returned
data will specify the number of affected documents. The update api
operation is similar to the update MongoDB method, except for the fact
that the Update API operation only updates the first document that
meets the query predicate's criteria, where as the MongoDB method can
accept an optional argument that will allow the method to update
multiple documents at one time. The following are the details of the
Update API operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.
:QUERY: - A query predicate in the form of a JSON document.
:NEW_DOCUMENT: - The JSON document that will replace the first instance of the document that meets the query predicate.
:DB_NAME: - The name of the database that contains the collection that you are updating the document in.
:COLLECTION_NAME: - The name of the collection or table that you are updating the document in.

POST URL::

    https://api.objectrocket.com/db/DB_NAME/collection/COLLECTION_NAME/update

POST Parameter::

   api_key=API_KEY&doc=QUERY&set=NEW_DOCUMENT

Example
~~~~~~~
.. code-block:: php

   // The name of your database.
   $db="mydb0";

   // The name of your collection or table.
   $collection="mycol0";

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/db/".$db."/collection/".$collection."/update";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the document parameter.
   $document = json_encode(array("first_name" => "Chuck"));

   # Define the document for the set parameter.
   $setDocument = json_encode(array("first_name"=>"Cornelius",
                                       "last_name"=>
                                       "Vanderbilt","age"=>40));

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey."&doc=".$document."&set=".$setDocument;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
       "rc": 0,
       "n": 1
   }

DELETE
^^^^^^

The Delete API operation deletes all documents in the given collection
(COLLECTION_NAME) in the given database (DB_NAME) that meet the
criteria specified in the query predicate (QUERY). If successful, the
returned data specifies the number of deleted documents. The delete
api operation is analogous to the remove MongoDB method. The following
are details about the Delete API operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.
:QUERY: - A query predicate in the form of a JSON document.
:DB_NAME: - The name of the database that contains the collection that you are deleting the document from.
:COLLECTION_NAME: - The name of the collection or table that you are deleting the document from.

POST URL::

   https://api.objectrocket.com/db/DB_NAME/collection/COLLECTION_NAME/delete

POST Parameter::

   api_key=API_KEY&doc=QUERY

Example
~~~~~~~
.. code-block:: php

   // The name of your database.
   $db="mydb0";

   // The name of your collection or table.
   $collection="mycol0";

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/db/".$db."/collection/".$collection."/delete";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the document parameter.
   $document = json_encode(array("age" => array('$lt' => 40)));

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey."&doc=".$document;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
       "rc": 0,
       "n": 4
   }

MongoDB Instance Management Operations
--------------------------------------

Instance Details
^^^^^^^^^^^^^^^^

The Instance Details API operation returns details about all
ObjectRocket instances associated with the given API key (API_KEY).
The following are details about the Instance Details API operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.

POST URL::

   https://api.objectrocket.com/instance

POST Parameter::

   api_key=API_KEY

Example
~~~~~~~
.. code-block:: php

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/instance";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
       "data": {
           "name": "rocketdemo",
           "zone": "US-West",
           "host": "w-mongos0.objectrocket.com",
           "plan": 20,
           "port": 10013,
           "size": 20.0
       },
       "rc": 0
   }

Server Status
^^^^^^^^^^^^^

The Server Status API operation returns an object of type ServerStatus
showing counters for various operations for the instances of the given
API key (API_KEY). The output returned by the Server Status API
operation is required by the rocketstat utility. The following are the
details for the Server Status API Operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.

POST URL::

   https://api.objectrocket.com/serverStatus

POST Parameter::

   api_key=API_KEY

Example
~~~~~~~
.. code-block:: php

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/serverStatus";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
       "data": {
           "indexCounters": {
               "btree": {
                   "missRatio": 0.0,
                   "resets": 0,
                   "hits": 1884749,
                   "misses": 0,
                   "accesses": 1884749
               }
           },
           "connections": {
               "current": 31,
               "available": 19969
           },
           "plan": 20,
           "cursors": {
               "clientCursors_size": 2,
               "timedOut": 33,
               "totalOpen": 2
           },
           "writeBacksQueued": false,
           "globalLock": {
               "totalTime": 4522903384036.0,
               "currentQueue": {
                   "total": 0,
                   "writers": 0,
                   "readers": 0
               },
               "lockTime": 3967860394.0,
               "ratio": 0.0008772817053764459,
               "activeClients": {
                   "total": 2,
                   "writers": 0,
                   "readers": 2
               }
           },
           "backgroundFlushing": {
               "last_finished": {
                   "$date": 1350873424334
               },
               "last_ms": 1,
               "flushes": 75381,
               "average_ms": 0.9229381409108396,
               "total_ms": 69572
           },
           "opcounters": {
               "getmore": 4261495,
               "insert": 51104017,
               "update": 4015099,
               "command": 22168920,
               "query": 2669,
               "delete": 3
           },
           "uptime": 4522903.0,
           "ok": 1.0,
           "network": {
               "numRequests": 77676659,
               "bytesOut": 18977925411.0,
               "bytesIn": 6275223047.0
           },
           "zone": "US-West",
           "instance": "rocketdemo",
           "version": "2.0.6",
           "asserts": {
               "msg": 0,
               "rollovers": 0,
               "regular": 0,
               "warning": 31,
               "user": 435
           }
       },
       "rc": 0
   }

Space Usage
^^^^^^^^^^^

The Space Usage API operation returns a summary of disk space usage in
bytes for each of the ObjectRocket instances for the given API key
(API_KEY). The following are details for the Space Usage API
operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.

POST URL::

   https://api.objectrocket.com/spaceusage/get

POST Parameter::

   api_key=API_KEY

Example
~~~~~~~
.. code-block:: php

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/spaceusage/get";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
       "data": {
           "total_size": 3502428160.0,
           "index_size": 2715159664.0,
           "shards": [
               {
                   "total_size": 8734789488.0,
                   "index_size": 2715037024.0,
                   "file_size": 16283598848.0,
                   "shard": "shard_30013",
                   "data_size": 7130697772.0
               }
           ],
           "data_size": 2459198904.0,
           "file_size": 10917511168.0
       },
       "rc": 0
   }

Add Database / Add User
^^^^^^^^^^^^^^^^^^^^^^^

The Add Database API operation will create a database with the given
name (DB_NAME) and given MongoDB user credentials (USERNAME, PASSWORD)
for the given API key (API_KEY). If the database already exists, a
user can be added to the database by using this operation. The
following are details for the Add Database API operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.
:USERNAME: - The username for the account that will be granted access to the given MongoDB database.
:PASSWORD: - The password for the account that will be granted access to the given MongoDB database.
:DB_NAME: - The name of the database that will be created or if the database already exists, the name of the database that the given account will be granted access to.

POST URL::

   https://api.objectrocket.com/db/DB_NAME/add

POST Parameter::

   api_key=API_KEY&doc={"USERNAME":"PASSWORD"}

Example
~~~~~~~
.. code-block:: php

   // The name of your database.
   $db="mydb0";

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/db/".$db."/add";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the document parameter.
   $document = json_encode(array("myUser012" => "myPass012"));

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey."&doc=".$document;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
       "data": "OK",
       "rc": 0
   }

List Databases
^^^^^^^^^^^^^^

The List Databases API operation will return statistics about all
databases owned by the given API key (API_KEY). The following is the
format of a cURL HTTP POST for the List Databases API operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.

POST URL::

   https://api.objectrocket.com/db

POST Parameter::

   api_key=API_KEY

Example
~~~~~~~
.. code-block:: php

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/db";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result =  curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
       "data": [
           {
               "stats": {
                   "dataSize": 328,
                   "ok": 1.0,
                   "avgObjSize": 46.857142857142854,
                   "indexes": 1,
                   "objects": 7,
                   "fileSize": 50331648,
                   "numExtents": 4,
                   "storageSize": 1064960,
                   "indexSize": 8176
               },
               "name": "mydb"
           },
           {
               "stats": {
                   "dataSize": 448,
                   "ok": 1.0,
                   "avgObjSize": 64.0,
                   "indexes": 1,
                   "objects": 7,
                   "fileSize": 50331648,
                   "numExtents": 4,
                   "storageSize": 1069056,
                   "indexSize": 8176
               },
               "name": "mydb0"
           },
       ],
       "rc": 0
   }

Get Profiler Data
^^^^^^^^^^^^^^^^^

The Get Profiler Data API operation returns standard MongoDB profiler
output for all queries that meet the given criteria on all shards for
the given API key. The following are details for the Get Profiler Data
API operation:

Parameters
~~~~~~~~~~

:API_KEY: - Your ObjectRocket API key.
:QUERY: - A query predicate in the form of a JSON document.

POST URL::

   https://api.objectrocket.com/profiler/get

POST Parameter::

   api_key=API_KEY&doc=QUERY

Example
~~~~~~~
.. code-block:: php

   // Define the url for the HTTP POST.
   $url="https://api.objectrocket.com/profiler/get";

   // The api key of your ObjectRocket user.
   $apiKey="abcd1234";

   // Define the document parameter.
   $document = json_encode(array("millis" => array('$gt' => 50)));

   // Define the HTTP POST parameters.
   $params="api_key=".$apiKey."&doc=".$document;

   // Initialize curl.
   $ch = curl_init( $url );

   // Configure curl options.
   $options = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_POST => 1,
       CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
       CURLOPT_POSTFIELDS => $params
   );

   // Set curl options.
   curl_setopt_array( $ch, $options );

   // Execute the post and get results.
   $result = curl_exec($ch);

   // Close curl.
   curl_close($ch);

Result
~~~~~~
.. code-block:: json

   {
       "data": [
           {
               "ns": "mydb0.mycol0",
               "millis": 54,
               "ts": {
                   "$date": 1351058243597
               },
               "client": "10.48.2.30",
               "user": "",
               "query": {
                   "first_name": "Chuck"
               },
               "updateobj": {
                   "first_name": "Cornelius",
                   "last_name": "Vanderbilt"
               },
               "nscanned": 1,
               "op": "update"
           }
       ],
       "rc": 0
   }


text:
class Model;
class Mob;
class Matrix;

// Size : 108
class MobRenderer : public EntityRenderer
{
public:
	bool wtf;			// 68
	Model *mainModel;	// 72
	Model *armorModel;	// 76
	char filler1[28];	// 80

public:
	MobRenderer(Model *, float);
	virtual ~MobRenderer();
	virtual void render(Entity &, const Vec3 &, float, float);
	virtual void prepareArmor(Mob &, int, float);
	virtual void setupPosition(Entity &, const Vec3 &, Matrix &);
	virtual void setupRotations(Entity &, float, float, Matrix &, float);
	virtual void getAttackAnim(Mob &, float);
	virtual void getBob(Mob &, float);
	virtual void getFlipDegrees(Mob &);
	virtual void scale(Mob &, Matrix &, float);
	virtual void additionalRendering(Mob &, float);
	virtual void bindMobTexture(Mob &);
};


text:
from .base import DoubanAPIBase, DoubanAPIBase_v1, DEFAULT_START, DEFAULT_COUNT

class User(DoubanAPIBase):

    def __repr__(self):
        return '<DoubanAPI User>'

    def get(self, id):
        return self._get('/v2/user/%s' % id)

    @property
    def me(self):
        return self.get('~me')

    def search(self, q, start=DEFAULT_START, count=DEFAULT_COUNT):
        return self._get('/v2/user', q=q, start=start, count=count)

    def follow(self, id):
        return self._post('/shuo/v2/friendships/create', user_id=id)

    def unfollow(self, id):
        return self._post('/shuo/v2/friendships/destroy', user_id=id)

    def following(self, id, start=DEFAULT_START, count=DEFAULT_COUNT):
        page = start / count
        return self._get('/shuo/v2/users/%s/following' % id, page=page, count=count)

    def followers(self, id, start=DEFAULT_START, count=DEFAULT_COUNT):
        page = start / count
        return self._get('/shuo/v2/users/%s/followers' % id, page=page, count=count)

class User_v1(DoubanAPIBase_v1):

    def __repr__(self):
        return '<DoubanAPI User_v1>'

    def reviews(self, user_id = '', start_index = '', max_results = '', orderby = ''):
        return self._get('/people/%s/reviews?alt=json&start-index=%s&max-results=%s&orderby=%s' % (user_id, start_index, max_results, orderby))


text:
package com.opendata.common.util;

import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * 此标签生成表单提交的唯一标识,用于解决表单重复提交产生的问题。
 *
 * @author Administrator
 *
 */
public class RepeatSubmitTag extends TagSupport
{
	public static String repeatSubmitName = "_Form_RepeatSubmit_Id_";
	private String type = "hidden"; // 当类型为hidden 时,则输出一个隐藏域 当类型为param时,则直接输出 属性

	public int doStartTag()
	{
		try
		{
			Long formRepeatSubmitId = IdFactory.getId();
			HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
			request.getSession().setAttribute(repeatSubmitName, formRepeatSubmitId);
			Writer out = this.pageContext.getOut();
			if (type.equals("param"))
			{
				out.write(RepeatSubmitTag.repeatSubmitName + "=" + formRepeatSubmitId);
			} else
			{
				out.write("<input type='hidden' name='" + RepeatSubmitTag.repeatSubmitName + "' value='" + formRepeatSubmitId + "' />");
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return this.SKIP_BODY;
	}

	public String getType()
	{
		return type;
	}

	public void setType(String type)
	{
		this.type = type;
	}

}


text:
@implementation CCPShellRunner

+ (void)runShellCommand:(NSString*)command withArgs:(NSArray*)args directory:(NSString*)directory completion:(void (^)(NSTask* t))completion
{
    static NSOperationQueue* operationQueue;
    if (operationQueue == nil) {
        operationQueue = [NSOperationQueue new];
    }

    NSTask* task = [NSTask new];

    NSMutableDictionary* environment = [[[NSProcessInfo processInfo] environment] mutableCopy];
    environment[@"LC_ALL"] = @"en_US.UTF-8";
    [task setEnvironment:environment];

    task.currentDirectoryPath = directory;
    task.launchPath = command;
    task.arguments = args;

    CCPRunOperation* operation = [[CCPRunOperation alloc] initWithTask:task];
    operation.completionBlock = ^{
        if (completion)
            completion(task);
    };
    [operationQueue addOperation:operation];
}

@end


text:
package io.syndesis.qe.pages.customizations.connectors;

import static com.codeborne.selenide.Condition.exist;
import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;

import io.syndesis.qe.pages.SyndesisPageObject;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriverException;

import com.codeborne.selenide.ElementsCollection;
import com.codeborne.selenide.SelenideElement;

public class ApiClientConnectors extends SyndesisPageObject {

    private static final class Element {
        public static final By ROOT = By.className("list-group");
        public static By CONNECTOR_TITLE = By.className("list-group-item-heading");
        public static By CONNECTORS_LIST_ITEM = By.className("list-group-item");
        public static By DETAIL_BUTTON = By.cssSelector("a[data-testid=\"api-connector-list-item-details-button\"]");
    }

    private static class Button {
        public static By CREATE_API_CONNECTOR_RIGHT = By.xpath("//a[text()[contains(.,'Create API Connector')]]");
    }

    public void startWizard() {
        $(Button.CREATE_API_CONNECTOR_RIGHT).shouldBe(visible).click();
    }

    @Override
    public SelenideElement getRootElement() {
        return $(Element.ROOT).shouldBe(exist);
    }

    public SelenideElement getConnectorItem(String connectorName) {
        return $(By.cssSelector(("div[data-testid=\"api-connector-list-item-" + connectorName.trim() + "-list-item\"]")
            .replaceAll("[\\s_]", "-").toLowerCase()))
            .should(exist);
    }

    @Override
    public boolean validate() {
        ElementsCollection pageTitleCollection = $$(".simple-page-header__title-text").filter(text("API Client Connectors"));
        return pageTitleCollection.size() == 1;
    }

    public boolean isConnectorPresent(String connectorName) {
        try {
            getRootElement().findAll(Element.CONNECTOR_TITLE).find(text(connectorName)).shouldBe(visible);
            return true;
        } catch (WebDriverException wde) {
            return false;
        }
    }

    public boolean isConnectorsListLongAs(int expectedSize) {
        try {
            $$(Element.CONNECTORS_LIST_ITEM).shouldHaveSize(expectedSize);
            return true;
        } catch (WebDriverException wde) {
            return false;
        }
    }

    public void clickConnectorByTitle(String connectorName) {
        $(By.cssSelector(("div[data-testid=\"api-connector-list-item-" + connectorName.trim() + "-list-item\"]")
            .replaceAll("[\\s_]", "-").toLowerCase()))
            .should(exist).$(Element.DETAIL_BUTTON).shouldBe(visible).click();
    }

    public SelenideElement getDeleteButton(String connectorName) {
        return getConnectorItem(connectorName).$(By.xpath(".//button[contains(.,\"Delete\")]"));
    }
}


text:
using namespace PaintsNow;
using namespace PaintsNow::NsEchoLegend;
using namespace PaintsNow::NsBridgeSunset;

EchoLegend::EchoLegend(IThread& threadApi, INetwork& n, BridgeSunset& bs) : IScript::Library(threadApi), network(n), bridgeSunset(bs) {}

void EchoLegend::DestroyScript(IScript::Request& request) {
	// TODO: Deactive all activive connections/listeners.
	Library::DestroyScript(request);
}

TObject<IReflect>& EchoLegend::operator () (IReflect& reflect) {
	ReflectClass(EchoLegend)[Interface(IScript::Library)];
	if (reflect.IsReflectMethod()) {
		ReflectMethod(RequestOpenListener)[ScriptMethod = "OpenListener"];
		ReflectMethod(RequestActivateListener)[ScriptMethod = "ActivateListener"];
		ReflectMethod(RequestGetListenerInfo)[ScriptMethod = "GetListenerInfo"];
		ReflectMethod(RequestDeactivateListener)[ScriptMethod = "DeactivateListener"];
		ReflectMethod(RequestOpenConnection)[ScriptMethod = "OpenConnection"];
		ReflectMethod(RequestActivateConnection)[ScriptMethod = "ActivateConnection"];
		ReflectMethod(RequestDeactivateConnection)[ScriptMethod = "DeactivateConnection"];
		ReflectMethod(RequestGetConnectionInfo)[ScriptMethod = "GetConnectionInfo"];
		ReflectMethod(RequestWriteConnection)[ScriptMethod = "WriteConnection"];
		ReflectMethod(RequestReadConnection)[ScriptMethod = "ReadConnection"];
		ReflectMethod(RequestWriteConnectionHttpRequest)[ScriptMethod = "WriteConnectionHttpRequest"];
		ReflectMethod(RequestWriteConnectionHttpResponse)[ScriptMethod = "WriteConnectionHttpResponse"];
		ReflectMethod(RequestReadConnectionHttpRequest)[ScriptMethod = "ReadConnectionHttpRequest"];
		ReflectMethod(RequestParseURL)[ScriptMethod = "ParseURL"];
		ReflectMethod(RequestMakeURL)[ScriptMethod = "MakeURL"];
		ReflectMethod(RequestOpenDispatcher)[ScriptMethod = "OpenDispatcher"];
		ReflectMethod(RequestActivateDispatcher)[ScriptMethod = "ActivateDispatcher"];
		ReflectMethod(RequestDeactivateDispatcher)[ScriptMethod = "DeactivateDispatcher"];
	}

	return *this;
}

void EchoLegend::RequestOpenListener(IScript::Request& request, IScript::Delegate<WorkDispatcher> dispatcher, String& ip, bool http, IScript::Request::Ref eventHandler, IScript::Request::Ref callback, IScript::Request::Ref connectCallback, bool packetMode) {
	METHOD_ENTRY(EchoLegend::RequestOpenListener);
	CHECK_REFERENCES_WITH_TYPE(eventHandler U connectCallback U callback, IScript::Request::FUNCTION U IScript::Request::FUNCTION U IScript::Request::FUNCTION);
	CHECK_DELEGATE(dispatcher);

	WorkDispatcher* disp = dispatcher.Get();
	TShared<Listener> p = TShared<Listener>::Make(bridgeSunset, network, disp, eventHandler, callback, connectCallback, ip, http, packetMode);

	if (p->IsValid()) {
		request.DoLock();
		request << delegate(p());
		request.UnLock();
	}
}

void EchoLegend::RequestActivateListener(IScript::Request& request, IScript::Delegate<Listener> listener) {
	METHOD_ENTRY(EchoLegend::RequestActivateListener);
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(listener);
	listener->Activate();
}

void EchoLegend::RequestDeactivateListener(IScript::Request& request, IScript::Delegate<Listener> listener) {
	METHOD_ENTRY(EchoLegend::RequestDeactivateListener);
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(listener);
	listener->Deactivate();
}

void EchoLegend::RequestGetListenerInfo(IScript::Request& request, IScript::Delegate<Listener> listener, IScript::Request::Ref callback) {
	METHOD_ENTRY(EchoLegend::RequestGetListenerInfo);
	CHECK_REFERENCES(callback);
	CHECK_DELEGATE(listener);
	listener->GetInfo(request, callback);
}

void EchoLegend::RequestOpenConnection(IScript::Request& request, IScript::Delegate<WorkDispatcher> dispatcher, String& ip, bool http, IScript::Request::Ref connectCallback, bool packetMode) {
	METHOD_ENTRY(EchoLegend::RequestOpenConnection);
	CHECK_REFERENCES_WITH_TYPE(connectCallback, IScript::Request::FUNCTION);
	CHECK_DELEGATE(dispatcher);

	WorkDispatcher* disp = dispatcher.Get();
	ITunnel::Connection* conn = nullptr;
	INetwork::HttpRequest* req = nullptr;
	TShared<Connection> c = TShared<Connection>::Make(bridgeSunset, network, disp, connectCallback, ip, conn, http, req, false, packetMode);

	if (c->IsValid()) {
		request.DoLock();
		request << delegate(c());
		request.UnLock();
	}
}

void EchoLegend::RequestActivateConnection(IScript::Request& request, IScript::Delegate<Connection> connection) {
	METHOD_ENTRY(EchoLegend::RequestActivateConnection);
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(connection);
	connection->Activate();
}

void EchoLegend::RequestDeactivateConnection(IScript::Request& request, IScript::Delegate<Connection> connection) {
	METHOD_ENTRY(EchoLegend::RequestDeactivateConnection);
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(connection);
	connection->Deactivate();
}

void EchoLegend::RequestGetConnectionInfo(IScript::Request& request, IScript::Delegate<Connection> connection, IScript::Request::Ref callback) {
	METHOD_ENTRY(EchoLegend::RequestGetConnectionInfo);
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(connection);
	connection->GetInfo(request, callback);
}

void EchoLegend::RequestWriteConnection(IScript::Request& request, IScript::Delegate<Connection> connection, String& data) {
	METHOD_ENTRY(EchoLegend::RequestWriteConnection);
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(connection);
	connection->Write(request, data);
}

void EchoLegend::RequestReadConnection(IScript::Request& request, IScript::Delegate<Connection> connection, IScript::Request::Ref callback) {
	METHOD_ENTRY(EchoLegend::RequestReadConnection);
	CHECK_REFERENCES_WITH_TYPE(callback, IScript::Request::FUNCTION);
	CHECK_DELEGATE(connection);

	connection->Read(request, callback);
}

void EchoLegend::RequestWriteConnectionHttpRequest(IScript::Request& request, IScript::Delegate<Connection> connection, String& uri, String& method, std::list<std::pair<String, String> >& header, String& data) {
	METHOD_ENTRY(EchoLegend::RequestWriteConnectionHttpRequest);
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(connection);
	connection->WriteHttpRequest(uri, method, header, data);
}

void EchoLegend::RequestWriteConnectionHttpResponse(IScript::Request& request, IScript::Delegate<Connection> connection, int code, String& data, String& reason, std::list<std::pair<String, String> >& header) {
	if (connection) {
		connection->WriteHttpResponse(data, code, reason, header);
	} else {
		request.Error("EchoLegend::WriteConnectionHttpReponse(connection, data) : invalid connection");
	}
}

void EchoLegend::RequestReadConnectionHttpRequest(IScript::Request& request, IScript::Delegate<Connection> connection, IScript::Request::Ref callback) {
	if (connection) {
		connection->ReadHttpRequest(request, callback);
	} else {
		request.Error("EchoLegend::ReadConnectionHttp(connection, data) : invalid connection");
		request.DoLock();
		request.Dereference(callback);
		request.UnLock();
	}
}

void EchoLegend::RequestParseURL(IScript::Request& request, String& url) {
	String user, host, path, fragment;
	int port;
	std::list<std::pair<String, String> > query;
	network.ParseUri(url, user, host, port, path, query, fragment);

	request.DoLock();
	request << begintable
		<< key("User") << user
		<< key("Host") << host
		<< key("Path") << path
		<< key("Fragment") << fragment
		<< key("Port") << port
		<< key("Query") << begintable;

	for (std::list<std::pair<String, String> >::const_iterator p = query.begin(); p != query.end(); ++p) {
		request << key((*p).first.c_str()) << (*p).second;
	}

	request << endtable << endtable;
	request.UnLock();
}

void EchoLegend::RequestMakeURL(IScript::Request& request, String& user, String& host, String& path, std::list<std::pair<String, String> >& query, String& fragment) {
	String result = network.MakeUri(user, host, path, query, fragment);
	request.DoLock();
	request << result;
	request.UnLock();
}

void EchoLegend::RequestOpenDispatcher(IScript::Request& request) {
	METHOD_ENTRY(EchoLegend::RequestOpenDispatcher);
	ITunnel::Dispatcher* disp = network.OpenDispatcher();
	if (disp != nullptr) {
		TShared<WorkDispatcher> dispatcher = TShared<WorkDispatcher>::Make(bridgeSunset, network, disp);
		request.DoLock();
		request << delegate(dispatcher());
		request.UnLock();
	}
}

void EchoLegend::RequestActivateDispatcher(IScript::Request& request, IScript::Delegate<WorkDispatcher> dispatcher) {
	METHOD_ENTRY(EchoLegend::RequestActivateDispatcher);
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(dispatcher);

	dispatcher->AsyncActivate(request);
}

void EchoLegend::RequestDeactivateDispatcher(IScript::Request& request, IScript::Delegate<WorkDispatcher> dispatcher) {
	METHOD_ENTRY(EchoLegend::RequestActivateDispatcher);
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(dispatcher);

	dispatcher->Deactivate();
}


text:
import sys.process._
import java.io.File

import org.hxiao.der.util.SolrUtility
import org.hxiao.der.wikipedia.classes.{SurfaceName => SF}
import org.hxiao.der.mention.{MentionDetector, Mention}

import org.scalatest._
import org.scalatest.Assertions._

import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer

class MentionDetectorSpec extends FlatSpec with BeforeAndAfter with Matchers {
  val port = "10987"
  val service_url = s"http://localhost:$port/solr/test/tag?overlaps=NO_SUB&tagsLimit=5000&fl=*&matchText=true"

  val home_dir = System.getProperty("user.home")
  val solr_home = System.getenv("SOLR_HOME")
  require(solr_home != null, "env var $SOLR_HOME is not set")

  val solr_core_dir = (new File(
    getClass().getResource("output-head-100.xml").getPath())
  ).getParent() + "/solr"
  val start_solr_cmd = s"$solr_home/bin/solr start -s $solr_core_dir -p $port"
  val stop_solr_cmd = s"$solr_home/bin/solr stop  -p $port"

  val solr_dir = getClass().getResource("solr").getPath()
  val solr_core_name = "test"
  var solr_server: EmbeddedSolrServer = _

  before {
    // create some fixtures
    solr_server = SolrUtility.createEmbeddedSolrServer(solr_dir, solr_core_name)

    val solr_util = new SolrUtility(solr_server)
    solr_util.addSurfaceNames(
      List("Super Bowl", "Denver", "Seattle", "Denver Broncos", "Seattle Seahawks").map(
        name => {
          new SF(name, null, 1)
        }
      ).toIterator
    )
    solr_server.shutdown()

    require((start_solr_cmd !) == 0, "solr server starts by cmd FAIL!")
  }

  "MentionDetector.detect" should "return a list of mentions" in {
    val detector = new MentionDetector(service_url)
    val text = """Down below, bomb-sniffing dogs will patrol the trains and buses that are expected to take approximately 30,000 of the 80,000-plus spectators to Sunday's Super Bowl between the Denver Broncos and Seattle Seahawks."""
    val mentions = detector.detect(text)

    List((153, 163, "Super Bowl"),
      (176, 190, "Denver Broncos"),
      (195, 211, "Seattle Seahawks")
    ) should equal {
      mentions.map {
        m => {
          (m.start, m.end, m.text)
        }
      }
    }
  }

  after {
    require((stop_solr_cmd !) == 0, "solr server cmd stop FAIL")

    if(solr_server != null){
      solr_server = SolrUtility.createEmbeddedSolrServer(solr_dir, solr_core_name)
      solr_server.deleteByQuery( "*:*" )
      solr_server.shutdown()
    }
  }
}


text:
package com.dubture.twig.ui.editor.contentassist;

import org.eclipse.jface.text.contentassist.ICompletionProposal;

import com.dubture.twig.core.codeassist.CompletionProposal;

public interface ICompletionProposalProvider {

	ICompletionProposal createCompletionProposal(CompletionProposal proposal);
}