text:
// This class has been generated, DO NOT EDIT!

package org.tensorflow.op.image;

import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.Operands;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.TString;
import org.tensorflow.types.TUint8;
import org.tensorflow.types.family.TNumber;

/**
 * Decode a PNG-encoded image to a uint8 or uint16 tensor.
 * The attr {@code channels} indicates the desired number of color channels for the
 * decoded image.
 *
Accepted values are:
 *

 *
0: Use the number of channels in the PNG-encoded image.

 *
1: output a grayscale image.

 *
3: output an RGB image.

 *
4: output an RGBA image.

 *

 *
If needed, the PNG-encoded image is transformed to match the requested number
 * of color channels.
 *
This op also supports decoding JPEGs and non-animated GIFs since the interface
 * is the same, though it is cleaner to use {@code tf.io.decode_image}.
 *
 * @param <T> data type for {@code image} output
 */
@OpMetadata(
    opType = DecodePng.OP_NAME,
    inputsClass = DecodePng.Inputs.class
)
@Operator(
    group = "image"
)
public final class DecodePng<T extends TNumber> extends RawOp implements Operand<T> {
  /**
   * The name of this op, as known by TensorFlow core engine
   */
  public static final String OP_NAME = "DecodePng";

  private Output<T> image;

  public DecodePng(Operation operation) {
    super(operation, OP_NAME);
    int outputIdx = 0;
    image = operation.output(outputIdx++);
  }

  /**
   * Factory method to create a class wrapping a new DecodePng operation.
   *
   * @param scope current scope
   * @param contents 0-D.  The PNG-encoded image.
   * @param dtype The value of the dtype attribute
   * @param options carries optional attribute values
   * @param <T> data type for {@code DecodePng} output and operands
   * @return a new instance of DecodePng
   */
  @Endpoint(
      describeByClass = true
  )
  public static <T extends TNumber> DecodePng<T> create(Scope scope, Operand<TString> contents,
      Class<T> dtype, Options... options) {
    OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "DecodePng");
    opBuilder.addInput(contents.asOutput());
    opBuilder.setAttr("dtype", Operands.toDataType(dtype));
    if (options != null) {
      for (Options opts : options) {
        if (opts.channels != null) {
          opBuilder.setAttr("channels", opts.channels);
        }
      }
    }
    return new DecodePng<>(opBuilder.build());
  }

  /**
   * Factory method to create a class wrapping a new DecodePng operation, with the default output types.
   *
   * @param scope current scope
   * @param contents 0-D.  The PNG-encoded image.
   * @param options carries optional attribute values
   * @return a new instance of DecodePng, with default output types
   */
  @Endpoint(
      describeByClass = true
  )
  public static DecodePng<TUint8> create(Scope scope, Operand<TString> contents,
      Options[] options) {
    return create(scope, contents, TUint8.class, options);
  }

  /**
   * Sets the channels option.
   *
   * @param channels Number of color channels for the decoded image.
   * @return this Options instance.
   */
  public static Options channels(Long channels) {
    return new Options().channels(channels);
  }

  /**
   * Gets image.
   * 3-D with shape {@code [height, width, channels]}.
   * @return image.
   */
  public Output<T> image() {
    return image;
  }

  @Override
  public Output<T> asOutput() {
    return image;
  }

  /**
   * Optional attributes for {@link org.tensorflow.op.image.DecodePng}
   */
  public static class Options {
    private Long channels;

    private Options() {
    }

    /**
     * Sets the channels option.
     *
     * @param channels Number of color channels for the decoded image.
     * @return this Options instance.
     */
    public Options channels(Long channels) {
      this.channels = channels;
      return this;
    }
  }

  @OpInputsMetadata(
      outputsClass = DecodePng.class
  )
  public static class Inputs extends RawOpInputs<DecodePng<?>> {
    /**
     * 0-D.  The PNG-encoded image.
     */
    public final Operand<TString> contents;

    /**
     * Number of color channels for the decoded image.
     */
    public final long channels;

    /**
     * The dtype attribute
     */
    public final DataType dtype;

    public Inputs(GraphOperation op) {
      super(new DecodePng<>(op), op, Arrays.asList("channels", "dtype"));
      int inputIndex = 0;
      contents = (Operand<TString>) op.input(inputIndex++);
      channels = op.attributes().getAttrInt("channels");
      dtype = op.attributes().getAttrType("dtype");
    }
  }
}


text:
package gocube

// A Solver finds shorter and shorter solutions in the background.
type Solver struct {
	stopper   chan struct{}
	solutions chan []Move
	phase1    *Phase1Solver
}

// NewSolver creates a new solver.
func NewSolver(c CubieCube, max int) *Solver {
	p1Moves := NewPhase1Moves()
	p1Heuristic := NewPhase1Heuristic(p1Moves)

	res := new(Solver)
	res.stopper = make(chan struct{})
	res.solutions = make(chan []Move)
	res.phase1 = NewPhase1Solver(c.Phase1Cube(), p1Heuristic, p1Moves)

	go res.backgroundLoop(c, nil, max)
	return res
}

// NewSolverTables creates a new solver using a set of pre-generated tables.
func NewSolverTables(c CubieCube, max int, tables SolverTables) *Solver {
	res := new(Solver)
	res.stopper = make(chan struct{})
	res.solutions = make(chan []Move)
	res.phase1 = NewPhase1Solver(c.Phase1Cube(), tables.P1Heuristic,
		tables.P1Moves)

	go res.backgroundLoop(c, &tables, max)
	return res
}

// Solutions is a channel over which shorter and shorter solutions are
// delivered.
func (s *Solver) Solutions() <-chan []Move {
	return s.solutions
}

// Stop stops the solver.
func (s *Solver) Stop() {
	s.phase1.Stop()
	close(s.stopper)
}

func (s *Solver) backgroundLoop(c CubieCube, tables *SolverTables, max int) {
	// Get the tables.
	var p2Moves *Phase2Moves
	var p2Heuristic *Phase2Heuristic
	if tables != nil {
		p2Moves = tables.P2Moves
		p2Heuristic = tables.P2Heuristic
	} else {
		p2Moves = NewPhase2Moves()
		p2Heuristic = NewPhase2Heuristic(p2Moves, false)
	}

OuterLoop:
	for p1Solution := range s.phase1.Solutions() {
		if len(p1Solution.Moves) > max {
			s.Stop()
			break
		}

		// Generate the cube after solving phase1.
		cube := c
		for _, m := range p1Solution.Moves {
			cube.Move(m)
		}
		// The phase-1 solution could be in the x, y, or z axis. We will go
		// through each axis and try solving it.
		x, y, z := p1Solution.Cube.Solved()
		for axis, solved := range []bool{x, y, z} {
			if !solved {
				continue
			}

			// Create the phase-2 cube and solve it.
			cube, err := NewPhase2Cube(cube, axis)
			if err != nil {
				continue
			}
			p2Solution := SolvePhase2(cube, max-len(p1Solution.Moves),
				p2Heuristic, p2Moves)
			if p2Solution == nil {
				continue
			}

			// Join the two solutions.
			solution := make([]Move, len(p1Solution.Moves))
			copy(solution, p1Solution.Moves)
			for _, move := range p2Solution {
				solution = append(solution, move.Move(axis))
			}
			max = len(solution) - 1
			select {
			case <-s.stopper:
				break OuterLoop
			case s.solutions <- solution:
			}
			if len(p2Solution) == 0 {
				break OuterLoop
			}
		}
	}
	close(s.solutions)
}

type SolverTables struct {
	P1Heuristic *Phase1Heuristic
	P1Moves     *Phase1Moves
	P2Heuristic *Phase2Heuristic
	P2Moves     *Phase2Moves
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to Apereo under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Apereo licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file
    except in compliance with the License.  You may obtain a
    copy of the License at the following location:

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

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

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="monitor"
          class="org.jasig.cas.monitor.ConnectionFactoryMonitor"
          c:factory-ref="provisioningConnectionFactory"
          c:validator-ref="searchValidator" />

</beans>


text:
import * as Container from '../../../util/container'
import * as ProfileGen from '../../../actions/profile-gen'
import * as RouteTreeGen from '../../../actions/route-tree-gen'
import openURL from '../../../util/open-url'
import EnterUsername from '.'

type OwnProps = {}

const ConnectedEnterUsername = Container.connect(
  state => {
    const {profile} = state
    const {username, platformGenericParams, platformGenericURL, errorText, platformGenericChecking} = profile
    return {
      _platformURL: platformGenericURL,
      error: errorText,
      serviceIcon: platformGenericParams?.logoBlack ?? [],
      serviceIconFull: platformGenericParams?.logoFull ?? [],
      serviceName: platformGenericParams?.title ?? '',
      serviceSub: platformGenericParams?.subtext ?? '',
      serviceSuffix: platformGenericParams?.suffix ?? '',
      submitButtonLabel: platformGenericParams?.buttonLabel ?? 'Submit',
      unreachable: !!platformGenericURL,
      username: username,
      waiting: platformGenericChecking,
    }
  },
  dispatch => ({
    onBack: () => {
      dispatch(ProfileGen.createCancelAddProof())
      dispatch(RouteTreeGen.createClearModals())
    },
    onChangeUsername: (username: string) => dispatch(ProfileGen.createUpdateUsername({username})),
    onContinue: () => dispatch(RouteTreeGen.createNavigateAppend({path: ['profileGenericProofResult']})),
    onSubmit: () => dispatch(ProfileGen.createSubmitUsername()),
  }),
  (stateProps, dispatchProps, _: OwnProps) => ({
    error: stateProps.error,
    onBack: dispatchProps.onBack,
    onCancel: dispatchProps.onBack,
    onChangeUsername: dispatchProps.onChangeUsername,
    onContinue: dispatchProps.onContinue,
    onSubmit: stateProps._platformURL
      ? () => stateProps._platformURL && openURL(stateProps._platformURL)
      : dispatchProps.onSubmit,
    serviceIcon: stateProps.serviceIcon,
    serviceIconFull: stateProps.serviceIconFull,
    serviceName: stateProps.serviceName,
    serviceSub: stateProps.serviceSub,
    serviceSuffix: stateProps.serviceSuffix,
    submitButtonLabel: stateProps.submitButtonLabel,
    unreachable: stateProps.unreachable,
    username: stateProps.username,
    waiting: stateProps.waiting,
  })
)(EnterUsername)

export default ConnectedEnterUsername


text:
"""
This creates an index.html file for the find-links directory on the openmdao.org site.
"""

import fnmatch
import hashlib
import os.path

def find_files(startdir, pats):
    """Return a list of files (using a generator) that match
    the given list of glob patterns. Walks an entire directory structure.
    """
    match = fnmatch.fnmatch
    join = os.path.join
    for path, dirlist, filelist in os.walk(startdir):
        for name in filelist:
            for pat in pats:
                if match(name, pat):
                    yield join(path, name)

def file_md5(fpath):
    """Return the MD5 digest for the given file"""
    try:
        f = open(fpath, 'rb')
        m = hashlib.md5()
        while True:
            s = f.read(4096)
            if not s:
                break
            m.update(s)
        return m.hexdigest()
    finally:
        f.close()

def make_egglist_index():
    startdir = os.path.abspath(os.path.dirname(__file__))
    out = open('index.html', 'w')
    out.write('\n\n')
    text = []
    for f in find_files(startdir, ["*.egg", "*.tar.gz", "*.zip", "*.exe"]):
        checksum = file_md5(f)
        basef = os.path.basename(f)
        text.append('
%s\n' % (basef, checksum, basef))
    text.sort()
    out.writelines(text)
    out.write('
\n\n')
    out.close()

if __name__ == '__main__':
    make_egglist_index()


text:
# OpenGL Shapes

Basic skeleton for OpenGL on Manjaro(Arch), with CMake

To install dependencies

```
sudo pacman -S sdl2
sudo pacman -S glew
sudo pacman -S glm
```

Sources were created by following [this](https://www.youtube.com/playlist?list=PLEETnX-uPtBXT9T-hD0Bj31DSnwio-ywh)
tutorial.

To build the project after installing the dependencies

```
./compile_and_run.sh
```

or alternatively

```
mkdir build
cd build
cmake ..
make
./open_gl_display
```


text:
import { ComponentFactoryResolver, EventEmitter, Injector, OnDestroy, ResolvedReflectiveProvider, ViewContainerRef } from '@angular/core';
import { RouterOutletMap } from '../router_outlet_map';
import { ActivatedRoute } from '../router_state';
/**
 * A router outlet is a placeholder that Angular dynamically fills based on the application's route.
 *
 * ## Example
 *
 * ```
 * <router-outlet></router-outlet>
 * <router-outlet name="left"></router-outlet>
 * <router-outlet name="right"></router-outlet>
 * ```
 *
 * A router outlet will emit an activate event any time a new component is being instantiated,
 * and a deactivate event when it is being destroyed.
 *
 * ## Example
 *
 * ```
 * <router-outlet (activate)="onActivate($event)"
 * (deactivate)="onDeactivate($event)"></router-outlet>
 * ```
 *
 * @stable
 */
export declare class RouterOutlet implements OnDestroy {
    private parentOutletMap;
    private location;
    private resolver;
    private name;
    private activated;
    private _activatedRoute;
    outletMap: RouterOutletMap;
    activateEvents: EventEmitter<any>;
    deactivateEvents: EventEmitter<any>;
    constructor(parentOutletMap: RouterOutletMap, location: ViewContainerRef, resolver: ComponentFactoryResolver, name: string);
    ngOnDestroy(): void;
    isActivated: boolean;
    component: Object;
    activatedRoute: ActivatedRoute;
    deactivate(): void;
    activate(activatedRoute: ActivatedRoute, loadedResolver: ComponentFactoryResolver, loadedInjector: Injector, providers: ResolvedReflectiveProvider[], outletMap: RouterOutletMap): void;
}


text:
title: Building a 360° Image Gallery
type: guides
layout: docs
parent_section: guides
order: 3
examples:
  - title: 360° Image Gallery
    src: https://glitch.com/edit/#!/aframe-gallery?path=index.html
---

![360° Image Viewer](/images/docs/360-image-viewer.png)

[registry]: https://aframe.io/registry/

Let's build an interactive gaze-based **360° image gallery**. There will be
three panels which the user can click on. Once clicked, the background will
fade and swap the 360° images.

[ecs]: ../introduction/entity-component-system.md

This guide will practice three concepts related to [entity-component][ecs]:

1. Using the standard components that come with A-Frame.
2. Using community components from the ecosystem.
3. Writing custom components to accomplish whatever we want.

<!--toc-->

## Skeleton

This is the starting point for our scene:

```html
<a-scene>
  <a-assets>
    <audio id="click-sound" src="audio/click.ogg"></audio>

    <!-- Images. -->
    <img id="city" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/city.jpg">
    <img id="city-thumb" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/thumb-city.jpg">
    <img id="cubes" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/cubes.jpg">
    <img id="cubes-thumb" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/thumb-cubes.jpg">
    <img id="sechelt" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/sechelt.jpg">
    <img id="sechelt-thumb" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/thumb-sechelt.jpg">
  </a-assets>

  <!-- 360-degree image. -->
  <a-sky id="image-360" radius="10" src="#city"></a-sky>

  <!-- Link we will build. -->
  <a-entity class="link"></a-entity>

  <!-- Camera + Cursor. -->
  <a-camera>
    <a-cursor id="cursor">
      <a-animation begin="click" easing="ease-in" attribute="scale"
                   fill="backwards" from="0.1 0.1 0.1" to="1 1 1" dur="150"></a-animation>
      <a-animation begin="cursor-fusing" easing="ease-in" attribute="scale"
                   from="1 1 1" to="0.1 0.1 0.1" dur="1500"></a-animation>
    </a-cursor>
  </a-camera>
</a-scene>
```

[a-sky]: ../primitives/a-sky.md
[ams]: ../core/asset-management-system.md
[animation-begin]: ../core/animations.md#begin
[camera]: ../primitives/a-camera.md
[component]: ../core/component.md
[cursor]: ../components/cursor.md

We have predefined:

- Several images to choose from in the [Asset Management System][ams] within `<a-assets>`.
- Our 360° image placeholder with [`<a-sky>`][a-sky].
- A [cursor][cursor] with visual feedback using event-driven
[animations][animation-begin], fixed to the [camera][camera].

## Using Standard Components

Standard components are components that ship with A-Frame, like any standard
library. We'll go over how to attach these components to entities and configure
them from HTML.

We want to build a textured plane to act as a link that when clicked, will
change the 360° image. We start with an empty entity. Without any
components, any empty entity does nothing and renders nothing:

```html
<a-entity class="link"></a-entity>
```

[geometry]: ../components/geometry.md

To give our entity shape, we can attach the [geometry component][geometry],
configured to a plane shape. We specify the component data using a syntax that
resembles that of inline CSS styles:

```html
<a-entity class="link"
  geometry="primitive: plane; height: 1; width: 1"></a-entity>
```

[material]: ../components/material.md

Then to give our entity appearance, we can attach the [material
component][material].  We set `shader` to `flat` so the image isn't affected
negatively by lighting. And we set `src` to `#cubes-thumb`, a selector to one
of the images defined in the [Asset Management System][ams].

```html
<a-entity class="link"
  geometry="primitive: plane; height: 1; width: 1"
  material="shader: flat; src: #cubes-thumb"></a-entity>
```

[sound]: ../components/sound.md

We can continue adding features to our entity by plugging in more components.
Let's attach one more standard component, the [sound component][sound]. We want
to make it such that when we click (via gazing) on the link, it plays a click
sound. The syntax is the same as before, but instead we are now using the sound
component's properties. We set `on` to `click` so the sound is played on click.
And we set `src` to `#click-sound`, a selector to our `<audio>` element.

```html
<a-entity class="link"
  geometry="primitive: plane; height: 1; width: 1"
  material="shader: flat; src: #cubes-thumb"
  sound="on: click; src: #click-sound"></a-entity>
```

Now we have a textured plane that plays a click sound when clicked.

## Using Community Components

[npm]: https://www.npmjs.com/search?q=aframe-component&page=1&ranking=optimal

A-Frame comes with a small core of standard components, but the magic is in the
large number of open source community components in the A-Frame ecosystem. We
can find community components from places such as [npm][npm] or the [A-Frame
Registry][registry]. We can drop them into our scene and use them straight in
our HTML. Components can do anything.  By using components that other people
have developed, we gain power without needing to write our own code.

We'll go through using three community components:

- [template](https://ngokevin.github.io/kframe/components/template/)
- [layout](https://ngokevin.github.io/kframe/components/layout/)
- [event-set](https://ngokevin.github.io/kframe/components/event-set/)

Community components are generally available through both GitHub and published
on npm. An easy way to include components is to use the [unpkg.com
CDN](http://unpkg.com/), which lets us include components hosted on npm as a
script tag, even with support for specifying fuzzy versions. We usually just
need to know the component's npm package name and the path:

```html
<html>
  <head>
    <title>360° Image Browser</title>
    <script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
    <script src="https://unpkg.com/aframe-template-component@3.x.x/dist/aframe-template-component.min.js"></script>
    <script src="https://unpkg.com/aframe-layout-component@3.x.x/dist/aframe-layout-component.min.js"></script>
    <script src="https://unpkg.com/aframe-event-set-component@3.x.x/dist/aframe-event-set-component.min.js"></script>
  </head>
  <body>
    <a-scene>
      <!-- ... -->
    </a-scene>
  </body>
</html>
```

### Template Component

Currently, we have one link. We want to create three of them, one for each of
our 360° images.

[template]: https://github.com/ngokevin/aframe-template-component

The [template component][template] integrates templating engines into A-Frame.
This lets us do things such as encapsulate groups of entities, passing data to
generate entities, or iteration. Since we want to turn one link into three,
without copy-and-pasting HTML, we can use the template component.

If we read the [template component's documentation][template], we see one way
to define a template is via a script tag in `<a-assets>`. Let's make our link a
template and give it a name using an `id`:

```html
<a-assets>
  <!-- ... -->
  <script id="plane" type="text/html">
    <a-entity class="link"
      geometry="primitive: plane; height: 1; width: 1"
      material="shader: flat; src: #cubes-thumb"
      sound="on: click; src: #click-sound"></a-entity>
  </script>
</a-assets>
```

Then we can use the template to create multiple planes without much work:

```html
<a-entity template="src: #plane"></a-entity>
<a-entity template="src: #plane"></a-entity>
<a-entity template="src: #plane"></a-entity>
```

[templateliteral]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals

But then they'll all be displaying the same image texture and look the same.
Here is where we'll need a template engine with variable substitution. The
template component comes with simple [ES6 string
interpolation][templateliteral] (i.e., `${var}` format). Though the template
component supports many popular templating engines such as Nunjucks, Jade,
Handlebars, or Mustache.

[data]: https://developer.mozilla.org/docs/Web/Guide/HTML/Using_data_attributes

To allow each instance of the template to be customizable, we define a
`${thumb}` variable in the template, which we can pass using [data
attributes][data]:

```html
<a-assets>
  <!-- ... -->
  <script id="plane" type="text/html">
    <a-entity class="link"
      geometry="primitive: plane; height: 1; width: 1"
      material="shader: flat; src: ${thumb}"
      sound="on: click; src: #click-sound"></a-entity>
  </script>
</a-assets>

<!-- ... -->

<!-- Pass image sources to the template. -->
<a-entity template="src: #plane" data-thumb="#city-thumb"></a-entity>
<a-entity template="src: #plane" data-thumb="#cubes-thumb"></a-entity>
<a-entity template="src: #plane" data-thumb="#sechelt-thumb"></a-entity>
```

The template component has allowed us to not have to repeat a lot of HTML,
keeping our scene very readable.

### Layout Component

[layout]: https://www.npmjs.com/package/aframe-layout-component

Because the default position of an entity is `0 0 0`, the entities will
overlap. While we could manually position each link, we could instead use the
[layout component][layout] to do it for us. The layout component will
automatically position its children to the specified layout.

We create a wrapper entity around our links and attach the layout component
using the `line` layout:

```html
<a-entity id="links" layout="layout: line; margin: 1.5" position="-3 -1 -4">
  <a-entity template="src: #plane" data-thumb="#city-thumb"></a-entity>
  <a-entity template="src: #plane" data-thumb="#cubes-thumb"></a-entity>
  <a-entity template="src: #plane" data-thumb="#sechelt-thumb"></a-entity>
</a-entity>
```

Now our links are no longer overlapping without us having to calculate and
fiddle with positions. The layout component supports other layouts including
grid, circle, and dodecahedron.

### Event-Set Component

[cursor-events]: ../components/cursor.md#events
[event-set]: https://www.npmjs.com/package/aframe-event-set-component
[scale]: ../components/scale.md

Lastly, we'll add some visual feedback to our links. We want them to scale up
and scale back when they are hovered or clicked. This involves writing an event
listener to do `setAttribute`s on the [scale component][scale] in response to
[cursor events][cursor-events]. This is a fairly common pattern so there is an
[event-set component][event-set] that does `setAttribute` in response to
events.

[multiple]: ../core/component.md#multiple-instancing

Let's attach event listeners on our links to scale them up when they are gazed
over, scale them down as they are being clicked, and scale them back when they
are no longer gazed upon. We are mimicking CSS `:hover` states. We can specify
event names with `_event` properties, and the rest of the properties define the
`setAttribute` calls. Notice that the event-set component can have [multiple
instances][multiple]:

```html
<a-assets>
  <!-- ... -->
  <script id="link" type="text/html">
    <a-entity class="link"
      geometry="primitive: plane; height: 1; width: 1"
      material="shader: flat; src: ${thumb}"
      sound="on: click; src: #click-sound"
      event-set__1="_event: mousedown; scale: 1 1 1"
      event-set__2="_event: mouseup; scale: 1.2 1.2 1"
      event-set__3="_event: mouseenter; scale: 1.2 1.2 1"
      event-set__4="_event: mouseleave; scale: 1 1 1"></a-entity>
  </script>
</a-assets>
```

Wielding components, we were able to do a lot with surprisingly little HTML.
Though the ecosystem has a lot to offer, non-trivial VR applications will
require us to write application-specific components.

## Writing an Application-Specific Component

> View the full [`set-image` component on GitHub](https://github.com/aframevr/360-image-viewer-boilerplate/blob/master/components/set-image.js).

We want to write the component that fades the sky into a new 360° image
once one of the links are clicked. We'll call it `set-image`. The [component
API documentation][component] provides a detailed reference for writing a
component. A basic component skeleton might look like:

Here is the skeleton for our set-image component.

```js
AFRAME.registerComponent('set-image', {
  schema: {
    // ...
  },

  init: function () {
    // ...
  }
});
```

Now we decide what the API for our image-setting component will be. We need:

- An event name to listen to.
- Which entity to change the texture of.
- The image texture.
- An animation fade duration.

So we translate those properties to the schema:

```js
AFRAME.registerComponent('set-image', {
  schema: {
    on: {type: 'string'},
    target: {type: 'selector'},
    src: {type: 'string'},
    dur: {type: 'number', default: 300}
  },

  init: function () {
    // ...
  },

  setupFadeAnimation: function () {
    // Appends an <a-animation> that fades to black.
  }
});
```

Now we set up the event listener to change the image while the texture has
faded to black. Whenever the event is emitted (in our case, a click), then the
component will trigger the animation (which is listening for `set-image-fade`),
wait the appropriate amount of time, and swap the image:

```js
  //...

  init: function () {
    var data = this.data;
    var el = this.el;

    this.setupFadeAnimation();

    el.addEventListener(data.on, function () {
      // Fade out image.
      data.target.emit('set-image-fade');
      // Wait for fade to complete.
      setTimeout(function () {
        // Set image.
        data.target.setAttribute('material', 'src', data.src);
      }, data.dur);
    });
  }

  //...
```

And that concludes our 360° image gallery.

> **[Try it out!](https://aframe-gallery.glitch.me)**


text:
'use strict'

describe('Model Builder Unit Test Spec', function() {

  describe('modelBuilder module spec', function() {
    it('modelBuilder module must return a function', function() {
      var modelBuildrFunction = require('../modelBuilder');

      expect(modelBuildrFunction).toEqual(jasmine.any(Function));
    });

    it('modelBuilder module should throw an erro if a dbHandler was not provided', function() {
      var modelBuilder = require('../modelBuilder');

      expect(modelBuilder).toThrow('A dbHandler must be provided.');
    });
  })

  describe('modelBuilder function spec', function() {
    var $modelBuilder;
    var $dbHandler = {};

    beforeEach(function() {
      $modelBuilder = require('../modelBuilder')($dbHandler);
    });

    it('modelBuilder Object must expose a function withThisSchema', function() {
      expect($modelBuilder.withThisSchema).toEqual(jasmine.any(Function));
    });

    it('modelBuilder Object must expose a function withThisField', function() {
      expect($modelBuilder.withThisField).toEqual(jasmine.any(Function));
    });

    it('modelBuilder Object must expose a function build', function() {
      expect($modelBuilder.build).toEqual(jasmine.any(Function));
    });

    it('withThisField must return its own modelBuilder instance', function() {
      var fieldName = 'fieldName';
      var fieldType = String;

      var returnedModelBuilder = $modelBuilder.withThisField(fieldName, fieldType);

      expect(returnedModelBuilder).toEqual($modelBuilder);
    });

    it('withThisSchema must return its own modelBuilder instance', function() {
      var schema = {
        fieldName: String
      };

      var returnedModelBuilder = $modelBuilder.withThisSchema(schema);

      expect(returnedModelBuilder).toEqual($modelBuilder);
    });

    it('build function must throw an Error if was invoked before withThis*', function() {
      expect($modelBuilder.build).toThrow('A schema must be defined before build a model (use withThisSchema(schemaJson) or withThisField(fieldName, fieldType))');
    });

    it('build function must invoke dbHandler.createModel function with the given schema and model name', function() {
      var schema = {
        fieldName: String
      };
      var modelName = 'modelName';

      $dbHandler.createModel = jasmine.createSpy('createModel');

      $modelBuilder
        .withThisSchema(schema)
        .build(modelName);

      expect($dbHandler.createModel).toHaveBeenCalledWith(modelName, schema);
    });

    it('build function must invoke dbHandler.createModel with schema create by withThisField function', function() {
      var numberFieldName = 'numberFieldName';
      var numberFieldType = Number;
      var stringFieldName = 'stringFieldName';
      var stringFieldType = String;
      var expectedSchema = {
        numberFieldName: Number,
        stringFieldName: String
      };
      var modelName = 'fieldBaseModelName';

      $dbHandler.createModel = jasmine.createSpy('createModel');

      $modelBuilder
        .withThisField(numberFieldName, numberFieldType)
        .withThisField(stringFieldName, stringFieldType)
        .build(modelName);

      expect($dbHandler.createModel).toHaveBeenCalledWith(modelName, expectedSchema);
    });

    it('build function should return what dbHandler.createModel returns', function() {
      var schema = {
        fieldName: String
      };
      var modelName = 'modelName';
      var expectedReturnValue = new Date();

      $dbHandler.createModel = function() {};

      spyOn($dbHandler, 'createModel').andReturn(expectedReturnValue);

      var returnedValue = $modelBuilder
        .withThisSchema(schema)
        .build(modelName);

      expect(returnedValue).toEqual(expectedReturnValue);
    });
  });
});


text:
<?php
/*
	TimesController.php
	--
	manages time clock entries

	@extends AppController
*/

class TimesController extends AppController
{
	//var $scaffold;

	public $components = array(
		'Paginator'
	);

	public $paginate = array(
		'limit' => 25,
		'order' => array(
			'Time.start_time' => 'asc'
		)
	);

	public function go_index()
	{
		return $this->redirect( array('volunteer' => true, 'controller' => 'times', 'action' => 'index') );
	}

	public function volunteer_index()
	{
		if( $this->request->is('post') )
		{
			if(
				isset($this->data["Organization"])
				&& isset($this->data["Organization"]['organization_id'])
			)
			{
				// redirect to the organization screen
				return $this->redirect(
					array(
						'volunteer' => true,
						'controller' => 'times',
						'action' => 'in',
						'organization',
						$this->data['Organization']['organization_id']
					)
				);
			}
			else if(
				isset($this->data['Time'])
				&& isset($this->data['locus'])
				&& isset($this->data['Time']['token'])
			)
			{
				$redirect = array(
					'volunteer' => true,
					'controller' => 'times',
					'action' => $this->data['locus']
				);

				if($this->data['locus'] == "in")
				{
					$redirect[] = 'event';
				}

				$redirect[] = $this->data['Time']['token'];

				$this->redirect( $redirect );
			}
		}
		$fields = array();
		$conditions = array(
			'Permission.write' => true
		);
		$contain = array('Organization' => array(
			'fields' => array('organization_id', 'name')));
		$orgs = $this->Time->OrganizationTime->Organization->Permission->find('all', compact('fields', 'contain', 'conditions'));
		//debug($orgs);

		$organizations = Hash::combine($orgs, '{n}.Organization.organization_id', '{n}.Organization.name');

		//$organizations = $this->Time->OrganizationTime->Organization->find('list');
		$this->set(compact('organizations') );
	}

	public function coordinator_dashboard()
	{
		$organization_ids = $this->_GetUserOrganizationsByPermission('write');

		$conditions = array(
			'OrganizationTime.organization_id' => $organization_ids
		);

		// $contain = array(
		// 	'Organization',
		// 	'Time' => array(
		// 		'conditions' => [
		// 			//'Time.status <>' => 'deleted'
		// 		],
		// 		'User',
		// 		'TimeComment' => array('fields' =>
		// 			array('COUNT(time_comment_id) as CommentCount')
		// 		)
		// 	)
		// );

		// $order = array(
		// 	'OrganizationTime.created' => 'DESC'
		// );
		// $this->Paginator->settings = compact('conditions', 'contain', 'order');

		// $times = $this->Paginator->paginate(
		// 	'OrganizationTime'
		// );

		// New select, using join system.
		$joins = [
			[
				'table' => 'organizations',
				'alias' => 'Organization',
				'type' => 'INNER',
				'conditions' => [
					'Organization.organization_id = OrganizationTime.organization_id'
				]
			],
			[
				'table' => 'times',
				'alias' => 'Time',
				'type' => 'INNER',
				'conditions' => [
					'OrganizationTime.time_id = Time.time_id'
				]
			],
			[
				'table' => 'users',
				'alias' => 'User',
				'type' => 'INNER',
				'conditions' => [
					'Time.user_id = User.user_id'
				]
			],
			[
				'table' => 'time_comments',
				'alias' => 'TimeComment',
				'type' => 'LEFT',
				'conditions' => [
					'Time.time_id = TimeComment.time_id'
				]
			]
		];

		$fields = [
			'User.first_name',
			'User.last_name',
			'User.email',
			'Organization.name',
			'OrganizationTime.memo',
			'OrganizationTime.created',
			'Time.time_id',
			'Time.status',
			'Time.start_time',
			'Time.stop_time'
		];

		$summary_fields = [
			'TIMESTAMPDIFF(MINUTE, Time.start_time, Time.stop_time)/60 AS duration',
			'COUNT(TimeComment.time_comment_id) AS comment_count'
		];

		$conditions = [
			'Time.status <>' => 'deleted',
			'OrganizationTime.organization_id' => $organization_ids
		];

		$this->Paginator->settings = [
			'conditions' => $conditions,
			'joins' => $joins,
			'fields' => array_merge( $fields, $summary_fields ),
			'order' => [
				'OrganizationTime.created' => 'DESC'
			],
			'group' => $fields,
			'contain' => []
		];

		$times = $this->Paginator->paginate('OrganizationTime');

		$this->set( ['times' => $times ] );
	}

	/*
		/volunteer/in/organization/1234
		/volunteer/in/event/39fx
	*/
	public function volunteer_in($mode = null, $id_or_token = null)
	{
		if($mode == null)
		{
			$this->Session->setFlash( __('%s was unable to determine the clock in mode.', Configure::read("Solution.name") ), 'danger');
			return $this->redirect( $this->_Redirector('volunteer', 'times', 'index') );
		}

		if( !in_array($mode, array('organization', 'event') ) )
		{
			$this->Session->setFlash( __('%s was unable to clock you in with the information provided.', Configure::read("Solution.name") ), 'danger');
			return $this->redirect( $this->_Redirector('volunteer', 'times', 'index') );
		}

		if( $mode == 'organization' )
		{
			$organization_id = $id_or_token;

			$organization_contain = array();
			$organization_conditions = array(
				'organization_id' => $organization_id
			);
			$options = array(
				'contain' => $organization_contain,
				'conditions' => $organization_conditions
			);

			$organization = $this->Time->OrganizationTime->Organization->find('first', $options);

			if( !empty($organization) )
			{
				if( $this->request->is('post') )
				{
					$memo = "";
					if( isset($this->data['OrganizationTime'][0]['memo']) )
						$memo = $this->data['OrganizationTime'][0]['memo'];

					$time = array(
						'Time' => array(
							'user_id' => $this->Auth->user('user_id'),
							'start_time' => $this->data['Time']['start_time'],
							'stop_time' => $this->data['Time']['stop_time'],
							'status' => 'pending'
						),
						'OrganizationTime' => array(
							array(
								'organization_id' => $organization_id,
								'memo' => $memo
							)
						)
					);

					if( $this->Time->saveAssociated($time) )
					{
						$this->Session->setFlash( __('Your time for %s has been logged.', $organization['Organization']['name'] ), 'success');
						return $this->redirect( array('volunteer' => true, 'action' => 'index') );
					}
					else
					{
						$this->Session->setFlash( __('There were problems saving your time for %s.', $organization['Organization']['name'] ), 'danger');
					}
				}
				$this->set( compact('organization') );
			}
		}

		if ( $mode == 'event' )
		{
			$start_token = $id_or_token;
			$event_conditions = array(
				'start_token' => $start_token
			);
			$event_contain = array(
				'Organization' => array(
					'Permission' => array(
						'conditions' => array('write' => true),
						'fields' => array(),
						'User'
					)
				),
				'EventTime' => array(
					'fields' => array(),
					'Time' => array(
						'conditions' => array('user_id' => $this->Auth->user('user_id') )
					)
				)
			);
			$options = array(
				'conditions' => $event_conditions,
				'contain' => $event_contain
			);

			$event = $this->Time->EventTime->Event->find('first', $options);
			if( !empty($event) )
			{
				if( $this->request->is('post') )
				{
					$time = array(
						'Time' => array(
							'user_id' => $this->Auth->user('user_id'),
							'status' => 'approved',
							'start_time' => date('Y-m-d H:i:s'),
							'stop_time' => null
						),
						'EventTime' => array(
							array(
								'event_id' => $event['Event']['event_id'])
						)
					);

					if( $this->Time->saveAssociated($time) )
					{
						$this->Session->setFlash( __('You have been clocked in to %s.', $event['Event']['title'] ), 'success');
						return $this->redirect( array('volunteer' => true, 'action' => 'index') );
					}
					else
					{
						$this->Session->setFlash( __('There were problems saving your time for %s.', $organization['Event']['title'] ), 'danger');
					}
				}

				$this->set( compact('event') );
			}
			else
			{
				$this->Session->setFlash( __('You provided an invalid time token.  Please talk to your event coordinator for more assistance.', Configure::read("Solution.name") ), 'danger');
				return $this->redirect( $this->_Redirector('volunteer', 'times', 'index') );
			}
		}
	}

	public function volunteer_out($stop_token = null, $time_id = null)
	{
		$event_conditions = array(
			'stop_token' => $stop_token
		);
		$event_contain = array(
			'Organization' => array(
				'Permission' => array(
					'conditions' => array('write' => true),
					'fields' => array(),
					'User'
				)
			),
			'EventTime' => array(
				'fields' => array(),
				'Time' => array(
					'conditions' => array(
						'user_id' => $this->Auth->user('user_id'),
						'stop_time' => null
					)
				)
			)
		);
		$options = array(
			'conditions' => $event_conditions,
			'contain' => $event_contain
		);

		$event = $this->Time->EventTime->Event->find('first', $options);
		for($i = 0; $i < count($event['EventTime']); $i++)
		{
			if( empty($event['EventTime'][$i]['Time']) )
			{
				unset($event['EventTime'][$i]);
			}
		}
		$event['EventTime'] = array_values($event['EventTime']);

		if( $this->request->is('post') )
		{
			$time = $this->Time->findByTimeId($time_id);

			if( isset($time['Time']['time_id']) )
			if( $time['Time']['user_id'] == $this->Auth->user('user_id') )
			{
				$this->Time->id = $time_id;
				if( $this->Time->saveField('stop_time', date("Y-m-d H:i:s")))
				{
					$this->Session->setFlash(
						__("You have successfully clocked out."),
						'success'
					);
				}
			}

			return $this->redirect( array('volunteer'=> true, 'controller' => 'times', 'action' => 'index') );
		}

		$this->set( compact('event') );
	}

	public function comment($time_id)
	{
		//debug($this->data);
		$conditions = array(
			'Time.time_id' => $time_id
		);
		$contain = array(
			'User',
			'EventTime' => array('Event'),
			'OrganizationTime' => array('Organization')
		);
		$time = $this->Time->find('first', compact('conditions', 'contain') );

		if( empty($time) )
		{
			throw new NotFoundException( __("You requested a page that does not exist.") );
		}

		if( !empty($time['OrganizationTime']) )
		{
			$this->organization_id = Hash::get($time, 'OrganizationTime.0.Organization.organization_id');
		}
		elseif( !empty($time['EventTime']) )
		{
			$this->organization_id = Hash::get($time, 'EventTime.0.Event.organization_id');
		}

		if( empty($time) )
			return;

		$can_comment = false;

		if( $time['Time']['user_id'] == $this->Auth->user('user_id') )
		{
			$can_comment = true;
		}
		elseif( $this->_CurrentUserCanWrite( $this->organization_id ) )
		{
			$can_comment = true;
		}

		if( $this->request->is('post') && $can_comment )
		{
			$time_comment = array(
				'time_id' => $time_id,
				'user_id' => AuthComponent::user('user_id'),
				'body' => $this->data['TimeComment']['body']
			);

			$this->Time->TimeComment->save( $time_comment );

			return $this->redirect( array('controller' => 'times', 'action' => 'view', $time_id) );
		}

		throw new BadRequestException( __("This request was invalid, so there is nothing to show you right now.") );
	}

	public function view($time_id = null)
	{
		if( $this->Time->exists($time_id) )
		{
			$contain = array(
				'User',
				'EventTime' => array('Event' => array('Organization')),
				'OrganizationTime' => array('Organization'),
				'TimeComment' => array('User')
			);
			$conditions = array(
				'Time.time_id' => $time_id
			);
			$time = $this->Time->find('first', compact('contain', 'conditions') );

			if( !empty($time['EventTime']) )
			{
				$this->organization_id = $time['EventTime'][0]['Event']['organization_id'];
			}

			if( !empty($time['OrganizationTime']) )
			{
				$this->organization_id = $time['OrganizationTime'][0]['Organization']['organization_id'];
			}

			// Get potential events for conversion
			$events = $this->Time->EventTime->Event->find('all', [
				'conditions' => [
					'Event.organization_id' => $this->organization_id,
					'OR' => [
						[
							// Time.start_time <= Event.stop_time
							// AND
							// Time.start_time >= Event.start_time
							'AND' => [
								sprintf(" DATE_ADD( Event.start_time, INTERVAL -1 HOUR) <= '%s' ", $time['Time']['start_time']),
								sprintf(" DATE_ADD( Event.stop_time, INTERVAL 1 HOUR) >= '%s' ", $time['Time']['start_time'])
							]
						],
						$time['Time']['stop_time'] == null ? [] : [
							// Time.stop_time <= Event.stop_time
							// AND
							// Time.stop_time >= Event.start_tim
							'AND' => [
								sprintf(" DATE_ADD( Event.start_time, INTERVAL -1 HOUR) <= '%s' ", $time['Time']['stop_time']),
								sprintf(" DATE_ADD( Event.stop_time, INTERVAL 1 HOUR) >= '%s' ", $time['Time']['stop_time'])
							]
						]
					]
				],
				'contain' => []
			]);
			$this->set( compact('events') );

			if(
				$time['User']['user_id'] == $this->Auth->user('user_id')
				|| $this->_CurrentUserCanWrite($this->organization_id)
			)
			{
				$title_for_layout = __("Time: %0.2f hour for %s", $time['Time']['duration'], $time['User']['full_name']);
				$this->set( compact('time', 'title_for_layout') );
			}
			else
			{
				throw new ForbiddenException( __("You do not have permission to view this page") );
			}
		}
		else
			throw new NotFoundException( __("There is nothing to see here. (Error 404)"));
	}

	private function _GetTimeState($time_id, $contain = null)
	{
		$rtn = null;

		if( $contain == null)
		{
			$contain = array(
				'User',
				'EventTime' => array('Event' => array('Organization')),
				'OrganizationTime' => array('Organization')
			);
		}
		$conditions = array(
			'Time.time_id' => $time_id
		);

		if( $this->Time->exists($time_id) )
			$rtn = $this->Time->find('first', compact('contain', 'conditions') );
		else
			return null;

		if( !empty($rtn['EventTime']) )
			$this->organization_id = $rtn['EventTime'][0]['Event']['organization_id'];

		if( !empty($rtn['OrganizationTime']) )
			$this->organization_id = $rtn['OrganizationTime'][0]['Organization']['organization_id'];

		$rtn['context'] = array(
			'owner' => $this->Auth->user('user_id') == $rtn['Time']['user_id'],
			'coordinator' => $this->_CurrentUserCanWrite($this->organization_id)
		);

		return $rtn;
	}

	public function volunteer_edit($time_id)
	{
		$state = $this->_GetTimeState($time_id);

		if( $state == null )
			throw new NotFoundException( __("The requested page does not exist.") );

		if( empty($state['OrganizationTime']) )
			throw new ForbiddenException( __("You cannot modify time entries from events you attended.") );

		if( $state['Time']['user_id'] != $this->Auth->user('user_id') )
			throw new ForbiddenException( __("You may not modify this time entry as its owner.") );

		if( $this->request->is('post') )
		{
			$save = $this->data['Time'];

			$save['time_id'] = $time_id;
			$save['status'] = 'pending';
			$save['user_id'] = $this->Auth->user('user_id');

			if( $this->Time->save($save) )
			{
				return $this->redirect( array('volunteer' => false, 'action' => 'view', $time_id) );
			}
		}

		$this->data = array(
			'Time' => $state['Time'],
			'OrganizationTime' => $state['OrganizationTime']
		);

	}

	public function edit($time_id = null)
	{
		$state = $this->_GetTimeState($time_id);

		if( $state == null )
			throw new NotFoundException( __("The requested page does not exist.") );

		if( $state['context']['owner'] )
		{
			return $this->redirect( array('volunteer' => true, 'action' => 'edit', $time_id) );
		}

		if( $state['context']['coordinator'] )
		{
			return $this->redirect( array('coordinator' => true, 'action' => 'edit', $time_id) );
		}

		debug( $state );

		throw new NotFoundException( __("The requested page does not exist") );

	}

	public function delete($time_id)
	{
		$contain = array(
			'User',
			'EventTime' => array('Event' => array('Organization')),
			'OrganizationTime' => array('Organization')
		);
		$conditions = array(
			'Time.time_id' => $time_id
		);
		$time = $this->Time->find('first', compact('contain', 'conditions') );

		if( !empty($time['EventTime']) )
		{
			$this->organization_id = $time['EventTime'][0]['Event']['organization_id'];
		}

		if( !empty($time['OrganizationTime']) )
		{
			$this->organization_id = $time['OrganizationTime'][0]['Organization']['organization_id'];
		}

		if( $time['User']['user_id'] == $this->Auth->user('user_id') )
		{
			$this->Time->id = $time_id;
			if( $this->Time->saveField('status', 'deleted') )
			{
				$this->Session->setFlash( _("This time entry was marked as deleted"), 'toast' );
			}
			else
			{
				$this->Session->setFlash( _("There was a problem deleting your time entry"), 'danger' );
			}

			return $this->redirect( array('controller' => 'users', 'action' => 'activity') );
		}
		else
		{
			throw new ForbiddenException(__("You do not have permission to delete this time entry") );
		}
	}

	public function undelete($time_id)
	{
		$contain = array(
			'User',
			'EventTime' => array('Event' => array('Organization')),
			'OrganizationTime' => array('Organization')
		);
		$conditions = array(
			'Time.time_id' => $time_id,
			'Time.status' => 'deleted'
		);
		$time = $this->Time->find('first', compact('contain', 'conditions') );

		$status = 'deleted';
		if( !empty($time['EventTime']) )
		{
			$status = 'approved';
		}

		if( !empty($time['OrganizationTime']) )
		{
			$status = 'pending';
		}

		if( $time['User']['user_id'] == $this->Auth->user('user_id') )
		{
			$this->Time->id = $time_id;
			if( $this->Time->saveField('status', $status) )
			{
				$this->Session->setFlash( _("This time entry has been undeleted."), 'toast' );
			}
			else
			{
				$this->Session->setFlash( _("This time entry couldn't be undeleted."), 'danger' );
			}

			return $this->redirect( array('controller' => 'times', 'action' => 'trash') );
		}
		else
		{
			throw new ForbiddenException(__("You do not have permission to undelete this time entry") );
		}
	}

	public function trash()
	{
		$this->Paginator->settings['conditions'] = array(
			'Time.user_id' => $this->Auth->user('user_id'),
			'Time.status' => 'deleted'
		);
		$this->Paginator->settings['contain'] = array(
			'User',
			'EventTime' => array(
				'Event' => 'Organization'
			),
			'OrganizationTime' => array('Organization')
		);

		$deleted_times = $this->Paginator->paginate('Time');

		$this->set( compact('deleted_times') );
	}

	/*
		api_approve
		--
		A lightweight request to approve a time entry.  Use the declarative syntax to call these on click
		<a
			class="api-trigger"
			data-target="#time-3"
			data-on-success="collapse"
			data-api="/servicespark/api/times/status/3/pending/1"
			href="/servicespark/coordinator/times/approve/3/1"
		>Approve</a>
	*/
	public function api_status($time_id = null, $status = null, $confirm = null)
	{
		if(
			$this->request->is('post', 'put')
			&& $confirm == 1
			&& $this->Time->exists($time_id)
			&& in_array($status, array('approved', 'rejected', 'pending') )
			&& ($time = $this->Time->findByTimeId($time_id) )
			&& !empty($time['OrganizationTime'])
			&& ($this->organization_id = $time['OrganizationTime'][0]['organization_id'])
			&& $this->_CurrentUserCanWrite($this->organization_id)
		)
		{
			$this->Time->id = $time_id;
			if( $this->Time->saveField('status', $status) )
			{
				if( isset($this->request->data['TimeComment']['body']) )
				{
					$comment = array(
						'time_id' => $time_id,
						'user_id' => $this->Auth->user('user_id'),
						'body' => $this->request->data['TimeComment']['body']
					);
					$this->Time->TimeComment->save($comment);
				}
				$response = array(
					'approved' => true,
					'message' => __("Time entry %s is %s", $this->Time->id, $status)
				);
			}
		}
		else
		{
			$response = array(
				'approved' => false,
				'message' => __("There was a problem with your request")
			);
		}

		$this->autoRender = false;
		$this->response->body( json_encode( compact('response') ) );
		$this->response->type('json');

		return $this->response;
	}

	public function coordinator_status($action = null, $time_id = null, $confirm = null)
	{

		if( $this->_status($time_id, $action, true) )
		{
			$this->Session->setFlash( __("%s time: succeeded", ucfirst($action)), 'toast' );
			return $this->redirect( array('coordinator' => false, 'controller' => 'times', 'action' => 'view', $time_id));
		}

		throw new ForbiddenException( __("There is nothing for you to see here") );
	}

	public function coordinator_approve($time_id = null, $confirm = null)
	{
		if(
			$this->request->is('post')
			&& $confirm == 1
			&& $this->Time->exists($time_id)
			&& ($time = $this->Time->findByTimeId($time_id) )
			&& ($this->organization_id = $time['OrganizationTime'][0]['organization_id'])
			&& $this->_CurrentUserCanWrite($this->organization_id)
		)
		{
			$this->Time->id = $time['Time']['time_id'];
			if( $this->Time->saveField('approved', true) )
			{
				$this->Session->setFlash( __('You approved time for %s.',
						$time['User']['full_name']
					),
					'toast'
				);
				return $this->redirect( array('coordinator' => true, 'controller' => 'times', 'action' => 'approve') );
			}
		}
		// make the permission model available to the Paginator

		if( $time_id != null )
		{
			$time = $this->Time->findByTimeId($time_id);

			if( !empty($time['EventTime']) )
			{
				$this->Session->setFlash( __('This time was recorded at an event and does not require your approval.'), 'warning');
				return $this->redirect( array('coordinator' => true, 'controller' => 'times', 'action' => 'approve') );
			}

			if( $time['Time']['status'] == "approved" )
			{
				$this->Session->setFlash( __('This time has already been approved'), 'success' );
				return $this->redirect( array('coordinator' => true, 'controller' => 'times', 'action' => 'approve') );
			}

			$this->set( compact('time') );

		}
		else
		{
			$user_write_organizations = $this->_GetUserOrganizationsByPermission('write');

			$conditions = array(
				'OrganizationTime.organization_id' => $user_write_organizations,
				'Time.status' => 'pending'
			);

			$this->Paginator->settings['contain'] = array('Organization', 'Time' => array('User'));
			$this->Paginator->settings['conditions'] = $conditions;
			$this->Paginator->settings['order'] = array('Time.status' => 'asc');
			$times = $this->Paginator->paginate('OrganizationTime');

			//debug($organizations);

			$this->set( compact('times') );
		}

	}

	public function coordinator_convert($time_id = null, $target_event_id = null) {
		$time = $this->Time->find('first', [
			'conditions' => ['Time.time_id' => $time_id]
		]);

		if( !$time ) {
			throw new NotFoundException('Unable to find time entry for time entry conversion.');
		}

		if( count($time['OrganizationTime']) !== 1 ) {
			throw new NotFoundException('Unable to find organization for time entry conversion.');
		}

		$organization_time_id = $time['OrganizationTime'][0]['organization_time_id'];
		$organization_id = $time['OrganizationTime'][0]['organization_id'];

		if( !$this->_CurrentUserCanWrite($organization_id)) {
			throw new ForbiddenException('You are not allowed to modify time for this organization.');
		}

		$event = $this->Time->EventTime->Event->find('first', [
			'conditions' => [
				'Event.event_id' => $target_event_id,
				'Event.organization_id' => $organization_id
			]
		]);

		if( !$event ) {
			throw new NotFoundException('Unable to find event for time entry conversion.');
		}

		// create save object
		$save = [
			'Time' => [
				'time_id' => $time_id,
				'status' => 'approved'
			],
			'EventTime' => [
				[
					'event_id' => $target_event_id,
					'time_id' => $time_id
				]
			]
		];

		// delete organizationtime
		$otDeleted = $this->Time->OrganizationTime->delete($organization_time_id);

		// save EventTime
		$etSaved = $this->Time->saveAll($save);

		// Both operation succeeded
		if( $otDeleted && $etSaved ) {
			$this->Session->setFlash(__('A time entry has been attached to this event.'), 'success');
		} else {
			$this->Session->setFlash(__('There was a problem converting an organization time entry to this event.'), 'success');
		}

		$redirect = isset($this->request->query['redirect'])
			? $this->request->query['redirect']
			: [
				'coordinator' => true,
				'controller' => 'events',
				'action' => 'view',
				$target_event_id
			];

		return $this->redirect($redirect);

	}

	private function _status($time_id = null, $status = null)
	{
		if($this->Time->exists($time_id)
			&& ($time = $this->Time->findByTimeId($time_id) )
			&& ($this->organization_id = $time['OrganizationTime'][0]['organization_id'])
			&& $this->_CurrentUserCanWrite($this->organization_id)
			&& in_array($status, array('approve', 'reject'))
		)
		{
			$verb_status = array(
				'approve' => 'approved',
				'reject' => 'rejected'
			);
			$this->Time->id = $time_id;
			return $this->Time->saveField('status', $verb_status[$status]);
		}

		return null;
	}

	public function coordinator_edit($time_id)
	{
		if( !$this->Time->exists($time_id) )
		{
			$this->Session->setFlash( __('An invalid time entry was specified.'), 'warning');
			return $this->redirect( $this->_Redirector('coordinator', 'events', 'index') );
		}

		// fetch time id
		$conditions = array('Time.time_id' => $time_id);
		$contain = array(
			'EventTime' => array(
				'Event' => array('Organization')
			),
			'OrganizationTime' => array(
				'Organization'
			),
			'User',
			'TimeComment'
		);
		$time = $this->Time->find('first', array('conditions' => $conditions, 'contain' => $contain) );

		//debug($time);

		if( empty($time['EventTime']) )
		{
			throw new NotFoundException( __("You cannot edit a time entry unless it is for events you coordinate") );
		}

		// verify that the current user can read/write this organization's time entries
		if( !$this->_CurrentUserCanWrite($time['EventTime'][0]['Event']['organization_id']) )
		{

			$this->Session->setFlash( __('You do not have permission to edit this organization\'s time entries'), 'warning');
			return $this->redirect( $this->_Redirector('go', 'organizations', 'view', $time['Event']['organization_id']) );
		}

		$title_for_layout = sprintf( __('Editing Time Entry %2$u – %1$s'), $time['EventTime'][0]['Event']['title'], $time['Time']['time_id']);

		// This block will execute when data is posted in the request
		if( $this->request->is( array('post', 'put') ) )
		{
			$save = [
				'Time' => $time['Time'],
				'TimeComment' => []
			];

			foreach(['start_time', 'stop_time'] as $key) {
				$save['Time'][$key] = $this->request->data['Time'][$key];
			}

			if( $this->request->data['Time']['blank'] )
			{
				$save['Time']['stop_time'] = null;
			}

			if( trim($this->request->data['TimeComment']['body']) != "" )
			{
				$save['TimeComment'][] = array(
					'user_id' => $this->Auth->user('user_id'),
					'body' => $this->request->data['TimeComment']['body']
				);
			}

			$this->Time->clear();

			//debug($save);

			if( $this->Time->saveAssociated($save) )
			{
				$this->Session->setFlash( sprintf(__('Time entry %1$u was successfully updated.'), $this->Time->id), 'success');

				return $this->redirect( $this->_Redirector('coordinator', 'events', 'view', $time['EventTime'][0]['Event']['event_id']) );
			}
			else
			{
				$this->Session->setFlash( __('There were problems saving your time entry edit.'), 'danger');
			}
		}

		$this->request->data = $time;
		$this->set( compact('time', 'title_for_layout') );

	}

	public function coordinator_delete($time_id)
	{
		if( !$this->Time->exists($time_id) )
		{
			$this->Session->setFlash( __('An invalid time entry was specified.'), 'warning');
			return $this->redirect( $this->_Redirector('coordinator', 'events', 'index') );
		}

		// fetch time id
		$time = $this->Time->findAllByTimeId($time_id);

		// verify that the current user can read/write this organization's time entries
		if( !$this->_CurrentUserCanWrite($time['Time']['organization_id']) )
		{
			$this->Session->setFlash( __("You are not allowed to edit this organization's time entries"), 'danger');
			return $this->redirect( $this->_Redirector('go', 'organizations', 'view', $time['Time']['organization_id']) );
		}

		$title_for_layout = sprintf( __('Deleting Time Entry %u'), $time_id);
		// post block
			// check a confirm variable
			// redirect to coordinator/event/edit/:event_id
		if( $this->request->is('post') )
		{
			if( $this->Time->delete($time_id) )
			{
				$this->Session->setFlash( sprintf(__("Time entry %u has been deleted."), $time_id), 'success');
				return $this->rediirect( array('coordinator' => true, 'controller' => 'times', 'action' => 'view', $time['Event']['event_id']) );
			}
		}

		$this->set( compact('title_for_layout') );
	}

	public function coordinator_adjust( $event_id )
	{
		$conditions = array(
			'Event.event_id' => $event_id
		);

		$contain = array('Organization');
		$event = $this->Time->EventTime->Event->find( 'first', array('conditions' => $conditions) );

		if( empty($event) ) {
			throw new NotFoundException('This event could not be found.');
		}

		// verify that the current user can read/write this organization's time entries
		if( !$this->_CurrentUserCanWrite($event['Organization']['organization_id']) )
		{
			$this->Session->setFlash( __("You are not allowed to edit this organization's time entries"), 'danger');
			return $this->redirect( $this->_Redirector('go', 'organizations', 'view', $time['Time']['organization_id']) );
		}

		$title_for_layout = sprintf( __('Adjusting Time Entries for %s'), $event['Event']['title']);

		$time_ids = $this->Time->EventTime->find('list', array(
			'conditions' => array(
				'EventTime.event_id' => $event_id
			),
			'fields' => array(
				'time_id'
			)
		));

		if( $this->request->is('post') )
		{
			$data = $this->request->data;

			if( $data['Adjust']['mode'] == 'save' ) {
				$save = [];
				foreach($data['Time'] as $idx => &$time) {
					if( $time['blank'] == '1' ) {
						$time['stop_time'] = null;
					}
					unset($time['blank']);
					$save[] = [
						'Time' => [
							'time_id' => $time['time_id'],
							'start_time' => $time['start_time'],
							'stop_time' => $time['stop_time']
							]
						];
				}

				if( $this->Time->saveMany($save, [
					'fieldList' => ['start_time', 'stop_time'],
					'validate' => false,
					'callbacks' => false
				])) {
					$this->Session->setFlash( __('Time entries for this event have been saved.'), 'success');
				}
			} else if( in_array($data['Adjust']['mode'], ['now', 'event__stop_time'])) {
				$time = $data['Adjust']['mode'] == 'now'
					? time()
					: strtotime($event['Event']['stop_time']);

				$new = array(
					'Time.stop_time' => sprintf("'%s'", date('Y-m-d H:i:s',  $time ) ) // this is disgusting syntax
				);

				$where = array(
					'Time.time_id' => $time_ids,
					'Time.stop_time IS NULL'
				);

				if( $this->Time->updateAll( $new, $where ) )
				{
					$message = $data['Adjust']['mode'] == 'now'
						? __('Missed punches have been set to now.')
						: __('Missed punches have been set to the end of the event.');
					$this->Session->setFlash( $message, 'success');
				}
				else
				{
					$this->Session->setFlash( __('Something went wrong with automatic time entry adjustment.'), 'danger');
				}
			} else {
				$this->Session->setFlash( __('Something went wrong with automatic time entry adjustment.'), 'danger');
			}
		}

		$allowed_sorts = [
			'User.first_name',
			'User.last_name',
			'User.username',
			'Time.start_time',
			'Time.stop_time'
		];

		$sortColumn = 'Time.start_time';
		if(
			isset($this->request->query['sort'])
			&& in_array($this->request->query['sort'], $allowed_sorts)
		) {
			$sortColumn = $this->request->query['sort'];
		}

		$allowed_directions = [
			'asc',
			'desc'
		];

		$sortDirection = 'asc';
		if(
			isset($this->request->query['direction'])
			&& in_array($this->request->query['direction'], $allowed_directions)
		) {
			$sortDirection = $this->request->query['direction'];
		}

		$timeTableName = $this->Time->table;
		$userTableName = $this->Time->User->table;
		$eventTimeTableName = $this->Time->EventTime->table;
		$eventTableName = $this->Time->EventTime->Event->table;

		$grouped = $this->Time->query(
sprintf(
"SELECT User.user_id,
		User.first_name ,
		User.last_name ,
		User.username ,
		CONCAT(User.first_name, ' ', User.last_name) as User__full_name,
		Time.time_id ,
		Time.start_time ,
		Time.stop_time
	FROM %s AS Time
	INNER JOIN %s AS User on Time.user_id = User.user_id
	INNER JOIN %s AS EventTime on Time.time_id = EventTime.time_id
	INNER JOIN %s AS Event on EventTime.event_id = Event.event_id
	WHERE Event.event_id = %u
	ORDER BY %s %s,
	Time.time_id ASC;
", $timeTableName, $userTableName, $eventTimeTableName, $eventTableName, $event_id, $sortColumn, $sortDirection)
);

		$this->set( compact('event', 'title_for_layout', 'grouped', 'sortColumn', 'sortDirection') );

		//throw new NotImplementedException('this method exists but has not been implemented');
	}

	public function supervisor_view( $time_id )
	{
		$conditions = array('Time.time_id' => $time_id);
		$contain = array('Event' => array('Organization'), 'User');

		$time = $this->Time->find('first', array('conditions' => $conditions, 'contain' => $contain) );

		if( !$this->_CurrentUserCanRead($time['Event']['Organization']['organization_id']) )
		{
			$this->Session->setFlash( __('You do not have permission to view information for this organization.'), 'danger');
			return $this->redirect( array('supervisor' => false, 'controller' => 'users', 'action' => 'activity') );
		}

		$title_for_layout = sprintf( __('Viewing Time Entry %u « %s « %s'), $time['Time']['time_id'], $time['Event']['title'], $time['Event']['Organization']['name']);

		$this->set( compact('time', 'title_for_layout') );
	}

}


text:
shared_examples 'a running Confluence Docker container without reverse proxy' do |container_name, |
  before :all do
    @container_confluence = Docker::Container.get(container_name)
    @container_confluence.start! PublishAllPorts: true
    @container_confluence.setup_capybara_confluence_url tcp: 8090
  end

  describe 'when checking a Confluence container' do
    subject { @container_confluence }

    it { is_expected.to_not be_nil }
    # it { is_expected.to be_running }
    it { is_expected.to have_mapped_ports tcp: 8090 }
    it { is_expected.not_to have_mapped_ports udp: 8090 }
    it { is_expected.to wait_until_output_matches REGEX_STARTUP_CONFLUENCE }
  end
end

shared_examples 'a running Confluence Docker container with reverse proxy' do |container_name, |
  before :all do
    @container_confluence = Docker::Container.get(container_name)
    @container_confluence.start! PublishAllPorts: true
    @container_confluence.setup_capybara_confluence_url tcp: 8090
  end

  describe 'when checking a Confluence container' do
    subject { @container_confluence }

    it { is_expected.to_not be_nil }
    # it { is_expected.to be_running }
    it { is_expected.to wait_until_output_matches REGEX_STARTUP_CONFLUENCE }
  end
end

shared_examples 'a running Jira Docker container without reverse proxy' do |container_name, |
  before :all do
    @container_jira = Docker::Container.get(container_name)
    # @container_jira.start! PublishAllPorts: true
    @container_jira.setup_capybara_jira_url tcp: 8080
  end

  describe 'when checking a Jira container' do
    subject { @container_jira }

    it { is_expected.to_not be_nil }
    # it { is_expected.to be_running }
    it { is_expected.to have_mapped_ports tcp: 8080 }
    it { is_expected.not_to have_mapped_ports udp: 8080 }
    it { is_expected.to wait_until_output_matches REGEX_STARTUP_JIRA }
  end
end

shared_examples 'a running Jira Docker container with reverse proxy' do |container_name, |
  before :all do
    @container_jira = Docker::Container.get(container_name)
    @container_jira.start! PublishAllPorts: true
    @container_jira.setup_capybara_jira_url tcp: 8080
  end

  describe 'when checking a Jira container' do
    subject { @container_jira }

    it { is_expected.to_not be_nil }
    # it { is_expected.to be_running }
    it { is_expected.to wait_until_output_matches REGEX_STARTUP_JIRA }
  end
end


text:
pub mod binary;
pub mod quick_sort;
pub mod bfs;
pub mod dijkstra;
pub mod dynamic_programming;


text:
<?php

namespace Kyoushu\InlineSwiftmailerTransport\Tests\MessageFilter;

use Kyoushu\InlineSwiftmailerTransport\Tests\TestCase;
use Symfony\Component\DomCrawler\Crawler;

class MessageFilterTestCase extends TestCase
{

    /**
     * @param \Swift_Transport|null $deliveryTransport
     * @param \Swift_Events_EventDispatcher|null $dispatcher
     * @return \Kyoushu\InlineSwiftmailerTransport\InlineTransport
     */
    protected function createInlineTransport(\Swift_Transport $deliveryTransport = null, \Swift_Events_EventDispatcher $dispatcher = null)
    {
        $transport = parent::createInlineTransport($deliveryTransport, $dispatcher);
        $transport->clearMessageFilters();
        return $transport;
    }

    /**
     * @param \Swift_Mime_Message $message
     * @param string $cssSelector
     * @param string $attrKey
     * @param string $expected
     */
    protected function assertBodyElementAttributesEquals(\Swift_Mime_Message $message, $cssSelector, $attrKey, $expected)
    {
        $body = $message->getBody();

        $crawler = new Crawler($body);

        /** @var \DOMElement[] $elements */
        $elements = $crawler->filter($cssSelector);

        $this->assertGreaterThan(0, count($elements));

        foreach($elements as $element){
            $elementAttrValue = $element->getAttribute($attrKey);
            $this->assertEquals($expected, $elementAttrValue);
        }
    }

}


text:
package org.apache.camel.component.azure.servicebus;

import java.util.HashMap;
import java.util.Map;

import com.azure.core.credential.TokenCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import org.apache.camel.ResolveEndpointFailedException;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

class ServiceBusEndpointTest extends CamelTestSupport {

    @Test
    void testCreateWithInvalidData() {
        assertThrows(ResolveEndpointFailedException.class,
                () -> context.getEndpoint("azure-servicebus:test//?"));

        assertThrows(ResolveEndpointFailedException.class,
                () -> context.getEndpoint("azure-servicebus://?connectionString=test"));

        // provided credential but no fully qualified namespace
        assertThrows(ResolveEndpointFailedException.class,
                () -> context.getEndpoint("azure-servicebus:test?tokenCredential=credential"));
    }

    @Test
    void testCreateEndpointWithConfig() throws Exception {
        final String uri = "azure-servicebus://testTopicOrQueue";
        final String remaining = "testTopicOrQueue";
        final Map<String, Object> params = new HashMap<>();
        params.put("serviceBusType", ServiceBusType.topic);
        params.put("prefetchCount", 10);
        params.put("connectionString", "testString");

        final ServiceBusEndpoint endpoint
                = (ServiceBusEndpoint) context.getComponent("azure-servicebus", ServiceBusComponent.class)
                        .createEndpoint(uri, remaining, params);

        assertEquals(ServiceBusType.topic, endpoint.getConfiguration().getServiceBusType());
        assertEquals("testTopicOrQueue", endpoint.getConfiguration().getTopicOrQueueName());
        assertEquals(10, endpoint.getConfiguration().getPrefetchCount());
        assertEquals("testString", endpoint.getConfiguration().getConnectionString());
    }

    @Test
    void testCreateEndpointWithFqns() throws Exception {
        final String uri = "azure-servicebus://testTopicOrQueue";
        final String remaining = "testTopicOrQueue";
        final String fullyQualifiedNamespace = "namespace.servicebus.windows.net";
        final Map<String, Object> params = new HashMap<>();
        params.put("serviceBusType", ServiceBusType.topic);
        params.put("prefetchCount", 10);
        params.put("fullyQualifiedNamespace", fullyQualifiedNamespace);

        final ServiceBusEndpoint endpoint
                = (ServiceBusEndpoint) context.getComponent("azure-servicebus", ServiceBusComponent.class)
                        .createEndpoint(uri, remaining, params);

        assertEquals(ServiceBusType.topic, endpoint.getConfiguration().getServiceBusType());
        assertEquals("testTopicOrQueue", endpoint.getConfiguration().getTopicOrQueueName());
        assertEquals(10, endpoint.getConfiguration().getPrefetchCount());
        assertEquals(fullyQualifiedNamespace, endpoint.getConfiguration().getFullyQualifiedNamespace());
        assertNotNull(endpoint.getConfiguration().getTokenCredential());
    }

    @Test
    void testCreateEndpointWithFqnsAndCredential() throws Exception {
        final String uri = "azure-servicebus://testTopicOrQueue";
        final String remaining = "testTopicOrQueue";
        final String fullyQualifiedNamespace = "namespace.servicebus.windows.net";
        final TokenCredential credential = new DefaultAzureCredentialBuilder().build();
        final Map<String, Object> params = new HashMap<>();
        params.put("serviceBusType", ServiceBusType.topic);
        params.put("prefetchCount", 10);
        params.put("fullyQualifiedNamespace", fullyQualifiedNamespace);
        params.put("tokenCredential", credential);

        final ServiceBusEndpoint endpoint
                = (ServiceBusEndpoint) context.getComponent("azure-servicebus", ServiceBusComponent.class)
                        .createEndpoint(uri, remaining, params);

        assertEquals(ServiceBusType.topic, endpoint.getConfiguration().getServiceBusType());
        assertEquals("testTopicOrQueue", endpoint.getConfiguration().getTopicOrQueueName());
        assertEquals(10, endpoint.getConfiguration().getPrefetchCount());
        assertEquals(fullyQualifiedNamespace, endpoint.getConfiguration().getFullyQualifiedNamespace());
        assertEquals(credential, endpoint.getConfiguration().getTokenCredential());
    }

    @Test
    void testCreateEndpointWithFqnsAndCredentialFromRegistry() throws Exception {
        final String uri = "azure-servicebus://testTopicOrQueue";
        final String remaining = "testTopicOrQueue";
        final String fullyQualifiedNamespace = "namespace.servicebus.windows.net";
        final TokenCredential credential = new DefaultAzureCredentialBuilder().build();
        final Map<String, Object> params = new HashMap<>();
        context().getRegistry().bind("tokenCredential", credential);
        params.put("serviceBusType", ServiceBusType.topic);
        params.put("prefetchCount", 10);
        params.put("fullyQualifiedNamespace", fullyQualifiedNamespace);

        final ServiceBusEndpoint endpoint
                = (ServiceBusEndpoint) context.getComponent("azure-servicebus", ServiceBusComponent.class)
                        .createEndpoint(uri, remaining, params);

        assertEquals(ServiceBusType.topic, endpoint.getConfiguration().getServiceBusType());
        assertEquals("testTopicOrQueue", endpoint.getConfiguration().getTopicOrQueueName());
        assertEquals(10, endpoint.getConfiguration().getPrefetchCount());
        assertEquals(fullyQualifiedNamespace, endpoint.getConfiguration().getFullyQualifiedNamespace());
        assertEquals(credential, endpoint.getConfiguration().getTokenCredential());
    }
}


text:
<?php

/*
 * This file is part of Mongator.
 *
 * (c) Pablo Díez <pablodip@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Mongator\Tests\Extension;

use Mongator\Tests\TestCase;

class CoreRepositoryTest extends TestCase
{
    public function testIdToMongo()
    {
        $id = '4af9f23d8ead0e1d32000000';
        $idToMongo = $this->mongator->getRepository('Model\Article')->idToMongo($id);
        $this->assertInstanceOf('MongoId', $idToMongo);
    }

    public function testSaveInsertingNotModified()
    {
        $article = $this->mongator->create('Model\Article');
        $this->mongator->getRepository('Model\Article')->save($article);
        $this->assertTrue($article->isNew());

        $articles = array(
            $this->mongator->create('Model\Article'),
            $this->mongator->create('Model\Article')->setTitle('foo'),
        );
        $this->mongator->getRepository('Model\Article')->save($articles);
        $this->assertTrue($articles[0]->isNew());
        $this->assertFalse($articles[1]->isNew());
    }

    public function testSaveUpdatingNotModified()
    {
        $article = $this->mongator->create('Model\Article')->setTitle('foo')->save();
        $this->mongator->getRepository('Model\Article')->save($article);

        $articles = array(
            $this->mongator->create('Model\Article')->setTitle('a1')->save(),
            $this->mongator->create('Model\Article')->setTitle('a2')->save()->setTitle('a2u'),
        );
        $this->mongator->getRepository('Model\Article')->save($articles);
    }

    public function testSaveInsertSingleDocument()
    {
        $article = $this->mongator->create('Model\Article')->fromArray(array(
            'title'   => 'foo',
            'content' => 12345,
        ));

        $this->mongator->getRepository('Model\Article')->save($article);
        $this->assertSame(1, $this->mongator->getRepository('Model\Article')->getCollection()->count());

        $this->assertFalse($article->isNew());
        $this->assertFalse($article->isModified());
        $articleRaw = $this->mongator->getRepository('Model\Article')->getCollection()->findOne();
        $this->assertSame(3, count($articleRaw));
        $this->assertEquals($article->getId(), $articleRaw['_id']);
        $this->assertSame('foo', $articleRaw['title']);
        $this->assertSame('12345', $articleRaw['content']);
        $this->assertTrue($this->mongator->getRepository('Model\Article')->getIdentityMap()->has($article->getId()));
    }

    public function testSaveInsertMultipleDocuments()
    {
        $articles = array();
        for ($i = 1; $i <= 5; $i++) {
            $articles[$i] = $this->mongator->create('Model\Article')->fromArray(array(
                'title'   => 'foo'.$i,
                'content' => 12345 + $i,
            ));
        }

        $this->mongator->getRepository('Model\Article')->save($articles);
        $this->assertSame(5, $this->mongator->getRepository('Model\Article')->getCollection()->count());

        foreach ($articles as $i => $article) {
            $this->assertFalse($article->isNew());
            $this->assertFalse($article->isModified());
            $articleRaw = $this->mongator->getRepository('Model\Article')->getCollection()->findOne(array('_id' => $article->getId()));
            $this->assertSame(3, count($articleRaw));
            $this->assertEquals($article->getId(), $articleRaw['_id']);
            $this->assertSame('foo'.$i, $articleRaw['title']);
            $this->assertSame(strval(12345 + $i), $articleRaw['content']);
            $this->assertTrue($this->mongator->getRepository('Model\Article')->getIdentityMap()->has($article->getId()));
        }
    }

    public function testSaveUpdateSingleDocument()
    {
        $articles = array();
        for ($i = 1; $i <= 5; $i++) {
            $articles[$i] = $this->mongator->create('Model\Article')->fromArray(array(
                'title'   => 'foo'.$i,
                'content' => 12345 + $i,
            ));
        }
        $this->mongator->getRepository('Model\Article')->save($articles);

        $articles[2]->setTitle('updated!');
        $this->mongator->getRepository('Model\Article')->save($articles[2]);

        $this->assertFalse($articles[2]->isModified());
        $this->assertSame(4, $this->mongator->getRepository('Model\Article')->getCollection()->find(array('title' => new \MongoRegex('/^foo/')))->count());
    }

    public function testSaveShouldConvertIdsToMongoWhenUpdating()
    {
        $article = $this->create('Model\Article')
            ->setTitle('foo')
            ->save();

        $id = $article->getId();
        $article
            ->setId($id->__toString())
            ->setTitle('bar')
            ->save();

        $collection = $this->getCollection('Model\Article');

        $result = $collection->findOne(array('_id' => $id));
        $expectedResult = array('_id' => $id, 'title' => 'bar');

        $this->assertEquals($expectedResult, $result);
    }

    public function testSaveUpdateMultipleDocument()
    {
        $articles = array();
        for ($i = 1; $i <= 5; $i++) {
            $articles[$i] = $this->mongator->create('Model\Article')->setTitle('foo'.$i);
        }
        $this->mongator->getRepository('Model\Article')->save($articles);

        $articles[2]->setTitle('updated!');
        $articles[4]->setTitle('updated!');
        $this->mongator->getRepository('Model\Article')->save(array($articles[2], $articles[4]));

        $this->assertFalse($articles[4]->isModified());
        $this->assertFalse($articles[4]->isModified());
        $this->assertSame(3, $this->mongator->getRepository('Model\Article')->getCollection()->find(array('title' => new \MongoRegex('/^foo/')))->count());
    }

    public function testSaveSaveReferences()
    {
        $article = $this->mongator->create('Model\Article')->setTitle('foo');
        $author = $this->mongator->create('Model\Author')->setName('bar');
        $article->setAuthor($author);
        $article->save();

        $this->assertFalse($article->isNew());
        $this->assertFalse($author->isNew());
        $this->assertSame($author->getId(), $article->getAuthorId());
    }

    public function testSaveSaveReferencesSameClass()
    {
        $messages = array();
        $messages['barbelith'] = $this->mongator->create('Model\Message')->setAuthor('barbelith');
        $messages['pablodip'] = $this->mongator->create('Model\Message')->setAuthor('pablodip')->setReplyTo($messages['barbelith']);

        $this->mongator->getRepository('Model\Message')->save($messages);

        $this->assertFalse($messages['pablodip']->isNew());
        $this->assertFalse($messages['barbelith']->isNew());
        $this->assertSame($messages['pablodip']->getReplyToId(), $messages['barbelith']->getId());
    }

    public function testSaveResetGroups()
    {
        // insert
        $article = $this->mongator->create('Model\Article')
            ->addCategories($category = $this->mongator->create('Model\Category')
                ->setName('foo')
            )
            ->save()
        ;
        $this->assertSame(0, count($article->getCategories()->getAdd()));

        // update
        $article
             ->addCategories($category = $this->mongator->create('Model\Category')
                ->setName('foo')
            )
            ->save()
        ;
        $this->assertSame(0, count($article->getCategories()->getAdd()));
    }

    public function testDeleteSingleDocument()
    {
        $articles = array();
        for ($i = 1; $i <= 5; $i++) {
            $articles[$i] = $this->mongator->create('Model\Article')->setTitle('foo');
        }
        $this->mongator->getRepository('Model\Article')->save($articles);

        $id = $articles[2]->getId();
        $this->mongator->getRepository('Model\Article')->delete($articles[2]);

        $this->assertTrue($articles[2]->isNew());
        $this->assertNull($this->mongator->getRepository('Model\Article')->getCollection()->findOne(array('_id' => $id)));
        $this->assertSame(4, $this->mongator->getRepository('Model\Article')->getCollection()->count());
        $this->assertFalse($this->mongator->getRepository('Model\Article')->getIdentityMap()->has($id));
        foreach (array(1, 3, 4, 5) as $key) {
            $this->assertFalse($articles[$key]->isNew());
            $this->assertNotNull($this->mongator->getRepository('Model\Article')->getCollection()->findOne(array('_id' => $articles[$key]->getId())));
            $this->assertTrue($this->mongator->getRepository('Model\Article')->getIdentityMap()->has($articles[$key]->getId()));
        }
    }

    public function testDeleteShouldConvertIdsToMongo()
    {
        $article = $this->create('Model\Article')
            ->setTitle('foo')
            ->save();

        $id = $article->getId();
        $article
            ->setId($id->__toString())
            ->delete();

        $collection = $this->getCollection('Model\Article');
        $result = $collection->findOne(array('_id' => $id));

        $this->assertNull($result);
    }

    public function testDeleteMultipleDocuments()
    {
        $articles = array();
        for ($i = 1; $i <= 5; $i++) {
            $articles[$i] = $this->mongator->create('Model\Article')->setTitle('foo');
        }
        $this->mongator->getRepository('Model\Article')->save($articles);

        $ids = array($articles[2]->getId(), $articles[3]->getId());
        $this->mongator->getRepository('Model\Article')->delete(array($articles[2], $articles[3]));

        $this->assertTrue($articles[2]->isNew());
        $this->assertTrue($articles[3]->isNew());
        $this->assertSame(0, $this->mongator->getRepository('Model\Article')->getCollection()->find(array('_id' => array('$in' => $ids)))->count());
        $this->assertFalse($this->mongator->getRepository('Model\Article')->getIdentityMap()->has($ids[0]));
        $this->assertFalse($this->mongator->getRepository('Model\Article')->getIdentityMap()->has($ids[1]));
        foreach (array(1, 4, 5) as $key) {
            $this->assertFalse($articles[$key]->isNew());
            $this->assertNotNull($this->mongator->getRepository('Model\Article')->getCollection()->findOne(array('_id' => $articles[$key]->getId())));
            $this->assertTrue($this->mongator->getRepository('Model\Article')->getIdentityMap()->has($articles[$key]->getId()));
        }
    }

    public function testEnsureIndexesMethod()
    {

        $admin = $this->mongator->getRepository('Model\Article')
            ->getMongator()
            ->getDefaultConnection()
            ->getMongo()->admin;

        $admin->command(array(
            'setParameter' => 1,
            'textSearchEnabled' => 1
        ));

        $this->mongator->getRepository('Model\Article')->ensureIndexes();

        $indexInfo = $this->mongator->getRepository('Model\Article')->getCollection()->getIndexInfo();

        // root
        $this->assertSame(array('slug' => 1), $indexInfo[1]['key']);
        $this->assertSame(true, $indexInfo[1]['unique']);
        $this->assertSame(array('authorId' => 1, 'isActive' => 1), $indexInfo[2]['key']);

        // embeddeds one
        $this->assertSame(array('source.name' => 1), $indexInfo[3]['key']);
        $this->assertSame(true, $indexInfo[3]['unique']);
        $this->assertSame(array('source.authorId' => 1, 'source.line' => 1), $indexInfo[4]['key']);

        // embeddeds one deep
        $this->assertSame(array('source.info.note' => 1), $indexInfo[5]['key']);
        $this->assertSame(true, $indexInfo[5]['unique']);
        $this->assertSame(array('source.info.name' => 1, 'source.info.line' => 1), $indexInfo[6]['key']);

        // embeddeds many
        $this->assertSame(array('comments.line' => 1), $indexInfo[7]['key']);
        $this->assertSame(true, $indexInfo[7]['unique']);
        $this->assertSame(array('comments.authorId' => 1, 'comments.note' => 1), $indexInfo[8]['key']);

        // embeddeds many deep
        $this->assertSame(array('comments.infos.note' => 1), $indexInfo[9]['key']);
        $this->assertSame(true, $indexInfo[9]['unique']);
        $this->assertSame(array('comments.infos.name' => 1, 'comments.infos.line' => 1), $indexInfo[10]['key']);
    }

    public function testEnsureIndexesMethodTextIndexes()
    {
        $this->mongator->getRepository('Model\Message')->ensureIndexes();

        $indexInfo = $this->mongator->getRepository('Model\Message')->getCollection()->getIndexInfo();

        $this->assertSame(array('_fts' => 'text', '_ftsx' => 1), $indexInfo[1]['key']);
        $this->assertSame('ExampleTextIndex', $indexInfo[1]['name']);
        $this->assertSame(array('author' => 100, 'text' => 30), $indexInfo[1]['weights']);
    }

    /*
     * Related to Mongator\Repository
     */

    public function testDocumentClass()
    {
        $this->assertSame('Model\Article', $this->mongator->getRepository('Model\Article')->getDocumentClass());
        $this->assertSame('Model\Category', $this->mongator->getRepository('Model\Category')->getDocumentClass());
    }

    public function testIsFile()
    {
        $this->assertFalse($this->mongator->getRepository('Model\Article')->isFile());
        $this->assertTrue($this->mongator->getRepository('Model\Image')->isFile());
    }

    public function testConnectionName()
    {
        $this->assertNull($this->mongator->getRepository('Model\Article')->getConnectionName());
        $this->assertSame('global', $this->mongator->getRepository('Model\ConnectionGlobal')->getConnectionName());
    }

    public function testCollectionName()
    {
        $this->assertSame('articles', $this->mongator->getRepository('Model\Article')->getCollectionName());
        $this->assertSame('model_category', $this->mongator->getRepository('Model\Category')->getCollectionName());
    }
}


text:
package com.github.programmerr47.vkgroups.background.methods;

import android.util.Log;

import com.github.programmerr47.vkgroups.VKGroupApplication;
import com.github.programmerr47.vkgroups.adapter.item.PostItem;
import com.github.programmerr47.vkgroups.adapter.item.PostItemNotifier;
import com.vk.sdk.api.VKApi;
import com.vk.sdk.api.VKApiConst;
import com.vk.sdk.api.VKError;
import com.vk.sdk.api.VKParameters;
import com.vk.sdk.api.VKRequest;
import com.vk.sdk.api.VKResponse;
import com.vk.sdk.api.model.VKApiCommunity;
import com.vk.sdk.api.model.VKApiPost;
import com.vk.sdk.api.model.VKApiUser;
import com.vk.sdk.api.model.VKPostArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author Mihail Spitsin
 * @since 2/17/2016
 */
public class VkApiWallDownloader {

    private static final Executor REQUEST_EXECUTOR = Executors.newSingleThreadExecutor();

//    private boolean isReady = true;
    private boolean isPostsDownloading;
    private boolean isPostsDownloadedCompletely;
//    private boolean isKnownAboutDownloading;

    private PostItemNotifier postItemNotifier;
    private GetPostsListener postsListener;

    public void download(int id) {
        download(id, 0);
    }

    public void download(int id, int offset) {
        download(id, offset, 20);
    }

    public void download(int id, final int offset, final int count) {
        if (!isPostsDownloading) {
            isPostsDownloading = true;
//            isKnownAboutDownloading = false;

            final VKRequest request = VKApi.wall().get(VKParameters.from(
                    VKApiConst.OWNER_ID, id,
                    VKApiConst.EXTENDED, 1,
                    VKApiConst.OFFSET, offset,
                    VKApiConst.COUNT, count));

            request.executeWithListener(new VKRequest.VKRequestListener() {
                @Override
                public void onComplete(final VKResponse response) {
                    REQUEST_EXECUTOR.execute(new Runnable() {
                        @Override
                        public void run() {
                            VKPostArray postArray = (VKPostArray) response.parsedModel;

                            if (postArray.size() < count) {

                                VKGroupApplication.getUiHandler().post(new Runnable() {
                                    @Override
                                    public void run() {
                                        isPostsDownloadedCompletely = true;
                                    }
                                });
                            }

                            Map<Integer, VKApiUser> userMap = new HashMap<>();
                            for (VKApiUser user : postArray.getUsers()) {
                                userMap.put(user.id, user);
                            }

                            Map<Integer, VKApiCommunity> groupMap = new HashMap<>();
                            for (VKApiCommunity group : postArray.getCommunities()) {
                                groupMap.put(group.id, group);
                            }

                            final List<PostItem> items = new ArrayList<>();
                            for (VKApiPost apiPost : postArray) {
                                PostItem postItem = new PostItem(apiPost, userMap, groupMap, postItemNotifier);
                                items.add(postItem);
                            }

                            VKGroupApplication.getUiHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    postsListener.onPostsLoaded(items, offset, count);
                                    isPostsDownloading = false;
                                }
                            });
                        }
                    });
                }

                @Override
                public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) {
                    super.attemptFailed(request, attemptNumber, totalAttempts);
                    isPostsDownloading = false;
                }

                @Override
                public void onError(VKError error) {
                    super.onError(error);
                    isPostsDownloading = false;
                }

                @Override
                public void onProgress(VKRequest.VKProgressType progressType, long bytesLoaded, long bytesTotal) {
                    super.onProgress(progressType, bytesLoaded, bytesTotal);
                }
            });
        }
    }

    public void setItemNotifier(PostItemNotifier postItemNotifier) {
        this.postItemNotifier = postItemNotifier;
    }

    public void setPostsListener(GetPostsListener postsListener) {
        this.postsListener = postsListener;
    }

//    public void setReadyState(boolean isReady) {
//        this.isReady = isReady;
//
//        if (isReady && !isPostsDownloading && !isKnownAboutDownloading) {
//            performCompletionOfDownloadingPart();
//        }
//    }

    public boolean isPostsDownloadedCompletely() {
        return isPostsDownloadedCompletely;
    }

    public boolean canDownload() {
        return !isPostsDownloadedCompletely && !isPostsDownloading;
    }

    public void setChatsDownloadedCompletely() {
        this.isPostsDownloadedCompletely = true;
    }

//    private void performCompletionOfDownloadingPart() {
//        onPartIsDownloaded();
//        isKnownAboutDownloading = true;
//    }

    public interface GetPostsListener {
        void onPostsLoaded(List<PostItem> posts, int offset, int count);
    }
}


text:
We craft experiences that transform brands and grow businesses.

Let's talk


text:
using System;

namespace sharpHDF.Library.Structs
{
    public struct Hdf5Identifier
    {

#if HDF5_VER1_10
        public Hdf5Identifier(Int64 _value)
        {
            Value = _value;
        }

        public Int64 Value;
#else
        public Hdf5Identifier(Int32 _value)
        {
            Value = _value;
        }

        public readonly Int32 Value;
#endif

        public bool Equals(Hdf5Identifier _other)
        {
            return Value == _other.Value;
        }

        public override int GetHashCode()
        {
            return Value;
        }
    }
}


text:
package de.intarsys.tools.authenticate;

import de.intarsys.tools.component.ConfigurationException;
import de.intarsys.tools.infoset.ElementTools;
import de.intarsys.tools.infoset.IElement;
import de.intarsys.tools.infoset.IElementConfigurable;
import de.intarsys.tools.reflect.ObjectCreationException;

public class FilteredCredentialStore implements ICredentialStore,
		IElementConfigurable {

	// similar to the one in commons-collections
	public static interface Predicate {

		public boolean evaluate(ICredentialScope scope);
	}

	// similar to the one in commons-collections
	private static class TruePredicate implements Predicate {

		@Override
		public boolean evaluate(ICredentialScope scope) {
			return true;
		}
	}

	private static final String TAG_PREDICATE = "predicate"; //$NON-NLS-1$

	private Predicate predicate;
	private ICredentialStore store = new BasicCredentialProvider();

	public FilteredCredentialStore() {
		this(new TruePredicate());
	}

	public FilteredCredentialStore(Predicate predicate) {
		this.predicate = predicate;
	}

	@Override
	public void clear() {
		store.clear();
	}

	@Override
	public void configure(IElement element)
			throws ConfigurationException {
		IElement predicateElement = element.element(TAG_PREDICATE);
		if (element != null) {
			try {
				predicate = ElementTools.createObject(predicateElement,
						Predicate.class, null);
			} catch (ObjectCreationException ex) {
				throw new ConfigurationException(ex);
			}
		}
	}

	@Override
	public ICredential getCredential(ICredentialScope scope) {
		if (predicate.evaluate(scope)) {
			return store.getCredential(scope);
		}
		return null;
	}

	@Override
	public void removeCredential(ICredentialScope scope) {
		if (predicate.evaluate(scope)) {
			store.removeCredential(scope);
		}
	}

	@Override
	public void setCredential(ICredentialScope scope, ICredential credential) {
		if (predicate.evaluate(scope)) {
			store.setCredential(scope, credential);
		}
	}
}