text:
---
layout: default
title: delite/DisplayContainer
---

# delite/DisplayContainer

`delite/DisplayContainer` is a [`delite/Container`](Container.md) subclass which adds the ability for the container to
manage the appearance of its children.

##### Table of Contents
[Using DisplayContainer](#using)
[Extending DisplayContainer](#extending)
[Events](#events)
[Writing a Controller for DisplayContainer](#controller)

## Using DisplayContainer

On a container extending `delite/DisplayContainer` one can trigger the visibility of a particular child by calling
the `show()` function. Conversely one can make sure a particular child is hidden by calling the `hide()` function. By
default the display container will just show or hide the child. However subclasses can implement particular transition
effects in order to transition from one visibility state to another. For this reason both functions managing the visibility
return a `Promise` that will be resolved when the transition is finished. Also both accept the same parameters:

* `dest` : Widget/HTMLElement or id that points to the child the function must show or hide
* `params` : Optional params to customize the transition, interpreted by subclasses.

```js
mycontainer.show("mychildid", {/* optional params depending on the subclass */}).then(function() {
  // promise has been resolved, the child is now visible
});
```

## Extending DisplayContainer

In order for a container to leverage `delite/DisplayContainer` it must extend it and possibly implement the `changeDisplay()`
and/or `load()` functions in order to customize their behavior. The following subclass is looking at the parameters passed
to the `show()` or `hide()` function in order to perform a visual transition when switching the child visibility. In
particular it performs a fading in or out transition based on the value of the `fade` parameter.

```js
require(["delite/register", "delite/DisplayContainer", "dojo/Deferred"/*, ...*/],
  function (register, DisplayContainer, Deferred/*, ...*/) {
  return register("my-container", [HTMElement, DisplayContainer], {
    changeDisplay: dcl.superCall(function(sup) {
      return function (widget, params) {
        var deferred = new Deferred();
        if (params.fade === "in") {
          // if there is a parameter telling us to do a fade in let's do it
          $(widget).fadeIn(1000, function() {
             deferred.resolve();
          });
        }
        sup.apply(this, arguments);
        if (params.fade === "out") {
          // if there is a parameter telling us to do a fade in let's do it by setting corresponding CSS class
          $(widget).fadeIn(1000, function() {
            deferred.resolve();
          });
        }
        return deferred.promise;
      };
    })
  });
});
```

Note that as the function performs an asynchronous action it returns a promise that will be resolved once the action
is completed.

One can trigger a fade in this way:

```js
mycontainer.show(child, { fade : "in" });
```

## Events

The `delite/DisplayContainer` class provides the following events:

|event name|dispatched|cancelable|bubbles|properties|
|----------|----------|----------|-------|----------|
|delite-display-load|on any show or hide action|True|True|

`dest`: the reference of the child to load

`loadDeferred`: the deferred to resolve once the child will be loaded; resolve with value like `{child: Element}`

`hide`: set to true if in a hide action

any other param passed to the show or hide function

|
|delite-before-show|just before a child is shown|False|True|

`dest`: the reference of the loaded child

`child`: the child to show

any other param passed to the show function

|
|delite-after-show|after a child has been shown|False|True|

`dest`: the reference of the loaded child

`child`: the child that has been shown

any other param passed to the show function

|
|delite-before-hide|just before a child is hidden|False|True|

`dest`: the reference of the loaded child

`child`: the child to hide

any other param passed to the hide function

|
|delite-after-hide|after a child has been hidden|False|True|

`dest`: the reference of the loaded child

`child`: the child that has been hidden

any other param passed to the hide function

|

## Writing a Controller for DisplayContainer

An application framework such as [dapp](https://github.com/ibm-js/dapp) can decide to listen to events from
`delite/DisplayContainer` in order to provide a controller that provides alternate/customized features.

In the following example the controller is listening to `delite-display-load` event in order to provide the ability
to load child defined in external HTML files:

```js
require(["delite/register", "delite/DisplayContainer", "dojo/request"/*, ...*/],
  function (register, DisplayContainer, request/*, ...*/) {
  document.addEventListener("delite-display-load", function(event) {
    event.preventDefault();
    // build a file name from the destination
    request(event.dest+".html", function (data) {
       // build a child from the data in the file
       var child = a_parse_function(data);
       // resolve with the child
       event.loadDeferred.resolve({ child: child });
    });
  });
});
```

In order to notify `delite/DisplayContainer` that the controller is handling child loading, the controller must:

  * call `preventDefault()` on the `delite-display-load` event.
  * resolve the event's `loadDeferred` deferred when it has finished loading the child


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Lan Bai's Homepage</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

        Lan Bai's Homepage
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              About

              Projects

              Awards

              Contact

Welcome!

          Home

 I am Lan Bai, a second year graduate student in the computer science department at University of Wisconsin, Madison. I received my bachalor degree in information engineering from the Chien-Shiung Wu Honors
College at Southeast University in 2016. I am a recipient of Microsoft Young Fellow awarded by Microsoft Research Asia in 2015. I was fortunate to work with  Dr. Jinglei Ren  and  Dr. Thomas Moscibroda as an intern in Microsoft Research Asia during summer 2017.

 My CV is available  here .

 I can also be found in  Linkedin,  Facebook,  Github.

 I am broadly interested in designing, building, and optimizing software systems. In particular, I am passionate about backend, infrastructure, and security.

 I am now looking for full-time job in Software and System Design starting 2018! Let me know if you have great opportunities.

          Home

Visitor Map

Copyright © Lan Bai 2017

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusarium semitectum var. semiglobatus

### Remarks
null


text:
import {expect} from 'chai';
import * as Rx from '../../dist/cjs/Rx';
import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports

declare const { asDiagram };
declare const expectObservable: typeof marbleTestingSignature.expectObservable;
declare const rxTestScheduler: Rx.TestScheduler;

const Observable = Rx.Observable;

/** @test {fromEvent} */
describe('Observable.fromEvent', () => {
  asDiagram('fromEvent(element, \'click\')')
  ('should create an observable of click on the element', () => {
    const target = {
      addEventListener: (eventType, listener) => {
        Observable.timer(50, 20, rxTestScheduler)
          .mapTo('ev')
          .take(2)
          .concat(Observable.never())
          .subscribe(listener);
      },
      removeEventListener: () => void 0,
      dispatchEvent: () => void 0,
    };
    const e1 = Observable.fromEvent(target, 'click');
    const expected = '-----x-x---';
    expectObservable(e1).toBe(expected, {x: 'ev'});
  });

  it('should setup an event observable on objects with "on" and "off" ', () => {
    let onEventName;
    let onHandler;
    let offEventName;
    let offHandler;

    const obj = {
      on: (a: string, b: Function) => {
        onEventName = a;
        onHandler = b;
      },
      off: (a: string, b: Function) => {
        offEventName = a;
        offHandler = b;
      }
    };

    const subscription = Observable.fromEvent(obj, 'click')
      .subscribe(() => {
        //noop
       });

    subscription.unsubscribe();

    expect(onEventName).to.equal('click');
    expect(typeof onHandler).to.equal('function');
    expect(offEventName).to.equal(onEventName);
    expect(offHandler).to.equal(onHandler);
  });

  it('should setup an event observable on objects with "addEventListener" and "removeEventListener" ', () => {
    let onEventName;
    let onHandler;
    let offEventName;
    let offHandler;

    const obj = {
      addEventListener: (a: string, b: EventListenerOrEventListenerObject, useCapture?: boolean) => {
        onEventName = a;
        onHandler = b;
      },
      removeEventListener: (a: string, b: EventListenerOrEventListenerObject, useCapture?: boolean) => {
        offEventName = a;
        offHandler = b;
      }
    };

    const subscription = Observable.fromEvent(<any>obj, 'click')
      .subscribe(() => {
        //noop
       });

    subscription.unsubscribe();

    expect(onEventName).to.equal('click');
    expect(typeof onHandler).to.equal('function');
    expect(offEventName).to.equal(onEventName);
    expect(offHandler).to.equal(onHandler);
  });

  it('should setup an event observable on objects with "addListener" and "removeListener" ', () => {
    let onEventName;
    let onHandler;
    let offEventName;
    let offHandler;

    const obj = {
      addListener: (a: string, b: Function) => {
        onEventName = a;
        onHandler = b;
      },
      removeListener: (a: string, b: Function) => {
        offEventName = a;
        offHandler = b;
      }
    };

    const subscription = Observable.fromEvent(obj, 'click')
      .subscribe(() => {
        //noop
       });

    subscription.unsubscribe();

    expect(onEventName).to.equal('click');
    expect(typeof onHandler).to.equal('function');
    expect(offEventName).to.equal(onEventName);
    expect(offHandler).to.equal(onHandler);
  });

  it('should error on invalid event targets', () => {
    const obj = {
      addListener: () => {
        //noop
      }
    };

    const subscribe = () => Observable.fromEvent(<any>obj, 'click').subscribe();
    expect(subscribe).to.throw(TypeError, 'Invalid event target');
  });

  it('should pass through options to addEventListener', () => {
    let actualOptions;
    const expectedOptions = { capture: true, passive: true };

    const obj = {
      addEventListener: (a: string, b: EventListenerOrEventListenerObject, c?: any) => {
        actualOptions = c;
      },
      removeEventListener: (a: string, b: EventListenerOrEventListenerObject, c?: any) => {
        //noop
      }
    };

    const subscription = Observable.fromEvent(<any>obj, 'click', expectedOptions)
      .subscribe(() => {
        //noop
       });

    subscription.unsubscribe();

    expect(actualOptions).to.equal(expectedOptions);
  });

  it('should pass through events that occur', (done: MochaDone) => {
    let send;
    const obj = {
      on: (name: string, handler: Function) => {
        send = handler;
      },
      off: () => {
        //noop
      }
    };

    Observable.fromEvent(obj, 'click').take(1)
      .subscribe((e: any) => {
        expect(e).to.equal('test');
      }, (err: any) => {
        done(new Error('should not be called'));
      }, () => {
        done();
      });

    send('test');
  });

  it('should pass through events that occur and use the selector if provided', (done: MochaDone) => {
    let send;
    const obj = {
      on: (name: string, handler: Function) => {
        send = handler;
      },
      off: () => {
        //noop
      }
    };

    function selector(x) {
      return x + '!';
    }

    Observable.fromEvent(obj, 'click', selector).take(1)
      .subscribe((e: any) => {
        expect(e).to.equal('test!');
      }, (err: any) => {
        done(new Error('should not be called'));
      }, () => {
        done();
      });

    send('test');
  });

  it('should not fail if no event arguments are passed and the selector does not return', (done: MochaDone) => {
    let send;
    const obj = {
      on: (name: string, handler: Function) => {
        send = handler;
      },
      off: () => {
        //noop
      }
    };

    function selector() {
      //noop
    }

    Observable.fromEvent(obj, 'click', selector).take(1)
      .subscribe((e: any) => {
        expect(e).not.exist;
      }, (err: any) => {
        done(new Error('should not be called'));
      }, () => {
        done();
      });

    send();
  });

  it('should return a value from the selector if no event arguments are passed', (done: MochaDone) => {
    let send;
    const obj = {
      on: (name: string, handler: Function) => {
        send = handler;
      },
      off: () => {
        //noop
      }
    };

    function selector() {
      return 'no arguments';
    }

    Observable.fromEvent(obj, 'click', selector).take(1)
      .subscribe((e: any) => {
        expect(e).to.equal('no arguments');
      }, (err: any) => {
        done(new Error('should not be called'));
      }, () => {
        done();
      });

    send();
  });

  it('should pass multiple arguments to selector from event emitter', (done: MochaDone) => {
    let send;
    const obj = {
      on: (name: string, handler: Function) => {
        send = handler;
      },
      off: () => {
        //noop
      }
    };

    function selector(x, y, z) {
      return [].slice.call(arguments);
    }

    Observable.fromEvent(obj, 'click', selector).take(1)
      .subscribe((e: any) => {
        expect(e).to.deep.equal([1, 2, 3]);
      }, (err: any) => {
        done(new Error('should not be called'));
      }, () => {
        done();
      });

    send(1, 2, 3);
  });

  it('should not throw an exception calling toString on obj with a null prototype', (done: MochaDone) => {
    // NOTE: Can not test with Object.create(null) or `class Foo extends null`
    // due to TypeScript bug. https://github.com/Microsoft/TypeScript/issues/1108
    class NullProtoEventTarget {
      on() { /*noop*/ }
      off() { /*noop*/ }
    }
    NullProtoEventTarget.prototype.toString = null;
    const obj: NullProtoEventTarget = new NullProtoEventTarget();

    expect(() => {
      Observable.fromEvent(obj, 'foo').subscribe();
      done();
    }).to.not.throw(TypeError);
  });

});


text:
const fs = require('fs');
const gulp = require('gulp');
const less = require('gulp-less');
const sourcemaps = require('gulp-sourcemaps');
const tsc = require('gulp-typescript');
const del = require('del');
const path = require('path');

const tsProject = tsc.createProject('./tsconfig.json');

gulp.task('clean', function() {
    return del('lib');
});

/**
 * Compile all typescript files
 * and copy to the destination
 */
gulp.task('compile', function() {
    return tsProject.src()
        .pipe(sourcemaps.init())
        .pipe(tsProject())
        .pipe(sourcemaps.write('.'))
        .on('error', (err) => console.log(err))
        .pipe(gulp.dest('lib/'))
});

gulp.task('less', function () {
    return gulp.src('./src/**/*.less')
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(path.join(__dirname, 'lib/src')));
});

/**
 * Copy all assets to JS codebase
 */
gulp.task('copy', function () {
    return gulp.src([
        './src/renderer/assets/*',
        './src/renderer/*.html',
        './src/locale/*',
        './package.json'
    ], {
        "base": "./src"
    }).pipe(gulp.dest('lib/src'))
});

/**
 * Set expiry time for test builds
 */
gulp.task('setExpiry', function (done) {
    // Set expiry of 15 days for test builds we create from CI
    const expiryDays = process.argv[4] || 15;
    console.log(`Setting expiry to ${expiryDays} days`);
    const milliseconds = 24*60*60*1000;
    const expiryTime = new Date().getTime() + (expiryDays * milliseconds);
    console.log(`Setting expiry time to ${expiryTime}`);

    const ttlHandlerFile = path.join(__dirname, 'src/app/ttl-handler.ts');
    fs.readFile(ttlHandlerFile, 'utf8', function (err,data) {
        if (err) {
            console.error(err);
            return done(err);
        }

        // Do a simple search and replace in the `ttl-handler.ts` file
        const replacementString = `const ttlExpiryTime = ${expiryTime}`;
        const result = data.replace(/const ttlExpiryTime = -1/g, replacementString);

        fs.writeFile(ttlHandlerFile, result, 'utf8', function (err) {
            if (err) {
                return done(err);
            }
            done();
        });
    });
});

gulp.task('build', gulp.series('clean', 'compile', 'less', 'copy'));


text:
import Gaffer
import GafferUI
import GafferImage

def __inputLabel( plug ) :

	s = int( plug.getName().replace( "in", "" ) )
	if s == 0 :
		return "B"
	elif s == 1 :
		return "A"
	else :
		return "A{}".format( s )

def __inputDescription( plug ) :

	return "The {} input.".format( __inputLabel( plug ) )

Gaffer.Metadata.registerNode(

	GafferImage.Merge,

	"description",
	"""
	Composites two or more images together. The following operations
	are available :

	  - Add : A + B
	  - Atop : Ab + B(1-a)
	  - Divide : A / B
	  - In : Ab
	  - Out : A(1-b)
	  - Mask : Ba
	  - Matte : Aa + B(1.-a)
	  - Multiply : AB
	  - Over : A + B(1-a)
	  - Subtract : A - B
	  - Difference : fabs( A - B )
	  - Under : A(1-b) + B
	  - Min : min( A, B )
	  - Max : max( A, B )
	""",

	plugs = {

		"in.*" : [

			"description", __inputDescription,
			"noduleLayout:label", __inputLabel,

		],

		"operation" : [

			"description",
			"""
			The compositing operation used to merge the
			image together. See node documentation for
			more details.
			""",

			"preset:Add", GafferImage.Merge.Operation.Add,
			"preset:Atop", GafferImage.Merge.Operation.Atop,
			"preset:Divide", GafferImage.Merge.Operation.Divide,
			"preset:In", GafferImage.Merge.Operation.In,
			"preset:Out", GafferImage.Merge.Operation.Out,
			"preset:Mask", GafferImage.Merge.Operation.Mask,
			"preset:Matte", GafferImage.Merge.Operation.Matte,
			"preset:Multiply", GafferImage.Merge.Operation.Multiply,
			"preset:Over", GafferImage.Merge.Operation.Over,
			"preset:Subtract", GafferImage.Merge.Operation.Subtract,
			"preset:Difference", GafferImage.Merge.Operation.Difference,
			"preset:Under", GafferImage.Merge.Operation.Under,
			"preset:Min", GafferImage.Merge.Operation.Min,
			"preset:Max", GafferImage.Merge.Operation.Max,

			"userDefault", GafferImage.Merge.Operation.Over,

			"plugValueWidget:type", "GafferUI.PresetsPlugValueWidget",

		],

	}

)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using BlueSheep.Common.Protocol.Types;
using BlueSheep.Common.IO;
using BlueSheep.Engine.Types;

namespace BlueSheep.Common.Protocol.Messages
{
    public class PaddockBuyResultMessage : Message
    {
        public new const uint ID =6516;
        public override uint ProtocolID
        {
            get { return ID; }
        }

        public int paddockId;
        public bool bought;
        public int realPrice;

        public PaddockBuyResultMessage()
        {
        }

        public PaddockBuyResultMessage(int paddockId, bool bought, int realPrice)
        {
            this.paddockId = paddockId;
            this.bought = bought;
            this.realPrice = realPrice;
        }

        public override void Serialize(BigEndianWriter writer)
        {
            writer.WriteInt(paddockId);
            writer.WriteBoolean(bought);
            writer.WriteVarInt(realPrice);
        }

        public override void Deserialize(BigEndianReader reader)
        {
            paddockId = reader.ReadInt();
            bought = reader.ReadBoolean();
            realPrice = reader.ReadVarInt();
            if (realPrice < 0)
                throw new Exception("Forbidden value on realPrice = " + realPrice + ", it doesn't respect the following condition : realPrice < 0");
        }

    }

}


text:
if test -d test-output
then
	if ! rmdir test-output
	then
		echo 'test-output directory is in the way. Move it first!'
		exit 1
	fi
fi
mkdir -p test-output

function run_example_test {
	exnum=$1
	rankingfileprefix=$2
	if test -z $rankingfileprefix
	then
		echo 'need 2 args to run_example_test'
		exit 1
	fi
	export PROPINQUITY_OUT_DIR="test-output/e${exnum}-${rankingfileprefix}"
	export OTT_DIR="examples/${exnum}/taxonomy"
	./build-from-newicks.sh "examples/${exnum}/${rankingfileprefix}-phylo-rankings.txt" || exit
	make || exit
	# make ${PROPINQUITY_OUT_DIR}/annotated_supertree/annotations.json || exit
	# make extra || exit
	# make ${PROPINQUITY_OUT_DIR}/assessments/summary.json || exit
	make html || exit
	make clean || exit
	rm -f "$PROPINQUITY_OUT_DIR/config"
	rmdir "$PROPINQUITY_OUT_DIR" || exit 1
}

run_example_test 1 two || exit
run_example_test 2 two || exit
run_example_test 2 three || exit
run_example_test 3 one || exit


text:
#include "QmitkNPOptitrackWidget.h"

#include "mitkOptitrackTrackingDevice.h"
#include "mitkNPOptitrackTrackingTypeInformation.h"

#include <QFileDialog>
#include <QScrollBar>
#include <Poco/Path.h>

const std::string QmitkNPOptitrackWidget::VIEW_ID = "org.mitk.views.NPOptitrackWidget";

QmitkNPOptitrackWidget::QmitkNPOptitrackWidget(QWidget* parent, Qt::WindowFlags f)
  : QmitkAbstractTrackingDeviceWidget(parent, f)
  , m_Controls(nullptr)
{
}

void QmitkNPOptitrackWidget::Initialize()
{
  InitializeSuperclassWidget();
  CreateQtPartControl(this);
  CreateConnections();
}

QmitkNPOptitrackWidget::~QmitkNPOptitrackWidget()
{
  delete m_Controls;
}

void QmitkNPOptitrackWidget::CreateQtPartControl(QWidget *parent)
{
  if (!m_Controls)
  {
    // create GUI widgets
    m_Controls = new Ui::QmitkNPOptitrackWidget;
    m_Controls->setupUi(parent);
  }
}

void QmitkNPOptitrackWidget::CreateConnections()
{
  if (m_Controls)
  {
    connect((QObject*)(m_Controls->m_testConnectionOptitrack), SIGNAL(clicked()), this, SLOT(TestConnection()));
    connect((QObject*)(m_Controls->m_SetOptitrackCalibrationFile), SIGNAL(clicked()), this, SLOT(SetOptitrackCalibrationFileClicked()));
  }
}

void QmitkNPOptitrackWidget::ResetOutput()
{
  m_Controls->m_outputTextOptitrack->setHtml("output:");
}

void QmitkNPOptitrackWidget::AddOutput(std::string s)
{
  m_Controls->m_outputTextOptitrack->setHtml(QString(s.c_str()));
  m_Controls->m_outputTextOptitrack->verticalScrollBar()->setValue(m_Controls->m_outputTextOptitrack->verticalScrollBar()->maximum());
}

mitk::TrackingDevice::Pointer QmitkNPOptitrackWidget::ConstructTrackingDevice()
{
  // Create the Tracking Device
  mitk::OptitrackTrackingDevice::Pointer tempTrackingDevice = mitk::OptitrackTrackingDevice::New();
  // Set the calibration File
  tempTrackingDevice->SetCalibrationPath(m_OptitrackCalibrationFile);

  //Set the camera parameters
  tempTrackingDevice->SetExp(m_Controls->m_OptitrackExp->value());
  tempTrackingDevice->SetLed(m_Controls->m_OptitrackLed->value());
  tempTrackingDevice->SetThr(m_Controls->m_OptitrackThr->value());

  tempTrackingDevice->SetType(mitk::NPOptitrackTrackingTypeInformation::GetTrackingDeviceName());
  return static_cast<mitk::TrackingDevice::Pointer>(tempTrackingDevice);
}

bool QmitkNPOptitrackWidget::IsDeviceInstalled()
{
  return mitk::OptitrackTrackingDevice::New()->IsDeviceInstalled();
}

void QmitkNPOptitrackWidget::SetOptitrackCalibrationFileClicked()
{
  std::string filename = QFileDialog::getOpenFileName(NULL, tr("Open Calibration File"), "/", "*.*").toLatin1().data();
  if (filename == "") { return; }
  else
  {
    m_OptitrackCalibrationFile = filename;
    Poco::Path myPath = Poco::Path(m_OptitrackCalibrationFile.c_str());
    m_Controls->m_OptitrackCalibrationFile->setText("Calibration File: " + QString(myPath.getFileName().c_str()));
  }
}

QmitkNPOptitrackWidget* QmitkNPOptitrackWidget::Clone(QWidget* parent) const
{
  QmitkNPOptitrackWidget* clonedWidget = new QmitkNPOptitrackWidget(parent);
  clonedWidget->Initialize();
  clonedWidget->m_OptitrackCalibrationFile = this->m_OptitrackCalibrationFile;
  clonedWidget->m_Controls->m_OptitrackCalibrationFile->setText(m_Controls->m_OptitrackCalibrationFile->text());

  clonedWidget->m_Controls->m_OptitrackExp->setValue(m_Controls->m_OptitrackExp->value());
  clonedWidget->m_Controls->m_OptitrackLed->setValue(m_Controls->m_OptitrackLed->value());
  clonedWidget->m_Controls->m_OptitrackThr->setValue(m_Controls->m_OptitrackThr->value());
  return clonedWidget;
}


text:
import sure
from unittest.mock import MagicMock
from django.test import TestCase
from .. import jobs
from ..models import Job
from . import factories

class PerformJobCase(TestCase):
    """Perform job case"""

    def setUp(self):
        self._mock_perform()
        self._mock_logger()

    def _mock_perform(self):
        """Mock Job.perform method"""
        self._orig_perform = Job.perform
        Job.perform = MagicMock()

    def _mock_logger(self):
        """Mock logger"""
        self._orig_logger = jobs.logger
        jobs.logger = MagicMock()

    def tearDown(self):
        Job.perform = self._orig_perform
        jobs.logger = self._orig_logger

    def test_perform(self):
        """Test perform"""
        job = factories.JobFactory()
        jobs.perform_job(job.id)
        Job.perform.call_count.should.be.equal(1)

    def test_job_doesnt_exists(self):
        """Test job doesnt exists"""
        jobs.perform_job(-1)
        Job.perform.call_count.should.be.equal(0)
        jobs.logger.exception.call_count.should.be.equal(1)


text:
<?php

/**
 * Interface for Cache Drivers.
 *
 * @author Iskandar Soesman <k4ndar@yahoo.com>
 *
 * @link http://panadaframework.com/
 *
 * @license http://www.opensource.org/licenses/bsd-license.php
 *
 * @since version 1.0.0
 */
namespace Resources\Interfaces;

interface Cache
{
    public function setValue($key, $value, $expire = 0, $namespace = false);
    public function addValue($key, $value, $expire = 0, $namespace = false);
    public function updateValue($key, $value, $expire = 0, $namespace = false);
    public function getValue($key, $namespace = false);
    public function deleteValue($key, $namespace = false);
    public function flushValues();
    public function incrementBy($key, $offset = 1);
    public function decrementBy($key, $offset = 1);
}


text:
txacme: A Twisted implementation of the ACME protocol
=====================================================

.. include:: ../README.rst
   :start-after: teaser-begin

Contents
========

.. toctree::
   :maxdepth: 2

   using
   certs-dir
   api-stability
   changelog
   API documentation </api/modules>

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
describe("Adding layers", function() {
  var map_with_layers, single_layer, multiple_layers = [];

  beforeEach(function() {
    map_with_layers = map_with_layers || new GMaps({
      el : '#map-with-layers',
      lat: -12.0433,
      lng: -77.0283,
      zoom: 12
    });
  });

  describe("Single layer", function() {
    beforeEach(function() {
      single_layer = single_layer || map_with_layers.addLayer('traffic');
    });

    it("should be added in the current map", function() {
      expect(single_layer.getMap()).toEqual(map_with_layers.map);
    });

    it("should be removed from the current map", function() {
      map_with_layers.removeLayer('traffic');

      expect(single_layer.getMap()).toBeNull();
    });
  });

  describe("Multiple layers", function() {
    beforeEach(function() {
      if (multiple_layers.length == 0) {
        multiple_layers.push(map_with_layers.addLayer('transit'));
        multiple_layers.push(map_with_layers.addLayer('bicycling'));
      }
    });

    it("should be added in the current map", function() {
      expect(multiple_layers[0].getMap()).toEqual(map_with_layers.map);
      expect(multiple_layers[1].getMap()).toEqual(map_with_layers.map);
    });

    it("should be removed from the current map", function() {
      map_with_layers.removeLayer('transit');
      map_with_layers.removeLayer('bicycling');

      expect(multiple_layers[0].getMap()).toBeNull();
      expect(multiple_layers[1].getMap()).toBeNull();
    });
  });
});


text:
#ifndef SD_LANGUAGE_H
#define SD_LANGUAGE_H

#ifdef __cplusplus
extern "C" {
#endif

/*! \brief Language string container
 *
 * Contains a single language string and a short description for it. Descriptions
 * may or may not be accurate.
 */
typedef struct {
    char description[32]; ///< Language string short description
    char *data;           ///< Language string itself.
} sd_lang_string;

/*! \brief Language string list
 *
 * Contains a list of language string descriptors.
 */
typedef struct {
    unsigned int count;      ///< Amount of language strings in the file
    sd_lang_string *strings; ///< Language string array
} sd_language;

/*! \brief Initialize language structure
 *
 * Initializes the language structure with empty values.
 *
 * \retval SD_INVALID_INPUT Language struct pointer was NULL
 * \retval SD_SUCCESS Success.
 *
 * \param language Allocated language struct pointer.
 */
int sd_language_create(sd_language *language);

/*! \brief Free language structure
 *
 * Frees up all memory reserved by the language structure.
 * All contents will be freed, all pointers to contents will be invalid.
 *
 * \param language Language struct to modify.
 */
void sd_language_free(sd_language *language);

/*! \brief Load a language file
 *
 * Loads the given language file to memory. The structure must be initialized with sd_language_create()
 * before using this function. Loading to a previously loaded or filled sd_language structure
 * will result in old data and pointers getting lost. This is very likely to cause a memory leak.
 *
 * \retval SD_FILE_OPEN_ERROR File could not be opened.
 * \retval SD_SUCCESS Success.
 *
 * \param language Language struct pointer.
 * \param filename Name of the language file to load from.
 */
int sd_language_load(sd_language *language, const char *filename);

/*! \brief Save language file
 *
 * Saves the given language file from memory to a file on disk. The structure must be at
 * least initialized by using sd_language_create() before running this.
 *
 * \retval SD_FILE_OPEN_ERROR File could not be opened for writing.
 * \retval SD_SUCCESS Success.
 *
 * \param language Language struct pointer.
 * \param filename Name of the language file to save into.
 */
int sd_language_save(sd_language *language, const char *filename);

/*! \brief Returns a language string entry.
 *
 * Returns a pointer to a language string entry.
 *
 * The structure memory will be owned by the library; do not attempt to
 * free it.
 *
 * \retval NULL If language ptr was NULL or string entry does not exist.
 * \retval sd_lang_string* Language string struct pointer on success.
 *
 * \param language Language struct pointer.
 * \param num Language entry number to get.
 */
const sd_lang_string *sd_language_get(const sd_language *language, int num);

#ifdef __cplusplus
}
#endif

#endif // SD_LANGUAGE_H


text:
use alloc::arc::Arc;
use std::mem;
use std::rt::local::Local;
use std::rt::task::{BlockedTask, Task};
use std::cell::UnsafeCell;

use homing::HomingMissile;

pub struct Access<T> {
    inner: Arc<UnsafeCell<Inner<T>>>,
}

pub struct Guard<'a, T:'static> {
    access: &'a mut Access<T>,
    missile: Option<HomingMissile>,
}

struct Inner<T> {
    queue: Vec<(BlockedTask, uint)>,
    held: bool,
    closed: bool,
    data: T,
}

impl<T: Send> Access<T> {
    pub fn new(data: T) -> Access<T> {
        Access {
            inner: Arc::new(UnsafeCell::new(Inner {
                queue: vec![],
                held: false,
                closed: false,
                data: data,
            }))
        }
    }

    pub fn grant<'a>(&'a mut self, token: uint,
                     missile: HomingMissile) -> Guard<'a, T> {
        // This unsafety is actually OK because the homing missile argument
        // guarantees that we're on the same event loop as all the other objects
        // attempting to get access granted.
        let inner = unsafe { &mut *self.inner.get() };

        if inner.held {
            let t: Box<Task> = Local::take();
            t.deschedule(1, |task| {
                inner.queue.push((task, token));
                Ok(())
            });
            assert!(inner.held);
        } else {
            inner.held = true;
        }

        Guard { access: self, missile: Some(missile) }
    }

    pub fn unsafe_get(&self) -> *mut T {
        unsafe { &mut (*self.inner.get()).data  as *mut _ }
    }

    // Safe version which requires proof that you are on the home scheduler.
    pub fn get_mut<'a>(&'a mut self, _missile: &HomingMissile) -> &'a mut T {
        unsafe { &mut *self.unsafe_get() }
    }

    pub fn close(&self, _missile: &HomingMissile) {
        // This unsafety is OK because with a homing missile we're guaranteed to
        // be the only task looking at the `closed` flag (and are therefore
        // allowed to modify it). Additionally, no atomics are necessary because
        // everyone's running on the same thread and has already done the
        // necessary synchronization to be running on this thread.
        unsafe { (*self.inner.get()).closed = true; }
    }

    // Dequeue a blocked task with a specified token. This is unsafe because it
    // is only safe to invoke while on the home event loop, and there is no
    // guarantee that this i being invoked on the home event loop.
    pub unsafe fn dequeue(&mut self, token: uint) -> Option<BlockedTask> {
        let inner = &mut *self.inner.get();
        match inner.queue.iter().position(|&(_, t)| t == token) {
            Some(i) => Some(inner.queue.remove(i).unwrap().val0()),
            None => None,
        }
    }

    /// Test whether this access is closed, using a homing missile to prove
    /// that it's safe
    pub fn is_closed(&self, _missile: &HomingMissile) -> bool {
        unsafe { (*self.inner.get()).closed }
    }
}

impl<T: Send> Clone for Access<T> {
    fn clone(&self) -> Access<T> {
        Access { inner: self.inner.clone() }
    }
}

impl<'a, T: Send> Guard<'a, T> {
    pub fn is_closed(&self) -> bool {
        // See above for why this unsafety is ok, it just applies to the read
        // instead of the write.
        unsafe { (*self.access.inner.get()).closed }
    }
}

impl<'a, T: Send> Deref<T> for Guard<'a, T> {
    fn deref<'a>(&'a self) -> &'a T {
        // A guard represents exclusive access to a piece of data, so it's safe
        // to hand out shared and mutable references
        unsafe { &(*self.access.inner.get()).data }
    }
}

impl<'a, T: Send> DerefMut<T> for Guard<'a, T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        unsafe { &mut (*self.access.inner.get()).data }
    }
}

#[unsafe_destructor]
impl<'a, T> Drop for Guard<'a, T> {
    fn drop(&mut self) {
        // This guard's homing missile is still armed, so we're guaranteed to be
        // on the same I/O event loop, so this unsafety should be ok.
        assert!(self.missile.is_some());
        let inner: &mut Inner<T> = unsafe {
            mem::transmute(self.access.inner.get())
        };

        match inner.queue.remove(0) {
            // Here we have found a task that was waiting for access, and we
            // current have the "access lock" we need to relinquish access to
            // this sleeping task.
            //
            // To do so, we first drop out homing missile and we then reawaken
            // the task. In reawakening the task, it will be immediately
            // scheduled on this scheduler. Because we might be woken up on some
            // other scheduler, we drop our homing missile before we reawaken
            // the task.
            Some((task, _)) => {
                drop(self.missile.take());
                task.reawaken();
            }
            None => { inner.held = false; }
        }
    }
}

#[unsafe_destructor]
impl<T> Drop for Inner<T> {
    fn drop(&mut self) {
        assert!(!self.held);
        assert_eq!(self.queue.len(), 0);
    }
}


text:
package com.sinacloud.scs.services.scs.model;

import java.util.Date;

import com.sinacloud.scs.services.scs.internal.ObjectExpirationResult;
import com.sinacloud.scs.services.scs.internal.ServerSideEncryptionResult;

/**
 * The CompleteMultipartUploadResult contains all the information about the
 * CompleteMultipartUpload method.
 */
public class CompleteMultipartUploadResult implements ServerSideEncryptionResult, ObjectExpirationResult {

    /** The name of the bucket containing the completed multipart upload. */
    private String bucketName;

    /** The key by which the object is stored. */
    private String key;

    /** The URL identifying the new multipart object. */
    private String location;

    /**
     * The entity tag identifying the new object. An entity tag is an opaque
     * string that changes if and only if an object's data changes.
     */
    private String eTag;

    /**
     * The version ID of the new object, only present if versioning has been
     * enabled for the bucket.
     */
    private String versionId;

    /** The server side encryption algorithm of the new object */
    private String serverSideEncryption;

    /** The time this object expires, or null if it has no expiration */
    private Date expirationTime;

    /** The expiration rule for this object */
    private String expirationTimeRuleId;

    /**
     * Returns the URL identifying the new multipart object.
     *
     * @return The URL identifying the new multipart object.
     */
    public String getLocation() {
        return location;
    }

    /**
     * Sets the URL identifying the new multipart object.
     *
     * @param location
     *            The URL identifying the new multipart object.
     */
    public void setLocation(String location) {
        this.location = location;
    }

    /**
     * Returns the name of the bucket containing the completed multipart object.
     *
     * @return The name of the bucket containing the completed multipart object.
     */
    public String getBucketName() {
        return bucketName;
    }

    /**
     * Sets the name of the bucket containing the completed multipart object.
     *
     * @param bucketName
     *            The name of the bucket containing the completed multipart
     *            object.
     */
    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    /**
     * Gets the key by which the newly created object is stored.
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets the key of the newly created object.
     */
    public void setKey(String key) {
        this.key = key;
    }

    /**
     * Returns the entity tag identifying the new object. An entity tag is an
     * opaque string that changes if and only if an object's data changes.
     *
     * @return An opaque string that changes if and only if an object's data
     *         changes.
     */
    public String getETag() {
        return eTag;
    }

    /**
     * Sets the entity tag identifying the new object. An entity tag is an
     * opaque string that changes if and only if an object's data changes.
     *
     * @param etag
     *            The entity tag.
     */
    public void setETag(String etag) {
        this.eTag = etag;
    }

    /**
     * Returns the version ID of the new object, only present if versioning has
     * been enabled for the bucket.
     *
     * @return The version ID of the new object, only present if versioning has
     *         been enabled for the bucket.
     */
    public String getVersionId() {
        return versionId;
    }

    /**
     * Sets the version ID of the new object, only present if versioning has
     * been enabled for the bucket.
     *
     * @param versionId
     *            The version ID of the new object, only present if versioning
     *            has been enabled for the bucket.
     */
    public void setVersionId(String versionId) {
        this.versionId = versionId;
    }

    /**
     * Returns the server-side encryption algorithm for the newly created
     * object, or null if none was used.
     */
    public String getServerSideEncryption() {
        return serverSideEncryption;
    }

    /**
     * Sets the server-side encryption algorithm for the newly created object.
     *
     * @param serverSideEncryption
     *            The server-side encryption algorithm for the new object.
     */
    public void setServerSideEncryption(String serverSideEncryption) {
        this.serverSideEncryption = serverSideEncryption;
    }

    /**
     * Returns the expiration time for this object, or null if it doesn't expire.
     */
    public Date getExpirationTime() {
        return expirationTime;
    }

    /**
     * Sets the expiration time for the object.
     *
     * @param expirationTime
     *            The expiration time for the object.
     */
    public void setExpirationTime(Date expirationTime) {
        this.expirationTime = expirationTime;
    }

    /**
     * Returns the {@link BucketLifecycleConfiguration} rule ID for this
     * object's expiration, or null if it doesn't expire.
     */
    public String getExpirationTimeRuleId() {
        return expirationTimeRuleId;
    }

    /**
     * Sets the {@link BucketLifecycleConfiguration} rule ID for this object's
     * expiration
     *
     * @param expirationTimeRuleId
     *            The rule ID for this object's expiration
     */
    public void setExpirationTimeRuleId(String expirationTimeRuleId) {
        this.expirationTimeRuleId = expirationTimeRuleId;
    }
}


text:
package com.google.firebase.database;

/**
 * Created by andre on 10.12.2016.
 */

public interface DatabaseReference {
}


text:
package org.apache.skywalking.oap.server.webapp;

import static org.yaml.snakeyaml.env.EnvScalarConstructor.ENV_FORMAT;
import static org.yaml.snakeyaml.env.EnvScalarConstructor.ENV_TAG;

import java.util.Collections;

import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.env.EnvScalarConstructor;

import com.linecorp.armeria.common.SessionProtocol;
import com.linecorp.armeria.server.HttpService;
import com.linecorp.armeria.server.Server;
import com.linecorp.armeria.server.file.FileService;
import com.linecorp.armeria.server.file.HttpFile;
import com.linecorp.armeria.server.healthcheck.HealthCheckService;

public class ApplicationStartUp {
    public static void main(String[] args) throws Exception {
        final Yaml yaml = new Yaml(
            new EnvScalarConstructor(
                new TypeDescription(Configuration.class),
                Collections.emptyList(),
                new LoaderOptions()));
        yaml.addImplicitResolver(ENV_TAG, ENV_FORMAT, "$");

        final Configuration configuration = yaml.loadAs(
            ApplicationStartUp.class.getResourceAsStream("/application.yml"),
            Configuration.class);

        final int port = configuration.port();
        final String[] oapServices = configuration.oapServices();

        final HttpService indexPage =
            HttpFile
                .of(ApplicationStartUp.class.getClassLoader(), "/public/index.html")
                .asService();

        Server
            .builder()
            .port(port, SessionProtocol.HTTP)
            .service("/graphql", new OapProxyService(oapServices))
            .service("/internal/l7check", HealthCheckService.of())
            .serviceUnder("/",
                FileService.of(
                    ApplicationStartUp.class.getClassLoader(),
                    "/public")
                    .orElse(indexPage))
            .build()
            .start()
            .join();
    }
}


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

<title>com.snakybo.torch.object (Torch Engine 1.0 API)</title>
<meta name="date" content="2016-09-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.snakybo.torch.object

Classes

Component

ComponentInternal

ComponentLoader

GameObject

GameObjectInternal

GameObjectLoader

TorchObject

Transform


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Contact - Kehilla Residential Programme</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/business-casual.css" rel="stylesheet">

    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">

Kehilla Residential Programme

262 Ridley Blvd. | Toronto, ON M5M 4N6 | 416.932.1212

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                Kehilla Residential Programme

                        Home

                        About

                        Blog

                        Contact

Contact
                        Kehilla

Phone:
                        416.932.1212

Fax:
                        416.932.1214

Email:
                        kehilla@rogers.com

Address:
                        262 Ridley Boulevard

Toronto, ON M5M 4N6

Contact
                        form

Please share your thoughts.

                    <form role="form">

                                Name
                                <input type="text" class="form-control">

                                Email Address
                                <input type="email" class="form-control">

                                Phone Number
                                <input type="tel" class="form-control">

                                Message
                                <textarea class="form-control" rows="6"></textarea>

                                <input type="hidden" name="save" value="contact">
                                <button type="submit" class="btn btn-default">Submit</button>

                    </form>

Copyright © Kehilla Residential Programme 2015


text:
var React = require('react');

module.exports = React.createClass({
	render: function() {
		var myStep = this.props.step || this.props.stepIndex;
		var className = (myStep <= this.props.stepNum) ? 'slide-step-visible' : 'slide-step-hidden';
		return
{this.props.children}
;
	}
});


text:
package vkapi

import (
	"errors"
	"log"
	"net/url"
	"strconv"
	"strings"
)

// Client allows you to transparently send requests to API server.
type Client struct {
	apiClient *APIClient
	LongPoll  *LongPoll
	VKUser    VKUser
	VKGroup   VKGroup
	//	Wall
	//	WallComment
	//  Message
	//  Chat
	//	Note
	//	Page
	//	Board
	//	BoardComment
}

// GetToken will return access_token
func (client *Client) GetToken() string {
	if client.apiClient == nil || client.apiClient.AccessToken == nil {
		return ""
	}

	return client.apiClient.AccessToken.AccessToken
}

// SetLanguage sets the language in which different data will be returned,
// for example, names of countries and cities.
func (client *Client) SetLanguage(lang string) error {
	if client.apiClient == nil {
		return errors.New(ErrApiClientNotFound)
	}

	client.apiClient.Language = lang
	return nil
}

// SetLogger sets logger.
func (client *Client) SetLogger(logger *log.Logger) error {
	if client.apiClient == nil {
		return errors.New(ErrApiClientNotFound)
	}

	client.apiClient.SetLogger(logger)
	return nil
}

// Log allow write log.
func (client *Client) Log(flag bool) error {
	if client.apiClient == nil {
		return errors.New(ErrApiClientNotFound)
	}

	client.apiClient.log = flag
	return nil
}

// NewClientFromAPIClient creates a new *Client instance.
func NewClientFromAPIClient(apiClient *APIClient) (client *Client, err error) {
	client = new(Client)
	client.apiClient = apiClient
	return
}

// NewClientFromToken creates a new *Client instance.
func NewClientFromToken(token string) (client *Client, err error) {
	client = new(Client)
	client.apiClient = NewApiClient()
	client.apiClient.SetAccessToken(token)
	return
}

// NewClientFromLogin creates a new *Client instance
// and allows you to pass a authentication.
func NewClientFromLogin(username string, password string, scope int64) (client *Client, err error) {
	client = new(Client)
	client.apiClient = NewApiClient()
	err = client.apiClient.Authenticate(NewApplication(username, password, scope))
	if err != nil {
		return nil, err
	}

	return
}

// NewClientFromApplication creates a new *Client instance
// and allows you to pass a custom application.
func NewClientFromApplication(app Application) (client *Client, err error) {
	client = new(Client)
	client.apiClient = NewApiClient()
	err = client.apiClient.Authenticate(app)
	if err != nil {
		return nil, err
	}

	return
}

// Do makes a request to a specific endpoint with our request
// and returns response.
func (client *Client) Do(request Request) (response *Response, err *Error) {
	if client.apiClient == nil {
		return nil, NewError(ErrBadCode, ErrApiClientNotFound)
	}

	t := client.GetToken()
	if request.Token == "" && t != "" {
		request.Token = t
	}

	return client.apiClient.Do(request)
}

// Destination describes the final destination.
type Destination struct {
	UserID      int64    `json:"user_id"`
	PeerID      int64    `json:"peer_id"`
	Domain      string   `json:"domain"`
	ChatID      int64    `json:"chat_id"`
	GroupID     int64    `json:"group_id"`
	GroupName   string   `json:"group_id"`
	GroupIDs    []int64  `json:"group_ids"`
	GroupNames  []string `json:"group_ids"`
	UserIDs     []int64  `json:"user_ids"`
	ScreenName  string   `json:"user_id"`
	ScreenNames []string `json:"user_ids"`
}

func (dst Destination) GetPeerID() int64 {
	switch {
	case dst.PeerID != 0:
		return dst.PeerID
	case dst.UserID != 0:
		return dst.UserID
	case dst.ChatID != 0:
		return 2000000000 + dst.ChatID
	case dst.GroupID != 0:
		return -dst.GroupID
	default:
		return 0
	}
}

func (dst Destination) Values() (values url.Values) {
	values = url.Values{}

	switch {
	case dst.UserID != 0:
		values.Add("user_id", strconv.FormatInt(dst.UserID, 10))
	case dst.PeerID != 0:
		values.Add("peer_id", strconv.FormatInt(dst.PeerID, 10))
	case dst.Domain != "":
		values.Add("domain", dst.Domain)
	case dst.ChatID != 0:
		values.Add("chat_id", strconv.FormatInt(dst.ChatID, 10))
	case dst.GroupID != 0:
		values.Add("group_id", strconv.FormatInt(dst.GroupID, 10))
	case dst.GroupName != "":
		values.Add("group_id", dst.GroupName)
	case len(dst.GroupIDs) != 0:
		values.Add("group_ids", ConcatInt64ToString(dst.GroupIDs...))
	case len(dst.GroupNames) > 0:
		values.Add("group_ids", strings.Join(dst.GroupNames, ","))
	case len(dst.UserIDs) != 0:
		values.Add("user_ids", ConcatInt64ToString(dst.UserIDs...))
	case dst.ScreenName != "":
		values.Add("user_id", dst.ScreenName)
	case len(dst.ScreenNames) > 0:
		values.Add("user_ids", strings.Join(dst.ScreenNames, ","))
	}

	return
}

// NewDstFromUserID creates a new MessageConfig instance from userID.
func NewDstFromUserID(userIDs ...int64) (dst Destination) {
	if len(userIDs) == 1 {
		dst.UserID = userIDs[0]
	} else {
		dst.UserIDs = userIDs
	}
	return
}

// NewDstFromScreenName creates a new MessageConfig instance from screenNames.
func NewDstFromScreenName(screenNames ...string) (dst Destination) {
	if len(screenNames) == 1 {
		dst.ScreenName = screenNames[0]
	} else {
		dst.ScreenNames = screenNames
	}
	return
}

// NewDstFromGroupName creates a new MessageConfig instance from groupNames.
func NewDstFromGroupName(groupNames ...string) (dst Destination) {
	if len(groupNames) == 1 {
		dst.GroupName = groupNames[0]
	} else {
		dst.GroupNames = groupNames
	}
	return
}

// NewDstFromPeerID creates a new MessageConfig instance from peerID.
func NewDstFromPeerID(peerID int64) (dst Destination) {
	dst.PeerID = peerID
	return
}

// NewDstFromChatID creates a new MessageConfig instance from chatID.
func NewDstFromChatID(chatID int64) (dst Destination) {
	dst.ChatID = chatID
	return
}

// NewDstFromGroupID creates a new MessageConfig instance from groupID.
func NewDstFromGroupID(groupIDs ...int64) (dst Destination) {
	if len(groupIDs) == 1 {
		dst.GroupID = groupIDs[0]
	} else {
		dst.GroupIDs = groupIDs
	}
	return
}

// NewDstFromDomain creates a new MessageConfig instance from domain.
func NewDstFromDomain(domain string) (dst Destination) {
	dst.Domain = domain
	return
}


text:
using System.Web;

using DogeNews.Services.Http.Contracts;

namespace DogeNews.Services.Http
{
    public class HttpContextService : IHttpContextService
    {
        public string GetQueryStringPairValue(string key)
        {
            string value = HttpContext.Current.Request.QueryString[key];
            return value;
        }

        public string GetLoggedInUserUsername()
        {
            string username = HttpContext.Current.User.Identity.Name;
            return username;
        }
    }
}


text:
package com.vapourdrive.sporecraft.event;

public class FMLEventHooks
{

}


text:
package observer;

import java.util.ArrayList;

public abstract class Arena {
	protected GameResult mGameResult;
	private ArrayList<ArenaViewer> Views = new ArrayList<ArenaViewer>();
	public GameResult getGameResult(){
		return mGameResult;
	}
	public void registerArenaViewer(ArenaViewer viewer){
		if(!Views.contains(viewer))Views.add(viewer);
	}
	public void unregisterArenaViewer(ArenaViewer viewer){
		if(Views.contains(viewer))Views.remove(viewer);
	}
	public void notifyViewers(){
		for(ArenaViewer viewer : Views){
			viewer.OnGameUpdate(mGameResult);
		}
	}
	public void onNewGameResult(GameResult gameResult ){
		mGameResult = gameResult;
		notifyViewers();
	}
}


text:
layout: posts_by_category
categories: puzzles
title: Puzzles
permalink: /category/puzzles
---


text:
<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Check;

use InvalidArgumentException;
use PhpSchool\PhpWorkshop\ComposerUtil\LockFileParser;
use PhpSchool\PhpWorkshop\Exercise\ExerciseInterface;
use PhpSchool\PhpWorkshop\Exercise\ExerciseType;
use PhpSchool\PhpWorkshop\ExerciseCheck\ComposerExerciseCheck;
use PhpSchool\PhpWorkshop\Input\Input;
use PhpSchool\PhpWorkshop\Result\Failure;
use PhpSchool\PhpWorkshop\Result\ResultInterface;
use PhpSchool\PhpWorkshop\Result\Success;

/**
 * This check looks for a set of composer packages specified by the exercise
 * in the students `composer.lock` file.
 */
class ComposerCheck implements SimpleCheckInterface
{
    /**
     * Return the check's name
     */
    public function getName(): string
    {
        return 'Composer Dependency Check';
    }

    /**
     * This check parses the `composer.lock` file and checks that the student
     * installed a set of required packages. If they did not a failure is returned, otherwise,
     * a success is returned.
     *
     * @param ExerciseInterface $exercise The exercise to check against.
     * @param Input $input The command line arguments passed to the command.
     * @return ResultInterface The result of the check.
     * @noinspection SpellCheckingInspection
     */
    public function check(ExerciseInterface $exercise, Input $input): ResultInterface
    {
        if (!$exercise instanceof ComposerExerciseCheck) {
            throw new InvalidArgumentException();
        }

        if (!file_exists(sprintf('%s/composer.json', dirname($input->getRequiredArgument('program'))))) {
            return new Failure($this->getName(), 'No composer.json file found');
        }

        if (!file_exists(sprintf('%s/composer.lock', dirname($input->getRequiredArgument('program'))))) {
            return new Failure($this->getName(), 'No composer.lock file found');
        }

        if (!file_exists(sprintf('%s/vendor', dirname($input->getRequiredArgument('program'))))) {
            return new Failure($this->getName(), 'No vendor folder found');
        }

        $lockFile = new LockFileParser(sprintf('%s/composer.lock', dirname($input->getRequiredArgument('program'))));
        $missingPackages = array_filter($exercise->getRequiredPackages(), function ($package) use ($lockFile) {
            return !$lockFile->hasInstalledPackage($package);
        });

        if (count($missingPackages) > 0) {
            return new Failure(
                $this->getName(),
                sprintf(
                    'Lockfile doesn\'t include the following packages at any version: "%s"',
                    implode('", "', $missingPackages)
                )
            );
        }

        return new Success($this->getName());
    }

    /**
     * This check can run on any exercise type.
     *
     * @param ExerciseType $exerciseType
     * @return bool
     */
    public function canRun(ExerciseType $exerciseType): bool
    {
        return in_array($exerciseType->getValue(), [ExerciseType::CGI, ExerciseType::CLI], true);
    }

    public function getExerciseInterface(): string
    {
        return ComposerExerciseCheck::class;
    }

    /**
     * This check can run before because if it fails, there is no point executing the solution.
     */
    public function getPosition(): string
    {
        return SimpleCheckInterface::CHECK_BEFORE;
    }
}


text:
import React, { PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import moment from 'moment';
import DayPicker from 'react-day-picker';

import {
	FormInput,
	FormSelect,
	Grid,
	SegmentedControl,
} from '../../../admin/client/App/elemental';

const INVERTED_OPTIONS = [
	{ label: 'Matches', value: false },
	{ label: 'Does NOT Match', value: true },
];

const MODE_OPTIONS = [
	{ label: 'On', value: 'on' },
	{ label: 'After', value: 'after' },
	{ label: 'Before', value: 'before' },
	{ label: 'Between', value: 'between' },
];

const DayPickerIndicator = ({ activeInputField }) => {
	const style = activeInputField === 'before' ? { left: '11rem' } : null;

	return (

	);
};

function getDefaultValue () {
	return {
		mode: MODE_OPTIONS[0].value,
		inverted: INVERTED_OPTIONS[0].value,
		value: moment(0, 'HH').format(),
		before: moment(0, 'HH').format(),
		after: moment(0, 'HH').format(),
	};
}

var DateFilter = React.createClass({
	displayName: 'DateFilter',
	propTypes: {
		filter: PropTypes.shape({
			mode: PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)),
			inverted: PropTypes.boolean,
		}),
	},
	statics: {
		getDefaultValue: getDefaultValue,
	},
	getDefaultProps () {
		return {
			format: 'DD-MM-YYYY',
			filter: getDefaultValue(),
			value: moment().startOf('day').toDate(),
		};
	},
	getInitialState () {
		return {
			activeInputField: 'after',
			month: new Date(), // The month to display in the calendar
		};
	},
	componentDidMount () {
		this.__isMounted = true;
	},
	componentWillUnmount () {
		this.__isMounted = false;
	},

	// ==============================
	// METHODS
	// ==============================

	updateFilter (value) {
		this.props.onChange({ ...this.props.filter, ...value });
	},
	toggleInverted (value) {
		this.updateFilter({ inverted: value });
		this.setFocus(this.props.filter.mode);
	},
	selectMode (e) {
		const mode = e.target.value;
		this.updateFilter({ mode });
		this.setFocus(mode);
	},
	setFocus (mode) {
		// give the UI a moment to render
		if (mode === 'between') {
			setTimeout(() => {
				findDOMNode(this.refs[this.state.activeInputField]).focus();
			}, 50);
		} else {
			setTimeout(() => {
				this.refs.input.focus();
			}, 50);
		}
	},
	handleInputChange (e) {
		// TODO @jedwatson
		// Entering virtually any value will return an "Invalid date", so I'm
		// temporarily disabling user entry. This entire component needs review.

		// const { value } = e.target;
		// let { month } = this.state;
		// // Change the current month only if the value entered by the user is a valid
		// // date, according to the `L` format
		// if (moment(value, 'L', true).isValid()) {
		// 	month = moment(value, 'L').toDate();
		// }
		// this.updateFilter({ value: value });
		// this.setState({ month }, this.showCurrentDate);
	},
	setActiveField (field) {
		this.setState({
			activeInputField: field,
		});
	},
	switchBetweenActiveInputFields (e, day, modifiers) {
		if (modifiers && modifiers.disabled) return;

		const { activeInputField } = this.state;
		const send = {};
		const newActiveField = activeInputField === 'before'
			? 'after'
			: 'before';
		send[activeInputField] = day;
		this.updateFilter(send);
		this.setState(
			{ activeInputField: newActiveField },
			() => {
				findDOMNode(this.refs[newActiveField]).focus();
			}
		);
	},
	selectDay (e, day, modifiers) {
		if (modifiers && modifiers.disabled) return;
		this.updateFilter({ value: day });
	},
	showCurrentDate () {
		// give the UI a moment to render
		setTimeout(() => {
			this.refs.daypicker.showMonth(this.state.month);
		}, 50);
	},

	// ==============================
	// RENDERERS
	// ==============================

	renderToggle () {
		const { filter } = this.props;
		return (

				<SegmentedControl
					equalWidthSegments
					onChange={this.toggleInverted}
					options={INVERTED_OPTIONS}
					value={filter.inverted}
				/>

		);
	},
	renderControls () {
		let controls;
		const { activeInputField } = this.state;
		const { field, filter } = this.props;
		const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
		const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...';

		// DayPicker Modifiers - Selected Day
		let modifiers = filter.mode === 'between' ? {
			selected: (day) => moment(filter[activeInputField]).isSame(day),
		} : {
			selected: (day) => moment(filter.value).isSame(day),
		};

		if (mode.value === 'between') {
			controls = (

						<Grid.Row xsmall="one-half" gutter={10}>
							<Grid.Col>
								<FormInput
									autoFocus
									ref="after"
									placeholder="From"
									onChange={this.handleInputChange}
									onFocus={() => this.setActiveField('after')}
									value={moment(filter.after).format(this.props.format)}
								/>
							</Grid.Col>
							<Grid.Col>
								<FormInput
									ref="before"
									placeholder="To"
									onChange={this.handleInputChange}
									onFocus={() => this.setActiveField('before')}
									value={moment(filter.before).format(this.props.format)}
								/>
							</Grid.Col>
						</Grid.Row>

						<DayPicker
							modifiers={modifiers}
							className="DayPicker--chrome"
							onDayClick={this.switchBetweenActiveInputFields}
						/>
						<DayPickerIndicator activeInputField={activeInputField} />

			);
		} else {
			controls = (

						<FormInput
							autoFocus
							ref="input"
							placeholder={placeholder}
							value={moment(filter.value).format(this.props.format)}
							onChange={this.handleInputChange}
							onFocus={this.showCurrentDate}
						/>

						<DayPicker
							ref="daypicker"
							modifiers={modifiers}
							className="DayPicker--chrome"
							onDayClick={this.selectDay}
						/>
						<DayPickerIndicator />

			);
		}

		return controls;
	},
	render () {
		const { filter } = this.props;
		const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
		return (

				{this.renderToggle()}

					<FormSelect
						options={MODE_OPTIONS}
						onChange={this.selectMode}
						value={mode.value}
					/>

				{this.renderControls()}

		);
	},
});

module.exports = DateFilter;


text:
using Android.OS;
#elif __IOS__ || __TVOS__
using Foundation;
using UIKit;
#elif WINDOWS_PHONE
using Microsoft.Phone.Info;
#endif
using System;

namespace InTheHand.Security.ExchangeActivesyncProvisioning
{
    /// <summary>
    /// Provides the app the ability to retrieve device information from the local device.
    /// </summary>
    /// <remarks>
    /// <para/><list type="table">
    /// <listheader><term>Platform</term><description>Version supported</description></listheader>
    /// <item><term>iOS</term><description>iOS 9.0 and later</description></item>
    /// <item><term>tvOS</term><description>tvOS 9.0 and later</description></item>
    /// <item><term>Windows UWP</term><description>Windows 10</description></item>
    /// <item><term>Windows Store</term><description>Windows 8.1 or later</description></item>
    /// <item><term>Windows Phone Store</term><description>Windows Phone 8.1 or later</description></item></list>
    /// <item><term>Windows Phone Silverlight</term><description>Windows Phone 8.0 or later</description></item>
    /// </remarks>
    public sealed class EasClientDeviceInformation
    {
#if __IOS__ || __TVOS__
        private UIDevice _device;
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP
        private Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation _deviceInformation;

        public static implicit operator Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation(EasClientDeviceInformation i)
        {
            return i._deviceInformation;
        }
#endif

        /// <summary>
        /// Creates an instance of an object that allows the caller app to retrieve device information from the local device.
        /// </summary>
        public EasClientDeviceInformation()
        {
#if __IOS__ || __TVOS__
            _device = UIDevice.CurrentDevice;
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP
            _deviceInformation = new Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation();
#endif
        }

        /// <summary>
        /// Returns the friendly name of the local device.
        /// </summary>
        public string FriendlyName
        {
            get
            {
#if __IOS__ || __TVOS__
                return _device.Name;
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP
                return _deviceInformation.FriendlyName;
#elif WINDOWS_PHONE
                return Windows.Networking.Proximity.PeerFinder.DisplayName;
#else
                throw new PlatformNotSupportedException();
#endif
            }
        }

        /// <summary>
        /// Returns the identifier of the local device.
        /// </summary>
        /// <remarks>For Windows Phone (Silverlight) apps you must declare the ID_CAP_IDENTITY_DEVICE capability in your WMAppManifest.</remarks>
        public Guid Id
        {
            get
            {
#if __IOS__ || __TVOS__
                return new Guid(_device.IdentifierForVendor.GetBytes());
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP
                return _deviceInformation.Id;
#elif WINDOWS_PHONE
                byte[] raw = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
                byte[] trimmed = new byte[16];
                Buffer.BlockCopy(raw, 0, trimmed, 0, 16);
                return new Guid(trimmed);
#else
                throw new PlatformNotSupportedException();
#endif
            }
        }

        /// <summary>
        /// Returns the operating system of the local device.
        /// </summary>
        public string OperatingSystem
        {
            get
            {
#if __IOS__
                return "Apple iOS";
#elif __TVOS__
                return "Apple tvOS";
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP
                return _deviceInformation.OperatingSystem;
#elif WINDOWS_PHONE
                return "Windows Phone";
#else
                throw new PlatformNotSupportedException();
#endif
            }
        }

        /// <summary>
        /// Returns the system manufacturer of the local device. Use this only if the SystemSku is empty.
        /// </summary>
        public string SystemManufacturer
        {
            get
            {
#if __IOS__ || __TVOS__
                return "Apple";
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP
                return _deviceInformation.SystemManufacturer;
#elif WINDOWS_PHONE
                return DeviceStatus.DeviceManufacturer;
#else
                throw new PlatformNotSupportedException();
#endif
            }
        }

        /// <summary>
        /// Returns the system product name of the local device.
        /// </summary>
        public string SystemProductName
        {
            get
            {
#if __IOS__ || __TVOS__
                return _device.Model;
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP
                return _deviceInformation.SystemProductName;
#elif WINDOWS_PHONE
                return DeviceStatus.DeviceName;
#else
                throw new PlatformNotSupportedException();
#endif
            }
        }

    }
}


text:
@interface UIImage (AdditionalFunctionalities)

//TintColor...
- (UIImage *)imageWithTint:(UIColor *)tintColor;
//scale and resize...
- (UIImage *)scaleToSize:(CGSize)size;

@end


text:
angular.module('stockMarketApp')
  .directive('stockWidget', [function() {
    return {
      templateUrl: 'stock.html',
      restrict: 'A',
      scope: {
        stockData: '='
      },
      link: function($scope, $element, $attrs) {
        $scope.getChange = function(stock) {
          return Math.ceil(((stock.price - stock.previous) /
              stock.previous) * 100);
        };
      }
    };
  }]);


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

package com.azure.resourcemanager.apimanagement.models;

import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.apimanagement.fluent.models.GroupContractProperties;
import com.azure.resourcemanager.apimanagement.fluent.models.UserContractInner;
import com.azure.resourcemanager.apimanagement.fluent.models.UserIdentityContractInner;
import java.time.OffsetDateTime;
import java.util.List;

/** An immutable client-side representation of UserContract. */
public interface UserContract {
    /**
     * Gets the id property: Fully qualified resource Id for the resource.
     *
     * @return the id value.
     */
    String id();

    /**
     * Gets the name property: The name of the resource.
     *
     * @return the name value.
     */
    String name();

    /**
     * Gets the type property: The type of the resource.
     *
     * @return the type value.
     */
    String type();

    /**
     * Gets the firstName property: First name.
     *
     * @return the firstName value.
     */
    String firstName();

    /**
     * Gets the lastName property: Last name.
     *
     * @return the lastName value.
     */
    String lastName();

    /**
     * Gets the email property: Email address.
     *
     * @return the email value.
     */
    String email();

    /**
     * Gets the registrationDate property: Date of user registration. The date conforms to the following format:
     * `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
     *
     * @return the registrationDate value.
     */
    OffsetDateTime registrationDate();

    /**
     * Gets the groups property: Collection of groups user is part of.
     *
     * @return the groups value.
     */
    List<GroupContractProperties> groups();

    /**
     * Gets the state property: Account state. Specifies whether the user is active or not. Blocked users are unable to
     * sign into the developer portal or call any APIs of subscribed products. Default state is Active.
     *
     * @return the state value.
     */
    UserState state();

    /**
     * Gets the note property: Optional note about a user set by the administrator.
     *
     * @return the note value.
     */
    String note();

    /**
     * Gets the identities property: Collection of user identities.
     *
     * @return the identities value.
     */
    List<UserIdentityContract> identities();

    /**
     * Gets the inner com.azure.resourcemanager.apimanagement.fluent.models.UserContractInner object.
     *
     * @return the inner object.
     */
    UserContractInner innerModel();

    /** The entirety of the UserContract definition. */
    interface Definition
        extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate {
    }
    /** The UserContract definition stages. */
    interface DefinitionStages {
        /** The first stage of the UserContract definition. */
        interface Blank extends WithParentResource {
        }
        /** The stage of the UserContract definition allowing to specify parent resource. */
        interface WithParentResource {
            /**
             * Specifies resourceGroupName, serviceName.
             *
             * @param resourceGroupName The name of the resource group.
             * @param serviceName The name of the API Management service.
             * @return the next definition stage.
             */
            WithCreate withExistingService(String resourceGroupName, String serviceName);
        }
        /**
         * The stage of the UserContract definition which contains all the minimum required properties for the resource
         * to be created, but also allows for any other optional properties to be specified.
         */
        interface WithCreate
            extends DefinitionStages.WithEmail,
                DefinitionStages.WithFirstName,
                DefinitionStages.WithLastName,
                DefinitionStages.WithPassword,
                DefinitionStages.WithAppType,
                DefinitionStages.WithConfirmation,
                DefinitionStages.WithState,
                DefinitionStages.WithNote,
                DefinitionStages.WithIdentities,
                DefinitionStages.WithNotify,
                DefinitionStages.WithIfMatch {
            /**
             * Executes the create request.
             *
             * @return the created resource.
             */
            UserContract create();

            /**
             * Executes the create request.
             *
             * @param context The context to associate with this operation.
             * @return the created resource.
             */
            UserContract create(Context context);
        }
        /** The stage of the UserContract definition allowing to specify email. */
        interface WithEmail {
            /**
             * Specifies the email property: Email address. Must not be empty and must be unique within the service
             * instance..
             *
             * @param email Email address. Must not be empty and must be unique within the service instance.
             * @return the next definition stage.
             */
            WithCreate withEmail(String email);
        }
        /** The stage of the UserContract definition allowing to specify firstName. */
        interface WithFirstName {
            /**
             * Specifies the firstName property: First name..
             *
             * @param firstName First name.
             * @return the next definition stage.
             */
            WithCreate withFirstName(String firstName);
        }
        /** The stage of the UserContract definition allowing to specify lastName. */
        interface WithLastName {
            /**
             * Specifies the lastName property: Last name..
             *
             * @param lastName Last name.
             * @return the next definition stage.
             */
            WithCreate withLastName(String lastName);
        }
        /** The stage of the UserContract definition allowing to specify password. */
        interface WithPassword {
            /**
             * Specifies the password property: User Password. If no value is provided, a default password is
             * generated..
             *
             * @param password User Password. If no value is provided, a default password is generated.
             * @return the next definition stage.
             */
            WithCreate withPassword(String password);
        }
        /** The stage of the UserContract definition allowing to specify appType. */
        interface WithAppType {
            /**
             * Specifies the appType property: Determines the type of application which send the create user request.
             * Default is legacy portal..
             *
             * @param appType Determines the type of application which send the create user request. Default is legacy
             *     portal.
             * @return the next definition stage.
             */
            WithCreate withAppType(AppType appType);
        }
        /** The stage of the UserContract definition allowing to specify confirmation. */
        interface WithConfirmation {
            /**
             * Specifies the confirmation property: Determines the type of confirmation e-mail that will be sent to the
             * newly created user..
             *
             * @param confirmation Determines the type of confirmation e-mail that will be sent to the newly created
             *     user.
             * @return the next definition stage.
             */
            WithCreate withConfirmation(Confirmation confirmation);
        }
        /** The stage of the UserContract definition allowing to specify state. */
        interface WithState {
            /**
             * Specifies the state property: Account state. Specifies whether the user is active or not. Blocked users
             * are unable to sign into the developer portal or call any APIs of subscribed products. Default state is
             * Active..
             *
             * @param state Account state. Specifies whether the user is active or not. Blocked users are unable to sign
             *     into the developer portal or call any APIs of subscribed products. Default state is Active.
             * @return the next definition stage.
             */
            WithCreate withState(UserState state);
        }
        /** The stage of the UserContract definition allowing to specify note. */
        interface WithNote {
            /**
             * Specifies the note property: Optional note about a user set by the administrator..
             *
             * @param note Optional note about a user set by the administrator.
             * @return the next definition stage.
             */
            WithCreate withNote(String note);
        }
        /** The stage of the UserContract definition allowing to specify identities. */
        interface WithIdentities {
            /**
             * Specifies the identities property: Collection of user identities..
             *
             * @param identities Collection of user identities.
             * @return the next definition stage.
             */
            WithCreate withIdentities(List<UserIdentityContractInner> identities);
        }
        /** The stage of the UserContract definition allowing to specify notify. */
        interface WithNotify {
            /**
             * Specifies the notify property: Send an Email notification to the User..
             *
             * @param notify Send an Email notification to the User.
             * @return the next definition stage.
             */
            WithCreate withNotify(Boolean notify);
        }
        /** The stage of the UserContract definition allowing to specify ifMatch. */
        interface WithIfMatch {
            /**
             * Specifies the ifMatch property: ETag of the Entity. Not required when creating an entity, but required
             * when updating an entity..
             *
             * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an
             *     entity.
             * @return the next definition stage.
             */
            WithCreate withIfMatch(String ifMatch);
        }
    }
    /**
     * Begins update for the UserContract resource.
     *
     * @return the stage of resource update.
     */
    UserContract.Update update();

    /** The template for UserContract update. */
    interface Update
        extends UpdateStages.WithEmail,
            UpdateStages.WithPassword,
            UpdateStages.WithFirstName,
            UpdateStages.WithLastName,
            UpdateStages.WithState,
            UpdateStages.WithNote,
            UpdateStages.WithIdentities,
            UpdateStages.WithIfMatch {
        /**
         * Executes the update request.
         *
         * @return the updated resource.
         */
        UserContract apply();

        /**
         * Executes the update request.
         *
         * @param context The context to associate with this operation.
         * @return the updated resource.
         */
        UserContract apply(Context context);
    }
    /** The UserContract update stages. */
    interface UpdateStages {
        /** The stage of the UserContract update allowing to specify email. */
        interface WithEmail {
            /**
             * Specifies the email property: Email address. Must not be empty and must be unique within the service
             * instance..
             *
             * @param email Email address. Must not be empty and must be unique within the service instance.
             * @return the next definition stage.
             */
            Update withEmail(String email);
        }
        /** The stage of the UserContract update allowing to specify password. */
        interface WithPassword {
            /**
             * Specifies the password property: User Password..
             *
             * @param password User Password.
             * @return the next definition stage.
             */
            Update withPassword(String password);
        }
        /** The stage of the UserContract update allowing to specify firstName. */
        interface WithFirstName {
            /**
             * Specifies the firstName property: First name..
             *
             * @param firstName First name.
             * @return the next definition stage.
             */
            Update withFirstName(String firstName);
        }
        /** The stage of the UserContract update allowing to specify lastName. */
        interface WithLastName {
            /**
             * Specifies the lastName property: Last name..
             *
             * @param lastName Last name.
             * @return the next definition stage.
             */
            Update withLastName(String lastName);
        }
        /** The stage of the UserContract update allowing to specify state. */
        interface WithState {
            /**
             * Specifies the state property: Account state. Specifies whether the user is active or not. Blocked users
             * are unable to sign into the developer portal or call any APIs of subscribed products. Default state is
             * Active..
             *
             * @param state Account state. Specifies whether the user is active or not. Blocked users are unable to sign
             *     into the developer portal or call any APIs of subscribed products. Default state is Active.
             * @return the next definition stage.
             */
            Update withState(UserState state);
        }
        /** The stage of the UserContract update allowing to specify note. */
        interface WithNote {
            /**
             * Specifies the note property: Optional note about a user set by the administrator..
             *
             * @param note Optional note about a user set by the administrator.
             * @return the next definition stage.
             */
            Update withNote(String note);
        }
        /** The stage of the UserContract update allowing to specify identities. */
        interface WithIdentities {
            /**
             * Specifies the identities property: Collection of user identities..
             *
             * @param identities Collection of user identities.
             * @return the next definition stage.
             */
            Update withIdentities(List<UserIdentityContractInner> identities);
        }
        /** The stage of the UserContract update allowing to specify ifMatch. */
        interface WithIfMatch {
            /**
             * Specifies the ifMatch property: ETag of the Entity. ETag should match the current entity state from the
             * header response of the GET request or it should be * for unconditional update..
             *
             * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of
             *     the GET request or it should be * for unconditional update.
             * @return the next definition stage.
             */
            Update withIfMatch(String ifMatch);
        }
    }
    /**
     * Refreshes the resource to sync with Azure.
     *
     * @return the refreshed resource.
     */
    UserContract refresh();

    /**
     * Refreshes the resource to sync with Azure.
     *
     * @param context The context to associate with this operation.
     * @return the refreshed resource.
     */
    UserContract refresh(Context context);

    /**
     * Retrieves a redirection URL containing an authentication token for signing a given user into the developer
     * portal.
     *
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return generate SSO Url operations response details.
     */
    GenerateSsoUrlResult generateSsoUrl();

    /**
     * Retrieves a redirection URL containing an authentication token for signing a given user into the developer
     * portal.
     *
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return generate SSO Url operations response details along with {@link Response}.
     */
    Response<GenerateSsoUrlResult> generateSsoUrlWithResponse(Context context);

    /**
     * Gets the Shared Access Authorization Token for the User.
     *
     * @param parameters Create Authorization Token parameters.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the Shared Access Authorization Token for the User.
     */
    UserTokenResult getSharedAccessToken(UserTokenParameters parameters);

    /**
     * Gets the Shared Access Authorization Token for the User.
     *
     * @param parameters Create Authorization Token parameters.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the Shared Access Authorization Token for the User along with {@link Response}.
     */
    Response<UserTokenResult> getSharedAccessTokenWithResponse(UserTokenParameters parameters, Context context);
}


text:
/******************************************************************************
  This source file is part of the Avogadro project.
  This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/

#include "closecontacts.h"

#include <avogadro/core/array.h>
#include <avogadro/core/atom.h>
#include <avogadro/core/bond.h>
#include <avogadro/core/elements.h>
#include <avogadro/core/neighborperceiver.h>
#include <avogadro/core/residue.h>
#include <avogadro/qtgui/molecule.h>
#include <avogadro/rendering/dashedlinegeometry.h>
#include <avogadro/rendering/geometrynode.h>
#include <avogadro/rendering/groupnode.h>

#include <QtCore/QSettings>
#include <QtWidgets/QDoubleSpinBox>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>

namespace Avogadro::QtPlugins {

using Core::Array;
using Core::Atom;
using Core::Bond;
using Core::NeighborPerceiver;
using QtGui::Molecule;
using QtGui::PluginLayerManager;
using Rendering::DashedLineGeometry;
using Rendering::GeometryNode;
using Rendering::GroupNode;

CloseContacts::CloseContacts(QObject *p) : ScenePlugin(p)
{
  m_layerManager = PluginLayerManager(m_name);

  QSettings settings;
  m_maximumDistances = {
    settings.value("closeContacts/maximumDistance0", 2.0).toDouble(),
    settings.value("closeContacts/maximumDistance1", 4.0).toDouble(),
    settings.value("closeContacts/maximumDistance2", 4.0).toDouble()
  };
  auto contactColor = settings.value("closeContacts/lineColor0", QColor(128, 128, 128)).value<QColor>();
  auto saltBColor = settings.value("closeContacts/lineColor1", QColor(192, 0, 255)).value<QColor>();
  auto repulsiveColor = settings.value("closeContacts/lineColor2", QColor(255, 64, 64)).value<QColor>();
  m_lineColors = {
    Vector3ub(contactColor.red(), contactColor.green(), contactColor.blue()),
    Vector3ub(saltBColor.red(), saltBColor.green(), saltBColor.blue()),
    Vector3ub(repulsiveColor.red(), repulsiveColor.green(), repulsiveColor.blue())
  };
  m_lineWidths = {
    settings.value("closeContacts/lineWidth0", 2.0).toFloat(),
    settings.value("closeContacts/lineWidth1", 5.0).toFloat(),
    settings.value("closeContacts/lineWidth2", 5.0).toFloat()
  };
}

CloseContacts::~CloseContacts() {}

static bool checkPairNot1213(const Molecule &molecule, Index i, Index n)
{
  static Array<Index> bondedCache;
  static Index lastIndex;
  static bool lastIndexValid = false;

  if (!lastIndexValid || lastIndex != i) {
    bondedCache.clear();
    for (const Bond *b : molecule.bonds(i))
      bondedCache.push_back(b->atom1().index() == i ? b->atom2().index() : b->atom1().index());
    lastIndex = i;
    lastIndexValid = true;
  }

  for (const Bond *b : molecule.bonds(n)) {
    Index m = (b->atom1().index() == n ? b->atom2() : b->atom1()).index();
    if (m == i) // exclude 1-2 pairs
      return false;
    for (Index bn: bondedCache)
      if (bn == m) // exclude 1-3 pairs
        return false;
  }
  return true;
}

void addChargedAtom(
  Array<Vector3> &positions, Array<signed char> &charges, Array<Index> &residues,
  const Molecule &molecule, Index residueId, Atom atom, double charge
) {
  auto pos = molecule.atomPosition3d(atom.index());
  if (molecule.formalCharge(atom.index()) != 0) {
    for (Index i = 0; i < positions.size(); i++) {
      if ((positions[i] - pos).norm() < 0.00001) {
        residues[i] = residueId;
        return;
      }
    }
  }
  positions.push_back(pos);
  charges.push_back(charge);
  residues.push_back(residueId);
}

void CloseContacts::process(const Molecule &molecule, Rendering::GroupNode &node)
{
  //Add general contacts
  NeighborPerceiver perceiver(molecule.atomPositions3d(), m_maximumDistances[0]);
  std::vector<bool> isAtomEnabled(molecule.atomCount());
  for (Index i = 0; i < molecule.atomCount(); ++i)
    isAtomEnabled[i] = m_layerManager.atomEnabled(i);

  auto *geometry = new GeometryNode;
  node.addChild(geometry);
  std::array<DashedLineGeometry *, 3> lineGroups;
  for (Index type = 0; type < 3; type++) {
    lineGroups[type] = new DashedLineGeometry;
    lineGroups[type]->identifier().molecule = &molecule;
    lineGroups[type]->identifier().type = Rendering::BondType;
    lineGroups[type]->setLineWidth(m_lineWidths[type]);
    geometry->addDrawable(lineGroups[type]);
  }

  Array<Index> neighbors;
  for (Index i = 0; i < molecule.atomCount(); ++i) {
    if (!isAtomEnabled[i])
      continue;
    Vector3 pos = molecule.atomPosition3d(i);
    perceiver.getNeighborsInclusiveInPlace(neighbors, pos);
    for (Index n : neighbors) {
      if (n <= i) // check each pair only once
        continue;
      if (!isAtomEnabled[n])
        continue;
      if (!checkPairNot1213(molecule, i, n))
        continue;

      Vector3 npos = molecule.atomPosition3d(n);
      double distance = (npos - pos).norm();
      if (distance < m_maximumDistances[0])
        lineGroups[0]->addDashedLine(pos.cast<float>(), npos.cast<float>(), m_lineColors[0], 8);
    }
  }

  // Add charged atoms
  Array<Vector3> positions;
  Array<signed char> charges;
  Array<Index> residues;
  for (Index i = 0; i < molecule.atomCount(); ++i) {
    if (molecule.formalCharge(i) != 0) {
      if (!isAtomEnabled[i])
        continue;
      positions.push_back(molecule.atomPosition3d(i));
      charges.push_back(molecule.formalCharge(i));
      residues.push_back(Index(0) - 1);
    }
  }

  // Add predicted charged atoms from residues
  for (const auto &r: molecule.residues()) {
    if (!r.residueName().compare("LYS")) {
      addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("NZ"), 1.0);
    } else if (!r.residueName().compare("ARG")) {
      addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("NE"), 1.0);
      addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("NH1"), 1.0);
      addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("NH2"), 1.0);
    } else if (!r.residueName().compare("HIS")) {
      addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("ND1"), 1.0);
    } else if (!r.residueName().compare("ASP")) {
      addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("OD1"), -1.0);
      addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("OD2"), -1.0);
    } else if (!r.residueName().compare("GLU")) {
      addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("OE1"), -1.0);
      addChargedAtom(positions, charges, residues, molecule, r.residueId(), r.getAtomByName("OE2"), -1.0);
    }
  }

  // detect contacts among them
  NeighborPerceiver ionPerceiver(positions, std::max(m_maximumDistances[1], m_maximumDistances[2]));
  for (Index i = 0; i < positions.size(); ++i) {
    const Vector3 &pos = positions[i];
    ionPerceiver.getNeighborsInclusiveInPlace(neighbors, pos);
    for (Index n: neighbors) {
      if (n <= i) // check each pair only once
        continue;
      if (residues[n] == residues[i] && residues[i] != Index(0) - 1)
        continue; // ignore intra-residue interactions

      Vector3 npos = positions[n];
      double distance = (npos - pos).norm();

      if (charges[i] * charges[n] > 0.0 && distance < m_maximumDistances[2])
        lineGroups[2]->addDashedLine(pos.cast<float>(), npos.cast<float>(), m_lineColors[2], 8);
      else if (distance < m_maximumDistances[1])
        lineGroups[1]->addDashedLine(pos.cast<float>(), npos.cast<float>(), m_lineColors[1], 8);
    }
  }
}

QWidget *CloseContacts::setupWidget()
{
  auto *widget = new QWidget(qobject_cast<QWidget *>(this->parent()));
  auto *v = new QVBoxLayout;
  auto *tabs = new QTabWidget;

  for (Index i = 0; i < 3; i++) {
    // maximum distance
    auto *distance_spin = new QDoubleSpinBox;
    distance_spin->setRange(1.5, 10.0);
    distance_spin->setSingleStep(0.1);
    distance_spin->setDecimals(1);
    distance_spin->setSuffix(tr(" Å"));
    distance_spin->setValue(m_maximumDistances[i]);
    QObject::connect(distance_spin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
			[this, i](float distance){ return setMaximumDistance(distance, i); }
		);

    // line width
		auto* lineWidth_spin = new QDoubleSpinBox;
		lineWidth_spin->setRange(1.0, 10.0);
		lineWidth_spin->setSingleStep(0.5);
		lineWidth_spin->setDecimals(1);
		lineWidth_spin->setValue(m_lineWidths[i]);
		QObject::connect(lineWidth_spin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
		    [this, i](float width){ return setLineWidth(width, i); }
		);

    auto *form = new QFormLayout;
    form->addRow(QObject::tr("Maximum distance:"), distance_spin);
    form->addRow(QObject::tr("Line width:"), lineWidth_spin);

    auto *page = new QWidget;
  	page->setLayout(form);
  	tabs->addTab(page, INTERACTION_NAMES[i]);
  }

  v->addWidget(tabs);
  v->addStretch(1);
  widget->setLayout(v);
  return widget;
}

void CloseContacts::setMaximumDistance(float maximumDistance, Index index)
{
  m_maximumDistances[index] = maximumDistance;
  emit drawablesChanged();

  QSettings settings;
  settings.setValue(QString("closeContacts/maximumDistance%1").arg(index), maximumDistance);
}

void CloseContacts::setLineWidth(float width, Index index)
{
  m_lineWidths[index] = width;
  emit drawablesChanged();

  QSettings settings;
  settings.setValue(QString("closeContacts/lineWidth%1").arg(index), width);
}

} // namespace Avogadro