text:
<?php

namespace App\Http\Controllers;

use App\Models\Store;
use Auth;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class StoreController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return View
     */
    public function index()
    {
        return view('stores.index', [ 'stores' => Store::all() ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create()
    {
        return view('stores.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     */
    public function store(Request $request)
    {
        // Create the new Store
        $store = new Store();
        $store->label = $request->label;
        $store->user_id = Auth::id();

        // Save it
        $store->save();

        session()->flash('message', 'Store has been saved');
        session()->flash('message-type', 'success');

        return redirect()->action('StoreController@index');
    }

    /**
     * Display the specified resource.
     *
     * @param Store $store
     *
     * @return View
     */
    public function show(Store $store)
    {
        return view('stores.show', [ 'store' => $store ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Store $store
     *
     * @return View
     */
    public function edit(Store $store)
    {
        return view('stores.edit', [ 'store' => $store ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param Store $store
     *
     * @return RedirectResponse
     */
    public function update(Request $request, Store $store)
    {
        // Update data
        $store->label = $request->label;

        // Save it
        $store->save();

        session()->flash('message', 'Store has been saved');
        session()->flash('message-type', 'success');

        return redirect()->action('StoreController@index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Store $store
     *
     * @return void
     */
    public function destroy(Store $store)
    {
        //
    }
}


text:
package com.facebook.imagepipeline.core;

import android.net.Uri;

import com.facebook.common.media.MediaUtils;
import com.facebook.common.memory.PooledByteBuffer;
import com.facebook.common.references.CloseableReference;
import com.facebook.common.util.UriUtil;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.producers.Producer;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.Postprocessor;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.RETURNS_MOCKS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Tests {@link ProducerSequenceFactory}.
 */
@RunWith(RobolectricTestRunner.class)
@PrepareForTest({UriUtil.class, MediaUtils.class})
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
@Config(manifest = Config.NONE)
public class ProducerSequenceFactoryTest {

  @Mock public ImageRequest mImageRequest;
  @Mock public Postprocessor mPostprocessor;
  private final String mDummyMime = "dummy_mime";
  private Uri mUri;
  private ProducerSequenceFactory mProducerSequenceFactory;

  @Rule
  public PowerMockRule rule = new PowerMockRule();

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    PowerMockito.mockStatic(UriUtil.class, MediaUtils.class);

    ProducerFactory producerFactory = mock(ProducerFactory.class, RETURNS_MOCKS);

    mProducerSequenceFactory =
        new ProducerSequenceFactory(producerFactory, null, true, false, null, false);

    when(mImageRequest.getLowestPermittedRequestLevel())
        .thenReturn(ImageRequest.RequestLevel.FULL_FETCH);
    mUri = Uri.parse("http://dummy");
    when(mImageRequest.getSourceUri()).thenReturn(mUri);
    when(MediaUtils.extractMime(mUri.getPath())).thenReturn(mDummyMime);
    when(MediaUtils.isVideo(mDummyMime)).thenReturn(false);
  }

  @Test
  public void testNetworkFullFetch() {
    PowerMockito.when(UriUtil.isNetworkUri(mUri)).thenReturn(true);
    Producer producer = mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mNetworkFetchSequence);
  }

  @Test
  public void testNetworkFullPrefetch() {
    PowerMockito.when(UriUtil.isNetworkUri(mUri)).thenReturn(true);
    Producer<Void> producer =
        mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(mImageRequest);
    assertSame(
        producer,
        mProducerSequenceFactory.mCloseableImagePrefetchSequences.get(
            mProducerSequenceFactory.mNetworkFetchSequence));
  }

  @Test
  public void testLocalFileFetchToEncodedMemory() {
    PowerMockito.when(UriUtil.isLocalFileUri(mUri)).thenReturn(true);
    Producer<CloseableReference<PooledByteBuffer>> producer =
        mProducerSequenceFactory.getEncodedImageProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mLocalFileEncodedImageProducerSequence);
  }

  @Test
  public void testNetworkFetchToEncodedMemory() {
    PowerMockito.when(UriUtil.isNetworkUri(mUri)).thenReturn(true);
    Producer<CloseableReference<PooledByteBuffer>> producer =
        mProducerSequenceFactory.getEncodedImageProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mNetworkEncodedImageProducerSequence);
  }

  @Test
  public void testLocalFileFetchToEncodedMemoryPrefetch() {
    PowerMockito.when(UriUtil.isLocalFileUri(mUri)).thenReturn(true);
    Producer<Void> producer =
        mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mLocalFileFetchToEncodedMemoryPrefetchSequence);
  }

  @Test
  public void testNetworkFetchToEncodedMemoryPrefetch() {
    PowerMockito.when(UriUtil.isNetworkUri(mUri)).thenReturn(true);
    Producer<Void> producer =
        mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mNetworkFetchToEncodedMemoryPrefetchSequence);
  }

  @Test
  public void testLocalImageFileFullFetch() {
    PowerMockito.when(UriUtil.isLocalFileUri(mUri)).thenReturn(true);
    Producer<CloseableReference<CloseableImage>> producer =
        mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mLocalImageFileFetchSequence);
  }

  @Test
  public void testLocalImageFileFullPrefetch() {
    PowerMockito.when(UriUtil.isLocalFileUri(mUri)).thenReturn(true);
    Producer<Void> producer =
        mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(mImageRequest);
    assertSame(
        producer,
        mProducerSequenceFactory.mCloseableImagePrefetchSequences.get(
            mProducerSequenceFactory.mLocalImageFileFetchSequence));
  }

  @Test
  public void testLocalVideoFileFullFetch() {
    PowerMockito.when(UriUtil.isLocalFileUri(mUri)).thenReturn(true);
    when(MediaUtils.isVideo(mDummyMime)).thenReturn(true);
    Producer<CloseableReference<CloseableImage>> producer =
        mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mLocalVideoFileFetchSequence);
  }

  @Test
  public void testLocalVideoFileFullPrefetch() {
    PowerMockito.when(UriUtil.isLocalFileUri(mUri)).thenReturn(true);
    when(MediaUtils.isVideo(mDummyMime)).thenReturn(true);
    Producer<Void> producer =
        mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(mImageRequest);
    assertSame(
        producer,
        mProducerSequenceFactory.mCloseableImagePrefetchSequences.get(
            mProducerSequenceFactory.mLocalVideoFileFetchSequence));
  }

  @Test
  public void testLocalContentUriFullFetch() {
    PowerMockito.when(UriUtil.isLocalContentUri(mUri)).thenReturn(true);
    Producer<CloseableReference<CloseableImage>> producer =
        mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mLocalContentUriFetchSequence);
  }

  @Test
  public void testLocalContentUriFullPrefetch() {
    PowerMockito.when(UriUtil.isLocalContentUri(mUri)).thenReturn(true);
    Producer<Void> producer =
        mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(mImageRequest);
    assertSame(
        producer,
        mProducerSequenceFactory.mCloseableImagePrefetchSequences.get(
            mProducerSequenceFactory.mLocalContentUriFetchSequence));
  }

  @Test
  public void testLocalResourceFullFetch() {
    PowerMockito.when(UriUtil.isLocalResourceUri(mUri)).thenReturn(true);
    Producer<CloseableReference<CloseableImage>> producer =
        mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mLocalResourceFetchSequence);
  }

  @Test
  public void testLocalAssetFullFetch() {
    PowerMockito.when(UriUtil.isLocalAssetUri(mUri)).thenReturn(true);
    Producer<CloseableReference<CloseableImage>> producer =
        mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest);
    assertSame(producer, mProducerSequenceFactory.mLocalAssetFetchSequence);
  }

  @Test
  public void testLocalAssetAndResourceFullPrefetch() {
    PowerMockito.when(UriUtil.isLocalResourceUri(mUri)).thenReturn(true);
    Producer<Void> localResourceSequence =
        mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(mImageRequest);
    assertSame(
        localResourceSequence,
        mProducerSequenceFactory.mCloseableImagePrefetchSequences.get(
            mProducerSequenceFactory.mLocalResourceFetchSequence));
    PowerMockito.when(UriUtil.isLocalResourceUri(mUri)).thenReturn(false);
    PowerMockito.when(UriUtil.isLocalAssetUri(mUri)).thenReturn(true);
    Producer localAssetSequence =
        mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(mImageRequest);
    assertSame(
        localAssetSequence,
        mProducerSequenceFactory.mCloseableImagePrefetchSequences.get(
            mProducerSequenceFactory.mLocalAssetFetchSequence));
    assertNotSame(localAssetSequence, localResourceSequence);
  }

  @Test
  public void testPostprocess() {
    PowerMockito.when(UriUtil.isNetworkUri(mUri)).thenReturn(true);
    when(mImageRequest.getPostprocessor()).thenReturn(mPostprocessor);
    Producer<CloseableReference<CloseableImage>> networkSequence =
        mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest);
    assertSame(
        networkSequence,
        mProducerSequenceFactory.mPostprocessorSequences.get(
            mProducerSequenceFactory.mNetworkFetchSequence));

    // each source type should be different
    PowerMockito.when(UriUtil.isNetworkUri(mUri)).thenReturn(false);
    PowerMockito.when(UriUtil.isLocalContentUri(mUri)).thenReturn(true);
    Producer<CloseableReference<CloseableImage>> localSequence =
        mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest);
    assertSame(
        localSequence,
        mProducerSequenceFactory.mPostprocessorSequences.get(
            mProducerSequenceFactory.mLocalContentUriFetchSequence));
    assertNotSame(networkSequence, localSequence);

    // encoded return types don't get postprocessed
    PowerMockito.when(UriUtil.isNetworkUri(mUri)).thenReturn(true);
    Producer<CloseableReference<PooledByteBuffer>> encodedSequence =
        mProducerSequenceFactory.getEncodedImageProducerSequence(mImageRequest);
    assertSame(
        encodedSequence,
        mProducerSequenceFactory.mNetworkEncodedImageProducerSequence);
    assertNull(
        mProducerSequenceFactory.mPostprocessorSequences.get(
            mProducerSequenceFactory.mBackgroundNetworkFetchToEncodedMemorySequence));
  }
}

redpajama_set_name: RedPajamaGithub


text:
package net.katagaitai.phpscan.compiler;

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

import lombok.AllArgsConstructor;
import lombok.ToString;
import lombok.Value;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@ToString
@AllArgsConstructor
public class PhpProject {

	//	絶対関数名:「ファイル名+引数の数」リスト
	private Map<String, List<FunctionInfo>> functionMap = Maps.newHashMap();
	//	絶対クラス名:ファイル名リスト
	private Map<String, List<String>> classMap = Maps.newHashMap();
	//	メソッド名:「ファイル名+絶対クラス名+引数の数」リスト
	private Map<String, List<MethodInfo>> methodMap = Maps.newHashMap();
	//	静的メソッド名:「ファイル名+絶対クラス名+引数の数」リスト
	private Map<String, List<MethodInfo>> staticMethodMap = Maps.newHashMap();
	//	絶対定数名:ファイル名リスト
	private Map<String, List<String>> constantMap = Maps.newHashMap();
	//	絶対クラス名:絶対サブクラス名リスト
	private Map<String, List<String>> subClassMap = Maps.newHashMap();

	public PhpProject() {
	}

	@Value
	public static class FunctionInfo {
		private String filepath;
		private int minArgumentSize;
		private int maxArgumentSize;
	}

	@Value
	public static class MethodInfo {
		private String filepath;
		private String className;
		private int minArgumentSize;
		private int maxArgumentSize;
	}

	public List<FunctionInfo> getFunction(String name) {
		return functionMap.get(name.toLowerCase());
	}

	public List<String> getClass(String name) {
		return classMap.get(name.toLowerCase());
	}

	public List<String> getConstant(String name) {
		return constantMap.get(name);
	}

	public List<MethodInfo> getMethod(String name) {
		return methodMap.get(name.toLowerCase());
	}

	public List<MethodInfo> getStaticMethod(String name) {
		return staticMethodMap.get(name.toLowerCase());
	}

	public List<String> getClassNameList() {
		return Lists.newArrayList(classMap.keySet());
	}

	public List<String> getAllSubClassNameList(String name) {
		List<String> result = Lists.newArrayList();
		List<String> initList = subClassMap.get(name.toLowerCase());
		if (initList == null) {
			return result;
		}
		result.addAll(initList);
		for (int i = 0; i < result.size(); i++) {
			String cur = result.get(i);
			List<String> nextList = subClassMap.get(cur.toLowerCase());
			if (nextList == null) {
				continue;
			}
			for (String next : nextList) {
				if (result.contains(next)) {
					// pass
				} else {
					result.add(next);
				}
			}
		}
		return result;
	}

	public boolean isSuperClass(String superClassname, String classname) {
		List<String> subClassNameList = getAllSubClassNameList(superClassname);
		return subClassNameList != null && subClassNameList.contains(classname.toLowerCase());
	}
}


text:
<?php

namespace spec\Sylius\Component\Core\StateResolver;

use SM\Factory\FactoryInterface;
use SM\StateMachine\StateMachineInterface;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\OrderPaymentStates;
use Sylius\Component\Core\OrderShippingStates;
use Sylius\Component\Core\StateResolver\OrderStateResolver;
use Sylius\Component\Order\OrderTransitions;
use Sylius\Component\Order\StateResolver\StateResolverInterface;

/**
 * @author Jan Góralski <jan.goralski@lakion.com>
 */
final class OrderStateResolverSpec extends ObjectBehavior
{
    function let(FactoryInterface $stateMachineFactory)
    {
        $this->beConstructedWith($stateMachineFactory);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType(OrderStateResolver::class);
    }

    function it_implements_a_state_resolver_interface()
    {
        $this->shouldImplement(StateResolverInterface::class);
    }

    function it_marks_an_order_as_fulfilled_when_its_paid_for_and_has_been_shipped(
        FactoryInterface $stateMachineFactory,
        OrderInterface $order,
        StateMachineInterface $stateMachine
    ) {
        $order->getShippingState()->willReturn(OrderShippingStates::STATE_SHIPPED);
        $order->getPaymentState()->willReturn(OrderPaymentStates::STATE_PAID);

        $stateMachineFactory->get($order, OrderTransitions::GRAPH)->willReturn($stateMachine);

        $stateMachine->can(OrderTransitions::TRANSITION_FULFILL)->willReturn(true);
        $stateMachine->apply(OrderTransitions::TRANSITION_FULFILL)->shouldBeCalled();

        $this->resolve($order);
    }

    function it_does_not_mark_an_order_as_fulfilled_when_it_has_been_paid_but_not_shipped(
        FactoryInterface $stateMachineFactory,
        OrderInterface $order,
        StateMachineInterface $stateMachine
    ) {
        $order->getShippingState()->willReturn(Argument::not(OrderShippingStates::STATE_SHIPPED));
        $order->getPaymentState()->willReturn(OrderPaymentStates::STATE_PAID);

        $stateMachineFactory->get($order, OrderTransitions::GRAPH)->willReturn($stateMachine);

        $stateMachine->can(OrderTransitions::TRANSITION_FULFILL)->willReturn(true);
        $stateMachine->apply(OrderTransitions::TRANSITION_FULFILL)->shouldNotBeCalled();

        $this->resolve($order);
    }

    function it_does_not_mark_an_order_as_fulfilled_when_it_has_been_shipped_but_not_paid(
        FactoryInterface $stateMachineFactory,
        OrderInterface $order,
        StateMachineInterface $stateMachine
    ) {
        $order->getShippingState()->willReturn(OrderShippingStates::STATE_SHIPPED);
        $order->getPaymentState()->willReturn(Argument::not(OrderPaymentStates::STATE_PAID));

        $stateMachineFactory->get($order, OrderTransitions::GRAPH)->willReturn($stateMachine);

        $stateMachine->can(OrderTransitions::TRANSITION_FULFILL)->willReturn(true);
        $stateMachine->apply(OrderTransitions::TRANSITION_FULFILL)->shouldNotBeCalled();

        $this->resolve($order);
    }
}


text:
if defined?(ChefSpec)
  ChefSpec.define_matcher :ohai_hint
  ChefSpec.define_matcher :ohai_plugin

  def create_ohai_hint(resource)
    ChefSpec::Matchers::ResourceMatcher.new(:ohai_hint, :create, resource)
  end

  def delete_ohai_hint(resource)
    ChefSpec::Matchers::ResourceMatcher.new(:ohai_hint, :delete, resource)
  end

  def create_ohai_plugin(resource)
    ChefSpec::Matchers::ResourceMatcher.new(:ohai_plugin, :create, resource)
  end

  def delete_ohai_plugin(resource)
    ChefSpec::Matchers::ResourceMatcher.new(:ohai_plugin, :delete, resource)
  end
end


text:
package repository

import (
	"context"

	"code.gitea.io/gitea/models/db"
	"code.gitea.io/gitea/models/perm"
	access_model "code.gitea.io/gitea/models/perm/access"
	repo_model "code.gitea.io/gitea/models/repo"
	user_model "code.gitea.io/gitea/models/user"
)

func addCollaborator(ctx context.Context, repo *repo_model.Repository, u *user_model.User) error {
	collaboration := &repo_model.Collaboration{
		RepoID: repo.ID,
		UserID: u.ID,
	}

	has, err := db.GetByBean(ctx, collaboration)
	if err != nil {
		return err
	} else if has {
		return nil
	}
	collaboration.Mode = perm.AccessModeWrite

	if err = db.Insert(ctx, collaboration); err != nil {
		return err
	}

	return access_model.RecalculateUserAccess(ctx, repo, u.ID)
}

// AddCollaborator adds new collaboration to a repository with default access mode.
func AddCollaborator(repo *repo_model.Repository, u *user_model.User) error {
	return db.WithTx(db.DefaultContext, func(ctx context.Context) error {
		return addCollaborator(ctx, repo, u)
	})
}


text:
package org.collectionspace.services.loanin;

import org.collectionspace.services.client.LoaninClient;
import org.collectionspace.services.common.NuxeoBasedResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path(LoaninClient.SERVICE_PATH)
@Consumes("application/xml")
@Produces("application/xml")
public class LoaninResource extends NuxeoBasedResource {

    final Logger logger = LoggerFactory.getLogger(LoaninResource.class);

    @Override
    protected String getVersionString() {
    	final String lastChangeRevision = "$LastChangedRevision$";
    	return lastChangeRevision;
    }

    @Override
    public String getServiceName() {
        return LoaninClient.SERVICE_NAME;
    }

    @Override
    public Class<LoansinCommon> getCommonPartClass() {
    	return LoansinCommon.class;
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">

<erlref>

    <copyright>
      <year>1996</year><year>2020</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

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

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

    </legalnotice>

    <title>epp</title>
    <prepared>Kenneth Lundin</prepared>
    <responsible>Kenneth Lundin</responsible>
    <docno>1</docno>
    <approved>Kenneth Lundin</approved>
    <checked></checked>
    <date>1997-01-31</date>
    <rev>B</rev>
    <file>epp.xml</file>

  <module since="">epp</module>
  <modulesummary>An Erlang code preprocessor.</modulesummary>
  <description>

The Erlang code preprocessor includes functions that are used by the
      <seeerl marker="compiler:compile"><c>compile</c></seeerl>
      module to preprocess macros and include files before
      the parsing takes place.

The Erlang source file <marker
      id="encoding"/>encoding is selected by a
      comment in one of the first two lines of the source file. The
      first string matching the regular expression
      <c>coding\s*[:=]\s*([-a-zA-Z0-9])+</c> selects the encoding. If
      the matching string is not a valid encoding, it is ignored. The
      valid encodings are <c>Latin-1</c> and <c>UTF-8</c>, where the
      case of the characters can be chosen freely.

Examples:

%% coding: utf-8

%% For this file we have chosen encoding = Latin-1

%% -*- coding: latin-1 -*-

  </description>

  <datatypes>
    <datatype>
      <name name="macros"></name>
    </datatype>
    <datatype>
      <name name="epp_handle"></name>
      <desc>
Handle to the <c>epp</c> server.
</desc>
    </datatype>
    <datatype>
      <name name="source_encoding"></name>
    </datatype>
    <datatype>
      <name name="warning_info"></name>
    </datatype>
  </datatypes>

  <funcs>
    <func>
      <name name="close" arity="1" since=""/>
      <fsummary>Close the preprocessing of the file associated with <c>Epp</c>.
      </fsummary>
      <desc>

Closes the preprocessing of a file.

      </desc>
    </func>

    <func>
      <name name="default_encoding" arity="0" since="OTP R16B"/>
      <fsummary>Return the default encoding of Erlang source files.</fsummary>
      <desc>

Returns the default encoding of Erlang source files.

      </desc>
    </func>

    <func>
      <name name="encoding_to_string" arity="1" since="OTP R16B"/>
      <fsummary>Return a string representation of an encoding.</fsummary>
      <desc>

Returns a string representation of an encoding. The string
          is recognized by
          <seemfa marker="#read_encoding/1"><c>read_encoding/1,2</c></seemfa>,
          <seemfa marker="#read_encoding_from_binary/1">
          <c>read_encoding_from_binary/1,2</c></seemfa>, and
          <seemfa marker="#set_encoding/1"><c>set_encoding/1,2</c></seemfa>
          as a valid encoding.

      </desc>
    </func>

    <func>
      <name name="format_error" arity="1" since="OTP R14B03"/>
      <fsummary>Format an error descriptor.</fsummary>
      <desc>

Takes an <c><anno>ErrorDescriptor</anno></c> and returns
          a string that
          describes the error or warning. This function is usually
          called implicitly when processing an <c>ErrorInfo</c>
          structure (see section
          <seeerl marker="#errorinfo">Error Information</seeerl>).

      </desc>
    </func>

    <func>
      <name name="open" arity="1" since="OTP 17.0"/>
      <fsummary>Open a file for preprocessing.</fsummary>
      <desc>

Opens a file for preprocessing.

If you want to change the file name of the implicit -file()
          attributes inserted during preprocessing, you can do with
          <c>{source_name, <anno>SourceName</anno>}</c>. If unset it will
          default to the name of the opened file.

If <c>extra</c> is specified in
          <c><anno>Options</anno></c>, the return value is
          <c>{ok, <anno>Epp</anno>, <anno>Extra</anno>}</c> instead
          of <c>{ok, <anno>Epp</anno>}</c>.

The option <c>location</c> is forwarded
         to the Erlang token scanner, see
         <seemfa marker="erl_scan#tokens/3"><c>erl_scan:tokens/3,4</c></seemfa>.

      </desc>
    </func>

    <func>
      <name name="open" arity="2" since=""/>
      <fsummary>Open a file for preprocessing.</fsummary>
      <desc>

Equivalent to
          <c>epp:open([{name, FileName}, {includes, IncludePath}])</c>.

      </desc>
    </func>

    <func>
      <name name="open" arity="3" since=""/>
      <fsummary>Open a file for preprocessing.</fsummary>
      <desc>

Equivalent to <c>epp:open([{name, FileName}, {includes, IncludePath},
          {macros, PredefMacros}])</c>.

      </desc>
    </func>

    <func>
      <name name="parse_erl_form" arity="1" since=""/>
      <fsummary>Return the next Erlang form from the opened Erlang source file.
      </fsummary>
      <desc>

Returns the next Erlang form from the opened Erlang source file.
        Tuple <c>{eof, <anno>Location</anno>}</c> is returned at the end
	  of the file. The first form corresponds to an implicit attribute
          <c>-file(File,1).</c>, where <c>File</c> is the file name.

      </desc>
    </func>

    <func>
      <name name="parse_file" arity="2" since="OTP 17.0"/>
      <fsummary>Preprocess and parse an Erlang source file.</fsummary>
      <desc>

Preprocesses and parses an Erlang source file.
          Notice that tuple <c>{eof, <anno>Location</anno>}</c> returned at the
          end of the file is included as a "form".

If you want to change the file name of the implicit -file()
          attributes inserted during preprocessing, you can do with
          <c>{source_name, <anno>SourceName</anno>}</c>. If unset it will
          default to the name of the opened file.

If <c>extra</c> is specified in
         <c><anno>Options</anno></c>, the return value is
         <c>{ok, [<anno>Form</anno>], <anno>Extra</anno>}</c> instead
         of <c>{ok, [<anno>Form</anno>]}</c>.

The option <c>location</c> is forwarded
         to the Erlang token scanner, see
         <seemfa marker="erl_scan#tokens/3"><c>erl_scan:tokens/3,4</c></seemfa>.

      </desc>
    </func>

    <func>
      <name name="parse_file" arity="3" since=""/>
      <fsummary>Preprocess and parse an Erlang source file.</fsummary>
      <desc>

Equivalent to <c>epp:parse_file(FileName, [{includes, IncludePath},
          {macros, PredefMacros}])</c>.

      </desc>
    </func>

    <func>
      <name name="read_encoding" arity="1" since="OTP R16B"/>
      <name name="read_encoding" arity="2" since="OTP R16B"/>
      <fsummary>Read the encoding from a file.</fsummary>
      <desc>

Read the <seeerl marker="#encoding">encoding</seeerl> from
          a file. Returns the read encoding, or <c>none</c> if no
          valid encoding is found.

Option <c>in_comment_only</c> is <c>true</c> by
          default, which is correct for Erlang source files. If set to
          <c>false</c>, the encoding string does not necessarily have to
          occur in a comment.

      </desc>
    </func>

    <func>
      <name name="read_encoding_from_binary" arity="1" since="OTP R16B"/>
      <name name="read_encoding_from_binary" arity="2" since="OTP R16B"/>
      <fsummary>Read the encoding from a binary.</fsummary>
      <desc>

Read the <seeerl marker="#encoding">encoding</seeerl> from
          a binary. Returns the read encoding, or <c>none</c> if no
          valid encoding is found.

Option <c>in_comment_only</c> is <c>true</c> by
          default, which is correct for Erlang source files. If set to
          <c>false</c>, the encoding string does not necessarily have to
          occur in a comment.

      </desc>
    </func>

    <func>
      <name name="scan_erl_form" arity="1" since="OTP R13B03"/>
      <fsummary>Return the raw tokens of the next Erlang form from the opened
      Erlang source file.</fsummary>
      <desc>

Returns the raw tokens of the next Erlang form from the opened
        Erlang source file. A tuple <c>{eof, Line}</c> is
        returned at the end of the file. The first form corresponds to an
        implicit attribute <c>-file(File,1).</c>, where <c>File</c> is the
        file name.

      </desc>
    </func>

    <func>
      <name name="scan_file" arity="2" since="OTP 24.0"/>
      <fsummary>Preprocess an Erlang source file, returning raw tokens.</fsummary>
      <desc>

Preprocesses an Erlang source file returning a list of the lists
        of raw tokens of each form.
        Notice that the tuple <c>{eof, Line}</c> returned at the
        end of the file is included as a "form", and any failures to scan a
        form are included in the list as tuples <c>{error,
        <anno>ErrorInfo</anno>}</c>.

      </desc>
    </func>

    <func>
      <name name="set_encoding" arity="1" since="OTP R16B"/>
      <fsummary>Read and set the encoding of an I/O device.</fsummary>
      <desc>

Reads the <seeerl marker="#encoding">encoding</seeerl> from
          an I/O device and sets the encoding of the device
          accordingly. The position of the I/O device referenced by
          <c><anno>File</anno></c> is not affected. If no valid
          encoding can be read from the I/O device, the encoding of the
          I/O device is set to the default encoding.

Returns the read encoding, or <c>none</c> if no valid
          encoding is found.

      </desc>
    </func>

    <func>
      <name name="set_encoding" arity="2" since="OTP 17.0"/>
      <fsummary>Read and set the encoding of an I/O device.</fsummary>
      <desc>

Reads the <seeerl marker="#encoding">encoding</seeerl> from
          an I/O device and sets the encoding of the device
          accordingly. The position of the I/O device referenced by
          <c><anno>File</anno></c> is not affected. If no valid
          encoding can be read from the I/O device, the encoding of the
          I/O device is set to the
          <seeerl marker="#encoding">encoding</seeerl> specified by
          <c><anno>Default</anno></c>.

Returns the read encoding, or <c>none</c> if no valid
          encoding is found.

      </desc>
    </func>
  </funcs>

    <title>Error Information</title>
    <marker id="errorinfo"/>

<c>ErrorInfo</c> is the standard <c>ErrorInfo</c> structure that is
      returned from all I/O modules. The format is as follows:

{ErrorLine, Module, ErrorDescriptor}

A string describing the error is obtained with the following call:

Module:format_error(ErrorDescriptor)

    <title>See Also</title>

<seeerl marker="erl_parse"><c>erl_parse(3)</c></seeerl>

</erlref>


text:
extern "Java"
{
  namespace java
  {
    namespace awt
    {
      namespace image
      {
          class DataBuffer;
          class SampleModel;
      }
    }
  }
}

class java::awt::image::SampleModel : public ::java::lang::Object
{

public:
  SampleModel(jint, jint, jint, jint);
  virtual jint getWidth();
  virtual jint getHeight();
  virtual jint getNumBands();
  virtual jint getNumDataElements() = 0;
  virtual jint getDataType();
  virtual jint getTransferType();
  virtual JArray< jint > * getPixel(jint, jint, JArray< jint > *, ::java::awt::image::DataBuffer *);
  virtual ::java::lang::Object * getDataElements(jint, jint, ::java::lang::Object *, ::java::awt::image::DataBuffer *) = 0;
  virtual ::java::lang::Object * getDataElements(jint, jint, jint, jint, ::java::lang::Object *, ::java::awt::image::DataBuffer *);
  virtual void setDataElements(jint, jint, ::java::lang::Object *, ::java::awt::image::DataBuffer *) = 0;
  virtual void setDataElements(jint, jint, jint, jint, ::java::lang::Object *, ::java::awt::image::DataBuffer *);
  virtual JArray< jfloat > * getPixel(jint, jint, JArray< jfloat > *, ::java::awt::image::DataBuffer *);
  virtual JArray< jdouble > * getPixel(jint, jint, JArray< jdouble > *, ::java::awt::image::DataBuffer *);
  virtual JArray< jint > * getPixels(jint, jint, jint, jint, JArray< jint > *, ::java::awt::image::DataBuffer *);
  virtual JArray< jfloat > * getPixels(jint, jint, jint, jint, JArray< jfloat > *, ::java::awt::image::DataBuffer *);
  virtual JArray< jdouble > * getPixels(jint, jint, jint, jint, JArray< jdouble > *, ::java::awt::image::DataBuffer *);
  virtual jint getSample(jint, jint, jint, ::java::awt::image::DataBuffer *) = 0;
  virtual jfloat getSampleFloat(jint, jint, jint, ::java::awt::image::DataBuffer *);
  virtual jdouble getSampleDouble(jint, jint, jint, ::java::awt::image::DataBuffer *);
  virtual JArray< jint > * getSamples(jint, jint, jint, jint, jint, JArray< jint > *, ::java::awt::image::DataBuffer *);
  virtual JArray< jfloat > * getSamples(jint, jint, jint, jint, jint, JArray< jfloat > *, ::java::awt::image::DataBuffer *);
  virtual JArray< jdouble > * getSamples(jint, jint, jint, jint, jint, JArray< jdouble > *, ::java::awt::image::DataBuffer *);
  virtual void setPixel(jint, jint, JArray< jint > *, ::java::awt::image::DataBuffer *);
  virtual void setPixel(jint, jint, JArray< jfloat > *, ::java::awt::image::DataBuffer *);
  virtual void setPixel(jint, jint, JArray< jdouble > *, ::java::awt::image::DataBuffer *);
  virtual void setPixels(jint, jint, jint, jint, JArray< jint > *, ::java::awt::image::DataBuffer *);
  virtual void setPixels(jint, jint, jint, jint, JArray< jfloat > *, ::java::awt::image::DataBuffer *);
  virtual void setPixels(jint, jint, jint, jint, JArray< jdouble > *, ::java::awt::image::DataBuffer *);
  virtual void setSample(jint, jint, jint, jint, ::java::awt::image::DataBuffer *) = 0;
  virtual void setSample(jint, jint, jint, jfloat, ::java::awt::image::DataBuffer *);
  virtual void setSample(jint, jint, jint, jdouble, ::java::awt::image::DataBuffer *);
  virtual void setSamples(jint, jint, jint, jint, jint, JArray< jint > *, ::java::awt::image::DataBuffer *);
  virtual void setSamples(jint, jint, jint, jint, jint, JArray< jfloat > *, ::java::awt::image::DataBuffer *);
  virtual void setSamples(jint, jint, jint, jint, jint, JArray< jdouble > *, ::java::awt::image::DataBuffer *);
  virtual ::java::awt::image::SampleModel * createCompatibleSampleModel(jint, jint) = 0;
  virtual ::java::awt::image::SampleModel * createSubsetSampleModel(JArray< jint > *) = 0;
  virtual ::java::awt::image::DataBuffer * createDataBuffer() = 0;
  virtual JArray< jint > * getSampleSize() = 0;
  virtual jint getSampleSize(jint) = 0;
public: // actually protected
  jint __attribute__((aligned(__alignof__( ::java::lang::Object)))) width;
  jint height;
  jint numBands;
  jint dataType;
public:
  static ::java::lang::Class class$;
};

#endif // __java_awt_image_SampleModel__


text:
package uk.dangrew.nuts.graphics.selection.view;

import java.util.List;

import javafx.scene.control.ScrollPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import uk.dangrew.kode.javafx.style.JavaFxStyle;

public class UiFoodSelectionPane extends BorderPane implements SelectionPane {

   private final int columns;
   private final ScrollPane scrollPane;
   private final GridPane grid;

   public UiFoodSelectionPane() {
      this( 5, 10 );
   }//End Constructor

   public UiFoodSelectionPane( int columns, int rows ) {
      this.columns = columns;
      JavaFxStyle styling = new JavaFxStyle();

      this.grid = new GridPane();
      this.grid.setHgap( 5 );
      this.grid.setVgap( 5 );
      this.scrollPane = styling.scrollPaneToFitFor( grid );
      this.setCenter( scrollPane );

      styling.configureConstraintsForEvenColumns( grid, columns );
      styling.configureConstraintsForEvenRows( grid, rows );
   }//End Constructor

   @Override public void layoutTiles( List< UiFoodSelectionTile > tiles ){
      grid.getChildren().clear();
      grid.getRowConstraints().clear();

      int column = 0;
      int row = 0;

      for ( UiFoodSelectionTile tile : tiles ) {
         //there is a memory leak here by not clearing the map, but it will be minimal
         grid.add( tile, column, row );

         column++;
         if ( column == columns ) {
            row++;
            column = 0;
         }
      }
   }//End Method

   GridPane grid(){
      return grid;
   }//End Method

}//End Class


text:
package org.ndexbio.task;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.UUID;

import org.ndexbio.common.exporter.SIFNetworkExporter;
import org.ndexbio.common.models.dao.orientdb.NetworkDocDAO;
import org.ndexbio.model.exceptions.NdexException;
import org.ndexbio.model.object.Status;
import org.ndexbio.model.object.Task;
import org.ndexbio.model.object.network.Network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SIFExporterTask extends NdexTask {

	private static final String NETWORK_EXPORT_PATH = "/opt/ndex/exported-networks/";
	private static final String XGMML_FILE_EXTENSION = ".sif";

	private static final Logger logger = LoggerFactory
			.getLogger(SIFExporterTask.class);

	private Status taskStatus;

	public SIFExporterTask(Task itask) throws NdexException {
		super(itask);
	}

	@Override
	public Task call() throws Exception {
		try {
			this.exportNetwork();
			return this.getTask();
		} catch (InterruptedException e) {
			logger.info(this.getClass().getName() +" interupted");
			return null;
		}
	}

	private void exportNetwork() throws Exception{

			this.taskStatus = Status.PROCESSING;
			this.startTask();
			String exportFilename = this.resolveFilename(NETWORK_EXPORT_PATH, XGMML_FILE_EXTENSION);

			Network network = null;
			try (NetworkDocDAO dao = new NetworkDocDAO()) {
				network = dao.getNetworkById(UUID.fromString(getTask().getResource()));

			}

			if ( network == null) throw new NdexException("Failed to get network from db.");

			try (FileOutputStream out = new FileOutputStream (exportFilename)) {

				OutputStreamWriter writer = new OutputStreamWriter(out);
				SIFNetworkExporter exporter = new SIFNetworkExporter (network);
				exporter.exportNetwork( writer );
				this.taskStatus = Status.COMPLETED;
				this.updateTaskStatus(this.taskStatus);
				writer.close();
			}
	}

	private String resolveFilename(String path, String extension) {
		// create the directory if not exists
		if (! new File(path).exists()) {
			new File(path).mkdir();
		}

		StringBuilder sb = new StringBuilder(path);
		sb.append(File.separator);
		sb.append(this.getTask().getExternalId());
		sb.append(extension);
		return sb.toString();
	}

}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Binky
{

	public interface IUpdateValue<TKey, TValue>
	{
		Task<TValue> Get(TKey key, CancellationToken cancellationToken);
	}
}


text:
layout: docs
title:  "Getting Started"
section: "guides"
---

# Getting Started
Before you can get started with **Effekt** you need to set up your
environment and add **Effekt** as a dependency to your `build.sbt` file:

```
resolvers += Opts.resolver.sonatypeSnapshots

libraryDependencies += "de.b-studios" %% "effekt" % "0.4-SNAPSHOT"
```

Alternatively, to play around with **Effekt** in your browser, you can
also use Scastie. We prepared two different Scasties for you

- [Scala 2.12](https://scastie.scala-lang.org/o2IcM13UTt60YKlcyNtv7g)
- [Dotty](https://scastie.scala-lang.org/Ilonelw2QgGDXh1pg4yXkg) -- Here
  you can also play around with implicit function types. The interface
  is slightly different at the moment.

## Define your first effect
First we import all the necessary types and functions.
Then, to define our first effect, we specify the *effect signature*.

```scala mdoc:silent
import effekt._

// The effect signature
trait Amb {
  def flip(): Control[Boolean]
}
```

Effect signatures in **Effekt** are ordinary Scala traits that simply
declare the effect operations.

For programming with effects the most important type is `Control`.
For now we only have to know that all
*effect operations* like `flip` have to be marked as returning
something in `Control`.

## Using the `Amb` effect

To actually use the flip effect we need to get our hands on a
capability (that is, an instance of the effect signature `Amb`)
that entitles us to do so. Since we don't yet know where to
get such capabilities from, we just define a function asking for it.
We flip a coin once and then return 2 or 3 depending on the result.

```scala mdoc:silent
def prog(amb: Amb): Control[Int] = for {
  x <- amb.flip()
} yield if (x) 2 else 3
```

The result type `Control[Int]` tells us that the integer-result will be
contained in the `Control` *monad* which is **Effekt** specific.

## Defining Handlers
Let us now define our own handler for the `Amb` effect. A handler is
just an implementation of the effect interface. However, it also
needs to give the type to interpret the effect into (`List[R]`).
Note how we make sure that the result of the handled program is
a list by mapping `r => List(r)` over it before applying the handler.
This way we convert the result type from `R` into the semantic
domain `List[R]`.

```scala mdoc:silent
def ambList[R](prog: Amb => Control[R]): Control[List[R]] =
  new Handler[List[R]] with Amb {
    def flip() = use { resume => for {
      ts <- resume(true)
      fs <- resume(false)
    } yield ts ++ fs }
  } handle { amb => prog(amb) map { r => List(r) } }
```

Notice how we use the trait `Handler` which provides us with the
method `use`. To implement `flip` we get access to the continuation
`resume` (the remaining program after the flip effect, up to the handler).

The type of the expression passed to `use` is thus:
```
type Body = (Boolean => Control[List[R]]) => Control[List[R]
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                  the continuation
```
Note how both, the continuation and the result type, coincide
to be `Control[List[R]]`.

## Handling Effects
To handle an effect we use the apply method that is defined on an
instance of `handler`.

```scala mdoc:silent
val handled: Control[List[Int]] = ambList { amb => prog(amb) }
```

One way of thinking about algebraic effects and handlers is to think
as (resumable) exceptions. In our example, the effect operation `flip`
would correspond to `throw` and the handler `ambList` to a surrounding
`try { ... }`.

After all effects are handled, we can now run the effectful computation:

```scala mdoc
run { handled }
```


text:
import * as assert from 'assert'
import Ajv from 'ajv'
import * as J from './JsonSchema'
import * as C from 'fp-ts/lib/Const'
import { pipe } from 'fp-ts/lib/pipeable'

const ajv = new Ajv()

describe('JsonSchema', () => {
  it('literal', () => {
    const validate = ajv.compile(J.literal('a').compile())
    assert.strictEqual(validate('a'), true)
    assert.strictEqual(validate(1), false)
  })

  it('string', () => {
    const validate = ajv.compile(J.string.compile())
    assert.strictEqual(validate('a'), true)
    assert.strictEqual(validate(1), false)
  })

  it('boolean', () => {
    const validate = ajv.compile(J.boolean.compile())
    assert.strictEqual(validate(true), true)
    assert.strictEqual(validate(1), false)
  })

  it('UnknownArray', () => {
    const validate = ajv.compile(J.UnknownArray.compile())
    assert.strictEqual(validate([]), true)
    assert.strictEqual(validate([1, 2, 3]), true)
    assert.strictEqual(validate(1), false)
    assert.strictEqual(validate([1, undefined, 3]), true)
  })

  it('UnknownRecord', () => {
    const validate = ajv.compile(J.UnknownRecord.compile())
    assert.strictEqual(validate({}), true)
    assert.strictEqual(validate({ a: 'a', b: 1 }), true)
    assert.strictEqual(validate(1), false)
    assert.strictEqual(validate({ a: 'a', b: 1, c: undefined }), true)
  })

  it('struct', () => {
    const schema = J.struct({ a: J.string, b: J.number }).compile()
    const validate = ajv.compile(schema)
    assert.strictEqual(validate({ a: 'a', b: 1 }), true)
    assert.strictEqual(validate({ a: 'a' }), false)
    assert.strictEqual(validate({ a: 'a', b: 'b' }), false)
  })

  it('partial', () => {
    const validate = ajv.compile(J.partial({ a: J.string, b: J.number }).compile())
    assert.strictEqual(validate({ a: 'a', b: 1 }), true)
    assert.strictEqual(validate({ a: 'a' }), true)
    assert.strictEqual(validate({ a: 'a', b: undefined }), true)
    assert.strictEqual(validate({ a: 'a', b: 'b' }), false)
  })

  it('record', () => {
    const validate = ajv.compile(J.record(J.string).compile())
    assert.strictEqual(validate({ a: 'a', b: 'b' }), true)
    assert.strictEqual(validate({ a: 'a', b: 1 }), false)
  })

  it('array', () => {
    const validate = ajv.compile(J.array(J.number).compile())
    assert.strictEqual(validate([]), true)
    assert.strictEqual(validate([1, 2, 3]), true)
    assert.strictEqual(validate([1, 'a', 3]), false)
  })

  it('tuple', () => {
    const validate = ajv.compile(J.tuple(J.string, J.number).compile())
    assert.strictEqual(validate(['a', 1]), true)
    assert.strictEqual(validate(['a', 1, true]), false)
    assert.strictEqual(validate(['a']), false)
  })

  describe('intersection', () => {
    it('should handle non primitive values', () => {
      const validate = ajv.compile(pipe(J.struct({ a: J.string }), J.intersect(J.struct({ b: J.number }))).compile())
      assert.strictEqual(validate({ a: 'a', b: 1 }), true)
      assert.strictEqual(validate({ a: 'a' }), false)
    })

    interface IntBrand {
      readonly Int: unique symbol
    }
    type Int = number & IntBrand

    const Int: J.JsonSchema<Int> = {
      compile: () =>
        C.make({
          type: 'integer'
        })
    }
    const Positive: J.JsonSchema<number> = {
      compile: () =>
        C.make({
          type: 'number',
          minimum: 0
        })
    }

    it('should handle primitives', () => {
      const validate = ajv.compile(pipe(Int, J.intersect(Positive)).compile())
      assert.strictEqual(validate(1), true)
      assert.strictEqual(validate(-1), false)
    })
  })

  it('sum', () => {
    const sum = J.sum('_tag')

    const A = J.struct({ _tag: J.literal('A'), a: J.string })
    const B = J.struct({ _tag: J.literal('B'), b: J.number })
    const validate = ajv.compile(sum({ A, B }).compile())
    assert.strictEqual(validate({ _tag: 'A', a: 'a' }), true)
    assert.strictEqual(validate({ _tag: 'B', b: 1 }), true)
    assert.strictEqual(validate(undefined), false)
    assert.strictEqual(validate({}), false)
  })

  it('union', () => {
    const validate = ajv.compile(J.union(J.string, J.number).compile())
    assert.strictEqual(validate('a'), true)
    assert.strictEqual(validate(1), true)
    assert.strictEqual(validate(true), false)
  })

  describe('lazy', () => {
    it('should support recursive json schemas', () => {
      interface A {
        readonly a: number
        readonly b?: A
      }

      const schema: J.JsonSchema<A> = J.lazy('A', () =>
        pipe(J.struct({ a: J.number }), J.intersect(J.partial({ b: schema })))
      )

      const jsonSchema = schema.compile()
      const validate = ajv.compile(jsonSchema)
      assert.strictEqual(validate({}), false)
      assert.strictEqual(validate({ a: 1 }), true)
      assert.strictEqual(validate({ a: 1, b: null }), false)
      assert.strictEqual(validate({ a: 1, b: { a: 2 } }), true)
    })

    it('should support mutually recursive json schemas', () => {
      interface A {
        readonly b?: B
      }
      interface B {
        readonly a?: A
      }
      const A: J.JsonSchema<A> = J.lazy('A', () => J.partial({ b: B }))
      const B: J.JsonSchema<B> = J.lazy('B', () => J.partial({ a: A }))
      const jsonSchema = A.compile()
      const validateA = ajv.compile(jsonSchema)
      assert.strictEqual(validateA({}), true)
      assert.strictEqual(validateA({ b: {} }), true)
      assert.strictEqual(validateA({ b: { a: {} } }), true)

      const validateB = ajv.compile(B.compile())
      assert.strictEqual(validateB({}), true)
      assert.strictEqual(validateB({ a: {} }), true)
      assert.strictEqual(validateB({ a: { b: {} } }), true)
    })
  })
})


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IQuotesPersistence.js.map


text:
import sys
import random

# Import custom modules
import file

# Definition for a public key
class PublicKey:
    def __init__(self, n, g):

        # 'n' is a product of the two primes chosen for the key
        self.n = n

        # 'g' is the public exponent used to encrypt messages
        self.g = g

# Definition for a private key
class PrivateKey:
    def __init__(self, n, phiN, u):

        # 'n' is a product of the two primes chosen for the key
        self.n = n

        # 'phiN' is the phi of the two primes chosen for the key
        self.phiN = phiN

        # 'u' is the modular inverse of n mod phi(n)
        self.u = u

# Generate a random number of 'n' bits from the system entropy function
def randomNumber(bits):
    return random.SystemRandom().getrandbits(bits)

# Perform an 'n' round Miller-Rabin primality test (default 40 rounds has fault rate of 2^-128)
def millerRabin(number, rounds=40):

    # Get 'm' and 'k' that satisfies 'number - 1 = 2^k * m' with whole numbers
    # Initalise 'k'
    k = 0

    # Initalise 'm'
    m = number - 1

    # When 'm' becomes odd the next iteration wont be whole
    while m % 2 == 0:

        # Iterate 'k'
        k += 1

        # Calculate 'm'
        m /= 2

    # Perform the specified number of rounds
    for index in xrange(rounds):

        # Perform a single round
        if not millerRabinRound(number, m, k):

            # The round failed, the number is a composite
            return False

        # The number passed the specified rounds of accuracy
        return True

# Perform a single Miller-Rabin round for the given values
# Returns true for a round pass
def millerRabinRound(number, m, k):

    # Generate a random 'a' where 1 < a < number - 1
    a = random.randrange(2, number - 1)

    # Calculate the value for 'x' where x = a^m mod number
    x = pow(a, m, number)

    # Check if 'x' is 1 or 'number' - 1 which indicates a probable prime
    if x == 1 or x == number - 1:

        # The number has passed the round
        return True

    # Loop the operation 'k' times until a round pass or a composite is found
    for index in xrange(k - 1):

        # Recalculate 'x'
        x = pow(x, 2, number)

        # Break loop if 'x' is 'number' - 1
        if x == number - 1:
            break

    # If the loop completes the number is composite
    else:

        # The number has failed the round
        return False

    #The number has passed the round
    return True

# Test if a number is a probable prime
def isProbablePrime(number):

    # Number is not prime if it is even
    if number % 2 == 0:
        return False

    # Perform a Miller-Rabin test with the default number of rounds
    if millerRabin(number):

        # The number passed the test
        return True

    else:

        # The number failed the test
        return False

# Generate a probable prime suitable for use in public key encryption
def generatePrime():

    # Loop until a suitable prime is found
    while True:

        # Generate a prime number of 512 bits
        possiblePrime = randomNumber(512)

        # Return the number if it is a probable prime
        if isProbablePrime(possiblePrime):
            return possiblePrime

# Calculate modular inverse (a^-1 mod c)
def modularInverse(a, c):

    # Set 'b' as 'c' for use in the algorithm
    b = c

    # Set initial Bezout Coefficients
    coefficientT = 0
    lastCoefficientT = 1
    coefficientS = 1
    lastCoefficientS = 0

    # Loop until a GCD is found
    gcdFound = False
    while not gcdFound:

        # Calculate the quotient for this round
        quotient = a // b

        # Calculate the remainder for this round
        a, b = b, a % b

        # Check if the GCD has been found
        if (b == 0):
            gcdFound = True

        # Calculate the coefficients for this round
        coefficientT, lastCoefficientT = lastCoefficientT - quotient * coefficientT, coefficientT
        coefficientS, lastCoefficientS = lastCoefficientS - quotient * coefficientS, coefficientS

    # Return the calculated inverse
    return lastCoefficientT % c

# Generate a Paillier private key and related public key
def generateKeyPair():

    # Get 2 Paillier suitable prime numbers
    firstPrime = generatePrime()
    secondPrime = generatePrime()

    # Ensure the primes are distinct
    if firstPrime == secondPrime:

        # Reattempt the generation
        return generateKeyPair()

    # Compute composite number 'n'
    n = firstPrime * secondPrime

    # Compute the phi of 'n'
    phiN = (firstPrime - 1) * (secondPrime - 1)

    # Compute 'g' for the public key
    g = n + 1

    # Compute the modular inverse of 'phiN' 'n', phiN^-1 mod n
    u = modularInverse(phiN, n)

    # Create the public key
    public = PublicKey(n, g)

    # Create the private key
    private = PrivateKey(n, phiN, u)

    # Return the key pair
    return public, private

# Encrypt plaintext using a Paillier public key
def encrypt(publicKey, plaintext):

    # Calculate n^2
    nSquared = publicKey.n ** 2

    # Generate a random 'r' where 1 < r < n - 1
    r = random.randrange(2, publicKey.n - 1)

    # Compute the cyphertext as cyphertext = (g^plaintext mod n^2) * (r^n mod n^2) mod n^2
    cyphertext = ( pow(publicKey.g, plaintext, nSquared) *
                   pow(r, publicKey.n, nSquared) % nSquared )

    # Return the encrypted cypher
    return cyphertext

# Decrypt Paillier cyphertext using a private key
def decrypt(privateKey, cyphertext):

    # Calculate n^2
    nSquared = privateKey.n ** 2

    # Compute the plaintext as plaintext = L(cyphertext^phiN mod n^2) * u mod n
    # Where L(x) = (x - 1) / n
    plaintext = ( (pow(cyphertext, privateKey.phiN, nSquared) - 1)
                   // privateKey.n * privateKey.u % privateKey.n )

    # Return the decrypted plaintext
    return plaintext

# Apply a homomorphic addition to two integers encrypted by the same key
def homomorphicAdd(publicKey, encryptedInteger1, encryptedInteger2):

    # Compute the addition as result = encryptedInteger1 * encryptedInteger2 mod n^2
    return encryptedInteger1 * encryptedInteger2 % (publicKey.n ** 2)

# Add the encrypted votes of a ballot
def addVotes(votes, publicKey):

    # Initalise results array
    results = []

    # Calculate the number of candidates
    candidateCount = len(votes[0])

    # Loop through each vote
    for index in xrange(len(votes)):

        # Check if this is the first vote
        if index == 0:

            # Simply add the values
            results = votes[index]

        else:

            # Loop through each value
            for valueIndex in xrange(candidateCount):

                # homomorphicly add this value to the result
                results[valueIndex] = homomorphicAdd(publicKey, results[valueIndex], votes[index][valueIndex])

    # Return the encrypted results
    return results


text:
location_script=/etc/profile.d/fix_XServer.sh
# Make sure only root can run our script
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

expert DISPLAY=:0

echo -e "#!/bin/bash \n xhost +local:" > $location_script
chmod +x $location_script


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__int_calloc_32.c
Label Definition File: CWE401_Memory_Leak.c.label.xml
Template File: sources-sinks-32.tmpl.c
*/
/*
 * @description
 * CWE: 401 Memory Leak
 * BadSource: calloc Allocate data using calloc()
 * GoodSource: Allocate data on the stack
 * Sinks:
 *    GoodSink: call free() on data
 *    BadSink : no deallocation of data
 * Flow Variant: 32 Data flow using two pointers to the same value within the same function
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifndef OMITBAD

void CWE401_Memory_Leak__int_calloc_32_bad()
{
    int * data;
    int * *dataPtr1 = &data;
    int * *dataPtr2 = &data;
    data = NULL;
    {
        int * data = *dataPtr1;
        /* POTENTIAL FLAW: Allocate memory on the heap */
        data = (int *)calloc(100, sizeof(int));
        /* Initialize and make use of data */
        data[0] = 5;
        printIntLine(data[0]);
        *dataPtr1 = data;
    }
    {
        int * data = *dataPtr2;
        /* POTENTIAL FLAW: No deallocation */
        ; /* empty statement needed for some flow variants */
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
    int * data;
    int * *dataPtr1 = &data;
    int * *dataPtr2 = &data;
    data = NULL;
    {
        int * data = *dataPtr1;
        /* FIX: Use memory allocated on the stack with ALLOCA */
        data = (int *)ALLOCA(100*sizeof(int));
        /* Initialize and make use of data */
        data[0] = 5;
        printIntLine(data[0]);
        *dataPtr1 = data;
    }
    {
        int * data = *dataPtr2;
        /* POTENTIAL FLAW: No deallocation */
        ; /* empty statement needed for some flow variants */
    }
}

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2G()
{
    int * data;
    int * *dataPtr1 = &data;
    int * *dataPtr2 = &data;
    data = NULL;
    {
        int * data = *dataPtr1;
        /* POTENTIAL FLAW: Allocate memory on the heap */
        data = (int *)calloc(100, sizeof(int));
        /* Initialize and make use of data */
        data[0] = 5;
        printIntLine(data[0]);
        *dataPtr1 = data;
    }
    {
        int * data = *dataPtr2;
        /* FIX: Deallocate memory */
        free(data);
    }
}

void CWE401_Memory_Leak__int_calloc_32_good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE401_Memory_Leak__int_calloc_32_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE401_Memory_Leak__int_calloc_32_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
"""Application base class for providing a list of data as output.
"""
import abc
import operator
import six

from . import display

@six.add_metaclass(abc.ABCMeta)
class Lister(display.DisplayCommandBase):
    """Command base class for providing a list of data as output.
    """

    @property
    def formatter_namespace(self):
        return 'cliff.formatter.list'

    @property
    def formatter_default(self):
        return 'table'

    @property
    def need_sort_by_cliff(self):
        """Whether sort procedure is performed by cliff itself.

        Should be overridden (return False) when there is a need to implement
        custom sorting procedure or data is already sorted."""
        return True

    @abc.abstractmethod
    def take_action(self, parsed_args):
        """Return a tuple containing the column names and an iterable
        containing the data to be listed.
        """

    def get_parser(self, prog_name):
        parser = super(Lister, self).get_parser(prog_name)
        group = self._formatter_group
        group.add_argument(
            '--sort-column',
            action='append',
            default=[],
            dest='sort_columns',
            metavar='SORT_COLUMN',
            help=("specify the column(s) to sort the data (columns specified "
                  "first have a priority, non-existing columns are ignored), "
                  "can be repeated")
        )
        return parser

    def produce_output(self, parsed_args, column_names, data):
        if parsed_args.sort_columns and self.need_sort_by_cliff:
            indexes = [column_names.index(c) for c in parsed_args.sort_columns
                       if c in column_names]
            if indexes:
                data = sorted(data, key=operator.itemgetter(*indexes))
        (columns_to_include, selector) = self._generate_columns_and_selector(
            parsed_args, column_names)
        if selector:
            # Generator expression to only return the parts of a row
            # of data that the user has expressed interest in
            # seeing. We have to convert the compress() output to a
            # list so the table formatter can ask for its length.
            data = (list(self._compress_iterable(row, selector))
                    for row in data)
        self.formatter.emit_list(columns_to_include,
                                 data,
                                 self.app.stdout,
                                 parsed_args,
                                 )
        return 0


text:
namespace _02.StudentsAndWorkers
{
    public class Student : Human
    {
        //Fields
        private int grade;

        //Constructors
        public Student(string inputFirstName, string inputLastName, int studentGrade) : base(inputFirstName, inputLastName)
        {
            this.Grade = studentGrade;
        }

        //Properties
        public int Grade
        {
            get { return this.grade; }
            private set { this.grade = value; }
        }

        //Methods
        public override string ToString()
        {
            return base.ToString() + " - Grade: " + Grade;
        }
    }
}


text:
package com.heliosmind.modulehandler;

import java.io.File;
import java.util.LinkedList;

public class MissingHandlerException extends Exception {
    private static final long serialVersionUID = 6634496329838454376L;

    private String missingExtension;
    private LinkedList<File> unloadedFiles;

    public MissingHandlerException(String missingExtension, File... unloadedFiles) {
	this.missingExtension = missingExtension;
	this.unloadedFiles = new LinkedList<File>();
	for (File unloadedModule : unloadedFiles)
	    this.unloadedFiles.add(unloadedModule);
    }

    /**
     * Returns the missingExtension.
     * @return the missingExtension
     */
    public String getMissingExtension() {
        return missingExtension;
    }

    /**
     * Sets the value of missingExtension to that of the parameter.
     * @param missingExtension the missingExtension to set
     */
    public void setMissingExtension(String missingExtension) {
        this.missingExtension = missingExtension;
    }

    /**
     * Returns the unloadedModules.
     * @return the unloadedModules
     */
    public LinkedList<File> getUnloadedFiles() {
        return unloadedFiles;
    }

    /**
     * Sets the value of unloadedModules to that of the parameter.
     * @param unloadedFiles the unloadedModules to set
     */
    public void setUnloadedFiles(LinkedList<File> unloadedFiles) {
        this.unloadedFiles = unloadedFiles;
    }

    public void registerUnloadedFile(File unloadedFile) {
	unloadedFiles.add(unloadedFile);
    }
}


text:
package net.sf.jxls.bean;

import java.util.ArrayList;
import java.util.List;

/**
 * Sample Department bean to demostrate main excel export features
 * author: Leonid Vysochyn
 */
public class Department {
    private String name;
    private Employee chief;
    private List staff = new ArrayList();

    public Department(String name) {
        this.name = name;
    }

    public Department(String name, Employee chief, List staff) {
        this.name = name;
        this.chief = chief;
        this.staff = staff;
    }

    public void addEmployee(Employee employee) {
        staff.add(employee);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Employee getChief() {
        return chief;
    }

    public void setChief(Employee chief) {
        this.chief = chief;
    }

    public List getStaff() {
        return staff;
    }

    public void setStaff(List staff) {
        this.staff = staff;
    }
}


text:
package org.onosproject.isis.io.util;

import org.onlab.packet.Ip4Address;

/**
 * Representation of ISIS Constants.
 */
public final class IsisConstants {
    public static final char PDU_LENGTH = 1497;
    public static final char CONFIG_LENGTH = 1498;
    public static final int MINIMUM_FRAME_LEN = 1521;
    public static final int METADATA_LEN = 7;
    public static final String SHOST = "127.0.0.1";
    public static final Ip4Address DEFAULTIP = Ip4Address.valueOf("0.0.0.0");
    public static final int SPORT = 3000;
    public static final byte L2 = 1;
    public static final int IRPDISCRIMINATOR = 131;
    public static final int ISISVERSION = 1;
    public static final int RESERVED = 0;
    public static final int PRIORITY = 0;
    public static final int MAXAREAADDRESS = 0;
    public static final int SYSTEMIDLENGTH = 0;
    public static final int PROTOCOLSUPPORTED = 204;
    public static final int LOCALCIRCUITIDFORP2P = 130;
    public static final int P2PHELLOHEADERLENGTH = 20;
    public static final int HELLOHEADERLENGTH = 27;
    public static final int CSNPDUHEADERLENGTH = 33;
    public static final int PSNPDUHEADERLENGTH = 17;
    public static final int PDULENGTHPOSITION = 17;
    public static final int COMMONHEADERLENGTH = 8;
    public static final int LSPMAXAGE = 1200;
    public static final int LSPREFRESH = 900;
    public static final int MAXSEQUENCENUMBER = Integer.MAX_VALUE;
    public static final int STARTLSSEQUENCENUM = 1;
    public static final int LENGTHPOSITION = 8;
    public static final int RESERVEDPOSITION = 6;
    public static final int CHECKSUMPOSITION = 24;
    public static final String REFRESHLSP = "refreshLsp";
    public static final String MAXAGELSP = "maxAgeLsp";
    public static final String DEFAULTLANID = "0000.0000.0000.00";
    public static final String PROCESSESID = "processId";
    public static final String INTERFACE = "interface";
    public static final String INTERFACEINDEX = "interfaceIndex";
    public static final String INTERMEDIATESYSTEMNAME = "intermediateSystemName";
    public static final String SYSTEMID = "systemId";
    public static final String RESERVEDPACKETCIRCUITTYPE = "reservedPacketCircuitType";
    public static final String CIRCUITID = "circuitId";
    public static final String NETWORKTYPE = "networkType";
    public static final String AREAADDRESS = "areaAddress";
    public static final String HOLDINGTIME = "holdingTime";
    public static final String HELLOINTERVAL = "helloInterval";
    public static final int PORT = 7000;
    public static final String LSPADDED = "LSP_ADDED";
    public static final String LSPREMOVED = "LSP_REMOVED";

    /**
     * Non parameterized constructor.
     */
    private IsisConstants() {
    }
}


text:
package net.sf.scrabble.core;

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

public class Scoring {
	public static int DEFAULT_CREDIT = 1;
	public static int DEFAULT_BONUS = 0;
	private Map<Integer, Integer> creditMap = new HashMap<Integer, Integer>();
	private Map<Coord, Integer> bonusMap = new HashMap<Coord, Integer>();
	private int bonusForUsingAll;

	public void addCredit(int value, int credit) {
		creditMap.put(Integer.valueOf(value), Integer.valueOf(credit));
	}

	public void addBonus(Coord coord, int bonus) {
		bonusMap.put(new Coord(coord), Integer.valueOf(bonus));
	}

	public int getScore(Word word, boolean usedAll, List<Cell> cellList) {
		int credit = word.plainCredit;
		if (usedAll) {
			credit += bonusForUsingAll;
		}
		int i = 0;
		for (Cell d : cellList) {
			if (d.letter == Alphabet.EMPTY_VALUE && d.bonus < 0) {
				credit += (-d.bonus - 1) * getCreditFor(word.valueArray[i]);
			}
            i++;
		}
		for (Cell d : cellList) {
			if (d.letter == Alphabet.EMPTY_VALUE && d.bonus > 0) {
				credit *= d.bonus;
			}
		}
		return credit;
	}

	public int getScore(Word word, int value, int bonus) {
		int wordCredit = word.plainCredit;
		if (bonus < 0) {
			wordCredit += (-bonus - 1) * getCreditFor(value);
		} else if (bonus > 0) {
			wordCredit *= bonus;
		}
		return wordCredit;
	}

	public int getBonusFor(Coord coord) {
		Integer boxed = bonusMap.get(coord);
		if (boxed == null) {
			return DEFAULT_BONUS;
		}
		return boxed.intValue();
	}

	public int getCreditFor(int value) {
		Integer boxed = creditMap.get(Integer.valueOf(value));
		if (boxed == null) {
			return DEFAULT_CREDIT;
		}
		return boxed.intValue();
	}

	public int getBonusForUsingAll() {
		return bonusForUsingAll;
	}

	public void setBonusForUsingAll(int bonusForUsingAll) {
		this.bonusForUsingAll = bonusForUsingAll;
	}
}


text:
import datetime
import random
import os
import logging

import unittest2
from dateutil.relativedelta import relativedelta

class KardboardTestCase(unittest2.TestCase):
    def setUp(self):
        if os.environ.get('KARDBOARD_SETTINGS'):
            os.environ['KARDBOARD_SETTINGS'] = ''

        from kardboard import default_settings
        default_settings.TEMPLATE_DEBUG = True
        from kardboard.views import app
        from flask.ext.mongoengine import MongoEngine
        from kardboard.util import now

        delattr(app, 'db')
        from mongoengine.connection import connect, disconnect
        disconnect()

        app.config.from_object('kardboard.default_settings')
        app.config['MONGODB_DB'] = 'kardboard_unittest'
        app.config['TESTING'] = True
        app.config['CELERY_ALWAYS_EAGER'] = True
        connect(app.config['MONGODB_DB'])
        app.db = MongoEngine(app)

        self.config = app.config
        self.app = app.test_client()
        self.flask_app = app

        self.used_keys = []
        self._setup_logging()
        self.now = now

        super(KardboardTestCase, self).setUp()

    def tearDown(self):
        if hasattr(self.config, 'TICKET_HELPER'):
            del self.config['TICKET_HELPER']
        self._flush_db()
        self.flask_app.logger.handlers = self._old_logging_handlers

    def _setup_logging(self):
        self._old_logging_handlers = self.flask_app.logger.handlers
        del self.flask_app.logger.handlers[:]
        new_handler = logging.StreamHandler()
        new_handler.setLevel(logging.CRITICAL)
        new_handler.setFormatter(logging.Formatter(self.flask_app.debug_log_format))
        self.flask_app.logger.addHandler(new_handler)

    def _flush_db(self):
        from mongoengine.connection import _get_db
        db = _get_db()
        #Truncate/wipe the test database
        names = [name for name in db.collection_names()
            if 'system.' not in name]
        [db.drop_collection(name) for name in names]

    def _get_target_url(self):
        raise NotImplementedError

    def _get_target_class(self):
        raise NotImplementedError

    def _make_one(self, *args, **kwargs):
        return self._get_target_class()(*args, **kwargs)

    def _get_card_class(self):
        from kardboard.models import Kard
        return Kard

    def _get_record_class(self):
        from kardboard.models import DailyRecord
        return DailyRecord

    def _get_person_class(self):
        from kardboard.models import Person
        return Person

    def _make_unique_key(self):
        key = random.randint(1, 10000)
        if key not in self.used_keys:
            self.used_keys.append(key)
            return key
        return self._make_unique_key()

    def _date(self, dtype, date=None, days=0):
        from kardboard.util import make_end_date, make_start_date
        from kardboard.util import now

        if not date:
            date = now()

        if dtype == 'start':
            date = make_start_date(date=date)
        elif dtype == 'end':
            date = make_end_date(date=date)

        date = date + relativedelta(days=days)
        return date

    def make_card(self, **kwargs):
        from kardboard.util import now
        key = self._make_unique_key()
        fields = {
            'key': "CMSAD-%s" % key,
            'title': "Theres always money in the banana stand",
            'backlog_date': now()
        }
        fields.update(**kwargs)
        k = self._get_card_class()(**fields)
        return k

    def delete_all_cards(self):
        self._get_card_class().objects.all().delete()

    def make_record(self, date, **kwargs):
        fields = {
            'date': date,
            'backlog': 3,
            'in_progress': 8,
            'done': 10,
            'completed': 1,
            'moving_cycle_time': 12,
            'moving_lead_time': 16,
            'moving_std_dev': 69,
            'moving_median_abs_dev': 30,
        }
        fields.update(**kwargs)
        r = self._get_record_class()(**fields)
        return r

    def make_person(self, **kwargs):
        key = self._make_unique_key()
        fields = {
            'name': 'cheisel-%s' % key,
        }
        fields.update(**kwargs)
        p = self._get_person_class()(**fields)
        return p

    def assertEqualDateTimes(self, expected, actual):
        expected = (expected.year, expected.month, expected.day, expected.hour, expected.minute)
        actual = (actual.year, actual.month, actual.day, actual.hour, actual.minute)
        self.assertEqual(expected, actual)

class DashboardTestCase(KardboardTestCase):
    def setUp(self):
        super(DashboardTestCase, self).setUp()

        from kardboard.models import Kard, DailyRecord
        self.Kard = Kard
        self.DailyRecord = DailyRecord
        self.year = datetime.datetime.now().year - 1
        self.month = 6
        self.day = 15

        self.team1 = 'Team 1'
        self.team2 = 'Team 2'

        self.backlogged_date = datetime.datetime(
            year=self.year, month=self.month, day=12)

        for i in xrange(0, 5):
            #board will have 5 cards in elabo, started, and done
            k = self.make_card(backlog_date=self.backlogged_date, team=self.team1)  # elabo
            k.save()

            k = self.make_card(start_date=datetime.datetime(
                year=self.year, month=self.month, day=12), team=self.team1)
            #k.save()

            k = self.make_card(
                start_date=datetime.datetime(year=self.year,
                    month=self.month, day=12),
                done_date=datetime.datetime(year=self.year,
                    month=self.month, day=19), team=self.team1)
            #k.save()

        for i in xrange(0, 3):
            #board will have 3 cards in elabo, started, and done
            k = self.make_card(backlog_date=self.backlogged_date, team=self.team2)  # backlogged
            #k.save()

            k = self.make_card(start_date=datetime.datetime(
                year=2011, month=6, day=12), team=self.team2)
            #k.save()

            k = self.make_card(
                start_date=datetime.datetime(year=2011, month=6, day=12),
                done_date=datetime.datetime(year=2011, month=6, day=19), team=self.team2)
            #k.save()

    def _set_up_records(self):
        from kardboard.util import make_start_date
        from kardboard.util import make_end_date

        start_date = datetime.datetime(2011, 1, 1)
        end_date = datetime.datetime(2011, 6, 30)

        start_date = make_start_date(date=start_date)
        end_date = make_end_date(date=end_date)

        current_date = start_date
        while current_date <= end_date:
            r = self.make_record(current_date)
            r.save()
            current_date = current_date + relativedelta(days=1)

class FormTests(KardboardTestCase):
    pass


text:
package com.ilivoo.ch5.ch7;

import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Arrays;

/**
 *1. Constructor Ìṩ¹ØÓÚÀàµÄµ¥¸ö¹¹Ôì·½·¨µÄÐÅÏ¢ÒÔ¼°¶ÔËüµÄ·ÃÎÊȨÏÞ¡£
 *2. Constructor ÔÊÐíÔÚ½«Êµ²ÎÓë´øÓеײ㹹Ôì·½·¨µÄÐÎ²ÎµÄ newInstance() Æ¥Åäʱ½øÐÐÀ©Õ¹×ª»»£¬µ«ÊÇÈç¹û·¢ÉúÊÕËõת»»£¬Ôò
 *   Å׳ö IllegalArgumentException¡£
 *3. Ê×ÏÈConstructorʵÏÖÁËAnnotatedElement, GenericDeclaration, MemberÈý¸ö½Ó¿Ú£¬ ÕâÈý¸ö½Ó¿ÚÒ²ÓÐ×Ô¼ºÏàÓ¦µÄÖ°Ôð£¬
 *   AnnotatedElement: Õâ¸ö½Ó¿ÚÖ÷ÒªÊÇΪÁË»ñµÃÕâ¸ö¹¹Ôì·½·¨ÉÏÃæµÄ×¢ÊÍ£¬ Class¡¢ Field¡¢ Constructor¡¢Method£¬
 *                     Package, AccessibleObjectʵÏÖÁËËü
 *   GenericDeclaration: Õâ¸ö½Ó¿ÚÖ÷ÒªÊÇ»ñµÃ²ÎÊýÀàÐͶø²Ù×÷µÄ£¬ Ö÷ÒªÊÇConstructorºÍMethod·½·¨ÊµÏÖÁËËü¡£
 *   Member£º ÕâÊÇÒ»¸ö»ù±¾½Ó¿ÚÖ÷ÒªÊÇField¡¢ Constructor¡¢MethodʵÏÖÁËËü£¬ Ìṩ»ù±¾µÄÈçÐÞÊηû£¬ ÉùÃ÷µÄClass¶ÔÏó£¬Ãû×Ö
 *           ÒѾÊÇ·ñÊDZàÒëÆ÷ÌṩµÄ¡£
 *3. ¶ÔÓÚÒ»¸ö¹¹Ôì·½·¨À´Ëµ£¬ ÎÒÃÇÓ¦¸Ã¿ÉÒÔ»ñµÃÄÄЩÐÅÏ¢£¬ ÒѾÄܽøÐÐÄÄЩ²Ù×÷ÄØ£¿ÎÒÃÇ¿ÉÒÔͨ¹ýÉÏÃæConstructorʵÏÖµÄÈý¸ö½Ó¿ÚÈëÊÖ
 *   ÌṩעÊÍÏà¹ØµÄ·½·¨£¬ Ìṩ»ñµÃ²ÎÊýÀàÐ͵ķ´·¨£¬ Ìṩ»ù±¾µÄÐÞÊηû£¬ ÉùÃ÷class¶ÔÏó£¬ Ãû×ֵȵȡ£
 *4. µ«ÊÇÎÒÃÇÒ²²»ÄÜÍü¼ÇËüµÄ×î»ù±¾µÄÔÔò£¬ ÄǾÍÊÇ´´½¨¶ÔÏó£¬ ²¢ÇÒËüÊǼ̳Ð×ÔAccessibleObject£¬ Ó¦¸ÃÓпɼûÐÔÉèÖÃÏà¹ØÎÊÌâ¡£
 */
public class ConstructorTest {
	public static void main(String[] args) throws Exception{
		ConstructorTest ct = new ConstructorTest();
		ct.testAnnotatedElement();//²âÊÔͨ¹ý½Ó¿ÚAnnotatedElementµÄ¼¸¸ö·½·¨
		ct.testAccessibleObject();
		ct.testGenericDeclaration();
		ct.testMember();
		ct.testEquals();
		ct.testGetExceptionTypes();
		ct.testGetGenericExceptionTypes();
		ct.testGetParameterAnnotations();
		ct.testGetParameterTypes();
		ct.testGetTypeParameters();
		ct.testIsVarArgs();
		ct.testToGenericString();
		ct.testNewInstance();
	}

	/**
	 *
	 */
	public void testAnnotatedElement() throws Exception{
		Class<Example> clazz = Example.class;
		Constructor<Example> cons = clazz.getConstructor(new Class[]{});

		Deprecated dep = cons.getAnnotation(Deprecated.class);
		System.out.println(dep);//@java.lang.Deprecated()

		Annotation[] anns = cons.getAnnotations();
		System.out.println(Arrays.toString(anns));//[@java.lang.Deprecated()]

		Annotation[] annsd = cons.getDeclaredAnnotations();
		System.out.println(Arrays.toString(annsd));//[@java.lang.Deprecated()]

		System.out.println(cons.isAnnotationPresent(Deprecated.class));//true
	}

	/**
	 * 1. annotationÒѾÔÚÉϸö·½·¨ÖÐÌåÏÖÁË£¬ ÕâÀïÖ»½²¾¿AccessibleObjectʣϵļ¸¸ö·½·¨¡£
	 */
	public void testAccessibleObject() throws Exception{
		Class<Example> clazz = Example.class;
		Constructor<Example> cons = clazz.getDeclaredConstructor(String.class);

		System.out.println(cons.isAccessible());//false

		cons.setAccessible(true);

		AccessibleObject.setAccessible(new Constructor<?>[]{cons}, true);
	}

	/**
	 *
	 */
	public void testGenericDeclaration() throws Exception{
		Class<Example> clazz = Example.class;
		Constructor<Example> cons = clazz.getConstructor(new Class[]{});

		TypeVariable<Constructor<Example>>[] tv = cons.getTypeParameters();
	}

	/**
	 *
	 */
	public void testMember() throws Exception{
		Class<Example> clazz = Example.class;
		Constructor<Example> cons = clazz.getConstructor(String.class, int.class);

		System.out.println(cons.getDeclaringClass());//class com.ilivoo.ch5.ch7.Example

		System.out.println(Modifier.toString(cons.getModifiers()));//public

		System.out.println(cons.getName());//com.ilivoo.ch5.ch7.Example

		System.out.println(cons.isSynthetic());//false
	}

	/**
    public boolean equals(Object obj) {
        if (obj != null && obj instanceof Constructor) { //ÅжÏÊÇ·ñÊÇConstructor
            Constructor<?> other = (Constructor<?>)obj;
            if (getDeclaringClass() == other.getDeclaringClass()) {  //ÊÇ·ñÊÇͬһ¸öÀàÉùÃ÷µÄ
                return equalParamTypes(parameterTypes, other.parameterTypes);//²ÎÊýÊÇ·ñÏàͬ
            }
        }
        return false;
    }
    //Ò²¾ÍÊÇÕâ¸öֻҪij¸öÀàµÄͬһ¸ö¹¹Ôì·½·¨µÄʵÀý¶¼ÊÇÕýÈ·µÄ¡£
    //Ò²¾ÍÊǹ¹ÔìÆ÷µÄ·½·¨Ç°ÃæÊÇͬһ¸ö¾ÍÊÇͬһ¸ö£¬ ¸úËüµÄ¿É¼ûÐÔûÓÐÈκιØϵµÄ¡£
	 */
	public void testEquals() throws Exception{
		Constructor<Example> cons = Example.class.getDeclaredConstructor(String.class);
		Constructor<Example> cons2 = Example.class.getDeclaredConstructor(String.class);
		System.out.println(cons.equals(cons2));//true

		cons.setAccessible(true);
		System.out.println(cons.equals(cons2));//true
	}

	/**
	 * 1. ·µ»ØÒ»×é±íʾÉùÃ÷ÒªÅ׳öµÄÒì³£ÀàÐ굀 Class ¶ÔÏó£¬ÕâЩÒì³£ÊÇÓÉ´Ë Constructor ¶ÔÏó±íʾµÄµ×²ã¹¹Ôì·½·¨Å׳öµÄ¡£Èç¹û
	 *    ¸Ã¹¹Ôì·½·¨ÉùÃ÷Æä throws ×Ó¾äÖÐûÓÐÈκÎÒì³££¬Ôò·µ»ØÒ»¸ö³¤¶ÈΪ 0 µÄÊý×é¡£
	 */
	public void testGetExceptionTypes() throws Exception{
		Constructor<Example> cons = Example.class.getConstructor(new Class[]{});
		Class<?>[] exces = cons.getExceptionTypes();
		System.out.println(Arrays.toString(exces));//[class java.lang.Exception]
	}

	/**
	 *
	 */
	public void testGetGenericExceptionTypes() throws Exception{
		Constructor<Example> cons = Example.class.getConstructor(new Class[]{});
		Type[] types = cons.getGenericExceptionTypes();
		System.out.println(Arrays.toString(types));//[class java.lang.Exception]
	}

	/**
	 *
	 */
	public void testGetParameterAnnotations() throws Exception{
		Constructor<Example> cons = Example.class.getConstructor(new Class[]{});
		Annotation[][] annss = cons.getParameterAnnotations();
		System.out.println(Arrays.deepToString(annss));//[]
	}

	/**
	 *
	 */
	public void testGetParameterTypes() throws Exception{
		Constructor<Example> cons = Example.class.getConstructor(new Class[]{});
		Class<?>[] tvs = cons.getParameterTypes();
		System.out.println(Arrays.toString(tvs));//[]
	}

	/**
	 *
	 */
	public void testGetTypeParameters() throws Exception{
		Constructor<Example> cons = Example.class.getConstructor(new Class[]{});
		TypeVariable<Constructor<Example>>[] tvs = cons.getTypeParameters();
		System.out.println(Arrays.toString(tvs));//[]
	}

	/**
	 * 1. Èç¹ûÉùÃ÷´Ë¹¹Ôì·½·¨¿ÉÒÔ´ø¿É±äÊýÁ¿µÄ²ÎÊý£¬Ôò·µ»Ø true£»·ñÔò·µ»Ø false¡£
	 */
	public void testIsVarArgs() throws Exception{
		Constructor<Example> cons = Example.class.getConstructor(new Class[]{});
		System.out.println(cons.isVarArgs());//false
	}

	/**
	 *
	 */
	public void testToGenericString() throws Exception{
		Constructor<Example> cons = Example.class.getConstructor(String.class, int.class);
		System.out.println(cons.toGenericString());//public com.ilivoo.ch5.ch7.Example(java.lang.String,int)
		System.out.println(cons.toString());//public com.ilivoo.ch5.ch7.Example(java.lang.String,int)
	}

	/**
	 *
	 */
	public void testNewInstance() throws Exception{
		Constructor<Example> cons = Example.class.getConstructor(new Class[]{});
		Example example = cons.newInstance();
		System.out.println(example);//null : 0

		Constructor<Example> cons2 = Example.class.getConstructor(String.class, int.class);
		Example example2 = cons2.newInstance("hello", 22);
		System.out.println(example2);//hello : 22

		Constructor<Example> cons3 = Example.class.getDeclaredConstructor(String.class);
		cons3.setAccessible(true);
		Example example3 = cons3.newInstance("world");
		System.out.println(example3);//world : 10
	}
}


text:
FOUNDATION_EXPORT double opencv2VersionNumber;
FOUNDATION_EXPORT const unsigned char opencv2VersionString[];


text:
There ara two default reporter for monitor data. They are ConsoleReporter and FileMetricsManagerReporter.

## Extend Report

The base interface for monitor data report is `Reporter`, with `start()` and `stop()` method.

All reporter implemented `Reporter`. You can implement these class as below.

![](https://img.alicdn.com/tfs/TB1sRFxigvD8KJjy0FlXXagBFXa-478-235.png)

- Reporter  Base interface
- ScheduledMetricsReporter  Scheduled reporter for Metrics
- ConsoleReporter  Console reporter for Metrics
- FileMetricsManagerReporter  File reporter for Metrics
- CustomReporter  Custom reporter
- TraceReporter  Reporter for trace

## Custom Report

Here is definition for `CustomReporter`. You should implement the `report` method to report your custom data.

```javascript
class MyReporter extends CustomReporter {

  metricsManager;
  endPointService;

  async report() {
  	// TODO execute report method where interval
  }
}
```

The `CustomReporter` class has two property, `metricManager` and `endPointService`. They contain almost every Pandora.js monitor ability.

The `metricsManager` interface is [Here](http://www.midwayjs.org/pandora/api-reference/metrics/interfaces/metricsmanager.html)

The `endPointService` has `getEndPoint()` method, you can get your need with different EndPoint.


text:
package org.apache.solr.util;

import com.carrotsearch.hppc.IntLongHashMap;
import com.carrotsearch.hppc.cursors.LongCursor;
import com.carrotsearch.hppc.procedures.IntLongProcedure;
import java.util.Arrays;
import java.util.function.LongConsumer;
import org.apache.lucene.util.ArrayUtil;

public class IntLongDynamicMap implements DynamicMap {
  private int maxSize;
  private IntLongHashMap hashMap;
  private long[] keyValues;
  private long emptyValue;
  private int threshold;

  /**
   * Create map with expected max value of key. Although the map will automatically do resizing to
   * be able to hold key {@code >=g expectedKeyMax}. But putting key much larger than {@code
   * expectedKeyMax} is discourage since it can leads to use LOT OF memory.
   */
  public IntLongDynamicMap(int expectedKeyMax, long emptyValue) {
    this.threshold = threshold(expectedKeyMax);
    this.maxSize = expectedKeyMax;
    this.emptyValue = emptyValue;
    if (useArrayBased(expectedKeyMax)) {
      upgradeToArray();
    } else {
      this.hashMap = new IntLongHashMap(mapExpectedElements(expectedKeyMax));
    }
  }

  private void upgradeToArray() {
    keyValues = new long[maxSize];
    if (emptyValue != 0) {
      Arrays.fill(keyValues, emptyValue);
    }
    if (hashMap != null) {
      hashMap.forEach((IntLongProcedure) (key, value) -> keyValues[key] = value);
      hashMap = null;
    }
  }

  private void growBuffer(int minSize) {
    assert keyValues != null;
    int size = keyValues.length;
    keyValues = ArrayUtil.grow(keyValues, minSize);
    if (emptyValue != 0) {
      for (int i = size; i < keyValues.length; i++) {
        keyValues[i] = emptyValue;
      }
    }
  }

  public void put(int key, long value) {
    if (keyValues != null) {
      if (key >= keyValues.length) {
        growBuffer(key + 1);
      }
      keyValues[key] = value;
    } else {
      this.maxSize = Math.max(key + 1, maxSize);
      this.hashMap.put(key, value);
      if (this.hashMap.size() >= threshold) {
        upgradeToArray();
      }
    }
  }

  public long get(int key) {
    if (keyValues != null) {
      if (key >= keyValues.length) {
        return emptyValue;
      }
      return keyValues[key];
    } else {
      return this.hashMap.getOrDefault(key, emptyValue);
    }
  }

  public void forEachValue(LongConsumer consumer) {
    if (keyValues != null) {
      for (long val : keyValues) {
        if (val != emptyValue) consumer.accept(val);
      }
    } else {
      for (LongCursor ord : hashMap.values()) {
        consumer.accept(ord.value);
      }
    }
  }

  public void remove(int key) {
    if (keyValues != null) {
      if (key < keyValues.length) keyValues[key] = emptyValue;
    } else {
      hashMap.remove(key);
    }
  }
}


text:
package org.springframework.data.neo4j.web.repo;

import java.util.UUID;

import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.web.domain.User;
import org.springframework.stereotype.Repository;

/**
 * @author Michal Bachman
 * @author Mark Angrish
 */
@Repository
public interface UserRepository extends Neo4jRepository<User, UUID> {

}


text:
package org.oxygine.GamePart3;

import org.oxygine.lib.OxygineActivity;

public class MainActivity extends OxygineActivity
{

}


text:
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>

#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
#elif TARGET_OS_OSX
#import <AppKit/AppKit.h>
#endif  // TARGET_OS_IOS || TARGET_OS_TV

NS_ASSUME_NONNULL_BEGIN

/** A notification sent out if the app is backgrounding. */
FOUNDATION_EXPORT NSString *const kGDTCORApplicationDidEnterBackgroundNotification;

/** A notification sent out if the app is foregrounding. */
FOUNDATION_EXPORT NSString *const kGDTCORApplicationWillEnterForegroundNotification;

/** A notification sent out if the app is terminating. */
FOUNDATION_EXPORT NSString *const kGDTCORApplicationWillTerminateNotification;

/** Compares flags with the WWAN reachability flag, if available, and returns YES if present.
 *
 * @param flags The set of reachability flags.
 * @return YES if the WWAN flag is set, NO otherwise.
 */
BOOL GDTCORReachabilityFlagsContainWWAN(SCNetworkReachabilityFlags flags);

/** A typedef identify background identifiers. */
typedef volatile NSUInteger GDTCORBackgroundIdentifier;

/** A background task's invalid sentinel value. */
FOUNDATION_EXPORT const GDTCORBackgroundIdentifier GDTCORBackgroundIdentifierInvalid;

#if TARGET_OS_IOS || TARGET_OS_TV
/** A protocol that wraps UIApplicationDelegate or NSObject protocol, depending on the platform. */
@protocol GDTCORApplicationDelegate <UIApplicationDelegate>
#elif TARGET_OS_OSX
@protocol GDTCORApplicationDelegate <NSApplicationDelegate>
#else
@protocol GDTCORApplicationDelegate <NSObject>
#endif  // TARGET_OS_IOS || TARGET_OS_TV

@end

/** A cross-platform application class. */
@interface GDTCORApplication : NSObject <GDTCORApplicationDelegate>

/** Flag to determine if the application is running in the background. */
@property(atomic, readonly) BOOL isRunningInBackground;

/** Creates and/or returns the shared application instance.
 *
 * @return The shared application instance.
 */
+ (nullable GDTCORApplication *)sharedApplication;

/** Creates a background task with the returned identifier if on a suitable platform.
 *
 * @name name The name of the task, useful for debugging which background tasks are running.
 * @param handler The handler block that is called if the background task expires.
 * @return An identifier for the background task, or GDTCORBackgroundIdentifierInvalid if one
 * couldn't be created.
 */
- (GDTCORBackgroundIdentifier)beginBackgroundTaskWithName:(NSString *)name
                                        expirationHandler:(void (^__nullable)(void))handler;

/** Ends the background task if the identifier is valid.
 *
 * @param bgID The background task to end.
 */
- (void)endBackgroundTask:(GDTCORBackgroundIdentifier)bgID;

@end

NS_ASSUME_NONNULL_END


text:
ATLAS Service Monitoring - SLS topology
=====

Topology processes a configurable subset of all SLS service XMLs from the directory specified in the
configuration file, and dumps the topology in a json file, and visualizes it as a PDF or PNG files.

Dependencies: Using BeautifulSoup library to parse XML files.
   ```
# pip install BeautifulSoup   # version 3.2.0
  ```
Using graphviz library to visualize directed graphs.
   ```
# pip install graphviz   # version 0.3.4
  ```

Configuration
-----
General configuration file: sls\_topology/settings/settings-sls-topology.cfg.

  Data.status is a configuration flag which determines whether the output files
  will or will not have UTC timestamp in the filename. If status=prod, the
  timestamp is left out from the output file name. Otherwise, the timestamp is
  part of the output file name.
  ```
[Data]
### status=prod: no timestamp in the output file name
### status=devel: timestamp is part of the output file name
status = prod
# status = devel

  ```

  Data.dir\_source\_xml specifies base directory with SLS service XML files
  (retrieved by the SLS Scraper).
  ```
[Data]
### dir_source_xml: directory with the service XML files
dir_source_xml = /data/jschovan/slsmon/download/sls/xml/

  ```

  Data.dir\_output specifies directory where the topology output files will
  be stored.
  ```
[Data]
### dir_output: directory to store output files: .json, .dot, .pdf, .png
dir_output = /data/jschovan/slsmon/topology/output/

  ```

  Data.groups specifies list of service groups to be plotted. A single service
  group is a relative directory path as a subdirectory in Data.dir\_source\_xml,
  e.g. ServicesForATLAS/ADC\_CS. Output topology file for a single group then
  contains parent <= child directed graph representing services and subservices
  listed the XML files of the single group directory, leaving out subdirectories
  of this single group (e.g. subgroup ServicesForATLAS/ADC\_CS/ATLAS-Frontier
  of group ServicesForATLAS/ADC\_CS will be displayed as a node in the ADC\_CS
  topology plots, and will be displayed as a more detailed graph in the
  ATLAS-Frontier topology plots).

  Too large service groups result in large PNG topology plots, that can be hard
  to read, please keep that in mind in specifying granularity of your
  service groups.
  ```
[Data]
### dir_output: directory to store output files: .json, .dot, .pdf, .png
dir_output = /data/jschovan/slsmon/topology/output/

  ```

  Document.tags specifies which XML tags will be translated into SLS topology
  json output. Tags can be structured. Parent tag and children tags are
  separated with a colon, children tags are separated with a pipe.
  ```
[Document]
### tags: list of XML tags to be parsed and stored in the output .json file
###    Parent tag is separated from children tags with a colon,
###        e.g. parent:child1
###    Children tags are separated with a pipe,
###        e.g. parent:child1|child2|child3
tags = id,fullname,shortname,type,searchable,visibleinsubservices,site,group,
 email,webpage,alarmpage,staticxmllocation,datasource:url|metaservice,
 availabilitythresholds:threshold,willbenotified,emailorsms,dependency,
 servicemanagers:servicemanager,staticxmllocation,subservices:subservice

  ```

How to run
-----
  ```
# cd sls\_topology/
# ls
__init__.py  README.md  settings  sls_topology.py
# export PYTHONPATH=$PWD:$PYTHONPATH
# python sls\_topology.py
  ```


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <ion-pane ng-controller="weatherCtrl as weather">

      <ion-header-bar class="bar-stable">

    <input type="search" placeholder="Search" ng-model="weather.searchQuery">

  <button class="button button-royal" ng-click="weather.search()">
    Search
  </button>

      </ion-header-bar>

      <ion-content>

{{weather.temp}}℉

{{weather.city}}

      </ion-content>
    </ion-pane>