text:
var App = require('app');
require('views/main/service/item');

describe('App.MainServiceItemView', function() {

  var view = App.MainServiceItemView.create({
    controller: Em.Object.create({
      content:{
        hostComponents: []
      }
    })
  });

  describe('#mastersExcludedCommands', function() {

    var nonCustomAction = ['RESTART_ALL', 'RUN_SMOKE_TEST', 'REFRESH_CONFIGS', 'ROLLING_RESTART', 'TOGGLE_PASSIVE', 'TOGGLE_NN_HA', 'TOGGLE_RM_HA', 'MOVE_COMPONENT', 'DOWNLOAD_CLIENT_CONFIGS','MASTER_CUSTOM_COMMAND'];

    var keys = Object.keys(view.mastersExcludedCommands);
    var mastersExcludedCommands = [];
    for (var i = 0; i < keys.length; i++) {
      mastersExcludedCommands[i] = view.mastersExcludedCommands[keys[i]];
    }
    console.log("value of masterExcluded: " + mastersExcludedCommands);
    var allMastersExcludedCommands = mastersExcludedCommands.reduce(function(previous, current){
      console.log(previous);
      return previous.concat(current);
    });
    var actionMap = view.actionMap();

    var customActionsArray = [];
    for (var iter in actionMap) {
      customActionsArray.push(actionMap[iter]);
    }
    var customActions = customActionsArray.mapProperty('customCommand').filter(function(action){
      return !nonCustomAction.contains(action);
    }).uniq();

    // remove null and undefined from the list
    customActions = customActions.filter(function(value) { return value != null; });

    customActions.forEach(function(action){
      it(action + ' should be present in App.MainServiceItemView mastersExcludedCommands object', function() {
        expect(allMastersExcludedCommands).to.contain(action);
      });
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
using MusicPimp.Audio;
using MusicPimp.Models;
using MusicPimp.ViewModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace MusicPimp.Network
{
    public class PimpLibrary: IDisposable
    {
        public HttpClient Client { get; private set; }
        public string RootFolderKey { get; protected set; }
        public PimpLibrary(Uri baseAddress, string username, string password)
        : this(BuildHttpClient(baseAddress, username, password)) {
        }

        public PimpLibrary(HttpClient client)
        {
            Client = client;
            RootFolderKey = string.Empty;
        }

        private static HttpClient BuildHttpClient(Uri baseAddress, string username, string password)
        {
            var client = new HttpClient();
            client.BaseAddress = baseAddress;
            var headers = client.DefaultRequestHeaders;
            headers.Authorization = HttpUtil.BasicAuthHeaderValue(username, password);
            headers.Accept.ParseAdd("application/vnd.musicpimp.v18+json");
            return client;
        }

        public Task<VersionResponse> PingAuth()
        {
            return GetJson<VersionResponse>("/pingauth");
        }

        public Task<IEnumerable<MusicItem>> ReloadRoot()
        {
            return Reload(RootFolderKey);
        }

        public async Task<IEnumerable<MusicItem>> Reload(string id)
        {
            var uri = id == RootFolderKey ? "/folders" : $"/folders/{id}";
            var serverResponse = await GetJson<FoldersPimpResponse>(uri);
            return Itemize(serverResponse);
        }

        public async Task<IEnumerable<MusicItem>> Search(string term)
        {
            var jsonResponse = await GetJson<IEnumerable<PimpTrack>>($"/search?term={term}&limit=100");
            return jsonResponse
                .Select(AudioConversions.PimpTrackToMusicItem)
                .ToList();
        }

        private async Task<T> GetJson<T>(string uri)
        {
            var contentAsString = await GetString(uri);
            return JsonConvert.DeserializeObject<T>(contentAsString);
        }

        private async Task<string> GetString(string uri)
        {
            var response = await Client.GetAsync(uri);
            if(response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            } else
            {
                return await Task.FromException<string>(new ResponseException(response));
            }
        }

        /// <summary>
        /// maps a json response to a list of music items
        /// </summary>
        /// <param name="response">the fetched data</param>
        private List<MusicItem> Itemize(FoldersPimpResponse response)
        {
            var ret = new List<MusicItem>();
            foreach (var folder in response.folders)
            {
                ret.Add(AudioConversions.FolderToMusicItem(folder));
            }
            foreach (var track in response.tracks)
            {
                ret.Add(AudioConversions.PimpTrackToMusicItem(track));
            }
            return ret;
        }

        public void Dispose()
        {
            Client.Dispose();
        }
    }
}


text:
Follow these steps to update the examples to the latest versions of Angular (and related dependencies):

- In [shared/package.json](./shared/package.json), bump all the `@angular/*` and `@nguniversal/*` package versions to the version you want to update to and update their peer dependencies (such as `@angular-devkit/*`, `rxjs`, `typescript`, `zone.js`) and other dependencies (e.g. `@types/*`) to the latest compatible versions.

  > NOTE:
  > The [angular-cli-diff](https://github.com/cexbrayat/angular-cli-diff) repo can be a useful resource for discovering what dependency versions are used for a basic CLI app at a specific CLI version.

- In the [shared/](./shared) directory, run `yarn` to update the dependencies in the [shared/node_modules/](./shared/node_modules) directory and the [shared/yarn.lock](./shared/yarn.lock) file.

- In the [shared/](./shared) directory, run `yarn sync-deps` to update the dependency versions of the `package.json` files in each sub-folder of [shared/boilerplate/](./shared/boilerplate) to match the ones in [shared/package.json](./shared/package.json).

- Follow the steps in the following section to update the rest of the boilerplate files.

## Update other boilerplate files

The Angular CLI default setup is updated using `ng update`.
Any necessary changes to boilerplate files will be done automatically through migration schematics.

> NOTE:
> Migrations affecting source code files will not happen automatically, because `ng update` does not know about all the examples in `aio/content/examples/`.
> You have to make these changes (if any) manually.
> Again, the [angular-cli-diff](https://github.com/cexbrayat/angular-cli-diff) repo can be a useful resource for discovering changes between versions.

- In the [shared/boilerplate/cli/](./shared/boilerplate/cli) directory, run the following commands to migrate the project to the current versions of Angular CLI and the Angular framework (updated in previous steps):
  ```sh
  # Ensure dependencies are installed.
  yarn install

  # Migrate project to new versions.
  yarn ng update @angular/cli --allow-dirty --migrate-only --from=<previous-cli-version>
  yarn ng update @angular/core --allow-dirty --migrate-only --from=<previous-core-version>
  ```

  > NOTE:
  > In order for `ng update` to work, there must be a `node_modules/` directory with installed dependencies inside the [shared/boilerplate/cli/](./shared/boilerplate/cli) directory.
  > This `node_modules/` directory is only needed during the update operation and is otherwise ignored (both by git and by the [example-boilerplate.js](./example-boilerplate.js) script) by means of the [shared/boilerplate/.gitignore](./shared/boilerplate/.gitignore) file.

- The previous command made any necessary changes to boilerplate files inside the `cli/` directory, but the same changes need to be applied to the other CLI-based boilerplate directories.
  Inspect the changes in `cli/` and manually apply the necessary ones to other CLI-based boilerplate directories.

- Also ensure that any relevant changes in the [shared/boilerplate/cli/](./shared/boilerplate/cli) directory are copied to the [shared/example-scaffold/](./shared/example-scaffold) directory, which is used when creating new examples (via `yarn create-example ...`).
  Only files that would not be considered boilerplate should be added to the `example-scaffold/` directory.

- Run the following command to list all the boilerplate files that are overridden in specific examples.
  ```sh
  node aio/tools/examples/example-boilerplate.js list-overrides
  ```
  Inspect each of these files to determine whether they need to be updated.

- Inspect the changes and determine whether some of them need to be applied to the `systemjs` boilerplate files.

- Inspect the changes and determine whether any updates to guides are necessary.
  For example, if a file is renamed or moved, any guides mentioning that file may need updating to refer to the new name/location.

- Commit all changes to the repository.


text:
"use strict";

import React, {PropTypes, Component} from "react";
import {Breadcrumb, BreadcrumbItem} from "react-bootstrap";
import {LinkContainer} from "react-router-bootstrap";

export default class Breadcrumbs extends Component {

	static propTypes = {
		routes: PropTypes.array.isRequired
	};

	render() {
		return (<Breadcrumb>{this.props.routes.map((item, i) =>
			<LinkContainer key={i} to={item.path || "/"}>
				<BreadcrumbItem>
					{item.component.displayName}
				</BreadcrumbItem>
			</LinkContainer>
		)}</Breadcrumb>);
	}

}


text:
set -o errexit
set -o nounset
set -o verbose

#  Controlling environment variables:
# GTM_DISABLE_ZOMBIES -
#   Set to a non-zero value to turn on zombie checks. You will probably
#   want to turn this off if you enable leaks.
GTM_DISABLE_ZOMBIES=${GTM_DISABLE_ZOMBIES:=1}

# GTM_ENABLE_LEAKS -
#   Set to a non-zero value to turn on the leaks check. You will probably want
#   to disable zombies, otherwise you will get a lot of false positives.

# GTM_DISABLE_TERMINATION
#   Set to a non-zero value so that the app doesn't terminate when it's finished
#   running tests. This is useful when using it with external tools such
#   as Instruments.

# GTM_LEAKS_SYMBOLS_TO_IGNORE
#   List of comma separated symbols that leaks should ignore. Mainly to control
#   leaks in frameworks you don't have control over.
#   Search this file for GTM_LEAKS_SYMBOLS_TO_IGNORE to see examples.
#   Please feel free to add other symbols as you find them but make sure to
#   reference Radars or other bug systems so we can track them.

# GTM_REMOVE_GCOV_DATA
#   Before starting the test, remove any *.gcda files for the current run so
#   you won't get errors when the source file has changed and the data can't
#   be merged.
#
GTM_REMOVE_GCOV_DATA=${GTM_REMOVE_GCOV_DATA:=0}

ScriptDir=$(dirname "$(echo $0 | sed -e "s,^\([^/]\),$(pwd)/\1,")")
ScriptName=$(basename "$0")
ThisScript="${ScriptDir}/${ScriptName}"

GTMXcodeNote() {
    echo ${ThisScript}:${1}: note: GTM ${2}
}

if [ "$PLATFORM_NAME" == "iphonesimulator" ]; then
  # We kill the iPhone simulator because otherwise we run into issues where
  # the unittests fail becuase the simulator is currently running, and
  # at this time the iPhone SDK won't allow two simulators running at the same
  # time.
  set +e
  /usr/bin/killall "iPhone Simulator"
  set -e

  if [ $GTM_REMOVE_GCOV_DATA -ne 0 ]; then
    if [ "${OBJECT_FILE_DIR}-${CURRENT_VARIANT}" != "-" ]; then
      if [ -d "${OBJECT_FILE_DIR}-${CURRENT_VARIANT}" ]; then
        GTMXcodeNote ${LINENO} "Removing any .gcda files"
        (cd "${OBJECT_FILE_DIR}-${CURRENT_VARIANT}" && \
            find . -type f -name "*.gcda" -print0 | xargs -0 rm -f )
      fi
    fi
  fi

  export DYLD_ROOT_PATH="$SDKROOT"
  export DYLD_FRAMEWORK_PATH="$CONFIGURATION_BUILD_DIR"
  export IPHONE_SIMULATOR_ROOT="$SDKROOT"
  export CFFIXED_USER_HOME="$TEMP_FILES_DIR/iPhone Simulator User Dir"

  # See http://developer.apple.com/technotes/tn2004/tn2124.html for an
  # explanation of these environment variables.

  export MallocScribble=YES
  export MallocPreScribble=YES
  export MallocGuardEdges=YES
  export MallocStackLogging=YES
  export NSAutoreleaseFreedObjectCheckEnabled=YES

  # Turn on the mostly undocumented OBJC_DEBUG stuff.
  export OBJC_DEBUG_FRAGILE_SUPERCLASSES=YES
  export OBJC_DEBUG_UNLOAD=YES
  # Turned off due to the amount of false positives from NS classes.
  # export OBJC_DEBUG_FINALIZERS=YES
  export OBJC_DEBUG_NIL_SYNC=YES
  export OBJC_PRINT_REPLACED_METHODS=YES

  if [ $GTM_DISABLE_ZOMBIES -eq 0 ]; then
    GTMXcodeNote ${LINENO} "Enabling zombies"
    export CFZombieLevel=3
    export NSZombieEnabled=YES
  fi

  # Cleanup user home and documents directory
  if [ -d "$CFFIXED_USER_HOME" ]; then
    rm -rf "$CFFIXED_USER_HOME"
  fi
  mkdir "$CFFIXED_USER_HOME"
  mkdir "$CFFIXED_USER_HOME/Documents"

  # 6251475 iPhone simulator leaks @ CFHTTPCookieStore shutdown if
  #         CFFIXED_USER_HOME empty
  GTM_LEAKS_SYMBOLS_TO_IGNORE="CFHTTPCookieStore"

  "$TARGET_BUILD_DIR/$EXECUTABLE_PATH" -RegisterForSystemEvents
else
  GTMXcodeNote ${LINENO} "Skipping running of unittests for device build."
fi
exit 0


text:
<?php

/**
 *  获取选项列表
 *
 * @access    public
 * @param     string  $selid  选择ID
 * @param     string  $userCatalog  用户类目
 * @param     string  $channeltype  频道类型
 * @return    string
 */
function GetOptionList($selid=0, $userCatalog=0, $channeltype=0)
{
    global $OptionArrayList, $channels, $dsql, $cfg_admin_channel, $admin_catalogs;

    $dsql->SetQuery("SELECT id,typename FROM `#@__channeltype` ");
    $dsql->Execute();
    $channels = Array();
    while($row = $dsql->GetObject()) $channels[$row->id] = $row->typename;

    $OptionArrayList = '';

    //当前选中的栏目
    if($selid > 0)
    {
        $row = $dsql->GetOne("SELECT id,typename,ispart,channeltype FROM `#@__arctype` WHERE id='$selid'");
        if($row['ispart']==1) $OptionArrayList .= "<option value='".$row['id']."' class='option1' selected='selected'>".$row['typename']."(封面频道)</option>\r\n";
        else $OptionArrayList .= "<option value='".$row['id']."' selected='selected'>".$row['typename']."</option>\r\n";
    }

    //是否限定用户管理的栏目
    if( $cfg_admin_channel=='array' )
    {
        if(count($admin_catalogs)==0)
        {
            $query = "SELECT id,typename,ispart,channeltype FROM `#@__arctype` WHERE 1=2 ";
        }
        else
        {
            $admin_catalog = join(',', $admin_catalogs);
            $dsql->SetQuery("SELECT reid FROM `#@__arctype` WHERE id IN($admin_catalog) GROUP BY reid ");
            $dsql->Execute();
            $topidstr = '';
            while($row = $dsql->GetObject())
            {
                if($row->reid==0) continue;
                $topidstr .= ($topidstr=='' ? $row->reid : ','.$row->reid);
            }
            $admin_catalog .= ','.$topidstr;
            $admin_catalogs = explode(',', $admin_catalog);
            $admin_catalogs = array_unique($admin_catalogs);
            $admin_catalog = join(',', $admin_catalogs);
            $admin_catalog = preg_replace("#,$#", '', $admin_catalog);
            $query = "SELECT id,typename,ispart,channeltype FROM `#@__arctype` WHERE id IN($admin_catalog) AND reid=0 AND ispart<>2 ";
        }
    }
    else
    {
        $query = "SELECT id,typename,ispart,channeltype FROM `#@__arctype` WHERE ispart<>2 AND reid=0 ORDER BY sortrank ASC ";
    }

    $dsql->SetQuery($query);
    $dsql->Execute();

    while($row=$dsql->GetObject())
    {
        $sonCats = '';
        LogicGetOptionArray($row->id, '─', $channeltype, $dsql, $sonCats);
        if($sonCats != '')
        {
            if($row->ispart==1) $OptionArrayList .= "<option value='".$row->id."' class='option1'>".$row->typename."(封面频道)</option>\r\n";
            else if($row->ispart==2) $OptionArrayList .= '';
            else if( empty($channeltype) && $row->ispart != 0 ) $OptionArrayList .= "<option value='".$row->id."' class='option2'>".$row->typename."(".$channels[$row->channeltype].")</option>\r\n";
            else $OptionArrayList .= "<option value='".$row->id."' class='option3'>".$row->typename."</option>\r\n";
            $OptionArrayList .= $sonCats;
        }
        else
        {
            if($row->ispart==0 && (!empty($channeltype) && $row->channeltype == $channeltype) )
            {
                $OptionArrayList .= "<option value='".$row->id."' class='option3'>".$row->typename."</option>\r\n";
            } else if($row->ispart==0 && empty($channeltype) )
            {
                // 专题
                $OptionArrayList .= "<option value='".$row->id."' class='option3'>".$row->typename."</option>\r\n";
            }
        }
    }
    return $OptionArrayList;
}

function LogicGetOptionArray($id,$step,$channeltype,&$dsql, &$sonCats)
{
    global $OptionArrayList, $channels, $cfg_admin_channel, $admin_catalogs;
    $dsql->SetQuery("Select id,typename,ispart,channeltype From `#@__arctype` where reid='".$id."' And ispart<>2 order by sortrank asc");
    $dsql->Execute($id);
    while($row=$dsql->GetObject($id))
    {
        if($cfg_admin_channel != 'all' && !in_array($row->id, $admin_catalogs))
        {
            continue;
        }
        if($row->channeltype==$channeltype && $row->ispart==1)
        {
            $sonCats .= "<option value='".$row->id."' class='option1'>$step".$row->typename."</option>\r\n";
        }
        else if( ($row->channeltype==$channeltype && $row->ispart==0) || empty($channeltype) )
        {
            $sonCats .= "<option value='".$row->id."' class='option3'>$step".$row->typename."</option>\r\n";
        }
        LogicGetOptionArray($row->id,$step.'─',$channeltype,$dsql, $sonCats);
    }
}


text:
package com.github.ptest.element;

import com.github.ptest.runConfiguration.PTestRunConfiguration;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.jetbrains.python.psi.PyClass;

import java.nio.file.Paths;

public class PTestXML extends PTestElement<PsiFile> {

    public PTestXML(PsiFile xmlFile) {
        super(xmlFile);
    }

    @Override
    public boolean setupConfiguration(PTestRunConfiguration configuration) {
        try {
            configuration.setValueForEmptyWorkingDirectory();
            configuration.setRunFailed(true);
            String xmlPath = getValue().getVirtualFile().getCanonicalPath();
            String xmlRelativePath = Paths.get(configuration.getWorkingDirectory()).relativize(Paths.get(xmlPath)).toString();
            configuration.setXunitXML(xmlRelativePath);
            configuration.setSuggestedName("ptests in " + xmlRelativePath);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static PTestXML createFrom(PsiElement element) {
        if (element instanceof PsiFile) {
            PsiFile xmlFile = (PsiFile) element;
            VirtualFile file = xmlFile.getVirtualFile();
            return file.getExtension() != null && file.getExtension().equalsIgnoreCase("xml") ? new PTestXML(xmlFile) : null;
        }
        return null;
    }
}


text:
import React            from 'react';
import ReactDOM         from 'react-dom';
import ActionListWidget from '..';

// Load CSS
require('normalize.css');
require('font-awesome/css/font-awesome.css');

const
    container = document.querySelector('.content'),
    list = [
        { name: 'Menu', action: 'something', data: 'CustomData...', icon: 'fa fa-fw fa-bars'},
        { name: 'Sub-menu', action: 'something else', icon: 'fa fa-fw fa-folder-o'},
        { name: 'regular', action: 'justMe', icon: 'fa fa-fw '},
        { name: 'a', action: 'a', icon: 'fa fa-fw fa-file-o'},
        { name: 'b', action: 'b', icon: 'fa fa-fw fa-file-o'},
        { name: 'c', action: 'c', icon: 'fa fa-fw fa-file-o'},
    ];

function onClick(name, action, user) {
    console.log(name, action, user);
}

ReactDOM.render(
    React.createElement(
        ActionListWidget,
        { list, onClick }),
    container);

document.body.style.margin = '10px';


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require 'matrix'

describe "Vector#eql?" do
  before do
    @vector = Vector[1, 2, 3, 4, 5]
  end

  it "returns true for self" do
    @vector.eql?(@vector).should be_true
  end

  it "returns false when there are a pair corresponding elements which are not equal in the sense of Kernel#eql?" do
    @vector.eql?(Vector[1, 2, 3, 4, 5.0]).should be_false
  end
end


text:
namespace gameplay
{

// Lua bindings for AudioSource.
int lua_AudioSource__gc(lua_State* state);
int lua_AudioSource_addRef(lua_State* state);
int lua_AudioSource_getGain(lua_State* state);
int lua_AudioSource_getNode(lua_State* state);
int lua_AudioSource_getPitch(lua_State* state);
int lua_AudioSource_getRefCount(lua_State* state);
int lua_AudioSource_getState(lua_State* state);
int lua_AudioSource_getVelocity(lua_State* state);
int lua_AudioSource_isLooped(lua_State* state);
int lua_AudioSource_isStreamed(lua_State* state);
int lua_AudioSource_pause(lua_State* state);
int lua_AudioSource_play(lua_State* state);
int lua_AudioSource_release(lua_State* state);
int lua_AudioSource_resume(lua_State* state);
int lua_AudioSource_rewind(lua_State* state);
int lua_AudioSource_setGain(lua_State* state);
int lua_AudioSource_setLooped(lua_State* state);
int lua_AudioSource_setPitch(lua_State* state);
int lua_AudioSource_setVelocity(lua_State* state);
int lua_AudioSource_static_create(lua_State* state);
int lua_AudioSource_stop(lua_State* state);

void luaRegister_AudioSource();

}

#endif


text:
'use strict';

require('../app/support/setup');
var requireNew = require('require-new');

describe('Orchestra', function() {
	beforeEach(function() {
		this.Orchestra = requireNew('../../src/index.js');
	});

	it('should expose Marionette classes', function() {
		expect(this.Orchestra.View).to.be.a('function');
		expect(this.Orchestra.CollectionView).to.be.a('function');
	});

	it('should expose the Backbone.Radio object', function() {
		expect(this.Orchestra.Radio).to.be.an('object');
	});

  it('should expose the Backbone.Syphon object', function() {
    expect(this.Orchestra.Syphon).to.be.an('object');
  });

  it('should expose the Backbone.Validation object', function() {
    expect(this.Orchestra.Validation).to.be.an('object');
  });

	it('should expose the Collection class', function() {
		expect(this.Orchestra.Collection).to.be.a('function');
	});

	it('should expose the Currency helper object', function() {
		expect(this.Orchestra.Currency).to.be.an('object');
	});

	it('should expose the Visibility helper object', function() {
		expect(this.Orchestra.Visibility).to.be.an('object');
	});

	it('should expose the Translator helper object', function() {
		expect(this.Orchestra.Translator).to.be.an('object');
	});

	it('should expose jQuery', function() {
		expect(this.Orchestra.$).to.be.a('function');
	});

	it('should expose lodash', function() {
		expect(this.Orchestra._).to.be.a('function');
	});

	describe('if window.agent exists', function() {
		beforeEach(function() {
			window.__agent = {
				start: this.sandbox.stub()
			};

			this.Orchestra = requireNew('../../src/index.js');
		});

		it('should call start', function() {
			expect(window.__agent.start.callCount).to.eql(1);
		});
	});
});


text:
/* Author: Ioan Sucan, Jon Binney */

#include <moveit/occupancy_map_monitor/occupancy_map_monitor.h>
#include <moveit/occupancy_map_monitor/occupancy_map_updater.h>

namespace occupancy_map_monitor
{
static const std::string LOGNAME = "occupancy_map_monitor";

OccupancyMapUpdater::OccupancyMapUpdater(const std::string& type) : type_(type)
{
}

OccupancyMapUpdater::~OccupancyMapUpdater() = default;

void OccupancyMapUpdater::setMonitor(OccupancyMapMonitor* monitor)
{
  monitor_ = monitor;
  tree_ = monitor->getOcTreePtr();
}

void OccupancyMapUpdater::readXmlParam(XmlRpc::XmlRpcValue& params, const std::string& param_name, double* value)
{
  if (params.hasMember(param_name))
  {
    if (params[param_name].getType() == XmlRpc::XmlRpcValue::TypeInt)
      *value = (int)params[param_name];
    else
      *value = (double)params[param_name];
  }
}

void OccupancyMapUpdater::readXmlParam(XmlRpc::XmlRpcValue& params, const std::string& param_name, unsigned int* value)
{
  if (params.hasMember(param_name))
    *value = (int)params[param_name];
}

bool OccupancyMapUpdater::updateTransformCache(const std::string& target_frame, const ros::Time& target_time)
{
  transform_cache_.clear();
  if (transform_provider_callback_)
  {
    bool success = transform_provider_callback_(target_frame, target_time, transform_cache_);
    if (!success)
      ROS_ERROR_THROTTLE_NAMED(
          1, LOGNAME,
          "Transform cache was not updated. Self-filtering may fail. If transforms were not available yet, consider "
          "setting robot_description_planning/shape_transform_cache_lookup_wait_time to wait longer for transforms");
    return success;
  }
  else
  {
    ROS_WARN_THROTTLE_NAMED(1, LOGNAME, "No callback provided for updating the transform cache for octomap updaters");
    return false;
  }
}
}  // namespace occupancy_map_monitor


text:
package io.jenkins.blueocean.rest.impl.pipeline;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import io.jenkins.blueocean.rest.hal.Link;
import io.jenkins.blueocean.rest.model.BluePipelineNode;
import io.jenkins.blueocean.rest.model.BlueRun;
import org.jenkinsci.plugins.workflow.actions.LabelAction;
import org.jenkinsci.plugins.workflow.actions.NotExecutedNodeAction;
import org.jenkinsci.plugins.workflow.actions.StageAction;
import org.jenkinsci.plugins.workflow.actions.TimingAction;
import org.jenkinsci.plugins.workflow.cps.nodes.StepAtomNode;
import org.jenkinsci.plugins.workflow.cps.nodes.StepEndNode;
import org.jenkinsci.plugins.workflow.graph.FlowGraphWalker;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.plugins.workflow.support.visualization.table.FlowGraphTable;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import static io.jenkins.blueocean.rest.impl.pipeline.PipelineNodeUtil.isParallelBranch;
import static io.jenkins.blueocean.rest.impl.pipeline.PipelineNodeUtil.isStage;

/**
 * Filters {@link FlowGraphTable} to BlueOcean specific model representing DAG like graph objects
 *
 * @author Vivek Pandey
 */
public class PipelineNodeGraphBuilder {

    private final List<FlowNode> sortedNodes;

    private final WorkflowRun run;
    private final Map<FlowNode, List<FlowNode>> parentToChildrenMap = new LinkedHashMap<>();
    private final Map<FlowNode, PipelineNodeGraphBuilder.NodeRunStatus> nodeStatusMap = new LinkedHashMap<>();

    public PipelineNodeGraphBuilder(WorkflowRun run) {
        this.run = run;

        TreeSet<FlowNode> nodeTreeSet = new TreeSet<>(new Comparator<FlowNode>() {
            @Override
            public int compare(FlowNode node1, FlowNode node2) {
                return Integer.compare(parseIota(node1), parseIota(node2));
            }

            private int parseIota(FlowNode node) {
                try {
                    return Integer.parseInt(node.getId());
                } catch (NumberFormatException e) {
                    return 0;
                }
            }
        });

        if(run.getExecution() != null) {
            Iterables.addAll(nodeTreeSet, new FlowGraphWalker(run.getExecution()));
        }
        this.sortedNodes = Collections.unmodifiableList(new ArrayList<>(nodeTreeSet));
//        dumpNodes(sortedNodes);
        build();

    }

    private void build(){
        FlowNode previousStage = null;
        FlowNode previousBranch = null;
        int count = 0;
        for (FlowNode node : sortedNodes) {
            if(!isStage(node) && !isParallelBranch(node)){
                continue;
            }
            boolean nestedInParallel = PipelineNodeUtil.isNestedInParallel(sortedNodes, node);
            if (isStage(node) && !nestedInParallel) { //Stage but not nested
                addChild(node, null);
                if (previousBranch != null) {
                    /**
                     * We encountered stage after previous branch, we need to
                     *  - get all branches from previous stage
                     *  - add this stage node as child to all branches
                     */
                    List<FlowNode> branches = parentToChildrenMap.get(previousStage);
                    for (FlowNode n : branches) {
                        addChild(n, node);
                    }
                    previousBranch = null;
                } else if (previousStage != null) {
                    addChild(previousStage, node);
                } else { //previousStage is null
                    addChild(node, null);
                }

                if(node.getAction(LabelAction.class) != null && node.getAction(StageAction.class) == null){
                    FlowNode endNode = PipelineNodeUtil.getStepEndNode(sortedNodes, node);
                    if(endNode == null){
                        endNode = PipelineNodeUtil.getEndNode(sortedNodes,node);
                    }
                    if(endNode != null){
                        nodeStatusMap.put(node, new PipelineNodeGraphBuilder.NodeRunStatus(endNode));
                    }
                }else if(previousStage!=null){
                    nodeStatusMap.put(previousStage, new PipelineNodeGraphBuilder.NodeRunStatus(sortedNodes.get(count - 1)));
                }
                previousStage = node;
            } else if (isParallelBranch(node) && !nestedInParallel) { //branch but not nested ones
                addChild(node, null);
                if(previousStage != null) {
                    addChild(previousStage, node);
                }
                FlowNode endNode = PipelineNodeUtil.getStepEndNode(sortedNodes,node);
                if (endNode != null) {
                    nodeStatusMap.put(node, new PipelineNodeGraphBuilder.NodeRunStatus(endNode));
                }else{
                    //It's still running, report it as state: running and result: unknown
                    nodeStatusMap.put(node, new PipelineNodeGraphBuilder.NodeRunStatus(BlueRun.BlueRunResult.UNKNOWN, BlueRun.BlueRunState.RUNNING));
                }
                previousBranch = node;
            }
            count++;
        }
        int size = parentToChildrenMap.keySet().size();
        if (size > 0) {
            PipelineNodeGraphBuilder.NodeRunStatus runStatus = PipelineNodeUtil.getStatus(run);
            FlowNode lastNode = getLastStageNode();
            nodeStatusMap.put(lastNode, runStatus);
        }
    }

    public FlowNode getNodeById(String id){
        for(FlowNode node: sortedNodes){
            if(node.getId().equals(id)){
                return node;
            }
        }
        return null;
    }

    public List<FlowNode> getSteps(FlowNode node){
        if(isStage(node)){
            return getStageSteps(node);
        }else if(isParallelBranch(node)){
            return getParallelBranchSteps(node);
        }
        return Collections.emptyList();
    }

    public List<FlowNode> getStageSteps(FlowNode p){
        List<FlowNode> steps = new ArrayList<>();
        int i = sortedNodes.indexOf(p);
        if(i>=0 && isStage(p)){
            FlowNode end = PipelineNodeUtil.getStepEndNode(sortedNodes,p);
            //collect steps till next stage is found otherwise till end of pipeline
            for(int j=i+1; j < sortedNodes.size(); j++){
                FlowNode c = sortedNodes.get(j);
                //if the stage is not nested ignore them, because we want to include steps from nested stages
                if(isStage(c) && !PipelineNodeUtil.isInBlock(p,end,c)){
                    break;
                }
                if(c instanceof StepAtomNode) {
                    steps.add(c);
                }
            }
        }
        return steps;
    }

    public List<FlowNode> getAllSteps(){
        List<FlowNode> steps = new ArrayList<>();
        for(FlowNode c: sortedNodes){
            if(c instanceof StepAtomNode && !isStage(c)) {
                steps.add(c);
            }
        }
        return steps;
    }

    public List<FlowNode> getParallelBranchSteps(FlowNode p){
        List<FlowNode> steps = new ArrayList<>();
        int i = sortedNodes.indexOf(p);
        FlowNode prev=p;
        if(i>=0 && isParallelBranch(p)){
            FlowNode end = PipelineNodeUtil.getStepEndNode(sortedNodes,p);
            for(int j=i+1; j < sortedNodes.size(); j++){
                FlowNode c = sortedNodes.get(j);
                if(c.equals(end)){
                    nodeStatusMap.put(p, new PipelineNodeGraphBuilder.NodeRunStatus(end));
                    break;
                }
                if(isParallelBranch(c)){
                    continue;
                }
                //we take only the legal children
                if(!PipelineNodeUtil.isInBlock(p, end, c) && !isParentOf(c,prev)){
                    continue;
                }
                if(c instanceof StepAtomNode) {
                    steps.add(c);
                    prev=c;

                    FlowNode endNode = PipelineNodeUtil.getStepEndNode(sortedNodes,c);
                    if (endNode != null) {
                        nodeStatusMap.put(c, new PipelineNodeGraphBuilder.NodeRunStatus(endNode));
                    }
                }
            }
        }
        return steps;
    }

    private boolean isParentOf(FlowNode node, FlowNode child){
        for(FlowNode n:node.getParents()){
            if(child.equals(n)){
                return true;
            }
        }
        return false;
    }

    /**
     * Create a union of current pipeline nodes with the one from future. Term future indicates that
     * this list of nodes are either in the middle of processing or failed somewhere in middle and we are
     * projecting future nodes in the pipeline.
     * <p>
     * Last element of this node is patched to point to the first node of given list. First node of given
     * list is indexed at thisNodeList.size().
     *
     * @param other Other {@link PipelineNodeGraphBuilder} to create union with
     * @return list of FlowNode that is union of current set of nodes and the given list of nodes. If futureNodes
     * are not bigger than this pipeline nodes then no union is performed.
     * @see PipelineNodeContainerImpl#PipelineNodeContainerImpl(WorkflowRun, Link)
     */
    public List<BluePipelineNode> union(PipelineNodeGraphBuilder other, Link parentLink) {
        Map<FlowNode, List<FlowNode>> futureNodes = other.parentToChildrenMap;
        if (parentToChildrenMap.size() < futureNodes.size()) {

            // XXX: If the pipeline was modified since last successful run then
            // the union might represent invalid future nodes.
            List<FlowNode> nodes = ImmutableList.copyOf(parentToChildrenMap.keySet());
            List<FlowNode> thatNodes = ImmutableList.copyOf(futureNodes.keySet());
            int currentNodeSize = nodes.size();
            for (int i = nodes.size(); i < futureNodes.size(); i++) {
                InactiveFlowNodeWrapper n = new InactiveFlowNodeWrapper(thatNodes.get(i));

                // Add the last successful pipeline's first node to the edge of current node's last node
                if (currentNodeSize> 0 && i == currentNodeSize) {
                    FlowNode latestNode = nodes.get(currentNodeSize - 1);
                    if (isStage(latestNode)) {
                        addChild(latestNode, n);
                    } else if (isParallelBranch(latestNode)) {
                        /**
                         * If its a parallel node, find all its siblings and add the next node as
                         * edge (if not already present)
                         */
                        //parallel node has at most one paraent
                        FlowNode parent = getParentStageOfBranch(latestNode);
                        if (parent != null) {
                            List<FlowNode> children = parentToChildrenMap.get(parent);
                            for (FlowNode c : children) {
                                // Add next node to the parallel node's edge
                                if (isParallelBranch(c)) {
                                    addChild(c, n);
                                }
                            }
                        }
                    }
                }
                parentToChildrenMap.put(n, futureNodes.get(n.inactiveNode));
            }
        }
        return getPipelineNodes(parentLink);
    }

    public List<BluePipelineNode> getPipelineNodes(Link parentLink) {
        List<BluePipelineNode> nodes = new ArrayList<>();
        for (FlowNode n : parentToChildrenMap.keySet()) {
            PipelineNodeGraphBuilder.NodeRunStatus status = nodeStatusMap.get(n);

            if (!isExecuted(n)) {
                status = new PipelineNodeGraphBuilder.NodeRunStatus(BlueRun.BlueRunResult.UNKNOWN, BlueRun.BlueRunState.QUEUED);
            } else if (status == null) {
                status = getEffectiveBranchStatus(n);
            }
            nodes.add(new PipelineNodeImpl(run, n, status, this,parentLink));
        }
        return nodes;
    }

    public List<FlowNode> getChildren(FlowNode parent){
        return parentToChildrenMap.get(parent);
    }

    @Nullable
    public Long getDurationInMillis(FlowNode node){
        long startTime = TimingAction.getStartTime(node);
        if( startTime == 0){
            return null;
        }
        /**
         * For Stage node:
         *
         * Find next stage node
         * duration = nextStageNodeStartTime - thisStageNode.startTime
         *
         * For Parallel node:
         *
         * Find the endNode of the parallel branch
         * duration = endNode.startTime - thisNode.startTime
         *
         * If this happens to be the last stage or parallel node in the pipeline
         * duration = pipelineEndTime - thisStageNode.startTime
         *
         */
        if(isStage(node)){
            boolean lookForNextStage = false;
            for(FlowNode n: parentToChildrenMap.keySet()){
                if(n.equals(node)){
                    lookForNextStage = true;
                    continue;
                }
                if(lookForNextStage && isStage(n)){ //we got the next stage
                    return TimingAction.getStartTime(n) - startTime;
                }
            }
        }else if(isParallelBranch(node)){
            FlowNode endNode = PipelineNodeUtil.getStepEndNode(sortedNodes,node);
            if(endNode != null){
                return TimingAction.getStartTime(endNode) - startTime;
            }
        }else if(node instanceof StepAtomNode){
            int i = sortedNodes.indexOf(node);
            if(i >=0 && i+1 < sortedNodes.size()){
                return TimingAction.getStartTime(sortedNodes.get(i+1)) - startTime;
            }
        }
        return run.getExecution().isComplete()
            ? (run.getDuration() + run.getStartTimeInMillis()) - startTime
            : System.currentTimeMillis() - startTime;
    }

    private boolean isEnd(FlowNode n){
        return n instanceof StepEndNode;
    }
    private FlowNode getLastNode() {
        if (parentToChildrenMap.keySet().isEmpty()) {
            return null;
        }
        FlowNode node = null;
        for (FlowNode n : parentToChildrenMap.keySet()) {
            node = n;
        }
        return node;
    }

    private FlowNode getParentStageOfBranch(FlowNode node) {
        if (node.getParents().size() == 0) {
            return null;
        }
        FlowNode p = node.getParents().get(0);
        if (isStage(p)) {
            return p;
        }
        return getParentStageOfBranch(p);
    }

    private FlowNode getLastStageNode() {
        if (parentToChildrenMap.keySet().isEmpty()) {
            return null;
        }
        FlowNode node = null;
        for (FlowNode n : parentToChildrenMap.keySet()) {
            if (isStage(n)) {
                node = n;
            }
        }
        return node;
    }

    private FlowNode getLastBranchNode() {
        if (parentToChildrenMap.keySet().isEmpty()) {
            return null;
        }
        FlowNode node = null;
        for (FlowNode n : parentToChildrenMap.keySet()) {
            if (isParallelBranch(n)) {
                node = n;
            }
        }
        return node;
    }

    private NodeRunStatus getEffectiveBranchStatus(FlowNode n) {
        List<FlowNode> children = parentToChildrenMap.get(n);
        BlueRun.BlueRunResult result = BlueRun.BlueRunResult.SUCCESS;
        BlueRun.BlueRunState state = BlueRun.BlueRunState.FINISHED;
        boolean atLeastOneBranchDidNotSucceed = false;
        boolean atLeastOneBranchisUnknown = false;
        for (FlowNode c : children) {
            if (isParallelBranch(c)) {
                PipelineNodeGraphBuilder.NodeRunStatus s = nodeStatusMap.get(c);
                if (s == null) {
                    continue;
                }
                if (!atLeastOneBranchDidNotSucceed && s.getResult() == BlueRun.BlueRunResult.FAILURE ||
                    s.getResult() == BlueRun.BlueRunResult.UNSTABLE) {
                    atLeastOneBranchDidNotSucceed = true;
                    result = s.getResult();
                }

                if (s.getResult() == BlueRun.BlueRunResult.UNKNOWN) {
                    atLeastOneBranchisUnknown = true;
                }
                if (s.getState() != BlueRun.BlueRunState.FINISHED) {
                    if (state != BlueRun.BlueRunState.RUNNING) {
                        state = s.getState();
                    }
                }
            }
        }

        if (!atLeastOneBranchDidNotSucceed && atLeastOneBranchisUnknown) {
            result = BlueRun.BlueRunResult.UNKNOWN;
        }

        return new PipelineNodeGraphBuilder.NodeRunStatus(result, state);
    }

    private boolean isExecuted(FlowNode node) {
        return NotExecutedNodeAction.isExecuted(node);
    }

    private List<FlowNode> addChild(FlowNode parent, FlowNode child) {
        List<FlowNode> children = parentToChildrenMap.get(parent);
        if (children == null) {
            children = new ArrayList<>();
            parentToChildrenMap.put(parent, children);
        }
        if (child != null) {
            children.add(child);
        }
        return children;
    }

    public void dumpNodes(List<FlowNode> nodes) {
        for (FlowNode n : nodes) {
            System.out.println(String.format("id: %s, name: %s, startTime: %s, type: %s, parent: %s", n.getId(), n.getDisplayName(), TimingAction.getStartTime(n), n.getClass(), n.getParents().size() > 0 ? n.getParents().get(0).getId(): null));
        }
    }

    public static class NodeRunStatus {
        private final BlueRun.BlueRunResult result;
        private final BlueRun.BlueRunState state;

        public NodeRunStatus(FlowNode endNode) {
            if (endNode.getError() != null) {
                this.result = BlueRun.BlueRunResult.FAILURE;
                this.state = endNode.isRunning() ? BlueRun.BlueRunState.RUNNING : BlueRun.BlueRunState.FINISHED;
            }else if (endNode.isRunning()) {
                this.result = BlueRun.BlueRunResult.UNKNOWN;
                this.state = BlueRun.BlueRunState.RUNNING;
            } else if (NotExecutedNodeAction.isExecuted(endNode)) {
                this.result = PipelineNodeUtil.getStatus(endNode.getError());
                this.state = BlueRun.BlueRunState.FINISHED;
            } else {
                this.result = BlueRun.BlueRunResult.NOT_BUILT;
                this.state = BlueRun.BlueRunState.QUEUED;
            }
        }

        public NodeRunStatus(BlueRun.BlueRunResult result, BlueRun.BlueRunState state) {
            this.result = result;
            this.state = state;
        }

        public BlueRun.BlueRunResult getResult() {
            return result;
        }

        public BlueRun.BlueRunState getState() {
            return state;
        }
    }

    public static class InactiveFlowNodeWrapper extends FlowNode {

        private final FlowNode inactiveNode;

        public InactiveFlowNodeWrapper(FlowNode node) {
            super(node.getExecution(), node.getId());
            this.inactiveNode = node;
        }

        @Override
        protected String getTypeDisplayName() {
            return PipelineNodeUtil.getDisplayName(inactiveNode);
        }
    }

    public List<FlowNode> getSages(){
        List<FlowNode> stages = new ArrayList<>();

        for(FlowNode n: parentToChildrenMap.keySet()){
            if(isStage(n)){
                stages.add(n);
            }
        }
        return stages;
    }

    public List<FlowNode> getParallelBranches(){
        List<FlowNode> parallel = new ArrayList<>();

        for(FlowNode n: parentToChildrenMap.keySet()){
            if(isParallelBranch(n)){
                parallel.add(n);
            }
        }
        return parallel;
    }
}


text:
'use strict';

/**
 * Pipeline reference type.
 *
 */
class PipelineReference {
  /**
   * Create a PipelineReference.
   * @member {string} referenceName Reference pipeline name.
   * @member {string} [name] Reference name.
   */
  constructor() {
  }

  /**
   * Defines the metadata of PipelineReference
   *
   * @returns {object} metadata of PipelineReference
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'PipelineReference',
      type: {
        name: 'Composite',
        className: 'PipelineReference',
        modelProperties: {
          type: {
            required: true,
            isConstant: true,
            serializedName: 'type',
            defaultValue: 'PipelineReference',
            type: {
              name: 'String'
            }
          },
          referenceName: {
            required: true,
            serializedName: 'referenceName',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = PipelineReference;


text:
//
//  Copyright (c) 2018 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "FUIAuthUtils.h"

NS_ASSUME_NONNULL_BEGIN

/* Name of the FirebaseEmailAuthUI resource bundle. */
extern NSString *const FUIEmailAuthBundleName;

#ifdef __cplusplus
extern "C" {
#endif

/** @fn FUIEmailAuthLocalizedString
    @brief Gets a localized string from a name.
    @param key The key value of the string.
    @return The string by the key localized in the current locale.
 */
NSString *FUIEmailAuthLocalizedString(NSString *key);

#ifdef __cplusplus
}
#endif

NS_ASSUME_NONNULL_END


text:
package fry.diabetes.tracking;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;

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

public class Day {
	private final Map<Duration, RateConfiguration> rates;
	private final Map<Duration, BodyGlucose> bodyGlucose;
	private final Collection<FoodEvent> foods;
	private final Collection<InsulinEvent> boluses;

	public Day(Map<Duration, RateConfiguration> rates,
				Map<Duration, BodyGlucose> bodyGlucose,
				Collection<FoodEvent> foods,
				Collection<InsulinEvent> boluses) {
		this.rates = Maps.newHashMap(rates);
		this.bodyGlucose = Maps.newHashMap(bodyGlucose);
		this.foods = Lists.newArrayList(foods);
		this.boluses = Lists.newArrayList(boluses);
	}

	public static void main(String[] args) throws IOException {
		RateConfiguration allDay = new RateConfiguration(1.2 / 60, 30, 6);
		Duration theDay = Duration.betweenHours(0, 24);
		BodyGlucose bGluc = new BodyGlucose(0.12);
		Map<Duration, RateConfiguration> rates = ImmutableMap.<Duration, RateConfiguration>builder().put(theDay, allDay).build();
		Map<Duration, BodyGlucose> bodyGlucose = ImmutableMap.<Duration, BodyGlucose>builder().put(theDay, bGluc).build();
		Collection<FoodEvent> foods = Lists.newArrayList();
		Collection<InsulinEvent> boluses = Lists.newArrayList();

		// breakfast
		boluses.add(InsulinEvent.bolusOfUnits(10, 9*60));
		foods.add(FoodEvent.fromCarbs(60, 9*60 + 20));

		Day day = new Day(rates, bodyGlucose, foods, boluses);
		List<Double> gluc = day.simulateDay();
		String file = "";
		for (int i = 8*60; i < 12*60; i++) {
			file += i + " " + gluc.get(i) + "\n";
		}
		FileUtils.writeStringToFile(new File(System.getProperty("user.dir") + "/outputs"), file);
	}

	public List<Double> simulateDay() {
		List<ProviderFunction> insulinFunctions = Lists.newArrayList();
		List<ProviderFunction> glucoseFunctions = Lists.newArrayList();

		for (FoodEvent event : foods) {
			glucoseFunctions.add(getFoodProviderFunction(event.getCarbs(), event.getTime()));
		}
		for (InsulinEvent event : boluses) {
			insulinFunctions.add(getInsulinProviderFunction(event.getQuantity(), event.getTime()));
		}
		for (int time = 0; time < Duration.MINUTES_IN_DAY; time++) {
			RateConfiguration rateConfig = getConfigFromTime(time);
			BodyGlucose bodyGlucose = getGlucoseFromTime(time);
			insulinFunctions.add(getInsulinProviderFunction(rateConfig.getBasalRate(), time));
			glucoseFunctions.add(getFoodProviderFunction(bodyGlucose.getRate(), time));
		}

		List<Double> day = Lists.newArrayList();
		double bloodGlucose = 100;
		for (int time = 0; time < Duration.MINUTES_IN_DAY; time++) {
			RateConfiguration rateConfig = getConfigFromTime(time);
			for (ProviderFunction func : insulinFunctions) {
				bloodGlucose -= rateConfig.getPointsPerUnit() / InsulinFunction.INTEGRAL * func.getValueAtTime(time);
			}
			for (ProviderFunction func : glucoseFunctions) {
				bloodGlucose += 1.0 / rateConfig.getCarbsPerUnit() * rateConfig.getPointsPerUnit() * func.getValueAtTime(time);
			}
			day.add(bloodGlucose);
		}
		return day;
	}

	private ProviderFunction getInsulinProviderFunction(final double value, final int start) {
		return new ProviderFunction() {
			@Override
			public double getValueAtTime(int minutes) {
				return InsulinFunction.getConcentrationAfterStart(minutes - start) * value;
			}
		};
	}

	private ProviderFunction getFoodProviderFunction(final double value, final int start) {
		return new ProviderFunction() {
			@Override
			public double getValueAtTime(int minutes) {
				return CarbFunction.getAddedDuringMinute(minutes - start) * value;
			}
		};
	}

	private BodyGlucose getGlucoseFromTime(int time) {
		for (Map.Entry<Duration, BodyGlucose> entry : bodyGlucose.entrySet()) {
			if (entry.getKey().containsMinute(time)) {
				return entry.getValue();
			}
		}
		throw new IllegalArgumentException("No glucose for time " + time);
	}

	private RateConfiguration getConfigFromTime(int time) {
		for (Map.Entry<Duration, RateConfiguration> entry : rates.entrySet()) {
			if (entry.getKey().containsMinute(time)) {
				return entry.getValue();
			}
		}
		throw new IllegalArgumentException("No config for time " + time);
	}
}


text:
import * as ts from 'typescript';
import { transformMethod } from './methods';
import { transformProperty } from './properties';

export function transformMembers(cls: ts.ClassDeclaration) {
  const propertyIndices: number[] = [];

  const members = cls.members.map((member: any, index: number) => {
    // only process decorated members
    if (!member.decorators || !member.decorators.length) return member;

    switch (member.kind) {
      case ts.SyntaxKind.MethodDeclaration:
        return transformMethod(member);
      case ts.SyntaxKind.PropertyDeclaration:
        propertyIndices.push(index);
        return member;
      case ts.SyntaxKind.Constructor:
        return ts.createConstructor(undefined, undefined, member.parameters, member.body);
      default:
        return member; // in case anything gets here by accident...
    }
  });

  propertyIndices.forEach((i: number) => {
    const [getter, setter] = transformProperty(members, i) as any;
    members.push(getter, setter);
  });

  propertyIndices.reverse().forEach(i => members.splice(i, 1));

  return members;
}


text:
package com.smoothcsv.framework.condition;

import java.util.Objects;
import java.util.function.Consumer;

/**
 * @author kohii
 */
public class AndCondition extends Condition {

  private final Condition condition0;

  private final Condition condition1;

  public AndCondition(Condition condition0, Condition condition1) {
    this.condition0 = condition0;
    this.condition1 = condition1;

    Consumer<ConditionValueChangeEvent> revalidateListener =
        new Consumer<Condition.ConditionValueChangeEvent>() {
          @Override
          public void accept(ConditionValueChangeEvent e) {
            revalidate();
          }
        };

    condition0.addValueChangedListener(revalidateListener);
    condition1.addValueChangedListener(revalidateListener);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj instanceof AndCondition) {
      AndCondition anotherCondition = (AndCondition) obj;
      return condition0.equals(anotherCondition.condition0)
          && condition1.equals(anotherCondition.condition1);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = 3;
    hash = 67 * hash + Objects.hashCode(this.condition0);
    hash = 67 * hash + Objects.hashCode(this.condition1);
    return hash;
  }

  @Override
  protected void activate() {
    // do nothing
  }

  @Override
  protected boolean computeValue() {
    return condition0.getValue() && condition1.getValue();
  }
}


text:
regexpbuild
===========

Library for creating regular expressions programmatically in Go.


text:
package com.sri.ai.util.collect;

import static com.sri.ai.util.Util.forAll;
import static com.sri.ai.util.Util.join;
import static com.sri.ai.util.collect.NestedIterator.nestedIterator;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import com.google.common.annotations.Beta;
import com.sri.ai.util.Util;

/**
 * An implementation of an immutable {@link List}
 * sharing elements with a pre-existing given list.
 * The immutability allows a faster implementation
 * through caching, as opposed to non-immutable {@link StackedLinkedList}.
 *
 * @author braz
 */
@Beta
public class ImmutableStackedLinkedList<E> implements List<E> {

	private List<E> base;
	private List<E> extension;

	public ImmutableStackedLinkedList(E top, List<E> base) {
		this.base = base;
		this.extension = new LinkedList<E>();
		this.extension.add(top);
	}

	public ImmutableStackedLinkedList(List<E> top, List<E> base) {
		this.base = base;
		this.extension = top;
	}

	public List<E> getBase() {
		return base;
	}

	private boolean sizeIsCached = false;
	private int cachedSize;

	@Override
	public int size() {
		if ( ! sizeIsCached) {
			cachedSize = base.size() + extension.size();
			sizeIsCached = true;
		}
		return cachedSize;
	}

	private boolean isEmptyIsCached = false;
	private boolean cachedIsEmpty;

	@Override
	public boolean isEmpty() {
		if ( ! isEmptyIsCached) {
			cachedIsEmpty = base.isEmpty() && extension.isEmpty();
			isEmptyIsCached = true;
		}
		return cachedIsEmpty;
	}

	@Override
	public boolean contains(Object o) {
		boolean result = extension.contains(o) || base.contains(o);
		return result;
	}

	@Override
	public Iterator<E> iterator() {
		return new NestedIterator<E>(base, extension);
	}

	private Object[] array;

	@Override
	public Object[] toArray() {
		if (array == null) {
			array = new Object[size()];
			base.toArray(array);
			int i = base.size();
			for (E element : extension) {
				array[i++] = element;
			}
		}
		return array;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T[] toArray(T[] a) {
		T[] result;

		if (a.length < size()) {
			result = (T[]) new Object[size()];
		}
		else {
			result = a;
		}

		base.toArray(result);
		int i = base.size();
		for (E element : extension) {
			result[i++] = (T) element;
		}

		for (; i != result.length; i++) {
			result[i] = null;
		}

		return result;
	}

	@Override
	public boolean add(E e) {
		throw new UnsupportedOperationException("add method not supported for immutable stacked linked lists.");
	}

	@Override
	public boolean remove(Object o) {
		throw new UnsupportedOperationException("remove method not supported for immutable stacked linked lists.");
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		boolean result = forAll(c, this::contains);
		return result;
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		throw new UnsupportedOperationException("addAll method not supported for immutable stacked linked lists.");
	}

	@Override
	public boolean addAll(int index, Collection<? extends E> c) {
		throw new UnsupportedOperationException("addAll method not supported for immutable stacked linked lists.");
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		throw new UnsupportedOperationException("removeAll method not supported for immutable stacked linked lists.");
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		throw new UnsupportedOperationException("retainAll not supported for " + getClass());
	}

	@Override
	public void clear() {
		throw new UnsupportedOperationException("clear method not supported for immutable stacked linked lists.");
	}

	@Override
	public E get(int index) {
		E result;
		if (index < base.size()) {
			result = base.get(index);
		}
		else {
			result = extension.get(index - base.size());
		}
		return result;
	}

	@Override
	public E set(int index, E element) {
		throw new UnsupportedOperationException("set method not supported for immutable stacked linked lists.");
	}

	@Override
	public void add(int index, E element) {
		throw new UnsupportedOperationException("add method not supported for immutable stacked linked lists.");
	}

	@Override
	public E remove(int index) {
		throw new UnsupportedOperationException("remove method not supported for immutable stacked linked lists.");
	}

	@Override
	public int indexOf(Object o) {
		int result = base.indexOf(o);
		if (result == -1) {
			result = extension.indexOf(o) + base.size();
		}
		return result;
	}

	@Override
	public int lastIndexOf(Object o) {
		int result = extension.indexOf(o);
		if (result == -1) {
			result = base.indexOf(o);
		}
		else {
			result = result + base.size();
		}
		return result;
	}

	@Override
	public ListIterator<E> listIterator() {
		throw new UnsupportedOperationException("List iterators not supported for " + getClass());
	}

	@Override
	public ListIterator<E> listIterator(int index) {
		throw new UnsupportedOperationException("List iterators not supported for " + getClass());
	}

	@Override
	public List<E> subList(int fromIndex, int toIndex) {
		throw new UnsupportedOperationException("subList not supported for " + getClass());
	}

	@Override
	public String toString() {
		return "[" + join(", ", nestedIterator(base, extension)) + "]";
	}

	@Override
	public boolean equals(Object o) {
		if (o == this) {
			return true;
		}

		if ( !(o instanceof List)) {
			return false;
		}

		@SuppressWarnings("unchecked")
		List<E> oList = (List<E>) o;

		if (oList.size() != size()) {
			return false;
		}

		Iterator<E> i1 = iterator();
		Iterator<E> i2 = oList.iterator();
		while (i1.hasNext()) {
			if ( ! Util.equals(i1.next(), i2.next())) {
				return false;
			}
		}

		return true;
	}

	@Override
	public int hashCode() {
	     int hashCode = 1;
	     for (E e : this) {
	         hashCode = 31*hashCode + (e == null ? 0 : e.hashCode());
	     }
	     return hashCode;
	}
}


text:
package com.terremark.api;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 * Catalog entry type refers to the source operation for the catalog item.
 *

 * Java class for CatalogEntryTypeEnum.
 *

 * The following schema fragment specifies the expected content contained within this class.
 *

 *
 *

 * <simpleType name="CatalogEntryTypeEnum">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="Upload"/>
 *     <enumeration value="Export"/>
 *   </restriction>
 * </simpleType>
 *

 */
@XmlType(name = "CatalogEntryTypeEnum")
@XmlEnum
public enum CatalogEntryTypeEnum {
    /** Catalog item was uploaded to the catalog from the organization. */
    @XmlEnumValue("Upload")
    UPLOAD("Upload"),
    /** Catalog item was exported to the catalog from a virtual machine in the environment. */
    @XmlEnumValue("Export")
    EXPORT("Export");

    private final String value;

    CatalogEntryTypeEnum(final String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static CatalogEntryTypeEnum fromValue(final String v) {
        for (final CatalogEntryTypeEnum c : CatalogEntryTypeEnum.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }
}


text:
@echo off
vlib work
vlog ..\src\direct_design2\FirFilterTree.sv
vlog ..\src\direct_design2\FirFilterDelayLine.sv
vlog ..\src\direct_design2\FirFilter.sv
vlog SignalTesterBurst.sv
vlog SignalTest_tb.sv
vsim SignalTest_tb -do "do SignalTest_wave.do; run -all"


text:
package cz.vse.easyminer.rest

import akka.actor.Actor
import cz.vse.easyminer.miner.{BadInputData, MinerTask}
import cz.vse.easyminer.miner.impl.{ARuleText, AprioriRProcess, BoolExpressionShortText, DBOptsPMML, MinerTaskValidatorImpl, MySQLDatasetBuilder, MySQLQueryBuilder, PMMLResult, PMMLTask, RConnectionPoolImpl}
import cz.vse.easyminer.rest.MinerControllerActor._
import cz.vse.easyminer.util.Conf
import org.slf4j.LoggerFactory
import scala.xml.NodeSeq

class MinerActor extends Actor {

  val logger = LoggerFactory.getLogger("cz.vse.easyminer.rest.MinerActor")
  val path = self.path.toStringWithoutAddress

  def receive = {
    case pmml: NodeSeq =>
      val starttime = System.currentTimeMillis
      logger.info(s"$path: mining start...")
      try {
        pmml.find(_.label == "PMML") match {
          case Some(_pmml) =>
            logger.trace("PMML Input:\n" + _pmml)
            val task = new PMMLTask(_pmml)
            val process = new AprioriRProcess(
              "RAprioriWithMySQL.mustache",
              Conf().get[String]("r-miner.jdbc-driver-dir-absolute-path"),
              RConnectionPoolImpl.default
            ) with MinerTaskValidatorImpl with MySQLDatasetBuilder with MySQLQueryBuilder with DBOptsPMML {
              val pmml = _pmml
            }
            val minertask = MinerTask(task.fetchAntecedent, task.fetchInterestMeasures, task.fetchConsequent)
            val result = process.mine(minertask)
            val pmmlresult = (new PMMLResult(result) with ARuleText with BoolExpressionShortText).toPMML
            logger.trace("PMML Output:\n" + pmmlresult)
            logger.info(s"$path: mining end in ${System.currentTimeMillis - starttime}ms")
            sender ! Sent.Result(pmmlresult)
          case None => throw new BadInputData("PMML element not found!")
        }
      } catch {
        case th: Throwable => sender ! Sent.Error(th)
      }
  }

  override def postStop() = {
    logger.debug(s"$path: stopping...")
  }

}


text:
<!DOCTYPE HTML>
<meta charset="utf-8">
<title>"content_security/policy" array items can contain semicolons to enforce multiple CSP directives</title>


text:
<<<<<<< HEAD
<<<<<<< HEAD
#! /usr/bin/env python3

"""Keywords (from "graminit.c")

This file is automatically generated; please don't muck it up!

To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:

    ./python Lib/keyword.py
"""

__all__ = ["iskeyword", "kwlist"]

kwlist = [
#--start keywords--
        'False',
        'None',
        'True',
        'and',
        'as',
        'assert',
        'break',
        'class',
        'continue',
        'def',
        'del',
        'elif',
        'else',
        'except',
        'finally',
        'for',
        'from',
        'global',
        'if',
        'import',
        'in',
        'is',
        'lambda',
        'nonlocal',
        'not',
        'or',
        'pass',
        'raise',
        'return',
        'try',
        'while',
        'with',
        'yield',
#--end keywords--
        ]

iskeyword = frozenset(kwlist).__contains__

def main():
    import sys, re

    args = sys.argv[1:]
    iptfile = args and args[0] or "Python/graminit.c"
    if len(args) > 1: optfile = args[1]
    else: optfile = "Lib/keyword.py"

    # load the output skeleton from the target, taking care to preserve its
    # newline convention.
    with open(optfile, newline='') as fp:
        format = fp.readlines()
    nl = format[0][len(format[0].strip()):] if format else '\n'

    # scan the source file for keywords
    with open(iptfile) as fp:
        strprog = re.compile('"([^"]+)"')
        lines = []
        for line in fp:
            if '{1, "' in line:
                match = strprog.search(line)
                if match:
                    lines.append("        '" + match.group(1) + "'," + nl)
    lines.sort()

    # insert the lines of keywords into the skeleton
    try:
        start = format.index("#--start keywords--" + nl) + 1
        end = format.index("#--end keywords--" + nl)
        format[start:end] = lines
    except ValueError:
        sys.stderr.write("target does not contain format markers\n")
        sys.exit(1)

    # write the output file
    with open(optfile, 'w', newline='') as fp:
        fp.writelines(format)

if __name__ == "__main__":
    main()
=======
#! /usr/bin/env python3

"""Keywords (from "graminit.c")

This file is automatically generated; please don't muck it up!

To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:

    ./python Lib/keyword.py
"""

__all__ = ["iskeyword", "kwlist"]

kwlist = [
#--start keywords--
        'False',
        'None',
        'True',
        'and',
        'as',
        'assert',
        'break',
        'class',
        'continue',
        'def',
        'del',
        'elif',
        'else',
        'except',
        'finally',
        'for',
        'from',
        'global',
        'if',
        'import',
        'in',
        'is',
        'lambda',
        'nonlocal',
        'not',
        'or',
        'pass',
        'raise',
        'return',
        'try',
        'while',
        'with',
        'yield',
#--end keywords--
        ]

iskeyword = frozenset(kwlist).__contains__

def main():
    import sys, re

    args = sys.argv[1:]
    iptfile = args and args[0] or "Python/graminit.c"
    if len(args) > 1: optfile = args[1]
    else: optfile = "Lib/keyword.py"

    # load the output skeleton from the target, taking care to preserve its
    # newline convention.
    with open(optfile, newline='') as fp:
        format = fp.readlines()
    nl = format[0][len(format[0].strip()):] if format else '\n'

    # scan the source file for keywords
    with open(iptfile) as fp:
        strprog = re.compile('"([^"]+)"')
        lines = []
        for line in fp:
            if '{1, "' in line:
                match = strprog.search(line)
                if match:
                    lines.append("        '" + match.group(1) + "'," + nl)
    lines.sort()

    # insert the lines of keywords into the skeleton
    try:
        start = format.index("#--start keywords--" + nl) + 1
        end = format.index("#--end keywords--" + nl)
        format[start:end] = lines
    except ValueError:
        sys.stderr.write("target does not contain format markers\n")
        sys.exit(1)

    # write the output file
    with open(optfile, 'w', newline='') as fp:
        fp.writelines(format)

if __name__ == "__main__":
    main()
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
#! /usr/bin/env python3

"""Keywords (from "graminit.c")

This file is automatically generated; please don't muck it up!

To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:

    ./python Lib/keyword.py
"""

__all__ = ["iskeyword", "kwlist"]

kwlist = [
#--start keywords--
        'False',
        'None',
        'True',
        'and',
        'as',
        'assert',
        'break',
        'class',
        'continue',
        'def',
        'del',
        'elif',
        'else',
        'except',
        'finally',
        'for',
        'from',
        'global',
        'if',
        'import',
        'in',
        'is',
        'lambda',
        'nonlocal',
        'not',
        'or',
        'pass',
        'raise',
        'return',
        'try',
        'while',
        'with',
        'yield',
#--end keywords--
        ]

iskeyword = frozenset(kwlist).__contains__

def main():
    import sys, re

    args = sys.argv[1:]
    iptfile = args and args[0] or "Python/graminit.c"
    if len(args) > 1: optfile = args[1]
    else: optfile = "Lib/keyword.py"

    # load the output skeleton from the target, taking care to preserve its
    # newline convention.
    with open(optfile, newline='') as fp:
        format = fp.readlines()
    nl = format[0][len(format[0].strip()):] if format else '\n'

    # scan the source file for keywords
    with open(iptfile) as fp:
        strprog = re.compile('"([^"]+)"')
        lines = []
        for line in fp:
            if '{1, "' in line:
                match = strprog.search(line)
                if match:
                    lines.append("        '" + match.group(1) + "'," + nl)
    lines.sort()

    # insert the lines of keywords into the skeleton
    try:
        start = format.index("#--start keywords--" + nl) + 1
        end = format.index("#--end keywords--" + nl)
        format[start:end] = lines
    except ValueError:
        sys.stderr.write("target does not contain format markers\n")
        sys.exit(1)

    # write the output file
    with open(optfile, 'w', newline='') as fp:
        fp.writelines(format)

if __name__ == "__main__":
    main()
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453


text:
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/64fa123d264f48369f98e84062d8547a)](https://www.codacy.com/app/dasantonym/node-sparql-hollandaise?utm_source=github.com&utm_medium=referral&utm_content=PieceMeta/node-sparql-hollandaise&utm_campaign=badger)
[![Build Status](https://travis-ci.org/PieceMeta/node-sparql-hollandaise.svg?branch=master)](https://travis-ci.org/PieceMeta/node-sparql-hollandaise) [![peerDependency Status](https://david-dm.org/PieceMeta/node-sparql-hollandaise/peer-status.svg)](https://david-dm.org/PieceMeta/node-sparql-hollandaise#info=peerDependencies) [![devDependency Status](https://david-dm.org/PieceMeta/node-sparql-hollandaise/dev-status.svg)](https://david-dm.org/PieceMeta/node-sparql-hollandaise#info=devDependencies) [![Code Climate](https://codeclimate.com/github/PieceMeta/node-sparql-hollandaise/badges/gpa.svg)](https://codeclimate.com/github/PieceMeta/node-sparql-hollandaise)

A JS client lib to communicate with a triple store database through SPARQL queries over HTTP.

## Stability

Experimental: Expect the unexpected. Please provide feedback on api and your use-case.

## Disclaimer

If you think this is a fully fledged SPARQL client for JS: nope. This is rather a starting point than a complete implementation. Also, I am not exactly an expert in using SPARQL (that's an understatement) so there might be all sorts of bullshit going on in the lib. Feel free to bash me in the issues...

## Features

The library is supposed to be modeled after the [1.1 version of the SPARQL spec](https://www.w3.org/TR/2013/REC-sparql11-query-20130321) but is not yet complete.

## Install

**Node (min 0.11 or iojs):** ``npm install sparql-hollandaise``

**Browser:** ``bower install sparql-hollandaise`` or download/clone the repo and use the files in ``dist/web/``.

## Usage

Node:
```javascript
var SPH = require('sparql-hollandaise'),
    query = new SPH.Query('https://here.goes.the/endpoint');
```

Browser:
```html
<head>
    <script type="text/javascript" src="/bower_components/babel-polyfill/browser-polyfill.js"></script>
    <script type="text/javascript" src="/bower_components/sparql-hollandaise/dist/web/sparql-hollandaise.js"></script>
</head>
```

Alternatively, if you are using ES6 JavaScript you can also just import the untranspiled code:
```javascript
import * as SPH from 'sparql-hollandaise/src/index'
```

Make sure to check out the basic [Angular example](https://github.com/PieceMeta/ng-sparql-hollandaise-example) as well.

### Creating Graph Patterns

The ``.where()`` function takes either a single ``GraphPattern`` object, or a ``GroupGraphPattern`` that in turn contains multiple ``GraphPattern`` objects.

```javascript
var graphPattern = new SPH.GraphPattern(
    ['array of triple strings'] ||
    'single triple string' ||
    new SPH.Filter('filter string')
);

// additional args for the GraphPattern
var graphPatternOptional = new SPH.GraphPattern('my super triple', true, false); // this pattern is OPTIONAL
var graphPatternAlternative = new SPH.GraphPattern('my super triple', false, true); // this pattern is an alternative (UNION)

var groupGraphPattern = new SPH.GraphPattern([graphPattern, graphPatternAlternative] || graphPattern);
groupGraphPattern.addElement(graphPatternOptional);
```

Once you have created your pattern, you can pass it to any of the queries.

### SELECT
```javascript
var query = new SPH.Query('https://here.goes.the/endpoint')
    .prefix(['foo: <http://bar>', 'pre: <http://fix>'] || 'pre: <http://fix>')
    .select('*') // you can add 'DISTINCT' or 'REDUCED' as a modifier in the second parameter
    .from('dataset clause', true) // second param indicates a named dataset (only pass this if named set)
    // you can add items to the where clause in any order
    // and at any time before calling exec()
    .where(graphPattern)
    .order('order string')
    .limit(10)
    .offset(5)
    .exec().then(function (result) {
        console.log(result);
    });
```

### DESCRIBE
```javascript
var query = new SPH.Query('https://here.goes.the/endpoint')
    .prefix('foo: <http://bar>')
    .describe('?x')
    .where(graphPattern)
    .exec().then(function (result) {
       console.log(result);
    });
```

### ASK
```javascript
var query = new SPH.Query('https://here.goes.the/endpoint')
    .prefix('foo: <http://bar>')
    .ask()
    .where(graphPattern)
    .exec().then(function (result) {
       console.log(result);
    });
```

### CONSTRUCT
```javascript
var query = new SPH.Query('https://here.goes.the/endpoint')
    .prefix('foo: <http://bar>')
    .construct(['array of triple strings'] || 'single triple string')
    .where(graphPattern)
    .order('order string')
    .limit(10)
    .offset(5)
    .exec().then(function (result) {
       console.log(result);
    });
```

### Convenience

You can initialize a QueryFactory to create queries from the same endpoint (mandatory), base (optional) and prefix(es) (optional).

```javascript
var queryFactory = new SPH.QueryFactory(
  'http://localhost',             // endpoint URL
  {},                             // auth (optional)
  'GET',                          // method (optional)
  '<http://example.org/foo/>',    // base (optional)
  'foo: http://bar'               // prefix(es) (optional)
);

// then get a query object based on those settings
var query = queryFactory.make();

// further configure the query as stated above
query.ask()
  .where(...)
  ...
```

### Other methods

These might be useful to you:

```javascript
// get the query's string representation that will be sent to the server
var queryString = query.toString();

// reset the entire query to reuse the object
query.reset();

```

## Development

API docs for the classes in ``src/sparql/`` can be [found here](http://piecemeta.github.io/node-sparql-hollandaise/doc/)

The classes in ``src/`` use most of the ES6 keywords, so transpiling is necessary. The project uses [gulp](http://gulpjs.com/), [Babel](https://babeljs.io/) and [Browserify](http://browserify.org/).

```shell
npm install
# build browser lib and transpile for NodeJS
gulp
# you can also do:
gulp build-web
gulp build-node
```

Run the tests with ``npm test`` and generate code coverage with ``npm run-script cover`` ([view coverage](http://piecemeta.github.io/node-sparql-hollandaise/coverage/lcov-report/)).

YUIDocs can be generated with ``npm run-script docs``.

## Credits

This client was conceived at a hackathon initiated by the [Pina Bausch Foundation](www.pinabausch.org) at the [Mediencampus Hochschule Darmstadt](https://mediencampus.h-da.de) in December 2015.


text: const char *stringpool_add(const char *);


text:
import { StoreConfig } from '../lib/storeConfig';
import { EntityStore } from '../lib/entityStore';
import { Store } from '../lib/store';

@StoreConfig({
  name: 'todos',
  resettable: true
})
class TodosStore extends EntityStore<any, any> {
  constructor() {
    super();
  }
}

const todosstore = new TodosStore();

@StoreConfig({
  name: 'auth',
  resettable: true
})
class AuthStore extends Store<any> {
  constructor() {
    super({
      id: null,
      firstName: '',
      lastName: '',
      token: ''
    });
  }
}

const authStore = new AuthStore();

describe('Reset store', () => {
  it('should reset store state to its initial state - Store', () => {
    authStore._setState(() => {
      return {
        id: 1,
        firstName: 'Netanel',
        lastName: 'Basal',
        token: 'token'
      };
    });
    jest.spyOn(authStore, 'setHasCache');
    authStore.reset();
    expect(authStore._value()).toEqual({ id: null, firstName: '', lastName: '', token: '' });
    expect(authStore.setHasCache).toHaveBeenCalledWith(false);
  });

  it('should reset store state to its initial state - EntityStore', () => {
    todosstore.add({ id: 1 });
    const expected = {
      entities: {},
      ids: [],
      loading: true,
      error: null
    };
    jest.spyOn(todosstore, 'setHasCache');
    todosstore.reset();
    expect(todosstore._value()).toEqual(expected);
    expect(todosstore.setHasCache).toHaveBeenCalledWith(false);
  });
});


text:
import React from 'react';
import {shallow} from 'enzyme';
import sinon from 'sinon';
import assert from 'assert';

import App from '../App';

import {DRAW_LINE} from '../actionLayer/ActionLayer';

describe('App', () => {
  let wrapper;
  let onDrop;
  let preventDefault;
  beforeEach(() => {
    onDrop = sinon.spy();
    preventDefault = sinon.spy();
    wrapper = shallow(<App onDrop={onDrop} />);
  });
  describe('DnD', () => {
    it('DnDのイベントが発生した際にEvent.preventDefaultが呼び出される', () => {
      assert(preventDefault.callCount === 0);
      wrapper.find('div').simulate('dragOver', {
        preventDefault,
        dataTransfer: {dropEffect: null},
      });
      assert(preventDefault.callCount === 1);
      wrapper.find('div').simulate('dragLeave', {preventDefault});
      assert(preventDefault.callCount === 2);
    });
    it('DnDイベントによってstate.isDragOverが適切に切り替わる', () => {
      assert(wrapper.state('isDragOver') === false);
      wrapper
        .find('div')
        .first()
        .simulate('dragEnter', {preventDefault});
      assert(wrapper.state('isDragOver') === true);
      wrapper
        .find('div')
        .first()
        .simulate('dragLeave', {preventDefault});
      assert(wrapper.state('isDragOver') === true);
      // カーソルがブラウザの外に出た時のみ、false になる
      wrapper
        .find('div')
        .first()
        .simulate('dragLeave', {preventDefault, clientX: 0});
      assert(wrapper.state('isDragOver') === false);
    });
    it('state.isDragOverがtrueのときのみ、ファイルドロップの案内文が表示される', () => {
      assert(wrapper.state('isDragOver') === false);
      assert(!wrapper.find('div').find('.guide-file-drop').length);
      wrapper
        .find('div')
        .first()
        .simulate('dragEnter', {preventDefault});
      assert(wrapper.state('isDragOver') === true);
      assert(wrapper.find('div').find('.guide-file-drop').length);
    });
  });
  describe('getActiveImage', () => {
    it('getActiveImage でアクティブな image を取得できる', () => {
      const inst = wrapper.instance();
      const image = inst.getActiveImage();
      assert(image.isActive === true);
    });
  });
  describe('updateImageData', () => {
    it('updateImageData に ImageData を渡すことで state.imageListHistory を更新できる', () => {
      assert(wrapper.state('imageListHistory').history.length === 1);
      assert(
        wrapper.state('imageListHistory').history[0][0].imageData.width === 500
      );
      wrapper.instance().updateImageData({data: 'foo', width: 99, height: 88});
      assert(wrapper.state('imageListHistory').history.length === 2);
      assert(
        wrapper.state('imageListHistory').history[0][0].imageData.width === 99
      );
    });
  });
  describe('updateImageList', () => {
    it('updateImageList で state.imageListHistory を更新できる', () => {
      assert(wrapper.state('imageListHistory').history.length === 1);
      assert(wrapper.state('imageListHistory').history[0][0].id === 0);
      wrapper
        .instance()
        .updateImageList([{id: 9, isActive: true}, {id: 0, isActive: false}]);
      assert(wrapper.state('imageListHistory').history.length === 2);
      assert(wrapper.state('imageListHistory').history[0][0].id === 9);
    });
  });
  describe('updateImageListHistory', () => {
    it('updateImageListHistory で state.imageListHistory を更新できる', () => {
      assert(wrapper.state('imageListHistory').position === 0);
      assert(wrapper.state('imageListHistory').history[0][0].id === 0);
      wrapper.instance().updateImageListHistory({
        history: [[{id: 1, isActive: true}], [{id: 0, isActive: true}]],
        position: 1,
        omitLength: null,
      });
      assert(wrapper.state('imageListHistory').position === 1);
      assert(wrapper.state('imageListHistory').history[0][0].id === 1);
    });
  });
  describe('updateActionLayerSettings', () => {
    it('updateActionLayerSettings で state.actionLayerSettings を更新できる', () => {
      const target = DRAW_LINE;
      assert(wrapper.state('actionLayerSettings')[target].ctx.lineWidth === 1);
      wrapper.instance().updateActionLayerSettings(target, {lineWidth: 3});
      assert(wrapper.state('actionLayerSettings')[target].ctx.lineWidth === 3);
    });
  });
  describe('changeDisplaySize', () => {
    it('渡された値に、 state.display のサイズを変える', () => {
      const inst = wrapper.instance();
      inst.changeDisplaySize(50, 90);
      assert(wrapper.state('display').width === 50);
      assert(wrapper.state('display').height === 90);
      inst.changeDisplaySize(100, 80);
      assert(wrapper.state('display').width === 100);
      assert(wrapper.state('display').height === 80);
    });
  });
  describe('uploadImageFile', () => {
    let inst;
    let file;
    beforeEach(() => {
      inst = wrapper.instance();
      file = new window.File(['<xml>foo</xml>'], 'example.xml', {
        type: 'text/xml',
      });
    });
    it('複数のファイルがアップロードされた場合は handleError が呼び出される', () => {
      const spy = sinon.spy(inst, 'handleError');
      assert(spy.callCount === 0);
      inst.uploadImageFile([file, file]);
      assert(spy.callCount === 1);
      spy.restore();
    });
    it('許可していないファイルタイプがアップロードされた場合は handleError が呼び出される', () => {
      const spy = sinon.spy(inst, 'handleError');
      assert(spy.callCount === 0);
      inst.uploadImageFile([file]);
      assert(file.type === 'text/xml');
      assert(spy.callCount === 1);
      spy.restore();
    });
  });
  describe('handleError', () => {
    it.skip('渡されたエラーに応じて、適切なメッセージを出す', () => {});
  });
});