text:
\echo Use "CREATE EXTENSION gp_replica_check" to load this file. \quit
CREATE FUNCTION gp_replica_check(primarydirpath text, mirrordirpath text, include_types text) RETURNS boolean
AS '$libdir/gp_replica_check', 'gp_replica_check'
LANGUAGE C STRICT;

redpajama_set_name: RedPajamaGithub


text:
const ChangeLogs = require('@warp-works/warpjs-change-logs');
const Promise = require('bluebird');

module.exports = (req, res, persistence, entity, instance) => Promise.resolve()
    .then(() => entity.removeEmbedded(instance, req.body.docLevel, 0))
    .then(() => ChangeLogs.add(ChangeLogs.ACTIONS.EMBEDDED_REMOVED, req.warpjsUser, instance, { key: req.body.docLevel }))
    .then(() => entity.updateDocument(persistence, instance, true))
;


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

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.cloudfront.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * FieldLevelEncryptionSummary StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class FieldLevelEncryptionSummaryStaxUnmarshaller implements Unmarshaller<FieldLevelEncryptionSummary, StaxUnmarshallerContext> {

    public FieldLevelEncryptionSummary unmarshall(StaxUnmarshallerContext context) throws Exception {
        FieldLevelEncryptionSummary fieldLevelEncryptionSummary = new FieldLevelEncryptionSummary();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return fieldLevelEncryptionSummary;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("Id", targetDepth)) {
                    fieldLevelEncryptionSummary.setId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("LastModifiedTime", targetDepth)) {
                    fieldLevelEncryptionSummary.setLastModifiedTime(DateStaxUnmarshallerFactory.getInstance("iso8601").unmarshall(context));
                    continue;
                }

                if (context.testExpression("Comment", targetDepth)) {
                    fieldLevelEncryptionSummary.setComment(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("QueryArgProfileConfig", targetDepth)) {
                    fieldLevelEncryptionSummary.setQueryArgProfileConfig(QueryArgProfileConfigStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("ContentTypeProfileConfig", targetDepth)) {
                    fieldLevelEncryptionSummary.setContentTypeProfileConfig(ContentTypeProfileConfigStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return fieldLevelEncryptionSummary;
                }
            }
        }
    }

    private static FieldLevelEncryptionSummaryStaxUnmarshaller instance;

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


text:
Jyväskylän yliopiston Pelinkehityshaaste-kurssin 2. syklin peli. Aiheena eduskunta ja vaalit vuonna 2015.

[**Pelisuunnitelma**](https://webapps.jyu.fi/wiki/display/pelihaaste/Suunnitelma+-+Puolueiden+Arvot+-+v1.0)

## Asennus

Asenna ensin [Ruby](https://www.ruby-lang.org/en/) ja [Ruby on Rails](http://rubyonrails.org/). Aja sitten seuraavat komennot päätteessä.

```bash
$ cd PuolueenArvot
$ bundle install
$ rake db:migrate
$ rake db:seed
$ rails s
```

Avaa selaimesi ja mene osoitteeseen http://localhost:3000. Peliohjeet saat ruudulle sinisestä painikkeesta ennen pelin alkua ja sen aikana.

## Tekijät

[Niko Heikkilä](https://github.com/nikoheikkila) & [Matias Berg](https://github.com/bergmatias)


text: """Defines ways of accessing Runs via HTTP interface."""


text:
using Eigen::MatrixXd;
using Eigen::VectorXd;
using stan::math::diagonal;
using stan::math::matrix_cl;

TEST(KernelGenerator, diagonal_test) {
  MatrixXd m = MatrixXd::Random(3, 4);

  matrix_cl<double> m_cl(m);

  matrix_cl<double> res_cl = diagonal(m_cl);
  MatrixXd res = stan::math::from_matrix_cl(res_cl);

  MatrixXd correct = m.diagonal();
  EXPECT_MATRIX_NEAR(res, correct, 1e-9);
}

TEST(KernelGenerator, diagonal_multiple_operations_test) {
  MatrixXd m = MatrixXd::Random(4, 3);

  matrix_cl<double> m_cl(m);

  matrix_cl<double> res_cl = diagonal(m_cl * 2);
  MatrixXd res = stan::math::from_matrix_cl(res_cl);

  MatrixXd correct = (2 * m).diagonal();
  EXPECT_MATRIX_NEAR(res, correct, 1e-9);
}

TEST(KernelGenerator, diagonal_multiple_operations_accept_lvalue_test) {
  MatrixXd m = MatrixXd::Random(3, 4);

  matrix_cl<double> m_cl(m);

  auto tmp = m_cl * 2;
  matrix_cl<double> res_cl = diagonal(tmp);
  MatrixXd res = stan::math::from_matrix_cl(res_cl);

  MatrixXd correct = (2 * m).diagonal();
  EXPECT_MATRIX_NEAR(res, correct, 1e-9);
}

TEST(KernelGenerator, diagonal_lhs_test) {
  MatrixXd m = MatrixXd::Random(3, 4);
  VectorXd v = VectorXd::Random(3);

  matrix_cl<double> m_cl(m);
  matrix_cl<double> v_cl(v);

  diagonal(m_cl) = v_cl;
  MatrixXd res = stan::math::from_matrix_cl(m_cl);

  MatrixXd correct = m;
  correct.diagonal() = v;
  EXPECT_MATRIX_NEAR(res, correct, 1e-9);
}

TEST(KernelGenerator, diagonal_of_a_block_test) {
  MatrixXd m = MatrixXd::Random(4, 4);

  matrix_cl<double> m_cl(m);

  diagonal(block_zero_based(m_cl, 0, 1, 3, 3))
      = diagonal(block_zero_based(m_cl, 1, 0, 3, 3));
  MatrixXd res = stan::math::from_matrix_cl(m_cl);

  MatrixXd correct = m;
  correct.diagonal(1) = correct.diagonal(-1);
  EXPECT_MATRIX_NEAR(res, correct, 1e-9);
}

TEST(KernelGenerator, diagonal_lhs_add_assign_test) {
  MatrixXd m = MatrixXd::Random(3, 4);
  MatrixXd correct = m;
  correct.diagonal().array() += 1;

  matrix_cl<double> m_cl(m);

  diagonal(m_cl) += 1;
  MatrixXd res = stan::math::from_matrix_cl(m_cl);

  EXPECT_MATRIX_NEAR(res, correct, 1e-9);
}

#endif


text:
Funcionario::Funcionario(const string &nom, const int &sal, const int fechIng[])
    : nombreFuncionario{nom}, salario{sal}
    {
        for(int i = 0; i < 3; i++){
            fechaIngreso[i] = fechIng[i];
        }
    }

Funcionario::~Funcionario()
{
    if(fechaCopia)
        delete[] fechaCopia;
}

void Funcionario::estabNomFun(const string &nomFun)
{
    nombreFuncionario = nomFun;
}

void Funcionario::estabSalario(const int &sal)
{
    salario = sal;
}

void Funcionario::estabFechaIngreso(const int fechIng[])
{
    for(int i = 0; i < 3; i++){
        fechaIngreso[i] = fechIng[i];
    }
}

string Funcionario::getNombFun() const
{
    return nombreFuncionario;
}

int Funcionario::getSalario() const
{
    return salario;
}

int *Funcionario::getFechIng()
{
    fechaCopia = new int[3];
    for(int i = 0; i < 3; i++){
        fechaCopia[i] = fechaIngreso[i];
    }
    return fechaCopia;
}

///////////////////////////////////////////////////////////////////////

Empresa::Empresa(const string &nom, const int &_ruc)
    : nombreEmpresa{nom}, ruc{_ruc} {}

void Empresa::estabNomEmp(const string &nomEmp)
{
    nombreEmpresa = nomEmp;
}

void Empresa::estabRuc(const int &_ruc)
{
    ruc = _ruc;
}

void Empresa::estabDepart(const string &dep)
{
    departFunc[dep];
}

void Empresa::estabNewFunc(Funcionario *const func, const string &dep)
{
    departFunc[dep].push_back(func);
}

string Empresa::getNomEmp() const
{
    return nombreEmpresa;
}

int Empresa::getRuc() const
{
    return ruc;
}

unsigned Empresa::getNumFuncDep(const string &dep)
{
    return departFunc[dep].size();
}

void Empresa::aumentoDiezPC(const string &dep)
{
    for (unsigned i = 0; i < departFunc[dep].size(); i++){
        int salAnt = departFunc[dep][i] -> getSalario();
        int newSal = salAnt + (salAnt / 10);
        departFunc[dep][i] -> estabSalario(newSal);
    }
}


text:
'use strict';

var Bluebird  = require('bluebird');
var expect    = require('expect.js');
var helper    = require('../helper');
var Migration = require('../../lib/migration');
var Umzug     = require('../../index');
var sinon     = require('sinon');

describe('Umzug', function () {
  describe('executed', function () {
    beforeEach(function () {
      return helper
        .prepareMigrations(3)
        .bind(this)
        .then(function (migrationNames) {
          this.migrationNames = migrationNames;
          this.umzug          = new Umzug({
            migrations:     { path: __dirname + '/../tmp/' },
            storageOptions: { path: __dirname + '/../tmp/umzug.json' }
          });
        });
    });

    describe('when no migrations has been executed yet', function () {
      beforeEach(function () {
        return this.umzug.executed()
          .bind(this).then(function (migrations) {
            this.migrations = migrations;
          });
      });

      it('returns an array', function () {
        expect(this.migrations).to.be.an(Array);
      });

      it('returns 0 items', function () {
        expect(this.migrations).to.have.length(0);
      });
    });

    describe('when one migration has been executed yet', function () {
      beforeEach(function () {
        return this.umzug.execute({
          migrations: [ this.migrationNames[0] ],
          method:     'up'
        }).bind(this).then(function () {
          return this.umzug.executed()
        }).then(function (migrations) {
          this.migrations = migrations;
        });
      });

      it('returns an array', function () {
        expect(this.migrations).to.be.an(Array);
      });

      it('returns 1 items', function () {
        expect(this.migrations).to.have.length(1);
        expect(this.migrations[0].file).to.equal(this.migrationNames[0] + '.js');
      });
    });

    describe('when all migration has been executed yet', function () {
      beforeEach(function () {
        return this.umzug.execute({
          migrations: this.migrationNames,
          method:     'up'
        }).bind(this).then(function () {
          return this.umzug.executed()
        }).then(function (migrations) {
          this.migrations = migrations;
        });
      });

      it('returns an array', function () {
        expect(this.migrations).to.be.an(Array);
      });

      it('returns 3 items', function () {
        expect(this.migrations).to.have.length(3);
        expect(this.migrations[0].file).to.equal(this.migrationNames[0] + '.js');
        expect(this.migrations[1].file).to.equal(this.migrationNames[1] + '.js');
        expect(this.migrations[2].file).to.equal(this.migrationNames[2] + '.js');
      });
    });

    describe('when storage returns a thenable', function() {
      beforeEach(function() {
        // migration has been executed already
        return this.umzug.execute({
          migrations: [ this.migrationNames[0] ],
          method:     'up'
        }).bind(this).then(function () {
          this.umzug.storage = helper.wrapStorageAsCustomThenable(this.umzug.storage);
          return this.umzug.executed();
        }).then(function (migrations) {
          this.migrations = migrations;
        });
      });

      it('returns an array', function () {
        expect(this.migrations).to.be.an(Array);
      });

      it('returns 1 items', function () {
        expect(this.migrations).to.have.length(1);
        expect(this.migrations[0].file).to.equal(this.migrationNames[0] + '.js');
      });
    });

  });
});


text:
exceptional
===========

This is a Haskell library that exists to house a type:

```haskell
data Exceptional x
  = Failure String
  | Success x
```

It's much like `Maybe`, except instead of `Nothing`, we have `Failure
String`.

A comparison could also be made to `Either String`. I made this
library because I was dissatisfied with the `Monad` instance for
`Either`. In this type, `fail = Failure`. It's rather simple.

Installing
----------

    cabal install exceptional

Or, add `exceptional` to the `build-depends` field in your `.cabal`
file.


text: google-site-verification: google49a99fccdf90f21b.html


text:
** __Deprecated BikeIndex.org resources archive__ **

Previously there was a spreadsheet here with the bicycling manufacturers from Bike Index, but it wasn't kept up to date.

This spreadsheet is now exclusively stored on Bike Index itself - [bikeindex.org/manufacturers/tsv](https://bikeindex.org/manufacturers/tsv) (it's a .tsv, because it's tab separated).

If you'd like to add a manufacturer or update one of the existing ones, please comment on [bikeindex.org/manufacturers](https://bikeindex.org/manufacturers)


text:
#ifndef INCLUDE_ULFBERHT_LOGGER_LOGOUTPUT_
#define INCLUDE_ULFBERHT_LOGGER_LOGOUTPUT_

/*
 * Author: jrahm
 * created: 2015/05/24
 * LogOutput.hpp: <description>
 */

#include <ulfberht/io/BaseOutput.hpp>
#include <ulfberht/io/PrintStream.hpp>

namespace logger {

class LogOutput: public io::PrintStream {
public:
    inline LogOutput(io::BaseOutput& output, bool colors=true)
        : io::PrintStream(output), m_colors_enabled(colors) {}

    inline bool isColorEnabled() const
        { return m_colors_enabled; }

private:
    bool m_colors_enabled;
};

};

#endif /* INCLUDE_ULFBERHT_LOGGER_LOGOUTPUT_ */


text:
require 'spec_helper'

describe 'Dashboard > User filters todos', feature: true, js: true do
  include WaitForAjax

  let(:user_1)    { create(:user, username: 'user_1', name: 'user_1') }
  let(:user_2)    { create(:user, username: 'user_2', name: 'user_2') }

  let(:project_1) { create(:empty_project, name: 'project_1') }
  let(:project_2) { create(:empty_project, name: 'project_2') }

  let(:issue) { create(:issue, title: 'issue', project: project_1) }

  let!(:merge_request) { create(:merge_request, source_project: project_2, title: 'merge_request') }

  before do
    create(:todo, user: user_1, author: user_2, project: project_1, target: issue, action: 1)
    create(:todo, user: user_1, author: user_1, project: project_2, target: merge_request, action: 2)

    project_1.team << [user_1, :developer]
    project_2.team << [user_1, :developer]
    login_as(user_1)
    visit dashboard_todos_path
  end

  it 'filters by project' do
    click_button 'Project'
    within '.dropdown-menu-project' do
      fill_in 'Search projects', with: project_1.name_with_namespace
      click_link project_1.name_with_namespace
    end

    wait_for_ajax

    expect(page).to     have_content project_1.name_with_namespace
    expect(page).not_to have_content project_2.name_with_namespace
  end

  context "Author filter" do
    it 'filters by author' do
      click_button 'Author'

      within '.dropdown-menu-author' do
        fill_in 'Search authors', with: user_1.name
        click_link user_1.name
      end

      wait_for_ajax

      expect(find('.todos-list')).to     have_content user_1.name
      expect(find('.todos-list')).not_to have_content user_2.name
    end

    it "shows only authors of existing todos" do
      click_button 'Author'

      within '.dropdown-menu-author' do
        # It should contain two users + "Any Author"
        expect(page).to have_selector('.dropdown-menu-user-link', count: 3)
        expect(page).to have_content(user_1.name)
        expect(page).to have_content(user_2.name)
      end
    end

    it "shows only authors of existing done todos" do
      user_3 = create :user
      user_4 = create :user
      create(:todo, user: user_1, author: user_3, project: project_1, target: issue, action: 1, state: :done)
      create(:todo, user: user_1, author: user_4, project: project_2, target: merge_request, action: 2, state: :done)

      project_1.team << [user_3, :developer]
      project_2.team << [user_4, :developer]

      visit dashboard_todos_path(state: 'done')

      click_button 'Author'

      within '.dropdown-menu-author' do
        # It should contain two users + "Any Author"
        expect(page).to have_selector('.dropdown-menu-user-link', count: 3)
        expect(page).to have_content(user_3.name)
        expect(page).to have_content(user_4.name)
        expect(page).not_to have_content(user_1.name)
        expect(page).not_to have_content(user_2.name)
      end
    end
  end

  it 'filters by type' do
    click_button 'Type'
    within '.dropdown-menu-type' do
      click_link 'Issue'
    end

    wait_for_ajax

    expect(find('.todos-list')).to     have_content issue.to_reference
    expect(find('.todos-list')).not_to have_content merge_request.to_reference
  end

  it 'filters by action' do
    click_button 'Action'
    within '.dropdown-menu-action' do
      click_link 'Assigned'
    end

    wait_for_ajax

    expect(find('.todos-list')).to     have_content ' assigned you '
    expect(find('.todos-list')).not_to have_content ' mentioned '
  end
end


text:
. $PSScriptRoot\model.ps1

function Run-JingaOperation
{
	Param (
		 [Parameter(Mandatory=$true)]
         [YamlModel]  $YamlModel
)
	     [JingaModel[]] $JingaModelCollection = @()

	foreach ($model in $YamlModel.SubstitutionModel) {
	$jingaModel = 	Get-JingaFactoryObject
		$jingaModel.FileName = $model.FileName;
		foreach ($Submodel in $model.SubstitutionCollection.GetEnumerator()) {
			 if($YamlModel.TypeModel.XpathType.ContainsKey($Submodel.Key))
			{
				 $jingaModel.XpathTypeCollection+=Add-VariableToCollection $Submodel $YamlModel.TypeModel.XpathType[$Submodel.Key]
				continue;
			}
				 if($YamlModel.TypeModel.RegexType.ContainsKey($Submodel.Key))
			{
				 $jingaModel.RegexCollection+=Add-VariableToCollection $Submodel $YamlModel.TypeModel.RegexType[$Submodel.Key]
				continue;
			}
			$jingaModel.StringTypeCollection+=Add-VariableToCollection  $Submodel $YamlModel.TypeModel.XpathType[$Submodel.Key]
		}
		$JingaModelCollection+=$jingaModel;
		}
	Write-Host $JingaModelCollection |Format-Table
		return $JingaModelCollection;
}

function Get-JingaFactoryObject()
{
		$jingaModel = New-Object JingaModel
		$jingaModel.StringTypeCollection = @()
		$jingaModel.XpathTypeCollection = @()
		$jingaModel.RegexCollection = @()
	return $jingaModel;
}

function Add-VariableToCollection($model,$typeProperty)
{
	$variable = New-Object VariableModel;
	$variable.Name = $model.Key;
	$variable.Value = $model.Value;
	$variable.TypeProperty = $typeProperty;
	return $variable;

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__int_rand_multiply_22a.c
Label Definition File: CWE191_Integer_Underflow__int.label.xml
Template File: sources-sinks-22a.tmpl.c
*/
/*
 * @description
 * CWE: 191 Integer Underflow
 * BadSource: rand Set data to result of rand(), which may be zero
 * GoodSource: Set data to a small, non-zero number (negative two)
 * Sinks: multiply
 *    GoodSink: Ensure there will not be an underflow before multiplying data by 2
 *    BadSink : If data is negative, multiply by 2, which can cause an underflow
 * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources.
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

/* The global variable below is used to drive control flow in the sink function */
int CWE191_Integer_Underflow__int_rand_multiply_22_badGlobal = 0;

void CWE191_Integer_Underflow__int_rand_multiply_22_badSink(int data);

void CWE191_Integer_Underflow__int_rand_multiply_22_bad()
{
    int data;
    /* Initialize data */
    data = 0;
    /* POTENTIAL FLAW: Set data to a random value */
    data = RAND32();
    CWE191_Integer_Underflow__int_rand_multiply_22_badGlobal = 1; /* true */
    CWE191_Integer_Underflow__int_rand_multiply_22_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* The global variables below are used to drive control flow in the sink functions. */
int CWE191_Integer_Underflow__int_rand_multiply_22_goodB2G1Global = 0;
int CWE191_Integer_Underflow__int_rand_multiply_22_goodB2G2Global = 0;
int CWE191_Integer_Underflow__int_rand_multiply_22_goodG2BGlobal = 0;

/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
void CWE191_Integer_Underflow__int_rand_multiply_22_goodB2G1Sink(int data);

static void goodB2G1()
{
    int data;
    /* Initialize data */
    data = 0;
    /* POTENTIAL FLAW: Set data to a random value */
    data = RAND32();
    CWE191_Integer_Underflow__int_rand_multiply_22_goodB2G1Global = 0; /* false */
    CWE191_Integer_Underflow__int_rand_multiply_22_goodB2G1Sink(data);
}

/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */
void CWE191_Integer_Underflow__int_rand_multiply_22_goodB2G2Sink(int data);

static void goodB2G2()
{
    int data;
    /* Initialize data */
    data = 0;
    /* POTENTIAL FLAW: Set data to a random value */
    data = RAND32();
    CWE191_Integer_Underflow__int_rand_multiply_22_goodB2G2Global = 1; /* true */
    CWE191_Integer_Underflow__int_rand_multiply_22_goodB2G2Sink(data);
}

/* goodG2B() - use goodsource and badsink */
void CWE191_Integer_Underflow__int_rand_multiply_22_goodG2BSink(int data);

static void goodG2B()
{
    int data;
    /* Initialize data */
    data = 0;
    /* FIX: Use a small, non-zero value that will not cause an integer underflow in the sinks */
    data = -2;
    CWE191_Integer_Underflow__int_rand_multiply_22_goodG2BGlobal = 1; /* true */
    CWE191_Integer_Underflow__int_rand_multiply_22_goodG2BSink(data);
}

void CWE191_Integer_Underflow__int_rand_multiply_22_good()
{
    goodB2G1();
    goodB2G2();
    goodG2B();
}

#endif /* OMITGOOD */

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

#ifdef INCLUDEMAIN

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

#endif


text:
/*!
 * \file
 * \brief The Filter Kernel (Extras)
 * \author Erik Rainey <erik.rainey@gmail.com>
 */

#include <VX/vx.h>
#include <VX/vx_lib_extras.h>
#include <VX/vx_helper.h>
#include <extras_k.h>

static vx_status VX_CALLBACK vxLaplacian3x3Kernel(vx_node node, vx_reference *parameters, vx_uint32 num)
{
    vx_status status = VX_ERROR_INVALID_PARAMETERS;
    if (num == 2)
    {
        vx_border_mode_t bordermode;
        vx_image src = (vx_image)parameters[0];
        vx_image dst = (vx_image)parameters[1];
        status = vxQueryNode(node, VX_NODE_ATTRIBUTE_BORDER_MODE, &bordermode, sizeof(bordermode));
        if (status == VX_SUCCESS)
        {
            status = vxLaplacian3x3(src, dst, &bordermode);
        }
    }
    return status;
}

static vx_status VX_CALLBACK vxFilterInputValidator(vx_node node, vx_uint32 index)
{
    vx_status status = VX_ERROR_INVALID_PARAMETERS;
    if (index == 0)
    {
        vx_parameter param = vxGetParameterByIndex(node, index);
        if (param)
        {
            vx_image input = 0;
            vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &input, sizeof(input));
            if (input)
            {
                vx_df_image format = 0;
                vxQueryImage(input, VX_IMAGE_ATTRIBUTE_FORMAT, &format, sizeof(format));
                if (format == VX_DF_IMAGE_U8)
                {
                    status = VX_SUCCESS;
                }
                vxReleaseImage(&input);
            }
            vxReleaseParameter(&param);
        }
    }
    return status;
}

static vx_status VX_CALLBACK vxFilterOutputValidator(vx_node node, vx_uint32 index, vx_meta_format meta)
{
    vx_status status = VX_ERROR_INVALID_PARAMETERS;
    if (index == 1)
    {
        vx_parameter param = vxGetParameterByIndex(node, 0); /* we reference the input image */
        if (param)
        {
            vx_image input = 0;
            vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &input, sizeof(input));
            if (input)
            {
                vx_uint32 width = 0, height = 0;
                vx_df_image format = VX_DF_IMAGE_U8;

                vxQueryImage(input, VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width));
                vxQueryImage(input, VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height));

                vxSetMetaFormatAttribute(meta, VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width));
                vxSetMetaFormatAttribute(meta, VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height));
                vxSetMetaFormatAttribute(meta, VX_IMAGE_ATTRIBUTE_FORMAT, &format, sizeof(format));

                vxReleaseImage(&input);

                status = VX_SUCCESS;
            }
            vxReleaseParameter(&param);
        }
    }
    return status;
}

static vx_param_description_t filter_kernel_params[] = {
    {VX_INPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED},
    {VX_OUTPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED},
};

vx_kernel_description_t laplacian3x3_kernel = {
    VX_KERNEL_EXTRAS_LAPLACIAN_3x3,
    "org.khronos.extras.laplacian3x3",
    vxLaplacian3x3Kernel,
    filter_kernel_params, dimof(filter_kernel_params),
    vxFilterInputValidator,
    vxFilterOutputValidator,
    NULL,
    NULL,
};


text:
layout : page
title : Resume
subtitle: Work Experiences
---

**Research Experience/Machine Learning Experience**
**Research Intern** in _1QBit, Canada_
_Sept 2017 – Present_
* Working in the machine learning team, focusing on the aspect of integrating knowledge of advanced quantum
computation and machine learning in the area of quantitative finance
* Worked with Accenture Labs and Biogen in developing a first-of-its-kind quantum-enabled molecular
comparison application which could vastly enhance advanced molecular design for drug discovery
* Learned about Agile framework when working with researchers and software developers, and the importance of
communication in meeting client-oriented project deadlines

**Teaching Experience**
**Teaching Assistant** for _Discrete Mathematics, Algorithms_ in _SFU, Canada_
_Jan 2017 – August 2017_
* Conducted tutorials on topics involving logics, set theory, combinatorics, design and analysis of algorithms using
resources such as textbook, online problem sets to help students build a solid foundation in mathematics
* Marked assignments, midterm exams within a time frame and provided useful feedbacks to the students by
showing common conceptual mistakes during tutorials
* Learned to convey sophisticated concepts in simpler terms, which helps improving communication and
presentation skills

**Research Experience/Optimization Experience**
**Research Assistant** in _Computational Biology_ in _SFU, Canada_
_Sept 2016 – Present_
* Study the diversity of pathogenic bacteria which causes Lyme disease, Borrelia Burgdorferi in tick samples using
mathematical and computational approaches under the supervision of Prof. Chindelevitch and Prof. Chauve
* Mapped and aligned ~60GB Illumina short reads data using Bowtie, SRA Toolkit and ClusterW
* Formulated mixed integer linear programs(MILP) to address different biological problems and coded MILPs
using CPLEX Python API
* Communicated with biologists about their prior expectations on co-infection pattern and the result of this project
will lead to improved ecological prevention and control protocol of Lyme disease

**Operational Research / Optimization Experience**
**Strategic Planning and Advisory Intern** in _AECOM Asia Co. Ltd., Hong Kong_
_June 2015 – Aug 2015_
* Participated in constructing a customized transport model for a major bus company in Hong Kong using different
software such as EMME, ArcGIS and Excel, where the company attained about 13% increase in bus route
efficiency after first trial run of the model
* Analysed traffic, transport and population related data using different aggregate and logical functions in Excel, in
which these analysed data were inputs of the transport model
* Experienced cultures and administrations of one of the largest multinational engineering consulting firm


text:
using System;
using System.Collections.Generic;
using NetTypeS.Interfaces;

namespace NetTypeS.Elements.Dynamic
{
    internal class SingleDynamicElement : IDynamicElement
    {
        private readonly ITypeScriptElement _element;
        private readonly Func<ITypeScriptElement> _customFunction;

        public SingleDynamicElement(Func<ITypeScriptElement> customFunction)
        {
            _customFunction = customFunction;
            _element = null;
        }

        public SingleDynamicElement(ITypeScriptElement element)
        {
            _element = element;
            _customFunction = null;
        }

        public IEnumerable<ITypeScriptElement> GetElements()
        {
            yield return _customFunction == null ? _element : _customFunction();
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>Animatable: One property, two values, endless possibilities</title>
<link href="style.css" rel="stylesheet" />

<hgroup>

Animatable

One property, two values, endless possibilities

</hgroup>

<input type="radio" name="animate" id="on-hover" checked />
Animate on hover
<input type="radio" name="animate" id="all" />
Animate all

	<a data-property="background-position" data-from="3px 0, 3px 0, 15px -150px, 15px -150px" data-to="3px -70px, 3px -70px, 15px -80px, 15px -80px" style="background-color: #E04332; background-repeat: repeat-x; background-size: 24px 300px; background-image: linear-gradient(135deg, slategray 25%, transparent 25%), linear-gradient(45deg, transparent 75%, slategray 75%), linear-gradient(45deg, slategray 25%, transparent 25%), linear-gradient(135deg, transparent 75%, slategray 75%);" data-author="kizmarh">

box-shadow

	◀
	▶

From:

0 0 black

To:

0 150px 10px -50px rgba(0,0,0,.5)

Author:

@leaverou

Made by Lea Verou with care

Tweet


text:
package org.apache.camel.component.google.calendar;

import java.util.Arrays;
import java.util.List;

import com.google.api.services.calendar.Calendar;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.component.google.calendar.internal.GoogleCalendarApiCollection;
import org.apache.camel.component.google.calendar.internal.GoogleCalendarApiName;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.component.AbstractApiComponent;

/**
 * Represents the component that manages {@link GoogleCalendarEndpoint}.
 */
@Component("google-calendar")
public class GoogleCalendarComponent extends AbstractApiComponent<GoogleCalendarApiName, GoogleCalendarConfiguration, GoogleCalendarApiCollection> {

    @Metadata
    GoogleCalendarConfiguration configuration;

    @Metadata(label = "advanced")
    private Calendar client;
    @Metadata(label = "advanced")
    private GoogleCalendarClientFactory clientFactory;

    public GoogleCalendarComponent() {
        super(GoogleCalendarEndpoint.class, GoogleCalendarApiName.class, GoogleCalendarApiCollection.getCollection());
    }

    public GoogleCalendarComponent(CamelContext context) {
        super(context, GoogleCalendarEndpoint.class, GoogleCalendarApiName.class, GoogleCalendarApiCollection.getCollection());
    }

    @Override
    protected GoogleCalendarApiName getApiName(String apiNameStr) throws IllegalArgumentException {
        return GoogleCalendarApiName.fromValue(apiNameStr);
    }

    public Calendar getClient(GoogleCalendarConfiguration config) {
        if (client == null) {

            List<String> list = null;
            if (config.getScopes() != null) {
                String[] arr = config.getScopes().split(",");
                list = Arrays.asList(arr);
            }

            client = getClientFactory().makeClient(config.getClientId(),
                    config.getClientSecret(), list,
                    config.getApplicationName(), config.getRefreshToken(),
                    config.getAccessToken(), config.getEmailAddress(),
                    config.getP12FileName(), config.getUser());
        }
        return client;
    }

    public GoogleCalendarClientFactory getClientFactory() {
        if (clientFactory == null) {
            clientFactory = new BatchGoogleCalendarClientFactory();
        }
        return clientFactory;
    }

    @Override
    public GoogleCalendarConfiguration getConfiguration() {
        if (configuration == null) {
            configuration = new GoogleCalendarConfiguration();
        }
        return super.getConfiguration();
    }

    /**
     * To use the shared configuration
     */
    @Override
    public void setConfiguration(GoogleCalendarConfiguration configuration) {
        super.setConfiguration(configuration);
    }

    /**
     * To use the GoogleCalendarClientFactory as factory for creating the client.
     * Will by default use {@link BatchGoogleCalendarClientFactory}
     */
    public void setClientFactory(GoogleCalendarClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }

    @Override
    protected Endpoint createEndpoint(String uri, String methodName, GoogleCalendarApiName apiName,
                                      GoogleCalendarConfiguration endpointConfiguration) {
        endpointConfiguration.setApiName(apiName);
        endpointConfiguration.setMethodName(methodName);
        return new GoogleCalendarEndpoint(uri, this, apiName, methodName, endpointConfiguration);
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stallone.api.complex;

import stallone.api.doubles.IDoubleElement;

/**
 *
 * @author noe
 */
public interface IComplexElement extends IDoubleElement
{
    public double re();

    public double im();

    public void setRe(double x);

    public void setIm(double x);
}


text:
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */

'use strict';

const msRest = require('ms-rest');
const ServiceClient = msRest.ServiceClient;
const WebResource = msRest.WebResource;

const models = require('./models');

/**
 * @summary The AutoSuggest API lets you send a search query to Bing and get
 * back a list of query suggestions. This section provides technical details
 * about the query parameters and headers that you use to request suggestions
 * and the JSON response objects that contain them.
 *
 * @param {string} query The user's search term.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.acceptLanguage] A comma-delimited list of one or
 * more languages to use for user interface strings. The list is in decreasing
 * order of preference. For additional information, including expected format,
 * see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
 * header and the setLang query parameter are mutually exclusive; do not
 * specify both. If you set this header, you must also specify the
 * [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#cc)
 * query parameter. To determine the market to return results for, Bing uses
 * the first supported language it finds from the list and combines it with the
 * cc parameter value. If the list does not include a supported language, Bing
 * finds the closest language and market that supports the request or it uses
 * an aggregated or default market for the results. To determine the market
 * that Bing used, see the BingAPIs-Market header. Use this header and the cc
 * query parameter only if you specify multiple languages. Otherwise, use the
 * [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#mkt)
 * and
 * [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#setlang)
 * query parameters. A user interface string is a string that's used as a label
 * in a user interface. There are few user interface strings in the JSON
 * response objects. Any links to Bing.com properties in the response objects
 * apply the specified language.
 *
 * @param {string} [options.pragma] By default, Bing returns cached content, if
 * available. To prevent Bing from returning cached content, set the Pragma
 * header to no-cache (for example, Pragma: no-cache).
 *
 * @param {string} [options.userAgent] The user agent originating the request.
 * Bing uses the user agent to provide mobile users with an optimized
 * experience. Although optional, you are encouraged to always specify this
 * header. The user-agent should be the same string that any commonly used
 * browser sends. For information about user agents, see [RFC
 * 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following
 * are examples of user-agent strings. Windows Phone: Mozilla/5.0 (compatible;
 * MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA;
 * Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH -
 * I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version /
 * 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS 6_1
 * like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142
 * iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3;
 * WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad: Mozilla / 5.0 (iPad;
 * CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version
 * / 7.0 Mobile / 11A465 Safari / 9537.53
 *
 * @param {string} [options.clientId] Bing uses this header to provide users
 * with consistent behavior across Bing API calls. Bing often flights new
 * features and improvements, and it uses the client ID as a key for assigning
 * traffic on different flights. If you do not use the same client ID for a
 * user across multiple requests, then Bing may assign the user to multiple
 * conflicting flights. Being assigned to multiple conflicting flights can lead
 * to an inconsistent user experience. For example, if the second request has a
 * different flight assignment than the first, the experience may be
 * unexpected. Also, Bing can use the client ID to tailor web results to that
 * client ID's search history, providing a richer experience for the user. Bing
 * also uses this header to help improve result rankings by analyzing the
 * activity generated by a client ID. The relevance improvements help with
 * better quality of results delivered by Bing APIs and in turn enables higher
 * click-through rates for the API consumer. IMPORTANT: Although optional, you
 * should consider this header required. Persisting the client ID across
 * multiple requests for the same end user and device combination enables 1)
 * the API consumer to receive a consistent user experience, and 2) higher
 * click-through rates via better quality of results from the Bing APIs. Each
 * user that uses your application on the device must have a unique, Bing
 * generated client ID. If you do not include this header in the request, Bing
 * generates an ID and returns it in the X-MSEdge-ClientID response header. The
 * only time that you should NOT include this header in a request is the first
 * time the user uses your app on that device. Use the client ID for each Bing
 * API request that your app makes for this user on the device. Persist the
 * client ID. To persist the ID in a browser app, use a persistent HTTP cookie
 * to ensure the ID is used across all sessions. Do not use a session cookie.
 * For other apps such as mobile apps, use the device's persistent storage to
 * persist the ID. The next time the user uses your app on that device, get the
 * client ID that you persisted. Bing responses may or may not include this
 * header. If the response includes this header, capture the client ID and use
 * it for all subsequent Bing requests for the user on that device. If you
 * include the X-MSEdge-ClientID, you must not include cookies in the request.
 *
 * @param {string} [options.clientIp] The IPv4 or IPv6 address of the client
 * device. The IP address is used to discover the user's location. Bing uses
 * the location information to determine safe search behavior. Although
 * optional, you are encouraged to always specify this header and the
 * X-Search-Location header. Do not obfuscate the address (for example, by
 * changing the last octet to 0). Obfuscating the address results in the
 * location not being anywhere near the device's actual location, which may
 * result in Bing serving erroneous results.
 *
 * @param {string} [options.location] A semicolon-delimited list of key/value
 * pairs that describe the client's geographical location. Bing uses the
 * location information to determine safe search behavior and to return
 * relevant local content. Specify the key/value pair as <key>:<value>. The
 * following are the keys that you use to specify the user's location. lat
 * (required): The latitude of the client's location, in degrees. The latitude
 * must be greater than or equal to -90.0 and less than or equal to +90.0.
 * Negative values indicate southern latitudes and positive values indicate
 * northern latitudes. long (required): The longitude of the client's location,
 * in degrees. The longitude must be greater than or equal to -180.0 and less
 * than or equal to +180.0. Negative values indicate western longitudes and
 * positive values indicate eastern longitudes. re (required): The radius, in
 * meters, which specifies the horizontal accuracy of the coordinates. Pass the
 * value returned by the device's location service. Typical values might be 22m
 * for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP
 * lookup. ts (optional): The UTC UNIX timestamp of when the client was at the
 * location. (The UNIX timestamp is the number of seconds since January 1,
 * 1970.) head (optional): The client's relative heading or direction of
 * travel. Specify the direction of travel as degrees from 0 through 360,
 * counting clockwise relative to true north. Specify this key only if the sp
 * key is nonzero. sp (optional): The horizontal velocity (speed), in meters
 * per second, that the client device is traveling. alt (optional): The
 * altitude of the client device, in meters. are (optional): The radius, in
 * meters, that specifies the vertical accuracy of the coordinates. Specify
 * this key only if you specify the alt key. Although many of the keys are
 * optional, the more information that you provide, the more accurate the
 * location results are. Although optional, you are encouraged to always
 * specify the user's geographical location. Providing the location is
 * especially important if the client's IP address does not accurately reflect
 * the user's physical location (for example, if the client uses VPN). For
 * optimal results, you should include this header and the X-MSEdge-ClientIP
 * header, but at a minimum, you should include this header.
 *
 * @param {string} [options.countryCode] A 2-character country code of the
 * country where the results come from. This API supports only the United
 * States market. If you specify this query parameter, it must be set to us. If
 * you set this parameter, you must also specify the Accept-Language header.
 * Bing uses the first supported language it finds from the languages list, and
 * combine that language with the country code that you specify to determine
 * the market to return results for. If the languages list does not include a
 * supported language, Bing finds the closest language and market that supports
 * the request, or it may use an aggregated or default market for the results
 * instead of a specified one. You should use this query parameter and the
 * Accept-Language query parameter only if you specify multiple languages;
 * otherwise, you should use the mkt and setLang query parameters. This
 * parameter and the mkt query parameter are mutually exclusive—do not specify
 * both.
 *
 * @param {string} [options.market] The market where the results come from. You
 * are strongly encouraged to always specify the market, if known. Specifying
 * the market helps Bing route the request and return an appropriate and
 * optimal response. This parameter and the cc query parameter are mutually
 * exclusive—do not specify both.
 *
 * @param {string} [options.safeSearch] Filter suggestions for adult content.
 * The following are the possible filter values. Off: Return suggestions with
 * adult text, images, or videos. Moderate: Return suggestion with adult text
 * but not adult images or videos. Strict: Do not return news articles with
 * adult text, images, or videos. If the request comes from a market that
 * Bing's adult policy requires that safeSearch is set to Strict, Bing ignores
 * the safeSearch value and uses Strict. If you use the site: query operator,
 * there is the chance that the response may contain adult content regardless
 * of what the safeSearch query parameter is set to. Use site: only if you are
 * aware of the content on the site and your scenario supports the possibility
 * of adult content. Possible values include: 'Off', 'Moderate', 'Strict'
 *
 * @param {string} [options.setLang] The language to use for user interface
 * strings. Specify the language using the ISO 639-1 2-letter language code.
 * For example, the language code for English is EN. The default is EN
 * (English). Although optional, you should always specify the language.
 * Typically, you set setLang to the same language specified by mkt unless the
 * user wants the user interface strings displayed in a different language.
 * This parameter and the Accept-Language header are mutually exclusive; do not
 * specify both. A user interface string is a string that's used as a label in
 * a user interface. There are few user interface strings in the JSON response
 * objects. Also, any links to Bing.com properties in the response objects
 * apply the specified language.
 *
 * @param {array} [options.responseFormat] The media type to use for the
 * response. The following are the possible case-insensitive values: JSON,
 * JSONLD. The default is JSON. If you specify JSONLD, the response body
 * includes JSON-LD objects that contain the search results.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link Suggestions} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _autoSuggest(query, options, callback) {
   /* jshint validthis: true */
  let client = this;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let acceptLanguage = (options && options.acceptLanguage !== undefined) ? options.acceptLanguage : undefined;
  let pragma = (options && options.pragma !== undefined) ? options.pragma : undefined;
  let userAgent = (options && options.userAgent !== undefined) ? options.userAgent : undefined;
  let clientId = (options && options.clientId !== undefined) ? options.clientId : undefined;
  let clientIp = (options && options.clientIp !== undefined) ? options.clientIp : undefined;
  let location = (options && options.location !== undefined) ? options.location : undefined;
  let countryCode = (options && options.countryCode !== undefined) ? options.countryCode : undefined;
  let market = (options && options.market !== undefined) ? options.market : 'en-us';
  let safeSearch = (options && options.safeSearch !== undefined) ? options.safeSearch : undefined;
  let setLang = (options && options.setLang !== undefined) ? options.setLang : undefined;
  let responseFormat = (options && options.responseFormat !== undefined) ? options.responseFormat : undefined;
  let xBingApisSDK = 'true';
  // Validate
  try {
    if (this.endpoint === null || this.endpoint === undefined || typeof this.endpoint.valueOf() !== 'string') {
      throw new Error('this.endpoint cannot be null or undefined and it must be of type string.');
    }
    if (acceptLanguage !== null && acceptLanguage !== undefined && typeof acceptLanguage.valueOf() !== 'string') {
      throw new Error('acceptLanguage must be of type string.');
    }
    if (pragma !== null && pragma !== undefined && typeof pragma.valueOf() !== 'string') {
      throw new Error('pragma must be of type string.');
    }
    if (userAgent !== null && userAgent !== undefined && typeof userAgent.valueOf() !== 'string') {
      throw new Error('userAgent must be of type string.');
    }
    if (clientId !== null && clientId !== undefined && typeof clientId.valueOf() !== 'string') {
      throw new Error('clientId must be of type string.');
    }
    if (clientIp !== null && clientIp !== undefined && typeof clientIp.valueOf() !== 'string') {
      throw new Error('clientIp must be of type string.');
    }
    if (location !== null && location !== undefined && typeof location.valueOf() !== 'string') {
      throw new Error('location must be of type string.');
    }
    if (countryCode !== null && countryCode !== undefined && typeof countryCode.valueOf() !== 'string') {
      throw new Error('countryCode must be of type string.');
    }
    if (market !== null && market !== undefined && typeof market.valueOf() !== 'string') {
      throw new Error('market must be of type string.');
    }
    if (query === null || query === undefined || typeof query.valueOf() !== 'string') {
      throw new Error('query cannot be null or undefined and it must be of type string.');
    }
    if (safeSearch !== null && safeSearch !== undefined && typeof safeSearch.valueOf() !== 'string') {
      throw new Error('safeSearch must be of type string.');
    }
    if (setLang !== null && setLang !== undefined && typeof setLang.valueOf() !== 'string') {
      throw new Error('setLang must be of type string.');
    }
    if (Array.isArray(responseFormat)) {
      for (let i = 0; i < responseFormat.length; i++) {
        if (responseFormat[i] !== null && responseFormat[i] !== undefined && typeof responseFormat[i].valueOf() !== 'string') {
          throw new Error('responseFormat[i] must be of type string.');
        }
      }
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'Suggestions';
  requestUrl = requestUrl.replace('{Endpoint}', this.endpoint);
  let queryParameters = [];
  if (countryCode !== null && countryCode !== undefined) {
    queryParameters.push('cc=' + encodeURIComponent(countryCode));
  }
  if (market !== null && market !== undefined) {
    queryParameters.push('mkt=' + encodeURIComponent(market));
  }
  queryParameters.push('q=' + encodeURIComponent(query));
  if (safeSearch !== null && safeSearch !== undefined) {
    queryParameters.push('safeSearch=' + encodeURIComponent(safeSearch));
  }
  if (setLang !== null && setLang !== undefined) {
    queryParameters.push('setLang=' + encodeURIComponent(setLang));
  }
  if (responseFormat !== null && responseFormat !== undefined) {
    queryParameters.push('ResponseFormat=' + encodeURIComponent(responseFormat.join(',')));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (xBingApisSDK !== undefined && xBingApisSDK !== null) {
    httpRequest.headers['X-BingApis-SDK'] = xBingApisSDK;
  }
  if (acceptLanguage !== undefined && acceptLanguage !== null) {
    httpRequest.headers['Accept-Language'] = acceptLanguage;
  }
  if (pragma !== undefined && pragma !== null) {
    httpRequest.headers['Pragma'] = pragma;
  }
  if (userAgent !== undefined && userAgent !== null) {
    httpRequest.headers['User-Agent'] = userAgent;
  }
  if (clientId !== undefined && clientId !== null) {
    httpRequest.headers['X-MSEdge-ClientID'] = clientId;
  }
  if (clientIp !== undefined && clientIp !== null) {
    httpRequest.headers['X-MSEdge-ClientIP'] = clientIp;
  }
  if (location !== undefined && location !== null) {
    httpRequest.headers['X-Search-Location'] = location;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['Suggestions']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/** Class representing a AutoSuggestClient. */
class AutoSuggestClient extends ServiceClient {
  /**
   * Create a AutoSuggestClient.
   * @param {credentials} credentials - Subscription credentials which uniquely identify client subscription.
   * @param {object} [options] - The parameter options
   * @param {Array} [options.filters] - Filters to be added to the request pipeline
   * @param {object} [options.requestOptions] - Options for the underlying request object
   * {@link https://github.com/request/request#requestoptions-callback Options doc}
   * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy
   * @param {string} [options.endpoint] - Supported Cognitive Services endpoints (protocol and hostname, for example: "https://westus.api.cognitive.microsoft.com", "https://api.cognitive.microsoft.com").
   */
  constructor(credentials, options) {
    if (credentials === null || credentials === undefined) {
      throw new Error('\'credentials\' cannot be null.');
    }

    if (!options) options = {};

    super(credentials, options);

    this.endpoint = 'https://api.cognitive.microsoft.com';
    this.baseUri = '{Endpoint}/bing/v7.0';
    this.credentials = credentials;

    let packageInfo = this.getPackageJsonInfo(__dirname);
    this.addUserAgentInfo(`${packageInfo.name}/${packageInfo.version}`);
    if(options.endpoint !== null && options.endpoint !== undefined) {
      this.endpoint = options.endpoint;
    }
    this.models = models;
    this._autoSuggest = _autoSuggest;
    msRest.addSerializationMixin(this);
  }

  /**
   * @summary The AutoSuggest API lets you send a search query to Bing and get
   * back a list of query suggestions. This section provides technical details
   * about the query parameters and headers that you use to request suggestions
   * and the JSON response objects that contain them.
   *
   * @param {string} query The user's search term.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.acceptLanguage] A comma-delimited list of one or
   * more languages to use for user interface strings. The list is in decreasing
   * order of preference. For additional information, including expected format,
   * see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
   * header and the setLang query parameter are mutually exclusive; do not
   * specify both. If you set this header, you must also specify the
   * [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#cc)
   * query parameter. To determine the market to return results for, Bing uses
   * the first supported language it finds from the list and combines it with the
   * cc parameter value. If the list does not include a supported language, Bing
   * finds the closest language and market that supports the request or it uses
   * an aggregated or default market for the results. To determine the market
   * that Bing used, see the BingAPIs-Market header. Use this header and the cc
   * query parameter only if you specify multiple languages. Otherwise, use the
   * [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#mkt)
   * and
   * [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#setlang)
   * query parameters. A user interface string is a string that's used as a label
   * in a user interface. There are few user interface strings in the JSON
   * response objects. Any links to Bing.com properties in the response objects
   * apply the specified language.
   *
   * @param {string} [options.pragma] By default, Bing returns cached content, if
   * available. To prevent Bing from returning cached content, set the Pragma
   * header to no-cache (for example, Pragma: no-cache).
   *
   * @param {string} [options.userAgent] The user agent originating the request.
   * Bing uses the user agent to provide mobile users with an optimized
   * experience. Although optional, you are encouraged to always specify this
   * header. The user-agent should be the same string that any commonly used
   * browser sends. For information about user agents, see [RFC
   * 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following
   * are examples of user-agent strings. Windows Phone: Mozilla/5.0 (compatible;
   * MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA;
   * Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH -
   * I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version /
   * 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS 6_1
   * like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142
   * iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3;
   * WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad: Mozilla / 5.0 (iPad;
   * CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version
   * / 7.0 Mobile / 11A465 Safari / 9537.53
   *
   * @param {string} [options.clientId] Bing uses this header to provide users
   * with consistent behavior across Bing API calls. Bing often flights new
   * features and improvements, and it uses the client ID as a key for assigning
   * traffic on different flights. If you do not use the same client ID for a
   * user across multiple requests, then Bing may assign the user to multiple
   * conflicting flights. Being assigned to multiple conflicting flights can lead
   * to an inconsistent user experience. For example, if the second request has a
   * different flight assignment than the first, the experience may be
   * unexpected. Also, Bing can use the client ID to tailor web results to that
   * client ID's search history, providing a richer experience for the user. Bing
   * also uses this header to help improve result rankings by analyzing the
   * activity generated by a client ID. The relevance improvements help with
   * better quality of results delivered by Bing APIs and in turn enables higher
   * click-through rates for the API consumer. IMPORTANT: Although optional, you
   * should consider this header required. Persisting the client ID across
   * multiple requests for the same end user and device combination enables 1)
   * the API consumer to receive a consistent user experience, and 2) higher
   * click-through rates via better quality of results from the Bing APIs. Each
   * user that uses your application on the device must have a unique, Bing
   * generated client ID. If you do not include this header in the request, Bing
   * generates an ID and returns it in the X-MSEdge-ClientID response header. The
   * only time that you should NOT include this header in a request is the first
   * time the user uses your app on that device. Use the client ID for each Bing
   * API request that your app makes for this user on the device. Persist the
   * client ID. To persist the ID in a browser app, use a persistent HTTP cookie
   * to ensure the ID is used across all sessions. Do not use a session cookie.
   * For other apps such as mobile apps, use the device's persistent storage to
   * persist the ID. The next time the user uses your app on that device, get the
   * client ID that you persisted. Bing responses may or may not include this
   * header. If the response includes this header, capture the client ID and use
   * it for all subsequent Bing requests for the user on that device. If you
   * include the X-MSEdge-ClientID, you must not include cookies in the request.
   *
   * @param {string} [options.clientIp] The IPv4 or IPv6 address of the client
   * device. The IP address is used to discover the user's location. Bing uses
   * the location information to determine safe search behavior. Although
   * optional, you are encouraged to always specify this header and the
   * X-Search-Location header. Do not obfuscate the address (for example, by
   * changing the last octet to 0). Obfuscating the address results in the
   * location not being anywhere near the device's actual location, which may
   * result in Bing serving erroneous results.
   *
   * @param {string} [options.location] A semicolon-delimited list of key/value
   * pairs that describe the client's geographical location. Bing uses the
   * location information to determine safe search behavior and to return
   * relevant local content. Specify the key/value pair as <key>:<value>. The
   * following are the keys that you use to specify the user's location. lat
   * (required): The latitude of the client's location, in degrees. The latitude
   * must be greater than or equal to -90.0 and less than or equal to +90.0.
   * Negative values indicate southern latitudes and positive values indicate
   * northern latitudes. long (required): The longitude of the client's location,
   * in degrees. The longitude must be greater than or equal to -180.0 and less
   * than or equal to +180.0. Negative values indicate western longitudes and
   * positive values indicate eastern longitudes. re (required): The radius, in
   * meters, which specifies the horizontal accuracy of the coordinates. Pass the
   * value returned by the device's location service. Typical values might be 22m
   * for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP
   * lookup. ts (optional): The UTC UNIX timestamp of when the client was at the
   * location. (The UNIX timestamp is the number of seconds since January 1,
   * 1970.) head (optional): The client's relative heading or direction of
   * travel. Specify the direction of travel as degrees from 0 through 360,
   * counting clockwise relative to true north. Specify this key only if the sp
   * key is nonzero. sp (optional): The horizontal velocity (speed), in meters
   * per second, that the client device is traveling. alt (optional): The
   * altitude of the client device, in meters. are (optional): The radius, in
   * meters, that specifies the vertical accuracy of the coordinates. Specify
   * this key only if you specify the alt key. Although many of the keys are
   * optional, the more information that you provide, the more accurate the
   * location results are. Although optional, you are encouraged to always
   * specify the user's geographical location. Providing the location is
   * especially important if the client's IP address does not accurately reflect
   * the user's physical location (for example, if the client uses VPN). For
   * optimal results, you should include this header and the X-MSEdge-ClientIP
   * header, but at a minimum, you should include this header.
   *
   * @param {string} [options.countryCode] A 2-character country code of the
   * country where the results come from. This API supports only the United
   * States market. If you specify this query parameter, it must be set to us. If
   * you set this parameter, you must also specify the Accept-Language header.
   * Bing uses the first supported language it finds from the languages list, and
   * combine that language with the country code that you specify to determine
   * the market to return results for. If the languages list does not include a
   * supported language, Bing finds the closest language and market that supports
   * the request, or it may use an aggregated or default market for the results
   * instead of a specified one. You should use this query parameter and the
   * Accept-Language query parameter only if you specify multiple languages;
   * otherwise, you should use the mkt and setLang query parameters. This
   * parameter and the mkt query parameter are mutually exclusive—do not specify
   * both.
   *
   * @param {string} [options.market] The market where the results come from. You
   * are strongly encouraged to always specify the market, if known. Specifying
   * the market helps Bing route the request and return an appropriate and
   * optimal response. This parameter and the cc query parameter are mutually
   * exclusive—do not specify both.
   *
   * @param {string} [options.safeSearch] Filter suggestions for adult content.
   * The following are the possible filter values. Off: Return suggestions with
   * adult text, images, or videos. Moderate: Return suggestion with adult text
   * but not adult images or videos. Strict: Do not return news articles with
   * adult text, images, or videos. If the request comes from a market that
   * Bing's adult policy requires that safeSearch is set to Strict, Bing ignores
   * the safeSearch value and uses Strict. If you use the site: query operator,
   * there is the chance that the response may contain adult content regardless
   * of what the safeSearch query parameter is set to. Use site: only if you are
   * aware of the content on the site and your scenario supports the possibility
   * of adult content. Possible values include: 'Off', 'Moderate', 'Strict'
   *
   * @param {string} [options.setLang] The language to use for user interface
   * strings. Specify the language using the ISO 639-1 2-letter language code.
   * For example, the language code for English is EN. The default is EN
   * (English). Although optional, you should always specify the language.
   * Typically, you set setLang to the same language specified by mkt unless the
   * user wants the user interface strings displayed in a different language.
   * This parameter and the Accept-Language header are mutually exclusive; do not
   * specify both. A user interface string is a string that's used as a label in
   * a user interface. There are few user interface strings in the JSON response
   * objects. Also, any links to Bing.com properties in the response objects
   * apply the specified language.
   *
   * @param {array} [options.responseFormat] The media type to use for the
   * response. The following are the possible case-insensitive values: JSON,
   * JSONLD. The default is JSON. If you specify JSONLD, the response body
   * includes JSON-LD objects that contain the search results.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<Suggestions>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  autoSuggestWithHttpOperationResponse(query, options) {
    let client = this;
    let self = this;
    return new Promise((resolve, reject) => {
      self._autoSuggest(query, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary The AutoSuggest API lets you send a search query to Bing and get
   * back a list of query suggestions. This section provides technical details
   * about the query parameters and headers that you use to request suggestions
   * and the JSON response objects that contain them.
   *
   * @param {string} query The user's search term.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.acceptLanguage] A comma-delimited list of one or
   * more languages to use for user interface strings. The list is in decreasing
   * order of preference. For additional information, including expected format,
   * see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
   * header and the setLang query parameter are mutually exclusive; do not
   * specify both. If you set this header, you must also specify the
   * [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#cc)
   * query parameter. To determine the market to return results for, Bing uses
   * the first supported language it finds from the list and combines it with the
   * cc parameter value. If the list does not include a supported language, Bing
   * finds the closest language and market that supports the request or it uses
   * an aggregated or default market for the results. To determine the market
   * that Bing used, see the BingAPIs-Market header. Use this header and the cc
   * query parameter only if you specify multiple languages. Otherwise, use the
   * [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#mkt)
   * and
   * [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#setlang)
   * query parameters. A user interface string is a string that's used as a label
   * in a user interface. There are few user interface strings in the JSON
   * response objects. Any links to Bing.com properties in the response objects
   * apply the specified language.
   *
   * @param {string} [options.pragma] By default, Bing returns cached content, if
   * available. To prevent Bing from returning cached content, set the Pragma
   * header to no-cache (for example, Pragma: no-cache).
   *
   * @param {string} [options.userAgent] The user agent originating the request.
   * Bing uses the user agent to provide mobile users with an optimized
   * experience. Although optional, you are encouraged to always specify this
   * header. The user-agent should be the same string that any commonly used
   * browser sends. For information about user agents, see [RFC
   * 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following
   * are examples of user-agent strings. Windows Phone: Mozilla/5.0 (compatible;
   * MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA;
   * Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH -
   * I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version /
   * 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS 6_1
   * like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142
   * iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3;
   * WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad: Mozilla / 5.0 (iPad;
   * CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version
   * / 7.0 Mobile / 11A465 Safari / 9537.53
   *
   * @param {string} [options.clientId] Bing uses this header to provide users
   * with consistent behavior across Bing API calls. Bing often flights new
   * features and improvements, and it uses the client ID as a key for assigning
   * traffic on different flights. If you do not use the same client ID for a
   * user across multiple requests, then Bing may assign the user to multiple
   * conflicting flights. Being assigned to multiple conflicting flights can lead
   * to an inconsistent user experience. For example, if the second request has a
   * different flight assignment than the first, the experience may be
   * unexpected. Also, Bing can use the client ID to tailor web results to that
   * client ID's search history, providing a richer experience for the user. Bing
   * also uses this header to help improve result rankings by analyzing the
   * activity generated by a client ID. The relevance improvements help with
   * better quality of results delivered by Bing APIs and in turn enables higher
   * click-through rates for the API consumer. IMPORTANT: Although optional, you
   * should consider this header required. Persisting the client ID across
   * multiple requests for the same end user and device combination enables 1)
   * the API consumer to receive a consistent user experience, and 2) higher
   * click-through rates via better quality of results from the Bing APIs. Each
   * user that uses your application on the device must have a unique, Bing
   * generated client ID. If you do not include this header in the request, Bing
   * generates an ID and returns it in the X-MSEdge-ClientID response header. The
   * only time that you should NOT include this header in a request is the first
   * time the user uses your app on that device. Use the client ID for each Bing
   * API request that your app makes for this user on the device. Persist the
   * client ID. To persist the ID in a browser app, use a persistent HTTP cookie
   * to ensure the ID is used across all sessions. Do not use a session cookie.
   * For other apps such as mobile apps, use the device's persistent storage to
   * persist the ID. The next time the user uses your app on that device, get the
   * client ID that you persisted. Bing responses may or may not include this
   * header. If the response includes this header, capture the client ID and use
   * it for all subsequent Bing requests for the user on that device. If you
   * include the X-MSEdge-ClientID, you must not include cookies in the request.
   *
   * @param {string} [options.clientIp] The IPv4 or IPv6 address of the client
   * device. The IP address is used to discover the user's location. Bing uses
   * the location information to determine safe search behavior. Although
   * optional, you are encouraged to always specify this header and the
   * X-Search-Location header. Do not obfuscate the address (for example, by
   * changing the last octet to 0). Obfuscating the address results in the
   * location not being anywhere near the device's actual location, which may
   * result in Bing serving erroneous results.
   *
   * @param {string} [options.location] A semicolon-delimited list of key/value
   * pairs that describe the client's geographical location. Bing uses the
   * location information to determine safe search behavior and to return
   * relevant local content. Specify the key/value pair as <key>:<value>. The
   * following are the keys that you use to specify the user's location. lat
   * (required): The latitude of the client's location, in degrees. The latitude
   * must be greater than or equal to -90.0 and less than or equal to +90.0.
   * Negative values indicate southern latitudes and positive values indicate
   * northern latitudes. long (required): The longitude of the client's location,
   * in degrees. The longitude must be greater than or equal to -180.0 and less
   * than or equal to +180.0. Negative values indicate western longitudes and
   * positive values indicate eastern longitudes. re (required): The radius, in
   * meters, which specifies the horizontal accuracy of the coordinates. Pass the
   * value returned by the device's location service. Typical values might be 22m
   * for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP
   * lookup. ts (optional): The UTC UNIX timestamp of when the client was at the
   * location. (The UNIX timestamp is the number of seconds since January 1,
   * 1970.) head (optional): The client's relative heading or direction of
   * travel. Specify the direction of travel as degrees from 0 through 360,
   * counting clockwise relative to true north. Specify this key only if the sp
   * key is nonzero. sp (optional): The horizontal velocity (speed), in meters
   * per second, that the client device is traveling. alt (optional): The
   * altitude of the client device, in meters. are (optional): The radius, in
   * meters, that specifies the vertical accuracy of the coordinates. Specify
   * this key only if you specify the alt key. Although many of the keys are
   * optional, the more information that you provide, the more accurate the
   * location results are. Although optional, you are encouraged to always
   * specify the user's geographical location. Providing the location is
   * especially important if the client's IP address does not accurately reflect
   * the user's physical location (for example, if the client uses VPN). For
   * optimal results, you should include this header and the X-MSEdge-ClientIP
   * header, but at a minimum, you should include this header.
   *
   * @param {string} [options.countryCode] A 2-character country code of the
   * country where the results come from. This API supports only the United
   * States market. If you specify this query parameter, it must be set to us. If
   * you set this parameter, you must also specify the Accept-Language header.
   * Bing uses the first supported language it finds from the languages list, and
   * combine that language with the country code that you specify to determine
   * the market to return results for. If the languages list does not include a
   * supported language, Bing finds the closest language and market that supports
   * the request, or it may use an aggregated or default market for the results
   * instead of a specified one. You should use this query parameter and the
   * Accept-Language query parameter only if you specify multiple languages;
   * otherwise, you should use the mkt and setLang query parameters. This
   * parameter and the mkt query parameter are mutually exclusive—do not specify
   * both.
   *
   * @param {string} [options.market] The market where the results come from. You
   * are strongly encouraged to always specify the market, if known. Specifying
   * the market helps Bing route the request and return an appropriate and
   * optimal response. This parameter and the cc query parameter are mutually
   * exclusive—do not specify both.
   *
   * @param {string} [options.safeSearch] Filter suggestions for adult content.
   * The following are the possible filter values. Off: Return suggestions with
   * adult text, images, or videos. Moderate: Return suggestion with adult text
   * but not adult images or videos. Strict: Do not return news articles with
   * adult text, images, or videos. If the request comes from a market that
   * Bing's adult policy requires that safeSearch is set to Strict, Bing ignores
   * the safeSearch value and uses Strict. If you use the site: query operator,
   * there is the chance that the response may contain adult content regardless
   * of what the safeSearch query parameter is set to. Use site: only if you are
   * aware of the content on the site and your scenario supports the possibility
   * of adult content. Possible values include: 'Off', 'Moderate', 'Strict'
   *
   * @param {string} [options.setLang] The language to use for user interface
   * strings. Specify the language using the ISO 639-1 2-letter language code.
   * For example, the language code for English is EN. The default is EN
   * (English). Although optional, you should always specify the language.
   * Typically, you set setLang to the same language specified by mkt unless the
   * user wants the user interface strings displayed in a different language.
   * This parameter and the Accept-Language header are mutually exclusive; do not
   * specify both. A user interface string is a string that's used as a label in
   * a user interface. There are few user interface strings in the JSON response
   * objects. Also, any links to Bing.com properties in the response objects
   * apply the specified language.
   *
   * @param {array} [options.responseFormat] The media type to use for the
   * response. The following are the possible case-insensitive values: JSON,
   * JSONLD. The default is JSON. If you specify JSONLD, the response body
   * includes JSON-LD objects that contain the search results.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {Suggestions} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link Suggestions} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  autoSuggest(query, options, optionalCallback) {
    let client = this;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._autoSuggest(query, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._autoSuggest(query, options, optionalCallback);
    }
  }

}

module.exports = AutoSuggestClient;
module.exports['default'] = AutoSuggestClient;
module.exports.AutoSuggestClient = AutoSuggestClient;
module.exports.AutoSuggestModels = models;


text:
Imports BaseClasses
Imports System.Web.UI
Imports DTIServerControls
Imports DTITagManager.dsTagger

''' <summary>
''' Page object with DTI-managed media meta data
''' </summary>
''' <remarks></remarks>
#If DEBUG Then
Public Class DTIBasePage
    Inherits BaseClasses.BaseSecurityPage
#Else
    <ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never), ComponentModel.ToolboxItem(False)> _
    Public Class DTIBasePage
        Inherits BaseClasses.BaseSecurityPage
#End If

        Public Enum modes
            Read = 1
            Write = 2
        End Enum

        Public MyMediaRow As dsMedia.DTIMediaManagerRow
        Protected tagTable As New DTITagManager.dsTagger.DTI_Content_TagsDataTable
        Public Event ModeChanged()
        Public Event LoadControls(ByVal modeChanged As Boolean)
        Protected Event DataChanged()

#Region "Properties"

        Public Shared ReadOnly Property siteEditOnDefaultKey() As String
            Get
                Return DTISharedVariables.siteEditOnDefaultKey
            End Get
        End Property

        Public Shared ReadOnly Property siteEditMainID() As String
            Get
                Return DTISharedVariables.siteEditMainID
            End Get
        End Property

        Public Shared ReadOnly Property siteLanguageID() As String
            Get
                Return DTISharedVariables.siteLanguageID
            End Get
        End Property

        Private _MainID As Long = 0
        Public Property MainID() As Long
            Get
                If MasterMainId >= 0 Then
                    Return MasterMainId
                Else
                    'language id is bit shifted to the top 10 bits and then ORed into the mainid
                    Dim shifted_language_id As Long = LanguageID * Math.Pow(2, 55)
                    Return shifted_language_id Or _MainID
                End If
            End Get
            Set(ByVal value As Long)
                Dim oldMain = _MainID
                _MainID = value
                If oldMain <> _MainID Then
                    RaiseEvent DataChanged()
                End If
            End Set
        End Property

        Public Overridable Property MasterMainId() As Long
            Get
                Return DTISharedVariables.MasterMainId
            End Get
            Set(ByVal value As Long)
                Dim oldMainId = DTISharedVariables.MasterMainId
                DTISharedVariables.MasterMainId = value
                If oldMainId <> value Then
                    RaiseEvent DataChanged()
                End If
            End Set
        End Property

        Private _LanguageID As Integer = 0
        Public Property LanguageID() As Integer
            Get
                If MasterLanguageId >= 0 Then
                    Return MasterLanguageId
                Else
                    Return _LanguageID
                End If
            End Get
            Set(ByVal value As Integer)
                Dim oldLanguage = _LanguageID
                _LanguageID = value
                If oldLanguage <> _LanguageID Then
                    RaiseEvent DataChanged()
                End If
            End Set
        End Property

        Public Overridable Property MasterLanguageId() As Integer
            Get
                Return DTISharedVariables.MasterLanguageId
            End Get
            Set(ByVal value As Integer)
                Dim oldMasterLangId = DTISharedVariables.MasterLanguageId
                DTISharedVariables.MasterLanguageId = value
                If oldMasterLangId <> value Then
                    RaiseEvent DataChanged()
                End If
            End Set
        End Property

        Private _staticMode As Boolean = False
        Public Property StaticMode() As Boolean
            Get
                Return _staticMode
            End Get
            Set(ByVal value As Boolean)
                _staticMode = value
            End Set
        End Property

        Public Overridable Property AdminOn() As Boolean
            Get
                Return DTISharedVariables.AdminOn
            End Get
            Set(ByVal value As Boolean)
                DTISharedVariables.AdminOn = value
            End Set
        End Property

        Public Property Mode() As modes
            Get
                If Session("ContentDisplayMode." & Me.ClientID) Is Nothing Then
                    Session("ContentDisplayMode." & Me.ClientID) = modes.Read
                End If

                If AdminOn AndAlso Session("ContentDisplayMode." & Me.ClientID) = modes.Read Then
                    Session("ContentDisplayMode." & Me.ClientID) = modes.Write
                End If

                If Not AdminOn AndAlso Not StaticMode AndAlso Session("ContentDisplayMode." & Me.ClientID) <> modes.Read Then
                    Session("ContentDisplayMode." & Me.ClientID) = modes.Read
                End If

                Return Session("ContentDisplayMode." & Me.ClientID)
            End Get
            Set(ByVal value As modes)
                Session("ContentDisplayMode." & Me.ClientID) = value
                RaiseEvent ModeChanged()
            End Set
        End Property

        Public Overrides Property Visible() As Boolean
            Get
                If Mode = modes.Read Then
                    Return MyBase.Visible
                Else
                    Return True
                End If
            End Get
            Set(ByVal value As Boolean)
                MyBase.Visible = value
            End Set
        End Property

        Private _ajaxEnabled As Boolean = False
        Public Property AJAXEnabled() As Boolean
            Get
                Return _ajaxEnabled
            End Get
            Set(ByVal value As Boolean)
                _ajaxEnabled = value
            End Set
        End Property

#End Region

#Region "Events"

        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

        End Sub

        'Private Sub Page_InitComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.InitComplete
        '    addscriptmanagerToPage()
        'End Sub

        Private Sub DTIServerControl_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            RaiseEvent LoadControls(False)
        End Sub

        Private Sub DTIServerControl_ModeChanged() Handles Me.ModeChanged
            RaiseEvent LoadControls(True)
        End Sub

        Private Sub Page_PreRender1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
            If MyMediaRow IsNot Nothing Then
                Dim metaData As String = ""

                If Not MyMediaRow.IsTitleNull Then
                    Me.Title = MyMediaRow.Title
                End If

                If Not MyMediaRow.IsDescriptionNull Then
                    metaData &= "<META name=""description"" content="""
                    metaData &= Server.HtmlEncode(MyMediaRow.Description)
                    metaData &= """ />"
                End If

                If tagTable.Count = 0 Then
                    Try
                        sqlHelper.SafeFillTable("select * from DTI_Content_Tags where Id in " & _
                            "(select Tag_Id from DTI_Content_Tag_Pivot where " & _
                            "Component_Type = @compType and Content_Id in (select Id from DTIMediaManager where Content_Id = @pid))", tagTable, _
                            New Object() {MyMediaRow.Component_Type, MyMediaRow.Content_Id})
                    Catch ex As Exception
                        sqlHelper.checkAndCreateTable(tagTable)
                        sqlHelper.checkAndCreateTable(New DTITagManager.dsTagger.DTI_Content_Tag_PivotDataTable)
                        sqlHelper.SafeFillTable("select * from DTI_Content_Tags where Id in " & _
                            "(select Tag_Id from DTI_Content_Tag_Pivot where " & _
                            "Component_Type = @compType and Content_Id = @pid)", tagTable, _
                            New Object() {MyMediaRow.Component_Type, MyMediaRow.Content_Id})
                    End Try

                End If

                If tagTable.Count > 0 Then
                    metaData &= "<META name=""keywords"" content="""
                    For Each tag As DTI_Content_TagsRow In tagTable
                        metaData &= Server.HtmlEncode(tag.Tag_Name) & ","
                    Next
                    metaData = metaData.Trim()
                    metaData = metaData.Trim(",") 'New Char() {","c}
                    metaData &= """ />"
                End If
                If Page.Header Is Nothing Then
                    jQueryLibrary.jQueryInclude.addControlToHeader(Page, New LiteralControl(metaData))
                Else
                    Page.Header.Controls.Add(New LiteralControl(metaData))
                End If
            End If

        End Sub

#End Region

#Region "Helper Function"

        Public Sub moveIt(ByVal sourceSelector As String, ByVal destSelector As String, Optional ByRef pageRef As Page = Nothing)
            If pageRef Is Nothing Then pageRef = Me
            DTISharedVariables.moveIt(sourceSelector, destSelector, pageRef)
        End Sub

        'Public Sub registerClientScriptBlock(ByVal key As String, ByVal script As String, Optional ByVal addScriptTags As Boolean = False, Optional ByRef addPage As Page = Nothing)
        '    ClientScript.RegisterClientScriptBlock(Me.GetType, key, script, addScriptTags)
        'End Sub

        Public Sub registerClientStartupScriptBlock(ByVal key As String, ByVal script As String, Optional ByVal addScriptTags As Boolean = False, Optional ByRef addPage As Page = Nothing)
            ClientScript.RegisterStartupScript(Me.GetType, key, script, addScriptTags)
        End Sub

        Public Sub registerClientScriptFile(ByVal key As String, ByVal URL As String, Optional ByRef addPage As Page = Nothing)
            ClientScript.RegisterClientScriptInclude(Me.GetType, key, URL)
        End Sub

        'Protected Sub addscriptmanagerToPage()
        '    If AJAXEnabled AndAlso ScriptManager.GetCurrent(Me) Is Nothing Then
        '        Form.Controls.AddAt(0, New ScriptManager)
        '    End If
        'End Sub

        Protected Sub raiseDataChanged()
            RaiseEvent DataChanged()
        End Sub

        Protected Function getPageMediaRow(ByVal page_Id As Integer) As dsMedia.DTIMediaManagerRow
            If DTIServerControl.initExternalType(GetType(DTIBasePage)) Then
                Dim dstag As New DTITagManager.dsTagger
                sqlHelper.checkAndCreateTable(dstag.DTI_Content_Tags)
                sqlHelper.checkAndCreateTable(dstag.DTI_Content_Tag_Pivot)
            End If
            Dim mediaRow As DTIMediaManager.dsMedia.DTIMediaManagerRow
            For Each row As DTIMediaManager.dsMedia.DTIMediaManagerRow In SharedMediaVariables.myMediaTable
                If row.Content_Type = "page" AndAlso row.Content_Id = page_Id Then
                    mediaRow = row
                    Exit For
                End If
            Next
            If mediaRow Is Nothing Then
                parallelDataHelper.addFillDataTable("select * from DTI_Content_Tags where Id in " & _
                    "(select Tag_Id from DTI_Content_Tag_Pivot where " & _
                    "Component_Type = 'ContentManagement' and Content_Id in (select Id from DTIMediaManager where Content_Id = @pid))", tagTable, _
                    New Object() {page_Id})
                parallelDataHelper.addFillDataTable("select * from DTIMediaManager where Content_Id = @pid and " & _
                    "Content_Type = 'page'", SharedMediaVariables.myMediaTable, _
                    New Object() {page_Id})

                parallelDataHelper.executeParallelDBCall()

                Dim dv As New DataView(SharedMediaVariables.myMediaTable, "Content_Type = 'page' and Content_Id = " & _
                    page_Id, "", DataViewRowState.CurrentRows)
                If dv.Count > 0 Then
                    mediaRow = dv(0).Row
                End If

                If mediaRow Is Nothing AndAlso page_Id <> -1 Then
                    mediaRow = SharedMediaVariables.myMediaTable.NewDTIMediaManagerRow
                    With mediaRow
                        .Component_Type = "ContentManagement"
                        .Content_Type = "page"
                        .Content_Id = page_Id
                        .Date_Added = Now
                        .Published = True
                        .Removed = False
                        .User_Id = -1 'currentUser.id
                        .Permanent_URL = Request.Url.PathAndQuery
                    End With
                    SharedMediaVariables.myMediaTable.AddDTIMediaManagerRow(mediaRow)
                    sqlHelper.Update(mediaRow.Table)
                End If
            End If

            Return mediaRow
        End Function

#End Region

    End Class