text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.04.16 at 12:23:52 PM PDT
//

package dtd.kegg;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "alt"
})
@XmlRootElement(name = "substrate")
public class Substrate {

    @XmlAttribute(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String id;
    @XmlAttribute(required = true)
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String name;
    protected Alt alt;

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setId(String value) {
        this.id = value;
    }

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the alt property.
     *
     * @return
     *     possible object is
     *     {@link Alt }
     *
     */
    public Alt getAlt() {
        return alt;
    }

    /**
     * Sets the value of the alt property.
     *
     * @param value
     *     allowed object is
     *     {@link Alt }
     *
     */
    public void setAlt(Alt value) {
        this.alt = value;
    }

}


text:
module ActiveRecord
  module Associations
    class BelongsToAssociation < AssociationProxy #:nodoc:
      def create(attributes = {})
        replace(@reflection.create_association(attributes))
      end

      def build(attributes = {})
        replace(@reflection.build_association(attributes))
      end

      def replace(record)
        counter_cache_name = @reflection.counter_cache_column

        if record.nil?
          if counter_cache_name && !@owner.new_record?
            @reflection.klass.decrement_counter(counter_cache_name, previous_record_id) if @owner[@reflection.primary_key_name]
          end

          @target = @owner[@reflection.primary_key_name] = nil
        else
          raise_on_type_mismatch(record)

          if counter_cache_name && !@owner.new_record?
            @reflection.klass.increment_counter(counter_cache_name, record.id)
            @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
          end

          @target = (AssociationProxy === record ? record.target : record)
          @owner[@reflection.primary_key_name] = record_id(record) unless record.new_record?
          @updated = true
        end

        set_inverse_instance(record, @owner)

        loaded
        record
      end

      def updated?
        @updated
      end

      private
        def find_target
          find_method = if @reflection.options[:primary_key]
                          "find_by_#{@reflection.options[:primary_key]}"
                        else
                          "find"
                        end
          the_target = @reflection.klass.send(find_method,
            @owner[@reflection.primary_key_name],
            :select     => @reflection.options[:select],
            :conditions => conditions,
            :include    => @reflection.options[:include],
            :readonly   => @reflection.options[:readonly]
          ) if @owner[@reflection.primary_key_name]
          set_inverse_instance(the_target, @owner)
          the_target
        end

        def foreign_key_present
          !@owner[@reflection.primary_key_name].nil?
        end

        def record_id(record)
          record.send(@reflection.options[:primary_key] || :id)
        end

        def previous_record_id
          @previous_record_id ||= if @reflection.options[:primary_key]
                                    previous_record = @owner.send(@reflection.name)
                                    previous_record.nil? ? nil : previous_record.id
                                  else
                                    @owner[@reflection.primary_key_name]
                                  end
        end

        # NOTE - for now, we're only supporting inverse setting from belongs_to back onto
        # has_one associations.
        def we_can_set_the_inverse_on_this?(record)
          @reflection.has_inverse? && @reflection.inverse_of.macro == :has_one
        end
    end
  end
end

redpajama_set_name: RedPajamaGithub


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

namespace UserInterface_Mockup_ICT4Reals.DataBase
{
    class TRdatabase : Database
    {
        /// <summary>
        /// change the location of the tram with given id
        /// replace the spoorid given spoorid
        /// </summary>
        /// <param name="tramId">ID of the tram</param>
        /// <param name="railId">ID of the rail it's moved to</param>
        /// <returns></returns>
        public bool MoveTram(int tramId, int railId, int statusId) // move the tram to a diffrent location
        {
            try
            {
                string queryRail; // the query will end up in here
                string queryStatus;
                queryRail = "UPDATE Tram SET";  //update the location of the tram
                queryRail += " SpoorID = " + railId + " WHERE TramID = " + tramId; //change the location of to a new location from the tram with the matching id
                queryStatus = "UPDATE Tram_Status SET"; //UPDATE tram status
                queryStatus+= " StatusStatusID = " + statusId + " WHERE TramTramID = " + tramId;
                if (doQuery(queryRail) == -1)  //query will be activated
                {
                    return false;
                }
                if (doQuery(queryStatus) == -1)
                {
                    return false;
                }
                else
                {
                    return true;
                }

            }
            catch
            {
                return false;   // if query fails, return a false.
            }
        }
        /// <summary>
        /// not used
        /// </summary>
        /// <param name="tramId"></param>
        /// <returns></returns>
        public int TramOnRail(int tramId) // replace user with the data u want to add/ change to the table
        {
            int ret = 0; //result of query will end up in here
            List<Dictionary<string, object>> RailQuery = getQuery("SELECT SpoorID FROM Tram WHERE TramID =" + tramId);
            foreach (Dictionary<string, object> results in RailQuery) //look for all possible results in the query result.
            {
                ret = ((Convert.ToInt32(results["SpoorID"]))); //add each result to the created list
            }

            return ret;     //this will return the list as result from the query
        }
        /// <summary>
        /// adds a tram to the database, uses the given variables
        /// </summary>
        /// <param name="tramId">the id of the tram</param>
        /// <param name="spoorId">the id of the rail the tram is on</param>
        /// <param name="typeId">the id of the type of the tram (represented vby an enum)</param>
        /// <returns></returns>
        public bool AddTram(int tramId, int spoorId, int typeId, int aanwezigOpSpoor)
        {
            try
            {
                string query; // the query will end up in here
                query = "INSERT INTO Tram(tramID, spoorID, typeID, AanwezigOpSpoor)";  //adding a tram
                query += " VALUES(" + tramId + ", " + spoorId + ", " + typeId + ", " + aanwezigOpSpoor +")"; //insert data given to db
                if (doQuery(query) == -1)//query will be activated
                {
                    return false;
                }
                query = "insert into Tram_Status(tramtramid, statusstatusid) values("+ tramId + ", " + "1)";
                if (doQuery(query) == -1)
                {
                    return false;
                }
                else
                {
                    return true;
                }

            }
            catch
            {
                return false;   // if query fails, return a false.
            }
        }
        /// <summary>
        /// Deletes a tram from the database matching the given id
        /// </summary>
        /// <param name="tramId">id of the tram you want to delete</param>
        /// <returns></returns>
        public bool DeleteTram(int tramId)
        {
            try
            {
                string query; // the query will end up in here
                query = "DELETE FROM Tram";  //delete a tram
                query += " WHERE TramID = " + tramId; //deletes tram with given tram id
                if (doQuery(query) == -1) //query will be activated
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;   // if query fails, return a false.
            }
        }

        /// <summary>
        /// Update the tram status
        /// </summary>
        /// <param name="tramId">the id of the tram you want to update</param>
        /// <param name="statusId">1= OK 2= Dirty 3= Defect 4= DirtyAndDefect</param>
        /// <returns>true if status is updates else false</returns>
        public bool UpdateTramStatus(int tramId, int statusId)
        {
            try
            {
                string query; // the query will end up in here
                query = "UPDATE Tram_Status SET"; //UPDATE tram status
                query += " StatusStatusID = '" + statusId + "' WHERE TramTramID = " + tramId;
                    //updates tram_status with given status
                if (doQuery(query) == -1) //query will be activated
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false; // if query fails, return a false.
            }
        }
    }
}


text:
using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace SimShift.Utils
{
    /// <summary>
    /// The RECT structure defines the coordinates of the upper-left and lower-right corners of a rectangle.
    /// </summary>
    [Serializable, StructLayout(LayoutKind.Sequential)]
    internal struct Rect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;

        public Rect(int left, int top, int right, int bottom)
        {
            this.Left = left;
            this.Top = top;
            this.Right = right;
            this.Bottom = bottom;
        }

        public Rectangle AsRectangle
        {
            get
            {
                return new Rectangle(this.Left, this.Top, this.Right - this.Left, this.Bottom - this.Top);
            }
        }

        public static Rect FromXYWH(int x, int y, int width, int height)
        {
            return new Rect(x, y, x + width, y + height);
        }

        public static Rect FromRectangle(Rectangle rect)
        {
            return new Rect(rect.Left, rect.Top, rect.Right, rect.Bottom);
        }
    }
}


text:
package org.oscm.ui.dialog.mp.accountNavigation;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import org.oscm.internal.types.constants.HiddenUIConstants;
import org.oscm.ui.beans.ApplicationBean;
import org.oscm.ui.beans.BaseBean;

/**
 * @author Yuyin
 *
 */
@ManagedBean(name = "accountNavigationBean")
@SessionScoped
public class AccountNavigationCtrl extends BaseBean implements Serializable {

    private static final long serialVersionUID = -6631452652280374841L;

    @ManagedProperty(value = "#{appBean}")
    private ApplicationBean applicationBean;
    @ManagedProperty(value = "#{accountNavigationModel}")
    private AccountNavigationModel model;

    @PostConstruct
    public void getInitialize() {
        String url = getRequest().getRequestURL().toString();
        computeBaseUrl(url);
    }

    protected void computeBaseUrl(String url) {
        String baseUrl = url.replaceFirst("/marketplace/.*", "");
        getModel().setBaseUrl(baseUrl);
        getModel().initLink();
    }

    public ApplicationBean getApplicationBean() {
        return applicationBean;
    }

    public void setApplicationBean(ApplicationBean applicationBean) {
        this.applicationBean = applicationBean;
    }

    public AccountNavigationModel getModel() {
        return model;
    }

    public List<String> getLink() {
        return getModel().getLink();
    }

    public List<String> getTitle() {
        return getModel().getTitle();
    }

    public List<String> getHiddenElement() {
        return getModel().getHiddenElement();
    }

    /**
     * Check if reporting box should be displayed - reporting must be available
     * and user must be logged in and have the administrator role.
     *
     * @return true if report box is available, false
     *         otherwise.
     */
    public boolean isReportingAvailable() {
        return (applicationBean.isReportingAvailable()
                && (isLoggedInAndAdmin() || isLoggedInAndUnitAdmin())
                && !applicationBean.isUIElementHidden(
                        HiddenUIConstants.MARKETPLACE_MENU_ITEM_ACCOUNT_REPORTS));
    }

    public boolean isPaymentAvailable() {

        return (isLoggedInAndAdmin()
                && !applicationBean.isUIElementHidden(
                        HiddenUIConstants.MARKETPLACE_MENU_ITEM_ACCOUNT_PAYMENT)
                && getConfigurationService().isPaymentInfoAvailable());
    }

    public void setModel(AccountNavigationModel model) {
        this.model = model;
    }

    /**
     * @param index
     *            the index of model.link or model.title
     * @return true if the index-1 of getHiddenElement() is
     *         available, false otherwise.
     */
    public boolean isLinkVisible(int index) {
        if (index < 1 || index > getLink().size()) {
            return false;
        }
        String hiddenElement = getHiddenElement().get(index - 1);
        if (HiddenUIConstants.MARKETPLACE_MENU_ITEM_ACCOUNT_REPORTS
                .equals(hiddenElement)) {
            return isReportingAvailable();
        } else if (HiddenUIConstants.MARKETPLACE_MENU_ITEM_ACCOUNT_USERS
                .equals(hiddenElement)) {
            return isLoggedInAndAdmin()
                    && !applicationBean.isUIElementHidden(hiddenElement);
        } else if (HiddenUIConstants.MARKETPLACE_MENU_ITEM_ACCOUNT_PAYMENT
                .equals(hiddenElement)) {
            return isPaymentAvailable();
        } else if (HiddenUIConstants.MARKETPLACE_MENU_ITEM_ACCOUNT_SUBSCRIPTIONS
                .equals(hiddenElement)) {
            return (isLoggedInAndAdmin() || isLoggedInAndSubscriptionManager()
                    || isLoggedInAndUnitAdmin())
                    && !applicationBean.isUIElementHidden(hiddenElement);
        } else if (HiddenUIConstants.MARKETPLACE_MENU_ITEM_ACCOUNT_UNITS
                .equals(hiddenElement)) {
            return isLoggedInAndUnitAdmin()
                    && !applicationBean.isUIElementHidden(hiddenElement);
        } else if (HiddenUIConstants.MARKETPLACE_MENU_ITEM_ACCOUNT_ADMINISTRATION
                .equals(hiddenElement)) {
            return isAdministrationAccess()
                    && !applicationBean.isUIElementHidden(hiddenElement);
        }
        return !applicationBean.isUIElementHidden(hiddenElement);
    }
}


text: export * from  './my-integer-input.module';


text:
'use strict';

// Deploy an app to Cloud Foundry

// Implemented in ES5 for now
/* eslint no-var: 0 */

var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var cp = require('child_process');
var commander = require('commander');
var yaml = require('js-yaml');

var noop = _.noop;

/* eslint no-process-exit: 1 */

// Create the directories we need
var mkdirs = function(cb) {
  // Create .cfpush directory
  fs.mkdir('.cfpush', function(err) {
    if(err) noop();
    cb();
  });
};

// Adjust manifest.yml env variables and write new manifest.yml
var remanifest = function(root, name, instances, conf, cb) {
  fs.readFile(
    path.join(process.cwd(), 'manifest.yml'), function(err, content) {
      if(err) return cb(err);
      var yml = yaml.load(content);
      var app = yml.applications[0];
      if(app) {
        app.name = name;
        app.host = name;
        if(instances)
          app.instances = parseInt(instances);
        app.path = '../' + app.path;
        if(conf) {
          if(!app.env) app.env = {};
          app.env.CONF = conf;
        }
      }
      fs.writeFile(
        path.join('.cfpush', [name, 'manifest.yml'].join('-')),
        yaml.dump(yml), cb);
    });
};

// Push an app
var push = function(name, start, cb) {
  var command = 'cf push ' +
    (start ? '' : '--no-start ') +
    '-f .cfpush/' + [name, 'manifest.yml'].join('-');
  var ex = cp.exec(command, {
    cwd: process.cwd()
  });
  ex.stdout.on('data', function(data) {
    process.stdout.write(data);
  });
  ex.stderr.on('data', function(data) {
    process.stderr.write(data);
  });
  ex.on('close', function(code) {
    cb(code);
  });
};

// Package an app for deployment to Cloud Foundry
var runCLI = function() {
  // Parse command line options
  commander
    // Accept root directory of local dependencies as a parameter, default
    // to the Abacus root directory
    .option('-n, --name <name>', 'app name',
      require(path.join(process.cwd(), 'package.json')).name)
    .option('-i, --instances <nb>', 'nb of instances')
    .option('-c, --conf <value>',
      'configuration name', process.env.CONF)
    .option('-s, --start',
      'start an app after pushing')
    .parse(process.argv);

  // Create the directories we need
  mkdirs(function(err) {
    if(err) {
      console.log('Couldn\'t setup cfpack layout -', err);
      process.exit(1);
    }

    // Generate the updated manifest.yml
    remanifest(commander.root,
      commander.name, commander.instances, commander.conf, function(err) {
        if(err) {
          console.log('Couldn\'t write manifest.yml -', err);
          process.exit(1);
        }

        // Produce the packaged app zip
        push(commander.name, commander.start, function(err) {
          if(err) {
            console.log('Couldn\'t push app %s -', commander.name, err);
            process.exit(1);
          }
        });
      });
  });
};

// Export our CLI
module.exports.runCLI = runCLI;


text:
<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>minDist</title><meta name="generator" content="MATLAB 8.4"><link rel="schema.DC" href="http://purl.org/dc/elements/1.1/"><meta name="DC.date" content="2014-10-01"><meta name="DC.source" content="HELP_minDist.m">

minDist

Below is a demonstration of the features of the <tt>minDist</tt> function

Contents

EXAMPLE FOR POINT CLOUD OR SURFACE DISTANCE COMPUTATION

EXAMPLE FOR NEAREST NEIGHBOUR SEARCH AND INTERPOLATION

clear; close all; clc;

PLOT SETTINGS

figColor='w';
figColorDef='white';
fontSize=10;
cmap=gray(250);
faceAlpha1=0.5;
faceAlpha2=1;

EXAMPLE FOR POINT CLOUD OR SURFACE DISTANCE COMPUTATION

Building test surfaces

%Defining shape 1 as a sphere
[F1,V1,~]=geoSphere(2,1);

%Defining shape 2 as a deformed sphere
[F2,V2,Vs]=geoSphere(3,1);
freqDef=3;
ampDef=0.25;
ampDefDiff=0.25;
n1=Vs(:,3)+(ampDef-ampDefDiff)+ampDef*sin(freqDef*Vs(:,1));
[V2(:,1),V2(:,2),~]=sph2cart(Vs(:,1),Vs(:,2),n1);

Plotting surfaces

hf1=figuremax(figColor,figColorDef);
title('The two surfaces','FontSize',fontSize);
xlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize);zlabel('Z','FontSize',fontSize);
hold on;
patch('faces',F1,'vertices',V1,'FaceColor','g','FaceAlpha',faceAlpha1);
patch('faces',F2,'vertices',V2,'FaceColor','b','FaceAlpha',faceAlpha1);

axis equal; view(3); axis tight; grid on;
set(gca,'FontSize',fontSize);
camlight headlight;
drawnow;

Get closest point based distance metric

D2=minDist(V2,V1);

On this type of use see also the <tt>triSurfSetDist</tt> function

Plotting results

[CF]=vertexToFaceMeasure(F2,D2);

hf2=figuremax(figColor,figColorDef);
title('Closest point distance metric on surface 2','FontSize',fontSize);
xlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize);zlabel('Z','FontSize',fontSize);
hold on;
patch('faces',F2,'vertices',V2,'FaceColor','flat','CData',CF);
patch('faces',F1,'vertices',V1,'FaceColor',0.5.*ones(1,3),'FaceAlpha',faceAlpha1,'EdgeColor','None');

colormap jet; colorbar;
axis equal; view(3); axis tight; axis off;
set(gca,'FontSize',fontSize);
camlight headlight;
drawnow;

EXAMPLE FOR NEAREST NEIGHBOUR SEARCH AND INTERPOLATION

Building test surfaces

%Defining shape 1 as a sphere
[F1,V1,~]=geoSphere(2,1);

%Defining shape 2 as a denser sphere
[F2,V2,Vs]=geoSphere(4,1);

%Simulate some kind of result on the coarse sphere
C1=triplyPeriodicMinimal(6.*V1,'g');

Find nearest neighbours

[~,indMin]=minDist(V2,V1);

Interpolation now reduces to simple indexing into the array

C2=C1(indMin);

Get "true" color to compare

C2_true=triplyPeriodicMinimal(6.*V2,'g');

Plotting surfaces

[CF1]=vertexToFaceMeasure(F1,C1);
[CF2]=vertexToFaceMeasure(F2,C2);
[CF2_true]=vertexToFaceMeasure(F2,C2_true);

hf2=figuremax(figColor,figColorDef);
subplot(1,3,1);
title('Coarse input','FontSize',fontSize);
xlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize);zlabel('Z','FontSize',fontSize);
hold on;
patch('faces',F1,'vertices',V1,'FaceColor','flat','CData',CF1,'FaceAlpha',faceAlpha2,'EdgeColor','k');

colormap jet; colorbar;
axis equal; view(3); axis tight; axis off;
set(gca,'FontSize',fontSize);
camlight headlight;

subplot(1,3,2);
title('Upsampled using nearest neighbours','FontSize',fontSize);
xlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize);zlabel('Z','FontSize',fontSize);
hold on;
patch('faces',F2,'vertices',V2,'FaceColor','flat','CData',CF2,'FaceAlpha',faceAlpha2,'EdgeColor','k');

colormap jet; colorbar;
axis equal; view(3); axis tight; axis off;
set(gca,'FontSize',fontSize);
camlight headlight;

subplot(1,3,3);
title('Truth','FontSize',fontSize);
xlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize);zlabel('Z','FontSize',fontSize);
hold on;
patch('faces',F2,'vertices',V2,'FaceColor','flat','CData',CF2_true,'FaceAlpha',faceAlpha2,'EdgeColor','none');

colormap jet; colorbar;
axis equal; view(3); axis tight; axis off;
set(gca,'FontSize',fontSize);
camlight headlight;

drawnow;

GIBBON www.gibboncode.org

Kevin Mattheus Moerman, gibbon.toolbox@gmail.com

Published with MATLAB® R2014b


text:
<?php

namespace RedKiteCms\EventSystem\Event\Block;

use JMS\Serializer\SerializerInterface;

/**
 * Class BlockApprovingEvent is the object assigned to implement the event raised before approving a new block
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\EventSystem\Event\Block
 */
class BlockApprovingEvent extends BlockApprovingRemovalEvent
{
    /**
     * @type string $sourceFile
     */
    private $sourceFile = null;

    /**
     * Constructor
     *
     * @param SerializerInterface $serializer
     * @param null                $sourceFile
     * @param                     $targetFile
     */
    public function __construct(SerializerInterface $serializer, $sourceFile, $targetFile)
    {
        parent::__construct($serializer, $targetFile);

        $this->sourceFile = $sourceFile;
    }

    /**
     * Returns the source file
     *
     * @return null|string
     */
    public function getSourceFile()
    {
        return $this->sourceFile;
    }

    /**
     * Sets the source file
     *
     * @param $sourceFile
     * @return $this
     */
    public function setSourceFile($sourceFile)
    {
        $this->sourceFile = $sourceFile;

        return $this;
    }
}


text:
/**
 * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v17.0.0
 * @link http://www.ag-grid.com/
 * @license MIT
 */
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("../context/context");
var column_1 = require("../entities/column");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var utils_1 = require("../utils");
var columnController_1 = require("./columnController");
var AutoGroupColService = (function () {
    function AutoGroupColService() {
    }
    AutoGroupColService_1 = AutoGroupColService;
    AutoGroupColService.prototype.createAutoGroupColumns = function (rowGroupColumns) {
        var _this = this;
        var groupAutoColumns = [];
        var doingTreeData = this.gridOptionsWrapper.isTreeData();
        var doingMultiAutoColumn = this.gridOptionsWrapper.isGroupMultiAutoColumn();
        if (doingTreeData && doingMultiAutoColumn) {
            console.log('ag-Grid: you cannot mix groupMultiAutoColumn with treeData, only one column can be used to display groups when doing tree data');
            doingMultiAutoColumn = false;
        }
        // if doing groupMultiAutoColumn, then we call the method multiple times, once
        // for each column we are grouping by
        if (doingMultiAutoColumn) {
            rowGroupColumns.forEach(function (rowGroupCol, index) {
                groupAutoColumns.push(_this.createOneAutoGroupColumn(rowGroupCol, index));
            });
        }
        else {
            groupAutoColumns.push(this.createOneAutoGroupColumn(null));
        }
        return groupAutoColumns;
    };
    // rowGroupCol and index are missing if groupMultiAutoColumn=false
    AutoGroupColService.prototype.createOneAutoGroupColumn = function (rowGroupCol, index) {
        // if one provided by user, use it, otherwise create one
        var defaultAutoColDef = this.generateDefaultColDef(rowGroupCol, index);
        var userAutoColDef = this.gridOptionsWrapper.getAutoGroupColumnDef();
        // if doing multi, set the field
        var colId;
        if (rowGroupCol) {
            colId = AutoGroupColService_1.GROUP_AUTO_COLUMN_ID + "-" + rowGroupCol.getId();
        }
        else {
            colId = AutoGroupColService_1.GROUP_AUTO_COLUMN_BUNDLE_ID;
        }
        utils_1._.mergeDeep(defaultAutoColDef, userAutoColDef);
        defaultAutoColDef.colId = colId;
        var noUserFilterPreferences = userAutoColDef == null || userAutoColDef.suppressFilter == null;
        if (noUserFilterPreferences && !this.gridOptionsWrapper.isTreeData()) {
            var produceLeafNodeValues = defaultAutoColDef.field != null || defaultAutoColDef.valueGetter != null;
            defaultAutoColDef.suppressFilter = !produceLeafNodeValues;
        }
        // if showing many cols, we don't want to show more than one with a checkbox for selection
        if (index > 0) {
            defaultAutoColDef.headerCheckboxSelection = false;
        }
        var newCol = new column_1.Column(defaultAutoColDef, colId, true);
        this.context.wireBean(newCol);
        return newCol;
    };
    AutoGroupColService.prototype.generateDefaultColDef = function (rowGroupCol, index) {
        var localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc();
        var defaultAutoColDef = {
            headerName: localeTextFunc('group', 'Group'),
            cellRenderer: 'agGroupCellRenderer'
        };
        // we never allow moving the group column
        // defaultAutoColDef.suppressMovable = true;
        if (rowGroupCol) {
            var rowGroupColDef = rowGroupCol.getColDef();
            utils_1._.assign(defaultAutoColDef, {
                // cellRendererParams.groupKey: colDefToCopy.field;
                headerName: this.columnController.getDisplayNameForColumn(rowGroupCol, 'header'),
                headerValueGetter: rowGroupColDef.headerValueGetter
            });
            if (rowGroupColDef.cellRenderer) {
                utils_1._.assign(defaultAutoColDef, {
                    cellRendererParams: {
                        innerRenderer: rowGroupColDef.cellRenderer,
                        innerRendererParams: rowGroupColDef.cellRendererParams
                    }
                });
            }
            defaultAutoColDef.showRowGroup = rowGroupCol.getColId();
        }
        else {
            defaultAutoColDef.showRowGroup = true;
        }
        return defaultAutoColDef;
    };
    AutoGroupColService.GROUP_AUTO_COLUMN_ID = 'ag-Grid-AutoColumn';
    AutoGroupColService.GROUP_AUTO_COLUMN_BUNDLE_ID = AutoGroupColService_1.GROUP_AUTO_COLUMN_ID;
    __decorate([
        context_1.Autowired('gridOptionsWrapper'),
        __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
    ], AutoGroupColService.prototype, "gridOptionsWrapper", void 0);
    __decorate([
        context_1.Autowired('context'),
        __metadata("design:type", context_1.Context)
    ], AutoGroupColService.prototype, "context", void 0);
    __decorate([
        context_1.Autowired('columnController'),
        __metadata("design:type", columnController_1.ColumnController)
    ], AutoGroupColService.prototype, "columnController", void 0);
    AutoGroupColService = AutoGroupColService_1 = __decorate([
        context_1.Bean('autoGroupColService')
    ], AutoGroupColService);
    return AutoGroupColService;
    var AutoGroupColService_1;
}());
exports.AutoGroupColService = AutoGroupColService;


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

'use strict';

var assert = require('chai').assert;
var sinon = require('sinon');
var stream = require('stream');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Client = require('../lib/client.js');
var SimulatedHttp = require('./http_simulated.js');
var clientTests = require('./_client_common_testrun.js');
var results = require('azure-iot-common').results;
var errors = require('azure-iot-common').errors;
var Message = require('azure-iot-common').Message;

describe('Client', function () {
  describe('#constructor', function () {
    /*Tests_SRS_NODE_DEVICE_CLIENT_05_001: [The Client constructor shall throw ReferenceError if the transport argument is falsy.]*/
    it('throws if transport arg is falsy', function () {
      [null, undefined, '', 0].forEach(function (transport) {
        assert.throws(function () {
          return new Client(transport);
        }, ReferenceError, 'transport is \'' + transport + '\'');
      });
    });
  });

  describe('#fromConnectionString', function () {
    var connectionString = 'HostName=host;DeviceId=id;SharedAccessKey=key';

    /*Tests_SRS_NODE_DEVICE_CLIENT_05_003: [The fromConnectionString method shall throw ReferenceError if the connStr argument is falsy.]*/
    it('throws if connStr arg is falsy', function () {
      [null, undefined, '', 0].forEach(function (value) {
        assert.throws(function () {
          return Client.fromConnectionString(value);
        }, ReferenceError, 'connStr is \'' + value + '\'');
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_05_006: [The fromConnectionString method shall return a new instance of the Client object, as by a call to new Client(new Transport(...)).]*/
    it('returns an instance of Client', function () {
      var DummyTransport = function () { };
      var client = Client.fromConnectionString(connectionString, DummyTransport);
      assert.instanceOf(client, Client);
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_027: [If a connection string argument is provided and is using SharedAccessKey authentication, the Client shall automatically generate and renew SAS tokens.] */
    it('automatically renews the SAS token before it expires', function (done) {
      this.clock = sinon.useFakeTimers();
      var clock = this.clock;
      var tick = 0;
      var firstTick = 1800000;
      var secondTick = 1200000;
      var sasUpdated = false;
      var DummyTransport = function () {
        this.updateSharedAccessSignature = function () {
          sasUpdated = true;
          assert.equal(tick, secondTick);
          clock.restore();
          done();
        };
      };

      var client = Client.fromConnectionString(connectionString, DummyTransport);
      assert.instanceOf(client, Client);
      tick = firstTick;
      this.clock.tick(tick); // 30 minutes. shouldn't have updated yet.
      assert.isFalse(sasUpdated);
      tick = secondTick;
      this.clock.tick(tick); // +20 => 50 minutes. should've updated so the callback will be called and the test will terminate.
    });

    it('doesn\'t try to renew the SAS token when using x509', function (done) {
      this.clock = sinon.useFakeTimers();
      var clock = this.clock;
      var DummyTransport = function () {
        this.updateSharedAccessSignature = function () {
          clock.restore();
          done(new Error('updateSharedAccessSignature should not have been called'));
        };
      };

      var x509ConnectionString = 'HostName=host;DeviceId=id;x509=true';
      var client = Client.fromConnectionString(x509ConnectionString, DummyTransport);
      assert.instanceOf(client, Client);
      this.clock.tick(3600000); // 1 hour: this should trigger the call to renew the SAS token.
      clock.restore();
      done();
    });
  });

  describe('#fromSharedAccessSignature', function () {
    /*Tests_SRS_NODE_DEVICE_CLIENT_16_029: [The fromSharedAccessSignature method shall throw a ReferenceError if the sharedAccessSignature argument is falsy.] */
    it('throws if sharedAccessSignature arg is falsy', function () {
      [null, undefined, '', 0].forEach(function (value) {
        assert.throws(function () {
          return Client.fromSharedAccessSignature(value);
        }, ReferenceError, 'sharedAccessSignature is \'' + value + '\'');
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_030: [The fromSharedAccessSignature method shall return a new instance of the Client object] */
    it('returns an instance of Client', function () {
      var DummyTransport = function () { };
      var sharedAccessSignature = '"SharedAccessSignature sr=hubName.azure-devices.net/devices/deviceId&sig=s1gn4tur3&se=1454204843"';
      var client = Client.fromSharedAccessSignature(sharedAccessSignature, DummyTransport);
      assert.instanceOf(client, Client);
    });

    it('create a correct config when sr is not URI-encoded', function () {
      var sharedAccessSignature = '"SharedAccessSignature sr=hubName.azure-devices.net/devices/deviceId&sig=s1gn4tur3&se=1454204843"';
      var DummyTransport = function (config) {
        assert.strictEqual(config.host, 'hubName.azure-devices.net');
        assert.strictEqual(config.deviceId, 'deviceId');
        assert.strictEqual(config.hubName, 'hubName');
        assert.strictEqual(config.sharedAccessSignature, sharedAccessSignature);
      };
      Client.fromSharedAccessSignature(sharedAccessSignature, DummyTransport);
    });

    it('create a correct config when sr is URI-encoded', function () {
      var sharedAccessSignature = '"SharedAccessSignature sr=hubName.azure-devices.net%2Fdevices%2FdeviceId&sig=s1gn4tur3&se=1454204843"';
      var DummyTransport = function (config) {
        assert.strictEqual(config.host, 'hubName.azure-devices.net');
        assert.strictEqual(config.deviceId, 'deviceId');
        assert.strictEqual(config.hubName, 'hubName');
        assert.strictEqual(config.sharedAccessSignature, sharedAccessSignature);
      };
      Client.fromSharedAccessSignature(sharedAccessSignature, DummyTransport);
    });
  });

  describe('setTransportOptions', function () {
    /*Tests_SRS_NODE_DEVICE_CLIENT_16_021: [The 'setTransportOptions' method shall call the 'setOptions' method on the transport object.]*/
    /*Tests_SRS_NODE_DEVICE_CLIENT_16_022: [The 'done' callback shall be invoked with a null error object and a 'TransportConfigured' object nce the transport has been configured.]*/
    it('calls the setOptions method on the transport object and gives it the options parameter', function (done) {
      var testOptions = { foo: 42 };
      var DummyTransport = function () {
        this.setOptions = function (options, callback) {
          assert.equal(options.http.receivePolicy, testOptions);
          callback(null, new results.TransportConfigured());
        };
      };
      var client = new Client(new DummyTransport());
      client.setTransportOptions(testOptions, function (err, result) {
        if (err) {
          done(err);
        } else {
          assert.equal(result.constructor.name, 'TransportConfigured');
          done();
        }
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_023: [The 'done' callback shall be invoked with a standard javascript Error object and no result object if the transport could not be configued as requested.]*/
    it('calls the \'done\' callback with an error object if setOptions failed', function (done) {
      var DummyTransport = function () {
        this.setOptions = function (options, callback) {
          var err = new Error('fail');
          callback(err);
        };
      };
      var client = new Client(new DummyTransport());
      client.setTransportOptions({ foo: 42 }, function (err) {
        assert.isNotNull(err);
        done();
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_024: [The 'setTransportOptions' method shall throw a 'ReferenceError' if the options object is falsy] */
    [null, undefined, '', 0].forEach(function (option) {
      it('throws a ReferenceError if options is ' + option, function () {
        var DummyTransport = function () {
          this.setOptions = function () { };
        };
        var client = new Client(new DummyTransport());
        assert.throws(function () {
          client.setTransportOptions(option, function () { });
        }, ReferenceError);
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_025: [The 'setTransportOptions' method shall throw a 'NotImplementedError' if the transport doesn't implement a 'setOption' method.]*/
    it('throws a NotImplementedError if the setOptions method is not implemented on the transport', function () {
      var DummyTransport = function () { };
      var client = new Client(new DummyTransport());
      assert.throws(function () {
        client.setTransportOptions({ foo: 42 }, function () { });
      }, errors.NotImplementedError);
    });
  });

  describe('setOptions', function() {
    /*Tests_SRS_NODE_DEVICE_CLIENT_16_042: [The `setOptions` method shall throw a `ReferenceError` if the options object is falsy.]*/
    [null, undefined].forEach(function(options) {
      it('throws is options is ' + options, function() {
        var client = new Client({});
        assert.throws(function () {
          client.setOptions(options, function () { });
        }, ReferenceError);
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_043: [The `done` callback shall be invoked no parameters when it has successfully finished setting the client and/or transport options.]*/
    it('calls the done callback with no parameters when it has successfully configured the client', function(done) {
      var DummyTransport = function () {
        this.setOptions = function (options, done) {
          done();
        };
      };

      var client = new Client(new DummyTransport());
      client.setOptions({}, done);
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_044: [The `done` callback shall be invoked with a standard javascript `Error` object and no result object if the client could not be configured as requested.]*/
    it('calls the done callback with no parameters when it has successfully configured the client', function(done) {
      var FailingTransport = function () {
        this.setOptions = function (options, done) {
          done(new Error('dummy error'));
        };
      };

      var client = new Client(new FailingTransport());
      client.setOptions({}, function(err) {
        assert.instanceOf(err, Error);
        done();
      });
    });
  });

  describe('uploadToBlob', function() {
    /*Tests_SRS_NODE_DEVICE_CLIENT_16_037: [The `uploadToBlob` method shall throw a `ReferenceError` if `blobName` is falsy.]*/
    [undefined, null, ''].forEach(function (blobName) {
      it('throws a ReferenceError if \'blobName\' is ' + blobName + '\'', function() {
        var client = new Client({}, null, {});
        assert.throws(function() {
          client.uploadToBlob(blobName, new stream.Readable(), 42, function() {});
        });
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_038: [The `uploadToBlob` method shall throw a `ReferenceError` if `stream` is falsy.]*/
    [undefined, null, ''].forEach(function (stream) {
      it('throws a ReferenceError if \'stream\' is ' + stream + '\'', function() {
        var client = new Client({}, null, {});
        assert.throws(function() {
          client.uploadToBlob('blobName', stream, 42, function() {});
        });
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_039: [The `uploadToBlob` method shall throw a `ReferenceError` if `streamLength` is falsy.]*/
    [undefined, null, '', 0].forEach(function (streamLength) {
      it('throws a ReferenceError if \'streamLength\' is ' + streamLength + '\'', function() {
        var client = new Client({}, null, {});
        assert.throws(function() {
          client.uploadToBlob('blobName', new stream.Readable(), streamLength, function() {});
        });
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_040: [The `uploadToBlob` method shall call the `done` callback with an `Error` object if the upload fails.]*/
    it('calls the done callback with an Error object if the upload fails', function(done) {
      var DummyBlobUploader = function () {
        this.uploadToBlob = function(blobName, stream, streamLength, callback) {
          callback(new Error('fake error'));
        };
      };

      var client = new Client({}, null, new DummyBlobUploader());
      client.uploadToBlob('blobName', new stream.Readable(), 42, function(err) {
        assert.instanceOf(err, Error);
        done();
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_041: [The `uploadToBlob` method shall call the `done` callback no parameters if the upload succeeds.]*/
    it('calls the done callback with no parameters if the upload succeeded', function (done) {
      var DummyBlobUploader = function () {
        this.uploadToBlob = function(blobName, stream, streamLength, callback) {
          callback();
        };
      };

      var client = new Client({}, null, new DummyBlobUploader());
      client.uploadToBlob('blobName', new stream.Readable(), 42, done);
    });
  });

  describe('#open', function () {
    var TransportCanOpen = function (config) {
      EventEmitter.call(this);
      this.config = config;
    };
    util.inherits(TransportCanOpen, EventEmitter);

    TransportCanOpen.prototype.connect = function (callback) {
      callback(null, new results.Connected());
    };

    /* Tests_SRS_NODE_DEVICE_CLIENT_12_001: [The open function shall call the transport's connect function, if it exists.] */
    it('calls connect on the transport if the method exists', function (done) {
      var client = new Client(new TransportCanOpen());
      client.open(function (err, result) {
        if (err) {
          done(err);
        } else {
          assert.equal(result.constructor.name, 'Connected');
          done();
        }
      });
    });

    it('doesn\'t fail if the connect method doesn\'t exist on the transport', function (done) {
      var TransportWithoutConnect = function () { };
      var client = new Client(new TransportWithoutConnect());
      client.open(function (err, result) {
        assert.isNull(err);
        assert.equal(result.constructor.name, 'Connected');
        done();
      });
    });

    it('connects the receiver if there\'s a listener on the message event', function (done) {
      var receiver = new EventEmitter();
      receiver.on = sinon.spy();
      var DummyTransport = function () {
        this.open = function (callback) {
          callback(null, new results.Connected());
        };
        this.getReceiver = function (callback) {
          callback(null, receiver);
        };
      };

      var client = new Client(new DummyTransport());
      client.on('message', function () { });
      client.open(function (err, result) {
        if (err) {
          done(err);
        } else {
          assert.equal(result.constructor.name, 'Connected');
          assert(receiver.on.calledWith('message'));
          done();
        }
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_045: [If the transport successfully establishes a connection the `open` method shall subscribe to the `disconnect` event of the transport.]*/
    it('subscribes to the \'disconnect\' event once connected', function(done) {
      var transport = new TransportCanOpen();
      var client = new Client(transport);
      client.open(function() {
        client.on('disconnect', function() {
          done();
        });

        transport.emit('disconnect');
      });
    });
  });

  describe('#close', function () {
    var TransportCanClose = function (config) {
      EventEmitter.call(this);
      this.config = config;
    };
    util.inherits(TransportCanClose, EventEmitter);

    TransportCanClose.prototype.connect = function (callback) {
      callback(null, new results.Connected());
    };

    TransportCanClose.prototype.disconnect = function (callback) {
      callback(null, new results.Disconnected(null, 'Disconnected by the client'));
    };

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_001: [The close function shall call the transport's disconnect function if it exists.] */
    it('calls disconnect on the transport if the method exists', function (done) {
      var client = new Client(new TransportCanClose());
      client.close(function () {
        done();
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_046: [** The `disconnect` method shall remove the listener that has been attached to the transport `disconnect` event.]*/
    it('unsubscribes for the \'disconnect\' event when disconnecting', function(done) {
      var transport = new TransportCanClose();
      var client = new Client(transport);
      var disconnectReceived = false;
      client.open(function() {
        client.on('disconnect', function() {
          disconnectReceived = true;
        });
        client.close(function() {
          transport.emit('disconnect');
          assert.isFalse(disconnectReceived);
          done();
        });
      });
    });
  });

  describe('#events', function () {
    /*Tests_SRS_NODE_DEVICE_CLIENT_16_002: [The 'message' event shall be emitted when a cloud-to-device message is received from the IoT Hub service.]*/
    it('emits a message event when a message is received', function (done) {
      var DummyReceiver = function () {
        EventEmitter.call(this);
        this.emitMessage = function (msg) {
          this.emit('message', msg);
        };
      };
      util.inherits(DummyReceiver, EventEmitter);

      var receiver = new DummyReceiver();
      var DummyTransport = function () {
        EventEmitter.call(this);
        this.getReceiver = function (callback) {
          callback(null, receiver);
        };
      };
      util.inherits(DummyTransport, EventEmitter);

      var client = new Client(new DummyTransport());
      client.on('message', function (msg) {
        /*Tests_SRS_NODE_DEVICE_CLIENT_16_003: [The 'message' event parameter shall be a 'Message' object.]*/
        assert.equal(msg.constructor.name, 'Message');
        done();
      });

      receiver.emitMessage(new Message());
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_004: [The client shall start listening for messages from the service whenever there is a listener subscribed to the 'message' event.]*/
    it('starts listening for messages when a listener subscribes to the message event', function () {
      var DummyReceiver = function () {
        EventEmitter.call(this);
      };
      util.inherits(DummyReceiver, EventEmitter);

      var receiver = new DummyReceiver();
      var DummyTransport = function () {
        EventEmitter.call(this);
        this.getReceiver = function (callback) {
          callback(null, receiver);
        };
      };
      util.inherits(DummyTransport, EventEmitter);

      var client = new Client(new DummyTransport());

      client.on('message', function () { });
      client.on('message', function () { });
      assert.equal(receiver.listeners('message').length, 1, 'receiver.on was not called once.');
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_005: [The client shall stop listening for messages from the service whenever the last listener unsubscribes from the 'message' event.]*/
    it('stops listening for messages when the last listener has unsubscribed', function () {
      var DummyReceiver = function () {
        EventEmitter.call(this);
        this.emitMessage = function (msg) {
          this.emit('message', msg);
        };
        this.removeAllListeners = sinon.spy();
      };
      util.inherits(DummyReceiver, EventEmitter);

      var receiver = new DummyReceiver();
      var DummyTransport = function () {
        EventEmitter.call(this);
        this.getReceiver = function (callback) {
          callback(null, receiver);
        };
      };
      util.inherits(DummyTransport, EventEmitter);

      var client = new Client(new DummyTransport());
      var listener1 = function () { };
      var listener2 = function () { };
      client.on('message', listener1);
      client.on('message', listener2);

      client.removeListener('message', listener1);
      assert.isFalse(receiver.removeAllListeners.calledOnce);
      client.removeListener('message', listener2);
      assert(receiver.removeAllListeners.calledOnce);
    });
  });

  describe('#complete', function () {
    /*Codes_SRS_NODE_DEVICE_CLIENT_16_016: [The 'complete' method shall throw a ReferenceError if the 'message' parameter is falsy.] */
    [undefined, null, '', 0].forEach(function (message) {
      it('throws if message is \'' + message + '\'', function () {
        var DummyTransport = function () { };
        var client = new Client(new DummyTransport());
        assert.throws(function () {
          client.complete(message, function () { });
        }, ReferenceError);
      });
    });

    /*Codes_SRS_NODE_DEVICE_CLIENT_16_007: [The 'complete' method shall call the 'complete' method of the transport with the message as an argument]*/
    it('calls the complete method on the transport with the message as an argument', function () {
      var DummyTransport = function () {
        this.complete = sinon.spy();
      };
      var client = new Client(new DummyTransport());
      var message = new Message();
      client.complete(message, function () { });
      assert(client._transport.complete.calledOnce);
      assert(client._transport.complete.calledWith(message));
    });

    /*Codes_SRS_NODE_DEVICE_CLIENT_16_008: [The 'done' callback shall be called with a null error object and a 'MessageCompleted' result once the transport has completed the message.]*/
    it('calls the done callback with a null error object and a result', function (done) {
      var DummyTransport = function () {
        this.complete = function (message, callback) {
          callback(null, new results.MessageCompleted());
        };
      };

      var client = new Client(new DummyTransport());
      var message = new Message();
      client.complete(message, function (err, res) {
        if (err) {
          done(err);
        } else {
          assert.equal(res.constructor.name, 'MessageCompleted');
          done();
        }
      });
    });

    /*Codes_SRS_NODE_DEVICE_CLIENT_16_009: [The 'done' callback shall be called with a standard javascript Error object and no result object if the transport could not complete the message.]*/
    it('calls the done callback with a null error object and a result', function (done) {
      var DummyTransport = function () {
        this.complete = function (message, callback) {
          callback(null, new results.MessageCompleted());
        };
      };

      var client = new Client(new DummyTransport());
      var message = new Message();
      client.complete(message, function (err, res) {
        if (err) {
          done(err);
        } else {
          assert.equal(res.constructor.name, 'MessageCompleted');
          done();
        }
      });
    });
  });

  describe('#reject', function () {
    /*Codes_SRS_NODE_DEVICE_CLIENT_16_018: [The 'reject' method shall throw a ReferenceError if the 'message' parameter is falsy.] */
    [undefined, null, '', 0].forEach(function (message) {
      it('throws if message is \'' + message + '\'', function () {
        var DummyTransport = function () { };
        var client = new Client(new DummyTransport());
        assert.throws(function () {
          client.reject(message, function () { });
        }, ReferenceError);
      });
    });

    /*Codes_SRS_NODE_DEVICE_CLIENT_16_010: [The 'reject' method shall call the 'reject' method of the transport with the message as an argument]*/
    it('calls the reject method on the transport with the message as an argument', function () {
      var DummyTransport = function () {
        this.reject = sinon.spy();
      };
      var client = new Client(new DummyTransport());
      var message = new Message();
      client.reject(message, function () { });
      assert(client._transport.reject.calledOnce);
      assert(client._transport.reject.calledWith(message));
    });

    /*Codes_SRS_NODE_DEVICE_CLIENT_16_011: [The 'done' callback shall be called with a null error object and a 'MessageRejected' result once the transport has rejected the message.]*/
    it('calls the done callback with a null error object and a result', function (done) {
      var DummyTransport = function () {
        this.reject = function (message, callback) {
          callback(null, new results.MessageRejected());
        };
      };

      var client = new Client(new DummyTransport());
      var message = new Message();
      client.reject(message, function (err, res) {
        if (err) {
          done(err);
        } else {
          assert.equal(res.constructor.name, 'MessageRejected');
          done();
        }
      });
    });

    /*Codes_SRS_NODE_DEVICE_CLIENT_16_012: [The 'done' callback shall be called with a standard javascript Error object and no result object if the transport could not reject the message.]*/
    it('calls the done callback with a null error object and a result', function (done) {
      var DummyTransport = function () {
        this.reject = function (message, callback) {
          callback(null, new results.MessageRejected());
        };
      };

      var client = new Client(new DummyTransport());
      var message = new Message();
      client.reject(message, function (err, res) {
        if (err) {
          done(err);
        } else {
          assert.equal(res.constructor.name, 'MessageRejected');
          done();
        }
      });
    });
  });

  describe('#abandon', function () {
    /*Codes_SRS_NODE_DEVICE_CLIENT_16_018: [The 'abandon' method shall throw a ReferenceError if the 'message' parameter is falsy.] */
    [undefined, null, '', 0].forEach(function (message) {
      it('throws if message is \'' + message + '\'', function () {
        var DummyTransport = function () { };
      var client = new Client(new DummyTransport());
        assert.throws(function () {
          client.abandon(message, function () { });
        }, ReferenceError);
      });
    });

    /*Codes_SRS_NODE_DEVICE_CLIENT_16_010: [The 'abandon' method shall call the 'abandon' method of the transport with the message as an argument]*/
    it('calls the abandon method on the transport with the message as an argument', function () {
      var DummyTransport = function () {
        this.abandon = sinon.spy();
      };
      var client = new Client(new DummyTransport());
      var message = new Message();
      client.abandon(message, function () { });
      assert(client._transport.abandon.calledOnce);
      assert(client._transport.abandon.calledWith(message));
    });

    /*Codes_SRS_NODE_DEVICE_CLIENT_16_011: [The 'done' callback shall be called with a null error object and a 'Messageabandoned' result once the transport has abandoned the message.]*/
    it('calls the done callback with a null error object and a result', function (done) {
      var DummyTransport = function () {
        this.abandon = function (message, callback) {
          callback(null, new results.MessageAbandoned());
        };
      };

      var client = new Client(new DummyTransport());
      var message = new Message();
      client.abandon(message, function (err, res) {
        if (err) {
          done(err);
        } else {
          assert.equal(res.constructor.name, 'MessageAbandoned');
          done();
        }
      });
    });

    /*Codes_SRS_NODE_DEVICE_CLIENT_16_012: [The 'done' callback shall be called with a standard javascript Error object and no result object if the transport could not abandon the message.]*/
    it('calls the done callback with a null error object and a result', function (done) {
      var DummyTransport = function () {
        this.abandon = function (message, callback) {
          callback(null, new results.MessageAbandoned());
        };
      };

      var client = new Client(new DummyTransport());
      var message = new Message();
      client.abandon(message, function (err, res) {
        if (err) {
          done(err);
        } else {
          assert.equal(res.constructor.name, 'MessageAbandoned');
          done();
        }
      });
    });
  });

  describe('#updateSharedAccessSignature', function () {
    var DummyBlobUploadClient = function() {};
    DummyBlobUploadClient.prototype.updateSharedAccessSignature = function() {};

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_031: [The updateSharedAccessSignature method shall throw a ReferenceError if the sharedAccessSignature parameter is falsy.]*/
    [undefined, null, '', 0].forEach(function (sas) {
      it('throws a ReferenceError if sharedAccessSignature is \'' + sas + '\'', function () {
        var DummyTransport = function () { };
        var client = new Client(new DummyTransport());
        assert.throws(function () {
          client.updateSharedAccessSignature(sas, function () { });
        }, ReferenceError);
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_032: [The updateSharedAccessSignature method shall call the updateSharedAccessSignature method of the transport currently in use with the sharedAccessSignature parameter.]*/
    it('calls the transport `updateSharedAccessSignature` method with the sharedAccessSignature parameter', function () {
      var DummyTransport = function () {
        this.updateSharedAccessSignature = sinon.spy();
      };
      var client = new Client(new DummyTransport(), null, new DummyBlobUploadClient());
      var sas = 'sas';
      client.updateSharedAccessSignature(sas, function () { });
      assert(client._transport.updateSharedAccessSignature.calledOnce);
      assert(client._transport.updateSharedAccessSignature.calledWith(sas));
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_033: [The updateSharedAccessSignature method shall reconnect the transport to the IoTHub service if it was connected before before the method is called.]*/
    it('Reconnects the transport and receiver if necessary', function (done) {
      var connectCalled = false;
      var getReceiverCalled = false;
      var DummyTransport = function () {
        EventEmitter.call(this);
        this.connect = function (callback) {
          connectCalled = true;
          callback(null);
        };
        this.updateSharedAccessSignature = function (sas, callback) {
          callback(null, new results.SharedAccessSignatureUpdated(true));
        };
        this.getReceiver = function (callback) {
          getReceiverCalled = true;
          callback(null, new EventEmitter());
        };
      };
      util.inherits(DummyTransport, EventEmitter);

      var client = new Client(new DummyTransport(), null, new DummyBlobUploadClient());
      client.on('message', function () { });
      client.updateSharedAccessSignature('sas', function (err, res) {
        if (err) {
          done(err);
        } else {
          assert.isFalse(res.needToReconnect);
          assert(connectCalled);
          assert(getReceiverCalled);
          done();
        }
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_034: [The updateSharedAccessSignature method shall not reconnect the transport if the transport was disconnected to begin with.]*/
    it('Doesn\'t reconnect the transport if it\'s not necessary', function (done) {
      var DummyTransport = function () {
        this.connect = function () { assert.fail(); };
        this.updateSharedAccessSignature = function (sas, callback) {
          callback(null, new results.SharedAccessSignatureUpdated(false));
        };
      };

      var client = new Client(new DummyTransport(), null, new DummyBlobUploadClient());
      client.updateSharedAccessSignature('sas', function (err, res) {
        if (err) {
          done(err);
        } else {
          assert.isFalse(res.needToReconnect);
          done();
        }
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_035: [The updateSharedAccessSignature method shall call the `done` callback with an error object if an error happened while renewing the token.]*/
    it('Calls the `done` callback with an error object if an error happened', function (done) {
      var DummyTransport = function () {
        this.updateSharedAccessSignature = function (sas, callback) {
          callback(new Error('foo'));
        };
      };

      var client = new Client(new DummyTransport(), null, new DummyBlobUploadClient());
      client.updateSharedAccessSignature('sas', function (err) {
        assert.isOk(err);
        done();
      });
    });

    /*Tests_SRS_NODE_DEVICE_CLIENT_16_036: [The updateSharedAccessSignature method shall call the `done` callback with a null error object and a result of type SharedAccessSignatureUpdated if the token was updated successfully.]*/
    it('Calls the `done` callback with a null error object and a SharedAccessSignatureUpdated result', function (done) {
      var DummyTransport = function () {
        this.updateSharedAccessSignature = function (sas, callback) {
          callback(null, new results.SharedAccessSignatureUpdated());
        };
      };

      var client = new Client(new DummyTransport(), null, new DummyBlobUploadClient());
      client.updateSharedAccessSignature('sas', function (err, res) {
        if (err) {
          done(err);
        } else {
          assert.equal(res.constructor.name, 'SharedAccessSignatureUpdated');
          done();
        }
      });
    });
  });
});

describe('Over simulated HTTPS', function () {
  var registry = {
    create: function(deviceId, done) {
      done(null, {
        deviceId: deviceId,
        authentication: {
          SymmetricKey: {
            primaryKey: 'key=='
          }
        }
      });
    },
    delete: function(deviceId, done) { done(); }
  };

  clientTests.sendEventTests(SimulatedHttp, registry);
  clientTests.sendEventBatchTests(SimulatedHttp, registry);
});


text:
exports[
  'do-not-merge responds to events creates failed check when label added 1'
] = {
  conclusion: 'failure',
  name: 'Do Not Merge',
  head_sha: 'c5b0c82f5d58dd4a87e4e3e5f73cd752e552931a',
  output: {
    title: 'Remove the do not merge label before merging',
    summary: 'Remove the do not merge label before merging',
  },
};

exports[
  'do-not-merge responds to events updates check to pass after label removed 1'
] = {
  conclusion: 'success',
  output: {
    title: 'OK to merge, label not found',
    summary: 'OK to merge, label not found',
  },
};

exports[
  'do-not-merge responds to events updates check to failure after label re-added 1'
] = {
  conclusion: 'failure',
  output: {
    title: 'Remove the do not merge label before merging',
    summary: 'Remove the do not merge label before merging',
  },
};

exports[
  'do-not-merge responds to events creates failed check when alternative label added 1'
] = {
  conclusion: 'failure',
  name: 'Do Not Merge',
  head_sha: 'c5b0c82f5d58dd4a87e4e3e5f73cd752e552931a',
  output: {
    title: 'Remove the do not merge label before merging',
    summary: 'Remove the do not merge label before merging',
  },
};

exports[
  'do-not-merge responds to events creates passing check if configured to always add check 1'
] = {
  conclusion: 'success',
  name: 'Do Not Merge',
  head_sha: 'c5b0c82f5d58dd4a87e4e3e5f73cd752e552931a',
  output: {
    title: 'OK to merge, label not found',
    summary: 'OK to merge, label not found',
  },
};


text:
from typing import Generator, Iterable, Optional, Set

from dvc.exceptions import InvalidArgumentError
from dvc.scm.git import Git

from .base import (
    EXEC_BASELINE,
    EXEC_NAMESPACE,
    EXPS_NAMESPACE,
    EXPS_STASH,
    ExpRefInfo,
)

def exp_refs(scm: "Git") -> Generator["ExpRefInfo", None, None]:
    """Iterate over all experiment refs."""
    for ref in scm.iter_refs(base=EXPS_NAMESPACE):
        if ref.startswith(EXEC_NAMESPACE) or ref == EXPS_STASH:
            continue
        yield ExpRefInfo.from_ref(ref)

def exp_refs_by_rev(
    scm: "Git", rev: str
) -> Generator["ExpRefInfo", None, None]:
    """Iterate over all experiment refs pointing to the specified revision."""
    for ref in scm.get_refs_containing(rev, EXPS_NAMESPACE):
        if not (ref.startswith(EXEC_NAMESPACE) or ref == EXPS_STASH):
            yield ExpRefInfo.from_ref(ref)

def exp_refs_by_name(
    scm: "Git", name: str
) -> Generator["ExpRefInfo", None, None]:
    """Iterate over all experiment refs matching the specified name."""
    for ref_info in exp_refs(scm):
        if ref_info.name == name:
            yield ref_info

def exp_refs_by_baseline(
    scm: "Git", rev: str
) -> Generator["ExpRefInfo", None, None]:
    """Iterate over all experiment refs with the specified baseline."""
    ref_info = ExpRefInfo(baseline_sha=rev)
    for ref in scm.iter_refs(base=str(ref_info)):
        if ref.startswith(EXEC_NAMESPACE) or ref == EXPS_STASH:
            continue
        yield ExpRefInfo.from_ref(ref)

def remote_exp_refs(
    scm: "Git", url: str
) -> Generator["ExpRefInfo", None, None]:
    """Iterate over all remote experiment refs."""
    for ref in scm.iter_remote_refs(url, base=EXPS_NAMESPACE):
        if ref.startswith(EXEC_NAMESPACE) or ref == EXPS_STASH:
            continue
        yield ExpRefInfo.from_ref(ref)

def remote_exp_refs_by_name(
    scm: "Git", url: str, name: str
) -> Generator["ExpRefInfo", None, None]:
    """Iterate over all remote experiment refs matching the specified name."""
    for ref_info in remote_exp_refs(scm, url):
        if ref_info.name == name:
            yield ref_info

def remote_exp_refs_by_baseline(
    scm: "Git", url: str, rev: str
) -> Generator["ExpRefInfo", None, None]:
    """Iterate over all remote experiment refs with the specified baseline."""
    ref_info = ExpRefInfo(baseline_sha=rev)
    for ref in scm.iter_remote_refs(url, base=str(ref_info)):
        if ref.startswith(EXEC_NAMESPACE) or ref == EXPS_STASH:
            continue
        yield ExpRefInfo.from_ref(ref)

def exp_commits(
    scm: "Git", ref_infos: Iterable["ExpRefInfo"] = None
) -> Iterable[str]:
    """Iterate over all experiment commits."""
    shas: Set["str"] = set()
    refs = ref_infos if ref_infos else exp_refs(scm)
    for ref_info in refs:
        shas.update(scm.branch_revs(str(ref_info), ref_info.baseline_sha))
        if ref_info.baseline_sha:
            shas.add(ref_info.baseline_sha)
    yield from shas

def remove_exp_refs(scm: "Git", ref_infos: Iterable["ExpRefInfo"]):
    from .base import EXEC_APPLY, EXEC_BRANCH, EXEC_CHECKPOINT

    exec_branch = scm.get_ref(EXEC_BRANCH, follow=False)
    exec_apply = scm.get_ref(EXEC_APPLY)
    exec_checkpoint = scm.get_ref(EXEC_CHECKPOINT)

    for ref_info in ref_infos:
        ref = scm.get_ref(str(ref_info))
        if exec_branch and str(ref_info):
            scm.remove_ref(EXEC_BRANCH)
        if exec_apply and exec_apply == ref:
            scm.remove_ref(EXEC_APPLY)
        if exec_checkpoint and exec_checkpoint == ref:
            scm.remove_ref(EXEC_CHECKPOINT)
        scm.remove_ref(str(ref_info))

def fix_exp_head(scm: "Git", ref: Optional[str]) -> Optional[str]:
    if ref:
        name, tail = Git.split_ref_pattern(ref)
        if name == "HEAD" and scm.get_ref(EXEC_BASELINE):
            return "".join((EXEC_BASELINE, tail))
    return ref

def resolve_exp_ref(
    scm, exp_name: str, git_remote: Optional[str] = None
) -> Optional[ExpRefInfo]:
    if exp_name.startswith("refs/"):
        return ExpRefInfo.from_ref(exp_name)

    if git_remote:
        exp_ref_list = list(remote_exp_refs_by_name(scm, git_remote, exp_name))
    else:
        exp_ref_list = list(exp_refs_by_name(scm, exp_name))

    if not exp_ref_list:
        return None
    if len(exp_ref_list) > 1:
        cur_rev = scm.get_rev()
        for info in exp_ref_list:
            if info.baseline_sha == cur_rev:
                return info
        if git_remote:
            msg = [
                (
                    f"Ambiguous name '{exp_name}' refers to multiple "
                    "experiments. Use full refname to push one of the "
                    "following:"
                ),
                "",
            ]
        else:
            msg = [
                (
                    f"Ambiguous name '{exp_name}' refers to multiple "
                    f"experiments in '{git_remote}'. Use full refname to pull "
                    "one of the following:"
                ),
                "",
            ]
        msg.extend([f"\t{info}" for info in exp_ref_list])
        raise InvalidArgumentError("\n".join(msg))
    return exp_ref_list[0]

def check_ref_format(scm: "Git", ref: ExpRefInfo):
    # "/" forbidden, only in dvc exp as we didn't support it for now.
    if not scm.check_ref_format(str(ref)) or "/" in ref.name:
        raise InvalidArgumentError(
            f"Invalid exp name {ref.name}, the exp name must follow rules in "
            "https://git-scm.com/docs/git-check-ref-format"
        )


text:
function LerkBite:OnTag(tagName)

    PROFILE("LerkBite:OnTag")

    if tagName == "hit" then

        local player = self:GetParent()

        if player then

            self:TriggerEffects("lerkbite_attack")
            self:OnAttack(player)

            self.spiked = false

            local didHit, target, endPoint, surface = AttackMeleeCapsule(self, player, kLerkBiteDamage, self:GetRange(), nil, false, EntityFilterOneAndIsa(player, "Babbler"))

            if didHit and target then

                if Client then
                    self:TriggerFirstPersonHitEffects(player, target)
                end

            end

            if target and HasMixin(target, "Live") and not target:GetIsAlive() then
                self:TriggerEffects("bite_kill")
            end

        end

    end

end


text:
package org.minijs.core.ast;

public class FunctionDeclarationExpression extends FunctionDeclaration implements Expression {

    public FunctionDeclarationExpression(FormalParameterList params, BlockStatement body) {
        super(null, params, body);
    }

    public FunctionDeclarationExpression(String name, FormalParameterList params, BlockStatement body) {
        super(name, params, body);
    }
}


text:
<?php

declare(strict_types=1);

namespace Centreon\Domain\ServiceConfiguration;

use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Engine\Interfaces\EngineConfigurationServiceInterface;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\HostConfiguration\Interfaces\HostConfigurationServiceInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Centreon\Domain\Service\AbstractCentreonService;
use Centreon\Domain\ServiceConfiguration\Exception\ServiceConfigurationServiceException;
use Centreon\Domain\ServiceConfiguration\Interfaces\ServiceConfigurationRepositoryInterface;
use Centreon\Domain\ServiceConfiguration\Interfaces\ServiceConfigurationServiceInterface;

class ServiceConfigurationService extends AbstractCentreonService implements ServiceConfigurationServiceInterface
{
    use LoggerTrait;

    /**
     * @var ServiceConfigurationRepositoryInterface
     */
    private $serviceRepository;
    /**
     * @var ReadAccessGroupRepositoryInterface
     */
    private $accessGroupRepository;
    /**
     * @var EngineConfigurationServiceInterface
     */
    private $engineConfigurationService;
    /**
     * @var HostConfigurationServiceInterface
     */
    private $hostConfigurationService;

    /**
     * ServiceConfigurationService constructor.
     *
     * @param ServiceConfigurationRepositoryInterface $serviceConfigurationRepository
     * @param ReadAccessGroupRepositoryInterface $accessGroupRepository
     * @param HostConfigurationServiceInterface $hostConfigurationService
     * @param EngineConfigurationServiceInterface $engineConfigurationService
     */
    public function __construct(
        ServiceConfigurationRepositoryInterface $serviceConfigurationRepository,
        ReadAccessGroupRepositoryInterface $accessGroupRepository,
        HostConfigurationServiceInterface $hostConfigurationService,
        EngineConfigurationServiceInterface $engineConfigurationService
    ) {
        $this->serviceRepository = $serviceConfigurationRepository;
        $this->accessGroupRepository = $accessGroupRepository;
        $this->engineConfigurationService = $engineConfigurationService;
        $this->hostConfigurationService = $hostConfigurationService;
    }

    /**
     * {@inheritDoc}
     * @return ServiceConfigurationServiceInterface
     */
    public function filterByContact($contact): ServiceConfigurationServiceInterface
    {
        parent::filterByContact($contact);

        $accessGroups = $this->accessGroupRepository->findByContact($contact);
        $this->serviceRepository
            ->setContact($contact)
            ->filterByAccessGroups($accessGroups);

        return $this;
    }

    /**
     * @inheritDoc
     */
    public function applyServices(Host $host): void
    {
        $this->info('Apply services to host');
        if ($host->getId() == null) {
            throw new ServiceConfigurationException(_('The host id cannot be null'));
        }
        $hostTemplates = $this->hostConfigurationService->findHostTemplatesRecursively($host);
        if (empty($hostTemplates)) {
            return;
        }
        $host->setTemplates($hostTemplates);
        /**
         * To avoid defining a service description with illegal characters,
         * we retrieve the engine configuration to retrieve the list of these characters.
         */
        $engineConfiguration = $this->engineConfigurationService->findEngineConfigurationByHost($host);
        if ($engineConfiguration === null) {
            throw new ServiceConfigurationException(_('Unable to find the Engine configuration'));
        }

        /**
         * Find all host templates recursively and copy their id into the given list.
         *
         * **We only retrieve templates that are enabled.**
         *
         * @param Host $host Host for which we will find all host template.
         * @return int[]
         */
        $extractHostTemplateIdsFromHost =
            function (Host $host) use (&$extractHostTemplateIdsFromHost): array {
                $hostTemplateIds = [];
                foreach ($host->getTemplates() as $hostTemplate) {
                    if ($hostTemplate->isActivated() === false) {
                        continue;
                    }
                    $hostTemplateIds[] = $hostTemplate->getId();
                    if (!empty($hostTemplate->getTemplates())) {
                        // The recursive call here allow you to keep the priority orders of the host templates
                        $hostTemplateIds = array_merge(
                            $hostTemplateIds,
                            $extractHostTemplateIdsFromHost($hostTemplate)
                        );
                    }
                }
                return $hostTemplateIds;
            };

        $hostTemplateIds = $extractHostTemplateIdsFromHost($host);

        /**
         * First, we will search for services already associated with the host to avoid creating a new one with
         * same service description.
         */
        $serviceAlreadyExists = $this->findServicesByHost($host);

        /**
         * Then, we memorize the alias of service.
         * The service description is based on the alias of service template when it was created.
         */
        $serviceAliasAlreadyUsed = [];
        foreach ($serviceAlreadyExists as $service) {
            $serviceAliasAlreadyUsed[] = $service->getDescription();
        }

        /**
         * Then, we will search for all service templates associated with the host templates
         */
        $hostTemplateServices = $this->findHostTemplateServices($hostTemplateIds);

        /**
         * Extract service templates associated to host template.
         *
         * **We retrieve service templates only from an enabled host template.**
         *
         * @param int $hostTemplateId Host template id for which we want to find the services templates
         * @return Service[]
         */
        $extractServiceTemplatesByHostTemplate = function (int $hostTemplateId) use ($hostTemplateServices): array {
            $serviceTemplates = [];
            foreach ($hostTemplateServices as $hostTemplateService) {
                if ($hostTemplateService->getHostTemplate()->getId() === $hostTemplateId) {
                    // Only if the host template is activated
                    if ($hostTemplateService->getHostTemplate()->isActivated()) {
                        $serviceTemplates[] = $hostTemplateService->getServiceTemplate();
                    }
                }
            }
            return $serviceTemplates;
        };

        $servicesToBeCreated = [];

        /**
         * Then, we set aside the services to be created.
         * We must not have two services with the same description (alias of the service template).
         * The priority order is defined by the list of host templates.
         * We only retrieve the service templates that are activated.
         */
        foreach ($hostTemplateIds as $hostTemplateId) {
            $serviceTemplates = $extractServiceTemplatesByHostTemplate($hostTemplateId);

            foreach ($serviceTemplates as $serviceTemplate) {
                if (!$serviceTemplate->isActivated()) {
                    continue;
                }

                if (
                    $serviceTemplate->getAlias() !== null
                    && !in_array($serviceTemplate->getAlias(), $serviceAliasAlreadyUsed)
                ) {
                    $serviceDescription = $engineConfiguration->removeIllegalCharacters($serviceTemplate->getAlias());

                    if (empty($serviceDescription)) {
                        continue;
                    }

                    $serviceAliasAlreadyUsed[] = $serviceDescription;
                    $serviceToBeCreated = (new Service())
                        ->setServiceType(Service::TYPE_SERVICE)
                        ->setTemplateId($serviceTemplate->getId())
                        ->setDescription($serviceDescription)
                        ->setActivated(true);
                    $servicesToBeCreated[] = $serviceToBeCreated;
                }
            }
        }

        try {
            $this->debug('Service to be created', [], function () use ($servicesToBeCreated) {
                return array_map(function (Service $service) {
                    return ['id' => $service->getId(), 'description' => $service->getDescription()];
                }, $servicesToBeCreated);
            });
            $this->serviceRepository->addServicesToHost($host, $servicesToBeCreated);
        } catch (\Throwable $ex) {
            $this->error($ex->getMessage());
            throw new ServiceConfigurationException(
                sprintf(
                    _('Error when adding services to the host %d'),
                    $host->getId()
                )
            );
        }
    }

    /**
     * @inheritDoc
     */
    public function findHostTemplateServices(array $hostTemplateIds): array
    {
        try {
            return $this->serviceRepository->findHostTemplateServices($hostTemplateIds);
        } catch (\Throwable $ex) {
            throw new ServiceConfigurationException(
                _('Error when searching for host and related service templates'),
                0,
                $ex
            );
        }
    }

    /**
     * @inheritDoc
     */
    public function findService(int $serviceId): ?Service
    {
        try {
            return $this->serviceRepository->findService($serviceId);
        } catch (\Throwable $ex) {
            throw new ServiceConfigurationException(_('Error while searching for the service'), 0, $ex);
        }
    }

    /**
     * @inheritDoc
     */
    public function findServicesByHost(Host $host): array
    {
        try {
            return $this->serviceRepository->findServicesByHost($host);
        } catch (\Throwable $ex) {
            throw new ServiceConfigurationException(_('Error when searching for services by host'), 0, $ex);
        }
    }

    /**
     * @inheritDoc
     */
    public function findCommandLine(int $serviceId): ?string
    {
        try {
            return $this->serviceRepository->findCommandLine($serviceId);
        } catch (\Throwable $ex) {
            throw new ServiceConfigurationException(_('Error while searching for the command of service'), 0, $ex);
        }
    }

    /**
     * @inheritDoc
     */
    public function findOnDemandServiceMacros(int $serviceId, bool $isUsingInheritance = false): array
    {
        try {
            return $this->serviceRepository->findOnDemandServiceMacros($serviceId, $isUsingInheritance);
        } catch (\Throwable $ex) {
            throw new ServiceConfigurationException(_('Error while searching for the service macros'), 0, $ex);
        }
    }

    /**
     * @inheritDoc
     */
    public function findServiceMacrosFromCommandLine(int $serviceId, string $command): array
    {
        $serviceMacros = [];
        if (preg_match_all('/(\$_SERVICE\S+?\$)/', $command, $matches)) {
            $matchedMacros = $matches[0];

            foreach ($matchedMacros as $matchedMacroName) {
                $hostMacros[$matchedMacroName] = (new ServiceMacro())
                    ->setName($matchedMacroName)
                    ->setValue('');
            }

            $linkedServiceMacros = $this->findOnDemandServiceMacros($serviceId, true);
            foreach ($linkedServiceMacros as $linkedServiceMacro) {
                if (in_array($linkedServiceMacro->getName(), $matchedMacros)) {
                    $serviceMacros[$linkedServiceMacro->getName()] = $linkedServiceMacro;
                }
            }
        }

        return array_values($serviceMacros);
    }

    /**
     * @return HostConfigurationServiceInterface
     */
    public function getHostConfigurationService(): HostConfigurationServiceInterface
    {
        return $this->hostConfigurationService;
    }

    /**
     * @param Host $host
     * @throws \Assert\AssertionFailedException
     * @throws ServiceConfigurationServiceException
     */
    public function removeServices(Host $host): void
    {
        Assertion::notNull($host->getId(), 'Host::id');
        try {
            $this->debug('Remove services from a host', ['host_id' => $host->getId()]);
            $this->serviceRepository->removeServicesOnHost($host->getId());
        } catch (\Throwable $ex) {
            $this->error(
                sprintf(
                    _('Error on removing services from the host #%d (Reason: %s)'),
                    $host->getId(),
                    $ex->getMessage()
                )
            );
            throw ServiceConfigurationServiceException::errorOnRemovingServicesFromHost($host->getId());
        }
    }
}


text:
#ifndef _BITS_TERMIOS_INLINES_H_
#define _BITS_TERMIOS_INLINES_H_

#include <errno.h>
#include <sys/cdefs.h>
#include <sys/ioctl.h>
#include <sys/types.h>

#include <linux/termios.h>

#if !defined(__BIONIC_TERMIOS_INLINE)
#define __BIONIC_TERMIOS_INLINE static __inline
#endif

__BEGIN_DECLS

// Supporting separate input and output speeds would require an ABI
// change for `struct termios`.

static __inline speed_t cfgetspeed(const struct termios* s) {
  return __BIONIC_CAST(static_cast, speed_t, s->c_cflag & CBAUD);
}

__BIONIC_TERMIOS_INLINE speed_t cfgetispeed(const struct termios* s) {
  return cfgetspeed(s);
}

__BIONIC_TERMIOS_INLINE speed_t cfgetospeed(const struct termios* s) {
  return cfgetspeed(s);
}

__BIONIC_TERMIOS_INLINE void cfmakeraw(struct termios* s) {
  s->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
  s->c_oflag &= ~OPOST;
  s->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
  s->c_cflag &= ~(CSIZE|PARENB);
  s->c_cflag |= CS8;
  s->c_cc[VMIN] = 1;
  s->c_cc[VTIME] = 0;
}

__BIONIC_TERMIOS_INLINE int cfsetspeed(struct termios* s, speed_t speed) {
  // CBAUD is 0x100f, and every matching bit pattern has a Bxxx constant.
  if ((speed & ~CBAUD) != 0) {
    errno = EINVAL;
    return -1;
  }
  s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);
  return 0;
}

__BIONIC_TERMIOS_INLINE int cfsetispeed(struct termios* s, speed_t speed) {
  return cfsetspeed(s, speed);
}

__BIONIC_TERMIOS_INLINE int cfsetospeed(struct termios* s, speed_t speed) {
  return cfsetspeed(s, speed);
}

__BIONIC_TERMIOS_INLINE int tcdrain(int fd) {
  // A non-zero argument to TCSBRK means "don't send a break".
  // The drain is a side-effect of the ioctl!
  return ioctl(fd, TCSBRK, __BIONIC_CAST(static_cast, unsigned long, 1));
}

__BIONIC_TERMIOS_INLINE int tcflow(int fd, int action) {
  return ioctl(fd, TCXONC, __BIONIC_CAST(static_cast, unsigned long, action));
}

__BIONIC_TERMIOS_INLINE int tcflush(int fd, int queue) {
  return ioctl(fd, TCFLSH, __BIONIC_CAST(static_cast, unsigned long, queue));
}

__BIONIC_TERMIOS_INLINE int tcgetattr(int fd, struct termios* s) {
  return ioctl(fd, TCGETS, s);
}

__BIONIC_TERMIOS_INLINE pid_t tcgetsid(int fd) {
  pid_t sid;
  return (ioctl(fd, TIOCGSID, &sid) == -1) ? -1 : sid;
}

__BIONIC_TERMIOS_INLINE int tcsendbreak(int fd, int duration) {
  return ioctl(fd, TCSBRKP, __BIONIC_CAST(static_cast, unsigned long, duration));
}

__BIONIC_TERMIOS_INLINE int tcsetattr(int fd, int optional_actions, const struct termios* s) {
  int cmd;
  switch (optional_actions) {
    case TCSANOW: cmd = TCSETS; break;
    case TCSADRAIN: cmd = TCSETSW; break;
    case TCSAFLUSH: cmd = TCSETSF; break;
    default: errno = EINVAL; return -1;
  }
  return ioctl(fd, cmd, s);
}

__END_DECLS

#endif


text:
/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */
/*
 * video.h - DEPRECATED MPEG-TS video decoder API
 *
 * NOTE: should not be used on future drivers
 *
 * Copyright (C) 2000 Marcus Metzler <marcus@convergence.de>
 *                  & Ralph  Metzler <ralph@convergence.de>
 *                    for convergence integrated media GmbH
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

#ifndef _DVBVIDEO_H_
#define _DVBVIDEO_H_

#include <linux/types.h>
#include <time.h>

typedef enum {
	VIDEO_FORMAT_4_3,     /* Select 4:3 format */
	VIDEO_FORMAT_16_9,    /* Select 16:9 format. */
	VIDEO_FORMAT_221_1    /* 2.21:1 */
} video_format_t;

typedef enum {
	VIDEO_PAN_SCAN,       /* use pan and scan format */
	VIDEO_LETTER_BOX,     /* use letterbox format */
	VIDEO_CENTER_CUT_OUT  /* use center cut out format */
} video_displayformat_t;

typedef struct {
	int w;
	int h;
	video_format_t aspect_ratio;
} video_size_t;

typedef enum {
	VIDEO_SOURCE_DEMUX, /* Select the demux as the main source */
	VIDEO_SOURCE_MEMORY /* If this source is selected, the stream
			       comes from the user through the write
			       system call */
} video_stream_source_t;

typedef enum {
	VIDEO_STOPPED, /* Video is stopped */
	VIDEO_PLAYING, /* Video is currently playing */
	VIDEO_FREEZED  /* Video is freezed */
} video_play_state_t;

/* Decoder commands */
#define VIDEO_CMD_PLAY        (0)
#define VIDEO_CMD_STOP        (1)
#define VIDEO_CMD_FREEZE      (2)
#define VIDEO_CMD_CONTINUE    (3)

/* Flags for VIDEO_CMD_FREEZE */
#define VIDEO_CMD_FREEZE_TO_BLACK	(1 << 0)

/* Flags for VIDEO_CMD_STOP */
#define VIDEO_CMD_STOP_TO_BLACK		(1 << 0)
#define VIDEO_CMD_STOP_IMMEDIATELY	(1 << 1)

/* Play input formats: */
/* The decoder has no special format requirements */
#define VIDEO_PLAY_FMT_NONE         (0)
/* The decoder requires full GOPs */
#define VIDEO_PLAY_FMT_GOP          (1)

/* The structure must be zeroed before use by the application
   This ensures it can be extended safely in the future. */
struct video_command {
	__u32 cmd;
	__u32 flags;
	union {
		struct {
			__u64 pts;
		} stop;

		struct {
			/* 0 or 1000 specifies normal speed,
			   1 specifies forward single stepping,
			   -1 specifies backward single stepping,
			   >1: playback at speed/1000 of the normal speed,
			   <-1: reverse playback at (-speed/1000) of the normal speed. */
			__s32 speed;
			__u32 format;
		} play;

		struct {
			__u32 data[16];
		} raw;
	};
};

/* FIELD_UNKNOWN can be used if the hardware does not know whether
   the Vsync is for an odd, even or progressive (i.e. non-interlaced)
   field. */
#define VIDEO_VSYNC_FIELD_UNKNOWN	(0)
#define VIDEO_VSYNC_FIELD_ODD		(1)
#define VIDEO_VSYNC_FIELD_EVEN		(2)
#define VIDEO_VSYNC_FIELD_PROGRESSIVE	(3)

struct video_event {
	__s32 type;
#define VIDEO_EVENT_SIZE_CHANGED	1
#define VIDEO_EVENT_FRAME_RATE_CHANGED	2
#define VIDEO_EVENT_DECODER_STOPPED	3
#define VIDEO_EVENT_VSYNC		4
	/* unused, make sure to use atomic time for y2038 if it ever gets used */
	long timestamp;
	union {
		video_size_t size;
		unsigned int frame_rate;	/* in frames per 1000sec */
		unsigned char vsync_field;	/* unknown/odd/even/progressive */
	} u;
};

struct video_status {
	int                   video_blank;   /* blank video on freeze? */
	video_play_state_t    play_state;    /* current state of playback */
	video_stream_source_t stream_source; /* current source (demux/memory) */
	video_format_t        video_format;  /* current aspect ratio of stream*/
	video_displayformat_t display_format;/* selected cropping mode */
};

struct video_still_picture {
	char *iFrame;        /* pointer to a single iframe in memory */
	__s32 size;
};

typedef __u16 video_attributes_t;
/*   bits: descr. */
/*   15-14 Video compression mode (0=MPEG-1, 1=MPEG-2) */
/*   13-12 TV system (0=525/60, 1=625/50) */
/*   11-10 Aspect ratio (0=4:3, 3=16:9) */
/*    9- 8 permitted display mode on 4:3 monitor (0=both, 1=only pan-sca */
/*    7    line 21-1 data present in GOP (1=yes, 0=no) */
/*    6    line 21-2 data present in GOP (1=yes, 0=no) */
/*    5- 3 source resolution (0=720x480/576, 1=704x480/576, 2=352x480/57 */
/*    2    source letterboxed (1=yes, 0=no) */
/*    0    film/camera mode (0=
 *camera, 1=film (625/50 only)) */

/* bit definitions for capabilities: */
/* can the hardware decode MPEG1 and/or MPEG2? */
#define VIDEO_CAP_MPEG1   1
#define VIDEO_CAP_MPEG2   2
/* can you send a system and/or program stream to video device?
   (you still have to open the video and the audio device but only
    send the stream to the video device) */
#define VIDEO_CAP_SYS     4
#define VIDEO_CAP_PROG    8
/* can the driver also handle SPU, NAVI and CSS encoded data?
   (CSS API is not present yet) */
#define VIDEO_CAP_SPU    16
#define VIDEO_CAP_NAVI   32
#define VIDEO_CAP_CSS    64

#define VIDEO_STOP                 _IO('o', 21)
#define VIDEO_PLAY                 _IO('o', 22)
#define VIDEO_FREEZE               _IO('o', 23)
#define VIDEO_CONTINUE             _IO('o', 24)
#define VIDEO_SELECT_SOURCE        _IO('o', 25)
#define VIDEO_SET_BLANK            _IO('o', 26)
#define VIDEO_GET_STATUS           _IOR('o', 27, struct video_status)
#define VIDEO_GET_EVENT            _IOR('o', 28, struct video_event)
#define VIDEO_SET_DISPLAY_FORMAT   _IO('o', 29)
#define VIDEO_STILLPICTURE         _IOW('o', 30, struct video_still_picture)
#define VIDEO_FAST_FORWARD         _IO('o', 31)
#define VIDEO_SLOWMOTION           _IO('o', 32)
#define VIDEO_GET_CAPABILITIES     _IOR('o', 33, unsigned int)
#define VIDEO_CLEAR_BUFFER         _IO('o',  34)
#define VIDEO_SET_STREAMTYPE       _IO('o', 36)
#define VIDEO_SET_FORMAT           _IO('o', 37)
#define VIDEO_GET_SIZE             _IOR('o', 55, video_size_t)

/**
 * VIDEO_GET_PTS
 *
 * Read the 33 bit presentation time stamp as defined
 * in ITU T-REC-H.222.0 / ISO/IEC 13818-1.
 *
 * The PTS should belong to the currently played
 * frame if possible, but may also be a value close to it
 * like the PTS of the last decoded frame or the last PTS
 * extracted by the PES parser.
 */
#define VIDEO_GET_PTS              _IOR('o', 57, __u64)

/* Read the number of displayed frames since the decoder was started */
#define VIDEO_GET_FRAME_COUNT	   _IOR('o', 58, __u64)

#define VIDEO_COMMAND		   _IOWR('o', 59, struct video_command)
#define VIDEO_TRY_COMMAND	   _IOWR('o', 60, struct video_command)

#endif /* _DVBVIDEO_H_ */


text:
//-----------------------------------------------------------------------------
// <copyright file="TalentFinder.cs" company="WheelMUD Development Team">
//   Copyright (c) WheelMUD Development Team. See LICENSE.txt. This file is
//   subject to the Microsoft Public License. All other rights reserved.
// </copyright>
//
//   Created by: Karak
//   Date      : June 5, 2011
//
//-----------------------------------------------------------------------------

namespace WarriorRogueMage
{
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Linq;

    using WheelMUD.Core;
    using WheelMUD.Interfaces;

    public class TalentFinder : IRecomposable
    {
        private static readonly TalentFinder SingletonInstance = new TalentFinder();

        /// Prevents a default instance of the TalentFinder class from being created.
        private TalentFinder()
        {
            this.Recompose();
        }

        /// Gets the singleton instance of the TalentFinder class.
        public static TalentFinder Instance
        {
            get { return SingletonInstance; }
        }

        public List<Talent> NormalTalents { get; private set; }

        public List<Talent> RacialTalents { get; private set; }

        [ImportMany]
        private List<Talent> AllTalents { get; set; }

        public void Recompose()
        {
            AttributedModelServices.ComposeParts(DefaultComposer.Container, this);

            this.NormalTalents = (from t in this.AllTalents where t.TalentType == TalentType.Normal select t).ToList();
            this.RacialTalents = (from t in this.AllTalents where t.TalentType == TalentType.Racial select t).ToList();
        }
    }
}


text:
INSERT INTO t_sys_config (ID,REMARKS,USING_STATUS,CONFIG_KEY,CONFIG_VALUE,SYSTEM_TAG) VALUES
('web00',NULL,'USING','lichkin.framework.web.isAdmin','true','LichKin-Project')
,('web01',NULL,'USING','lichkin.framework.web.request.suffix.formatter','yyyy_MM_dd','LichKin-Project')
,('web02',NULL,'USING','lichkin.framework.web.webjarsCompress','true','LichKin-Project')
,('web03',NULL,'USING','lichkin.framework.web.ui','','LichKin-Project')
;