text:
// -
// Copyright 2009 Colin Percival
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
// The code in this file is taken from a file which was originally written by Colin Percival as part of the Tarsnap
// online backup system.
// -

#ifndef _CRYPTO_SCRYPT_H_
#define _CRYPTO_SCRYPT_H_

#include <stdint.h>
#include <unistd.h>

/**
 * crypto_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):
 * Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,
 * p, buflen) and write the result into buf.  The parameters r, p, and buflen
 * must satisfy r * p < 2^30 and buflen <= (2^32 - 1) * 32.  The parameter N
 * must be a power of 2 greater than 1.
 *
 * Return 0 on success; or -1 on error.
 */
int crypto_scrypt(const uint8_t*, size_t, const uint8_t*, size_t, uint64_t, uint32_t, uint32_t, uint8_t*, size_t);

#endif

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='utf-8'?>
<TEI xmlns="http://www.tei-c.org/ns/1.0" xml:id="PrL-0285">
  <teiHeader>
      <fileDesc>
         <titleStmt>
            <title>Private Letter: Date?: to McLean</title>
            <author>
               <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/9614/">William Colenso</name>
            </author>
         </titleStmt>
         <publicationStmt>

         </publicationStmt>
         <sourceDesc>

ATL Object #1015589 from MS-Papers-0032-0222.

         </sourceDesc>
      </fileDesc>
      <profileDesc>
         <correspDesc>
            <correspAction type="received">
               <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/70546/">McLean</name>
            </correspAction>
         </correspDesc>
         <creation xmlns:tei="http://www.tei-c.org/ns/1.0"/>
      </profileDesc>
  </teiHeader>
  <text>
      <front>

Date?: to McLean<note xml:id="ftn2-213" place="foot" n="213">ATL Object #1015589 from MS-Papers-0032-0222.</note>

      </front>

Monday 15

My dear Mr. McLean

Many thanks for your kind intimation. That party however is <hi rend="italic">clear</hi>—I would that I could say as much to those S. of Ahuriri.

When shall I see you again? I have looked in twice—but you were not. One of those times however I was deceived (<hi rend="italic">unintentionally</hi>) by Capt. Carter—as you were within.

Tomorrow early, I leave for Clive to inspect the School there. I will call on you at ½ past IV. this evening.

     Ever yrs truly

             W. Colenso.

  </text>
</TEI>


text:
import java.io.*;
import java.util.Stack.*;
import java.util.*;

/**
 * This class recieves a filename for a data text file
 * - this data file is merely an ordered list of data files - one
 * for every curve pertaining to a three-D plot.
 * Job of this procedure is to return a vector-of-vectors i.e.,
 * a sequential list of vectors - each vector in the list
 * corresponding to the data contained in the file pointed
 * to by the filenames in the original list. The vector
 * of vectors is ordered - i.e., first filename in original list
 * corresponds to first vector in vector of vectors.
 *
 * Furthermore, the data in each vector is ordered - in ascending
 * x-value.
 *
 * @see XYDataPoint.class
 */
public class GetXYVectorOfVectors
  {
  private Vector rtn;
  private Vector filelist;
  /**
   * Returns the ordered vector of vectors to the calling object.
   */
  public Vector getVector ()
    {
    return rtn;
    }

  public GetXYVectorOfVectors (String filename)
    {
    ReadTextFile rtf = new ReadTextFile(filename);
    Object dummy;

    rtn = new Vector();
    filelist = rtf.getTextFileVector ();
    Enumeration e = filelist.elements ();

    while (e.hasMoreElements ())
      {
      dummy = e.nextElement ();
      if (dummy instanceof String)
        {
	GetOrderedXYDataFileVector g = new GetOrderedXYDataFileVector
                                           ((String)dummy);
        rtn.addElement(g.getVector());
	}
      }
    }
  }


text:
package com.google.api.ads.adwords.jaxws.v201402.video;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import com.google.api.ads.adwords.jaxws.v201402.cm.Page;

/**
 *
Java class for VideoCampaignCriterionPage complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="VideoCampaignCriterionPage">
 *   <complexContent>
 *     <extension base="{https://adwords.google.com/api/adwords/cm/v201402}Page">
 *       <sequence>
 *         <element name="entries" type="{https://adwords.google.com/api/adwords/video/v201402}VideoCampaignCriterion" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="summaryStats" type="{https://adwords.google.com/api/adwords/video/v201402}VideoEntityStats" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VideoCampaignCriterionPage", propOrder = {
    "entries",
    "summaryStats"
})
public class VideoCampaignCriterionPage
    extends Page
{

    protected List<VideoCampaignCriterion> entries;
    protected List<VideoEntityStats> summaryStats;

    /**
     * Gets the value of the entries property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the entries property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getEntries().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link VideoCampaignCriterion }
     *
     *
     */
    public List<VideoCampaignCriterion> getEntries() {
        if (entries == null) {
            entries = new ArrayList<VideoCampaignCriterion>();
        }
        return this.entries;
    }

    /**
     * Gets the value of the summaryStats property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the summaryStats property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getSummaryStats().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link VideoEntityStats }
     *
     *
     */
    public List<VideoEntityStats> getSummaryStats() {
        if (summaryStats == null) {
            summaryStats = new ArrayList<VideoEntityStats>();
        }
        return this.summaryStats;
    }

}


text:
class ShopStore < ActiveRecord::Base
  has_many :orders, dependent: :destroy
end


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

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

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

"""

import os.path

from resource_management.core.environment import Environment
from resource_management.core.source import InlineTemplate
from resource_management.core.source import Template
from resource_management.core.resources import Execute
from resource_management.core.resources.service import Service
from resource_management.core.resources.service import ServiceConfig
from resource_management.core.resources.system import Directory
from resource_management.core.resources.system import File
from resource_management.libraries.script import Script
from resource_management.libraries.resources import PropertiesFile
from resource_management.libraries.functions import format

from ambari_commons import OSConst
from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl

@OsFamilyFuncImpl(os_family = OsFamilyImpl.DEFAULT)
def falcon(type, action = None):
  import params

  if action == 'config':
    Directory(params.falcon_pid_dir,
      owner = params.falcon_user,
      recursive = True)

    Directory(params.falcon_log_dir,
      owner = params.falcon_user,
      recursive = True)

    Directory(params.falcon_webapp_dir,
      owner = params.falcon_user,
      recursive = True)

    Directory(params.falcon_home,
      owner = params.falcon_user,
      recursive = True)

    Directory(params.etc_prefix_dir,
      mode = 0755,
      recursive = True)

    Directory(params.falcon_conf_dir,
      owner = params.falcon_user,
      recursive = True)

    File(params.falcon_conf_dir + '/falcon-env.sh',
      content = InlineTemplate(params.falcon_env_sh_template),
      owner = params.falcon_user,
      group=params.user_group,
    )

    File(params.falcon_conf_dir + '/client.properties',
      content = Template('client.properties.j2'),
      mode = 0644,
      owner = params.falcon_user)

    PropertiesFile(params.falcon_conf_dir + '/runtime.properties',
      properties = params.falcon_runtime_properties,
      mode = 0644,
      owner = params.falcon_user)

    PropertiesFile(params.falcon_conf_dir + '/startup.properties',
      properties = params.falcon_startup_properties,
      mode = 0644,
      owner = params.falcon_user)

    if params.falcon_graph_storage_directory:
      Directory(params.falcon_graph_storage_directory,
        owner = params.falcon_user,
        group = params.user_group,
        mode = 0775,
        recursive = True,
        cd_access = "a")

    if params.falcon_graph_serialize_path:
      Directory(params.falcon_graph_serialize_path,
        owner = params.falcon_user,
        group = params.user_group,
        mode = 0775,
        recursive = True,
        cd_access = "a")

  if type == 'server':
    if action == 'config':
      if params.store_uri[0:4] == "hdfs":
        params.HdfsResource(params.store_uri,
          type = "directory",
          action = "create_on_execute",
          owner = params.falcon_user,
          mode = 0755)
      elif params.store_uri[0:4] == "file":
        Directory(params.store_uri[7:],
          owner = params.falcon_user,
          recursive = True)

      # TODO change to proper mode
      params.HdfsResource(params.flacon_apps_dir,
        type = "directory",
        action = "create_on_execute",
        owner = params.falcon_user,
        mode = 0777)

      if params.falcon_store_uri[0:4] == "hdfs":
        params.HdfsResource(params.falcon_store_uri,
          type = "directory",
          action = "create_on_execute",
          owner = params.falcon_user,
          mode = 0755)
      elif params.falcon_store_uri[0:4] == "file":
        Directory(params.falcon_store_uri[7:],
          owner = params.falcon_user,
          recursive = True)

      if params.supports_hive_dr:
        params.HdfsResource(params.dfs_data_mirroring_dir,
          type = "directory",
          action = "create_on_execute",
          owner = params.falcon_user,
          group = params.proxyuser_group,
          recursive_chown = True,
          recursive_chmod = True,
          mode = 0770,
          source = params.local_data_mirroring_dir)

      params.HdfsResource(None, action = "execute")
      Directory(params.falcon_local_dir,
        owner = params.falcon_user,
        recursive = True,
        cd_access = "a")

      if params.falcon_embeddedmq_enabled == True:
        Directory(
          os.path.abspath(os.path.join(params.falcon_embeddedmq_data, "..")),
          owner = params.falcon_user,
          recursive = True)

        Directory(params.falcon_embeddedmq_data,
          owner = params.falcon_user,
          recursive = True)

    # although Falcon's falcon-config.sh will use 'which hadoop' to figure
    # this out, in an upgraded cluster, it's possible that 'which hadoop'
    # still points to older binaries; it's safer to just pass in the
    # hadoop home directory to use
    environment_dictionary = { "HADOOP_HOME" : params.hadoop_home_dir }

    if action == 'start':
      Execute(format('{falcon_home}/bin/falcon-start -port {falcon_port}'),
        user = params.falcon_user,
        path = params.hadoop_bin_dir,
        environment=environment_dictionary)

    if action == 'stop':
      Execute(format('{falcon_home}/bin/falcon-stop'),
        user = params.falcon_user,
        path = params.hadoop_bin_dir,
        environment=environment_dictionary)

      File(params.server_pid_file, action = 'delete')

@OsFamilyFuncImpl(os_family = OSConst.WINSRV_FAMILY)
def falcon(type, action = None):
  import params

  if action == 'config':
    env = Environment.get_instance()
    # These 2 parameters are used in ../templates/client.properties.j2
    env.config.params["falcon_host"] = params.falcon_host
    env.config.params["falcon_port"] = params.falcon_port
    File(os.path.join(params.falcon_conf_dir, 'falcon-env.sh'),
      content = InlineTemplate(params.falcon_env_sh_template))

    File(os.path.join(params.falcon_conf_dir, 'client.properties'),
      content = Template('client.properties.j2'))

    PropertiesFile(os.path.join(params.falcon_conf_dir, 'runtime.properties'),
      properties = params.falcon_runtime_properties)

    PropertiesFile(os.path.join(params.falcon_conf_dir, 'startup.properties'),
      properties = params.falcon_startup_properties)

  if type == 'server':
    ServiceConfig(params.falcon_win_service_name,
      action = "change_user",
      username = params.falcon_user,
      password = Script.get_password(params.falcon_user))

    if action == 'start':
      Service(params.falcon_win_service_name, action = "start")

    if action == 'stop':
      Service(params.falcon_win_service_name, action = "stop")


text:
#ifndef BARRIER_H
#define BARRIER_H

/*
 * This used to be a separate file, full of compiler/architecture
 * dependent defines, but it's not included in the atomics.h
 * infrastructure and just kept for backward compatibility.
 */
#include "port/atomics.h"

#endif   /* BARRIER_H */


text:
@implementation UIImage (Additions)

- (UIImage *)stretchableImageFromCenter {
    return [self stretchableImageWithLeftCapWidth:self.size.width/2 topCapHeight:self.size.height/2];
}

- (UIImage*)scaleToWidth:(CGFloat)width {
    if (width >= self.size.width) {
        return self;
    }
    CGSize newSize;
    newSize.width = width;
    newSize.height = self.size.height/self.size.width*newSize.width;

    UIGraphicsBeginImageContext(newSize);
    [self drawInRect:CGRectMake(0, 0, floorf(newSize.width)+1, floorf(newSize.height)+1)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

@end


text:
package codeu.chat.server;

import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;

import codeu.chat.common.BasicController;
import codeu.chat.common.Conversation;
import codeu.chat.common.Message;
import codeu.chat.common.User;
import codeu.chat.util.Uuid;

public final class BasicControllerTest {

  private Model model;
  private BasicController controller;

  @Before
  public void doBefore() {
    model = new Model();
    controller = new Controller(Uuid.NULL, model);
  }

  @Test
  public void testAddUser() {

    final User user = controller.newUser("user", "password");

    assertFalse(
        "Check that user has a valid reference",
        user == null);
  }

  @Test
  public void testAddConversation() {

    final User user = controller.newUser("user", "password");

    assertFalse(
        "Check that user has a valid reference",
        user == null);

    final Conversation conversation = controller.newConversation(
        "conversation",
        user.id);

    assertFalse(
        "Check that conversation has a valid reference",
        conversation == null);
  }

  @Test
  public void testAddMessage() {

    final User user = controller.newUser("user", "password");

    assertFalse(
        "Check that user has a valid reference",
        user == null);

    final Conversation conversation = controller.newConversation(
        "conversation",
        user.id);

    assertFalse(
        "Check that conversation has a valid reference",
        conversation == null);

    final Message message = controller.newMessage(
        user.id,
        conversation.id,
        "Hello World");

    assertFalse(
        "Check that the message has a valid reference",
        message == null);
  }
}


text:
package ru.stqa.selenium.page_objects_hw.tests;

import org.junit.Before;
import ru.stqa.selenium.page_objects_hw.app.Application;

import java.io.IOException;

public class TestBase {

  public static ThreadLocal<Application> tlApp = new ThreadLocal<>();
  public Application app;

  @Before
  public void start() throws IOException {
    if (tlApp.get() != null) {
      app = tlApp.get();
      return;
    }

    app = new Application();
    tlApp.set(app);

    Runtime.getRuntime().addShutdownHook(
            new Thread(() -> {
              app.quit();
              app = null;
            }));
  }
}


text:
namespace SunflowerUtil
{

std::fstream GetFileStream(const boost::filesystem::path filePath, std::ios_base::openmode openMode)
{
    try
    {
        std::fstream fileStream;
        fileStream.exceptions(std::ios_base::failbit | std::ios_base::badbit | std::ios_base::eofbit);
        fileStream.open(filePath.c_str(), openMode);
        return fileStream;
    }
    catch(std::ios_base::failure e)
    {
        e_throw(FileLoadException() << error_description_info("Could not load file: " + String::Narrow(filePath.c_str())) << inner_exception(boost::current_exception()));
    }
}

std::vector<char> LoadFile(const boost::filesystem::path filePath)
{
    try
    {
        auto fileStream = GetFileStream(filePath);
        fileStream.seekg(0, std::ios::end);
        std::streamsize size = fileStream.tellg();
        fileStream.seekg(0, std::ios::beg);

        std::vector<char> buffer(size);
        fileStream.read(&buffer[0], size);

        return buffer;
    }
    catch(std::ios_base::failure)
    {
        e_throw(FileLoadException() << error_description_info("Could not load file: " + String::Narrow(filePath.c_str())) << inner_exception(boost::current_exception()));
    }
}

}


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

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.workmail.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DeregisterFromWorkMailResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeregisterFromWorkMailResultJsonUnmarshaller implements Unmarshaller<DeregisterFromWorkMailResult, JsonUnmarshallerContext> {

    public DeregisterFromWorkMailResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        DeregisterFromWorkMailResult deregisterFromWorkMailResult = new DeregisterFromWorkMailResult();

        return deregisterFromWorkMailResult;
    }

    private static DeregisterFromWorkMailResultJsonUnmarshaller instance;

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


text:
using System;
using System.Diagnostics;
using System.Globalization;

namespace Octokit
{
    /// <summary>
    /// Describes the current download state of a pre-receive environment image.
    /// </summary>
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class PreReceiveEnvironmentDownload
    {
        public PreReceiveEnvironmentDownload()
        { }

        public PreReceiveEnvironmentDownload(string url, PreReceiveEnvironmentDownloadState state, string message, DateTimeOffset? downloadedAt)
        {
            Url = url;
            State = state;
            Message = message;
            DownloadedAt = downloadedAt;
        }

        /// <summary>
        /// URL to the download status for a pre-receive environment.
        /// </summary>
        public string Url { get; private set; }

        /// <summary>
        /// The state of the most recent download.
        /// </summary>
        public StringEnum<PreReceiveEnvironmentDownloadState> State { get; private set; }

        /// <summary>
        /// On failure, this will have any error messages produced.
        /// </summary>
        public string Message { get; private set; }

        /// <summary>
        /// The time when the most recent download started.
        /// </summary>
        public DateTimeOffset? DownloadedAt { get; private set; }

        internal string DebuggerDisplay
        {
            get { return string.Format(CultureInfo.InvariantCulture, "State: {0} Message: {1}", State, Message); }
        }
    }
}


text:
using System.Composition;
using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Microsoft.ApiDesignGuidelines.Analyzers
{
    /// <summary>
    /// CA1044: Properties should not be write only
    /// </summary>
    [ExportCodeFixProvider(LanguageNames.CSharp), Shared]
    public sealed class CSharpPropertiesShouldNotBeWriteOnlyFixer : PropertiesShouldNotBeWriteOnlyFixer
    {

    }
}


text:
package nom.bdezonia.zorbage.algebra;

/**
 *
 * @author Barry DeZonia
 *
 * @param <U>
 */
public interface ConstructibleFromInt<U> {

	U construct(int... vals);
}


text:
title: Overview
---

## Overview

PromCon 2018 is the third conference dedicated to the
[Prometheus monitoring system](https://prometheus.io/). It will take place
August 9 & 10 (Thu & Fri)
at Google Munich as a single-track event with space for 220 attendees.

PromCon aims to connect Prometheus users and developers from around the world in
order to exchange knowledge, best practices, and experience gained around using
Prometheus. We also want to collaborate to build a community and grow
professional connections around systems and service monitoring.

Get an impression of last year's PromCon 2017:

<%= youtube_player("4Pr-z8-r1eo") %>

## Registration

Registration for PromCon 2018 is closed.

## Our sponsors

A big thank you to all of our sponsors who helped make PromCon 2018 happen!

Diamond

Venue

Venue Food & Social

Gold

Silver

Diversity

## Contact

PromCon is organized by the [Prometheus developer
community](https://prometheus.io/community/). For PromCon-related inquiries,
please contact the [PromCon team](mailto:promcon-organizers@googlegroups.com).
This year's edition is lead by [Richard "RichiH" Hartmann](speakers/richard-hartmann/).


text:
package org.apache.shardingsphere.shardingscaling.postgresql.wal.event;

import lombok.Getter;
import lombok.Setter;

import java.util.List;

/**
 * Update row event.
 */
@Setter
@Getter
public final class UpdateRowEvent extends AbstractRowEvent {

    private List<Object> afterRow;
}


text:
package com.spotify.heroic.cluster;

import com.spotify.heroic.QueryOptions;
import com.spotify.heroic.aggregation.AggregationInstance;
import com.spotify.heroic.common.DateRange;
import com.spotify.heroic.common.RangeFilter;
import com.spotify.heroic.common.Series;
import com.spotify.heroic.filter.Filter;
import com.spotify.heroic.metadata.CountSeries;
import com.spotify.heroic.metadata.DeleteSeries;
import com.spotify.heroic.metadata.FindKeys;
import com.spotify.heroic.metadata.FindSeries;
import com.spotify.heroic.metadata.FindTags;
import com.spotify.heroic.metadata.MetadataBackend;
import com.spotify.heroic.metadata.MetadataManager;
import com.spotify.heroic.metric.MetricBackendGroup;
import com.spotify.heroic.metric.MetricManager;
import com.spotify.heroic.metric.MetricType;
import com.spotify.heroic.metric.ResultGroups;
import com.spotify.heroic.metric.WriteMetric;
import com.spotify.heroic.metric.WriteResult;
import com.spotify.heroic.suggest.KeySuggest;
import com.spotify.heroic.suggest.MatchOptions;
import com.spotify.heroic.suggest.SuggestBackend;
import com.spotify.heroic.suggest.SuggestManager;
import com.spotify.heroic.suggest.TagKeyCount;
import com.spotify.heroic.suggest.TagSuggest;
import com.spotify.heroic.suggest.TagValueSuggest;
import com.spotify.heroic.suggest.TagValuesSuggest;
import eu.toolchain.async.AsyncFramework;
import eu.toolchain.async.AsyncFuture;
import lombok.RequiredArgsConstructor;
import lombok.ToString;

import javax.inject.Inject;
import java.util.List;
import java.util.Optional;

@ToString(exclude = {"async", "metrics", "metadata", "suggest"})
public class LocalClusterNode implements ClusterNode {
    private final AsyncFramework async;
    private final NodeMetadata localMetadata;
    private final MetricManager metrics;
    private final MetadataManager metadata;
    private final SuggestManager suggest;

    @Inject
    public LocalClusterNode(
        AsyncFramework async, NodeMetadata localMetadata, MetricManager metrics,
        MetadataManager metadata, SuggestManager suggest
    ) {
        this.async = async;
        this.localMetadata = localMetadata;
        this.metrics = metrics;
        this.metadata = metadata;
        this.suggest = suggest;
    }

    @Override
    public NodeMetadata metadata() {
        return localMetadata;
    }

    @Override
    public AsyncFuture<Void> close() {
        return async.resolved(null);
    }

    @Override
    public Group useGroup(String group) {
        return new TracingClusterNodeGroup(LocalClusterNode.class, new LocalGroup(group));
    }

    @RequiredArgsConstructor
    private final class LocalGroup implements ClusterNode.Group {
        private final String group;

        @Override
        public ClusterNode node() {
            return LocalClusterNode.this;
        }

        @Override
        public AsyncFuture<ResultGroups> query(
            MetricType source, Filter filter, DateRange range, AggregationInstance aggregation,
            QueryOptions options
        ) {
            return metrics().query(source, filter, range, aggregation, options);
        }

        @Override
        public AsyncFuture<FindTags> findTags(RangeFilter filter) {
            return metadata().findTags(filter);
        }

        @Override
        public AsyncFuture<FindKeys> findKeys(RangeFilter filter) {
            return metadata().findKeys(filter);
        }

        @Override
        public AsyncFuture<FindSeries> findSeries(RangeFilter filter) {
            return metadata().findSeries(filter);
        }

        @Override
        public AsyncFuture<DeleteSeries> deleteSeries(RangeFilter filter) {
            return metadata().deleteSeries(filter);
        }

        @Override
        public AsyncFuture<CountSeries> countSeries(RangeFilter filter) {
            return metadata().countSeries(filter);
        }

        @Override
        public AsyncFuture<TagKeyCount> tagKeyCount(RangeFilter filter) {
            return suggest().tagKeyCount(filter);
        }

        @Override
        public AsyncFuture<TagSuggest> tagSuggest(
            RangeFilter filter, MatchOptions options, Optional<String> key, Optional<String> value
        ) {
            return suggest().tagSuggest(filter, options, key, value);
        }

        @Override
        public AsyncFuture<KeySuggest> keySuggest(
            RangeFilter filter, MatchOptions options, Optional<String> key
        ) {
            return suggest().keySuggest(filter, options, key);
        }

        @Override
        public AsyncFuture<TagValuesSuggest> tagValuesSuggest(
            RangeFilter filter, List<String> exclude, int groupLimit
        ) {
            return suggest().tagValuesSuggest(filter, exclude, groupLimit);
        }

        @Override
        public AsyncFuture<TagValueSuggest> tagValueSuggest(
            RangeFilter filter, Optional<String> key
        ) {
            return suggest().tagValueSuggest(filter, key);
        }

        @Override
        public AsyncFuture<WriteResult> writeSeries(DateRange range, Series series) {
            return metadata().write(series, range);
        }

        @Override
        public AsyncFuture<WriteResult> writeMetric(WriteMetric write) {
            return metrics().write(write);
        }

        private SuggestBackend suggest() {
            return suggest.useGroup(group);
        }

        private MetadataBackend metadata() {
            return metadata.useGroup(group);
        }

        private MetricBackendGroup metrics() {
            return metrics.useGroup(group);
        }
    }
}


text:
#ifndef LIBBARRELFISH_PMAP_PRIV_H
#define LIBBARRELFISH_PMAP_PRIV_H

/**
 * \brief internal mapping function. This assumes that enough slabs are
 * available for metadata.
 */
errval_t do_map(struct pmap *pmap, genvaddr_t vaddr,
                struct capref frame, size_t offset, size_t size,
                vregion_flags_t flags, size_t *retoff, size_t *retsize);

/**
 * \brief return the number of slabs required for mapping a region of size
 * `bytes` with small pages.
 */
size_t max_slabs_required(size_t bytes);

errval_t pmap_slab_refill(struct pmap *pmap, struct slab_allocator *slab,
                          size_t max_slabs_for_mapping);

errval_t pmap_vnode_mgmt_current_init(struct pmap *pmap);

static inline void
set_mapping_cap(struct pmap *pmap, struct vnode *vnode,
                struct vnode *root, uint16_t entry)
{
    assert(root->v.is_vnode);
    assert(entry < PTABLE_ENTRIES);
#ifdef GLOBAL_MCN
    vnode->v.mapping.cnode = root->u.vnode.mcnode[entry / L2_CNODE_SLOTS];
    vnode->v.mapping.slot  = entry % L2_CNODE_SLOTS;
    assert(!cnoderef_is_null(vnode->v.mapping.cnode));
    assert(!capref_is_null(vnode->v.mapping));
#else
    /* just use the slot allocator associated with the pmap. */
    errval_t err;
    err = pmap->slot_alloc->alloc(pmap->slot_alloc, &vnode->v.mapping);
    // TODO: error propagation
    assert(err_is_ok(err));
#endif
}

#endif // LIBBARRELFISH_PMAP_PRIV_H


text:
iOSBasics
=========

Examples of iOSBasics captured here


text:
//
// MessageExtensions.cs
//
// Author:
//   Eric Maupin <me@ermau.com>
//
// Copyright (c) 2011 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.IO;
using NUnit.Framework;

namespace Tempest.Tests
{
	public static class MessageExtensions
	{
		public static T AssertLengthMatches<T> (this T self)
			where T : Message, new()
		{
			if (self == null)
				throw new ArgumentNullException ("self");

			var stream = new MemoryStream (20480);
			var writer = new StreamValueWriter (stream);
			var reader = new StreamValueReader (stream);

			var msg = new T();
			var context = SerializationContextTests.GetContext (msg.Protocol);

			self.WritePayload (context, writer);
			long len = stream.Position;
			stream.Position = 0;

			msg.ReadPayload (context, reader);
			Assert.AreEqual (len, stream.Position);

			return msg;
		}
	}
}


text:
package controllers

import (
	"encoding/json"

	"github.com/quintilesims/d.ims.io/models"
	"github.com/zpatrick/fireball"
	"github.com/zpatrick/go-plugin-swagger"
)

type SwaggerController struct{}

func NewSwaggerController() *SwaggerController {
	return &SwaggerController{}
}

func (s *SwaggerController) Routes() []*fireball.Route {
	routes := []*fireball.Route{
		{
			Path: "/swagger.json",
			Handlers: fireball.Handlers{
				"GET": s.serveSwaggerJSON,
			},
		},
	}

	return routes
}

func (s *SwaggerController) serveSwaggerJSON(c *fireball.Context) (fireball.Response, error) {
	spec := swagger.Spec{
		SwaggerVersion: "2.0",
		Host:           c.Request.Host,
		Schemes:        []string{"https", "http"},
		Info: &swagger.Info{
			Title:   "D.IMS.IO",
			Version: "1.0.0",
		},
		Tags: []swagger.Tag{
			{
				Name:        "Token",
				Description: "Methods for Tokens",
			},
			{
				Name:        "Repository",
				Description: "Methods for Repositories",
			},
			{
				Name:        "Image",
				Description: "Methods for Images",
			},
			{
				Name:        "Account",
				Description: "Methods for Account Access",
			},
		},
		Paths: map[string]swagger.Path{
			"/token": map[string]swagger.Method{
				"post": {
					Tags:       []string{"Token"},
					Summary:    "Create a new Token",
					Security:   swagger.BasicAuthSecurity("login"),
					Parameters: []swagger.Parameter{},
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
							Schema:      swagger.NewObjectSchema("CreateTokenResponse"),
						},
					},
				},
			},
			"/token/{token}": map[string]swagger.Method{
				"delete": {
					Tags:     []string{"Token"},
					Summary:  "Delete a Token",
					Security: swagger.BasicAuthSecurity("login"),
					Parameters: []swagger.Parameter{
						swagger.NewStringPathParam("token", "The token to delete", true),
					},
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
						},
					},
				},
			},
			"/repository": map[string]swagger.Method{
				"get": {
					Tags:     []string{"Repository"},
					Summary:  "List all Repositories",
					Security: swagger.BasicAuthSecurity("login"),
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
							Schema:      swagger.NewObjectSchema("ListRepositoriesResponse"),
						},
					},
				},
			},
			"/repository/{owner}": map[string]swagger.Method{
				"get": {
					Tags:     []string{"Repository"},
					Summary:  "List all Repositories for an Owner",
					Security: swagger.BasicAuthSecurity("login"),
					Parameters: []swagger.Parameter{
						swagger.NewStringPathParam("owner", "Owner of the Repositories", true),
					},
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
							Schema:      swagger.NewObjectSchema("ListRepositoriesResponse"),
						},
					},
				},
				"post": {
					Tags:     []string{"Repository"},
					Summary:  "Create a new Repository",
					Security: swagger.BasicAuthSecurity("login"),
					Parameters: []swagger.Parameter{
						swagger.NewStringPathParam("owner", "Owner for the Repository", true),
						swagger.NewBodyParam("CreateRepositoryRequest", "none", true),
					},
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
							Schema:      swagger.NewObjectSchema("CreateRepositoryResponse"),
						},
					},
				},
			},
			"/repository/{owner}/{name}": map[string]swagger.Method{
				"get": {
					Tags:     []string{"Repository"},
					Summary:  "Describe a Repository",
					Security: swagger.BasicAuthSecurity("login"),
					Parameters: []swagger.Parameter{
						swagger.NewStringPathParam("owner", "Owner of the Repository", true),
						swagger.NewStringPathParam("name", "Name of the Repository", true),
					},
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
							Schema:      swagger.NewObjectSchema("Repository"),
						},
					},
				},
				"delete": {
					Tags:     []string{"Repository"},
					Summary:  "Delete a Repository",
					Security: swagger.BasicAuthSecurity("login"),
					Parameters: []swagger.Parameter{
						swagger.NewStringPathParam("owner", "Owner of the Repository", true),
						swagger.NewStringPathParam("name", "Name of the Repository", true),
					},
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
						},
					},
				},
			},
			"/repository/{owner}/{name}/image": map[string]swagger.Method{
				"get": {
					Tags:    []string{"Image"},
					Summary: "List all images in a repository",
					Parameters: []swagger.Parameter{
						swagger.NewStringPathParam("owner", "Owner of the Repository", true),
						swagger.NewStringPathParam("name", "Name of the Repository", true),
					},
					Security: swagger.BasicAuthSecurity("login"),
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
							Schema:      swagger.NewObjectSchema("ListImagesResponse"),
						},
					},
				},
			},
			"/repository/{owner}/{name}/image/{tag}": map[string]swagger.Method{
				"get": {
					Tags:    []string{"Image"},
					Summary: "Describe an Image",
					Parameters: []swagger.Parameter{
						swagger.NewStringPathParam("owner", "Owner of the Repository", true),
						swagger.NewStringPathParam("name", "Name of the Repository", true),
						swagger.NewStringPathParam("tag", "Tag of the Image to view", true),
					},
					Security: swagger.BasicAuthSecurity("login"),
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
							Schema:      swagger.NewObjectSchema("Image"),
						},
					},
				},
				"delete": {
					Tags:    []string{"Image"},
					Summary: "Delete an Image",
					Parameters: []swagger.Parameter{
						swagger.NewStringPathParam("owner", "Owner of the Repository", true),
						swagger.NewStringPathParam("name", "Name of the Repository", true),
						swagger.NewStringPathParam("tag", "Tag of the Image to delete", true),
					},
					Security: swagger.BasicAuthSecurity("login"),
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
						},
					},
				},
			},
			"/account": map[string]swagger.Method{
				"get": {
					Tags:     []string{"Account"},
					Summary:  "List all accounts that can access all the repositories",
					Security: swagger.BasicAuthSecurity("login"),
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
							Schema:      swagger.NewObjectSchema("ListAccountsResponse"),
						},
					},
				},
				"post": {
					Tags:     []string{"Account"},
					Summary:  "Grant access to an account",
					Security: swagger.BasicAuthSecurity("login"),
					Parameters: []swagger.Parameter{
						swagger.NewBodyParam("GrantAccessRequest", "none", true),
					},
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
						},
					},
				},
			},
			"/account/{id}": map[string]swagger.Method{
				"delete": {
					Tags:    []string{"Account"},
					Summary: "Revoke access from an account",
					Parameters: []swagger.Parameter{
						swagger.NewStringPathParam("account", "Account that you want to revoke access to", true),
					},
					Security: swagger.BasicAuthSecurity("login"),
					Responses: map[string]swagger.Response{
						"200": {
							Description: "success",
						},
					},
				},
			},
		},
		Definitions: map[string]swagger.Definition{
			"CreateRepositoryRequest":  models.CreateRepositoryRequest{}.Definition(),
			"CreateRepositoryResponse": models.CreateRepositoryResponse{}.Definition(),
			"CreateTokenResponse":      models.CreateTokenResponse{}.Definition(),
			"ListRepositoriesResponse": models.ListRepositoriesResponse{}.Definition(),
			"Repository":               models.Repository{}.Definition(),
			"ListImagesResponse":       models.ListImagesResponse{}.Definition(),
			"Image":                    models.Image{}.Definition(),
			"ListAccountsResponse":     models.ListAccountsResponse{}.Definition(),
			"GrantAccessRequest":       models.GrantAccessRequest{}.Definition(),
		},
		SecurityDefinitions: map[string]swagger.SecurityDefinition{
			"login": {
				Type:        "basic",
				Description: "Basic authentication",
			},
		},
	}

	bytes, err := json.MarshalIndent(spec, "", "    ")
	if err != nil {
		return nil, err
	}

	return fireball.NewResponse(200, bytes, fireball.JSONHeaders), nil
}


text:
This is the documentation of **Smart Interactions Management Kit** (SIMKit). The present code samples are based on PyREEM version of PyRide (see https://github.com/kunle12/pyride_reem and https://github.com/uts-magic-lab/pyride_pr2). SIMKit can be used on any robot with PyRide installed.

To use SIMKit in python you just have to import the class `RobotScript` and `Event` from `SIMKit` module:

```
from SIMKit import RobotScript, Event
```

Then you can start create fancy robot scripts!

## Hello world script

A robot script is composed by **channels** and **assets**. Let's start with the small pieces of the puzzle: the assets.

An asset is simply a call to a PyRide function. For example it can be a text we want to have the robot to say, the movement of an arm, the pitch and pan of the head, or even the enrolment of a new person in the face dataset for face recognition tasks!
The asset can be played at specific times or after a certain event occurred, for example when another asset succeeded or failed, or even during more complex composed events, such as when an asset succeed after a certain time is reached.

A channel is a collection of assets. It specifies the PyRide function to use in order to run its assets and the related callback function to manage its success or failure (if available).

But putting the words into code, here is a simple example on how to design a very simple `"Hello world"` script:

```
#Creating the robot script object
rs = RobotScript()

#In this example we will have the REEM robot waving and saying hello world
#for this reason we need a channel for the speech, and another for the default motions

#to create a channel we use the method addChannel
#this method requires the PyREEM function to use in order to play the assets
#the onSuccess callback function and the onFailed callback function
#if those do not exist (or we do not want to specify them) we can use None
channel_playmotion_id = rs.addChannel("playDefaultMotion", "onPlayMotionSuccess", "onPlayMotionFailed")
channel_speech_id = rs.addChannel("say", "onSpeakSuccess", "onSpeakFailed")

#when creating a channel, the object RobotScript returns a string with the channelID
#we can use it to add new assets to the script

#to create an asset in a channel we use the method addAssetToChannel
#the method requires the channel_id string
#the list of starting times we want the asset to run
#and the tuple with the list of parameters for the PyREEM function specified in the channel
asset_wave_id = rs.addAssetToChannel(channel_playmotion_id, [0], ("wave",))
asset_helloworld_id = rs.addAssetToChannel(channel_speech_id, [2], ("Hello world!",))
asset_imchip_id = rs.addAssetToChannel(channel_speech_id, [4], ("I am REEM!",)

#also this time the method returns the id of the created asset
```

That's it! We just created a script with the robot waving and saying `"Hello world! I am REEM!"`.
In this script the robot will wave right after the script is played (at 0 seconds), then say `"Hello world!"` after 2 seconds, and then `"I am REEM!"` after 2 more seconds (at 4 seconds from the beginning of the script).

Now let's run our script:

```
rs.play()
```

Easy, isn't it?! But now, here is the trick... let's say we want the script to say `"Hello"` and the name of a person that we will know only before running the script. Can we design the script in a way to be used for different names on the fly? Of course!

We can use **placeholders**. A placeholder is simply a variable inside our asset, defined as `$<name of the variable>`. The name of the variable must contains only alphanumeric characters (`[a-zA-Z0-9_]`). The current version of SIMKit can only support placeholders for parameters that are strings (_new version with more complex placeholders coming_).

```
asset_hw_placeholder_id = rs.addAssetToChannel(channel_speech_id, [2], ("Hello $NAME!",))
```

Now that we have our new asset with the placeholder we can play the script again, but before we need a dictionary in which we can specify how to translate the placeholders into proper values:

```
kb = {"NAME": "Jonathan"}
```

The dictionary can be built on the fly, just before running the script when the desired information is available. Then we can simply run the script with this new parameter:

```
rs.play(kb)
```

Obviously we can also stop a script:

```
rs.stop()
```

If so, all the channels will stop to play any further asset. However, _the assets already running would not be stopped_.

## Adding Events and Triggers

Sometimes it is preferable to synchronize assets automatically rather then using fixed times. With SIMKit it is possible to do that.
In order to do that we need to specify **events** and **triggers**. An event is a temporal situation, a change in the state of a certain asset or a composition of other events.

But first, let's have a step back. The assets have **different states**: `off`, `on`, `succeeded`, `failed`. An asset is off when it is not playing. It is on when the asset is currently playing but not yet succeeded or failed. It is succeeded when the `onSuccess` callback function is invoked, and failed when the `onFailed` callback function is invoked. If in the channel is not specified an `onSuccess` callback function, its assets pass automatically from `"on"` to `"succeeded"`.

There are different possibilities for an action to fail in PyRide, for example when the required movement cannot reach the desired position, or when there is already a movement running for the specific required joints.

There are currently 5 types of events: `TIME_EVENT`, `SUCCEEDED_EVENT`, `FAILED_EVENT`, `AND_EVENT` and `OR_EVENT`. In the following code are shown possible examples of any event:

```
#this event occurs when 10 seconds are elapsed
#the first parameter is the type of the event
#the second parameter is the time when the event occurs
event1 = Event(Event.TIME_EVENT, 10)

#this event occurs when the helloworld asset succeeds
#the first parameter is the type of the event
#the second parameter is the asset id string we are monitoring
event2 = Event(Event.SUCCEEDED_EVENT, asset_helloworld_id)

#this event occurs when the waving fails
#the first parameter is the type of the event
#the second parameter is the asset id string we are monitoring
event3 = Event(Event.FAILED_EVENT, asset_wave_id)

#this event occurs when the helloworld asset succeeds and at least 10 seconds are elapsed
#the first parameter is the type of the event
#the second parameter is the first event to occur
#the third parameter is the second event to occur
event4 = Event(Event.AND_EVENT, event1, event2)

#this event occurs when the helloworld asset succeeds or if at least 10 seconds are elapsed, whichever first
#the first parameter is the type of the event
#the second parameter is the first event to monitor
#the third parameter is the second event to monitor
event5 = Event(Event.OR_EVENT, event1, event2)
```

Obviously, there is no limit in composing events of type `AND_EVENT` and `OR_EVENT`.

In order to play a specific asset when an event occurs we need a trigger. Let's say we want to say `"I am REEM"` 1 second after the `"Hello world"` asset fully succeeded. To create this trigger is very simple with the method `addTrigger`:

```
rs.addTrigger(asset_imchip_id, event2, 1, 1)
```

The first parameter of this method is the `assetID` string of the asset we need to run when the trigger is triggered.
The second parameter is the previously created event, in this case a `SUCCEEDED_EVENT` of the asset `helloworld`.
The third parameter is the delay time, namely how many seconds the trigger needs to wait until playing the referred asset.
The fourth parameter is the number of times the trigger needs to be triggered. If 1, the trigger is launched and then disabled, otherwise if greater than 1 and the same event occurs multiple times, the trigger is launched multiple times. If None, the trigger is launched infinite times.

## Play a default state script when the main script is committed

Another cool feature is the possibility to create a script to use as a "**default state**" of the robot to play right after the main script is fully committed. For example, coming back to the home position and setting the monitor to the Magic Lab webpage.
To avoid to duplicate this information multiple times in the scripts with the risk of possible errors, it is possible to add a default script to the main script (_not fully tested_).

In this following code we create a default state script first, and then add it to our main robot script previously created:

```
import json

#this script returns CHIP to home position and set its monitor to the CBA logo
default_rs = RobotScript()

channel_playmotion_id = default_rs.addChannel("playDefaultMotion", "onPlayMotionSuccess", "onPlayMotionFailed")
channel_monitor_id = default_rs.addChannel("directToWeb")

default_rs.addAssetToChannel(channel_playmotion_id, [0], ("home",))
default_rs.addAssetToChannel(channel_monitor_id, [0], ("http://themagiclab.org/",))

#now that we created the default state script
#we can add it to the main script with setDefaultStateScript method
rs.setDefaultStateScript(default_rs, delay=0.5, script_KB={})

#the method takes:
#as first parameter the default state script to run after the main script is committed
#as second parameter the optional time delay to wait after the main script committed
#as third paramter the optional dictionary to use in order to translate the placeholders of the default state script
```

## How to manage the commitment of a script

If we need to know when the script is fully committed, we can also add a callback function to be invoked when the script fully commits (_not fully tested_).

```
rs.setOnCommitCallbackFunction(my_callback_function)
```

The parameter of this method is the callback function to be invoked when the script fully commits (if it has a default state script, after the default state script fully committed). The callback function needs to have one parameter, namely the notifier `RobotScript` object (at the moment the callback takes no parameters but I will change it for more convenience):

```
def my_callback_function(notifier):
  notifier.printNotificationsHystory()
```

In this example we can use the method `printNotificationsHystory` (_to be done soon_) of the notifying committed `RobotScript` object to retrieve the timeline hystory of all the assets states for each channel:

```
--------
channel_say
--------
2s: asset_1@channel_say -> ON
3.2s: asset_1@channel_say -> SUCCEEDED
4.2s: asset_2@channel_say -> ON
5.5s: asset_2@channel_say -> SUCCEEDED

--------
channel_playDefaultMotion
--------
0s: asset_1@channel_playDefaultMotion -> ON
4s: asset_1@channel_playDefaultMotion -> SUCCEEDED
```

This information can be useful to debug and test a robot script.

## Export and Import scripts with JSON

After we created and tested a script, it is convenient to save it on a file. With SIMKit it is possible to do that with just a line of code:

```
rs.exportToJSON(where_we_are_saving_the_file)
```

This method requires the URL where we desire to save the exported JSON file. The URL must include the name of the file with the extension .json.

The exportation process will include assets, channels, triggers and the default state script. It will not export the onCommit callback function, since this is independent from the script.

If we want to import the script from a previously saved json file we can do that again with a single line of code:

```
rs = RobotScript.importFromJSON(url_where_we_saved_the_file)
```

The method requires the URL where the script file in json is saved, and it returns the functioning `RobotScript` object.

To playback the script we need simply to play it again:

```
rs.play()
```


text:
/* eslint-disable */

/// <reference path="jqwidgets.d.ts" />

import '../jqwidgets/jqxcore.js';
import '../jqwidgets/jqxbuttons.js';

import { Component, Input, Output, EventEmitter, ElementRef, OnChanges, SimpleChanges } from '@angular/core';
declare let JQXLite: any;

@Component({
    selector: 'jqxToggleButton',
    template: '<button><ng-content></ng-content></button>'
})

export class jqxToggleButtonComponent implements OnChanges
{
   @Input('disabled') attrDisabled: boolean;
   @Input('imgSrc') attrImgSrc: string;
   @Input('imgWidth') attrImgWidth: number | string;
   @Input('imgHeight') attrImgHeight: number | string;
   @Input('imgPosition') attrImgPosition: string;
   @Input('roundedCorners') attrRoundedCorners: string;
   @Input('rtl') attrRtl: boolean;
   @Input('textPosition') attrTextPosition: string;
   @Input('textImageRelation') attrTextImageRelation: string;
   @Input('theme') attrTheme: string;
   @Input('template') attrTemplate: string;
   @Input('toggled') attrToggled: boolean;
   @Input('value') attrValue: string;
   @Input('width') attrWidth: string | number;
   @Input('height') attrHeight: string | number;

   @Input('auto-create') autoCreate: boolean = true;

   properties: string[] = ['disabled','height','imgSrc','imgWidth','imgHeight','imgPosition','roundedCorners','rtl','textPosition','textImageRelation','theme','template','toggled','width','value'];
   host: any;
   elementRef: ElementRef;
   widgetObject:  jqwidgets.jqxToggleButton;

   constructor(containerElement: ElementRef) {
      this.elementRef = containerElement;
   }

   ngOnInit() {
      if (this.autoCreate) {
         this.createComponent();
      }
   };

   ngOnChanges(changes: SimpleChanges) {
      if (this.host) {
         for (let i = 0; i < this.properties.length; i++) {
            let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1);
            let areEqual: boolean = false;

            if (this[attrName] !== undefined) {
               if (typeof this[attrName] === 'object') {
                  if (this[attrName] instanceof Array) {
                     areEqual = this.arraysEqual(this[attrName], this.host.jqxToggleButton(this.properties[i]));
                  }
                  if (areEqual) {
                     return false;
                  }

                  this.host.jqxToggleButton(this.properties[i], this[attrName]);
                  continue;
               }

               if (this[attrName] !== this.host.jqxToggleButton(this.properties[i])) {
                  this.host.jqxToggleButton(this.properties[i], this[attrName]);
               }
            }
         }
      }
   }

   arraysEqual(attrValue: any, hostValue: any): boolean {
      if ((attrValue && !hostValue) || (!attrValue && hostValue)) {
         return false;
      }
      if (attrValue.length != hostValue.length) {
         return false;
      }
      for (let i = 0; i < attrValue.length; i++) {
         if (attrValue[i] !== hostValue[i]) {
            return false;
         }
      }
      return true;
   }

   manageAttributes(): any {
      let options = {};
      for (let i = 0; i < this.properties.length; i++) {
         let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1);
         if (this[attrName] !== undefined) {
            options[this.properties[i]] = this[attrName];
         }
      }
      return options;
   }

   moveClasses(parentEl: HTMLElement, childEl: HTMLElement): void {
      let classes: any = parentEl.classList;
      if (classes.length > 0) {
        childEl.classList.add(...classes);
      }
      parentEl.className = '';
   }

   moveStyles(parentEl: HTMLElement, childEl: HTMLElement): void {
      let style = parentEl.style.cssText;
      childEl.style.cssText = style
      parentEl.style.cssText = '';
   }

   createComponent(options?: any): void {
      if (this.host) {
         return;
      }
      if (options) {
         JQXLite.extend(options, this.manageAttributes());
      }
      else {
        options = this.manageAttributes();
      }
      this.host = JQXLite(this.elementRef.nativeElement.firstChild);

      this.moveClasses(this.elementRef.nativeElement, this.host[0]);
      this.moveStyles(this.elementRef.nativeElement, this.host[0]);

      this.__wireEvents__();
      this.widgetObject = jqwidgets.createInstance(this.host, 'jqxToggleButton', options);

   }

   createWidget(options?: any): void {
        this.createComponent(options);
   }

   __updateRect__() : void {
      if(this.host) this.host.css({ width: this.attrWidth, height: this.attrHeight });
   }

   setOptions(options: any) : void {
      this.host.jqxToggleButton('setOptions', options);
   }

   // jqxToggleButtonComponent properties
   disabled(arg?: boolean): boolean {
      if (arg !== undefined) {
          this.host.jqxToggleButton('disabled', arg);
      } else {
          return this.host.jqxToggleButton('disabled');
      }
   }

   height(arg?: number | string): number | string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('height', arg);
      } else {
          return this.host.jqxToggleButton('height');
      }
   }

   imgSrc(arg?: string): string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('imgSrc', arg);
      } else {
          return this.host.jqxToggleButton('imgSrc');
      }
   }

   imgWidth(arg?: number | string): number | string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('imgWidth', arg);
      } else {
          return this.host.jqxToggleButton('imgWidth');
      }
   }

   imgHeight(arg?: number | string): number | string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('imgHeight', arg);
      } else {
          return this.host.jqxToggleButton('imgHeight');
      }
   }

   imgPosition(arg?: string): string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('imgPosition', arg);
      } else {
          return this.host.jqxToggleButton('imgPosition');
      }
   }

   roundedCorners(arg?: string): string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('roundedCorners', arg);
      } else {
          return this.host.jqxToggleButton('roundedCorners');
      }
   }

   rtl(arg?: boolean): boolean {
      if (arg !== undefined) {
          this.host.jqxToggleButton('rtl', arg);
      } else {
          return this.host.jqxToggleButton('rtl');
      }
   }

   textPosition(arg?: string): string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('textPosition', arg);
      } else {
          return this.host.jqxToggleButton('textPosition');
      }
   }

   textImageRelation(arg?: string): string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('textImageRelation', arg);
      } else {
          return this.host.jqxToggleButton('textImageRelation');
      }
   }

   theme(arg?: string): string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('theme', arg);
      } else {
          return this.host.jqxToggleButton('theme');
      }
   }

   template(arg?: string): string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('template', arg);
      } else {
          return this.host.jqxToggleButton('template');
      }
   }

   toggled(arg?: boolean): boolean {
      if (arg !== undefined) {
          this.host.jqxToggleButton('toggled', arg);
      } else {
          return this.host.jqxToggleButton('toggled');
      }
   }

   width(arg?: string | number): string | number {
      if (arg !== undefined) {
          this.host.jqxToggleButton('width', arg);
      } else {
          return this.host.jqxToggleButton('width');
      }
   }

   value(arg?: string): string {
      if (arg !== undefined) {
          this.host.jqxToggleButton('value', arg);
      } else {
          return this.host.jqxToggleButton('value');
      }
   }

   // jqxToggleButtonComponent functions
   check(): void {
      this.host.jqxToggleButton('check');
   }

   destroy(): void {
      this.host.jqxToggleButton('destroy');
   }

   focus(): void {
      this.host.jqxToggleButton('focus');
   }

   render(): void {
      this.host.jqxToggleButton('render');
   }

   toggle(): void {
      this.host.jqxToggleButton('toggle');
   }

   unCheck(): void {
      this.host.jqxToggleButton('unCheck');
   }

   val(value?: string): any {
      if (value !== undefined) {
         return this.host.jqxToggleButton('val', value);
      } else {
         return this.host.jqxToggleButton('val');
      }
   };

   // jqxToggleButtonComponent events
   @Output() onClick = new EventEmitter();

   __wireEvents__(): void {
      this.host.on('click', (eventData: any) => { this.onClick.emit(eventData); });
   }

} //jqxToggleButtonComponent


text:
<style>
h1 {
    text-decoration: line-through;
    font-style: italic;
}

h2 {
    text-decoration: line-through;
}

h3 {
    text-decoration: line-through underline;
}
</style>


text:
namespace DesignPatterns.Behavioral.Visitor
{
    /// <summary>
    /// Interface defining a way to visit a word.
    /// </summary>
    public interface IWordsVisitor
    {
        void Visit(string word);
    }
}


text:
<?php

namespace Respect\Validation\Rules\SubdivisionCode;

use Respect\Validation\Rules\AbstractSearcher;

/**
 * Validator for Mali subdivision code.
 *
 * ISO 3166-1 alpha-2: ML
 *
 * @link http://www.geonames.org/ML/administrative-division-mali.html
 */
class MlSubdivisionCode extends AbstractSearcher
{
    public $haystack = array(
        '1', // Kayes
        '2', // Koulikoro
        '3', // Sikasso
        '4', // Segou
        '5', // Mopti
        '6', // Tombouctou
        '7', // Gao
        '8', // Kidal
        'BKO', // Bamako Capital District
    );

    public $compareIdentical = true;
}


text:
package com.android.cts.verifier.p2p.testcase;

import java.util.ArrayList;

import android.content.Context;

/**
 * Test suite for go negotiation requester.
 */
public class GoNegReqTestSuite {

    private static ArrayList<ReqTestCase> sTestSuite = null;

    /**
     * Return test suite.
     * @param context
     * @return
     */
    public static ArrayList<ReqTestCase> getTestSuite(Context context) {
        initialize(context);
        return sTestSuite;
    }

    /**
     * Return the specified test case.
     * @param context
     * @param testId
     * @return
     */
    public static ReqTestCase getTestCase(Context context,
            String testId) {
        initialize(context);

        for (ReqTestCase test: sTestSuite) {
            if (test.getTestId().equals(testId)) {
                return test;
            }
        }
        return null;
    }

    private static void initialize(Context context) {
        if (sTestSuite != null) {
            return;
        }

        sTestSuite = new ArrayList<ReqTestCase>();
        sTestSuite.add(new GoNegReqPbcTestCase(context));
        sTestSuite.add(new GoNegReqPinTestCase(context));
    }
}


text:
var path = require('path');

module.exports = {
  ROOT_DIR: path.resolve(__dirname, "../"),               // Root dir
  SRC_DIR: path.resolve(__dirname, "../src"),             // Source files
  CLIENT_DIR: path.resolve(__dirname, "../src/client"),   // Client source files
  SERVER_DIR: path.resolve(__dirname, "../src/server"),   // Server source files
  PUBLIC_DIR: path.resolve(__dirname, "../public"),       // Build destination
  DIST_DIR: path.resolve(__dirname, "../public/bundle"),  // Build destination
  NPM_DIR:   path.resolve(__dirname, "../node_modules"),  // Npm dir
};


text:
package org.kuali.rice.krad.datadictionary.validation.fieldlevel;

import org.junit.Test;
import org.kuali.rice.kns.datadictionary.validation.fieldlevel.ZipcodeValidationPattern;
import org.kuali.test.KRADTestCase;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class ZipcodeValidationPatternTest extends KRADTestCase {
    private ZipcodeValidationPattern pattern;

    @Override
    public void setUp() throws Exception {
        super.setUp();

        pattern = new ZipcodeValidationPattern();
    }

    @Test public final void testMatches_5digit_valid() {
        assertTrue(pattern.matches("12345"));
    }

    @Test public final void testMatches_9digit_valid() {
        assertTrue(pattern.matches("12345-1234"));
    }

    @Test public final void testMatches_invalid1() {
        assertFalse(pattern.matches("123456"));
    }

    @Test public final void testMatches_invalid2() {
        assertFalse(pattern.matches("1234"));
    }

    @Test public final void testMatches_invalid3() {
        assertFalse(pattern.matches("12345-12345"));
    }

    @Test public final void testMatches_invalid4() {
        assertFalse(pattern.matches("12345-123"));
    }
}


text:
'Django package for bootstrap-fileinput:' \
    ' An enhanced HTML 5 file input for Bootstrap 3.x with file preview,' \
    ' multiple selection, and more features.'

from setuptools import setup

setup(
    name='django-bootstrap-fileinput',
    version='1.6.0',
    url='http://plugins.krajee.com/file-input',
    description=globals()['__doc__'],
    author='Kartik Visweswaran',
    maintainer='Renat Galimov',
    maintainer_email='renat2017@gmail.com',
    keywords=['django', 'bootstrap'],
    platforms='any',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Utilities',
    ],
    packages=['django_bootstrap_fileinput'],
    package_data={'django_bootstrap_fileinput':
                  ['static/django_bootstrap_fileinput/js/*.js',
                   'static/django_bootstrap_fileinput/css/*.css',
                   'static/django_bootstrap_fileinput/img*.gif']}
)


text:
package functional;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import utils.PropertyLoader;
import webdriver.Browser;
import webdriver.BrowserFactory;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * Created by c246T on 23.02.2015.
 */
public class AbstractTest {
    public Browser browser;

    @BeforeSuite
    public void initEnv()
    {
        browser = BrowserFactory.create(PropertyLoader.loadProperty("browser"));
    }

    @AfterSuite
    public void shutEnv()
    {
        if (browser != null)
            browser.quit();
    }
}


text:
<?php
use phpforms\Form;
use phpforms\Validator\Validator;

/* =============================================
    start session and include form class
============================================= */

session_start();
include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpforms/Form.php';

/* =============================================
    validation if posted
============================================= */

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    include_once $_SERVER['DOCUMENT_ROOT'] . '/phpforms/Validator/Validator.php';
    include_once $_SERVER['DOCUMENT_ROOT'] . '/phpforms/Validator/Exception.php';
    $validator = new Validator($_POST);
    $required = array('user-name', 'user-email');
    foreach ($required as $required) {
        $validator->required()->validate($required);
    }
    $validator->email()->validate('user-email');

    // check for errors

    if ($validator->hasErrors()) {
        $_SESSION['errors']['newsletter-suscribe-modal-form'] = $validator->getAllErrors();
    } else {

        /* Database insert (disabled for demo) */

        /*require_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpforms/database/db-connect.php';
        require_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpforms/database/Mysql.php';

        $db = new Mysql();
        $insert['ID'] = Mysql::SQLValue('');
        $insert['user_name'] = Mysql::SQLValue($_POST['user-name']);
        $insert['user_email'] = Mysql::SQLValue($_POST['user-email']);
        if (!$db->insertRow('YOUR_TABLE', $insert)) {
            $user_message = '
' . $db->error() . '
' . $db->getLastSql() . '
' . " \n";
        } else {
            $user_message = '
Thanks for suscribe !
' . " \n";
            Form::clear('newsletter-suscribe-modal-form');
        }*/
        Form::clear('newsletter-suscribe-modal-form'); // just for demo ; delete this line if real database recording.
        $user_message = '
Thanks for suscribe !
' . " \n"; // just for demo ; delete this line if real database recording.
    }
}

/* ==================================================
    The Form

    for class and methods documentation,
    go to documentation/index.html
================================================== */

$form = new Form('newsletter-suscribe-modal-form', 'vertical', 'novalidate=true');
$form->addHtml('

');
$form->addInputWrapper('

', 'user-name');
$form->addHtml('

', 'user-name', 'before');
$form->addInput('text', 'user-name', '', '', $attr = 'placeholder=Your Name, required=required');
$form->addInputWrapper('

', 'user-email');
$form->addHtml('

', 'user-email', 'before');
$form->addInput('email', 'user-email', '', '', $attr = 'placeholder=Your E-mail, required=required');
$form->addBtn('submit', 'submit-btn', 1, 'Suscribe ', 'class=btn btn-primary btn-block');
$form->addHtml('

');
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Newsletter Suscribe Modal Form</title>

    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
    <?php $form->printIncludes('css'); ?>

Newsletter Suscribe Modal Form

            <?php
            if (isset($user_message)) {
                echo $user_message;
            }
            ?>
            <?php /* code preview button */
                include_once '../assets/code-preview.php';
            ?>

                <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModalForm">Suscribe to our Newsletter </button>

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Suscribe to our Newsletter
and receive exclusive offers, updates and news!

                        <?php
                        $form->render();
                        ?>

        <?php
            $form->printIncludes('js');
            $form->printJsCode();
        ?>
        <?php

        /* Launch form modal if form has posted errors */
        if ($_SERVER["REQUEST_METHOD"] == "POST" && $validator->hasErrors()) {
            ?>

            <?php
        }
        ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/lmp-mr1-supportlib-release/frameworks/support/v7/mediarouter/res/values-kk-rKZ/strings.xml -->
    <eat-comment/>
    <string msgid="4271159405637008602" name="mr_media_route_button_content_description">"Meдиа құрылғылары"</string>
    <string msgid="7553005460920830010" name="mr_media_route_chooser_searching">"Құрылғыларды іздеуде…"</string>
    <string msgid="7106830097177242655" name="mr_media_route_chooser_title">"Құрылғыға жалғау"</string>
    <string msgid="109793632378378069" name="mr_media_route_controller_disconnect">"Ажырату"</string>
    <string msgid="5441529851481176817" name="mr_system_route_name">"Жүйе"</string>
    <string msgid="7498112907524977311" name="mr_user_route_category_name">"Құрылғылар"</string>
</resources>


text:
package chart;

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;

/**
 * @version 1.33 2007-06-12
 * @author Cay Horstmann
 */
public class Chart extends JApplet
{
   public void init()
   {
      EventQueue.invokeLater(new Runnable()
         {
            public void run()
            {
               String v = getParameter("values");
               if (v == null) return;
               int n = Integer.parseInt(v);
               double[] values = new double[n];
               String[] names = new String[n];
               for (int i = 0; i < n; i++)
               {
                  values[i] = Double.parseDouble(getParameter("value." + (i + 1)));
                  names[i] = getParameter("name." + (i + 1));
               }

               add(new ChartComponent(values, names, getParameter("title")));
            }
         });
   }
}

/**
 * A component that draws a bar chart.
 */
class ChartComponent extends JComponent
{
   private double[] values;
   private String[] names;
   private String title;

   /**
    * Constructs a ChartComponent.
    * @param v the array of values for the chart
    * @param n the array of names for the values
    * @param t the title of the chart
    */
   public ChartComponent(double[] v, String[] n, String t)
   {
      values = v;
      names = n;
      title = t;
   }

   public void paintComponent(Graphics g)
   {
      Graphics2D g2 = (Graphics2D) g;

      // compute the minimum and maximum values
      if (values == null) return;
      double minValue = 0;
      double maxValue = 0;
      for (double v : values)
      {
         if (minValue > v) minValue = v;
         if (maxValue < v) maxValue = v;
      }
      if (maxValue == minValue) return;

      int panelWidth = getWidth();
      int panelHeight = getHeight();

      Font titleFont = new Font("SansSerif", Font.BOLD, 20);
      Font labelFont = new Font("SansSerif", Font.PLAIN, 10);

      // compute the extent of the title
      FontRenderContext context = g2.getFontRenderContext();
      Rectangle2D titleBounds = titleFont.getStringBounds(title, context);
      double titleWidth = titleBounds.getWidth();
      double top = titleBounds.getHeight();

      // draw the title
      double y = -titleBounds.getY(); // ascent
      double x = (panelWidth - titleWidth) / 2;
      g2.setFont(titleFont);
      g2.drawString(title, (float) x, (float) y);

      // compute the extent of the bar labels
      LineMetrics labelMetrics = labelFont.getLineMetrics("", context);
      double bottom = labelMetrics.getHeight();

      y = panelHeight - labelMetrics.getDescent();
      g2.setFont(labelFont);

      // get the scale factor and width for the bars
      double scale = (panelHeight - top - bottom) / (maxValue - minValue);
      int barWidth = panelWidth / values.length;

      // draw the bars
      for (int i = 0; i < values.length; i++)
      {
         // get the coordinates of the bar rectangle
         double x1 = i * barWidth + 1;
         double y1 = top;
         double height = values[i] * scale;
         if (values[i] >= 0) y1 += (maxValue - values[i]) * scale;
         else
         {
            y1 += maxValue * scale;
            height = -height;
         }

         // fill the bar and draw the bar outline
         Rectangle2D rect = new Rectangle2D.Double(x1, y1, barWidth - 2, height);
         g2.setPaint(Color.RED);
         g2.fill(rect);
         g2.setPaint(Color.BLACK);
         g2.draw(rect);

         // draw the centered label below the bar
         Rectangle2D labelBounds = labelFont.getStringBounds(names[i], context);

         double labelWidth = labelBounds.getWidth();
         x = x1 + (barWidth - labelWidth) / 2;
         g2.drawString(names[i], (float) x, (float) y);
      }
   }
}


text:
import { useDeps } from 'react-simple-di';
import { withTracker, withHandlers, composeAll } from 'react-komposer-plus';

import AdminCore from '../../components/admin';

const userEvents = {
  saveCoreConfigs({ context, saveConfigs }, event) {
    event.preventDefault();
    const { dispatch } = context;
    const configs = {
      appName: event.target.appName.value
    };
    dispatch(saveConfigs(configs));
  }
};
const subscriptions = ({ context }, onData) => {
  const { Collections } = context;
  const corePkg = Collections.Packages.findOne({ name: 'core' });
  if (corePkg) {
    const appName = corePkg.configs.appName;
    onData(null, { appName });
  }
};

const depsToProps = (context, actions) => ({
  context,
  saveConfigs: actions.core.saveConfigs
});

export default composeAll(
  withHandlers(userEvents),
  withTracker(subscriptions),
  useDeps(depsToProps)
)(AdminCore);


text:
class MockDeviceOAuth2TokenStore : public DeviceOAuth2TokenStore {
 public:
  MockDeviceOAuth2TokenStore() = default;
  ~MockDeviceOAuth2TokenStore() override = default;

  // DeviceOAuth2TokenStore:
  void Init(InitCallback callback) override {
    pending_init_callback_ = std::move(callback);
  }
  CoreAccountId GetAccountId() const override { return account_id_; }
  std::string GetRefreshToken() const override { return refresh_token_; }

  void SetAndSaveRefreshToken(const std::string& refresh_token,
                              StatusCallback result_callback) override {
    refresh_token_ = refresh_token;
    pending_status_callback_ = std::move(result_callback);
  }

  void PrepareTrustedAccountId(TrustedAccountIdCallback callback) override {
    pending_trusted_account_id_callback_ = std::move(callback);
    TriggerTrustedAccountIdCallback(true);
  }

#if !BUILDFLAG(IS_CHROMEOS_ASH)
  void SetAccountEmail(const std::string& account_email) override {
    account_id_ = CoreAccountId::FromEmail(account_email);
  }
#endif

  // Mock-specific functions:
  void SetRefreshTokenForTesting(const std::string& token) {
    refresh_token_ = token;
  }

  void SetAccountIdForTesting(CoreAccountId account_id) {
    account_id_ = account_id;
  }

  void TriggerInitCallback(bool success, bool validation_required) {
    std::move(pending_init_callback_).Run(success, validation_required);
  }

  void TriggerStatusCallback(bool success) {
    std::move(pending_status_callback_).Run(success);
  }

  void TriggerTrustedAccountIdCallback(bool account_present) {
    std::move(pending_trusted_account_id_callback_).Run(account_present);
  }

 private:
  CoreAccountId account_id_;
  std::string refresh_token_;

  InitCallback pending_init_callback_;
  StatusCallback pending_status_callback_;
  TrustedAccountIdCallback pending_trusted_account_id_callback_;
};

class DeviceOAuth2TokenServiceTest : public testing::Test {
 public:
  DeviceOAuth2TokenServiceTest()
      : scoped_testing_local_state_(TestingBrowserProcess::GetGlobal()) {}

  // Most tests just want a noop crypto impl with a dummy refresh token value in
  // Local State (if the value is an empty string, it will be ignored).
  void SetUpDefaultValues() {
    CreateService();
    token_store_->SetRefreshTokenForTesting("device_refresh_token_4_test");
    SetRobotAccountId("service_acct@g.com");
    AssertConsumerTokensAndErrors(0, 0);

    token_store_->TriggerInitCallback(true, true);
  }

  void SetRobotAccountId(const std::string& account_id) {
    token_store_->SetAccountIdForTesting(CoreAccountId::FromEmail(account_id));
  }

  std::unique_ptr<OAuth2AccessTokenManager::Request> StartTokenRequest() {
    return oauth2_service_->StartAccessTokenRequest(std::set<std::string>(),
                                                    &consumer_);
  }

  void SetUp() override {}

  void TearDown() override {
    oauth2_service_.reset();
    base::ThreadPoolInstance::Get()->FlushForTesting();
    base::RunLoop().RunUntilIdle();
  }

  MockDeviceOAuth2TokenStore* token_store() { return token_store_; }

  void CreateService() {
    auto store = std::make_unique<MockDeviceOAuth2TokenStore>();
    token_store_ = store.get();

    oauth2_service_.reset(new DeviceOAuth2TokenService(
        test_url_loader_factory_.GetSafeWeakWrapper(), std::move(store)));
    oauth2_service_->max_refresh_token_validation_retries_ = 0;
    oauth2_service_->GetAccessTokenManager()
        ->set_max_authorization_token_fetch_retries_for_testing(0);
  }

  std::string GetValidTokenInfoResponse(const std::string& email) {
    return "{ \"email\": \"" + email +
           "\","
           "  \"user_id\": \"1234567890\" }";
  }

  bool RefreshTokenIsAvailable() {
    return oauth2_service_->RefreshTokenIsAvailable();
  }

  std::string GetRefreshToken() {
    if (!RefreshTokenIsAvailable())
      return std::string();
    return oauth2_service_->GetRefreshToken();
  }

  // A utility method to return fake URL results, for testing the refresh token
  // validation logic.  For a successful validation attempt, this method will be
  // called three times for the steps listed below.
  //
  // Step 1a: fetch the access token for the tokeninfo API.
  // Step 1b: call the tokeninfo API.
  // Step 2:  Fetch the access token for the requested scope
  //          (in this case, cloudprint).
  void ReturnOAuthUrlFetchResults(const std::string& url,
                                  net::HttpStatusCode response_code,
                                  const std::string& response_string);

  // Generates URL fetch replies with the specified results for requests
  // generated by the token service.
  void PerformURLFetchesWithResults(
      net::HttpStatusCode tokeninfo_access_token_status,
      const std::string& tokeninfo_access_token_response,
      net::HttpStatusCode tokeninfo_fetch_status,
      const std::string& tokeninfo_fetch_response,
      net::HttpStatusCode service_access_token_status,
      const std::string& service_access_token_response);

  // Generates URL fetch replies for the success path.
  void PerformURLFetches();

  void AssertConsumerTokensAndErrors(int num_tokens, int num_errors);

 protected:
  // This is here because DeviceOAuth2TokenService's destructor is private;
  // base::DefaultDeleter therefore doesn't work. However, the test class is
  // declared friend in DeviceOAuth2TokenService, so this deleter works.
  struct TokenServiceDeleter {
    inline void operator()(DeviceOAuth2TokenService* ptr) const { delete ptr; }
  };

  content::BrowserTaskEnvironment task_environment_;
  ScopedTestingLocalState scoped_testing_local_state_;
  network::TestURLLoaderFactory test_url_loader_factory_;
  std::unique_ptr<DeviceOAuth2TokenService, TokenServiceDeleter>
      oauth2_service_;
  TestingOAuth2AccessTokenManagerConsumer consumer_;
  raw_ptr<MockDeviceOAuth2TokenStore> token_store_;
};

void DeviceOAuth2TokenServiceTest::ReturnOAuthUrlFetchResults(
    const std::string& url,
    net::HttpStatusCode response_code,
    const std::string& response_string) {
  if (test_url_loader_factory_.IsPending(url)) {
    test_url_loader_factory_.SimulateResponseForPendingRequest(
        GURL(url), network::URLLoaderCompletionStatus(net::OK),
        network::CreateURLResponseHead(response_code), response_string);
  }
}

void DeviceOAuth2TokenServiceTest::PerformURLFetchesWithResults(
    net::HttpStatusCode tokeninfo_access_token_status,
    const std::string& tokeninfo_access_token_response,
    net::HttpStatusCode tokeninfo_fetch_status,
    const std::string& tokeninfo_fetch_response,
    net::HttpStatusCode service_access_token_status,
    const std::string& service_access_token_response) {
  ReturnOAuthUrlFetchResults(GaiaUrls::GetInstance()->oauth2_token_url().spec(),
                             tokeninfo_access_token_status,
                             tokeninfo_access_token_response);

  ReturnOAuthUrlFetchResults(
      GaiaUrls::GetInstance()->oauth2_token_info_url().spec(),
      tokeninfo_fetch_status, tokeninfo_fetch_response);

  ReturnOAuthUrlFetchResults(GaiaUrls::GetInstance()->oauth2_token_url().spec(),
                             service_access_token_status,
                             service_access_token_response);
}

void DeviceOAuth2TokenServiceTest::PerformURLFetches() {
  PerformURLFetchesWithResults(
      net::HTTP_OK, GetValidTokenResponse("tokeninfo_access_token", 3600),
      net::HTTP_OK, GetValidTokenInfoResponse("service_acct@g.com"),
      net::HTTP_OK, GetValidTokenResponse("scoped_access_token", 3600));
}

void DeviceOAuth2TokenServiceTest::AssertConsumerTokensAndErrors(
    int num_tokens,
    int num_errors) {
  EXPECT_EQ(num_tokens, consumer_.number_of_successful_tokens_);
  EXPECT_EQ(num_errors, consumer_.number_of_errors_);
}

TEST_F(DeviceOAuth2TokenServiceTest, RefreshTokenValidation_Success) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();

  PerformURLFetches();
  AssertConsumerTokensAndErrors(1, 0);

  EXPECT_EQ("scoped_access_token", consumer_.last_token_);
}

TEST_F(DeviceOAuth2TokenServiceTest, RefreshTokenValidation_SuccessAsyncLoad) {
  CreateService();
  token_store()->SetRefreshTokenForTesting("device_refresh_token_4_test");
  SetRobotAccountId("service_acct@g.com");

  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();
  PerformURLFetches();
  AssertConsumerTokensAndErrors(0, 0);

  token_store()->TriggerInitCallback(true, true);
  base::RunLoop().RunUntilIdle();

  PerformURLFetches();
  AssertConsumerTokensAndErrors(1, 0);

  EXPECT_EQ("scoped_access_token", consumer_.last_token_);
}

TEST_F(DeviceOAuth2TokenServiceTest, RefreshTokenValidation_Cancel) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();
  request.reset();

  PerformURLFetches();

  // Test succeeds if this line is reached without a crash.
}

TEST_F(DeviceOAuth2TokenServiceTest, RefreshTokenValidation_InitFailure) {
  CreateService();
  token_store()->SetRefreshTokenForTesting("device_refresh_token_4_test");
  SetRobotAccountId("service_acct@g.com");
  token_store()->TriggerInitCallback(false, true);

  EXPECT_FALSE(RefreshTokenIsAvailable());

  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();
  base::RunLoop().RunUntilIdle();

  AssertConsumerTokensAndErrors(0, 1);
}

TEST_F(DeviceOAuth2TokenServiceTest,
       RefreshTokenValidation_Failure_TokenInfoAccessTokenHttpError) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();

  PerformURLFetchesWithResults(net::HTTP_UNAUTHORIZED, "", net::HTTP_OK,
                               GetValidTokenInfoResponse("service_acct@g.com"),
                               net::HTTP_OK,
                               GetValidTokenResponse("ignored", 3600));

  AssertConsumerTokensAndErrors(0, 1);
}

TEST_F(DeviceOAuth2TokenServiceTest,
       RefreshTokenValidation_Failure_TokenInfoAccessTokenInvalidResponse) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();

  PerformURLFetchesWithResults(net::HTTP_OK, "invalid response", net::HTTP_OK,
                               GetValidTokenInfoResponse("service_acct@g.com"),
                               net::HTTP_OK,
                               GetValidTokenResponse("ignored", 3600));

  AssertConsumerTokensAndErrors(0, 1);
}

TEST_F(DeviceOAuth2TokenServiceTest,
       RefreshTokenValidation_Failure_TokenInfoApiCallHttpError) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();

  PerformURLFetchesWithResults(
      net::HTTP_OK, GetValidTokenResponse("tokeninfo_access_token", 3600),
      net::HTTP_INTERNAL_SERVER_ERROR, "", net::HTTP_OK,
      GetValidTokenResponse("ignored", 3600));

  AssertConsumerTokensAndErrors(0, 1);
}

TEST_F(DeviceOAuth2TokenServiceTest,
       RefreshTokenValidation_Failure_TokenInfoApiCallInvalidResponse) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();

  PerformURLFetchesWithResults(
      net::HTTP_OK, GetValidTokenResponse("tokeninfo_access_token", 3600),
      net::HTTP_OK, "invalid response", net::HTTP_OK,
      GetValidTokenResponse("ignored", 3600));

  AssertConsumerTokensAndErrors(0, 1);
}

TEST_F(DeviceOAuth2TokenServiceTest,
       RefreshTokenValidation_Failure_CloudPrintAccessTokenHttpError) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();

  PerformURLFetchesWithResults(
      net::HTTP_OK, GetValidTokenResponse("tokeninfo_access_token", 3600),
      net::HTTP_OK, GetValidTokenInfoResponse("service_acct@g.com"),
      net::HTTP_BAD_REQUEST, "");

  AssertConsumerTokensAndErrors(0, 1);
}

TEST_F(DeviceOAuth2TokenServiceTest,
       RefreshTokenValidation_Failure_CloudPrintAccessTokenInvalidResponse) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();

  PerformURLFetchesWithResults(
      net::HTTP_OK, GetValidTokenResponse("tokeninfo_access_token", 3600),
      net::HTTP_OK, GetValidTokenInfoResponse("service_acct@g.com"),
      net::HTTP_OK, "invalid request");

  AssertConsumerTokensAndErrors(0, 1);
}

TEST_F(DeviceOAuth2TokenServiceTest, RefreshTokenValidation_Failure_BadOwner) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();

  SetRobotAccountId("WRONG_service_acct@g.com");

  PerformURLFetchesWithResults(
      net::HTTP_OK, GetValidTokenResponse("tokeninfo_access_token", 3600),
      net::HTTP_OK, GetValidTokenInfoResponse("service_acct@g.com"),
      net::HTTP_OK, GetValidTokenResponse("ignored", 3600));

  AssertConsumerTokensAndErrors(0, 1);
}

TEST_F(DeviceOAuth2TokenServiceTest, RefreshTokenValidation_Retry) {
  SetUpDefaultValues();
  std::unique_ptr<OAuth2AccessTokenManager::Request> request =
      StartTokenRequest();

  PerformURLFetchesWithResults(
      net::HTTP_INTERNAL_SERVER_ERROR, "", net::HTTP_OK,
      GetValidTokenInfoResponse("service_acct@g.com"), net::HTTP_OK,
      GetValidTokenResponse("ignored", 3600));

  AssertConsumerTokensAndErrors(0, 1);

  // Retry should succeed.
  request = StartTokenRequest();
  PerformURLFetches();
  AssertConsumerTokensAndErrors(1, 1);
}


text:
namespace Simple.Data.SqlServer
{
    using System.Data;
    using Ado.Schema;

    public class SqlColumn : Column
    {
        private readonly SqlDbType _sqlDbType;

        public SqlColumn(string actualName, Table table) : base(actualName, table)
        {
        }

        public SqlColumn(string actualName, Table table, SqlDbType sqlDbType) : base(actualName, table)
        {
            _sqlDbType = sqlDbType;
        }

        public SqlColumn(string actualName, Table table, bool isIdentity) : base(actualName, table, isIdentity)
        {
        }

        public SqlColumn(string actualName, Table table, bool isIdentity, SqlDbType sqlDbType, int maxLength)
            : base(actualName, table, isIdentity, default(DbType), maxLength)
        {
            _sqlDbType = sqlDbType;
        }

        public SqlDbType SqlDbType
        {
            get { return _sqlDbType; }
        }

        public override bool IsBinary
        {
            get
            {
                return SqlDbType == SqlDbType.Binary || SqlDbType == SqlDbType.Image ||
                       SqlDbType == SqlDbType.VarBinary;
            }
        }

        public override bool IsWriteable
        {
            get { return (!IsIdentity) && SqlDbType != SqlDbType.Timestamp; }
        }
    }
}


text:
There are several different ways to read input from a text file, including the use of `Scanners` along with their various "next" methods, such as *nextInt()*. (There's a good explanation of this at [https://docs.oracle.com/javase/tutorial/essential/io/scanning.html][1].) Here is an example of a somewhat old-fashioned approach that has the advantage of working from within an application or an applet. The "`StreamTokenizer`" parses the contents of the input file into "tokens", which are basically words--sequences of characters delineated by whitespace. (By the way, the method outlined here does not use `FileReaders`, a technique outlined in most introductory Java textbooks. The `Resource` technique is what allows programs to run correctly both from within Java apps and applets.)

In the code below, *foo* must be an instance of a user-defined class (i.e., a class that you have written, not a system-provided class.) If this code was in a public, non-static method, you could omit the "*foo*".

```
try
    {
    //create file input stream. Note that foo must a member of a user-defined class
    InputStream inS = foo.getClass().getResourceAsStream("input.txt");
    if (inS == null) {
       System.out.println("File not found: input.txt");
       return;
    }
    // A Reader reads input as characters, rather than raw data.
    BufferedReader buffR = new BufferedReader(new InputStreamReader(inS));
    //The stream tokenizer parses the characters into words, integers, etc.
    StreamTokenizer in = new StreamTokenizer(buffR);
    in.nextToken(); // Get the first token. (A token can be a word, a number,    EOF, etc.)
    while (in.ttype != in.TT_EOF) // Keep going until exhausting tokens
    {
       if (in.ttype == in.TT_WORD) {
           if (in.sval.equals("JOB")) {
               ...
           }
           ...
       }
       in.nextToken(); // Get the next token
    }
} // yrt
catch (IOException ex){
    System.out.println(ex.getMessage());
}
finally {
    try {
       if (inS != null) inS.close();
    }
    catch (IOException ex)
    {
       System.err.println("Had trouble closing input.txt.");
    }
}
```

[1]: https://docs.oracle.com/javase/tutorial/essential/io/scanning.html


text:
namespace exceptxx
{
    using namespace std;

    template<class T>
    class BaseExceptionImpl : public BaseException
    {
    public:
        using BaseException::BaseException;

        virtual unique_ptr<BaseException> cloneMove() override
        {
            return unique_ptr<BaseException>(new T(move(*static_cast<T*>(this))));
        }

        virtual void rethrow() override
        {
            throw *static_cast<T*>(this);
        }
    };
}