text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import functools
import os
import unittest
from contextlib import contextmanager

import mock

from pants.build_graph.address import Address
from pants.build_graph.address_lookup_error import AddressLookupError
from pants.build_graph.build_file_aliases import BuildFileAliases, TargetMacro
from pants.build_graph.target import Target
from pants.init.engine_initializer import EngineInitializer
from pants.init.options_initializer import BuildConfigInitializer
from pants.init.target_roots_calculator import TargetRootsCalculator
from pants.option.options_bootstrapper import OptionsBootstrapper
from pants.subsystem.subsystem import Subsystem
from pants.util.contextutil import temporary_dir
from pants_test.engine.util import init_native

# Macro that adds the specified tag.
def macro(target_cls, tag, parse_context, tags=None, **kwargs):
  tags = tags or set()
  tags.add(tag)
  parse_context.create_object(target_cls, tags=tags, **kwargs)

class GraphTestBase(unittest.TestCase):

  _native = init_native()

  def _make_setup_args(self, specs):
    options = mock.Mock(target_specs=specs)
    options.for_scope.return_value = mock.Mock(diffspec=None, changes_since=None)
    options.for_global_scope.return_value = mock.Mock(owner_of=None)
    return options

  def _default_build_config(self, build_file_aliases=None):
    # TODO: Get default BuildFileAliases by extending BaseTest post
    #   https://github.com/pantsbuild/pants/issues/4401
    build_config = BuildConfigInitializer.get(OptionsBootstrapper())
    if build_file_aliases:
      build_config.register_aliases(build_file_aliases)
    return build_config

  @contextmanager
  def graph_helper(self,
                   build_configuration=None,
                   build_file_imports_behavior='allow',
                   include_trace_on_error=True,
                   path_ignore_patterns=None):

    with temporary_dir() as work_dir:
      path_ignore_patterns = path_ignore_patterns or []
      build_config = build_configuration or self._default_build_config()
      # TODO: This test should be swapped to using TestBase.
      graph_helper = EngineInitializer.setup_legacy_graph_extended(
        path_ignore_patterns,
        work_dir,
        build_file_imports_behavior,
        build_configuration=build_config,
        native=self._native,
        include_trace_on_error=include_trace_on_error
      )
      yield graph_helper

  @contextmanager
  def open_scheduler(self, specs, build_configuration=None):
    with self.graph_helper(build_configuration=build_configuration) as graph_helper:
      graph, target_roots = self.create_graph_from_specs(graph_helper, specs)
      addresses = tuple(graph.inject_roots_closure(target_roots))
      yield graph, addresses, graph_helper.scheduler.new_session()

  def create_graph_from_specs(self, graph_helper, specs):
    Subsystem.reset()
    session = graph_helper.new_session()
    target_roots = self.create_target_roots(specs, session, session.symbol_table)
    graph = session.create_build_graph(target_roots)[0]
    return graph, target_roots

  def create_target_roots(self, specs, session, symbol_table):
    return TargetRootsCalculator.create(self._make_setup_args(specs), session, symbol_table)

class GraphTargetScanFailureTests(GraphTestBase):

  def test_with_missing_target_in_existing_build_file(self):
    # When a target is missing,
    #  the suggestions should be in order
    #  and there should only be one copy of the error if tracing is off.
    with self.assertRaises(AddressLookupError) as cm:
      with self.graph_helper(include_trace_on_error=False) as graph_helper:
        self.create_graph_from_specs(graph_helper, ['3rdparty/python:rutabaga'])
        self.fail('Expected an exception.')

    error_message = str(cm.exception)
    expected_message = '"rutabaga" was not found in namespace "3rdparty/python".' \
                       ' Did you mean one of:\n' \
                       '  :Markdown\n' \
                       '  :Pygments\n'
    self.assertIn(expected_message, error_message)
    self.assertTrue(error_message.count(expected_message) == 1)

  def test_with_missing_directory_fails(self):
    with self.assertRaises(AddressLookupError) as cm:
      with self.graph_helper() as graph_helper:
        self.create_graph_from_specs(graph_helper, ['no-such-path:'])

    self.assertIn('Path "no-such-path" does not contain any BUILD files',
                  str(cm.exception))

  def test_with_existing_directory_with_no_build_files_fails(self):
    with self.assertRaises(AddressLookupError) as cm:
      path_ignore_patterns=[
        # This is a symlink that points out of the build root.
        '/build-support/bin/native/src'
      ]
      with self.graph_helper(path_ignore_patterns=path_ignore_patterns) as graph_helper:
        self.create_graph_from_specs(graph_helper, ['build-support/bin::'])

    self.assertIn('does not match any targets.', str(cm.exception))

  def test_inject_bad_dir(self):
    with self.assertRaises(AddressLookupError) as cm:
      with self.graph_helper() as graph_helper:
        graph, target_roots = self.create_graph_from_specs(graph_helper, ['3rdparty/python:'])

        graph.inject_address_closure(Address('build-support/bin', 'wat'))

    self.assertIn('Path "build-support/bin" does not contain any BUILD files',
                  str(cm.exception))

class GraphInvalidationTest(GraphTestBase):

  def test_invalidate_fsnode(self):
    with self.open_scheduler(['3rdparty/python::']) as (_, _, scheduler):
      initial_node_count = scheduler.node_count()
      self.assertGreater(initial_node_count, 0)

      invalidated_count = scheduler.invalidate_files(['3rdparty/python/BUILD'])
      self.assertGreater(invalidated_count, 0)
      self.assertLess(scheduler.node_count(), initial_node_count)

  def test_invalidate_fsnode_incremental(self):
    with self.open_scheduler(['//:', '3rdparty/::']) as (_, _, scheduler):
      node_count = scheduler.node_count()
      self.assertGreater(node_count, 0)

      # Invalidate the '3rdparty/python' DirectoryListing, the `3rdparty` DirectoryListing,
      # and then the root DirectoryListing by "touching" files/dirs.
      for filename in ('3rdparty/python/BUILD', '3rdparty/jvm', 'non_existing_file'):
        invalidated_count = scheduler.invalidate_files([filename])
        self.assertGreater(invalidated_count,
                           0,
                           'File {} did not invalidate any Nodes.'.format(filename))
        node_count, last_node_count = scheduler.node_count(), node_count
        self.assertLess(node_count, last_node_count)

  def _ordering_test(self, spec, expected_sources=None):
    expected_sources = expected_sources or ['p', 'a', 'n', 't', 's', 'b', 'u', 'i', 'l', 'd']
    with self.open_scheduler([spec]) as (graph, _, _):
      target = graph.get_target(Address.parse(spec))
      sources = [os.path.basename(s) for s in target.sources_relative_to_buildroot()]
      self.assertEquals(expected_sources, sources)

  def test_sources_ordering_literal(self):
    self._ordering_test('testprojects/src/resources/org/pantsbuild/testproject/ordering:literal')

  def test_sources_ordering_glob(self):
    self._ordering_test('testprojects/src/resources/org/pantsbuild/testproject/ordering:globs')

  def test_target_macro_override(self):
    """Tests that we can "wrap" an existing target type with additional functionality.

    Installs an additional TargetMacro that wraps `target` aliases to add a tag to all definitions.
    """
    spec = 'testprojects/tests/python/pants/build_parsing:'

    tag = 'tag_added_by_macro'
    target_cls = Target
    tag_macro = functools.partial(macro, target_cls, tag)
    target_symbols = {'target': TargetMacro.Factory.wrap(tag_macro, target_cls)}

    build_config = self._default_build_config(BuildFileAliases(targets=target_symbols))

    # Confirm that python_tests in a small directory are marked.
    with self.open_scheduler([spec], build_configuration=build_config) as (graph, addresses, _):
      self.assertTrue(len(addresses) > 0, 'No targets matched by {}'.format(addresses))
      for address in addresses:
        self.assertIn(tag, graph.get_target(address).tags)


text:
namespace QI4N.Framework.Runtime
{
    public class ImportedServiceInstance
    {
        private readonly ServiceImporter importer;

        private readonly object instance;

        public ImportedServiceInstance(object instance, ServiceImporter importer)
        {
            this.importer = importer;
            this.instance = instance;
        }

        public ServiceImporter Importer
        {
            get
            {
                return this.importer;
            }
        }

        public object Instance
        {
            get
            {
                return this.instance;
            }
        }

        public bool IsActive
        {
            get
            {
                return this.importer.IsActive(this.instance);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.cloudstack.api.command.user.network;

import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.vpc.NetworkACL;
import com.cloud.network.vpc.Vpc;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
import org.apache.cloudstack.api.*;
import org.apache.cloudstack.api.response.NetworkACLResponse;
import org.apache.cloudstack.api.response.NetworkResponse;
import org.apache.cloudstack.api.response.PrivateGatewayResponse;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.log4j.Logger;

@APICommand(name = "replaceNetworkACLList", description="Replaces ACL associated with a Network or private gateway", responseObject=SuccessResponse.class)
public class ReplaceNetworkACLListCmd extends BaseAsyncCmd {
    public static final Logger s_logger = Logger.getLogger(ReplaceNetworkACLListCmd.class.getName());
    private static final String s_name = "replacenetworkacllistresponse";

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @Parameter(name=ApiConstants.ACL_ID, type=CommandType.UUID, entityType = NetworkACLResponse.class,
            required=true, description="the ID of the network ACL")
    private long aclId;

    @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class,
            description="the ID of the network")
    private Long networkId;

    @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.UUID, entityType = PrivateGatewayResponse.class,
            description="the ID of the private gateway")
    private Long privateGatewayId;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public long getAclId() {
        return aclId;
    }

    public Long getNetworkId(){
        return networkId;
    }

    public Long getPrivateGatewayId() {
        return privateGatewayId;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////
    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public String getEventType() {
        return EventTypes.EVENT_NETWORK_ACL_REPLACE;
    }

    @Override
    public String getEventDescription() {
        return  ("Associating Network ACL id=" + aclId+ " with Network id="+ networkId);
    }

    @Override
    public long getEntityOwnerId() {
        Account caller = UserContext.current().getCaller();
        return caller.getAccountId();
    }

    @Override
    public void execute() throws ResourceUnavailableException {
        if (getNetworkId() == null && getPrivateGatewayId() == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Network id and private gateway can't be null at  the same time");
        }

        if (getNetworkId() != null && getPrivateGatewayId() != null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Network id and private gateway can't be passed  at  the same time");
        }

        UserContext.current().setEventDetails("Network ACL Id: " + aclId);
        boolean result = false;
        if (getPrivateGatewayId() != null) {
            result = _networkACLService.replaceNetworkACLonPrivateGw(aclId, privateGatewayId);
        } else {
            result = _networkACLService.replaceNetworkACL(aclId, networkId);
        }

        if (result) {
            SuccessResponse response = new SuccessResponse(getCommandName());
            this.setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to replace network ACL");
        }
    }
}


text:
class CreateColors < ActiveRecord::Migration[5.1]
  def change
    create_table :colors do |t|
      t.string :title
      t.string :slug
      t.text :desc
      t.references :parent_color, index: true

      t.timestamps
    end
    add_index :colors, :slug, unique: true
  end
end


text:
var url = require("url")
var EngineServer = require("engine.io").Server
var WebSocketStream = require("websocket-stream")

module.exports = createEngineServer

function createEngineServer(socketListener) {
    var engineServer = new EngineServer()

    engineServer.on("connection", function engineHandler(socket) {
        var stream = WebSocketStream(socket)
        stream.uri = url.parse(socket.request.url, true).query.uri

        socketListener(stream, socket.request)
    })

    return engineServer
}


text:
package com.google.android.exoplayer.text;

import com.google.android.exoplayer.ExoPlaybackException;
import com.google.android.exoplayer.MediaFormatHolder;
import com.google.android.exoplayer.SampleHolder;
import com.google.android.exoplayer.SampleSource;
import com.google.android.exoplayer.SampleSource.SampleSourceReader;
import com.google.android.exoplayer.TrackRenderer;
import com.google.android.exoplayer.util.Assertions;

import android.annotation.TargetApi;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * A {@link TrackRenderer} for textual subtitles. The actual rendering of each line of text to a
 * suitable output (e.g. the display) is delegated to a {@link TextRenderer}.
 */
@TargetApi(16)
public class TextTrackRenderer extends TrackRenderer implements Callback {

  private static final int MSG_UPDATE_OVERLAY = 0;

  private final Handler textRendererHandler;
  private final TextRenderer textRenderer;
  private final SampleSourceReader source;
  private final MediaFormatHolder formatHolder;
  private final SubtitleParser[] subtitleParsers;

  private int parserIndex;
  private int trackIndex;

  private boolean inputStreamEnded;

  private Subtitle subtitle;
  private Subtitle nextSubtitle;
  private SubtitleParserHelper parserHelper;
  private HandlerThread parserThread;
  private int nextSubtitleEventIndex;

  /**
   * @param source A source from which samples containing subtitle data can be read.
   * @param textRenderer The text renderer.
   * @param textRendererLooper The looper associated with the thread on which textRenderer should be
   *     invoked. If the renderer makes use of standard Android UI components, then this should
   *     normally be the looper associated with the applications' main thread, which can be
   *     obtained using {@link android.app.Activity#getMainLooper()}. Null may be passed if the
   *     renderer should be invoked directly on the player's internal rendering thread.
   * @param subtitleParsers An array of available subtitle parsers. Where multiple parsers are able
   *     to render a subtitle, the one with the lowest index will be preferred.
   */
  public TextTrackRenderer(SampleSource source, TextRenderer textRenderer,
      Looper textRendererLooper, SubtitleParser... subtitleParsers) {
    this.source = source.register();
    this.textRenderer = Assertions.checkNotNull(textRenderer);
    this.textRendererHandler = textRendererLooper == null ? null
        : new Handler(textRendererLooper, this);
    this.subtitleParsers = Assertions.checkNotNull(subtitleParsers);
    formatHolder = new MediaFormatHolder();
  }

  @Override
  protected int doPrepare(long positionUs) throws ExoPlaybackException {
    try {
      boolean sourcePrepared = source.prepare(positionUs);
      if (!sourcePrepared) {
        return TrackRenderer.STATE_UNPREPARED;
      }
    } catch (IOException e) {
      throw new ExoPlaybackException(e);
    }
    for (int i = 0; i < subtitleParsers.length; i++) {
      for (int j = 0; j < source.getTrackCount(); j++) {
        if (subtitleParsers[i].canParse(source.getTrackInfo(j).mimeType)) {
          parserIndex = i;
          trackIndex = j;
          return TrackRenderer.STATE_PREPARED;
        }
      }
    }
    return TrackRenderer.STATE_IGNORE;
  }

  @Override
  protected void onEnabled(long positionUs, boolean joining) {
    source.enable(trackIndex, positionUs);
    parserThread = new HandlerThread("textParser");
    parserThread.start();
    parserHelper = new SubtitleParserHelper(parserThread.getLooper(), subtitleParsers[parserIndex]);

    seekToInternal();
  }

  @Override
  protected void seekTo(long positionUs) {
    source.seekToUs(positionUs);
    seekToInternal();
  }

  private void seekToInternal() {
    inputStreamEnded = false;
    subtitle = null;
    nextSubtitle = null;
    parserHelper.flush();
    clearTextRenderer();
  }

  @Override
  protected void doSomeWork(long positionUs, long elapsedRealtimeUs) throws ExoPlaybackException {
    try {
      source.continueBuffering(trackIndex, positionUs);
    } catch (IOException e) {
      throw new ExoPlaybackException(e);
    }

    if (nextSubtitle == null) {
      try {
        nextSubtitle = parserHelper.getAndClearResult();
      } catch (IOException e) {
        throw new ExoPlaybackException(e);
      }
    }

    boolean textRendererNeedsUpdate = false;
    long subtitleNextEventTimeUs = Long.MAX_VALUE;
    if (subtitle != null) {
      // We're iterating through the events in a subtitle. Set textRendererNeedsUpdate if we
      // advance to the next event.
      subtitleNextEventTimeUs = getNextEventTime();
      while (subtitleNextEventTimeUs <= positionUs) {
        nextSubtitleEventIndex++;
        subtitleNextEventTimeUs = getNextEventTime();
        textRendererNeedsUpdate = true;
      }
    }

    if (subtitleNextEventTimeUs == Long.MAX_VALUE && nextSubtitle != null
        && nextSubtitle.getStartTime() <= positionUs) {
      // Advance to the next subtitle. Sync the next event index and trigger an update.
      subtitle = nextSubtitle;
      nextSubtitle = null;
      nextSubtitleEventIndex = subtitle.getNextEventTimeIndex(positionUs);
      textRendererNeedsUpdate = true;
    }

    if (textRendererNeedsUpdate && getState() == TrackRenderer.STATE_STARTED) {
      // textRendererNeedsUpdate is set and we're playing. Update the renderer.
      updateTextRenderer(subtitle.getCues(positionUs));
    }

    if (!inputStreamEnded && nextSubtitle == null && !parserHelper.isParsing()) {
      // Try and read the next subtitle from the source.
      try {
        SampleHolder sampleHolder = parserHelper.getSampleHolder();
        sampleHolder.clearData();
        int result = source.readData(trackIndex, positionUs, formatHolder, sampleHolder, false);
        if (result == SampleSource.SAMPLE_READ) {
          parserHelper.startParseOperation();
        } else if (result == SampleSource.END_OF_STREAM) {
          inputStreamEnded = true;
        }
      } catch (IOException e) {
        throw new ExoPlaybackException(e);
      }
    }
  }

  @Override
  protected void onDisabled() {
    subtitle = null;
    nextSubtitle = null;
    parserThread.quit();
    parserThread = null;
    parserHelper = null;
    clearTextRenderer();
    source.disable(trackIndex);
  }

  @Override
  protected void onReleased() {
    source.release();
  }

  @Override
  protected long getDurationUs() {
    return source.getTrackInfo(trackIndex).durationUs;
  }

  @Override
  protected long getBufferedPositionUs() {
    // Don't block playback whilst subtitles are loading.
    return END_OF_TRACK_US;
  }

  @Override
  protected boolean isEnded() {
    return inputStreamEnded && (subtitle == null || getNextEventTime() == Long.MAX_VALUE);
  }

  @Override
  protected boolean isReady() {
    // Don't block playback whilst subtitles are loading.
    // Note: To change this behavior, it will be necessary to consider [Internal: b/12949941].
    return true;
  }

  private long getNextEventTime() {
    return ((nextSubtitleEventIndex == -1)
        || (nextSubtitleEventIndex >= subtitle.getEventTimeCount())) ? Long.MAX_VALUE
        : (subtitle.getEventTime(nextSubtitleEventIndex));
  }

  private void updateTextRenderer(List<Cue> cues) {
    if (textRendererHandler != null) {
      textRendererHandler.obtainMessage(MSG_UPDATE_OVERLAY, cues).sendToTarget();
    } else {
      invokeRendererInternalCues(cues);
    }
  }

  private void clearTextRenderer() {
    updateTextRenderer(Collections.<Cue>emptyList());
  }

  @SuppressWarnings("unchecked")
  @Override
  public boolean handleMessage(Message msg) {
    switch (msg.what) {
      case MSG_UPDATE_OVERLAY:
        invokeRendererInternalCues((List<Cue>) msg.obj);
        return true;
    }
    return false;
  }

  private void invokeRendererInternalCues(List<Cue> cues) {
    textRenderer.onCues(cues);
  }

}


text:
<?php

/**
* TestCase class for PHPUnit
* @author Arandi López <arandilopez.93@gmail.com>
*/
class TestCase extends PHPUnit_Framework_TestCase {

	public function createNewApp()
	{
		return new App();
	}
}


text:
rightscale_marker

  log "Dummy place keeper: Install mysql5.5 installation code here."
  log "For sake of example am adding mysql 4.1.2."

  include_recipe "mysql::client"
  include_recipe "mysql::server"


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RoboNui.Core
{
    /**
     *
     * Struct of constants for translating pulse widths to angles and angles to pulse widths.s
     *
     *
     * <remarks>
     * Author: Jon Eisen (yanatan16@gmail.com)
     * </remarks>
     */
    public class PulseWidthConstants
    {
        /**
         * Multiplier M for linear function of angle to pulse width: PW = M * A + C
         */
        private double Multiplier { get; set;  }

        /**
         * Constant C for linear function of angle to pulse width: PW = M * A + C
         */
        private ulong Constant { get; set; }

        /**
         *
         * Constructor with arguments
         *
         * <param name="C">Constant value</param>
         * <param name="M">Multiplier value</param>
         */
        public PulseWidthConstants(double M, ulong C) :
            base()
        {
            Multiplier = M;
            Constant = C;
        }

        /**
         *
         * Convert an Angle to a Pulse Width
         *
         * <param name="a">Angle to convert</param>
         * <returns>Pulse width</returns>
         */
        public ulong AngleToPulseWidth(double a)
        {
            return (ulong)(a * Multiplier) + Constant;
        }

        /**
         *
         * Convert a Pulse Width to an Angle
         *
         * <param name="pw">Pulse width to convert</param>
         * <returns>Angle value</returns>
         */
        public double PulseWidthToAngle(ulong pw)
        {
            return (pw - Constant) / Multiplier;
        }
    }

    /**
     *
     * A struct that contains the angles of the robot
     *
     * <remarks>Author: Jon Eisen (yanatan16@gmail.com)</remarks>
     * <seealso cref="RoboticAngle"/>
     */
    public class AngleSet
    {
        /**
         *
         * Construct the JointSet.
         *
         */
        public AngleSet()
        {
            AngleMap = new Dictionary<RoboticAngle, double>();
        }

        /**
         *
         * Map of Robotic Angles to double angles.
         *
         * <remarks>
         * Angles are in the range -Math.PI to Math.PI
         * </remarks>
         */
        public Dictionary<RoboticAngle, double> AngleMap { get; set; }

        /**
         *
         * Translate the Angle Map to a pulse width map given a struct of Pulse Width Constants
         *
         * <param name="pwc">Pulse Width Constant for pulse width translation</param>
         * <returns>Pulse Width Dictionary Map</returns>
         */
        public Dictionary<RoboticAngle, ulong> GetPulseWidthMap(PulseWidthConstants pwc)
        {
            Dictionary<RoboticAngle, ulong> PulseWidthMap = new Dictionary<RoboticAngle, ulong>();
            foreach (KeyValuePair<RoboticAngle, double> angle in AngleMap)
            {
                PulseWidthMap[angle.Key] = pwc.AngleToPulseWidth(angle.Value);
            }
            return PulseWidthMap;
        }

        /**
         *
         * Set the Angle Map by setting a Pulse Width Map given a struct of Pulse Width Constants
         *
         * <param name="PulseWidthMap">Map of roboticangles to pulse widths</param>
         * <param name="pwc">Pulse Width Constant for pulse width translation</param>
         */
        public void SetPulseWidthMap(Dictionary<RoboticAngle, ulong> PulseWidthMap, PulseWidthConstants pwc)
        {
            AngleMap.Clear();
            foreach (KeyValuePair<RoboticAngle, ulong>pw in PulseWidthMap)
            {
                AngleMap[pw.Key] = pwc.PulseWidthToAngle(pw.Value);
            }
        }

        public override string ToString()
        {
            string str = "AngleSet{ ";
            int i = 0;
            foreach (KeyValuePair<RoboticAngle, double> pair in AngleMap)
            {
                str += "(" + pair.Key.ToString() + "," + pair.Value.ToString() + ")";
                if (++i < AngleMap.Count)
                    str += ", ";
            }
            str += " }";
            return str;
        }

    }
}


text:
/************************************************************************/
/* zmqcoms.c								*/
/*                                                                      */
/* Serial port control routines.					*/
/************************************************************************/
/*                                                                      */
/*                    CHARA ARRAY USER INTERFACE			*/
/*                 Based on the SUSI User Interface			*/
/*		In turn based on the CHIP User interface		*/
/*                                                                      */
/*            Center for High Angular Resolution Astronomy              */
/*              Mount Wilson Observatory, CA 91001, USA			*/
/*                                                                      */
/* Telephone: 1-626-796-5405                                            */
/* Fax      : 1-626-796-6717                                            */
/* email    : theo@chara.gsu.edu                                        */
/* WWW      : http://www.chara.gsu.edu			                */
/*                                                                      */
/* (C) This source code and its associated executable                   */
/* program(s) are copyright.                                            */
/*                                                                      */
/************************************************************************/
/*                                                                      */
/* Author : Tony Johnson & Theo ten Brummelaar                          */
/* Date   : Original Version 1990 - ported to Linux 1998                */
/************************************************************************/

/*
 * Include files
 */

#include "zmqcoms.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>

#include <netdb.h>
#include <resolv.h>
#include <sys/socket.h>
#include <sys/time.h>
//#include <signal.h>
#include <netinet/tcp.h>

#define MAX_CONNECTIONS 10
#define SERVER_PORT 3001
#define SERVER_SOCKET_BUFFER 65536

#undef max
#define max(x,y) ((x) > (y) ? (x) : (y))

/*
 * Local globals
 */

static void *context;
static void *responder;
static int rc;

static int	message_socket = -1;	/* socket used for outside messages */
static struct {
		int  fd;		/* File descriptor */
		char *machine; 	/* Name of connecting machine */
			} client_sockets[MAX_CONNECTIONS]; /* Active channels */
static char	server_computer_name[81];	/* This machine's name */
static int	server_port;		/* The port we are listening too */
static int	curr_client = 0;		/* Current socket to check */

//static int (*(message_jobs[MAX_JOBS]))(struct smessage *message);

static int current_socket = -1;

//static unsigned char client_signals[MAX_CONNECTIONS][MAX_SIGNAL];

//static bool sent_signal_message = FALSE;

static FILE *server_log_fd = NULL;

/* Globals */

int client_socket = -1;                 /*
                                         * The current client socket.
                                         * Set to -1 if no client socket.
                                         */

char *client_machine;                   /*
                                         * The current server machine.
                                         * Set to 0 if no server machine.
                                         */

char	*server_name;			/* What we call ourselves */

//static bool Messages_on = TRUE; 	/* Should we process messages? */

int message(char *fmt, ...)
{
    char err_string[4097];
    int sprintf_len;
    va_list args;
    va_start(args,fmt);
    sprintf_len = vsprintf(err_string, fmt, args);
    fprintf(stderr, "%s\n", err_string);
    return NOERROR;
}

void send_raw_message(char *message,int len)
{
    if (client_socket != -1){
        zmq_send(responder,message,len,0);
    }
}

int error(int level, char *fmt, ...)
{
	char err_string[4097];
	int sprintf_len, i;
	va_list args;
	va_start(args, fmt);
	sprintf_len = vsprintf(err_string, fmt, args);
	if (client_socket==-1){
		fprintf(stderr, "%s\n", err_string);
	} else {
        zmq_send(responder,err_string,strlen(err_string),0);
        /* Error checking??? */
	}
	return NOERROR;
}

int get_next_command(char *command)
{
	struct timeval tv = { 0L, 0L };
	fd_set fds;
	int nr;

	/* Start off with no command */
	command[0]=0;
    client_socket=-1;

	/* Set up our file descriptor set. Stdin is file descriptor number 0 */
	FD_ZERO(&fds);
    FD_SET(0, &fds);
	if (select(1, &fds, NULL, NULL, &tv) > 0){
		fgets(command, COMMAND_BUFFERSIZE, stdin);
        nr = strlen(command);
	} else {
        /* Receive from ZMQ */
        nr = zmq_recv (responder, command, COMMAND_BUFFERSIZE-1, ZMQ_DONTWAIT);
        if (nr>0)
            client_socket=0;
    }
    /* Null terminate and tidy up */
    command[nr]=0;
    if (command[nr-1] == '\n' || command[nr-1] == '\r') command[nr-1]=0;
	if (command[nr-2] == '\r') command[nr-2]=0;

	return NOERROR;
}

/************************************************************************/
/* open_server_socket()	               					*/
/* 									*/
/* Opens a message socket that can be used for accepting and sending	*/
/* outside messages. 							*/
/************************************************************************/

int open_server_socket(void)
{
    char tcp_string[40];

    /* Straight out of ZMQ tutorial*/
    context = zmq_ctx_new ();
    responder = zmq_socket (context, ZMQ_REP);
    sprintf(tcp_string, "tcp://*:%d", SERVER_PORT);
    rc = zmq_bind (responder, tcp_string);
    if (rc != 0)
        return error(FATAL,"ZMQ socket failure.");

	/* Reset current socket pointer. */
    client_socket=-1;

	return NOERROR;

} /* open_message_socket() */

/************************************************************************/
/* close_server_socket()						*/
/* 									*/
/* Close the server socket if it's open. Remember this could cause     */
/* trouble if you do this while the channel is server. If the message	*/
/* socket is not open this function will do nothing.			*/
/*									*/
/************************************************************************/

void close_server_socket(void)
{
	int i;

	/* Do nothing if it isn't open */
	if (responder == NULL) return;

	zmq_close(responder);

} /* close_message_socket() */

/************************************************************************/
/* open_serial_port()							*/
/* 									*/
/* Opens a serial port, returns and sets up serial structure.		*/
/* Second variable set's blocking or non-blocking. TRUE for blocking,	*/
/* FALSE for non-blocking.						*/
/* Structure will contain a copy of the termios data which you		*/
/* can manipulate with various functions like set_serial_baud_rate().	*/
/* The original termios structure is saved and can be restored. See	*/
/* close_serial_port().							*/
/* Returns the struct sserial structure.				*/
/* On error file discriptor set to -1.					*/
/* The user should also setup baud rates etc. 				*/
/************************************************************************/

struct sserial open_serial_port(char *port_name, bool blocking)
{
	struct sserial  port;	/* The return value */
	struct stat stat_buf;
	int	     lock_fd;
	char	     s[81];

	/* Construct the lock_file_name */

	lock_file_name(port_name, port.lock_file);

	/* Does this file exist already? */

	if (stat(port.lock_file, &stat_buf) == 0)
		error(MESSAGE, "Device %s seemed to be blocked, but I ignored it.",port_name);
/*	sprintf(s,"Device %s seems to be blocked.",port_name);
	if (stat(port.lock_file, &stat_buf) == 0 &&
		!ask_yes_no(s,"Shall we go on as if this is a stale block?"))
	{
		port.fd = -1;
		return port;
	}*/

	/* OK, better lock the file up */

	if ((lock_fd = open(port.lock_file,
		O_WRONLY | O_CREAT | 0x550)) == -1)
	{
		error(WARNING,
	"Could not create lock file %s (errno = %d).\nPort %s not opened.",
			port.lock_file, errno, port_name);
		port.fd = -1;
		return port;
	}
	chmod(port.lock_file, S_IWUSR | S_IWGRP | S_IRUSR | S_IRGRP);
	close(lock_fd);

	/* Copy the name */

	strncpy(port.name,port_name,80);

	/* Try and open the port */

	if (blocking)
	{
		if ((port.fd = open(port_name,O_RDWR)) == -1)
		{
			port.fd = -1;
			unlink(port.lock_file);
			error(WARNING,"Could not open serial port %s.",
				port_name);
			return port;
		}
	}
	else
	{
		if ((port.fd = open(port_name,O_RDWR | O_NONBLOCK)) == -1)
		{
			port.fd = -1;
			unlink(port.lock_file);
			error(WARNING,"Could not open serial port %s.",
				port_name);
			return port;
		}
	}

	/* Get the termios structure into orig_termios */

	if (tcgetattr(port.fd, &(port.orig_termios)) == -1)
	{
		error(WARNING,"Could not get termios for serial port %s.",
			port_name);
		close(port.fd);
		port.fd = -1;
		unlink(port.lock_file);
		return port;
	}

	/* Get the termios structure into curr_termios */

	if (tcgetattr(port.fd, &(port.curr_termios)) == -1)
	{
		error(WARNING,"Could not get termios for serial port %s.",
			port_name);
		close(port.fd);
		port.fd = -1;
		unlink(port.lock_file);
		return port;
	}

	/* Setinto raw, no echo mode, not canonical */

	port.curr_termios.c_iflag = IGNBRK;
	port.curr_termios.c_lflag = 0;
	port.curr_termios.c_oflag = 0;
	port.curr_termios.c_cflag |= (CLOCAL | CREAD);

	/* No hardware control */

	port.curr_termios.c_cflag &= (~CRTSCTS);

	/* Now send this stuff away to the port. */

	if (tcsetattr(port.fd, TCSADRAIN, &(port.curr_termios)) == -1)
	{
		error(WARNING,
			"Could not write termios for defaults port %s.",
			port.name);
		close(port.fd);
		port.fd = -1;
		unlink(port.lock_file);
		return port;
	}

	/* Return the structure */

	return port;

} /* open_serial_port() */

/************************************************************************/
/* lock_file_name()							*/
/*									*/
/* Constructs the name of a lock file. Puts it in the directory		*/
/* LOCK_DIR and uses LOCK_START and the last part of path name of file	*/
/* sent it to create the file name.					*/
/* Places name in string s, which is also the return value.		*/
/* The string's needs to have enough space to do this....		*/
/************************************************************************/

char *lock_file_name(char *path, char *s)
{
	char 	*pc;

	/* Find the last name in the path */

	for (pc = path+strlen(path); pc != path && *pc != '/'; pc--);
	if (pc != path) pc++;

	/* Now build the lock file name */

	sprintf(s,"%s/%s%s",LOCK_DIR,LOCK_START,pc);

	/* That is all */

	return s;

} /* lock_file_name() */

/************************************************************************/
/* close_serial_port()							*/
/* 									*/
/* Closes a serial port.						*/
/* The original termios structure is restored. 				*/
/* close_serial_port().							*/
/************************************************************************/

int	close_serial_port(struct sserial port)
{

	/* Put back the old termios data */

	if (tcsetattr(port.fd, TCSADRAIN, &(port.orig_termios)) == -1)
	{
		/* If we fail, let the user know, but go on anyway. */

		error(WARNING,"Could not write termios for serial port %s.",
			port.name);
	}

	/* Close the port */

	if (close(port.fd) == -1)
	{
		/* If we fail, let the user know, but go on anyway. */

		error(WARNING,"Could not close serial port %s.",port.name);
	}

	/* Remove the lock file */

	unlink(port.lock_file);

	/* Make sure the FD is set to -1 */

	port.fd = -1;

	return NOERROR;

} /* close_serial_port() */

/************************************************************************/
/* set_serial_baud_rate()						*/
/*									*/
/* Set's up the baud rate for a serial port.				*/
/* Returns NOERROR if all OK, error level otherwise.			*/
/* The speeds are defined in the termios.h header file, for example	*/
/* you could use B9600 for 9600 baud.					*/
/************************************************************************/

int set_serial_baud_rate(struct sserial *port, speed_t speed)
{
	/* Set up the speed in the current termios */

	if (cfsetospeed(&(port->curr_termios), speed) == -1)
	{
		error(WARNING,
			"Could not set output baud rate for serial port %s.",
			port->name);
		return WARNING;
	}

	if (cfsetispeed(&(port->curr_termios), speed) == -1) /* Same speed */
	{
		error(WARNING,
			"Could not set input baud rate for serial port %s.",
			port->name);
		return WARNING;
	}

	if (tcsetattr(port->fd, TCSADRAIN, &(port->curr_termios)) == -1)
	{
		error(WARNING,
			"Could not write termios for baud rate change port %s.",
			port->name);
		return WARNING;
	}

	return NOERROR;

} /* set_serial_baud_rate() */

/************************************************************************/
/* set_serial_parity()							*/
/*									*/
/* Set's a port's parity bit in it's termios.c_cflag on or off.		*/
/* Argument can be either OFF, EVEN or ODD.				*/
/* Returns NOERROR of all OK or error level otherwise.			*/
/************************************************************************/

int set_serial_parity(struct sserial *port, int parity)
{

	if (parity != ODD && parity != EVEN && parity != OFF)
	{
		error(WARNING,
		"Invalid argument to set_serial_parity(). No changes made.");
		return WARNING;
	}

	/* Make the appropriate change to the c_cflag entry */

	if (parity == OFF)
	{
		port->curr_termios.c_cflag &= (~PARENB);
	}
	else
	{
		port->curr_termios.c_cflag |= PARENB;

		if (parity == EVEN)
		{
			port->curr_termios.c_cflag &= (~PARODD);
		}
		else
		{
			port->curr_termios.c_cflag |= PARODD;
		}
	}

	/* Now write the changed termios to the port */

	if (tcsetattr(port->fd, TCSADRAIN, &(port->curr_termios)) == -1)
	{
		error(WARNING,
			"Could not write termios for parity change port %s.",
			port->name);
		return WARNING;
	}

	return NOERROR;

} /* set_serial_parity() */

/************************************************************************/
/* set_serial_xonxoff()							*/
/*									*/
/* Sets a port's xonxoff in it's termios.c_cflag on or off.		*/
/* Argument can be either OFF or OFF.					*/
/* Returns NOERROR of all OK or error level otherwise.			*/
/************************************************************************/

int set_serial_xonxoff(struct sserial *port, int xonxoff)
{
	if (xonxoff != OFF && xonxoff != ON)
	{
		error(WARNING,
		"Invalid argument to set_serial_xonxoff(). No changes made.");
		return WARNING;
	}

	/* Make the appropriate change to the c_iflag entry */

	if (xonxoff == ON)
	{
		port->curr_termios.c_iflag |= IXON;
		port->curr_termios.c_iflag |= IXOFF;
	}
	else
	{
		port->curr_termios.c_iflag &= (~IXON);
		port->curr_termios.c_iflag &= (~IXOFF);
	}

	/* Now write the changed termios to the port */

	if (tcsetattr(port->fd, TCSADRAIN, &(port->curr_termios)) == -1)
	{
		error(WARNING,
			"Could not write termios for xonxoff change port %s.",
			port->name);
		return WARNING;
	}

	return NOERROR;

} /* set_serial_xonxoff() */

/************************************************************************/
/* set_serial_hard_handshake()						*/
/*									*/
/* Turns hardware handshaking on or off.  				*/
/* Argument can be either OFF or OFF.					*/
/* Returns NOERROR of all OK or error level otherwise.			*/
/************************************************************************/

int set_serial_hard_handshake(struct sserial *port, int hard_handshake)
{
	if (hard_handshake != OFF && hard_handshake != ON)
	{
		error(WARNING,
	"Invalid argument to set_serial_hard_handshake(). No changes made.");
		return WARNING;
	}

	/* Make the appropriate change to the c_iflag entry */

	if (hard_handshake == ON)
	{
		port->curr_termios.c_cflag |= CRTSCTS;
		port->curr_termios.c_cflag &= (~CLOCAL);
	}
	else
	{
		port->curr_termios.c_cflag &= (~CRTSCTS);
		port->curr_termios.c_cflag |= CLOCAL;
	}

	/* Now write the changed termios to the port */

	if (tcsetattr(port->fd, TCSADRAIN, &(port->curr_termios)) == -1)
	{
		error(WARNING,
			"Could not write termios for handshake change port %s.",
			port->name);
		return WARNING;
	}

	return NOERROR;

} /* set_serial_hard_handshake() */

/************************************************************************/
/* set_serial_bitlength()						*/
/*									*/
/* Sets a port's bit length in it's termios.c_cflag.			*/
/* Argument can be either 5, 6, 7 or 8.					*/
/* Returns NOERROR of all OK or error level otherwise.			*/
/************************************************************************/

int set_serial_bitlength(struct sserial *port, int bits)
{
	int mask;

	/* Make the appropriate change to the c_iflag entry */

	switch(bits)
	{
		case 5: mask = CS5;
		        break;

		case 6: mask = CS6;
		        break;

		case 7: mask = CS7;
		        break;

		case 8: mask = CS8;
		        break;

		default: error(WARNING,
	"Invalid argument to set_serial_bitlength(). No changes made.");
			return WARNING;
	}

	port->curr_termios.c_cflag &= (~CSIZE);
	port->curr_termios.c_cflag |= mask;

	/* Now write the changed termios to the port */

	if (tcsetattr(port->fd, TCSADRAIN, &(port->curr_termios)) == -1)
	{
		error(WARNING,
		    "Could not write termios for bit length change port %s.",
		    port->name);
		return WARNING;
	}

	return NOERROR;

} /* set_serial_bitlength() */

/************************************************************************/
/* set_serial_stopbits()						*/
/*									*/
/* Sets a port's stop bits in it's termios.c_cflag.			*/
/* Argument can be either 1 or 2.					*/
/* Returns NOERROR of all OK or error level otherwise.			*/
/************************************************************************/

int set_serial_stopbits(struct sserial *port, int bits)
{
	/* Make the appropriate change to the c_iflag entry */

	switch(bits)
	{
		case 1: port->curr_termios.c_cflag &= (~CSTOPB);
		        break;

		case 2: port->curr_termios.c_cflag |= CSTOPB;
		        break;

		default: error(WARNING,
	"Invalid argument to set_serial_stopbits(). No changes made.");
			return WARNING;
	}

	/* Now write the changed termios to the port */

	if (tcsetattr(port->fd, TCSADRAIN, &(port->curr_termios)) == -1)
	{
		error(WARNING,
		    "Could not write termios for bit length change port %s.",
		    port->name);
		return WARNING;
	}

	return NOERROR;

} /* set_serial_stopbits() */

/************************************************************************/
/* serial_getchar()							*/
/*									*/
/* Reads a character from a serial port.				*/
/* Returns the character or -1 on error or 0 if there is no character.	*/
/************************************************************************/

unsigned char serial_getchar(struct sserial port)
{
	unsigned char c;

	if (read(port.fd,&c,1) != 1)
	{
		if (errno == EAGAIN)
		{
			return 0;
		}
		else
		{
			error(WARNING,"Error reading from port %s.\n",
				port.name);
			return -1;
		}
	}
	return c;

} /* serial_getchar() */

/************************************************************************/
/* serial_putchar()							*/
/*									*/
/* Writes a character to a serial port.					*/
/* Returns character sent or -1 on error.				*/
/************************************************************************/

unsigned char serial_putchar(struct sserial port, unsigned char c)
{
	if (write(port.fd,&c,1) != 1)
	{
		error(WARNING,"Error writing to port %s.\n",port.name);
		return -1;
	}
	return c;

} /* serial_putchar() */

/************************************************************************/
/* serial_print() 							*/
/*									*/
/* This is the equivalent of a printf command but sends the result	*/
/* to the given serial port. 						*/
/* Returns the number of characters printed.				*/
/************************************************************************/

int	serial_print(struct sserial port, char *fmt, ...)
{
	char	s[BUFFER_SIZE];
	va_list args;
	int	len;
	char	err_string[256];

	/* Check that the string is not too long */

        if (strlen(fmt) > sizeof(s) - sizeof((char)0))
        {
                strcpy(err_string,"Serial message too long\n");
                strcat(err_string,"Consult software supplier");
                error(FATAL,err_string);
        }

        /* Create the string */

        va_start(args, fmt);
        len = vsprintf(s, fmt, args);

        if (len > sizeof(s) - sizeof((char)0))
        {
                strcpy(err_string,"Serial message too long\n");
                strcat(err_string,"Consult software supplier");
                error(FATAL,err_string);
        }

	/* Write the message to the serial */

	if (write(port.fd, s, strlen(s)) != strlen(s))
	{
		error(WARNING,
			"Failed to write message to port %s.",port.name);
		return 0;
	}

	return len;

} /* serial_print() */

/************************************************************************/
/* serial_scan() 							*/
/*									*/
/* This is the equivalent of a scanf command but reads the data		*/
/* from the given serial. 						*/
/* Returns the number of items actually read.				*/
/************************************************************************/

int	serial_scan(struct sserial port, char *fmt, ...)
{
	char	s[BUFFER_SIZE];
	va_list args;

	/* Get a line of text from the serial. */

	if (serial_gets(port, s, BUFFER_SIZE) == (char *) EOF) return 0;

        /* Create the string */

        va_start(args, fmt);
        return vsscanf(s, fmt, args);

} /* serial_scan() */

/************************************************************************/
/* serial_gets() 							*/
/* 									*/
/* Equivalent to the normal gets() function, this function tries	*/
/* to get a string from the given serial. The return character (if	*/
/* there is one) is removed. The return value is a pointer to the 	*/
/* sent as an argument or EOF on end of file or error.			*/
/* In nonblocking mode, the string is empty if there was nothing	*/
/* to get.								*/
/* Will read up to n-1 characters leaving room for null at end.		*/
/************************************************************************/

char *serial_gets(struct sserial port, char *s, int n)
{

	int	len;

	/* Get the line of text */

	if ((len = read(port.fd, s, n-1)) <= 0)
	{
		if (errno == EAGAIN)
		{
			*s = 0;
			return s;
		}
		else
		{
			return (char *)EOF;
		}
	}

	/* Terminate the string */

	s[len] = 0;

	/* Remove the final return character */

	if (s[len-1] == '\n') s[len-1] = 0;

	return s;

} /* serial_gets() */


text:
@interface JJLeftTableViewCell : UITableViewCell

+ (instancetype)leftTableViewCellWithTableView:(UITableView *)tableView;
@end


text:
package org.apache.storm.kafka.spout.internal;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.storm.kafka.spout.DefaultRecordTranslator;
import org.apache.storm.kafka.spout.FirstPollOffsetStrategy;
import org.apache.storm.kafka.spout.Func;
import org.apache.storm.kafka.spout.RecordTranslator;
import org.apache.storm.kafka.spout.SimpleRecordTranslator;
import org.apache.storm.kafka.spout.subscription.ManualPartitioner;
import org.apache.storm.kafka.spout.subscription.NamedTopicFilter;
import org.apache.storm.kafka.spout.subscription.PatternTopicFilter;
import org.apache.storm.kafka.spout.subscription.RoundRobinManualPartitioner;
import org.apache.storm.kafka.spout.subscription.TopicFilter;
import org.apache.storm.tuple.Fields;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class CommonKafkaSpoutConfig<K, V> implements Serializable {
    public static final long DEFAULT_POLL_TIMEOUT_MS = 200;
    public static final long DEFAULT_PARTITION_REFRESH_PERIOD_MS = 2_000;
    // Earliest start
    public static final long DEFAULT_START_TS = 0L;
    public static final FirstPollOffsetStrategy DEFAULT_FIRST_POLL_OFFSET_STRATEGY = FirstPollOffsetStrategy.UNCOMMITTED_EARLIEST;

    public static final Logger LOG = LoggerFactory.getLogger(CommonKafkaSpoutConfig.class);

    // Kafka consumer configuration
    private final Map<String, Object> kafkaProps;
    private final TopicFilter topicFilter;
    private final ManualPartitioner topicPartitioner;
    private final long pollTimeoutMs;

    // Kafka spout configuration
    private final RecordTranslator<K, V> translator;
    private final FirstPollOffsetStrategy firstPollOffsetStrategy;
    private final long partitionRefreshPeriodMs;
    private final long startTimeStamp;

    /**
     * Creates a new CommonKafkaSpoutConfig using a Builder.
     *
     * @param builder The Builder to construct the CommonKafkaSpoutConfig from
     */
    public CommonKafkaSpoutConfig(Builder<K, V, ?> builder) {
        this.kafkaProps = builder.kafkaProps;
        this.topicFilter = builder.topicFilter;
        this.topicPartitioner = builder.topicPartitioner;
        this.translator = builder.translator;
        this.firstPollOffsetStrategy = builder.firstPollOffsetStrategy;
        this.pollTimeoutMs = builder.pollTimeoutMs;
        this.partitionRefreshPeriodMs = builder.partitionRefreshPeriodMs;
        this.startTimeStamp = builder.startTimeStamp;
    }

    public abstract static class Builder<K, V, T extends Builder<K, V, T>> {

        private final Map<String, Object> kafkaProps;
        private final TopicFilter topicFilter;
        private final ManualPartitioner topicPartitioner;
        private RecordTranslator<K, V> translator;
        private long pollTimeoutMs = DEFAULT_POLL_TIMEOUT_MS;
        private FirstPollOffsetStrategy firstPollOffsetStrategy = DEFAULT_FIRST_POLL_OFFSET_STRATEGY;
        private long partitionRefreshPeriodMs = DEFAULT_PARTITION_REFRESH_PERIOD_MS;
        private long startTimeStamp = DEFAULT_START_TS;

        public Builder(String bootstrapServers, String... topics) {
            this(bootstrapServers, new NamedTopicFilter(topics), new RoundRobinManualPartitioner());
        }

        public Builder(String bootstrapServers, Set<String> topics) {
            this(bootstrapServers, new NamedTopicFilter(topics), new RoundRobinManualPartitioner());
        }

        public Builder(String bootstrapServers, Pattern topics) {
            this(bootstrapServers, new PatternTopicFilter(topics), new RoundRobinManualPartitioner());
        }

        /**
         * Create a KafkaSpoutConfig builder with default property values and no key/value deserializers.
         *
         * @param bootstrapServers The bootstrap servers the consumer will use
         * @param topicFilter The topic filter defining which topics and partitions the spout will read
         * @param topicPartitioner The topic partitioner defining which topics and partitions are assinged to each spout task
         */
        public Builder(String bootstrapServers, TopicFilter topicFilter, ManualPartitioner topicPartitioner) {
            kafkaProps = new HashMap<>();
            if (bootstrapServers == null || bootstrapServers.isEmpty()) {
                throw new IllegalArgumentException("bootstrap servers cannot be null");
            }
            kafkaProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
            this.topicFilter = topicFilter;
            this.topicPartitioner = topicPartitioner;
            this.translator = new DefaultRecordTranslator<>();
        }

        /**
         * Set a {@link KafkaConsumer} property.
         */
        public T setProp(String key, Object value) {
            kafkaProps.put(key, value);
            return (T)this;
        }

        /**
         * Set multiple {@link KafkaConsumer} properties.
         */
        public T setProp(Map<String, Object> props) {
            kafkaProps.putAll(props);
            return (T)this;
        }

        /**
         * Set multiple {@link KafkaConsumer} properties.
         */
        public T setProp(Properties props) {
            props.forEach((key, value) -> {
                if (key instanceof String) {
                    kafkaProps.put((String) key, value);
                } else {
                    throw new IllegalArgumentException("Kafka Consumer property keys must be Strings");
                }
            });
            return (T)this;
        }

        //Spout Settings
        /**
         * Specifies the time, in milliseconds, spent waiting in poll if data is not available. Default is 200ms.
         *
         * @param pollTimeoutMs time in ms
         */
        public T setPollTimeoutMs(long pollTimeoutMs) {
            this.pollTimeoutMs = pollTimeoutMs;
            return (T)this;
        }

        /**
         * Sets the offset used by the Kafka spout in the first poll to Kafka broker upon process start. Please refer to to the
         * documentation in {@link FirstPollOffsetStrategy}
         *
         * @param firstPollOffsetStrategy Offset used by Kafka spout first poll
         */
        public T setFirstPollOffsetStrategy(FirstPollOffsetStrategy firstPollOffsetStrategy) {
            this.firstPollOffsetStrategy = firstPollOffsetStrategy;
            return (T)this;
        }

        public T setRecordTranslator(RecordTranslator<K, V> translator) {
            this.translator = translator;
            return (T)this;
        }

        /**
         * Configure a translator with tuples to be emitted on the default stream.
         *
         * @param func extracts and turns a Kafka ConsumerRecord into a list of objects to be emitted
         * @param fields the names of the fields extracted
         * @return this to be able to chain configuration
         */
        public T setRecordTranslator(Func<ConsumerRecord<K, V>, List<Object>> func, Fields fields) {
            return setRecordTranslator(new SimpleRecordTranslator<>(func, fields));
        }

        /**
         * Configure a translator with tuples to be emitted to a given stream.
         *
         * @param func extracts and turns a Kafka ConsumerRecord into a list of objects to be emitted
         * @param fields the names of the fields extracted
         * @param stream the stream to emit the tuples on
         * @return this to be able to chain configuration
         */
        public T setRecordTranslator(Func<ConsumerRecord<K, V>, List<Object>> func, Fields fields, String stream) {
            return setRecordTranslator(new SimpleRecordTranslator<>(func, fields, stream));
        }

        /**
         * Sets partition refresh period in milliseconds. This is how often Kafka will be polled to check for new topics and/or new
         * partitions.
         *
         * @param partitionRefreshPeriodMs time in milliseconds
         * @return the builder (this)
         */
        public T setPartitionRefreshPeriodMs(long partitionRefreshPeriodMs) {
            this.partitionRefreshPeriodMs = partitionRefreshPeriodMs;
            return (T)this;
        }

        /**
         * Specifies the startTimeStamp if the first poll strategy is TIMESTAMP or UNCOMMITTED_TIMESTAMP.
         * @param startTimeStamp time in ms
         */
        public T setStartTimeStamp(long startTimeStamp) {
            this.startTimeStamp = startTimeStamp;
            return (T)this;
        }

        protected Map<String, Object> getKafkaProps() {
            return kafkaProps;
        }

        public abstract CommonKafkaSpoutConfig<K, V> build();
    }

    /**
     * Gets the properties that will be passed to the KafkaConsumer.
     *
     * @return The Kafka properties map
     */
    public Map<String, Object> getKafkaProps() {
        return kafkaProps;
    }

    public TopicFilter getTopicFilter() {
        return topicFilter;
    }

    public ManualPartitioner getTopicPartitioner() {
        return topicPartitioner;
    }

    public RecordTranslator<K, V> getTranslator() {
        return translator;
    }

    public FirstPollOffsetStrategy getFirstPollOffsetStrategy() {
        return firstPollOffsetStrategy;
    }

    public long getPollTimeoutMs() {
        return pollTimeoutMs;
    }

    public long getPartitionRefreshPeriodMs() {
        return partitionRefreshPeriodMs;
    }

    public long getStartTimeStamp() {
        return startTimeStamp;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
            .append("kafkaProps", kafkaProps)
            .append("partitionRefreshPeriodMs", partitionRefreshPeriodMs)
            .append("pollTimeoutMs", pollTimeoutMs)
            .append("topicFilter", topicFilter)
            .append("topicPartitioner", topicPartitioner)
            .append("translator", translator)
            .append("startTimeStamp", startTimeStamp)
            .toString();
    }
}


text:
* [Description](Project-Description)
* [Themes/Features](Themes-Features)
* [Personas](Personas)
* [User Stories](User-Stories)
* [Domain Analysis](Domain-Analysis)
* [Requirements](Requirements)
* [Plan](Plan)
* [RAM](Responsibility-Assignment-Matrix)
* [Communication Plan](Communication-Plan)
* [Use Cases](https://github.com/bounswe/bounswe2016group5/wiki/Use-Cases)
* [Class Diagram](https://raw.githubusercontent.com/bounswe/bounswe2016group5/master/images/Class%20diagram.jpeg)
* [Sequence Diagrams](Sequence-Diagrams)
* [Activity Diagrams](https://github.com/bounswe/bounswe2016group5/wiki/Activity-Diagrams)
* [Mobile Mock-ups] (https://github.com/bounswe/bounswe2016group5/wiki/Mobile-Mock-ups)
* [Web Mock-ups] (https://github.com/bounswe/bounswe2016group5/wiki/Web-Mock-ups)
* [Setup Guide For Development Environments] (https://github.com/bounswe/bounswe2016group5/wiki/Setup-Guide-For-Development-Environments)
* [Test Cases](https://docs.google.com/spreadsheets/d/17_JDvX7WhxRXAYmnl69BhXH02nCzyQEJ3hEU17Vg7EY/edit?usp=sharing)
* [Test Project (just main page and our personal pages)](http://ec2-54-186-82-41.us-west-2.compute.amazonaws.com:8080/TestWebProject/)
* [Assignment6 Pages](https://github.com/bounswe/bounswe2016group5/wiki/Assignment6-Pages)

# Milestones

* [Milestone-1](https://github.com/bounswe/bounswe2016group5/wiki/Milestone-1)
* [Milestone-2](https://github.com/bounswe/bounswe2016group5/wiki/Milestone-2)

# Project Development
* **_It Will Be Developed (soon)_**

# Meeting Notes

### CmpE 352 Meeting Notes
* [Meeting 1 (15.02.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-1-(15.02.2016))
* [Meeting 2 (4.03.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-2-(4.03.2016))
* [Meeting 3 (14.03.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-3-(14.03.2016))
* [Meeting 4 (16.03.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-4-(16.03.2016))
* [Customer Meeting 1 (29.03.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Customer-Meeting-1-(29.03.2016))
* [Meeting 5 (29.03.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-5-(29.03.2016))

### CmpE 451 Meeting Notes
* [Meeting 1 (26.09.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-1-(26.09.2016))
* [Meeting 2 (29.09.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-2-(29.09.2016))
* [Meeting 3 (04.10.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-3-(04.10.2016))
* [Meeting 4 (11.10.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-4-(11.10.2016))
* [Meeting 5 (27.10.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-5-(27.10.2016))
* [Meeting 6 (10.11.2016)](https://github.com/bounswe/bounswe2016group5/wiki/Meeting-6-(10.11.2016))

# Group Members

* [Atakan Guney](https://github.com/bounswe/bounswe2016group5/wiki/Atakan-G%C3%BCney)
* [Buğra Çil](https://github.com/bounswe/bounswe2016group5/wiki/Bu%C4%9Fra-%C3%87il)
* [Burak Suyunu](https://github.com/bounswe/bounswe2016group5/wiki/Burak-Suyunu)
* [Kerim Gökarslan](https://github.com/bounswe/bounswe2016group5/wiki/Kerim-G%C3%B6karslan)
* [Ahmet Enes Bayraktar](https://github.com/bounswe/bounswe2016group5/wiki/Ahmet-Enes-Bayraktar)
* [Şeyma Ertem](https://github.com/bounswe/bounswe2016group5/wiki/Seyma-Ertem)
* [Öykü Yılmaz](https://github.com/bounswe/bounswe2016group5/wiki/Oyku-Yilmaz)
* [Şahin Batmaz](https://github.com/bounswe/bounswe2016group5/wiki/Sahin-Batmaz)
* [Ozan Bulut](https://github.com/bounswe/bounswe2016group5/wiki/Ozan-Bulut)

### Past Members

* [Sevda Çopur](https://github.com/bounswe/bounswe2016group5/wiki/Sevda-%C3%87opur)
* [Umut M. Dabager](https://github.com/bounswe/bounswe2016group5/wiki/Umut-M.-Dabager)
* [Özer Biber](https://github.com/bounswe/bounswe2016group5/wiki/%C3%96zer-Biber)

# Documentation

### CmpE 352

* [About Versioning System and Git](https://github.com/bounswe/bounswe2016group5/wiki/About-Versioning-System-and-Git)
* [Issue System](https://github.com/bounswe/bounswe2016group5/wiki/Issue-Tracking-System)
* [Agile Software Developement](https://github.com/bounswe/bounswe2016group5/wiki/Agile-Software-Development)
    * [SCRUM](SCRUM)
* [Five Dysfunctions Of a Team](Five-Dysfunctions-Of-a-Team)
* [Teamwork and Communication](Teamwork)
    * [The Marsmallow Challenge](https://github.com/bounswe/bounswe2016group5/wiki/The-Marshmallow-Challenge)
* [SDLC](Software-Development-Life-Cycle)
* [Good & Bad Practices](https://github.com/bounswe/bounswe2016group5/wiki/Good-&-Bad-Practices)
* [Peer Review for Group 1](Peer-Review-for-Group-1)

### CmpE 451


text:
const config_service = require('../../lib/configService.js');
const config_oauth2 = config_service.get_config().oauth2;

// BD to store all applicationes with their feautures
module.exports = function (sequelize, DataTypes) {
  const OAuthClient = sequelize.define(
    'OauthClient',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true
      },
      name: {
        type:
          DataTypes.STRING(255) +
          (sequelize.getDialect() === 'mysql' ? ' CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci' : ''),
        validate: { notEmpty: { msg: 'name' } }
      },
      description: {
        type:
          DataTypes.TEXT() + (sequelize.getDialect() === 'mysql' ? ' CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci' : ''),
        validate: { notEmpty: { msg: 'description' } }
      },
      secret: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4
      },
      url: {
        type:
          DataTypes.STRING(2000) +
          (sequelize.getDialect() === 'mysql' ? ' CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci' : ''),
        validate: {
          notEmpty: { msg: 'url' },
          isUnique(value, next) {
            if (config_oauth2.unique_url) {
              const self = this;
              OAuthClient.find({ where: { url: value } })
                .then(function (oauth_client) {
                  if (oauth_client && self.id !== oauth_client.id) {
                    return next('urlUsed');
                  }
                  return next();
                })
                .catch(function (err) {
                  return next(err);
                });
            } else {
              return next();
            }
          }
        }
      },
      redirect_uri: {
        type:
          DataTypes.STRING(2000) +
          (sequelize.getDialect() === 'mysql' ? ' CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci' : ''),
        validate: { notEmpty: { msg: 'redirectUri' } },
        get() {
          return this.getDataValue('redirect_uri') ? this.getDataValue('redirect_uri').split(',') : [];
        },
        set(val) {
          this.setDataValue('redirect_uri', val ? val.toString() : null);
        }
      },
      redirect_sign_out_uri: {
        type:
          DataTypes.STRING(2000) +
          (sequelize.getDialect() === 'mysql' ? ' CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci' : '')
      },
      image: {
        type: DataTypes.STRING,
        defaultValue: 'default'
      },
      grant_type: {
        type: DataTypes.STRING,
        get() {
          return this.getDataValue('grant_type') ? this.getDataValue('grant_type').split(',') : [];
        },
        set(val) {
          this.setDataValue('grant_type', val.join(','));
        }
      },
      response_type: {
        type: DataTypes.STRING,
        get() {
          return this.getDataValue('response_type') ? this.getDataValue('response_type').split(',') : [];
        },
        set(val) {
          this.setDataValue('response_type', val.join(','));
        }
      },
      token_types: {
        type: DataTypes.STRING(2000),
        defaultValue: 'bearer',
        get() {
          return this.getDataValue('token_types') ? this.getDataValue('token_types').split(',') : ['bearer'];
        },
        set(val) {
          if (val && val.length > 0) {
            val.push('bearer');
          } else {
            val = ['bearer'];
          }
          this.setDataValue('token_types', val.toString());
        }
      },
      jwt_secret: {
        type: DataTypes.STRING(2000),
        defaultValue: null
      },
      client_type: DataTypes.STRING(15),
      scope: {
        type: DataTypes.STRING(2000),
        get() {
          return this.getDataValue('scope') ? this.getDataValue('scope').split(',') : [];
        },
        set(val) {
          this.setDataValue('scope', val ? val.toString() : null);
        }
      },
      extra: DataTypes.JSON
    },
    {
      tableName: 'oauth_client',
      timestamps: false,
      underscored: true
    }
  );

  return OAuthClient;
};


text:
IN2SEC
======
__Inter-Instance Constraint Model Checker__


text:
<?php

    namespace Neoform\Entity\Record;

    use Neoform\Entity\Exception;
    use Neoform;

    /**
     * Record Collection
     */
    abstract class Collection
        extends Neoform\Entity\Collection
        implements Neoform\Entity\Record\Entity {

        /**
         * Get a collection by a given field or fields
         * folderCollection::byParent(5) will return a folder collection.
         * this is just a shortcut for folderCollection::fromPks(Dao::dao('Neoform\Folder')->byParent(5));
         *
         * @param string $name
         * @param array  $args
         *
         * @return Collection
         */
        public static function __callStatic($name, array $args) {
            $collectionClassName = '\\' . static::getNamespace() . '\\Collection';
            if ($name === 'all' || $name === 'records') {
                return $collectionClassName::fromArrays(
                    call_user_func_array(
                        [
                            Dao::dao(static::getNamespace()),
                            $name,
                        ],
                        $args
                    )
                );
            }

            return $collectionClassName::fromPks(
                call_user_func_array(
                    [
                        Dao::dao(static::getNamespace()),
                        $name,
                    ],
                    $args
                )
            );
        }

        /**
         * Create a collection an array of PKs
         *
         * @param array       $pks
         * @param string|null $mapField
         *
         * @return static
         */
        public static function fromPks(array $pks, $mapField=null) {

            if (! $pks) {
                return new static;
            }

            $infos = Dao::dao(static::getNamespace())->records($pks);

            if (! $infos) {
                return new static;
            }

            $collection     = new static;
            $modelClassName = '\\' . static::getNamespace() . '\\Model';

            foreach ($infos as $key => $info) {
                try {
                    if (is_array($info)) {
                        $collection->models[$mapField !== null ? $info[$mapField] : $key] = $modelClassName::fromArray($info);
                    }
                } catch (Exception $e) {

                }
            }

            return $collection;
        }

        /**
         * Create a collection from an array of info arrays
         *
         * @param array       $arrs
         * @param string|null $mapField
         *
         * @return static
         * @throws \Exception
         */
        public static function fromArrays(array $arrs, $mapField=null) {

            if (! $arrs) {
                return new static;
            }

            $collection     = new static;
            $modelClassName = '\\' . static::getNamespace() . '\\Model';

            foreach ($arrs as $key => $arr) {
                if (! is_array($arr)) {
                    throw new \Exception('fromArrays() only accepts arrays');
                }

                $collection->models[$mapField !== null ? $arr[$mapField] : $key] = $modelClassName::fromArray($arr);
            }

            return $collection;
        }

        /**
         * Create a collection from an array of models
         *
         * @param Model[]     $models
         * @param string|null $mapField
         *
         * @return static
         * @throws \Exception
         */
        public static function fromModels(array $models, $mapField=null) {

            if (! $models) {
                return new static;
            }

            $collection     = new static;
            $modelClassName = '\\' . static::getNamespace() . '\\Model';

            foreach ($models as $key => $model) {
                if (! ($model instanceof $modelClassName)) {
                    throw new \Exception('fromArrays() only accepts arrays');
                }

                $collection->models[$mapField !== null ? $model->get($mapField) : $key] = $model;
            }

            return $collection;
        }

        /**
         * Add a model to the collection
         *
         * @param Model $model
         * @param string|null $mapField Assign collection keys based on this field (taken from the models)
         *
         * @return $this
         */
        public function add($model, $mapField=null) {
            if ($mapField !== null) {
                $this->models[$model->get($mapField)] = $model;
            } else {
                $this->models[] = $model;
            }

            // Reset
            $this->_vars = [];

            return $this;
        }

        /**
         * Add a model to the collection by info array
         *
         * @param array $info
         * @param string|null $mapField Assign collection keys based on this field (taken from the models)
         *
         * @return $this
         */
        public function addByArray(array $info, $mapField=null) {
            $modelClassName = '\\' . static::getNamespace() . '\\Model';
            $model = $modelClassName::fromArray($info);

            if ($mapField !== null) {
                $this->models[$model->get($mapField)] = $model;
            } else {
                $this->models[] = $model;
            }

            //reset
            $this->_vars = [];

            return $this;
        }

        /**
         * Add a model to the collection by PK
         *
         * @param string|int $pk
         * @param string|null $mapField Assign collection keys based on this field (taken from the models)
         *
         * @return $this
         */
        public function addByPk($pk, $mapField=null) {
            $modelClassName = '\\' . static::getNamespace() . '\\Model';
            $model = $modelClassName::fromPk($pk);

            if ($mapField !== null) {
                $this->models[$model->get($mapField)] = $model;
            } else {
                $this->models[] = $model;
            }

            //reset
            $this->_vars = [];

            return $this;
        }

        /**
         * Remap the collection according to a certain field - this makes the key of the collection be that field
         *
         * @param string $field
         * @param bool   $ignoreNull
         *
         * @return Collection $this
         */
        public function remap($field, $ignoreNull=false) {
            $new = [];
            if ($ignoreNull) {
                foreach ($this->models as $model) {
                    if ($model->get($field) !== null) {
                        $new[$model->get($field)] = $model;
                    }
                }
            } else {
                foreach ($this->models as $model) {
                    $new[$model->get($field)] = $model;
                }
            }
            $this->models = $new;
            return $this;
        }

        /**
         * Get an array with the values of the models in the collection
         *
         * @param string      $field
         * @param string|null $key
         *
         * @return array
         */
        public function field($field, $key=null) {
            $arr = [];
            foreach ($this->models as $k => $model) {
                $arr[$key ? $model->get($key) : $k] = $model->get($field);
            }
            return $arr;
        }

        /**
         * Exports an array with all the data from the models, or select fields
         *
         * @param array|null $fields to export
         *
         * @return array
         */
        public function export(array $fields=null) {
            $arr = [];
            foreach ($this->models as $k => $model) {
                $arr[$k] = $model->export($fields);
            }
            return $arr;
        }

        /**
         * Get many groups of records all in one shot. This greatly reduces the number of requests to the cache service,
         * which can greatly speed up an application.
         *
         * @param string       $varKey    Key (in $model::$_var) that stores preloaded model data
         * @param string       $entity      eg, user
         * @param string       $by_function eg, by_comments
         * @param array|null   $order_by    array of field names (as the key) and sort direction (Neoform\Entity\Record\Dao::SORT_ASC, Neoform\Entity\Record\Dao::SORT_DESC)
         * @param integer|null $offset      get PKs starting at this offset
         * @param integer|null $limit       max number of PKs to return
         *
         * @return Collection
         * @deprecated
         */
        protected function _preload_one_to_many($varKey, $entity, $by_function, array $order_by=null, $offset=null,
                                                $limit=null) {

            $collection_name  = "\\{$entity}\\Collection";
            $model_name       = "\\{$entity}\\Model";
            $dao              = Dao::dao($entity);
            $by_function     .= '_multi';

            // Get the ids for those
            $pks_groups = $dao->$by_function($this, $order_by, $offset, $limit);
            $pks        = [];

            // make a flat array of all keys, removing dupes along the way.
            foreach ($pks_groups as $pks_group) {
                foreach ($pks_group as $pk) {
                    $pks[$pk] = $pk;
                }
            }

            // get all the records all in one shot
            $collection = $collection_name::fromPks($pks);

            // sort flat array back into grouped data again
            foreach ($pks_groups as & $pks_group) {
                foreach ($pks_group as $k => $pk) {
                    if (isset($collection[$pk])) {
                        $pks_group[$k] = $collection[$pk];
                    } else {
                        // this shouldn't actually happen... if it did, something went wrong in the DAO
                        unset($pks_group[$k]);
                    }
                }
            }

            // load the child models into the $_var of each model in this collection
            foreach ($this->models as $key => $model) {
                if (isset($pks_groups[$key])) {
                    $model->_preloadCache(
                        $model_name::_limitVarKey(
                            $varKey,
                            $order_by,
                            $offset,
                            $limit
                        ),
                        $collection_name::fromModels($pks_groups[$key])
                    );
                }
            }

            return $collection;
        }

        /**
         * Get many groups of records all in one shot. This greatly reduces the number of requests to the cache service,
         * which can greatly speed up an application.
         *
         * @param string       $varKey    Key (in $model::$_var) that stores preloaded model data
         * @param string       $entity     eg, user
         * @param string       $byFunction eg, by_comments
         * @param array|null   $orderBy    array of field names (as the key) and sort direction (Neoform\Entity\Record\Dao::SORT_ASC, Neoform\Entity\Record\Dao::SORT_DESC)
         * @param integer|null $offset     get PKs starting at this offset
         * @param integer|null $limit      max number of PKs to return
         *
         * @return Collection
         */
        protected function _preloadOneToMany($varKey, $entity, $byFunction, array $orderBy=null, $offset=null,
                                                $limit=null) {

            $collectionName = "\\{$entity}\\Collection";
            $modelName      = "\\{$entity}\\Model";
            $dao            = Dao::dao($entity);
            $byFunction    .= 'Multi';

            // Get the ids for those
            $pksGroups = $dao->{$byFunction}($this, $orderBy, $offset, $limit);
            $pks       = [];

            // make a flat array of all keys, removing dupes along the way.
            foreach ($pksGroups as $pksGroup) {
                foreach ($pksGroup as $pk) {
                    $pks[$pk] = $pk;
                }
            }

            // get all the records all in one shot
            $collection = $collectionName::fromArrays($dao->records($pks));

            // sort flat array back into grouped data again
            foreach ($pksGroups as & $pksGroup) {
                foreach ($pksGroup as $k => $pk) {
                    if (isset($collection[$pk])) {
                        $pksGroup[$k] = $collection[$pk];
                    } else {
                        // this shouldn't actually happen... if it did, something went wrong in the DAO
                        unset($pksGroup[$k]);
                    }
                }
            }

            // load the child models into the $_var of each model in this collection
            foreach ($this->models as $key => $model) {
                if (isset($pksGroups[$key])) {
                    $model->_preloadCache(
                        $modelName::_limitVarKey(
                            $varKey,
                            $orderBy,
                            $offset,
                            $limit
                        ),
                        $collectionName::fromModels($pksGroups[$key])
                    );
                }
            }

            return $collection;
        }

        /**
         * Get many groups of records all in one shot. This greatly reduces the number of requests to the cache service,
         * which can greatly speed up an application.
         *
         * @param string       $varKey       Key (in $model::$_var) that stores preloaded model data
         * @param string       $entity         eg, user_permission
         * @param string       $by_function    eg, by_user
         * @param string       $foreign_type   eg, permission
         * @param array|null   $orderBy       array of field names (as the key) and sort direction (Neoform\Entity\Record\Dao::SORT_ASC, Neoform\Entity\Record\Dao::SORT_DESC)
         * @param integer|null $offset         get PKs starting at this offset
         * @param integer|null $limit          max number of PKs to return
         *
         * @return Collection
         * @deprecated
         */
        protected function _preload_many_to_many($varKey, $entity, $by_function, $foreign_type,
                                                 array $orderBy=null, $offset=null, $limit=null) {

            $by_function              .= '_multi';
            $foreign_collection_name  = "\\{$foreign_type}\\Collection";

            // Get the ids for those
            $pks_groups = Dao::dao($entity)->$by_function($this, $orderBy, $offset, $limit);
            $pks        = [];

            // make a flat array of all keys, removing dupes along the way.
            foreach ($pks_groups as $pks_group) {
                foreach ($pks_group as $pk) {
                    $pks[$pk] = $pk;
                }
            }

            // get all the records all in one shot
            $collection = $foreign_collection_name::fromPks($pks);

            // sort flat array back into grouped data again
            foreach ($pks_groups as & $pks_group) {
                foreach ($pks_group as $k => $pk) {
                    if (isset($collection[$pk])) {
                        $pks_group[$k] = $collection[$pk];
                    } else {
                        // this shouldn't actually happen... if it did, something went wrong in the DAO
                        unset($pks_group[$k]);
                    }
                }
            }

            foreach ($this->models as $key => $model) {
                if (isset($pks_groups[$key])) {
                    $model->_preloadCache(
                        $varKey,
                        $foreign_collection_name::fromModels($pks_groups[$key])
                    );
                }
            }

            return $collection;
        }

        /**
         * Get many groups of records all in one shot. This greatly reduces the number of requests to the cache service,
         * which can greatly speed up an application.
         *
         * @param string     $varKey      Key (in $model::$_var) that stores preloaded model data
         * @param string     $entity      eg, user_permission
         * @param string     $byFunction  eg, by_user
         * @param string     $foreignType eg, permission
         * @param array|null $orderBy     array of field names (as the key) and sort direction (Neoform\Entity\Record\Dao::SORT_ASC, Neoform\Entity\Record\Dao::SORT_DESC)
         * @param int|null   $offset      get PKs starting at this offset
         * @param int|null   $limit       max number of PKs to return
         *
         * @return Collection
         */
        protected function _preloadManyToMany($varKey, $entity, $byFunction, $foreignType,
                                                 array $orderBy=null, $offset=null, $limit=null) {

            $byFunction            .= 'Multi';
            $foreignCollectionName  = "\\{$foreignType}\\Collection";

            // Get the ids for those
            $pksGroups = Dao::dao($entity)->{$byFunction}($this, $orderBy, $offset, $limit);
            $pks       = [];

            // make a flat array of all keys, removing dupes along the way.
            foreach ($pksGroups as $pksGroup) {
                foreach ($pksGroup as $pk) {
                    $pks[$pk] = $pk;
                }
            }

            // get all the records all in one shot
            $collection = $foreignCollectionName::fromPks($pks);

            // sort flat array back into grouped data again
            foreach ($pksGroups as & $pksGroup) {
                foreach ($pksGroup as $k => $pk) {
                    if (isset($collection[$pk])) {
                        $pks_group[$k] = $collection[$pk];
                    } else {
                        // this shouldn't actually happen... if it did, something went wrong in the DAO
                        unset($pksGroup[$k]);
                    }
                }
            }

            foreach ($this->models as $key => $model) {
                if (isset($pksGroups[$key])) {
                    $model->_preloadCache(
                        $varKey,
                        $foreignCollectionName::fromModels($pksGroups[$key])
                    );
                }
            }

            return $collection;
        }

        /**
         * Get many groups of records all in one shot. This greatly reduces the number of requests to the cache service,
         * which can greatly speed up an application.
         *
         * @param string $varKey Key (in $model::$_var) that stores preloaded model data
         * @param string $entity   Name of the entity
         * @param string $field    Corresponding field for that entity
         *
         * @return Collection
         * @deprecated
         */
        protected function _preload_one_to_one($varKey, $entity, $field) {

            $modelName      = "\\{$entity}\\Model";
            $collectionName = "\\{$entity}\\Collection";

            $pks = [];
            // we don't want to look up duplicates, just unique values
            foreach ($this->models as $model) {
                $pks[$model->get($field)] = $model->get($field);
            }
            $infos  = Dao::dao($entity)->records($pks);
            $models = [];

            foreach ($this->models as $key => $model) {
                $k = $model->get($field);
                if (isset($infos[$k])) {
                    $model->_preloadCache(
                        $varKey,
                        $models[$key] = $modelName::fromArray($infos[$k])
                    );
                }
            }

            return $collectionName::fromModels($models);
        }

        /**
         * Get many groups of records all in one shot. This greatly reduces the number of requests to the cache service,
         * which can greatly speed up an application.
         *
         * @param string $varKey                  Key (in $model::$_var) that stores preloaded model data
         * @param string $entity                  Name of the entity
         * @param string $fieldGetterFunctionName Corresponding field for that entity
         *
         * @return Collection
         */
        protected function _preloadOneToOne($varKey, $entity, $fieldGetterFunctionName) {

            $modelName      = "\\{$entity}\\Model";
            $collectionName = "\\{$entity}\\Collection";

            $pks = [];
            // we don't want to look up duplicates, just unique values
            foreach ($this->models as $model) {
                $pks[$model->{$fieldGetterFunctionName}()] = $model->{$fieldGetterFunctionName}();
            }
            $infos  = Dao::dao($entity)->records($pks);
            $models = [];

            foreach ($this->models as $key => $model) {
                $k = $model->{$fieldGetterFunctionName}();
                if (isset($infos[$k])) {
                    $model->_preloadCache(
                        $varKey,
                        $models[$key] = $modelName::fromArray($infos[$k])
                    );
                }
            }

            return $collectionName::fromModels($models);
        }

        /**
         * Preload record/link counts based on fields
         *
         * @param string $varKey
         * @param string $entity
         * @param string $foreign_field_name field name used to filter the dao count
         *
         * @return Collection
         * @deprecated
         */
        protected function _preload_counts($varKey, $entity, $foreign_field_name) {

            $pk = static::getPrimaryKeyName();

            // Build list of keyvals to filter the counts
            $fieldvals = [];
            foreach ($this->models as $k => $model) {
                $fieldvals[$k] = [ $foreign_field_name => $model->get($pk), ];
            }

            // Get the counts (as a multi get)
            $counts = Dao::dao($entity)->countMulti($fieldvals);

            // Insert the counts into each model's $_var cache
            foreach ($this->models as $k => $model) {
                $model->_preloadCache(
                    $model::_countVarKey(
                        $varKey,
                        $fieldvals[$k]
                    ),
                    $counts[$k]
                );
            }

            // Return the counts
            return $counts;
        }

        /**
         * Preload record/link counts based on fields
         *
         * @param string $varKey
         * @param string $entity
         * @param string $foreign_field_name field name used to filter the dao count
         *
         * @return Collection
         */
        protected function _preloadCounts($varKey, $entity, $foreignFieldName) {

            $pk = static::getPrimaryKeyName();

            // Build list of keyvals to filter the counts
            $fieldVals = [];
            foreach ($this->models as $k => $model) {
                $fieldVals[$k] = [ $foreignFieldName => $model->get($pk), ];
            }

            // Get the counts (as a multi get)
            $counts = Dao::dao($entity)->countMulti($fieldVals);

            // Insert the counts into each model's $_var cache
            foreach ($this->models as $k => $model) {
                $model->_preloadCache(
                    $model::_countVarKey(
                        $varKey,
                        $fieldVals[$k]
                    ),
                    $counts[$k]
                );
            }

            // Return the counts
            return $counts;
        }
    }


text:
using System.Net.Http;
using AlternativePayments.Infrastructure.Constants;

namespace AlternativePayments
{
    public class PaymentService : BaseService<Payment>
    {
        public PaymentService(HttpClient client, string apiUrl)
            : base(client, apiUrl)
        {
        }

        public Payment Get(string paymentId)
        {
            return GetResource($"{Urls.Payments}/{paymentId}");
        }

        public Payment Create(Payment payment)
        {
            return CreateResource(Urls.Payments, payment);
        }
    }
}


text:
<?php

namespace app\modules\admin\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\admin\models\Lang;

/**
 * LangSearch represents the model behind the search form about `app\modules\admin\models\Lang`.
 */
class LangSearch extends Lang
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'default', 'date_update', 'date_create'], 'integer'],
            [['url', 'local', 'name'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Lang::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'default' => $this->default,
            'date_update' => $this->date_update,
            'date_create' => $this->date_create,
        ]);

        $query->andFilterWhere(['like', 'url', $this->url])
            ->andFilterWhere(['like', 'local', $this->local])
            ->andFilterWhere(['like', 'name', $this->name]);

        return $dataProvider;
    }
}