text:
from numpy.testing import assert_array_equal

class NumpyArrayTestingMixIn(object):
    def assertArrayEqual(self, actual, expected):
        try:
            assert_array_equal(actual, expected)
        except AssertionError as error:
            self.fail(error)

redpajama_set_name: RedPajamaGithub


text:
@import UIKit;

@interface IETViewController : UIViewController

@end


text:
- Piotr Karkut [ekiro](http://github.com/ekiro)
- Tomasz Wąsiński [wasinski](http://github.com/wasinski)


text:
@interface MasterViewController ()

@property (strong, nonatomic) NSMutableArray *menus;

@end

@implementation MasterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];

    self.menus = [NSMutableArray arrayWithObjects:kLockPincode, nil];
}

- (void)viewWillAppear:(BOOL)animated {
    self.clearsSelectionOnViewWillAppear = self.splitViewController.isCollapsed;
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.menus count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSString *text = [self.menus objectAtIndex:indexPath.row];
    [cell.textLabel setText:text];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *text = [self.menus objectAtIndex:indexPath.row];
    if ([text isEqualToString:kLockPincode] == YES)
    {
        PFXLockPincodePlugin *lockPincodePlugin = [PFXLockPincodePlugin new];
        NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"0000", @"pincode", nil];
        [lockPincodePlugin executeWithInfo:infoDict completion:^(NSDictionary *resultDict) {

        } failure:^(NSError *error) {

        }];

        return;
    }
}

@end


text:
package com.mongodb;

import com.mongodb.util.TestCase;
import org.testng.annotations.*;

/**
 * Test that QueryOpBuilder creates query operations that abide by
 * @author stevebriskin
 *
 */
public class QueryOpTest extends TestCase{

	@Test
	public void testQueryOnly(){
		DBObject query = QueryBuilder.start("x").greaterThan(1).get();
		DBObject obj = new QueryOpBuilder().addQuery(QueryBuilder.start("x").greaterThan(1).get()).get();
		assertEquals(query, obj);

		assertNotNull(new QueryOpBuilder().get());

	}

	@Test
	public void testQueryAndOthers(){
		DBObject query = QueryBuilder.start("x").greaterThan(1).get();
		DBObject orderBy = new BasicDBObject("x", 1);
		DBObject hintObj = new BasicDBObject("x_i", 1);
		DBObject readPref = new BasicDBObject("$readPreference",ReadPreference.primary().toDBObject());
		String hintStr = "y_i";

		DBObject queryOp = new QueryOpBuilder().addQuery(query).addOrderBy(orderBy).addHint(hintStr).get();
		assertEquals(queryOp.get("$query"), query);
		assertEquals(queryOp.get("$orderby"), orderBy);
		assertEquals(queryOp.get("$hint"), hintStr);
		assertNull(queryOp.get("$explain"));
		assertNull(queryOp.get("$snapshot"));

		//orderby should only be there if added
		queryOp = new QueryOpBuilder().addQuery(query).addHint(hintStr).get();
		assertEquals(queryOp.get("$query"), query);
		assertNull(queryOp.get("$orderby"));

		//hintObj takes precedence over hintStr
		queryOp = new QueryOpBuilder().addQuery(query).addOrderBy(orderBy).addHint(hintStr).addHint(hintObj).get();
		assertEquals(queryOp.get("$query"), query);
		assertEquals(queryOp.get("$orderby"), orderBy);
		assertEquals(queryOp.get("$hint"), hintObj);

		queryOp = new QueryOpBuilder().addQuery(query).addExplain(true).addSnapshot(true).get();
		assertEquals(queryOp.get("$query"), query);
		assertNull(queryOp.get("$orderby"));
		assertNull(queryOp.get("$hint"));
		assertEquals(queryOp.get("$explain"), true);
		assertEquals(queryOp.get("$snapshot"), true);

		queryOp = new QueryOpBuilder().addQuery(query).addSpecialFields(new BasicDBObject("flag", "val")).get();
		assertEquals(queryOp.get("flag"), "val");
		assertEquals(queryOp.get("$query"), query);
		assertNull(queryOp.get("$orderby"));
		assertNull(queryOp.get("$hint"));
		assertNull(queryOp.get("$explain"));
		assertNull(queryOp.get("$snapshot"));

		queryOp = new QueryOpBuilder().addQuery(query).addReadPreference(readPref).get();
        assertEquals(queryOp.get("$query"), query);
        assertNull(queryOp.get("$orderby"));
        assertNull(queryOp.get("$hint"));
        assertNull(queryOp.get("$explain"));
        assertNull(queryOp.get("$snapshot"));
        assertEquals(queryOp.get("$readPreference"), readPref);
	}
}


text:
package com.coolweather.android.util;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Http网络请求工具
 * Created by Yang on 2017/6/5.
 */

public class HttpUtil {

    public static void sendOkHttpRequest(String address, Callback callback) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(address).build();
        client.newCall(request).enqueue(callback);
    }
}


text:
@@./tables/t_app.sql
@@./tables/t_appender.sql
@@./tables/t_app_appender.sql
@@./tables/t_param.sql
@@./tables/t_schema_app.sql
@@./tables/t_logger.sql
@@./tables/t_log.sql


text:
package concrete_test

import (
	"testing"

	"github.com/gonum/graph"
	"github.com/gonum/graph/concrete"
)

var _ graph.Graph = (*concrete.Graph)(nil)
var _ graph.Graph = (*concrete.Graph)(nil)

func TestAssertMutableNotDirected(t *testing.T) {
	var g graph.MutableGraph = concrete.NewGraph()
	if _, ok := g.(graph.DirectedGraph); ok {
		t.Fatal("concrete.Graph is directed, but a MutableGraph cannot safely be directed!")
	}
}

func TestMaxID(t *testing.T) {
	g := concrete.NewGraph()
	nodes := make(map[graph.Node]struct{})
	for i := concrete.Node(0); i < 3; i++ {
		g.AddNode(i)
		nodes[i] = struct{}{}
	}
	g.RemoveNode(concrete.Node(0))
	delete(nodes, concrete.Node(0))
	g.RemoveNode(concrete.Node(2))
	delete(nodes, concrete.Node(2))
	n := g.NewNode()
	g.AddNode(n)
	if !g.NodeExists(n) {
		t.Error("added node does not exist in graph")
	}
	if _, exists := nodes[n]; exists {
		t.Errorf("Created already existing node id: %v", n.ID())
	}
}


text:
export const DEFAULT_ACTION = 'app/BrowserPage/DEFAULT_ACTION'
export const BROWSER_PAGE_LOADED = 'app/BrowserPage/BROWSER_PAGE_LOADED'
export const REFRESH_BROWSER_MENU = 'app/BrowserPage/REFRESH_BROWSER_MENU'
export const BROWSER_MENU_FETCH_SUCCEEDED = 'app/BrowserPage/BROWSER_MENU_FETCH_SUCCEEDED'
export const BROWSER_MENU_FETCH_FAILED = 'app/BrowserPage/BROWSER_MENU_FETCH_FAILED'
export const BROWSER_CONTENT_FETCH_SUCCEEDED = 'app/BrowserPage/BROWSER_CONTENT_FETCH_SUCCEEDED'
export const BROWSER_CONTENT_FETCH_FAILED = 'app/BrowserPage/BROWSER_CONTENT_FETCH_FAILED'
export const CHOOSE_MENU_ITEM = 'app/BrowserPage/CHOOSE_MENU_ITEM'


text:
package com.navercorp.pinpoint.grpc.server;

import io.grpc.Attributes;
import io.grpc.Grpc;
import io.grpc.Status;

import java.net.InetSocketAddress;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Woonduk Kang(emeroad)
 */
public class TransportMetadataFactory {

    private static final AtomicLong idGenerator = new AtomicLong(0);
    private final String debugString;

    public TransportMetadataFactory(String debugString) {
        this.debugString = Objects.requireNonNull(debugString, "debugString");
    }

    public TransportMetadata build(Attributes attributes) {
        final InetSocketAddress remoteSocketAddress = (InetSocketAddress) attributes.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
        if (remoteSocketAddress == null) {
            // Unauthenticated
            throw Status.INTERNAL.withDescription("RemoteSocketAddress is null").asRuntimeException();
        }
        final InetSocketAddress localSocketAddress = (InetSocketAddress) attributes.get(Grpc.TRANSPORT_ATTR_LOCAL_ADDR);
        if (localSocketAddress == null) {
            // Unauthenticated
            throw Status.INTERNAL.withDescription("LocalSocketAddress is null").asRuntimeException();
        }

        final long transportId = idGenerator.getAndIncrement();
        final long connectedTime = System.currentTimeMillis();

        final Long logId = attributes.get(MetadataServerTransportFilter.LOG_ID);
        if (logId == null) {
            throw Status.INTERNAL.withDescription("LogId not found").asRuntimeException();
        }
        return new DefaultTransportMetadata(debugString, remoteSocketAddress, localSocketAddress, transportId, connectedTime, logId);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("TransportMetadataFactory{");
        sb.append("debugString='").append(debugString).append('\'');
        sb.append('}');
        return sb.toString();
    }
}


text:
require "liquid/block"
require "jekyll/graphviz/renderer"

module Jekyll
  module Graphviz
    class Block < Liquid::Block
      def initialize tag_name, text, tokens
        super
        @tag_name = tag_name
        @title = text.strip
      end

      def render context
        config = context.registers[:site].config
        @renderer = Jekyll::Graphviz::Renderer.new(config["graphviz"])
        render_graph super
      end

      private

      def render_graph code
        case @tag_name
        when 'graphviz' then render_graphviz code
        when 'graph'    then render_graphviz %[graph "#{@title}" {\n#{code}\n}]
        when 'digraph'  then render_graphviz %[digraph "#{@title}" {\n#{code}\n}]
        else raise "unknown liquid tag name: #{@tag_name}"
        end
      end

      def render_graphviz code
        @renderer.render code, @title
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/concepts/government-and-economics/secretary-of-agriculture" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/concepts/government-and-economics/secretary-of-agriculture</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Secretary of Agriculture</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/concepts/government-and-economics/secretary-of-agriculture</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/concepts/government-and-economics/secretary-of-agriculture</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
import {Bar} from 'cli-progress';

import {Log} from '../../utils/logging.js';
import {AuthenticatedGitClient} from '../../utils/git/authenticated-git-client.js';
import {GitCommandError} from '../../utils/git/git-client.js';
import {
  fetchPendingPullRequestsFromGithub,
  PullRequestFromGithub,
} from '../common/fetch-pull-request.js';

/** Name of a temporary local branch that is used for checking conflicts. **/
const tempWorkingBranch = '__NgDevRepoBaseAfterChange__';

/** Checks if the provided PR will cause new conflicts in other pending PRs. */
export async function discoverNewConflictsForPr(newPrNumber: number, updatedAfter: number) {
  /** The singleton instance of the authenticated git client. */
  const git = await AuthenticatedGitClient.get();

  // If there are any local changes in the current repository state, the
  // check cannot run as it needs to move between branches.
  if (git.hasUncommittedChanges()) {
    Log.error('Cannot run with local changes. Please make sure there are no local changes.');
    process.exit(1);
  }

  /** The active github branch or revision before we performed any Git commands. */
  const previousBranchOrRevision = git.getCurrentBranchOrRevision();
  /* Progress bar to indicate progress. */
  const progressBar = new Bar({format: `[{bar}] ETA: {eta}s | {value}/{total}`});
  /* PRs which were found to be conflicting. */
  const conflicts: Array<PullRequestFromGithub> = [];

  Log.info(`Requesting pending PRs from Github`);
  /** List of PRs from github currently known as mergable. */
  const allPendingPRs = await fetchPendingPullRequestsFromGithub(git);

  if (allPendingPRs === null) {
    Log.error('Unable to find any pending PRs in the repository');
    process.exit(1);
  }

  /** The PR which is being checked against. */
  const requestedPr = allPendingPRs.find((pr) => pr.number === newPrNumber);
  if (requestedPr === undefined) {
    Log.error(
      `The request PR, #${newPrNumber} was not found as a pending PR on github, please confirm`,
    );
    Log.error(`the PR number is correct and is an open PR`);
    process.exit(1);
  }

  const pendingPrs = allPendingPRs.filter((pr) => {
    return (
      // PRs being merged into the same target branch as the requested PR
      pr.baseRef.name === requestedPr.baseRef.name &&
      // PRs which either have not been processed or are determined as mergable by Github
      pr.mergeable !== 'CONFLICTING' &&
      // PRs updated after the provided date
      new Date(pr.updatedAt).getTime() >= updatedAfter
    );
  });
  Log.info(`Retrieved ${allPendingPRs.length} total pending PRs`);
  Log.info(`Checking ${pendingPrs.length} PRs for conflicts after a merge of #${newPrNumber}`);

  // Fetch and checkout the PR being checked.
  git.run(['fetch', '-q', requestedPr.headRef.repository.url, requestedPr.headRef.name]);
  git.run(['checkout', '-q', '-B', tempWorkingBranch, 'FETCH_HEAD']);

  // Rebase the PR against the PRs target branch.
  git.run(['fetch', '-q', requestedPr.baseRef.repository.url, requestedPr.baseRef.name]);
  try {
    git.run(['rebase', 'FETCH_HEAD'], {stdio: 'ignore'});
  } catch (err) {
    if (err instanceof GitCommandError) {
      Log.error('The requested PR currently has conflicts');
      git.checkout(previousBranchOrRevision, true);
      process.exit(1);
    }
    throw err;
  }

  // Start the progress bar
  progressBar.start(pendingPrs.length, 0);

  // Check each PR to determine if it can merge cleanly into the repo after the target PR.
  for (const pr of pendingPrs) {
    // Fetch and checkout the next PR
    git.run(['fetch', '-q', pr.headRef.repository.url, pr.headRef.name]);
    git.run(['checkout', '-q', '--detach', 'FETCH_HEAD']);
    // Check if the PR cleanly rebases into the repo after the target PR.
    try {
      git.run(['rebase', tempWorkingBranch], {stdio: 'ignore'});
    } catch (err) {
      if (err instanceof GitCommandError) {
        conflicts.push(pr);
      } else {
        throw err;
      }
    }
    // Abort any outstanding rebase attempt.
    git.runGraceful(['rebase', '--abort'], {stdio: 'ignore'});

    progressBar.increment(1);
  }
  // End the progress bar as all PRs have been processed.
  progressBar.stop();
  Log.info();
  Log.info(`Result:`);

  git.checkout(previousBranchOrRevision, true);

  // If no conflicts are found, exit successfully.
  if (conflicts.length === 0) {
    Log.info(`No new conflicting PRs found after #${newPrNumber} merging`);
    process.exit(0);
  }

  // Inform about discovered conflicts, exit with failure.
  Log.error.group(`${conflicts.length} PR(s) which conflict(s) after #${newPrNumber} merges:`);
  for (const pr of conflicts) {
    Log.error(`  - #${pr.number}: ${pr.title}`);
  }
  Log.error.groupEnd();
  process.exit(1);
}


text:
package isolation_test

import (
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/pingcap/failpoint"
	"github.com/pingcap/tidb/infoschema"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/sessiontxn"
	"github.com/pingcap/tidb/testkit"
	"github.com/pingcap/tidb/testkit/testfork"
	"github.com/pingcap/tidb/testkit/testsetup"
	"github.com/stretchr/testify/require"
	"github.com/tikv/client-go/v2/oracle"
	"github.com/tikv/client-go/v2/tikv"
	"go.uber.org/goleak"
)

func TestMain(m *testing.M) {
	testsetup.SetupForCommonTest()
	tikv.EnableFailpoints()
	opts := []goleak.Option{
		goleak.IgnoreTopFunction("github.com/golang/glog.(*loggingT).flushDaemon"),
		goleak.IgnoreTopFunction("github.com/lestrrat-go/httprc.runFetchWorker"),
		goleak.IgnoreTopFunction("go.etcd.io/etcd/client/pkg/v3/logutil.(*MergeLogger).outputLoop"),
		goleak.IgnoreTopFunction("go.opencensus.io/stats/view.(*worker).start"),
	}
	goleak.VerifyTestMain(m, opts...)
}

func getOracleTS(t testing.TB, sctx sessionctx.Context) uint64 {
	ts, err := sctx.GetStore().GetOracle().GetTimestamp(context.TODO(), &oracle.Option{TxnScope: oracle.GlobalTxnScope})
	require.NoError(t, err)
	return ts
}

type txnAssert[T sessiontxn.TxnContextProvider] struct {
	sctx                  sessionctx.Context
	isolation             string
	minStartTime          time.Time
	active                bool
	inTxn                 bool
	minStartTS            uint64
	startTS               uint64
	causalConsistencyOnly bool
	couldRetry            bool
}

func (a *txnAssert[T]) Check(t testing.TB) {
	provider := sessiontxn.GetTxnManager(a.sctx).GetContextProvider()
	sessVars := a.sctx.GetSessionVars()
	txnCtx := sessVars.TxnCtx

	if sessVars.SnapshotInfoschema == nil {
		require.Same(t, provider.GetTxnInfoSchema(), txnCtx.InfoSchema)
	} else {
		require.Equal(t, sessVars.SnapshotInfoschema.(infoschema.InfoSchema).SchemaMetaVersion(), provider.GetTxnInfoSchema().SchemaMetaVersion())
	}
	require.Equal(t, a.isolation, txnCtx.Isolation)
	require.Equal(t, a.isolation != "", txnCtx.IsPessimistic)
	require.Equal(t, sessVars.CheckAndGetTxnScope(), txnCtx.TxnScope)
	require.Equal(t, sessVars.ShardAllocateStep, int64(txnCtx.ShardStep))
	require.False(t, txnCtx.IsStaleness)
	require.GreaterOrEqual(t, txnCtx.CreateTime.UnixNano(), a.minStartTime.UnixNano())
	require.Equal(t, a.inTxn, sessVars.InTxn())
	require.Equal(t, a.inTxn, txnCtx.IsExplicit)
	require.Equal(t, a.couldRetry, txnCtx.CouldRetry)
	require.Equal(t, assertTxnScope, txnCtx.TxnScope)
	require.Equal(t, assertTxnScope, provider.GetTxnScope())
	require.Equal(t, assertReplicaReadScope, provider.GetReadReplicaScope())

	txn, err := a.sctx.Txn(false)
	require.NoError(t, err)
	require.Equal(t, a.active, txn.Valid())
	if !a.active {
		require.False(t, a.inTxn)
		require.Zero(t, a.startTS)
		require.Zero(t, txnCtx.StartTS)
	} else {
		require.True(t, a.minStartTS != 0 || a.startTS != 0)
		require.Greater(t, txnCtx.StartTS, a.minStartTS)
		if a.startTS != 0 {
			require.Equal(t, a.startTS, txnCtx.StartTS)
		}
		require.Equal(t, txnCtx.StartTS, txn.StartTS())
		require.Same(t, sessVars.KVVars, txn.GetVars())
		require.Equal(t, txnCtx.TxnScope, txn.GetOption(kv.TxnScope))
		require.Equal(t, a.causalConsistencyOnly, !txn.GetOption(kv.GuaranteeLinearizability).(bool))
		require.Equal(t, txnCtx.IsPessimistic, txn.IsPessimistic())
	}
	// The next line is testing the provider has the type T, if not, the cast will panic
	_ = provider.(T)
}

func activeSnapshotTxnAssert(sctx sessionctx.Context, ts uint64, isolation string) *txnAssert[sessiontxn.TxnContextProvider] {
	return &txnAssert[sessiontxn.TxnContextProvider]{
		sctx:         sctx,
		minStartTime: time.Now(),
		startTS:      ts,
		active:       true,
		inTxn:        false,
		isolation:    isolation,
	}
}

func (a *txnAssert[T]) CheckAndGetProvider(t testing.TB) T {
	a.Check(t)
	return sessiontxn.GetTxnManager(a.sctx).GetContextProvider().(T)
}

var assertTxnScope = kv.GlobalTxnScope
var assertReplicaReadScope = kv.GlobalReplicaScope

func forkScopeSettings(t *testfork.T, store kv.Storage) func() {
	tk := testkit.NewTestKit(t, store)
	failPointEnabled := false
	clearFunc := func() {
		assertTxnScope = kv.GlobalTxnScope
		assertReplicaReadScope = kv.GlobalReplicaScope
		tk.MustExec("set @@global.tidb_replica_read='leader'")
		tk.MustExec("set @@global.tidb_enable_local_txn=0")
		if failPointEnabled {
			require.NoError(t, failpoint.Disable("tikvclient/injectTxnScope"))
		}
	}

	clearFunc()
	success := false
	defer func() {
		if !success {
			clearFunc()
		}
	}()

	zone := testfork.PickEnum(t, "", "bj")
	if zone != "" {
		require.NoError(t, failpoint.Enable("tikvclient/injectTxnScope", fmt.Sprintf(`return("%v")`, zone)))
		failPointEnabled = true
		if testfork.PickEnum(t, "", "enableLocalTxn") != "" {
			tk.MustExec("set @@global.tidb_enable_local_txn=1")
			assertTxnScope = zone
			assertReplicaReadScope = zone
		}
	}

	if testfork.PickEnum(t, "", "closetRead") != "" {
		tk.MustExec("set @@global.tidb_replica_read='closest-replicas'")
		if zone != "" {
			assertReplicaReadScope = zone
		}
	}

	success = true
	return clearFunc
}


text:
package org.locationtech.geowave.analytic.extract;

import org.locationtech.jts.geom.Geometry;

/**
 * Strategy to extract a representative dimensions and Geometry for an Object
 *
 * @param <T>
 */
public interface DimensionExtractor<T> extends java.io.Serializable {
  /** @param anObject -- */
  public double[] getDimensions(T anObject);

  /**
   * @return Dimension names in the same order as dimentions returns from the
   *         {@link DimensionExtractor#getDimensions(Object)}
   */
  public String[] getDimensionNames();

  /**
   * @param anObject -- an object with Geospatial properties
   * @return A Point that must have the SRID set for a valid CRS.
   */
  public Geometry getGeometry(T anObject);

  /**
   * @param anObject the object to get the group ID from
   * @return An assigned group ID, if one exists, otherwise {@code null}
   */
  public String getGroupID(T anObject);
}


text:
<?php

/**
 * lbows
 * integrated integration
 *
 * Lbows Documentation handler
 *
 * Gathers documentation information about modules and methods and
 * 'returns' (or outputs) them via specialized producers.
 *
 * @category   Lbows
 * @package    Lbows_Handler
 * @subpackage Doc
 * @author     Dennis Ploeger <develop@dieploegers.de>
 * @copyright  see LICENSE-FILE
 * @license    see LICENSE-file
 * @version    see VERSION-file
 * @link       http://www.lbows.org
 * @since      Always
 */

class Lbows_Handler_Doc extends Lbows_Handler
{

    /**
     * We're the handler
     *
     * @var string
     * @see Lbows_Handler::$_handler
     */

    protected $_handler = 'Lbows_Handler_Doc';

    /**
     * Our method
     *
     * @var string
     */

    protected $_method = 'Doc';

    /**
     * An array of non complex types
     *
     * @param array
     */

    protected $_nonComplex = array(

        'int', 'integer',
        'string',
        'float', 'double',
        'array', 'struct', 'object', 'mixed',
        'boolean', 'bool',

    );

    /**
     * Error Constants
     */

    /**
     * Cannot find method to reflect
     *
     * @var integer
     */

    const ERR_REFLECT_METHOD = 1;

    /**
     * Cannot find parameter in method
     *
     * @var integer
     */

    const ERR_REFLECT_NOPARAMETER = 2;

    /**
     * Cannot reflect class
     *
     * @var integer
     */

    const ERR_REFLECT_CLASS = 3;

    /**
     * Cannot find param-docblock for property
     *
     * @var integer
     */

    const ERR_REFLECT_PROPERTY_PARAM = 4;

    /**
     * Cannot find property in class
     *
     * @var integer
     */

    const ERR_REFLECT_NOPROPERTY = 5;

    /**
     * Construct the documentation handler
     *
     * @param Zend_Config $config Lbows Configuration
     * @param Zend_Log    $logger Lbows Logger
     */

    public function __construct($config, $logger)
    {

        parent::__construct($config, $logger);

        // Register our external namespace

        $loader = Zend_Loader_Autoloader::getInstance();
        $loader->registerNamespace('LbowsDoc_');

    }

    /**
     * Document a module.
     *
     * List all methods and the short and long description
     *
     * @param string $module Module name
     *
     * @return array The documentation array
     */

    private function _documentModule($module)
    {

        $docArray = array();

        $reflect = new Zend_Reflection_Class($this->_moduleClass);

        // Documentation header for the module

        $docArray['module']['name'] = $module;
        $docArray['module']['class'] = $this->_moduleClass;

        // Document methods

        $docArray['method'] = array();

        foreach (
            $reflect->getMethods(ReflectionMethod::IS_PUBLIC) as $method
        ) {

            if (preg_match('/^__/', $method->name)) {

                // Skip magic methods

                continue;

            }

            $methodArray = array();

            $methodArray['name'] = $method->name;

            $methodDoc = $method->getDocBlock();

            $methodArray['description']['short'] =
                $methodDoc->getShortDescription();

            $methodArray['description']['long'] =
                $methodDoc->getLongDescription();

            $methodArray['url'] = $this->_config->handler->baseUrl
                . $this->_config->sys->namespaceSeparator
                . $method->name;

            $docArray['method'][] = $methodArray;

        }

        return $docArray;

    }

    /**
     * Document a specific method.
     *
     * List the description, all parameters with their type,
     * their description, if they are optional or not,
     * if they are complex or not, the return type and its description.
     *
     * @param string $module  Name of the module
     * @param string $options The handler's handler_options
     *
     * @return array The documentation array
     */

    private function _documentMethod($module, $options)
    {

        $methodName = $options;

        $docArray = array();

        // Documentation header for th emodule

        $docArray['module'] = array();

        $docArray['module']['name'] = $module;

        $docArray['module']['url'] = $this->_config->handler->baseUrl;

        // Reflect the module class

        $reflect = new Zend_Reflection_Class($this->_moduleClass);

        try {

            $method = $reflect->getMethod($methodName);

        } catch (Exception $e) {

            throw new Lbows_Exception_Handler(
                'Cannot reflect method ' . $methodName,
                self::ERR_REFLECT_METHOD, $e
            );

        }

        // Documentation header for the method

        $docArray['method']['name'] = $method->name;

        $methodDoc = $method->getDocBlock();

        $docArray['method']['description']['short'] =
            $methodDoc->getShortDescription();

        $docArray['method']['description']['long'] =
            $methodDoc->getLongDescription();

        // Documentation for the parameters

        $paramVariables = $method->getParameters();

        $docArray['param'] = array();

        $tags = $methodDoc->getTags();

        foreach ($tags as $tag) {

            switch (get_class($tag)) {

                case 'Zend_Reflection_Docblock_Tag_Param':

                    $param = array();

                    $param['name'] = substr(
                        $tag->getVariableName(),
                        1,
                        strlen($tag->getVariableName()) - 1
                    );

                    $param['type'] = $tag->getType();

                    if (strcmp($param['type'], 'array') == 0) {

                        $param['isArray'] = true;

                    }

                    $typearray = explode('|', $param['type']);

                    $isComplex = false;

                    foreach ($typearray as $type) {

                        $isComplex = !in_array(
                            strtolower($type), $this->_nonComplex
                        );

                        if ($isComplex) {

                            $param['url'] = $this->_config->handler->baseUrl
                                . $this->_config->sys->namespaceSeparator
                                . $method->name
                                . $this->_config->sys->namespaceSeparator
                                . $param['name'];

                            // We only document the first complex type

                            break;

                        }

                    }

                    $param['complex'] = $isComplex;

                    $param['description'] = $tag->getDescription();

                    if (preg_match('/^\[\] /', $param['description'])) {

                        $param['description'] =
                            preg_replace(
                                '/^\[\] /', '', $param['description']
                            );

                        $param['isArray'] = true;

                    }

                    $param['optional'] = false;

                    foreach ($paramVariables as $variable) {

                        $paramComparison = strcmp(
                            $variable->getName(), $param['name']
                        );

                        if ($paramComparison == 0) {

                            if ($variable->isOptional()) {

                                $param['optional'] = true;

                                if ($variable->isDefaultValueAvailable()) {

                                    $param['default'] =
                                        $variable->getDefaultValue();

                                }

                            }

                        }

                    }

                    $docArray['param'][] = $param;

                    break;
                case 'Zend_Reflection_Docblock_Tag_Return':

                    // Documentation for the return type

                    $docArray['return']['type'] = $tag->getType();
                    $docArray['return']['description'] =
                        $tag->getDescription();

                    break;
                default:
                    // All other tags unhandled
                    break;

            }

        }

        return $docArray;

    }

    /**
     * Document a complex type variable
     *
     * List the variable's description, all its subparameters
     * with their type and if they are optional or not
     *
     * @param string $options The handler's handler_options
     *
     * @return array The documentation array
     */

    private function _documentComplexType($options)
    {

        $components = explode(
            $this->_config->sys->namespaceSeparator, $options
        );

        $thisComponents = $components;

        $returnComponents = $components;

        $variableName = array_pop($returnComponents);

        $methodName = $components[0];

        $docArray = array();

        $docArray['param'] = array();

        // Reflect the module class

        try {

            $reflect = new Zend_Reflection_Class($this->_moduleClass);

            $method = $reflect->getMethod($methodName);

        } catch (Exception $e) {

            throw new Lbows_Exception_Handler(
                'Cannot reflect method ' . $methodName,
                self::ERR_REFLECT_METHOD, $e
            );

        }

        // Find the class name of the parameter to be documented

        $tags = $method->getDocBlock()->getTags();

        $inspectClass = false;

        foreach ($tags as $tag) {

            $isParam = strcmp(
                strtolower(get_class($tag)),
                'zend_reflection_docblock_tag_param'
            );

            if ($isParam == 0) {

                $isCurrentVariable = strcmp(
                    strtolower($tag->getVariableName()),
                    '$' . strtolower($components[1])
                );

                if ($isCurrentVariable == 0) {

                    $inspectClass = $tag->getType();

                }

            }

        }

        if (preg_match('/|/', $inspectClass)) {

            /**
             * If type is given in alternatives,
             * stubbornly use the first valid class
             */

            $classes = explode('|', $inspectClass);

            $classFound = false;

            foreach ($classes as $class) {

                if ((!$classFound) && (class_exists($class))) {

                    $inspectClass = $class;

                    $classFound = true;

                }

            }

        }

        if (!$inspectClass) {

            throw new Lbows_Exception_Handler(
                'Cannot find method parameter '
                . $components[1]
                . 'in method '
                . $components[0],
                self::ERR_REFLECT_NOPARAMETER
            );

        }

        if (count($components) > 2) {

            // We're documenting subclasses, so dive into the classes

            // Remove method name and first parameter name

            array_shift($components);
            array_shift($components);

            $inspectClass = $this->_getSubClass($components, $inspectClass);

        }

        // Reflect complex type class

        try {

            $reflect = new Zend_Reflection_Class($inspectClass);

        } catch (Exception $e) {

            throw new Lbows_Exception_Handler(
                'Cannot reflect class ' . $inspectClass,
                self::ERR_REFLECT_CLASS, $e
            );

        }

        $properties = $reflect->getProperties();

        $docArray = array();

        // Documentation header for the complex type

        $docArray['complexType']['previous'] =
            $this->_config->handler->baseUrl
            . $this->_config->sys->namespaceSeparator
            . join(
                $this->_config->sys->namespaceSeparator, $returnComponents
            );

        $docArray['complexType']['name'] = $variableName;
        $docArray['complexType']['class'] = $inspectClass;

        // Documentation for the class variables

        $propertyVals = get_class_vars($inspectClass);

        foreach ($properties as $property) {

            $param = array();

            $docblock = $property->getDocComment();

            $param['name'] = $property->getName();
            $param['description']['short'] = $docblock->getShortDescription();
            $param['description']['long'] = $docblock->getLongDescription();

            $varTag = $docblock->getTag('var');

            $param['type'] = $varTag->getDescription();

            if (strcasecmp($param['type'], 'array') == 0) {

                $param['isArray'] = true;

            }

            $typearray = explode('|', $param['type']);

            $isComplex = false;

            foreach ($typearray as $type) {

                if (!in_array(strtolower($type), $this->_nonComplex)) {

                    $isComplex = true;

                    $param['url'] =
                        $this->_config->handler->baseUrl
                        . $this->_config->sys->namespaceSeparator
                        . join(
                            $this->_config->sys->namespaceSeparator,
                            $thisComponents
                        )
                        . $this->_config->sys->namespaceSeparator
                        . $param['name'];

                }

            }

            $param['complex'] = $isComplex;

            $propValue = $propertyVals[$param['name']];

            if ($propValue === null) {

                $param['optional'] = true;
                $param['default'] = $propValue;

            } else {

                $param['optional'] = false;

            }

            if (preg_match('/^\[\] /', $param['description'])) {

                $param['description'] =
                    preg_replace('/^\[\] /', '', $param['description']);
                $param['isArray'] = true;

            }

            $docArray['param'][] = $param;

        }

        return $docArray;

    }

    /**
     * Dive into a class and find the class of a subvariable
     *
     * @param array $components Components we need to find
     * @param array $baseClass  Class to start searching
     *
     * @return string The name of the class to document
     */

    private function _getSubClass($components, $baseClass)
    {

        // Reflect the base class

        $reflect = new Zend_Reflection_Class($baseClass);

        $properties = $reflect->getProperties();

        $inspectClass = false;

        foreach ($properties as $property) {

            $isCurrentProperty = strcmp(
                strtolower($property->getName()), strtolower($components[0])
            );

            if ($isCurrentProperty == 0) {

                $tag = $property->getDocComment()->getTag('var');

                if (!$tag) {

                    throw new Lbows_Exception_Handler(
                        'Cannot find Param-Docblock for '
                        . 'property '
                        . $property->getName(),
                        self::ERR_REFLECT_PROPERTY_PARAM
                    );

                }

                $inspectClass = $tag->getDescription();

            }

        }

        if (!$inspectClass) {

            throw new Lbows_Exception_Handler(
                'Cannot find property '
                . $components[0]
                . ' in class '
                . $baseClass,
                self::ERR_REFLECT_NOPROPERTY
            );

        }

        // Do we have to dive deeper?

        array_shift($components);

        if (count($components) > 0) {

            return $this->_getSubClass($components, $inspectClass);

        }

        return $inspectClass;

    }

    /**
     * Return the method name, this request is calling
     *
     * @param string $request The request, this handler will handle
     * @param array  $handlerRequest A Handler request (Array consisting of
     *                               'handler', 'module' and 'options')
     *
     * @return string Method name
     */

    public function getMethod($request, $handlerRequest) {

        // Overridden by handler

        $options = $handlerRequest['options'];

        if (is_empty($options)) {

            // We're about to document a module

            return '';

        }

        $namespaceSeparatorInOptions = strpos(
            $options, $this->_config->sys->namespaceSeparator
        );

        if ($namespaceSeparatorInOptions === false) {

            return $options;

        }

        /**
         * We're about to document a complex type.
         * Return the first part of the options-argument before
         * the first namespace separator
         */

        $options = explode(
            $this->_config->sys->namespaceSeparator,
            $options
        );

        return $options[0];

    }

    /**
     * Handle a documentation request
     *
     * @param array  $handlerRequest A Handler request (Array consisting
     *                               of 'handler', 'module' and 'options')
     * @param string $request        The request to handle
     *                               (taken from php://input)
     *
     * @return bool Result
     * @see Lbows_Handler
     */

    public function handle($handlerRequest, $request)
    {

        $this->_logger->debug('Doc Handler started');

        $module = $handlerRequest['module'];
        $options = $handlerRequest['options'];

        // Load module

        $this->_loadModule($module);

        // Chop off return type of the options

        $validTypes = array();

        for (
            $i = 1;
            $i <= $this->_config->LbowsHandlerDoc->producers;
            $i++
        ) {

            $producerType = $this->_config->LbowsHandlerDoc
                ->get('producer' . $i)->type;

            $validTypes[$producerType] =
                $this->_config->LbowsHandlerDoc->get('producer' . $i)->class;

        }

        $optionMatch = preg_match(
            '/('
            . preg_quote($this->_config->sys->namespaceSeparator, '/')
            . ')?('
            . join('|', array_keys($validTypes))
            . ')/i', $options, $matches
        );

        if ($optionMatch) {

            $returnType = $matches[2];
            $options = str_replace($matches[1] . $returnType, '', $options);

            $returnType = strtolower($returnType);

        } else {

            $returnType = $this->_config->LbowsHandlerDoc->defaultType;

        }

        /**
         * What should we do?
         *
         * .../doc -> List all methods including short and long description
         * .../doc/method1 -> List all parameters and the return
         *     value for the method
         * .../doc/method1/complexVariable1 -> List parameters in a
         *     complex type (object)
         * .../doc/method1/complexVariable1/complexSubVariable1 -> List
         *     parameters in a complex type under a complex type
         */

        $namespaceSeparatorInOptions = strpos(
            $options, $this->_config->sys->namespaceSeparator
        );

        if (empty($options)) {

            $docMode = 'moduleDocumentation';

            $docArray = $this->_documentModule($module);

        } else if ($namespaceSeparatorInOptions === false) {

            $docMode = 'methodDocumentation';

            $docArray = $this->_documentMethod($module, $options);

        } else {

            $docMode = 'complexTypeDocumentation';

            $docArray = $this->_documentComplexType($options);

        }

        // Instantiate the producer

        $producer = new $validTypes[$returnType](
            $this->_config, $this->_logger, $docArray, $docMode
        );

        // Set the content type provided by the producer

        header('Content-Type: ' . $producer->contentType);

        // Let the producer generate the output

        $data = $producer->produce();

        print $producer->toString($data);

        return true;

    }

}


text:
/**@cond To Make Doxygen skip documentation generation for this file.
 * @{
 */
#include "sdk_config.h"
#include "ble_db_discovery.h"
#include "ble_types.h"
#include "ble_srv_common.h"
#include "ble_gattc.h"
#include "sdk_common.h"
#include "amt.h"

#define NRF_LOG_MODULE_NAME "AMT_C"
#include "nrf_log.h"

#define TX_BUFFER_MASK         0x07                  /**< TX Buffer mask, must be a mask of continuous zeroes, followed by continuous sequence of ones: 000...111. */
#define TX_BUFFER_SIZE         (TX_BUFFER_MASK + 1)  /**< Size of send buffer, which is 1 higher than the mask. */

#define WRITE_MESSAGE_LENGTH   BLE_CCCD_VALUE_LEN    /**< Length of the write message for CCCD. */

typedef enum
{
    READ_REQ,  /**< Type identifying that this tx_message is a read request. */
    WRITE_REQ  /**< Type identifying that this tx_message is a write request. */
} tx_request_t;

/**@brief Structure for writing a message to the peer, i.e. CCCD.
 */
typedef struct
{
    uint8_t                  gattc_value[WRITE_MESSAGE_LENGTH];  /**< The message to write. */
    ble_gattc_write_params_t gattc_params;                       /**< GATTC parameters for this message. */
} write_params_t;

/**@brief Structure for holding data to be transmitted to the connected central.
 */
typedef struct
{
    uint16_t     conn_handle;  /**< Connection handle to be used when transmitting this message. */
    tx_request_t type;         /**< Type of this message, i.e. read or write message. */
    union
    {
        uint16_t       read_handle;  /**< Read request message. */
        write_params_t write_req;    /**< Write request message. */
    } req;
} tx_message_t;

static tx_message_t   m_tx_buffer[TX_BUFFER_SIZE];  /**< Transmit buffer for messages to be transmitted to the central. */
static uint32_t       m_tx_insert_index = 0;        /**< Current index in the transmit buffer where the next message should be inserted. */
static uint32_t       m_tx_index = 0;               /**< Current index in the transmit buffer from where the next message to be transmitted resides. */

/**@brief Function for passing any pending request from the buffer to the stack.
 */
static void tx_buffer_process(void)
{
    if (m_tx_index != m_tx_insert_index)
    {
        uint32_t err_code;

        if (m_tx_buffer[m_tx_index].type == READ_REQ)
        {
            err_code = sd_ble_gattc_read(m_tx_buffer[m_tx_index].conn_handle,
                                         m_tx_buffer[m_tx_index].req.read_handle,
                                         0);
        }
        else
        {
            err_code = sd_ble_gattc_write(m_tx_buffer[m_tx_index].conn_handle,
                                          &m_tx_buffer[m_tx_index].req.write_req.gattc_params);
        }

        if (err_code == NRF_SUCCESS)
        {
            NRF_LOG_DEBUG("SD Read/Write API returns Success.\r\n");
            m_tx_index++;
            m_tx_index &= TX_BUFFER_MASK;
        }
        else
        {
            NRF_LOG_DEBUG("SD Read/Write API returns error, will retry later.\r\n");
        }
    }
}

/**@brief     Function for handling Handle Value Notification received from the SoftDevice.
 *
 * @details   This function will uses the Handle Value Notification received from the SoftDevice
 *            and checks if it is a notification of the AMT from the peer.
 *            If it is, this function will send an event to the peer.
 *
 * @param[in] p_ctx        Pointer to the AMT Client structure.
 * @param[in] p_ble_evt    Pointer to the BLE event received.
 */
static void on_hvx(nrf_ble_amtc_t * p_ctx, const ble_evt_t * p_ble_evt)
{
    // Check if the event if on the link for this instance
    if (p_ctx->conn_handle != p_ble_evt->evt.gattc_evt.conn_handle)
    {
        return;
    }

    // Check if this is a AMT notification.
    if (p_ble_evt->evt.gattc_evt.params.hvx.handle == p_ctx->peer_db.amt_handle)
    {
        nrf_ble_amtc_evt_t amt_c_evt;
        p_ctx->bytes_rcvd_cnt           += p_ble_evt->evt.gattc_evt.params.hvx.len;
        amt_c_evt.evt_type              = NRF_BLE_AMT_C_EVT_NOTIFICATION;
        amt_c_evt.conn_handle           = p_ble_evt->evt.gattc_evt.conn_handle;
        amt_c_evt.params.hvx.notif_len  = p_ble_evt->evt.gattc_evt.params.hvx.len;
        amt_c_evt.params.hvx.bytes_sent = uint32_decode(p_ble_evt->evt.gattc_evt.params.hvx.data);
        amt_c_evt.params.hvx.bytes_rcvd = p_ctx->bytes_rcvd_cnt;
        p_ctx->evt_handler(p_ctx, &amt_c_evt);
    }
}

/**@brief     Function for handling read response event received from the SoftDevice.
 *
 * @details   This function will uses the read response received from the SoftDevice
 *            and checks if it is a read response of the AMT from the peer.
 *            If it is, this function will send an event to the peer.
 *
 * @param[in] p_ctx        Pointer to the AMT Client structure.
 * @param[in] p_ble_evt    Pointer to the BLE event received.
 */
static void on_read_response(nrf_ble_amtc_t * p_ctx, const ble_evt_t * p_ble_evt)
{
    // Check if the event if on the link for this instance
    if (p_ctx->conn_handle != p_ble_evt->evt.gattc_evt.conn_handle)
    {
        return;
    }

    // Check if this is a AMT RCB read response.
    if (p_ble_evt->evt.gattc_evt.params.read_rsp.handle == p_ctx->peer_db.amt_rbc_handle)
    {
        nrf_ble_amtc_evt_t amt_c_evt;
        amt_c_evt.evt_type             = NRF_BLE_AMT_C_EVT_RBC_READ_RSP;
        amt_c_evt.conn_handle          = p_ble_evt->evt.gattc_evt.conn_handle;
        amt_c_evt.params.rcv_bytes_cnt = uint32_decode(p_ble_evt->evt.gattc_evt.params.read_rsp.data);
        p_ctx->evt_handler(p_ctx, &amt_c_evt);
    }
}

/**@brief     Function for handling write response event received from the SoftDevice.
 *
 * @details   This function will uses the read response received from the SoftDevice
 *            and checks if it is a write response of the AMT from the peer.
 *
 * @param[in] p_ctx        Pointer to the AMT Client structure.
 * @param[in] p_ble_evt    Pointer to the BLE event received.
 */
static void on_write_response(nrf_ble_amtc_t * p_ctx, const ble_evt_t * p_ble_evt)
{
    // Check if the event if on the link for this instance
    if (p_ctx->conn_handle != p_ble_evt->evt.gattc_evt.conn_handle)
    {
        return;
    }

    // Check if this is a write response on the CCCD.
    if (p_ble_evt->evt.gattc_evt.params.write_rsp.handle == p_ctx->peer_db.amt_cccd_handle)
    {
        NRF_LOG_DEBUG("CCCD configured.\r\n");
    }
}

void nrf_ble_amtc_on_db_disc_evt(nrf_ble_amtc_t * p_ctx, const ble_db_discovery_evt_t * p_evt)
{
    // Check if the AMT Service was discovered.
    if (   (p_evt->evt_type != BLE_DB_DISCOVERY_COMPLETE)
        || (p_evt->params.discovered_db.srv_uuid.uuid != AMT_SERVICE_UUID)
        || (p_evt->params.discovered_db.srv_uuid.type != p_ctx->uuid_type))
    {
        return;
    }

    nrf_ble_amtc_evt_t evt;
    evt.conn_handle = p_evt->conn_handle;

    // Find the CCCD Handle of the AMT characteristic.
    for (uint32_t i = 0; i < p_evt->params.discovered_db.char_count; i++)
    {
        ble_uuid_t uuid = p_evt->params.discovered_db.charateristics[i].characteristic.uuid;

        if ((uuid.uuid == AMTS_CHAR_UUID) && (uuid.type == p_ctx->uuid_type))
        {
            // Found AMT characteristic. Store handles.
            evt.params.peer_db.amt_cccd_handle =
                p_evt->params.discovered_db.charateristics[i].cccd_handle;
            evt.params.peer_db.amt_handle      =
                p_evt->params.discovered_db.charateristics[i].characteristic.handle_value;
        }

        if ((uuid.uuid == AMT_RCV_BYTES_CNT_CHAR_UUID) && (uuid.type == p_ctx->uuid_type))
        {
            // Found AMT Number of received bytes characteristic. Store handles.
            evt.params.peer_db.amt_rbc_handle      =
                p_evt->params.discovered_db.charateristics[i].characteristic.handle_value;
        }
    }

    NRF_LOG_DEBUG("AMT Service discovered at peer.\r\n");

    //If the instance has been assigned prior to db_discovery, assign the db_handles.
    if (p_ctx->conn_handle != BLE_CONN_HANDLE_INVALID)
    {
        if (   (p_ctx->peer_db.amt_cccd_handle == BLE_GATT_HANDLE_INVALID)
            && (p_ctx->peer_db.amt_handle == BLE_GATT_HANDLE_INVALID))
        {
            p_ctx->peer_db = evt.params.peer_db;
        }
    }

    p_ctx->bytes_rcvd_cnt = 0;

    evt.evt_type = NRF_BLE_AMT_C_EVT_DISCOVERY_COMPLETE;
    p_ctx->evt_handler(p_ctx, &evt);
}

ret_code_t nrf_ble_amtc_init(nrf_ble_amtc_t * p_ctx, nrf_ble_amtc_evt_handler_t evt_handler)
{
    VERIFY_PARAM_NOT_NULL(p_ctx);
    VERIFY_PARAM_NOT_NULL(evt_handler);

    ble_uuid128_t base_uuid = {SERVICE_UUID_BASE};
    ble_uuid_t    amt_uuid;

    ret_code_t err_code = sd_ble_uuid_vs_add(&base_uuid, &p_ctx->uuid_type);
    VERIFY_SUCCESS(err_code);

    amt_uuid.type = p_ctx->uuid_type;
    amt_uuid.uuid = AMT_SERVICE_UUID;

    p_ctx->evt_handler                  = evt_handler;
    p_ctx->bytes_rcvd_cnt               = 0;
    p_ctx->conn_handle                  = BLE_CONN_HANDLE_INVALID;
    p_ctx->peer_db.amt_cccd_handle      = BLE_GATT_HANDLE_INVALID;
    p_ctx->peer_db.amt_handle           = BLE_GATT_HANDLE_INVALID;
    p_ctx->conn_handle                  = BLE_CONN_HANDLE_INVALID;
    p_ctx->peer_db.amt_rbc_handle       = BLE_GATT_HANDLE_INVALID;

    return ble_db_discovery_evt_register(&amt_uuid);
}

ret_code_t nrf_ble_amtc_handles_assign(nrf_ble_amtc_t   * p_ctx,
                                      uint16_t            conn_handle,
                                      nrf_ble_amtc_db_t * p_peer_handles)
{
    VERIFY_PARAM_NOT_NULL(p_ctx);
    p_ctx->conn_handle = conn_handle;
    if (p_peer_handles != NULL)
    {
        p_ctx->peer_db = *p_peer_handles;
    }

    return NRF_SUCCESS;
}

/**@brief     Function for handling Disconnected event received from the SoftDevice.
 *
 * @details   This function check if the disconnect event is happening on the link
 *            associated with the current instance of the module, if so it will set its
 *            conn_handle to invalid.
 *
 * @param[in] p_ctx       Pointer to the AMT Client structure.
 * @param[in] p_ble_evt   Pointer to the BLE event received.
 */
static void on_disconnected(nrf_ble_amtc_t * p_ctx, ble_evt_t const * p_ble_evt)
{
    if (p_ctx->conn_handle != p_ble_evt->evt.gap_evt.conn_handle)
    {
        return;
    }

    p_ctx->conn_handle             = BLE_CONN_HANDLE_INVALID;
    p_ctx->peer_db.amt_cccd_handle = BLE_GATT_HANDLE_INVALID;
    p_ctx->peer_db.amt_handle      = BLE_GATT_HANDLE_INVALID;
    p_ctx->peer_db.amt_rbc_handle  = BLE_GATT_HANDLE_INVALID;
    p_ctx->bytes_rcvd_cnt          = 0;
}

void nrf_ble_amtc_on_ble_evt(nrf_ble_amtc_t * p_ctx, ble_evt_t const * p_ble_evt)
{
    if ((p_ctx == NULL) || (p_ble_evt == NULL))
    {
        return;
    }

    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GATTC_EVT_HVX:
            on_hvx(p_ctx, p_ble_evt);
            break;

        case BLE_GAP_EVT_DISCONNECTED:
            on_disconnected(p_ctx, p_ble_evt);
            break;

        case BLE_GATTC_EVT_WRITE_RSP:
            on_write_response(p_ctx, p_ble_evt);
            break;

        case BLE_GATTC_EVT_READ_RSP:
            on_read_response(p_ctx, p_ble_evt);
            break;

        default:
            break;
    }
    // Check if the event if on the link for this instance
    if (p_ctx->conn_handle != p_ble_evt->evt.gattc_evt.conn_handle)
    {
        return;
    }
    // Check if there is any message to be sent across to the peer and send it.
    tx_buffer_process();

}

/**@brief Function for creating a message for writing to the CCCD.
 */
static ret_code_t cccd_configure(uint16_t conn_handle, uint16_t handle_cccd, bool enable)
{
    NRF_LOG_DEBUG("Configuring CCCD. CCCD Handle = %d, Connection Handle = %d\r\n",
        handle_cccd, conn_handle);

    tx_message_t * p_msg;
    uint16_t       cccd_val = enable ? BLE_GATT_HVX_NOTIFICATION : 0;

    p_msg              = &m_tx_buffer[m_tx_insert_index++];
    m_tx_insert_index &= TX_BUFFER_MASK;

    p_msg->req.write_req.gattc_params.handle   = handle_cccd;
    p_msg->req.write_req.gattc_params.len      = WRITE_MESSAGE_LENGTH;
    p_msg->req.write_req.gattc_params.p_value  = p_msg->req.write_req.gattc_value;
    p_msg->req.write_req.gattc_params.offset   = 0;
    p_msg->req.write_req.gattc_params.write_op = BLE_GATT_OP_WRITE_REQ;
    p_msg->req.write_req.gattc_value[0]        = LSB_16(cccd_val);
    p_msg->req.write_req.gattc_value[1]        = MSB_16(cccd_val);
    p_msg->conn_handle                         = conn_handle;
    p_msg->type                                = WRITE_REQ;

    tx_buffer_process();

    return NRF_SUCCESS;
}

ret_code_t nrf_ble_amtc_notif_enable(nrf_ble_amtc_t * p_ctx)
{
    VERIFY_PARAM_NOT_NULL(p_ctx);

    if (p_ctx->conn_handle == BLE_CONN_HANDLE_INVALID)
    {
        return NRF_ERROR_INVALID_STATE;
    }

    return cccd_configure(p_ctx->conn_handle, p_ctx->peer_db.amt_cccd_handle, true);
}

ret_code_t nrf_ble_amtc_rcb_read(nrf_ble_amtc_t * p_ctx)
{
    VERIFY_PARAM_NOT_NULL(p_ctx);

    if (p_ctx->conn_handle == BLE_CONN_HANDLE_INVALID)
    {
        return NRF_ERROR_INVALID_STATE;
    }

    NRF_LOG_DEBUG("Reading RCB characteristic.\r\n");

    tx_message_t * p_msg = &m_tx_buffer[m_tx_insert_index++];

    p_msg->req.read_handle = p_ctx->peer_db.amt_rbc_handle;
    p_msg->conn_handle     = p_ctx->conn_handle;
    p_msg->type            = READ_REQ;

    m_tx_insert_index &= TX_BUFFER_MASK;
    tx_buffer_process();

    return NRF_SUCCESS;
}

/** @}
 *  @endcond
 */


text:
set vc_version=2008
build_win20xx.bat


text:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

N = 100
industry = ['a','b','c']
city = ['x','y','z']
ind = np.random.choice(industry, N)
cty = np.random.choice(city, N)
jobs = np.random.randint(low=1,high=250,size=N)
df_city =pd.DataFrame({'industry':ind,'city':cty,'jobs':jobs})

## how many panels do we need?
cols =df_city.city.value_counts().shape[0]
fig, axes = plt.subplots(1, cols, figsize=(8, 8))

for x, city in enumerate(df_city.city.value_counts().index.values):
    data = df_city[(df_city['city'] == city)]
    data = data.groupby(['industry']).jobs.sum()
    print (data)
    print type(data.index)
    left=  [k[0] for k in enumerate(data)]
    right=  [k[1] for k in enumerate(data)]

    axes[x].bar(left,right,label="%s" % (city))
    axes[x].set_xticks(left, minor=False)
    axes[x].set_xticklabels(data.index.values)

    axes[x].legend(loc='best')
    axes[x].grid(True)
    fig.suptitle('Employment By Industry By City', fontsize=20)
plt.show(1)

from ggplot import *

print ggplot(aes(x='city'), data=df_city) + geom_bar() + facet_grid(x=None, y="city", nrow=1)


text:
var expect = require('chai').expect,
  unique = require('../lib/unique.js');

describe('unique', function() {
  it ('shold return false if array of objects is not unique.', function(done) {
		unique([{test:{ing:123}},{test:{ing:123}}], function(res) {
			expect(res).to.be.false;
			done();
		});
	})
	it ('shold return true if array of objects is unique.', function(done) {
		unique([{test:{ing:123}},{test:{ing:456}}], function(res) {
			expect(res).to.be.true;
			done();
		});
	})
});


text:
--------------------------------
--
-- @function [parent=#PhysicsJoint] getBodyB
-- @param self
-- @return PhysicsBody#PhysicsBody ret (return value: cc.PhysicsBody)

--------------------------------
--  Get the max force setting
-- @function [parent=#PhysicsJoint] getMaxForce
-- @param self
-- @return float#float ret (return value: float)

--------------------------------
--  Set the max force between two bodies
-- @function [parent=#PhysicsJoint] setMaxForce
-- @param self
-- @param #float force
-- @return PhysicsJoint#PhysicsJoint self (return value: cc.PhysicsJoint)

--------------------------------
--
-- @function [parent=#PhysicsJoint] isEnabled
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
--  Enable/Disable the joint
-- @function [parent=#PhysicsJoint] setEnable
-- @param self
-- @param #bool enable
-- @return PhysicsJoint#PhysicsJoint self (return value: cc.PhysicsJoint)

--------------------------------
--  Enable/disable the collision between two bodies
-- @function [parent=#PhysicsJoint] setCollisionEnable
-- @param self
-- @param #bool enable
-- @return PhysicsJoint#PhysicsJoint self (return value: cc.PhysicsJoint)

--------------------------------
--
-- @function [parent=#PhysicsJoint] getWorld
-- @param self
-- @return PhysicsWorld#PhysicsWorld ret (return value: cc.PhysicsWorld)

--------------------------------
--
-- @function [parent=#PhysicsJoint] setTag
-- @param self
-- @param #int tag
-- @return PhysicsJoint#PhysicsJoint self (return value: cc.PhysicsJoint)

--------------------------------
--  Remove the joint from the world
-- @function [parent=#PhysicsJoint] removeFormWorld
-- @param self
-- @return PhysicsJoint#PhysicsJoint self (return value: cc.PhysicsJoint)

--------------------------------
--
-- @function [parent=#PhysicsJoint] isCollisionEnabled
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
--
-- @function [parent=#PhysicsJoint] getTag
-- @param self
-- @return int#int ret (return value: int)

return nil


text:
package org.glowroot.agent.plugin.jdbc.message;

import org.glowroot.agent.plugin.api.QueryMessage;
import org.glowroot.agent.plugin.api.QueryMessageSupplier;

public class BatchPreparedStatementMessageSupplier2 extends QueryMessageSupplier {

    private final int batchSize;

    public BatchPreparedStatementMessageSupplier2(int batchSize) {
        this.batchSize = batchSize;
    }

    @Override
    public QueryMessage get() {
        String prefix;
        if (batchSize > 1) {
            // print out number of batches to make it easy to identify
            prefix = "jdbc query: " + batchSize + " x ";
        } else {
            prefix = "jdbc query: ";
        }
        return QueryMessage.create(prefix);
    }
}


text:
/* sysv_api.c - implements the obsolete System V signal API using POSIX.
 *
 * Previously, both System V and BSD had its own signal API. POSIX defined a
 * standard API for handling signals on UNIX systems which defined a more powerful
 * way of changing signal dispositions, restarting interrupted system calls,
 * among other improvements.
 *
 * This program implements the - now obsolete - System V API using standard POSIX
 * signal API. It accepts a numeric command line argument that tells it what
 * to do. Each number tests one or more functions from the System V API. Refer to
 * the usage guide for information on the available options.
 *
 * Usage
 *
 *    $ ./sysv_api <numop>
 *    numop - the operation number that defines the program behavior. Possible values are:
 *
 *      1 - sigset    - Changes SIGINT disposition.
 *      2 - sighold   - Blocks SIGINT.
 *      3 - sigrelse  - Blocks SIGINT and then removes it from the process signal procmask.
 *      4 - sigignore - Igores SIGINT.
 *      5 - sigpause  - suspends execution until SIGINT is received.
 *
 * All operations will wait for a SIGINT before finishing so that the function
 * implementation can be verified.
 *
 * Author: Renato Mascarenhas Costa
 */

#define _XOPEN_SOURCE 700

#include <limits.h>
#ifndef LONG_MIN
#  include <linux/limits.h>
#endif

#include <unistd.h>
#include <signal.h>
#include <errno.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef void (*sighandler_t)(int);

enum { SIGSET = 1, SIGHOLD = 2, SIGRELSE = 3, SIGIGNORE = 4, SIGPAUSE = 5 };

static void helpAndLeave(const char *progname, int status);
static void pexit(const char *fCall);

static void handler(int sig);

static sighandler_t _sigset(int sig, sighandler_t handler);
static int _sighold(int sig);
static int _sigrelse(int sig);
static int _sigignore(int sig);
static int _sigpause(int sig);

int
main(int argc, char *argv[]) {
  if (argc != 2) {
    helpAndLeave(argv[0], EXIT_FAILURE);
  }

  char *endptr;
  long operation;
  struct sigaction action;

  operation = strtol(argv[1], &endptr, 10);
  if (operation == LONG_MIN || operation == LONG_MAX || endptr == argv[1] || operation < 1 || operation > 4) {
    fprintf(stderr, "%s: invalid operation %s\n", argv[0], argv[1]);
    exit(EXIT_FAILURE);
  }

  switch (operation) {
    case SIGSET:
      if (_sigset(SIGINT, handler) == (sighandler_t) -1) {
        pexit("_sigset");
      }

      printf("Changed disposition of SIGSET. Type Ctrl-C to see its handler.\n");
      pause();

      break;
    case SIGHOLD:
      if (_sighold(SIGINT) == -1) {
        pexit("_sighold");
      }

      printf("SIGINT is blocked. Ctrl-C will not stop this process.\n");
      pause();
      break;

    case SIGRELSE:
      if (_sighold(SIGINT) == -1) {
        pexit("_sighold");
      }
      printf("SIGINT blocked\n");

      if (_sigrelse(SIGINT) == -1) {
        pexit("_sigrelse");
      }
      printf("SIGINT unblocked. You can now finish this process with Ctrl-C\n");
      pause();
      break;

    case SIGIGNORE:
      if (_sigignore(SIGINT) == -1) {
        pexit("_sigignore");
      }
      printf("SIGINT is ignored. Ctrl-C will not stop this process\n");
      pause();
      break;

    case SIGPAUSE:
      action.sa_handler = handler;

      if (sigaction(SIGINT, &action, NULL) == -1) {
        pexit("sigaction");
      }

      printf("Suspending process until you hit Ctrl-C...\n");
      _sigpause(SIGINT);
      printf("Execution is back\n");
      break;
  }

  exit(EXIT_SUCCESS);
}

static sighandler_t
_sigset(int sig, sighandler_t handler) {
  sigset_t blocked_signals;
  struct sigaction act, oldact;

  if (sigprocmask(SIG_BLOCK, NULL, &blocked_signals) == -1) {
    return (sighandler_t) -1;
  }

  act.sa_handler = handler;
  if (sigaction(sig, &act, &oldact) == -1) {
    return (sighandler_t) -1;
  }

  if (handler == SIG_HOLD) {
    _sighold(sig);
    return oldact.sa_handler;
  }

  if (sigismember(&blocked_signals, sig)) {
    return SIG_HOLD;
  } else {
    return oldact.sa_handler;
  }
}

static int
_sighold(int sig) {
  sigset_t block_mask;

  sigemptyset(&block_mask);
  sigaddset(&block_mask, sig);

  return sigprocmask(SIG_BLOCK, &block_mask, NULL);
}

static int
_sigrelse(int sig) {
  sigset_t unblock_mask;

  sigemptyset(&unblock_mask);
  sigaddset(&unblock_mask, sig);

  return sigprocmask(SIG_UNBLOCK, &unblock_mask, NULL);
}

static int
_sigignore(int sig) {
  struct sigaction action;

  action.sa_handler = SIG_IGN;
  return sigaction(sig, &action, NULL);
}

static int
_sigpause(int sig) {
  sigset_t mask;
  if (sigprocmask(SIG_SETMASK, NULL, &mask) == -1) {
    pexit("sigprocmask");
  }

  sigdelset(&mask, sig);

  return sigsuspend(&mask);
}

static void
handler(__attribute__((unused)) int sig) {
  /* UNSAFE: uses printf(3) */
  printf("\tSIGINT received\n");
}

static void
helpAndLeave(const char *progname, int status) {
  FILE *stream = stderr;

  if (status == EXIT_SUCCESS) {
    stream = stdout;
  }

  fprintf(stream, "Usage: %s <numop>\n", progname);
  fprintf(stream, "\t1 - sighold   - Blocks SIGINT\n");
  fprintf(stream, "\t2 - sigrelse  - Blocks SIGINT and then removes it from the process procmask\n");
  fprintf(stream, "\t3 - sigignore - Ignores SIGINT\n");
  fprintf(stream, "\t4 - sigpause  - suspends execution until SIGINT is received\n");

  exit(status);
}

static void
pexit(const char *fCall) {
  perror(fCall);
  exit(EXIT_FAILURE);
}


text:
'''
Created on 09.04.2015

@author: marscher
'''
from pyemma.coordinates.transform.transformer import Transformer
import numpy as np
import functools

class ReaderInterface(Transformer):
    """basic interface for readers
    """

    def __init__(self, chunksize=100):
        super(ReaderInterface, self).__init__(chunksize=chunksize)
        # needs to be set, to ensure some getters of Transformer will work.
        self._data_producer = self

        # internal counters
        self._t = 0
        self._itraj = 0

        # lengths and dims
        # NOTE: children have to make sure, they set these attributes in their ctor
        self._ntraj = -1
        self._ndim = -1
        self._lengths = []

        # storage for arrays (used in _add_array_to_storage)
        self._data = []

    @Transformer.data_producer.setter
    def data_producer(self, value):
        self._logger.warning("tried to set data_producer in reader, which makes"
                             " no sense.")
        import inspect
        res = inspect.getouterframes(inspect.currentframe())[1]
        self._logger.debug(str(res))

    def number_of_trajectories(self):
        """
        Returns the number of trajectories

        :return:
            number of trajectories
        """
        return self._ntraj

    def trajectory_length(self, itraj, stride=1):
        """
        Returns the length of trajectory

        :param itraj:
            trajectory index
        :param stride:
            return value is the number of frames in trajectory when
            running through it with a step size of `stride`

        :return:
            length of trajectory
        """
        return (self._lengths[itraj] - 1) // int(stride) + 1

    def trajectory_lengths(self, stride=1):
        """
        Returns the length of each trajectory

        :param stride:
            return value is the number of frames in trajectories when
            running through them with a step size of `stride`

        :return:
            numpy array containing length of each trajectory
        """
        return np.array([(l - 1) // stride + 1 for l in self._lengths], dtype=int)

    def n_frames_total(self, stride=1):
        """
        Returns the total number of frames, over all trajectories

        :param stride:
            return value is the number of frames in trajectories when
            running through them with a step size of `stride`

        :return:
            the total number of frames, over all trajectories
        """
        if stride == 1:
            return np.sum(self._lengths)
        else:
            return sum(self.trajectory_lengths(stride))

    def dimension(self):
        """
        Returns the number of output dimensions

        :return:
        """
        return self._ndim

    def _add_array_to_storage(self, array):
        """
        checks shapes, eg convert them (2d), raise if not possible
        after checks passed, add array to self._data
        """

        if array.ndim == 1:
            array = np.atleast_2d(array).T
        elif array.ndim == 2:
            pass
        else:
            shape = array.shape
            # hold first dimension, multiply the rest
            shape_2d = (shape[0],
                        functools.reduce(lambda x, y: x * y, shape[1:]))
            array = np.reshape(array, shape_2d)

        self._data.append(array)

    # handle abstract methods and special cases
    def map(self, X):
        raise NotImplementedError("a reader can not map data, it is a data source")

    def _map_array(self, X):
        raise NotImplementedError("a reader can not map data, it is a data source")

    def _param_add_data(self, *args, **kwargs):
        raise NotImplementedError("a reader is not meant to be parameterized by data")


text:
'use strict';

var async = require('async');

// Fetch all document leaf revisions from source that are missed at target.
// Use previously calculated revisions difference which defined all missed documents and their
// revisions.
module.exports = function(options, config, state, callback) {
  if (typeof config === 'function') {
    callback = config;
    config = {};
    state = {};
  }
  if (typeof state === 'function') {
    callback = state;
    state = {};
  }

  state.docs = [];
  state.docs_read = state.docs_read || 0;

  // only process if we have changed docs
  if (!state.changedDocs) {
    return callback(null, {
      ok: true,
      docs: state.docs
    });
  }

  var missingRevs = state.changedDocs;
  var ids = Object.keys(missingRevs);

  // abort on empty changed docs
  if (!ids.length) {
    return callback(null, {
      ok: true,
      docs: state.docs
    });
  }

  // To fetch the document make `GET /{db}/{docid}` request with the following
  // query parameters:
  //
  // `revs=true`: Instructs the source to include list of all known revisions into
  // the document at _revisions field. This information is needed to synchronize
  // document's ancestors history between source and target.
  //
  // The open_revs query parameter contains value as JSON array with list of
  // leaf revisions that are need to be fetched. If specified revision
  // exists, document is returned for this revision. Otherwise, source
  // returns object with single field missing with missed revision as
  // value. In case when document contains attachments source returns
  // information only for those ones that had been changed (added or updated)
  // since specified revision values. If attachment was deleted, document
  // has stub information for him.
  //
  // `latest=true` ensures that source will return latest document
  // revision regardless which one was specified in `open_revs` query
  // parameter. This parameter solves race condition problem when
  // requested document may be changed in between this step and handling
  // related event on changes feed.
  function fetch(id, next) {
    options.source.get(id, {
      revs: true,
      attachments: true,
      latest: true,
      open_revs: JSON.stringify(state.changedDocs[id].missing)
    }, next);
  }

  function fetchSingleDocuments(ids, next) {
    if (!ids.length) {
      return next(null);
    }

    async.mapLimit(ids, config.max_requests || 4, fetch, function(err, body) {
      if (err) {
        return next(err);
      }

      var docs = body.reduce(function(memo, arr) {
        return arr.reduce(function(m, d) {
          if (d.ok) {
            m.push(d.ok);
          }
          return m;
        }, memo);
      }, []);

      state.docs = state.docs.concat(docs);
      state.docs_read += docs.length;

      next(null);
    });
  }

  // A limited case of the above-mentioned bulk-get optimization is possible
  // with the current API: revisions of generation 1 (revision ID starts with
  // "1-") can be fetched in bulk via _all_docs, because by definition they have
  // no revision histories. Unfortunately _all_docs can't include attachment
  // bodies, so if it returns a document whose JSON indicates it has
  // attachments, those will have to be fetched separately. Nonetheless, this
  // optimization can help significantly, and is currently implemented in
  // TouchDB.
  function fetchGenerationOne(ids, next) {
    if (!ids.length) {
      return next(null);
    }

    options.source.allDocs({
      keys: ids,
      include_docs: true
    }, function(err, result) {
      if (err) {
        return next(err);
      }

      // Collect documents which have to be fetched again using single fetch.
      // Those are documents which
      // * are deleted
      // * have attachments
      // * or have changed since the current batch
      var docs = result.rows.reduce(function(memo, row) {
        var outstanding = row.value.deleted ||
          (row.doc._attachments && Object.keys(row.doc._attachments).length > 0) ||
          parseInt(row.doc._rev, 10) > 1;

        if (outstanding) {
          memo.outstandingIds.push(row.id);
          return memo;
        }

        row.doc._revisions = {
          start: 1,
          ids: [
            row.doc._rev.split('-')[1]
          ]
        };
        memo.completedDocs.push(row.doc);

        return memo;
      }, { completedDocs: [], outstandingIds: [] });

      state.docs = state.docs.concat(docs.completedDocs);
      state.docs_read += docs.completedDocs.length;

      if (!docs.outstandingIds.length) {
        return next(null);
      }

      fetchSingleDocuments(docs.outstandingIds, next);
    });
  }

  // TODO: think about fetching revisions and attachments via multipart/related request
  //       or fetch attachments via standalone attachments api

  var generationOneIds = ids.filter(function(id) {
    var missing = missingRevs[id].missing;
    return missing.length === 1 && parseInt(missing[0], 10) === 1;
  });

  fetchGenerationOne(generationOneIds, function(err) {
    if (err) {
      return callback(err);
    }

    var otherIds = ids.filter(function(id) {
      var missing = missingRevs[id].missing;
      return missing.length > 1 || parseInt(missing[0], 10) > 1;
    });

    fetchSingleDocuments(otherIds, function(err) {
      if (err) {
        return callback(err);
      }

      // only process if we have docs to upload
      if (!state.docs || !state.docs.length) {
        return callback(null, {
          ok: true,
          docs: []
        });
      }

      callback(null, {
        ok: true,
        docs: state.docs
      });
    });
  });
};


text:
#pragma once

#include <map>
#include <memory>
#include <string>

#include <mos/gfx/character.hpp>
#include <mos/gfx/font.hpp>
#include <mos/gfx/mesh.hpp>
#include <mos/gfx/model.hpp>

namespace mos::gfx {

/** Text for rendering. */
class Text final {
public:
  Text(const std::string &txt, Font font,
       const glm::mat4 &transform = glm::mat4(1.0f), float spacing = 0.0f,
       float opacity = 1.0f, float roughness = 1.0f, float metallic = 0.0f,
       const glm::vec3 &emission = glm::vec3(0.0f));

  /** Set text. */
  auto text(const std::string &text) -> void;

  /** Get text. */
  auto text() const -> std::string;

  /** Approximate width. */
  auto width() const -> float;

  /** Approximate height. */
  auto height() const -> float;

  /** Set position */
  auto position(const glm::vec2 &position) -> void;

  /** Set position */
  auto position(const glm::vec3 &position) -> void;

  /** Get position. */
  auto position() const -> glm::vec2;

  /** Set scale. */
  auto scale(float scale) -> void;

  /** Set transform */
  auto transform(const glm::mat4 &transform) -> void;

  /** Get transform */
  auto transform() const -> glm::mat4;

  /** Get model. */
  auto model() const -> Model;

  /** Set opacity. */
  auto opacity(float opacity) -> void;

  /** Set if the text is emissive. */
  auto emission(const glm::vec3 &emission) -> void;

  /** Get the font. */
  auto font() const -> Font;

  float spacing;

  auto operator=(const std::string &input) -> Text &;

  auto operator+=(const std::string &input) -> Text &;

private:
  Model model_;
  std::string text_;
  Font font_;
};
} // namespace mos::gfx


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';

class Events extends REST_Controller {
	function __construct()
    {
        // Construct the parent class
        parent::__construct();
    }

	public function find_get()
    {
    	$id = $this->get('id');
        // If the id parameter doesn't exist return all the events
        if ($id === NULL)
        {
            $events = $this->db->get("events");
            $this->response($events, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
        } else {
            $event = $this->db->get_where("events", array('id' => $id));
            if($event === NULL) {

	            $this->set_response([
	                'status' => FALSE,
	                'message' => 'User could not be found'
	            ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code

            } else {
        		$this->response($event, REST_Controller::HTTP_OK);
            }
        }
    }
}


text:
.class Lcom/android/server/notification/NotificationManagerService$5;
.super Landroid/service/vr/IVrStateCallbacks$Stub;
.source "NotificationManagerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/notification/NotificationManagerService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/notification/NotificationManagerService;

# direct methods
.method constructor <init>(Lcom/android/server/notification/NotificationManagerService;)V
    .locals 0

    iput-object p1, p0, Lcom/android/server/notification/NotificationManagerService$5;->this$0:Lcom/android/server/notification/NotificationManagerService;

    invoke-direct {p0}, Landroid/service/vr/IVrStateCallbacks$Stub;-><init>()V

    return-void
.end method

# virtual methods
.method public onVrStateChanged(Z)V
    .locals 2

    iget-object v1, p0, Lcom/android/server/notification/NotificationManagerService$5;->this$0:Lcom/android/server/notification/NotificationManagerService;

    invoke-static {v1}, Lcom/android/server/notification/NotificationManagerService;->-get19(Lcom/android/server/notification/NotificationManagerService;)Lcom/android/server/notification/NotificationManagerService$NotificationListeners;

    move-result-object v0

    if-eqz p1, :cond_0

    if-eqz v0, :cond_0

    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Lcom/android/server/notification/NotificationManagerService$NotificationListeners;->rebindServices(Z)V

    :cond_0
    return-void
.end method


text:
package utilities;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import utilities.internal.ConsoleReader;
import utilities.internal.CustomToStringBuilder;
import utilities.internal.DatabaseUtil;

public class QueryDatabase {

	public static void main(String[] args) throws Throwable {
		DatabaseUtil databaseUtil;
		ConsoleReader reader;
		String line;
		boolean quit;

		databaseUtil = null;

		try {
			System.out.printf("QueryDatabase 1.3%n");
			System.out.printf("-----------------%n%n");

			System.out.printf("Initialising persistence context `%s'...%n", DatabaseConfig.PersistenceUnit);
			databaseUtil = new DatabaseUtil();

			reader = new ConsoleReader();

			do {
				line = reader.readCommand();
				quit = interpretLine(databaseUtil, line);
			} while (!quit);
		} catch (Throwable oops) {
			System.out.flush();
			System.err.printf("%n%s%n", oops.getLocalizedMessage());
			//oops.printStackTrace(System.out);
		} finally {
			databaseUtil.close();
		}
	}

	private static boolean interpretLine(DatabaseUtil databaseUtil, String line) {
		boolean result;
		String command;
		List<?> objects;
		int affected;

		result = false;
		try {
			command = StringUtils.substringBefore(line, " ");
			switch (command) {
				case "quit":
					result = true;
					break;
				case "begin":
					databaseUtil.openTransaction();
					System.out.println("Transaction started");
					break;
				case "commit":
					databaseUtil.commitTransaction();
					System.out.println("Transaction committed");
					break;
				case "rollback":
					databaseUtil.rollbackTransaction();
					System.out.println("Transaction rollbacked");
					break;
				case "update":
				case "delete":
					affected = databaseUtil.executeUpdate(line);
					System.out.printf("%d objects affected%n", affected);
					break;
				case "select":
					objects = databaseUtil.executeSelect(line);
					System.out.printf("%d objects found%n", objects.size());
					printResultList(objects);
					break;
				default:
					System.err.println("Command not understood");
			}
		} catch (Throwable oops) {
			System.err.println(oops.getMessage());
			// oops.printStackTrace(System.err);
		}

		return result;
	}

	private static void printResultList(List<?> objects) {
		String text;
		Object obj;

		for (int i = 0; i < objects.size(); i++) {
			obj = objects.get(i);
			text = CustomToStringBuilder.toString(obj);
			System.out.printf("Object #%d = %s %n", i, text);
		}
	}

}


text:
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
<TITLE>GNU gettext utilities - Footnotes</TITLE>

GNU gettext tools, version 0.19.4

Native Language Support Library and Tools

Edition 0.19.4, 9 December 2014

<ADDRESS>Ulrich Drepper</ADDRESS>
<ADDRESS>Jim Meyering</ADDRESS>
<ADDRESS>François Pinard</ADDRESS>
<ADDRESS>Bruno Haible</ADDRESS>

(1)

In this manual, all mentions of Emacs
refers to either GNU Emacs or to XEmacs, which people sometimes call FSF
Emacs and Lucid Emacs, respectively.

(2)

This
limitation is not imposed by GNU gettext, but is for compatibility
with the msgfmt implementation on Solaris.

(3)

Some
system, e.g. mingw, don't have LC_MESSAGES.  Here we use a more or
less arbitrary value for it, namely 1729, the smallest positive integer
which can be represented in two different ways as the sum of two cubes.

(4)

When the system does not support setlocale its behavior
in setting the locale values is simulated by looking at the environment
variables.

(5)

Additions are welcome.  Send appropriate information to
bug-gnu-gettext@gnu.org and bug-glibc-manual@gnu.org.

(6)

you can also use it through the
<SAMP>‘MSGMERGE_OPTIONS’</SAMP> option from <TT>‘Makevars’</TT>

This document was generated on 24 December 2014 using the
texi2html
translator version 1.52b.


text:
package org.spongepowered.common;

import com.google.inject.Inject;
import net.minecraft.server.dedicated.DedicatedServer;
import org.spongepowered.api.Platform;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandManager;
import org.spongepowered.api.service.ServiceManager;
import org.spongepowered.api.service.ban.BanService;
import org.spongepowered.api.service.pagination.PaginationService;
import org.spongepowered.api.service.permission.PermissionService;
import org.spongepowered.api.service.rcon.RconService;
import org.spongepowered.api.service.sql.SqlService;
import org.spongepowered.api.service.user.UserStorageService;
import org.spongepowered.api.service.whitelist.WhitelistService;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.common.command.SpongeCommands;
import org.spongepowered.common.service.ban.SpongeBanService;
import org.spongepowered.common.service.pagination.SpongePaginationService;
import org.spongepowered.common.service.rcon.MinecraftRconService;
import org.spongepowered.common.service.sql.SqlServiceImpl;
import org.spongepowered.common.service.user.SpongeUserStorageService;
import org.spongepowered.common.service.whitelist.SpongeWhitelistService;
import org.spongepowered.common.text.action.SpongeCallbackHolder;
import org.spongepowered.common.util.SpongeUsernameCache;

/**
 * Used to setup the ecosystem.
 */
@NonnullByDefault
public final class SpongeBootstrap {

    @Inject private static ServiceManager serviceManager;
    @Inject private static CommandManager commandManager;

    public static void initializeServices() {
        registerService(SqlService.class, new SqlServiceImpl());
        registerService(PaginationService.class, new SpongePaginationService());
        if (SpongeImpl.getGame().getPlatform().getType() == Platform.Type.SERVER) {
            registerService(RconService.class, new MinecraftRconService((DedicatedServer) Sponge.getServer()));
        }
        registerService(UserStorageService.class, new SpongeUserStorageService());
        registerService(BanService.class, new SpongeBanService());
        registerService(WhitelistService.class, new SpongeWhitelistService());
        SpongeInternalListeners.getInstance().registerServiceCallback(PermissionService.class, input -> SpongeImpl.getGame().getServer().getConsole().getContainingCollection());
        SpongeUsernameCache.load();
    }

    public static void initializeCommands() {
        commandManager.register(SpongeImpl.getPlugin(), SpongeCommands.createSpongeCommand(), "sponge", "sp");
        commandManager.register(SpongeImpl.getPlugin(), SpongeCommands.createHelpCommand(), "help", "?");
        commandManager.register(SpongeImpl.getPlugin(), SpongeCallbackHolder.getInstance().createCommand(), SpongeCallbackHolder.CALLBACK_COMMAND);
    }

    private static <T> void registerService(Class<T> serviceClass, T serviceImpl) {
        serviceManager.setProvider(SpongeImpl.getPlugin(), serviceClass, serviceImpl);
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>ICCM 2014 Union Square Local/Tourist Map</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
        <link rel="stylesheet" href="css/main.css">


text:
FROM alpine:3.16
ARG NCPU=4

## [BEGIN packaging.md]

# Install the minimal development tools, libcurl, and OpenSSL:

# ```bash
RUN apk update && \
    apk add bash ca-certificates ccache cmake curl git \
        gcc g++ make tar unzip zip zlib-dev
# ```

# Alpine's version of `pkg-config` (https://github.com/pkgconf/pkgconf) is slow
# when handling `.pc` files with lots of `Requires:` deps, which happens with
# Abseil, so we use the normal `pkg-config` binary, which seems to not suffer
# from this bottleneck. For more details see
# https://github.com/pkgconf/pkgconf/issues/229 and
# https://github.com/googleapis/google-cloud-cpp/issues/7052.

# ```bash
WORKDIR /var/tmp/build/pkg-config-cpp
RUN curl -sSL https://pkgconfig.freedesktop.org/releases/pkg-config-0.29.2.tar.gz | \
    tar -xzf - --strip-components=1 && \
    ./configure --with-internal-glib && \
    make -j ${NCPU:-4} && \
    make install
ENV PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig:/usr/local/lib/pkgconfig:/usr/lib64/pkgconfig
# ```

# #### Dependencies

# The versions of Abseil, Protobuf, gRPC, OpenSSL, and nlohmann-json included
# with Alpine >= 3.16 meet `google-cloud-cpp`'s requirements. We can simply
# install the development packages

# ```bash
RUN apk update && \
    apk add abseil-cpp-dev c-ares-dev curl-dev grpc-dev \
        protobuf-dev nlohmann-json openssl-dev re2-dev
# ```

# #### crc32c

# The project depends on the Crc32c library, we need to compile this from
# source:

# ```bash
WORKDIR /var/tmp/build/crc32c
RUN curl -sSL https://github.com/google/crc32c/archive/1.1.2.tar.gz | \
    tar -xzf - --strip-components=1 && \
    cmake \
        -DCMAKE_BUILD_TYPE=Release \
        -DBUILD_SHARED_LIBS=yes \
        -DCRC32C_BUILD_TESTS=OFF \
        -DCRC32C_BUILD_BENCHMARKS=OFF \
        -DCRC32C_USE_GLOG=OFF \
        -S . -B cmake-out && \
    cmake --build cmake-out -- -j ${NCPU:-4} && \
    cmake --build cmake-out --target install -- -j ${NCPU:-4}
# ```

## [DONE packaging.md]


text:
require 'unit_spec_helper'

describe Rpush::Client::Redis::Wns::BadgeNotification do
  it_behaves_like 'Rpush::Client::Wns::BadgeNotification'
end if redis?


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Penicillium fasciculare Berk. & Broome

### Remarks
null


text:
package com.pantor.blink.msg.blink;

public class F64 extends TypeDef
{

}


text:
date: 2008-01-24
type: "Internal"
title: Forums are back online!
---
After months of returning error messages to users who went to
opensource.cse.ohio-state.edu/forum, the [Open Source Club forums](http://opensource.cse.ohio-state.edu/forum "Click here to enter our forums")
are back online. This past summer, p0rn and pharmaceutical spammers had a
field day, then our website got taken offline and we had to disable forums and
comments. We have cleaned up some lingering spam comments, re-enabled the forum,
and added a captcha requirement in order for anyone to log in, as well as a few
other random things. Spamming in the forums will absolutely not be tolerated. If
you find any spam on this site, please report it [here](http://opensource.cse.ohio-state.edu/forum/21)
and a moderator will delete it and block/delete the offending user's account.

For the time being, only *.edu e-mail addresses may register* but if you have a
current account with another address that you already registered then it should
still be active. If you do not have a `.edu` address and would like access to
the forum, you can [contact me](http://opensource.cse.ohio-state.edu/contact "Contact us")
or another administrator telling us your e-mail address before you try to create
the account so we can authorize it. *Please* only do this if you do not have a
`.edu` address. Otherwise, we ask that you use your school address for
registering. We use this to keep track of users (e.g. someone with a
`name.#@osu.edu` is less likely to be a spammer than `admin@viagra.com` or
`cmbb@dbx.hk`) and to restrict spammers from creating accounts just to hose
the page with inappropriate content.


text:
from django.conf import settings
from django.template import RequestContext
from django.shortcuts import render_to_response

import urllib
import json

# create your views here

def example(request):
    return render_to_response('{{ app_name }}/example.html', context_instance=RequestContext(request))

def test(request):
    return render_to_response('{{ app_name }}/test.html', context_instance=RequestContext(request))


text:
layout: post
title: How to parallelize a web crawler
categories: [crawler]
tags: [crawler, Puppeteer]
description: Second post of a series about crawlers. We present how to parallelize a crawler based on Chrome headless and Puppeteer to take screenshots of the home page of the 100 most popular websites.
published: true
---

In the first post of this series we
presented a simple crawler based on Puppeteer and Chrome headless.
We showed that while it was simple to crawl 100 pages to take a screenshot of their home page, it still required more than 8 minutes.
In this post, we explain how we can make our crawler faster by parallelizing it.

## Parallelization: Browsers vs pages
We can use two strategies to parallelize our crawler on a single machine:
1. Create more instance of Chrome headless;
2. Increase the number of simultaneous pages per browser.

We can combine the two approaches, i.e. increasing both the number of Chrome headless instances and the number of
simultaneous pages per browser.
Be careful to adapt the number of browser instances and pages based on the characteristic of your machine, otherwise
adding more browser instances will only degrade the performance.
Moreover, you should not open too many pages per browser since a crash of a page may bring down all the pages of this browser.
Browserless, a company providing crawling services
even advises to run only a single page per browser.
I have also noticed an increase in the frequency of bugs when I use more than 8-9 pages per browser in my experiments.

Creating a single page per browser to parallelize may add overhead since browser instances consume more resources than pages.
In this post, we define the number of browsers and the number of pages per browser as parameters so that they can be
modified depending on your machine and your needs.

## Code of the parallel crawler

We use the same function as in the previous article to read the list of URLs.
```javascript
const fs = require('fs');

function readURLFile(path) {
    return fs.readFileSync(path, 'utf-8')
        .split('\n')
        .map((elt) => {
            const url = elt.split(',')[1].replace('\r', '');
            return `http://${url.toLowerCase()}`;
        });
}
```

Then, we modify the code of the crawler presented in the first post of the series to make it parallel.
We define the number of browsers to create in a variable called `NUM_BROWSERS` and the number of pages per browser in
the `NUM_PAGES` variable.
First, in the outer loop, we launch `NUM_BROWSERS` instances of Chrome headless.
We associate a promise to each of these browsers and we store the promise in the `promisesBrowsers` array.
Then, in the inner loop, for each browser, we create `NUM_PAGES` pages.
For each of these browsers and pages, we also associate a promise that we store in the `promisesPages` variable.
While there are URLs to fetch, i.e. `while (urls.length > 0)`, each page get an URL from the `urls` array, visit it,
and take a screenshot using the same code as the non-parallelized crawler.
When all the URLs have been processed, we resolve the pages promises using `resPage()`, we close the browser and we
resolve every browser promises using `resBrowser`.

```javascript
const puppeteer = require('puppeteer');

const NUM_BROWSERS = 2;
const NUM_PAGES = 3;

(async () => {
    const startDate = new Date().getTime();
    const USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3239.108 Safari/537.36';
    const urls = readURLFile('./urls.csv');

    const promisesBrowsers = [];
    for (let numBrowser= 0; numBrowser < NUM_BROWSERS; numBrowser++) {
        promisesBrowsers.push(new Promise(async (resBrowser) => {
            const browser = await puppeteer.launch();
            const promisesPages = [];

            for (let numPage = 0; numPage < NUM_PAGES; numPage++ ) {
                promisesPages.push(new Promise(async(resPage) => {
                    while(urls.length > 0) {
                        const url = urls.pop();
                        console.log(`Visiting url: ${url}`);
                        let page = await browser.newPage();
                        await page.setUserAgent(USER_AGENT);

                        try{
                            await page.goto(url);
                            let fileName = url.replace(/(\.|\/|:|%|#)/g, "_");
                            if (fileName.length > 100) {
                                fileName = fileName.substring(0, 100);
                            }
                            await page.screenshot({ path: `./screenshots/${fileName}.jpeg`, fullPage: true });
                        } catch(err) {
                            console.log(`An error occured on url: ${url}`);
                        } finally {
                            await page.close();
                        }
                    }

                    resPage();
                }));
            }

            await Promise.all(promisesPages);
            await browser.close();
            resBrowser();
        }));
    }

    await Promise.all(promisesBrowsers);
    console.log(`Time elapsed ${Math.round((new Date().getTime() - startDate) / 1000)} s`);

})();
```

We ran the code on the same MacBook Pro with a 4 cores i5 (2.3 GHz) connected to a gigabit connection via ethernet.
We set the number of browsers to 2 and the number of pages per browser to 3.
In total, it took 111 seconds, i.e. less than 2 minutes, to visit the 100 URLs and take a screenshot.
Compare to the non-parallelized version of the crawler, it is an improvement of 395 seconds (78%).
Thus, now it would 'only' take 13 days to crawl the top home page of the top Alexa 1M websites.