text:
date: "2021-08-03"
version: "3.11.0"
title: "v3.11 Release Notes"
---

Welcome to `gatsby@3.11.0` release (August 2021 #1)

Key highlights of this release:

- [Improvements to Parallel Query Running](#improvements-to-parallel-query-running) - Better performance and more configurable

Also check out [notable bugfixes](#notable-bugfixes--improvements).

**Bleeding Edge:** Want to try new features as soon as possible? Install `gatsby@next` and let us know
if you have any [issues](https://github.com/gatsbyjs/gatsby/issues).

[Previous release notes](/docs/reference/release-notes/v3.10)

[Full changelog](https://github.com/gatsbyjs/gatsby/compare/gatsby@3.11.0-next.0...gatsby@3.11.0)

---

## Improvements to Parallel Query Running

In case you missed it, in [3.10](/docs/reference/release-notes/v3.10) we've added experimental support for Parallel Query Running. Depending on your site you will see dramatic improvements in `gatsby build` performance. We've moved more information [into LMDB](https://github.com/gatsbyjs/gatsby/pull/32431), fixed a [bug](https://github.com/gatsbyjs/gatsby/pull/32520) and [optimized](https://github.com/gatsbyjs/gatsby/pull/32440) how we merge the state of the workers. You can also force the chunk size for each worker now by setting the `GATSBY_PARALLEL_QUERY_CHUNK_SIZE` environment variable.

To learn more about Parallel Query Running head to the [previous release notes](/docs/reference/release-notes/v3.10/#experimental-parallel-query-running).

Please give it a try and report back in the [PQR GitHub Discussion](https://github.com/gatsbyjs/gatsby/discussions/32389). We really appreciate any feedback!

## Notable bugfixes & improvements

- `gatsby`: Display message about unfit flags found in `gatsby-config.js` per [PR #32394](https://github.com/gatsbyjs/gatsby/pull/32394)
- `gatsby`: Correct pagination logic (fixing a regression) per [PR #32496](https://github.com/gatsbyjs/gatsby/pull/32496)
- `gatsby-source-shopify`: Add a query for `ShopifyLocation` and `ShopifyInventoryLevel` per [PR #32450](https://github.com/gatsbyjs/gatsby/pull/32450)
- `gatsby-plugin-mdx`: Performance improvement for a specific usage scenario (multiple GraphQL fields that require MDX processing) per [PR #32462](https://github.com/gatsbyjs/gatsby/pull/32462)
- `gatsby-source-wordpress`: Fetch referenced media items during single node updates per [PR #32381](https://github.com/gatsbyjs/gatsby/pull/32381)
- `gatsby-plugin-gatsby-cloud`: Fix bug where Incremental Builds on Gatsby Cloud would result in downloading duplicate JavaScript assets per [PR #32535](https://github.com/gatsbyjs/gatsby/pull/32535)

## Contributors

A big **Thank You** to [our community who contributed](https://github.com/gatsbyjs/gatsby/compare/gatsby@3.11.0-next.0...gatsby@3.11.0) to this release 💜

- [angeloashmore](https://github.com/angeloashmore): fix(gatsby): correct hasNextPage pagination info when resultOffset is provided [PR #32319](https://github.com/gatsbyjs/gatsby/pull/32319)
- [jvidalv](https://github.com/jvidalv): chore(docs): modified file-mock path for typescript config on unit-te… [PR #32390](https://github.com/gatsbyjs/gatsby/pull/32390)
- [kik-o](https://github.com/kik-o): chore(docs): SEO remove typos & outdated information [PR #32433](https://github.com/gatsbyjs/gatsby/pull/32433)
- [farhan443](https://github.com/farhan443): chore(docs): Fix a minor typo "with" > "will" [PR #32491](https://github.com/gatsbyjs/gatsby/pull/32491)
- [nyedidikeke](https://github.com/nyedidikeke): chore(docs): Fix typo in documentation for assetPrefix [PR #32499](https://github.com/gatsbyjs/gatsby/pull/32499)
- [xugetsu](https://github.com/xugetsu): chore(docs): Fix typo in File System Route API doc [PR #32517](https://github.com/gatsbyjs/gatsby/pull/32517)


text:
using JetBrains.ReSharper.Feature.Services.Daemon;

namespace JetBrains.ReSharper.Plugins.Unity.Shaders.ShaderLab.Daemon
{
    public abstract class ShaderLabElementProblemAnalyzer<T> : ElementProblemAnalyzer<T>
    {
        protected sealed override void Run(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            var processKind = data.GetDaemonProcessKind();
            if (processKind != DaemonProcessKind.VISIBLE_DOCUMENT && processKind != DaemonProcessKind.SOLUTION_ANALYSIS)
                return;

            Analyze(element, data, consumer);
        }

        protected abstract void Analyze(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.tensorflow;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link Shape}. */
@RunWith(JUnit4.class)
public class ShapeTest {

  @Test
  public void unknown() {
    assertEquals(-1, Shape.unknown().numDimensions());
    assertEquals("<unknown>", Shape.unknown().toString());
  }

  @Test
  public void scalar() {
    assertEquals(0, Shape.scalar().numDimensions());
    assertEquals("[]", Shape.scalar().toString());
  }

  @Test
  public void make() {
    Shape s = Shape.make(2);
    assertEquals(1, s.numDimensions());
    assertEquals(2, s.size(0));
    assertEquals("[2]", s.toString());

    s = Shape.make(2, 3);
    assertEquals(2, s.numDimensions());
    assertEquals(2, s.size(0));
    assertEquals(3, s.size(1));
    assertEquals("[2, 3]", s.toString());

    s = Shape.make(-1, 2, 3);
    assertEquals(3, s.numDimensions());
    assertEquals(-1, s.size(0));
    assertEquals(2, s.size(1));
    assertEquals(3, s.size(2));
    assertEquals("[?, 2, 3]", s.toString());
  }

  @Test
  public void nodesInAGraph() {
    try (Graph g = new Graph()) {
      Output n = TestUtil.placeholder(g, "feed", DataType.FLOAT);
      assertEquals(-1, n.shape().numDimensions());

      n = TestUtil.constant(g, "scalar", 3);
      assertEquals(0, n.shape().numDimensions());

      n = TestUtil.constant(g, "vector", new float[2]);
      assertEquals(1, n.shape().numDimensions());
      assertEquals(2, n.shape().size(0));

      n = TestUtil.constant(g, "matrix", new float[4][5]);
      assertEquals(2, n.shape().numDimensions());
      assertEquals(4, n.shape().size(0));
      assertEquals(5, n.shape().size(1));
    }
  }
}


text:
package it.nicolasanti.autoconfigure;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Italian is a great language but there is not a general rule
 * to pluralize name: this annotation let you specifiy your
 * entity class plural manually.
 *
 *
 * @author nicola
 *
 */
@Deprecated
@Retention(RetentionPolicy.RUNTIME)
public @interface Plural {
	public String value();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
(C) Copyright 2015 Somonar B.V.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 -->

<resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/ofbiz-properties.xsd">

    <property key="Configuration">
        <value xml:lang="en">Configuration</value>
        <value xml:lang="nl">Configuratie</value>
    </property>
    <property key="Gateway">
        <value xml:lang="en">Gateway</value>
    </property>
    <property key="SystemProperty">
        <value xml:lang="en">System Property</value>
        <value xml:lang="nl">Configuratie-element</value>
    </property>
    <property key="SystemProperties">
        <value xml:lang="en">System Properties</value>
        <value xml:lang="nl">Configuratie-elementen</value>
    </property>
    <property key="NewSystemProperty">
        <value xml:lang="en">New System Property</value>
        <value xml:lang="nl">Nieuw configuratie-element </value>
    </property>

</resource>


text:
.. automodule:: scenesim.objects.sso
   :members:


text:
docker start mongo
docker start sprout


text:
An Ansible role for installing [Duply](http://duply.net/). In addition, this role can be used to easily backup a directory to Amazon S3.

## Role Variables

- `duply_version` - Duply version
- `duply_profile` - The name of a Duply profile
- `duply_gpg_key` - The GPG key for encrypting backups (default: `disabled`)
- `duply_gpg_pw` - The GPG password for encrypting backups
- `duply_target` - Target for your backups (see [here](http://duply.net/wiki/index.php/Duply-documentation) for details)
- `duply_target_user` - Target user
- `duply_target_pass` - Target password
- `duply_source` - Source path of backups
- `duply_max_age` - Maximum age for backups (default: `1M` for 1 month)
- `duply_max_full_age` - Maximum age of full backups
- `duply_max_full_backups` - Maximum number of full backups
- `duply_excludes` - A list of backup exclusions  (default: `[]`)

## Example Playbook

See the [examples](./examples/) directory.


text:
// Author: nforman@google.com (Naomi Forman)
//
// Implements the convert_meta_tags filter, which creates a
// response header for http-equiv meta tags.

#include "net/instaweb/rewriter/public/meta_tag_filter.h"

#include "net/instaweb/htmlparse/public/html_element.h"
#include "net/instaweb/htmlparse/public/html_name.h"
#include "net/instaweb/http/public/content_type.h"
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/util/public/statistics.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"

namespace {

// Statistics variable for number of tags converted to headers.
const char kConvertedMetaTags[] = "converted_meta_tags";

}  // namespace

namespace net_instaweb {

MetaTagFilter::MetaTagFilter(RewriteDriver* rewrite_driver)
    : CommonFilter(rewrite_driver),
      response_headers_(NULL) {
  Statistics* stats = driver()->statistics();
  converted_meta_tag_count_ = stats->GetVariable(kConvertedMetaTags);
}

void MetaTagFilter::InitStats(Statistics* stats) {
  stats->AddVariable(kConvertedMetaTags);
}

MetaTagFilter::~MetaTagFilter() {}

void MetaTagFilter::StartDocumentImpl() {
  // This pointer will be nulled at first Flush to guarantee that we don't
  // write it after that (won't work).
  response_headers_ = driver()->mutable_response_headers();
}

void MetaTagFilter::EndElementImpl(HtmlElement* element) {
  // If response_headers_ are null, they got reset due to a flush, so don't
  // try to convert any tags into response_headers_ (which were already
  // finalized). Also don't add meta tags to response_headers_ if they're
  // inside a noscript tag.
  if (response_headers_ == NULL || noscript_element() != NULL ||
      element->keyword() != HtmlName::kMeta) {
    return;
  }
  if (ExtractAndUpdateMetaTagDetails(element, response_headers_)) {
    converted_meta_tag_count_->Add(1);
  }
}

bool MetaTagFilter::ExtractAndUpdateMetaTagDetails(
    HtmlElement* element,
    ResponseHeaders* response_headers) {
  if (response_headers == NULL) {
    return false;
  }
  GoogleString content, mime_type, charset;

  if (ExtractMetaTagDetails(*element, response_headers,
                            &content, &mime_type, &charset)) {
    if (!content.empty()) {
      // Yes content => it has http-equiv and content attributes,
      // and a mime_type and/or a charset, but we need a mime_type.
      if (!mime_type.empty()) {
        const ContentType* type = MimeTypeToContentType(mime_type);
        // We only want to propagate the charset for HTML;
        // XHTML is forced to UTF-8 anyway and we really don't want to propagate
        // an XHTML type in cases where Apache is unsure just to propagate
        // a charset that's not supposed to take any effect.
        if (type != NULL && type->type() == ContentType::kHtml) {
          if (response_headers->MergeContentType(content)) {
            return true;
          }
        }
      }
    } else {
      // No content => it has a charset attribute (and no mime_type).
      GoogleString type = StrCat("; charset=", charset);
      if (response_headers->MergeContentType(type)) {
        return true;
      }
    }
  }
  return false;
}

void MetaTagFilter::Flush() {
  response_headers_ = NULL;
}

}  // namespace net_instaweb


text:
import paramiko
import configparser
from multiprocessing import Pool,Process

conffile='a.ini'

config=configparser.ConfigParser()
config.read(conffile)
#print(config.sections()) #标题
#print(config.options('global')) #key
#print(config.items('group'))#key value
#print(config.get('h1','ip'))  #标题下 键对应的值

def info_init(hostname):
    ip=config.get(hostname,'ip')
    port=config.get(hostname,'port')
    user=config.get(hostname,'user')
    passwd=config.get(hostname,'passwd')
    print('%s host_info'%(hostname),ip,port,user,passwd)
    return ip,port,user,passwd

def ssh_conn(login,command):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(login[0],int(login[1]),login[2],login[3])
    stdin,stdout,stderr = ssh.exec_command(command)
    print(stdout.read().decode('utf-8'))
    ssh.close()

class ftp_conn():
    def __init__(self):
        pass
    def ftp_put(self):
        t=paramiko.Transport(('172.21.120.247',41022,))
        t.connect(username='dev',password='imsa1qaz@WSX')
        sftp=paramiko.SFTPClient.from_transport(t)
        #sftp.put('')
        sftp.close()
    def ftp_get(self):
        pass
if __name__ == '__main__':
    #info_init('h1')        测试可以正常读取到主机名对应的信息,下面使用回调函数
    # pool=Pool()
    # p
    # res=info_init('h1')
    # print(type(res))
    # print(res[1])
    hostname=input('请输入主机名')
    command=input('请输入执行的命令')
    ssh_conn(info_init(hostname),command)


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CommandWithResult.cs" company="Julien Blin">
//   Copyright (c) 2014 Julien Blin
// </copyright>
// <summary>
//   Defines the CommandWithResult type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Hexagon.Database.EF.Tests.Commands
{
    using System;

    public class CommandWithResult : IDatabaseCommand<DateTime>
    {
    }
}


text:
extern float g_additionalBodyMass;

//comment this out to compare with original spring constraint
#define USE_6DOF2
#ifdef USE_6DOF2
	#define CONSTRAINT_TYPE btGeneric6DofSpring2Constraint
	#define EXTRAPARAMS
#else
	#define CONSTRAINT_TYPE btGeneric6DofSpringConstraint
	#define EXTRAPARAMS ,true
#endif

#include "../CommonInterfaces/CommonRigidBodyBase.h"

struct Dof6ConstraintTutorial : public CommonRigidBodyBase
{
	struct Dof6ConstraintTutorialInternalData* m_data;

	Dof6ConstraintTutorial(struct GUIHelperInterface* helper);
	virtual ~Dof6ConstraintTutorial();
	virtual void initPhysics();

	virtual void stepSimulation(float deltaTime);

	void animate();

	virtual void resetCamera()
	{
		float dist = 5;
		float pitch = 722;
		float yaw = 35;
		float targetPos[3]={4,2,-11};
		m_guiHelper->resetCamera(dist,pitch,yaw,targetPos[0],targetPos[1],targetPos[2]);
	}
};

struct Dof6ConstraintTutorialInternalData
{
		btRigidBody*              m_TranslateSpringBody;
	btRigidBody*              m_TranslateSpringBody2;
	btRigidBody*              m_RotateSpringBody;
	btRigidBody*              m_RotateSpringBody2;
	btRigidBody*              m_BouncingTranslateBody;
	btRigidBody*              m_MotorBody;
	btRigidBody*              m_ServoMotorBody;
	btRigidBody*              m_ChainLeftBody;
	btRigidBody*              m_ChainRightBody;
	CONSTRAINT_TYPE*          m_ServoMotorConstraint;
	CONSTRAINT_TYPE*          m_ChainLeftConstraint;
	CONSTRAINT_TYPE*          m_ChainRightConstraint;

	TimeSeriesCanvas*			m_timeSeriesCanvas;

	float mDt;

	unsigned int frameID;
	Dof6ConstraintTutorialInternalData()
		:	mDt(1./60.),frameID(0)
	{
	}
};

Dof6ConstraintTutorial::Dof6ConstraintTutorial(struct GUIHelperInterface* helper)
	:CommonRigidBodyBase(helper)
{
	m_data = new Dof6ConstraintTutorialInternalData;
	m_data->m_timeSeriesCanvas = new TimeSeriesCanvas(helper->get2dCanvasInterface(),256,256,"Position and Velocity");
	m_data->m_timeSeriesCanvas ->setupTimeSeries(20,100, 0);
	m_data->m_timeSeriesCanvas->addDataSource("X position (m)", 255,0,0);
	m_data->m_timeSeriesCanvas->addDataSource("X velocity (m/s)", 0,0,255);
	m_data->m_timeSeriesCanvas->addDataSource("dX/dt (m/s)", 0,0,0);

}
Dof6ConstraintTutorial::~Dof6ConstraintTutorial()
{
	delete m_data->m_timeSeriesCanvas;
	m_data->m_timeSeriesCanvas = 0;
	exitPhysics();
	delete m_data;
}
void Dof6ConstraintTutorial::initPhysics()
{
	// Setup the basic world

	m_guiHelper->setUpAxis(1);

		m_collisionConfiguration = new btDefaultCollisionConfiguration();
		m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
		btVector3 worldAabbMin(-10000,-10000,-10000);
		btVector3 worldAabbMax(10000,10000,10000);
		m_broadphase = new btAxisSweep3 (worldAabbMin, worldAabbMax);

/////// uncomment the corresponding line to test a solver.
		//m_solver = new btSequentialImpulseConstraintSolver;
		m_solver = new btNNCGConstraintSolver;
		//m_solver = new btMLCPSolver(new btSolveProjectedGaussSeidel());
		//m_solver = new btMLCPSolver(new btDantzigSolver());
		//m_solver = new btMLCPSolver(new btLemkeSolver());

		m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
		m_dynamicsWorld->getDispatchInfo().m_useContinuous = true;
		m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);

		m_dynamicsWorld->setGravity(btVector3(0,0,0));

		// Setup a big ground box
	if (0)
		{
			btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(200.),btScalar(5.),btScalar(200.)));
			btTransform groundTransform;
			groundTransform.setIdentity();
			groundTransform.setOrigin(btVector3(0,-10,0));
#define CREATE_GROUND_COLLISION_OBJECT 1
#ifdef CREATE_GROUND_COLLISION_OBJECT
			btCollisionObject* fixedGround = new btCollisionObject();
			fixedGround->setCollisionShape(groundShape);
			fixedGround->setWorldTransform(groundTransform);
			m_dynamicsWorld->addCollisionObject(fixedGround);
#else
			localCreateRigidBody(btScalar(0.),groundTransform,groundShape);
#endif //CREATE_GROUND_COLLISION_OBJECT
		}

		m_dynamicsWorld->getSolverInfo().m_numIterations = 100;

		btCollisionShape* shape;
		btVector3 localInertia(0,0,0);
		btDefaultMotionState* motionState;
		btTransform bodyTransform;
		btScalar mass;
		btTransform localA;
		btTransform localB;
		CONSTRAINT_TYPE* constraint;

		//static body centered in the origo
		mass = 0.0;
		shape= new btBoxShape(btVector3(0.5,0.5,0.5));
		localInertia = btVector3(0,0,0);
		bodyTransform.setIdentity();
		motionState = new btDefaultMotionState(bodyTransform);
		btRigidBody* staticBody = new btRigidBody(mass,motionState,shape,localInertia);
		m_dynamicsWorld->addRigidBody(staticBody);

/////////// box with undamped translate spring attached to static body
/////////// the box should oscillate left-to-right forever
		{
			mass = 1.0;
			shape= new btBoxShape(btVector3(0.5,0.5,0.5));
			shape->calculateLocalInertia(mass,localInertia);
			bodyTransform.setIdentity();
			bodyTransform.setOrigin(btVector3(-2,0,-5));
			motionState = new btDefaultMotionState(bodyTransform);
			m_data->m_TranslateSpringBody = new btRigidBody(mass,motionState,shape,localInertia);
			m_data->m_TranslateSpringBody->setActivationState(DISABLE_DEACTIVATION);
			m_dynamicsWorld->addRigidBody(m_data->m_TranslateSpringBody);
 			localA.setIdentity();localA.getOrigin() = btVector3(0,0,-5);
			localB.setIdentity();
 			constraint =  new CONSTRAINT_TYPE(*staticBody, *m_data->m_TranslateSpringBody, localA, localB EXTRAPARAMS);
			constraint->setLimit(0, 1,-1);
			constraint->setLimit(1, 0, 0);
			constraint->setLimit(2, 0, 0);
			constraint->setLimit(3, 0, 0);
			constraint->setLimit(4, 0, 0);
			constraint->setLimit(5, 0, 0);
			constraint->enableSpring(0, true);
			constraint->setStiffness(0, 100);
	#ifdef USE_6DOF2
			constraint->setDamping(0, 0);
	#else
			constraint->setDamping(0, 1);
	#endif
			constraint->setEquilibriumPoint(0, 0);
			constraint->setDbgDrawSize(btScalar(2.f));
			m_dynamicsWorld->addConstraint(constraint, true);
		}
#if 0
/////////// box with rotate spring, attached to static body
/////////// box should swing (rotate) left-to-right forever
		{
			mass = 1.0;
			shape= new btBoxShape(btVector3(0.5,0.5,0.5));
			shape->calculateLocalInertia(mass,localInertia);
			bodyTransform.setIdentity();
			bodyTransform.getBasis().setEulerZYX(0,0,M_PI_2);
			motionState = new btDefaultMotionState(bodyTransform);
			m_data->m_RotateSpringBody = new btRigidBody(mass,motionState,shape,localInertia);
			m_data->m_RotateSpringBody->setActivationState(DISABLE_DEACTIVATION);
			m_dynamicsWorld->addRigidBody(m_data->m_RotateSpringBody);
			localA.setIdentity();localA.getOrigin() = btVector3(0,0,0);
			localB.setIdentity();localB.setOrigin(btVector3(0,0.5,0));
			constraint =  new CONSTRAINT_TYPE(*staticBody, *m_data->m_RotateSpringBody, localA, localB EXTRAPARAMS);
			constraint->setLimit(0, 0, 0);
			constraint->setLimit(1, 0, 0);
			constraint->setLimit(2, 0, 0);
			constraint->setLimit(3, 0, 0);
			constraint->setLimit(4, 0, 0);
			constraint->setLimit(5, 1, -1);
			constraint->enableSpring(5, true);
			constraint->setStiffness(5, 100);
	#ifdef USE_6DOF2
			constraint->setDamping(5, 0);
	#else
			constraint->setDamping(5, 1);
	#endif
			constraint->setEquilibriumPoint(0, 0);
			constraint->setDbgDrawSize(btScalar(2.f));
			m_dynamicsWorld->addConstraint(constraint, true);
		}

/////////// box with bouncing constraint, translation is bounced at the positive x limit, but not at the negative limit
/////////// bouncing can not be set independently at low and high limits, so two constraints will be created: one that defines the low (non bouncing) limit, and one that defines the high (bouncing) limit
/////////// the box should move to the left (as an impulse will be applied to it periodically) until it reaches its limit, then bounce back
		{
			mass = 1.0;
			shape= new btBoxShape(btVector3(0.5,0.5,0.5));
			shape->calculateLocalInertia(mass,localInertia);
			bodyTransform.setIdentity();
			bodyTransform.setOrigin(btVector3(0,0,-3));
			motionState = new btDefaultMotionState(bodyTransform);
			m_data->m_BouncingTranslateBody = new btRigidBody(mass,motionState,shape,localInertia);
			m_data->m_BouncingTranslateBody->setActivationState(DISABLE_DEACTIVATION);
			m_data->m_BouncingTranslateBody->setDeactivationTime(btScalar(20000000));
			m_dynamicsWorld->addRigidBody(m_data->m_BouncingTranslateBody);
			localA.setIdentity();localA.getOrigin() = btVector3(0,0,0);
			localB.setIdentity();
			constraint =  new CONSTRAINT_TYPE(*staticBody, *m_data->m_BouncingTranslateBody, localA, localB EXTRAPARAMS);
			constraint->setLimit(0, -2, SIMD_INFINITY);
			constraint->setLimit(1, 0, 0);
			constraint->setLimit(2, -3, -3);
			constraint->setLimit(3, 0, 0);
			constraint->setLimit(4, 0, 0);
			constraint->setLimit(5, 0, 0);
		#ifdef USE_6DOF2
			constraint->setBounce(0,0);
		#else //bounce is named restitution in 6dofspring, but not implemented for translational limit motor, so the following line has no effect
			constraint->getTranslationalLimitMotor()->m_restitution = 0.0;
		#endif
			constraint->setParam(BT_CONSTRAINT_STOP_ERP,0.995,0);
			constraint->setParam(BT_CONSTRAINT_STOP_CFM,0.0,0);
			constraint->setDbgDrawSize(btScalar(2.f));
			m_dynamicsWorld->addConstraint(constraint, true);
			constraint =  new CONSTRAINT_TYPE(*staticBody, *m_data->m_BouncingTranslateBody, localA, localB EXTRAPARAMS);
			constraint->setLimit(0, -SIMD_INFINITY, 2);
			constraint->setLimit(1, 0, 0);
			constraint->setLimit(2, -3, -3);
			constraint->setLimit(3, 0, 0);
			constraint->setLimit(4, 0, 0);
			constraint->setLimit(5, 0, 0);
		#ifdef USE_6DOF2
			constraint->setBounce(0,1);
		#else //bounce is named restitution in 6dofspring, but not implemented for translational limit motor, so the following line has no effect
			constraint->getTranslationalLimitMotor()->m_restitution = 1.0;
		#endif
			constraint->setParam(BT_CONSTRAINT_STOP_ERP,0.995,0);
			constraint->setParam(BT_CONSTRAINT_STOP_CFM,0.0,0);
			constraint->setDbgDrawSize(btScalar(2.f));
			m_dynamicsWorld->addConstraint(constraint, true);
		}

/////////// box with rotational motor, attached to static body
/////////// the box should rotate around the y axis
		{
			mass = 1.0;
			shape= new btBoxShape(btVector3(0.5,0.5,0.5));
			shape->calculateLocalInertia(mass,localInertia);
			bodyTransform.setIdentity();
			bodyTransform.setOrigin(btVector3(4,0,0));
			motionState = new btDefaultMotionState(bodyTransform);
			m_data->m_MotorBody = new btRigidBody(mass,motionState,shape,localInertia);
			m_data->m_MotorBody->setActivationState(DISABLE_DEACTIVATION);
			m_dynamicsWorld->addRigidBody(m_data->m_MotorBody);
			localA.setIdentity();localA.getOrigin() = btVector3(4,0,0);
			localB.setIdentity();
			constraint =  new CONSTRAINT_TYPE(*staticBody, *m_data->m_MotorBody, localA, localB EXTRAPARAMS);
			constraint->setLimit(0, 0, 0);
			constraint->setLimit(1, 0, 0);
			constraint->setLimit(2, 0, 0);
			constraint->setLimit(3, 0, 0);
			constraint->setLimit(4, 0, 0);
			constraint->setLimit(5, 1,-1);
		#ifdef USE_6DOF2
			constraint->enableMotor(5,true);
			constraint->setTargetVelocity(5,3.f);
			constraint->setMaxMotorForce(5,10.f);
		#else
			constraint->getRotationalLimitMotor(2)->m_enableMotor = true;
			constraint->getRotationalLimitMotor(2)->m_targetVelocity = 3.f;
			constraint->getRotationalLimitMotor(2)->m_maxMotorForce = 10;
		#endif
			constraint->setDbgDrawSize(btScalar(2.f));
			m_dynamicsWorld->addConstraint(constraint, true);
		}

/////////// box with rotational servo motor, attached to static body
/////////// the box should rotate around the y axis until it reaches its target
/////////// the target will be negated periodically
		{
			mass = 1.0;
			shape= new btBoxShape(btVector3(0.5,0.5,0.5));
			shape->calculateLocalInertia(mass,localInertia);
			bodyTransform.setIdentity();
			bodyTransform.setOrigin(btVector3(7,0,0));
			motionState = new btDefaultMotionState(bodyTransform);
			m_data->m_ServoMotorBody = new btRigidBody(mass,motionState,shape,localInertia);
			m_data->m_ServoMotorBody->setActivationState(DISABLE_DEACTIVATION);
			m_dynamicsWorld->addRigidBody(m_data->m_ServoMotorBody);
			localA.setIdentity();localA.getOrigin() = btVector3(7,0,0);
			localB.setIdentity();
			constraint =  new CONSTRAINT_TYPE(*staticBody, *m_data->m_ServoMotorBody, localA, localB EXTRAPARAMS);
			constraint->setLimit(0, 0, 0);
			constraint->setLimit(1, 0, 0);
			constraint->setLimit(2, 0, 0);
			constraint->setLimit(3, 0, 0);
			constraint->setLimit(4, 0, 0);
			constraint->setLimit(5, 1,-1);
		#ifdef USE_6DOF2
			constraint->enableMotor(5,true);
			constraint->setTargetVelocity(5,3.f);
			constraint->setMaxMotorForce(5,10.f);
			constraint->setServo(5,true);
			constraint->setServoTarget(5, M_PI_2);
		#else
			constraint->getRotationalLimitMotor(2)->m_enableMotor = true;
			constraint->getRotationalLimitMotor(2)->m_targetVelocity = 3.f;
			constraint->getRotationalLimitMotor(2)->m_maxMotorForce = 10;
			//servo motor is not implemented in 6dofspring constraint
		#endif
			constraint->setDbgDrawSize(btScalar(2.f));
			m_dynamicsWorld->addConstraint(constraint, true);
			m_data->m_ServoMotorConstraint = constraint;
		}

////////// chain of boxes linked together with fully limited rotational and translational constraints
////////// the chain will be pulled to the left and to the right periodically. They should strictly stick together.
		{
			btScalar limitConstraintStrength = 0.6;
			int bodycount = 10;
			btRigidBody* prevBody = 0;
			for(int i = 0; i < bodycount; ++i)
			{
				mass = 1.0;
				shape= new btBoxShape(btVector3(0.5,0.5,0.5));
				shape->calculateLocalInertia(mass,localInertia);
				bodyTransform.setIdentity();
				bodyTransform.setOrigin(btVector3(- i,0,3));
				motionState = new btDefaultMotionState(bodyTransform);
				btRigidBody* body = new btRigidBody(mass,motionState,shape,localInertia);
				body->setActivationState(DISABLE_DEACTIVATION);
				m_dynamicsWorld->addRigidBody(body);
				if(prevBody != 0)
				{
					localB.setIdentity();
					localB.setOrigin(btVector3(0.5,0,0));
					btTransform localA;
					localA.setIdentity();
					localA.setOrigin(btVector3(-0.5,0,0));
					CONSTRAINT_TYPE* constraint =  new CONSTRAINT_TYPE(*prevBody, *body, localA, localB EXTRAPARAMS);
					constraint->setLimit(0, -0.01, 0.01);
					constraint->setLimit(1, 0, 0);
					constraint->setLimit(2, 0, 0);
					constraint->setLimit(3, 0, 0);
					constraint->setLimit(4, 0, 0);
					constraint->setLimit(5, 0, 0);
					for(int a = 0; a < 6; ++a)
					{
						constraint->setParam(BT_CONSTRAINT_STOP_ERP,0.9,a);
						constraint->setParam(BT_CONSTRAINT_STOP_CFM,0.0,a);
					}
					constraint->setDbgDrawSize(btScalar(1.f));
					m_dynamicsWorld->addConstraint(constraint, true);

					if(i < bodycount - 1)
					{
						localA.setIdentity();localA.getOrigin() = btVector3(0,0,3);
						localB.setIdentity();
						CONSTRAINT_TYPE* constraintZY =  new CONSTRAINT_TYPE(*staticBody, *body, localA, localB EXTRAPARAMS);
						constraintZY->setLimit(0, 1, -1);
						constraintZY->setDbgDrawSize(btScalar(1.f));
						m_dynamicsWorld->addConstraint(constraintZY, true);

					}
				}
				else
				{
					localA.setIdentity();localA.getOrigin() = btVector3(bodycount,0,3);
					localB.setIdentity();
					localB.setOrigin(btVector3(0,0,0));
					m_data->m_ChainLeftBody = body;
					m_data->m_ChainLeftConstraint = new CONSTRAINT_TYPE(*staticBody, *body, localA, localB EXTRAPARAMS);
					m_data->m_ChainLeftConstraint->setLimit(3,0,0);
					m_data->m_ChainLeftConstraint->setLimit(4,0,0);
					m_data->m_ChainLeftConstraint->setLimit(5,0,0);
					for(int a = 0; a < 6; ++a)
					{
						m_data->m_ChainLeftConstraint->setParam(BT_CONSTRAINT_STOP_ERP,limitConstraintStrength,a);
						m_data->m_ChainLeftConstraint->setParam(BT_CONSTRAINT_STOP_CFM,0.0,a);
					}
					m_data->m_ChainLeftConstraint->setDbgDrawSize(btScalar(1.f));
					m_dynamicsWorld->addConstraint(m_data->m_ChainLeftConstraint, true);
				}
				prevBody = body;
			}
			m_data->m_ChainRightBody = prevBody;
			localA.setIdentity();localA.getOrigin() = btVector3(-bodycount,0,3);
			localB.setIdentity();
			localB.setOrigin(btVector3(0,0,0));
			m_data->m_ChainRightConstraint = new CONSTRAINT_TYPE(*staticBody, *m_data->m_ChainRightBody, localA, localB EXTRAPARAMS);
			m_data->m_ChainRightConstraint->setLimit(3,0,0);
			m_data->m_ChainRightConstraint->setLimit(4,0,0);
			m_data->m_ChainRightConstraint->setLimit(5,0,0);
			for(int a = 0; a < 6; ++a)
			{
				m_data->m_ChainRightConstraint->setParam(BT_CONSTRAINT_STOP_ERP,limitConstraintStrength,a);
				m_data->m_ChainRightConstraint->setParam(BT_CONSTRAINT_STOP_CFM,0.0,a);
			}
		}
#endif
		m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}

void Dof6ConstraintTutorial::animate()
{

/////// servo motor: flip its target periodically
#ifdef USE_6DOF2
		static float servoNextFrame = -1;
		btScalar pos = m_data->m_ServoMotorConstraint->getRotationalLimitMotor(2)->m_currentPosition;
		btScalar target = m_data->m_ServoMotorConstraint->getRotationalLimitMotor(2)->m_servoTarget;
		if(servoNextFrame < 0)
		{
			m_data->m_ServoMotorConstraint->getRotationalLimitMotor(2)->m_servoTarget *= -1;
			servoNextFrame = 3.0;
		}
		servoNextFrame -= m_data->mDt;
#endif

/////// constraint chain: pull the chain left and right periodically
		static float chainNextFrame = -1;
		static bool left = true;
		if(chainNextFrame < 0)
		{
			if(!left)
			{
				m_data->m_ChainRightBody->setActivationState(ACTIVE_TAG);
				m_dynamicsWorld->removeConstraint(m_data->m_ChainRightConstraint);
				m_data->m_ChainLeftConstraint->setDbgDrawSize(btScalar(2.f));
				m_dynamicsWorld->addConstraint(m_data->m_ChainLeftConstraint, true);
			}
			else
			{
				m_data->m_ChainLeftBody->setActivationState(ACTIVE_TAG);
				m_dynamicsWorld->removeConstraint(m_data->m_ChainLeftConstraint);
				m_data->m_ChainRightConstraint->setDbgDrawSize(btScalar(2.f));
				m_dynamicsWorld->addConstraint(m_data->m_ChainRightConstraint, true);
			}
			chainNextFrame = 3.0;
			left = !left;
		}
		chainNextFrame -= m_data->mDt;

/////// bouncing constraint: push the box periodically
		m_data->m_BouncingTranslateBody->setActivationState(ACTIVE_TAG);
		static float bounceNextFrame = -1;
		if(bounceNextFrame < 0)
		{
			m_data->m_BouncingTranslateBody->applyCentralImpulse(btVector3(10,0,0));
			bounceNextFrame = 3.0;
		}
		bounceNextFrame -= m_data->mDt;

		m_data->frameID++;
}

void Dof6ConstraintTutorial::stepSimulation(float deltaTime)
{
	//animate();

	float time = m_data->m_timeSeriesCanvas->getCurrentTime();

	float prevPos = m_data->m_TranslateSpringBody->getWorldTransform().getOrigin().x();
	m_dynamicsWorld->stepSimulation(deltaTime);
	float xPos = m_data->m_TranslateSpringBody->getWorldTransform().getOrigin().x();

	m_data->m_timeSeriesCanvas->insertDataAtCurrentTime(xPos,0,true);
	m_data->m_timeSeriesCanvas->insertDataAtCurrentTime(m_data->m_TranslateSpringBody->getLinearVelocity().x(),1,true);

	if (deltaTime>0)
	{
		m_data->m_timeSeriesCanvas->insertDataAtCurrentTime((xPos-prevPos)/deltaTime,2,true);
	}
	prevPos = xPos;
	m_data->m_timeSeriesCanvas->nextTick();

}

class CommonExampleInterface*    Dof6ConstraintTutorialCreateFunc( CommonExampleOptions& options)
{
	return new Dof6ConstraintTutorial(options.m_guiHelper);
}


text:
import java.util.Scanner;

public class ReadAllCommand extends FrostCommand {

	@Override
	public void execute(FrostThread frostThread) {
		if (frostThread.carry.get() instanceof Scanner) {
			String out = "";
			Scanner scanner = (Scanner) frostThread.carry.get();
			while (scanner.hasNextLine()) {
				out += scanner.nextLine()+"\n";
			}
			scanner.close();
			frostThread.carry.set(out);
		} else {
			frostThread.error("The right value of read must be a stream");
		}
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/Widget.AppTheme.Toolbar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/toolbar_shadow_size"
        android:background="@drawable/toolbar_shadow" />

</LinearLayout>


text:
MKDEP:=-MD
COPY:=cp
SED:=sed
RM:=rm -f

TOP?=$(shell cd ../..; pwd)

PY_VERSION:=2.5

# Python C++ flags
CXXFLAGS:=-fPIC
PYTHON_CXXFLAGS:=$(shell python2.5-config --cflags)
CXXFLAGS+=$(filter-out -Wstrict-prototypes,$(PYTHON_CXXFLAGS))

# Python linker flags
LDFLAGS+=$(filter-out -L%,$(shell python$(PY_VERSION)-config --ldflags))

# Boost C++ flags
CXXFLAGS+=-I/usr/local/include/boost_1_55_0

# Boost linker flags
BOOST_LIB_ROOT:=/usr/local/lib/boost_1_55_0
BOOST_LIBS+=$(BOOST_LIB_ROOT)/libboost_system.a
BOOST_LIBS+=$(BOOST_LIB_ROOT)/libboost_filesystem.a
BOOST_LIBS+=$(BOOST_LIB_ROOT)/libboost_python$(PY_VERSION).a
LDFLAGS+=$(BOOST_LIBS)

# Extra C++ flags
CXXFLAGS+=-ggdb
CXXFLAGSy+=-O0

# Extra preprocessor flags
CPPFLAGS+=-I$(TOP)/Providers/PythonHelper

# targets
TARGET:=test

LIB_TARGET:=extension.so

all: $(LIB_TARGET) $(TARGET)

# source files
SOURCES:=main.cpp

# this object is part of the Providers project
OBJS:=$(TOP)/Providers/bin/$(PY_VERSION)/python_io_helper.o

# this rule calls the Providers makefile to build this object
$(TOP)/Providers/bin/$(PY_VERSION)/python_io_helper.o :
	$(MAKE) --directory=$(TOP)/Providers $@

LIB_SOURCES:=extension.cpp

$(TARGET): $(SOURCES:.cpp=.o) $(OBJS)
	$(LINK.cpp) $(LDFLAGS) -o $@ $^ $(LDFLAGS)

$(LIB_TARGET) : $(LIB_SOURCES:.cpp=.o $(OBJS))
	$(CXX) -shared -o $@ $^ $(BOOST_LIBS)

clean:
	rm -f $(TARGET) $(LIB_TARGET) $(SOURCES:.cpp=.o) $(SOURCES:.cpp=.d) \
	    $(SOURCES:.cpp=.P) $(LIB_SOURCES:.cpp=.o) $(LIB_SOURCES:.cpp=.d) \
	    $(LIB_SOURCES:.cpp=.P)

%.o : %.cpp
	$(COMPILE.cpp) $(MKDEP) -o $@ $<
	-@$(COPY) $*.d $*.P;
	@$(SED) -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
	    -e '/^$$/ d' -e 's/$$/ :/' < $*.d >> $*.P;
	@$(RM) $*.d

-include $(SOURCES:.cpp=.P)


text:
import { Component } from '@angular/core';

@Component({
  selector: 'tabset-component',
  template: `
    <ngb-tabset>
      <ngb-tab title="Tab one">
        <ng-template ngbTabContent>Content one</ng-template>
      </ngb-tab>
      <ngb-tab>
        <ng-template ngbTabTitle><b>Tab</b> two</ng-template>
        <ng-template ngbTabContent>Content two</ng-template>
      </ngb-tab>
      <ngb-tab title="Tab three" [disabled]="true">
        <ng-template ngbTabContent>Content three</ng-template>
      </ngb-tab>
    </ngb-tabset>
  `
})
export class TabsetComponent {
}


text:
package com.distelli.europa;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.DefaultServlet;
import com.distelli.webserver.AjaxRequestHandler;
import com.distelli.webserver.RouteMatcher;
import com.distelli.europa.handlers.*;
import lombok.extern.log4j.Log4j;

@Log4j
public class WebAppRoutes
{
    private static final RouteMatcher ROUTES = new RouteMatcher();

    public static RouteMatcher getRouteMatcher() {
        return ROUTES;
    }

    static {
        //Add the routes below this line
        //Ajax Routes
        ROUTES.add("GET", "/ajax", AjaxRequestHandler.class);
        ROUTES.add("POST", "/ajax", AjaxRequestHandler.class);
        ROUTES.add("POST", "/storage", AjaxRequestHandler.class);

        //Kubernetes health check
        ROUTES.add("GET", "/healthz", RegistryHealthCheck.class);

        ROUTES.setDefaultRequestHandler(DefaultRequestHandler.class);
    }
}


text:
if [ $# != 2 ]; then cat << EOM

    usage: $0 ENDPOINT INDEX

    where ENDPOINT is the path to the qbox.io endpoint (or http://localhost:9200)
      and INDEX is the name of the endpoint, e.g. 'sagan-production'

EOM
    exit
fi

ENDPOINT=$1
INDEX=$2

echo "\nDelete the existing index."
curl -XDELETE "$ENDPOINT/$INDEX"
sleep 1

echo "\nCreate the index again."
curl -X PUT $ENDPOINT/$INDEX -d '{ "number_of_shards" : 1, "number_of_replicas" : 0}'
sleep 1

echo "\nInstall the settings, requires closing the index first."
curl -XPOST "$ENDPOINT/$INDEX/_close"
sleep 1
curl -XPUT "$ENDPOINT/$INDEX/_settings" -d @../sagan-site/src/main/resources/elasticsearch/settings.json
sleep 1
echo "\nInstall the mapping - do once per type/mapping file."
curl -XPOST "$ENDPOINT/$INDEX/site/_mapping" -d @../sagan-site/src/main/resources/elasticsearch/mappings/site.json
sleep 1
curl -XPOST "$ENDPOINT/$INDEX/apiDoc/_mapping" -d @../sagan-site/src/main/resources/elasticsearch/mappings/apiDoc.json
sleep 1
curl -XPOST "$ENDPOINT/$INDEX/_open"
sleep 1

echo "\nCheck the settings."
curl $ENDPOINT/$INDEX/_settings?pretty=true
sleep 1

echo "\nCheck the mappings."
curl $ENDPOINT/$INDEX/_mapping?pretty=true


text:
package ip.tweet.client;

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Iterator;
import java.util.List;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;

import ip.tweet.component.MainMenuBar;
import ip.tweet.component.SplashScreen;
import ip.tweet.component.RefreshPopup;
import ip.tweet.constant.ChatConstant;
import ip.tweet.data.BroadcastStatus;
import ip.tweet.data.User;
import ip.tweet.renderer.UserListCellRenderer;
import ip.tweet.server.InformationBroadcaster;
import ip.tweet.server.InformationReceiver;
import ip.tweet.service.ChatPublisher;
import ip.tweet.util.ChatIdUtil;
import ip.tweet.util.CommonUtil;
import ip.tweet.util.ImageUtil;
import ip.tweet.util.SharedData;
import ip.tweet.util.TrayUtil;

/**
 *
 * @author Vitthal Kavitake
 *
 */
public class IpTweet extends JFrame{
	/**
	 *
	 */
	private static final long serialVersionUID = -7979445332604816492L;
	final static JList<User> userList = new JList<User>();
	static IpTweet thisFrame;

	public void refreshUserList(){
		List<User> loggedInUsers = SharedData.getInstance().getLoggedInUsers();
		User[] data = new User[loggedInUsers.size()];
		loggedInUsers.toArray(data);
		userList.setListData(data);
	}

	public static IpTweet getInstance(){
		return thisFrame;
	}

	public static void showOnScreen(){
		thisFrame.setVisible(true);
		thisFrame.setState(JFrame.NORMAL);
		thisFrame.toFront();
	}

	private IpTweet(){
		thisFrame = this;

		CommonUtil.initialize();
		SharedData.getInstance().setLoggedInUser(login());

		new InformationReceiver().start();
		try{Thread.sleep(500);}catch(Exception e){}

		InformationBroadcaster ib = new InformationBroadcaster();
		ib.sendSelfInfo(BroadcastStatus.LOGIN);

		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		panel.setAlignmentX(LEFT_ALIGNMENT);
		setContentPane(panel);

		JScrollPane pane = new JScrollPane(userList);
		userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		userList.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent event) {
				if(event.getClickCount()==2 && event.getButton()==MouseEvent.BUTTON1 && userList.getSelectedValue()!=null){
					/*if(userList.getSelectedValue().equals(self))
						return;
					else*/
					 ChatScreen.initialize(userList.getSelectedValue(), true);
				}
				if(event.getButton()==MouseEvent.BUTTON3){
					JPopupMenu popup = new RefreshPopup();
					popup.show(IpTweet.userList,event.getX(), event.getY());
				}
			}
		});
		refreshUserList();
		userList.setCellRenderer(new UserListCellRenderer(SharedData.getInstance().getLoggedInUser().getUserName()));
		JLabel lblWelcome = new JLabel();
		lblWelcome.setFont(ChatConstant.WELCOME_LBL_FONT);
		lblWelcome.setText("Welcome "+SharedData.getInstance().getLoggedInUser().getDisplayName());
		lblWelcome.setForeground(ChatConstant.WELCOME_LBL_COLOR);
		JPanel welcomePanel = new JPanel();
		welcomePanel.setLayout(new BoxLayout(welcomePanel, BoxLayout.X_AXIS));
		welcomePanel.add(Box.createHorizontalGlue());
		welcomePanel.add(lblWelcome);
		welcomePanel.add(Box.createHorizontalGlue());
		panel.add(welcomePanel);
		panel.add(Box.createRigidArea(new Dimension(1,15)));

		JLabel lblUserList = new JLabel("Online Users:");
		JPanel userListLblPanel = new JPanel();
		userListLblPanel.setLayout(new BoxLayout(userListLblPanel, BoxLayout.X_AXIS));
		userListLblPanel.add(lblUserList);
		userListLblPanel.add(Box.createHorizontalGlue());
		panel.add(userListLblPanel);

		panel.add(pane);

		setTitle(ChatConstant.APP_NAME + " - "+SharedData.getInstance().getLoggedInUser().getDisplayName());
		setSize(ChatConstant.APP_WIDTH, ChatConstant.APP_HEIGHT);
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

		setJMenuBar(new MainMenuBar());

		setVisible(true);

		setIconImage(ImageUtil.getChatLogoImage());
		TrayUtil.addToTray(this);
	}

	public User login(){
		User user = new User();
		user.setUserName(ChatIdUtil.getLoginName());

		user.setDisplayName(ChatIdUtil.getDisplayName());
		user.setHostName(ChatIdUtil.getHostName());

		ChatPublisher.publish();
		user.setConnectAddress(ChatPublisher.getPublishUrl());
		return user;
	}

	public static void main(String args[]){
		SplashScreen splash = new SplashScreen();
		splash.showSplash();
		createAndShowGUI();
		splash.hideSplash();
	}

	public static void createAndShowGUI(){
		final SplashScreen splash = new SplashScreen();
		splash.showSplash();
		try{Thread.sleep(2000);}catch(Exception e){}//banner display timeout
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new IpTweet();
				splash.hideSplash();
			}
		});
	}

	public static void exit(){
		// log off the user
		InformationBroadcaster ib = new InformationBroadcaster();
		ib.sendSelfInfo(BroadcastStatus.LOGOUT);

		//remove from tray icon
		TrayUtil.removeTrayIcon();
		//send group conversation left message
		if(ChatScreen.getActiveChats().size()>0){
			Iterator<String> itrChatId = ChatScreen.getActiveChats().keySet().iterator();
			while(itrChatId.hasNext()){
				String chatId = itrChatId.next();
				ChatScreen.getActiveChats().get(chatId).removeChat();
			}
		}
		System.exit(0);
	}
}


text:
require 'symmetric-encryption'

class GridDomainAuthorization
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Enum

  belongs_to :grid

  enum :state, [:created, :requested, :validated, :error], default: :created

  field :domain, type: String
  field :challenge, type: Hash
  field :challenge_opts, type: Hash # TODO encrypt?
  field :authorization_type, type: String, default: 'tls-sni-01'

  belongs_to :grid_service_deploy

  field :encrypted_tls_sni_certificate, type: String, encrypted: true

  belongs_to :grid_service # Usually a LB service

  index({ grid_id: 1 })
  index({ domain: 1 })
  index({ grid_id: 1, domain: 1 }, {unique: true})

  validates_uniqueness_of :domain, scope: [:grid_id]

  # @return [String]
  def to_path
    "#{self.grid.try(:name)}/#{self.domain}"
  end

  def status
    if self.grid_service_deploy && !self.grid_service_deploy.finished?
      # Deploy still in progress
      :deploying # So that CLI or other clients know to wait before requesting the cert
    elsif self.grid_service_deploy && self.grid_service_deploy.finished? && self.grid_service_deploy.error?
      :deploy_error
    else
      self.state
    end
  end

end


text:
Follow this guide to upgrade from Cisco Spark to Webex.

## Environment variables

**Rename these environment variables**

| old                        | new                   |
| -------------------------- | --------------------- |
| `CISCOSPARK_ACCESS_TOKEN`  | `WEBEX_ACCESS_TOKEN`  |
| `CISCOSPARK_APPID_ORGID`   | `WEBEX_APPID_ORGID`   |
| `CISCOSPARK_APPID_SECRET`  | `WEBEX_APPID_SECRET`  |
| `CISCOSPARK_CLIENT_ID`     | `WEBEX_CLIENT_ID`     |
| `CISCOSPARK_CLIENT_SECRET` | `WEBEX_CLIENT_SECRET` |
| `CISCOSPARK_LOG_LEVEL`     | `WEBEX_LOG_LEVEL`     |
| `CISCOSPARK_REDIRECT_URI`  | `WEBEX_REDIRECT_URI`  |
| `CISCOSPARK_SCOPE`         | `WEBEX_SCOPE`         |

## Package

**Replace package references to `ciscospark` with `webex`**

```js
// old
require('ciscospark');
```

_**becomes**_

```js
// new
require('webex');
```

## Constructor

**Replace any references to `CiscoSpark` with `Webex`**

```js
// old
CiscoSpark.init({
  config: { ... }
});
```

_**becomes**_

```js
// new
Webex.init({
  config: { ... }
});
```

**Replace any references to `spark-core` with `webex-core`**

```js
import CiscoSpark from '@ciscospark/spark-core';
// old
const spark = CiscoSpark.init({
  config: { ... }
});
```

_**becomes**_

```js
import WebexCore from '@webex/webex-core';
// new
const webex = WebexCore.init({
  config: { ... }
});
```

## Plugins

**Replace any references to `SparkPlugin` with `WebexPlugin`**

```js
import {SparkPlugin} from '@ciscospark/spark-core';

const Avatar = SparkPlugin.extend({
  namespace: 'Avatar',
  ...
```

_**becomes**_

```js
import {WebexPlugin} from '@webex/webex-core';

const Avatar = WebexPlugin.extend({
  namespace: 'Avatar',
  ...
```


text:
namespace StiGame {

/// \class ActionBinding
/// \brief Manage a Text file that contains Action Binding. Action Name associated to Key/Mouse Event
class ActionBinding :
    public VarFile
{
    public:
		/// \brief Default Filename
        static const std::string FILENAME;
        /// \brief Constructor of empty Action Binding
		ActionBinding();
		/// \brief Constructor of a existing file
		/// \param m_filepath Filepath
        ActionBinding(std::string m_filepath);
		/// \brief Read the file
        void read(void);
		/// \brief Write the file
        void write(void);
		/// \brief Add a binding
		/// \param bname Action Name
		/// \param amap Action Map
        void addBinding(std::string bname, ActionMap *amap);

        void addBinding(ActionMap *amap);

		/// \brief Overwrite a binding
		/// \param bname Action Name
		/// \param nmap New Action Map
		void overwrite(std::string bname, ActionMap *nmap);
		/// \brief Get Action By Mouse Button
		/// \return Action Name
        std::string getActionByMouseButton(Uint8 button);
		/// \brief Get Action By Keycode
		/// \return Action Name
        std::string getActionByKeyCode(SDL_Keycode keycode);
		/// \brief Get Action Map by name
		/// \param bname Action Name
		/// \return Action Map
        ActionMap* getBinding(std::string bname);
		/// \brief Destructor
        virtual ~ActionBinding();
    protected:
		/// \brief Binding map
        std::map<std::string, ActionMap*> bindings;
    private:
};

}

#endif // ACTIONBINDING_H


text:
This gem is a wrapper around log4j and is primarily meant to be used in the Mojo framework. It will standardize logs accross Mojo applications and provide a single location to edit the Mojo Logger code base. It comes with a few benefits:

* **JSON** Logs will be printed for nice splunk logging when the mojo_* methods are called.
* No need for a log4j.properties file (although you can use one if you prefer). You can configure the logger on the fly and this gem will build a StringIO object to mock the log4j.properties file

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'mojo_logger'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install mojo_logger

## Usage

#### Simple access to a CONSOLE appender:

```ruby
require 'mojo_logger'

MojoLogger.debug "This is a message"
#=> This is a message

```

#### Mojo Formatted JSON logs
```ruby
require 'mojo_logger'

api_request = {
    session_id: '111111-11111',
    reference_id: 'client',
    api: 'get-user-info'
}

MojoLogger.mojo_warn(api_request, "Oops", "Some Warn Message")
#=> {"time":"08-25-2015 19:22:59.940 +0000","app":"Mojo","session_id":"111111-11111","reference_id":"client","api":"get-user-info","category":"Oops","message":"Some Warn Message"}

```

#### Mojo Formatted JSON logs with cusom keys
```ruby
require 'mojo_logger'

api_request = {
    session_id: '111111-11111',
    reference_id: 'client',
    api: 'get-user-info'
}

MojoLogger.mojo_warn(api_request, "Oops", "Some Warn Message", {my_key: "Some value", my_other_key: :another_val})
#=> {"time":"08-25-2015 19:24:57.575 +0000","app":"Mojo","session_id":"111111-11111","reference_id":"client","api":"get-user-info","category":"Oops","message":"Some Warn Message","my_key":"Some value","my_other_key":"another_val"}

```

## Configuration

#### CONSOLE appender with "WARN" log level
```ruby
require 'mojo_logger'

MojoLogger.config do |config|
  config.default_log_level = :warn
end

MojoLogger.debug "This won't show up"
#=> nil

MojoLogger.warn "This will show up"
#=> This will show up

```

#### Rolling File appender
This will create a rolling file logger rather than a console logger with the following settings:
Max File Size = 10MB
Max Backup Index = 10
Pattern = '%n %m %n'  (I need to change this but this is what it is for now.)

```ruby
require 'mojo_logger'

MojoLogger.config do |config|
  config.log_file = '/var/log/my_log.log'
end

```

#### Add Custom lines to the generated log4j.properties 'file'

```ruby
require 'mojo_logger'

MojoLogger.config do |config|
  config.custom_line("log4j.logger.org.apache.zookeeper.ClientCnxn=INFO")
end

```

#### Add Custom adapter for format your logs
Add an adapter that will accept whatever fields you want to input and output a hash.
This hash will be converted to json by MojoLogger.

```ruby
require 'mojo_logger'
include MojoLogger

ENV['RACK_ENV'] = 'development'

# by default you use the standard adapter

mojo_debug({}, 'category', 'this is my message', { custom: :field })
# => {"time":"04-01-2016 22:25:33.019 +0000","app":"Mojo","env":"development","session_id":null,"reference_id":null,"api":null,"category":"category","message":"this is my message","custom":"field"}

class CustomLogAdapter
  # an adapter must repond to #format() and return a Hash
  def format(message)
    {
      'message'     => message,
      'constant'    => 'Hello!'
    }
  end
end

MojoLogger.config do |config|
  config.adapter = CustomLogAdapter.new
end

# now you can call the #mojo_* methods with the parameter you define

mojo_debug('my message')
# => {"time":"04-01-2016 22:26:43.441 +0000","app":"Mojo","env":"development","message":"my message","constant":"Hello!"}

```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/[my-github-username]/mojo_logger/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

if (!defined('MOODLE_INTERNAL')) {
    die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
}

/**
 * Plagiarism base class used by plugins.
 *
 * @since Moodle 2.0
 * @package    core_plagiarism
 * @copyright  2010 Dan Marsden http://danmarsden.com
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
abstract class plagiarism_plugin {

    /**
     * Return the list of form element names.
     *
     * @return array contains the form element names.
     */
    public function get_configs() {
        return array();
    }

    /**
     * hook to allow plagiarism specific information to be displayed beside a submission
     * @param array  $linkarraycontains all relevant information for the plugin to generate a link
     * @return string
     */
    public function get_links($linkarray) {
        return '';
    }
    /**
     * hook to allow plagiarism specific information to be returned unformatted
     * @param int $cmid
     * @param int $userid
     * @param $file file object
     * @return array containing at least:
     *   - 'analyzed' - whether the file has been successfully analyzed
     *   - 'score' - similarity score - ('' if not known)
     *   - 'reporturl' - url of originality report - '' if unavailable
     */
    public function get_file_results($cmid, $userid, $file) {
        return array('analyzed' => '', 'score' => '', 'reporturl' => '');
    }
    /**
     * hook to add plagiarism specific settings to a module settings page
     * @param object $mform  - Moodle form
     * @param object $context - current context
     * @param string $modulename - Name of the module
     */
    public function get_form_elements_module($mform, $context, $modulename = "") {
    }
    /* hook to save plagiarism specific settings on a module settings page
     * @param object $data - data from an mform submission.
     */
    public function save_form_elements($data) {
    }
    /**
     * hook to allow a disclosure to be printed notifying users what will happen with their submission
     * @param int $cmid - course module id
     * @return string
     */
    public function print_disclosure($cmid) {
    }
    /**
     * hook to allow status of submitted files to be updated - called on grading/report pages.
     *
     * @param object $course - full Course object
     * @param object $cm - full cm object
     */
    public function update_status($course, $cm) {
    }

    /**
     * Deprecated cron method.
     *
     * This method was added by mistake in the previous versions of Moodle, do not override it since it is never called.
     * To implement cron you need to register a scheduled task, see https://docs.moodle.org/dev/Task_API.
     * For backward compatibility with the old cron API the method cron() from this class can also be used.
     *
     * @deprecated since Moodle 3.1 MDL-52702 - please use scheduled tasks instead.
     */
    public function plagiarism_cron() {
        debugging('plagiarism_plugin::plagiarism_cron() is deprecated. Please use scheduled tasks instead', DEBUG_DEVELOPER);
    }
}


text:
import Dexie from 'dexie';
import 'dexie-observable';
import '../../src/Dexie.Syncable';
import {module, asyncTest, start, stop, strictEqual, deepEqual, ok} from 'QUnit';

/* The following is being tested:

 1. A dummy implementation of ISyncProtocol is registered so that the unit test can interact with the database correctly.
 2. Test status changes
 3. Test disconnect/reconnect and that we get changes which happened as we were disconnected
 */
var db1 = new Dexie("db1");
var db2 = new Dexie("db1");
var deletePromise = Dexie.delete("db1");

module("tests-syncable", {
  setup: function () {
    db1.close();
    db2.close();
    stop();
    deletePromise.then(function () {
      start()
    });
  },
  teardown: function () {
  }
});

asyncTest("connect(), disconnect()", function () {
  var testNo = 0;
  var callbacks = [];
  Dexie.Syncable.registerSyncProtocol("testProtocol", {
    sync: function (context, url, options, baseRevision, syncedRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError) {
      var thiz = this, args = arguments;
      Dexie.vip(function () {
        try {
          callbacks[testNo++].apply(thiz, args);
        } catch (err) {
          db1.close();
          ok(false, err);
          start();
        }
      });
    },
    partialsThreshold: 1000
  });

  db1.version(1).stores({objects: "$$"});
  db2.version(1).stores({objects: "$$"});

  db1.on('populate', function () {
    db1.objects.add({name: "one"});
    db1.objects.add({name: "two"});
    db1.objects.add({name: "three"}).then(function (key) {
      db1.objects.update(key, {name: "four"});
    });
  });

  db1.syncable.on('statusChanged', function (newStatus) {
    ok(true, "Status changed to " + Dexie.Syncable.StatusTexts[newStatus]);
  });
  db2.syncable.on('statusChanged', function (newStatus) {
    ok(true, "Status changed to " + Dexie.Syncable.StatusTexts[newStatus]);
  });

  db1.open();

  var connectPromise = db1.syncable.connect("testProtocol", "http://dummy.local", {option1: "option1"});

  // Test first sync call
  callbacks.push(function (context, url, options, baseRevision, syncedRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError) {
    // url
    equal(url, "http://dummy.local", "URL got through");
    // options
    equal(options.option1, "option1", "Options got through");
    // baseRevision
    equal(baseRevision, null, "Base revision is null");
    // syncedRevision
    equal(syncedRevision, null, "Sync revision is null");
    // changes
    equal(changes.length, 3, "Three changes (change number four should be reduced into change no 3");
    ok(changes.every(function (change) {
      return change.type == 1
    }), "All three changes are create changes");
    ok(changes.some(function (change) {
      return change.obj.name == "one"
    }), "'one' is among changes");
    ok(changes.some(function (change) {
      return change.obj.name == "two"
    }), "'two' is among changes");
    ok(changes.some(function (change) {
      return change.obj.name == "four"
    }), "'four' is among changes");
    // partial
    equal(partial, false, "Not partial since number of changes are below 1000");
    // applyRemoteChanges
    applyRemoteChanges([{
      type: 1,
      table: "objects",
      key: "apa",
      obj: {name: "five"}
    }], "revision one", false, false).then(function () {
      // Create a local change between remoteChanges application
      return db1.objects.add({name: "six"});
    }).then(function () {
      return applyRemoteChanges([{
        type: 1,
        table: "objects",
        key: "apa2",
        obj: {name: "seven"}
      }], "revision two", false, false);
    }).then(function () {
      // onChangesAccepted
      onChangesAccepted();
      return db1.objects.add({name: "eight"});
    }).then(function () {
      // onSuccess
      onSuccess({again: 1});
    });
  });

  connectPromise.then(function () {
    db1.objects.count(function (count) {
      equal(count, 7, "There should be seven objects in db after sync");
      // From populate:
      // 1: one
      // 2: two
      // 3: four
      // 4: applyRemoteChanges: "five" ("apa")
      // 5: db.objects.add("six")
      // 6: applyRemoteChanges: "seven" ("apa2")
      // 7: db.objects.add("eight");
    });
    db1.objects.get("apa2", function (seven) {
      equal(seven.name, "seven", "Have got the change from the server. If not, check that promise does not fire until all changes have committed.");
    });
  }).catch('DatabaseClosedError', function () {
    console.warn("DatabaseClosedError");
  }).catch(function (ex) {
    ok(false, "Could not connect. Error: " + (ex.stack || ex));
  });

  callbacks.push(function (context, url, options, baseRevision, syncedRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError) {
    // url
    equal(url, "http://dummy.local", "URL still there");
    // options
    equal(options.option1, "option1", "Options still there");
    // baseRevision
    equal(baseRevision, "revision one", "First chunk of changes is based on revision one because 'six' was created based on revision one");
    // syncedRevision
    equal(syncedRevision, "revision two", "Sync revision is 'revision two' because client has got it");
    // changes
    equal(changes.length, 1, "Even though there's two changes, we should only get the first one because they are based on different revisions");
    equal(changes[0].obj.name, "six", "First change is six");
    equal(partial, false);
    onChangesAccepted();
    onSuccess({again: 1});
  });

  // Prepare disconnect test
  callbacks.push(function (context, url, options, baseRevision, syncedRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError) {
    // baseRevision
    equal(baseRevision, "revision two", "Now we get changes based on revision two");
    // syncedRevision
    equal(syncedRevision, "revision two", "Sync revision is 'revision two' because client has got it");
    // changes
    equal(changes.length, 1, "Got another change");
    equal(changes[0].obj.name, "eight", "change is eight");
    equal(partial, false);
    onChangesAccepted();

    // Test disconnect()
    db1.syncable.disconnect("http://dummy.local");
    onSuccess({again: 1}); // Framework should ignore again: 1 since it's disconnected.
    setTimeout(reconnect, 500);
    db1.objects.add({name: "changeAfterDisconnect"});
  });

  function reconnect() {
    db1.close();
    db1 = db2;
    db1.open().then(function () {
      return db1.objects.add({name: "changeBeforeReconnect"});
    }).then(function () {
      return db1.syncable.getStatus("http://dummy.local", function (status) {
        equal(status, Dexie.Syncable.Statuses.OFFLINE, "Status is OFFLINE");
      });
    }).then(function () {
      db1.syncable.connect("testProtocol", "http://dummy.local");
    });
  }

  callbacks.push(function (context, url, options, baseRevision, syncedRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError) {
    // baseRevision
    equal(baseRevision, "revision two", "baseRevision Still revision two");
    // syncedRevision
    equal(syncedRevision, "revision two", "syncedRevision Still revision two");
    // changes
    equal(changes.length, 2, "Got 2 changes after reconnect.");
    equal(changes[0].obj.name, "changeAfterDisconnect", "change one is changeAfterDisconnect");
    equal(changes[1].obj.name, "changeBeforeReconnect", "change two is changeBeforeReconnect");
    onChangesAccepted();

    onSuccess({again: 10000}); // Wait a looong time for calling us again (so that we have the time to close and reopen and then force a sync sooner)

    setTimeout(function () {
      db1.syncable.getStatus("http://dummy.local", function (status) {
        // Close and open again and it will be status connected at once
        equal(status, Dexie.Syncable.Statuses.ONLINE, "Status is ONLINE");
      }).then(function () {
        // Close and open again and it will be status connected at once
        return db1.delete();
      }).catch(function (err) {
        ok(false, "Got error: " + err);
      }).finally(start);
    }, 100);
  });
});

asyncTest('delete()', () => {
  var testNo = 0;
  var callbacks = [];
  Dexie.Syncable.registerSyncProtocol("testProtocol", {
    sync: function (context, url, options, baseRevision, syncedRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError) {
      var thiz = this, args = arguments;
      Dexie.vip(function () {
        try {
          callbacks[testNo++].apply(thiz, args);
        } catch (err) {
          db1.close();
          ok(false, err);
          start();
        }
      });
    },
    partialsThreshold: 10
  });

  db1.version(1).stores({objects: "$$"});

  db1.on('populate', function () {
    db1.objects.add({name: "one"});
    db1.objects.add({name: "two"});
  });

  db1.open();

  const url = "http://urlToDelete.local";
  db1.syncable.connect("testProtocol", url);

  db1.syncable.on('statusChanged', function (newStatus) {
    ok(true, "Status changed to " + Dexie.Syncable.StatusTexts[newStatus]);
  });

  const originalDisconnect = db1.syncable.disconnect;

  let disconnectWasCalled = false;
  db1.syncable.disconnect = function (url) {
    disconnectWasCalled = true;
    return originalDisconnect(url);
  };

  const originalDeleteOldChanges = Dexie.Observable.deleteOldChanges;

  let deleteOldChangesWasCalled = false;
  Dexie.Observable.deleteOldChanges = function (db) {
    deleteOldChangesWasCalled = true;
    return originalDeleteOldChanges(db);
  };

  callbacks.push(function (context, url, options, baseRevision, syncedRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError) {
    // Add some uncommitted changes
    applyRemoteChanges([{
      type: 1,
      table: "objects",
      key: "apa",
      obj: {name: "uncommittedChangeBeforeDelete"}
    }], "revision with uncommitted", true, false)
        .then(() => {
          return db1.syncable.delete(url);
        })
        .then(() => {
          ok(disconnectWasCalled, 'We got disconnected');
          return db1._uncommittedChanges.toArray();
        })
        .then((uncommittedChanges) => {
          ok(uncommittedChanges.every(function (change) {
            return change.obj.name !== 'uncommittedChangeBeforeDelete'
          }), 'The uncommitted change should not be in _uncommittedChanges anymore');
          return db1._syncNodes.where('url').equals(url).toArray();
        })
        .then((nodes) => {
          strictEqual(nodes.length, 0, 'All nodes with this url should be deleted');
          ok(deleteOldChangesWasCalled, 'Observable.deleteOldChanges was called');
        })
        .catch(function (err) {
          ok(false, "Got error: " + err);
        }).finally(start);
    onSuccess(); // Stop syncing
  });
});


text:
namespace mojo {

// AssociatedInterfacePtrInfo stores necessary information to construct an
// associated interface pointer. It is similar to InterfacePtrInfo except that
// it doesn't own a message pipe handle.
template <typename Interface>
class AssociatedInterfacePtrInfo {
  DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND(AssociatedInterfacePtrInfo);

 public:
  AssociatedInterfacePtrInfo() : version_(0u) {}

  AssociatedInterfacePtrInfo(AssociatedInterfacePtrInfo&& other)
      : handle_(std::move(other.handle_)), version_(other.version_) {
    other.version_ = 0u;
  }

  AssociatedInterfacePtrInfo(ScopedInterfaceEndpointHandle handle,
                             uint32_t version)
      : handle_(std::move(handle)), version_(version) {}

  ~AssociatedInterfacePtrInfo() {}

  AssociatedInterfacePtrInfo& operator=(AssociatedInterfacePtrInfo&& other) {
    if (this != &other) {
      handle_ = std::move(other.handle_);
      version_ = other.version_;
      other.version_ = 0u;
    }

    return *this;
  }

  bool is_valid() const { return handle_.is_valid(); }

  ScopedInterfaceEndpointHandle PassHandle() {
    return std::move(handle_);
  }
  const ScopedInterfaceEndpointHandle& handle() const { return handle_; }
  void set_handle(ScopedInterfaceEndpointHandle handle) {
    handle_ = std::move(handle);
  }

  uint32_t version() const { return version_; }
  void set_version(uint32_t version) { version_ = version; }

 private:
  ScopedInterfaceEndpointHandle handle_;
  uint32_t version_;
};

}  // namespace mojo

#endif  // MOJO_PUBLIC_CPP_BINDINGS_ASSOCIATED_INTERFACE_PTR_INFO_H_


text:
function plot_contextmenu(ud)

% PLOT_CONTEXTMENU callback for the plot contextmenu.
% --------------------
% plot_contextmenu(ud)
% --------------------
% Description: callback for the plot contextmenu.
% Input:       {ud} userdata of parent window.

% © Liran Carmel
% Classification: Visualization
% Last revision date: 02-Apr-2004

% extract relevant information from userdata structure
cmenu = ud.cmenu;
ssm = ud.data;

% find mouse location
location = get(gca,'currentpoint');
location = location(1,1:2);

% find the closest row and column variable
row_samp = max(min(floor(location(1)),get(ssm,'no_cols')),1);
col_samp = max(min(floor(location(2)),get(ssm,'no_rows')),1);

% first contextmenu item
row_names = get(ssm,'rows_samples');
col_names = get(ssm,'cols_samples');
str = sprintf('%s / %s',upper(row_names{row_samp}),...
    upper(col_names{col_samp}));
h = findobj(cmenu,'tag','item_1');
set(h,'label',str);

% second contextmenu item
matrix = get(ssm,'matrix');
str = sprintf('w = %.2f',matrix(row_samp,col_samp));
h = findobj(cmenu,'tag','item_2');
set(h,'label',str);


text:
#include "clearpath_tec_teleop/JoystickTeleop.h"

JoystickTeleop::JoystickTeleop (ros::NodeHandle &n): node_(n)
{
    left_trigger_nonzero = false;
    right_trigger_nonzero = false;

    for (int i=0;i<NUM_JOINTS;i++) {
        joint_value[i].value = 0;
        joint_value[i].unit = "rad/s";
        joint_value[i].joint_uri = "N/A";
        joint_value[i].timeStamp = ros::Time::now();
    }

    gripperActivated = false;
    gripper_mode = BASIC_MODE;
    arm_enabled = false;
    sample_command.velocities.resize(NUM_JOINTS);

    joint_vel_pub = node_.advertise<brics_actuator::JointVelocities>("arm_controller/cmd_vel",1000);
    arm_light_pub = node_.advertise<std_msgs::Bool>("/husky_01/arm_light",1);
    mast_light_pub = node_.advertise<std_msgs::Bool>("/husky_01/mast_light",1);
    joy_sub = node_.subscribe<sensor_msgs::Joy>("joy", 1000, &JoystickTeleop::joystickCallback,this);
    gripper_pub = node_.advertise<robotiq_s_model_control::SModel_robot_output>("SModelRobotOutput",1000);
    arm_light.data = false;
    mast_light.data = false;

}

void JoystickTeleop::sendArmCommand(const ros::TimerEvent&)
{
    for (int i=0;i<NUM_JOINTS;i++) {
        joint_value[i].timeStamp = ros::Time::now();
        sample_command.velocities[i] = joint_value[i];
    }

    gripper_pub.publish (gripper_command);
    if (arm_enabled)
        joint_vel_pub.publish(sample_command);
}

void JoystickTeleop::joystickCallback(const sensor_msgs::Joy::ConstPtr& msg)
{
   if (msg->buttons[0] != 1 && // husky is not being actively controlled
       msg->buttons[3] == 1) { // and the arm is enabled
        arm_enabled = true;
        double left_trigger_value = msg->axes[2];
        double right_trigger_value = msg->axes[5];
        double wrist_l_val = 0;
        double wrist_r_val = 0;

        //triggers swing from -1 to 1, rescale to 0-1
        wrist_r_val = -(right_trigger_value - 1) /2.0;
        wrist_l_val = -(left_trigger_value - 1)/2.0;

        //slight joystick driver oddity handled here, trigger always reads zero unless its pressed after which it swings from -1 to 1
        if (left_trigger_value==0 && !left_trigger_nonzero)  //if left trigger value is zero, and it has never become non zero before then read zero
            wrist_l_val = 0;
        else if(left_trigger_value !=0 && left_trigger_nonzero) //well you are nonzero now
            left_trigger_nonzero = true;

        if (right_trigger_value==0 && !right_trigger_nonzero)  //same thing with right trigger
            wrist_r_val = 0;
        else if(right_trigger_value !=0 && right_trigger_nonzero) //well you are nonzero now
            right_trigger_nonzero = true;

        joint_value[0].value = -msg->axes[3] * MAX_VEL;
        joint_value[1].value = -msg->axes[4] * MAX_VEL;
        joint_value[2].value = -msg->axes[0] * MAX_VEL;
        joint_value[3].value = -msg->axes[1] * MAX_VEL;
        joint_value[4].value = msg->axes[6] * MAX_VEL;
        joint_value[5].value = msg->axes[7] * MAX_VEL;
        joint_value[6].value = (wrist_r_val - wrist_l_val) * MAX_VEL;
    }
    else arm_enabled = false;

    if (msg->buttons[1] == 1) { // switch gripping mode
        if (!gripperActivated) {
            gripper_command.rACT = 1;
            gripper_command.rGTO = 1;
            gripper_command.rSPA = 255;
            gripper_command.rFRA = 150;
            gripperActivated = true;
        }
        else{
            gripper_mode = (gripper_mode+1)%NUM_GRIPPER_MODES;
            gripper_command.rMOD = gripper_mode;
            if (gripper_mode == BASIC_MODE)
                ROS_INFO("Gripper mode set to BASIC");
            if (gripper_mode == PINCH_MODE)
                ROS_INFO("Gripper mode set to PINCH");
            if (gripper_mode == WIDE_MODE)
                ROS_INFO("Gripper mode set to WIDE");
            if (gripper_mode == SCISSOR_MODE)
                ROS_INFO("Gripper mode set to SCISSOR");
        }
    }

    if (msg->buttons[4] == 1) { //close gripper
        if (!gripperActivated) {
            gripper_command.rACT = 1;
            gripper_command.rGTO = 1;
            gripper_command.rSPA = 255;
            gripper_command.rFRA = 150;
            gripperActivated = true;
        }
        else{
            gripper_command.rPRA = 255;
        }
    }

    if (msg->buttons[5] == 1) { //open gripper
        if (!gripperActivated) {
            gripper_command.rACT = 1;
            gripper_command.rGTO = 1;
            gripper_command.rSPA = 255;
            gripper_command.rFRA = 150;
            gripperActivated = true;
        }
        else {
            gripper_command.rPRA = 0;
        }
    }

    if (msg->buttons[4] ==1) {
        arm_light.data = !(arm_light.data);
        arm_light_pub.publish(arm_light);
    }

    if (msg->buttons[5] == 1) {
        mast_light.data = !(mast_light.data);
        mast_light_pub.publish(mast_light);
    }

}

int main(int argc, char **argv)
{
    ros::init (argc, argv, "logitech_teleop");
    ros::NodeHandle nh;

    JoystickTeleop teleop_obj(nh);

    //send arm commands at 1/0.02 = 50Hz
    ros::Timer timer = nh.createTimer(ros::Duration(0.02), &JoystickTeleop::sendArmCommand, &teleop_obj);
    ros::spin();
    return 0;
}


text:
node-chopped-stream
===================

[![Build Status](https://travis-ci.org/abi/node-chopped-stream.png)](https://travis-ci.org/abi/node-chopped-stream)

Convert any stream into one that gives you data in user-defined sized chunks.

```javascript
var assert = require('assert')
var choppedStream = require('../.')
var fs = require('fs')
var path = require('path')

var numChunks = 0
fs.createReadStream(path.join(__dirname, 'data/data.txt'))
  .pipe(choppedStream(1000))
  .on('data', function (chunk) {
    numChunks++
    if (numChunks < 20) {
      assert(chunk.length === 1000,
             'Each chunk except for the last one should be 1000 bytes long')
    } else {
      assert(chunk.length === 660,
             'Last chunk should be 660 bytes long')
    }
  })
```

Install
------------

`npm install chopped-stream`


text:
package org.apache.camel.component.openstack.keystone.producer;

import java.util.List;
import java.util.Map;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.component.openstack.common.OpenstackConstants;
import org.apache.camel.component.openstack.keystone.KeystoneConstants;
import org.apache.camel.component.openstack.keystone.KeystoneEndpoint;
import org.apache.camel.util.StringHelper;
import org.openstack4j.api.Builders;
import org.openstack4j.api.OSClient;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.identity.v3.Project;
import org.openstack4j.model.identity.v3.builder.ProjectBuilder;

public class ProjectProducer extends AbstractKeystoneProducer {

    public ProjectProducer(KeystoneEndpoint endpoint, OSClient client) {
        super(endpoint, client);
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        final String operation = getOperation(exchange);
        switch (operation) {
        case OpenstackConstants.CREATE:
            doCreate(exchange);
            break;
        case OpenstackConstants.GET:
            doGet(exchange);
            break;
        case OpenstackConstants.GET_ALL:
            doGetAll(exchange);
            break;
        case OpenstackConstants.UPDATE:
            doUpdate(exchange);
            break;
        case OpenstackConstants.DELETE:
            doDelete(exchange);
            break;
        default:
            throw new IllegalArgumentException("Unsupported operation " + operation);
        }
    }

    private void doCreate(Exchange exchange) {
        final Project in = messageToProject(exchange.getIn());
        final Project out = osV3Client.identity().projects().create(in);
        exchange.getIn().setBody(out);
    }

    private void doGet(Exchange exchange) {
        final Message msg = exchange.getIn();
        final String id = msg.getHeader(OpenstackConstants.ID, String.class);
        StringHelper.notEmpty(id, "Project ID");
        final Project result = osV3Client.identity().projects().get(id);
        msg.setBody(result);
    }

    private void doGetAll(Exchange exchange) {
        final List<? extends Project> out = osV3Client.identity().projects().list();
        exchange.getIn().setBody(out);
    }

    private void doUpdate(Exchange exchange) {
        final Message msg = exchange.getIn();
        final Project in = messageToProject(msg);
        final Project out = osV3Client.identity().projects().update(in);
        msg.setBody(out);
    }

    private void doDelete(Exchange exchange) {
        final Message msg = exchange.getIn();
        final String id = msg.getHeader(OpenstackConstants.ID, String.class);
        StringHelper.notEmpty(id, "Project ID");
        final ActionResponse response = osV3Client.identity().projects().delete(id);
        checkFailure(response, msg, "Delete project with ID " + id);
    }

    private Project messageToProject(Message message) {
        Project project = message.getBody(Project.class);

        if (project == null) {
            Map headers = message.getHeaders();
            ProjectBuilder builder = Builders.project();

            StringHelper.notEmpty(message.getHeader(OpenstackConstants.NAME, String.class), "Name");
            builder.name(message.getHeader(OpenstackConstants.NAME, String.class));

            if (headers.containsKey(KeystoneConstants.DOMAIN_ID)) {
                builder.domainId(message.getHeader(KeystoneConstants.DOMAIN_ID, String.class));
            }

            if (headers.containsKey(KeystoneConstants.DESCRIPTION)) {
                builder.description(message.getHeader(KeystoneConstants.DESCRIPTION, String.class));
            }

            if (headers.containsKey(KeystoneConstants.PARENT_ID)) {
                builder.parentId(message.getHeader(KeystoneConstants.PARENT_ID, String.class));
            }

            project = builder.build();
        }
        return project;
    }
}


text:
// Code generated by informer-gen. DO NOT EDIT.

package v1alpha2

import (
	"context"
	time "time"

	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
	watch "k8s.io/apimachinery/pkg/watch"
	cache "k8s.io/client-go/tools/cache"
	versioned "knative.dev/net-gateway-api/pkg/client/gatewayapi/clientset/versioned"
	internalinterfaces "knative.dev/net-gateway-api/pkg/client/gatewayapi/informers/externalversions/internalinterfaces"
	v1alpha2 "knative.dev/net-gateway-api/pkg/client/gatewayapi/listers/apis/v1alpha2"
	apisv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
)

// TCPRouteInformer provides access to a shared informer and lister for
// TCPRoutes.
type TCPRouteInformer interface {
	Informer() cache.SharedIndexInformer
	Lister() v1alpha2.TCPRouteLister
}

type tCPRouteInformer struct {
	factory          internalinterfaces.SharedInformerFactory
	tweakListOptions internalinterfaces.TweakListOptionsFunc
	namespace        string
}

// NewTCPRouteInformer constructs a new informer for TCPRoute type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewTCPRouteInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
	return NewFilteredTCPRouteInformer(client, namespace, resyncPeriod, indexers, nil)
}

// NewFilteredTCPRouteInformer constructs a new informer for TCPRoute type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredTCPRouteInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
	return cache.NewSharedIndexInformer(
		&cache.ListWatch{
			ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
				if tweakListOptions != nil {
					tweakListOptions(&options)
				}
				return client.GatewayV1alpha2().TCPRoutes(namespace).List(context.TODO(), options)
			},
			WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
				if tweakListOptions != nil {
					tweakListOptions(&options)
				}
				return client.GatewayV1alpha2().TCPRoutes(namespace).Watch(context.TODO(), options)
			},
		},
		&apisv1alpha2.TCPRoute{},
		resyncPeriod,
		indexers,
	)
}

func (f *tCPRouteInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
	return NewFilteredTCPRouteInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}

func (f *tCPRouteInformer) Informer() cache.SharedIndexInformer {
	return f.factory.InformerFor(&apisv1alpha2.TCPRoute{}, f.defaultInformer)
}

func (f *tCPRouteInformer) Lister() v1alpha2.TCPRouteLister {
	return v1alpha2.NewTCPRouteLister(f.Informer().GetIndexer())
}


text:
import argparse
import os
import shutil
import traceback
import re

from pathlib import Path
from utilities import SDC_Build_Utilities

def check_sdc_installed(sdc_utils, sdc_package):
    cmd_output = sdc_utils.get_command_output('conda list sdc')
    pattern = sdc_package.replace('=', r'\s+')
    return re.search(pattern, cmd_output)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--python', default='3.7', choices=['3.6', '3.7', '3.8'],
                        help='Python version, default = 3.7')
    parser.add_argument('--channels', default=None, help='Default env channels')
    parser.add_argument('--sdc-channel', default=None, help='Intel SDC channel')

    args = parser.parse_args()

    sdc_utils = SDC_Build_Utilities(args.python, args.channels, args.sdc_channel)
    sdc_utils.log_info('Test Intel(R) SDC conda install', separate=True)
    sdc_utils.log_info(sdc_utils.line_double)
    sdc_utils.create_environment()
    sdc_package = f'sdc={sdc_utils.get_sdc_version_from_channel()}'

    # channels list is aligned with install instruction in README.rst
    install_channels = "-c intel/label/beta -c intel -c defaults -c conda-forge"
    sdc_utils.install_conda_package([sdc_package], channels=install_channels)

    assert check_sdc_installed(sdc_utils, sdc_package), "SDC package was not installed"


text:
/*
 * T002a_Test.java
 * JUnit based test
 *
 * Created on 8. June 2007, 23:42
 */

package org.ujorm.implementation.xml.t002_tech;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import junit.framework.*;
import org.ujorm.MyTestCase;
import org.ujorm.core.UjoManagerXML;

/**
 *
 * @author Pavel Ponec
 */
public class T002a_Test extends MyTestCase {

    public T002a_Test(String testName) {
        super(testName);
    }

    public static TestSuite suite() {
        TestSuite suite = new TestSuite(T002a_Test.class);
        return suite;
    }

    /**
     * Test of printProperties method, of class org.apache.person.implementation.imlXML.XmlUjo.
     */
    public void testPrintXML() throws Exception {
        System.out.println("testPrintXML: " + suite().toString());
        StringBuilder writer = new StringBuilder(256);
        try {
            UTechnicalBean person = createPerson();
            UjoManagerXML.getInstance().saveXML(writer, person, null, "TEST");

            System.out.println("XML:\n" + writer.toString());
        } catch (RuntimeException | OutOfMemoryError ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Test of printProperties method, of class org.ujorm.person.implementation.imlXML.XmlUjo.
     */
    public void testRestoreXML() throws Exception {
        System.out.println("testPrintXML: " + suite().toString());
        StringBuilder writer = new StringBuilder(256);
        //
        UTechnicalBean person = createPerson();
        UjoManagerXML.getInstance().saveXML(writer, person, null, "TEST");
        ByteArrayInputStream is = new ByteArrayInputStream(writer.toString().getBytes(StandardCharsets.UTF_8));
        UTechnicalBean person2 = UjoManagerXML.getInstance().parseXML(is, UTechnicalBean.class, false);

        assertEquals(person, person2);
    }

    protected UTechnicalBean createPerson() {
        UTechnicalBean result = new UTechnicalBean();
        UTechnicalBean.P0_BOOL.setValue(result, true);
        UTechnicalBean.P1_BYTE.setValue(result, new Byte((byte)60));
        UTechnicalBean.P2_CHAR.setValue(result, 'A');
        UTechnicalBean.P3_SHORT.setValue(result, new Short((short)314));
        UTechnicalBean.P4_INTE.setValue(result, 314000);
        UTechnicalBean.P5_LONG.setValue(result, 123456789L);
        UTechnicalBean.P6_FLOAT.setValue(result, 5.5f);
        UTechnicalBean.P7_DOUBLE.setValue(result, 5.5d);
        UTechnicalBean.P8_BIG_INT.setValue(result, BigInteger.valueOf(300));
        UTechnicalBean.P9_BIG_DECI.setValue(result, BigDecimal.valueOf(300.003));
        UTechnicalBean.PD_DATE.setValue(result, new Date());
        UTechnicalBean.PA_BYTES.setValue(result, new byte[]{ 63,64,65 });
        UTechnicalBean.PB_CHARS.setValue(result, new char[]{ 'X', 'Y', 'X' });

        return result;
    }

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

}


text:
using Bumblebee.Extensions;
using Bumblebee.Interfaces;
using FluentAssertions;
using OpenQA.Selenium;

namespace Automation.E2E.Extensions
{
    /// <summary>
    /// Extension methods for verifying values
    /// </summary>
    public static class VerificationExtension
    {

        /// <summary>
        /// Verifies presence and visibility of an element
        /// </summary>
        /// <typeparam name="TBlock"></typeparam>
        /// <param name="page"></param>
        /// <param name="description"></param>
        /// <param name="by">Locator</param>
        /// <returns></returns>
        public static TBlock VerifyElementVisible<TBlock>(this TBlock page, string description, By by)
            where TBlock : IBlock
        {
            // Verify that element is present on the page
            page.VerifyPresenceOf(description, by);

            // Verify that element is visible
            page.Session.Driver.FindElement(by).Displayed
                .Should().Be(true, $"expected '{description}' element to be visible");

            return page;
        }

    }
}


text:
package breeze.optimize.linear

import org.scalatest._;
import org.scalatest.junit._;
import org.scalatest.prop._;

import org.junit.runner.RunWith

@RunWith(classOf[JUnitRunner])
class CompetitiveLinkingTest extends FunSuite with Checkers {
  test("sanity check") {
    val arr = Array( Seq(2.,4.,7.,9.), Seq(3.,9.,5.,1.), Seq(8.,2.,9.,7.));
    val (matching,weight) = CompetitiveLinking.extractMatching(arr.map(_.toSeq));
    assert(weight === 5.0);
    assert(matching(0) === 0)
    assert(matching(1) === 3)
    assert(matching(2) === 1)
  }

}


text:
<?php

namespace AuthTest\Dependency;

use PHPUnit\Framework\TestCase;

use Auth\Dependency\Manager;
use Zend\EventManager\EventManagerInterface as Events;
use Auth\Entity\UserInterface as User;
use Doctrine\ODM\MongoDB\DocumentManager;
use Zend\EventManager\EventManager;
use Auth\Dependency\ListInterface;

/**
 * @coversDefaultClass \Auth\Dependency\Manager
 */
class ManagerTest extends TestCase
{
    /**
     * @var Manager
     */
    private $manager;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $events;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $documentManager;

    /**
     * @see PHPUnit\Framework\TestCase::setUp()
     */
    protected function setUp()
    {
        $this->events = $this->getMockBuilder(Events::class)
            ->getMock();

        $this->documentManager = $this->getMockBuilder(DocumentManager::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->manager = new Manager($this->documentManager);
        $this->manager->setEventManager($this->events);
    }

    /**
     * @covers ::__construct
     * @covers ::getLists
     */
    public function testGetLists()
    {
        $return = [];

        $this->events->expects($this->once())
            ->method('trigger')
            ->with($this->equalTo(Manager::EVENT_GET_LISTS), $this->equalTo($this->manager))
            ->willReturn($return);

        $this->assertSame($return, $this->manager->getLists());
    }

    public function removeItemsTestDataProvider()
    {
        return [
            ['onTrigger'], ['onFlush'], ['no']
        ];
    }

    /**
     * @dataProvider removeItemsTestDataProvider
     * @covers ::removeItems
     */
    public function testRemoveItems($throwException)
    {
        $user = $this->getMockBuilder(User::class)
            ->getMock();

        $triggerStub = $this->events->expects($this->once())
            ->method('trigger')
            ->with($this->equalTo(Manager::EVENT_REMOVE_ITEMS), $this->equalTo($this->manager), $this->equalTo(['user' => $user]));

        if ('onTrigger' == $throwException) {
            $triggerStub->will($this->throwException(new \Exception));
            $expects = false;
            $flushStub = $this->documentManager->expects($this->never())->method('flush');
        } elseif ('onFlush' == $throwException) {
            $this->documentManager->expects($this->once())->method('flush')->will($this->throwException(new \Exception));
            $expects = false;
        } else {
            $this->documentManager->expects($this->once())->method('flush');
            $expects = true;
        }

        $this->assertSame($expects, $this->manager->removeItems($user));
    }

    /**
     * @covers ::attachDefaultListeners
     */
    public function testAttachDefaultListeners()
    {
        $this->events->expects($this->once())
            ->method('attach')
            ->with($this->equalTo(Manager::EVENT_REMOVE_ITEMS));

        $this->manager->setEventManager($this->events);
    }

    /**
     * @covers ::attachDefaultListeners
     */
    public function testDefaultListenersAreCalled()
    {
        $user = $this->getMockBuilder(User::class)
            ->getMock();

        $this->events = new EventManager();

        $item = new \stdClass();
        $items = [$item];

        $list = $this->getMockBuilder(ListInterface::class)
            ->getMock();
        $list->expects($this->once())
            ->method('getEntities')
            ->with($this->equalTo($user))
            ->willReturn($items);

        $this->manager = $this->getMockBuilder(Manager::class)
            ->setConstructorArgs([$this->documentManager])
            ->setMethods(['getLists'])
            ->getMock();
        $this->manager->expects($this->once())
            ->method('getLists')
            ->willReturn([$list]);
        $this->manager->setEventManager($this->events);

        $this->documentManager->expects($this->once())
            ->method('remove')
            ->with($this->equalTo($item));

        $this->assertTrue($this->manager->removeItems($user));
    }
}


text:
package com.amazonaws.services.cloudfront.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.cloudfront.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * CreateResponseHeadersPolicyResult StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateResponseHeadersPolicyResultStaxUnmarshaller implements Unmarshaller<CreateResponseHeadersPolicyResult, StaxUnmarshallerContext> {

    public CreateResponseHeadersPolicyResult unmarshall(StaxUnmarshallerContext context) throws Exception {
        CreateResponseHeadersPolicyResult createResponseHeadersPolicyResult = new CreateResponseHeadersPolicyResult();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument()) {
            context.setCurrentHeader("Location");
            createResponseHeadersPolicyResult.setLocation(StringStaxUnmarshaller.getInstance().unmarshall(context));

            context.setCurrentHeader("ETag");
            createResponseHeadersPolicyResult.setETag(StringStaxUnmarshaller.getInstance().unmarshall(context));

        }

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return createResponseHeadersPolicyResult;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("ResponseHeadersPolicy", targetDepth)) {
                    createResponseHeadersPolicyResult.setResponseHeadersPolicy(ResponseHeadersPolicyStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return createResponseHeadersPolicyResult;
                }
            }
        }
    }

    private static CreateResponseHeadersPolicyResultStaxUnmarshaller instance;

    public static CreateResponseHeadersPolicyResultStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new CreateResponseHeadersPolicyResultStaxUnmarshaller();
        return instance;
    }
}


text:
require 'puppetlabs_spec_helper/module_spec_helper'

RSpec.configure do |c|

  c.treat_symbols_as_metadata_keys_with_true_values = true

  c.before :each do
    # Ensure that we don't accidentally cache facts and environment
    # between test cases.
    Facter::Util::Loader.any_instance.stubs(:load_all)
    Facter.clear
    Facter.clear_messages

    # Store any environment variables away to be restored later
    @old_env = {}
    ENV.each_key {|k| @old_env[k] = ENV[k]}

    c.default_facts = {
      :kernel          => 'Linux',
      :concat_basedir  => '/var/lib/puppet/concat',
      :lsbdistid       => 'Ubuntu',
      :operatingsystem => 'Ubuntu',
      :osfamily        => 'Debian',
      :lsbdistcodename        => 'precise',
      :lsbdistdescription     => 'Ubuntu 12.04.2 LTS',
      :lsbdistrelease         => '12.04',
      :lsbmajdistrelease      => '12',
      :operatingsystemrelease => '12.04',
    }

    if ENV['STRICT_VARIABLES'] == 'yes'
      Puppet.settings[:strict_variables]=true
    end
  end
end

shared_examples :compile, :compile => true do
  it { should compile.with_all_deps }
end


text:
Continuation of programming 1, in C.

## Testing
For testing check the README.md file in the hw folder.


text:
{-|
  Functions to convert graph-generators 'Data.Graph.Generators.GraphInfo'
  to FGL data structures.

  Copyright (C) 2014 Uli Köhler
  Apache License v2.0
-}
module Data.Graph.Generators.FGL (
        graphInfoToUGr
    ) where

import Data.Graph.Generators
import Data.Graph.Inductive

-- | Convert a graph-generators 'GraphInfo' to a FGL 'UGr' (unlabelled)
graphInfoToUGr :: GraphInfo -- ^ The graph to convert
               -> UGr       -- ^ The resulting FGL graph
graphInfoToUGr (GraphInfo n edges) =
    let nodes = [0..n-1]
    in mkUGraph nodes edges


text:
class QWidget;

class MainWindow : public QMainWindow
{
  Q_OBJECT

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

protected:
  virtual void closeEvent(QCloseEvent * closeEvent);

private:
  QWidget * m_surface;
};