text:
module Fayde.Text.Buffer {
    export function cut (text: string, start: number, len: number): string {
        if (!text)
            return "";
        return text.slice(0, start) + text.slice(start + len);
    }

    export function insert (text: string, index: number, str: string): string {
        if (!text)
            return str;
        return [text.slice(0, index), str, text.slice(index)].join('');
    }

    export function replace (text: string, start: number, len: number, str: string): string {
        if (!text)
            return str;
        return [text.slice(0, start), str, text.slice(start + len)].join('');
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Hancock Zone Motors Show
date: 2016-05-24
author: Debra Morrow
tags: weekly links, java
status: published
summary: Duis pharetra euismod leo a.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 08/29/2017
  endDate: 09/02/2017
  ctyhocn: RDUCLHX
  groupCode: HZMS
published: true
---
Ut consectetur tellus felis, sit amet rutrum purus tempus vel. Pellentesque imperdiet eget ante eu porta. Sed condimentum congue metus sit amet aliquam. Curabitur vitae leo euismod, iaculis nulla sit amet, congue tortor. Donec vitae convallis ligula. Ut consectetur egestas erat eget rutrum. Nullam tristique, mauris eget tempus pulvinar, ipsum tortor euismod nisi, vitae aliquet justo mauris pellentesque erat. Nulla convallis ligula eget sem dignissim eleifend. Proin tempor nisl mauris, eu mollis neque porta vitae. Aliquam ornare eleifend dolor non egestas. Sed hendrerit risus vitae ex maximus, vulputate suscipit lorem convallis. Suspendisse potenti. Cras bibendum odio in tincidunt sagittis.

1 Morbi id libero quis sem commodo rutrum
1 Fusce pellentesque eros vel bibendum vehicula.

Nunc sagittis nibh sed nibh sagittis tempus. Cras ultrices bibendum dolor, sit amet dignissim turpis pharetra vel. Proin eu elit ac nisl pharetra tempus. Morbi lorem leo, mattis sed pellentesque varius, porttitor ac nisi. Fusce vel lobortis sapien. Proin aliquam ligula a libero cursus, quis accumsan nunc sagittis. Vivamus varius lacinia diam, vel scelerisque lacus feugiat nec. Praesent fringilla lacus vel lobortis fermentum. Ut eget fermentum dolor, ut venenatis velit. Proin sagittis faucibus hendrerit.


text:
define([ "lib/text!../../../templates/test_plan_list_html", "../../navigation" ],
		function(testTemplate, navigation) {

	var TestPlanListView = Backbone.View.extend({
		events : {
			"click input[data-tm-role='delete']" : "deletePlan"
		},

		initialize : function() {
			this.model.bind("all", this.render, this);
		},

		render : function() {
			// Compile the template using underscore
			var template = _.template(testTemplate, {
				plans : this.model.models
			});

			// Load the compiled HTML into the Backbone "el"
			this.$el.html(template);

			navigation.highlight(['product','version']);
		},

		deletePlan : function(event) {
			var id = $(event.currentTarget).data("tm-id");
			this.model.get(id).destroy({
				success : function() {
					addMessage("success", "Test plan successfully removed.");
					navigation.buildTestPlanOptions();
				}
			});
		}
	});

	return TestPlanListView;
});


text:
import * as React from 'react';
import * as strings from 'TilesWebPartStrings';
import styles from './Tiles.module.scss';
import { ITileInfo, ITilesProps } from '.';
import { Tile } from './tile';
import { WebPartTitle } from '@pnp/spfx-controls-react/lib/WebPartTitle';
import { Placeholder } from '@pnp/spfx-controls-react/lib/Placeholder';
import { createstyles } from './ThemeVariantTypeStyle.styles';
import { css } from "@uifabric/utilities/lib/css";

export class Tiles extends React.Component<ITilesProps, {}> {

  /**
   * Default React remder method
   */
  public render(): React.ReactElement<ITilesProps> {
    const CustomStyles = createstyles(this.props.themeVariant);

    return (

        <WebPartTitle displayMode={this.props.displayMode}
          title={this.props.title}
          updateProperty={this.props.fUpdateProperty} />

        {
          this.props.collectionData && this.props.collectionData.length > 0 ? (

              {
                this.props.collectionData
                  .sort((a: ITileInfo, b: ITileInfo) =>
                    parseInt(a.sortOrder) > parseInt(b.sortOrder) ?
                      1 : ((parseInt(b.sortOrder) > parseInt(a.sortOrder) ? -1 : 0)))
                  .map((tile, idx) =>
                    <Tile key={idx}
                      item={tile}
                      tileHeight={this.props.tileHeight}
                      tileWidth={this.props.tileWidth}
                      tileColour={this.props.tileColour}
                      tileFont={this.props.tileFont}
                      staticWidth={this.props.staticWidth}
                      colourMode={this.props.colourMode}
                      themeVariant={this.props.themeVariant}
                      ThemeColorsFromWindow={this.props.ThemeColorsFromWindow} />)
              }

          ) : (
            <Placeholder
              iconName='Edit'
              iconText={strings.noTilesIconText}
              description={strings.noTilesConfigured}
              buttonLabel={strings.noTilesBtn}
              onConfigure={this.props.fPropertyPaneOpen} />
          )
        }

    );
  }
}


text:
package unnamed.api;

public interface IResultListener {
    void onSuccess();

    void onFailure();
}


text:
<title>gcloud components</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="project_path" value="/sdk/_project.yaml">
<meta name="book_path" value="/sdk/_book.yaml">

NAME

gcloud components - list, install, update, or remove Google Cloud SDK components or packages

SYNOPSIS

gcloud components   <var>GROUP</var>   |   <var>COMMAND</var>   <nobr>[--format   <var>FORMAT</var>]</nobr>   <nobr>[--help]</nobr>   <nobr>[--project   <var>PROJECT_ID</var>]</nobr>   <nobr>[--quiet,   -q]</nobr>   <nobr>[-h]</nobr>

DESCRIPTION

List, install, update, or remove Google Cloud SDK components or packages.

Because you might need only some of the tools in the Cloud SDK to do
your work, you can control which tools are installed on your
workstation. You can install new tools on your workstation when you
find that you need them, and remove tools that you no longer need.
The gcloud command regularly checks whether updates are available for
the tools you already have installed, and gives you the opportunity
to upgrade to the latest version.

Tools can be installed as individual components or as preconfigured
packages of components that are typically all used together to
perform a particular task (such as developing a PHP application on
App Engine).

Certain components depend on other components. When you install a
component that you need, all components upon which it directly or
indirectly depends, and that are not already present on your
workstation, are installed automatically. When you remove a
component, all components that depend on the removed component are
also removed.

FLAGS

--format <var>FORMAT</var>

Specify a format for printed output. By default, a command-specific
human-friendly output format is used. Setting this flag to one of
the available options will serialize the result of the command in
the chosen format and print it to stdout. Supported formats are:
json, text, yaml.

--help

Display detailed help.

--project <var>PROJECT_ID</var>

The Google Cloud Platform project name to use for this invocation. If
omitted then the current project is assumed.

--quiet, -q

Disable all interactive prompts when running gcloud commands. If input
is required, defaults will be used, or an error will be raised.

-h

Print a summary help and exit.

GROUPS

<var>GROUP</var> is one of the following:

repositories

Manage additional component repositories for Trusted Tester programs.

COMMANDS

<var>COMMAND</var> is one of the following:

list

List the status of all Cloud SDK components.

remove

Remove one or more installed components.

restore

Restore the Cloud SDK installation to its previous state.

update

Update or install one or more Cloud SDK components or packages.

NOTES

This command is in the Google Cloud SDK core component. See
installing components
if it is not installed.


text:
title: Flamelink
repo:
weight: ''
description: A real-time headless CMS for Firebase
date: 2018-07-11 00:00:00 -0400
tools:
- Content Management
interactions: []
license: Commercial
data_model: Database
language: ''
related_tools:
- tool/firebase-realtime-database.md
tags: []
urls:
  website: https://flamelink.io/
  github: https://github.com/flamelink
  twitter: https://twitter.com/flamelinkcms
  other: ''
resources: []

---
Flamelink is a realtime, headless CMS powered by Google's Firebase.

Flamelink offers Coders and Content Managers an easy-to-use interface to add, manage and update content seamlessly integrated with their Firebase project.

This lets Developers do what they do best — write white-hot code, while Content Managers can play around with content to their hearts desire.


text:
import { intlFormat } from 'date-fns/fp'
export default intlFormat


text:
function [a, b] = d2c(phi, gamma, t)
%D2C  Conversion of discrete LTI models to continuous time.
%
%   SYSC = D2C(SYSD,METHOD) produces a continuous-time model SYSC
%   that is equivalent to the discrete-time LTI model SYSD.
%   The string METHOD selects the conversion method among the
%   following:
%      'zoh'       Assumes zero-order hold on the inputs.
%      'tustin'    Bilinear (Tustin) approximation.
%      'prewarp'   Tustin approximation with frequency prewarping.
%                  The critical frequency Wc is specified last as in
%                  D2C(SysD,'prewarp',Wc)
%      'matched'   Matched pole-zero method (for SISO systems only).
%   The default is 'zoh' when METHOD is omitted.
%
%   See also C2D, D2D, LTIMODELS.

%   J.N. Little 4-21-85
%   Copyright (c) 1986-1999 The Mathworks, Inc. All Rights Reserved.
%   $Revision: 1.6 $  $Date: 1999/01/05 12:08:35 $

error(nargchk(3,3,nargin));
[msg,phi,gamma]=abcdchk(phi,gamma); error(msg);

[m,n] = size(phi);
[m,nb] = size(gamma);

% phi = 1 case cannot be computed through matrix logarithm.  Handle
% as a special case.
if m == 1
    if phi == 1
        a = 0; b = gamma/t;
        return
    end
end

% Remove rows in gamma that correspond to all zeros
b = zeros(m,nb);
nz = 0;
nonzero = [];
for i=1:nb
    if any(gamma(:,i)~=0)
        nonzero = [nonzero, i];
        nz = nz + 1;
    end
end

% Do rest of cases using matrix logarithm.

[s, esterr] = logm([[phi gamma(:,nonzero)]; zeros(nz,n) eye(nz)]);
s = s/t;
if max(esterr,norm(imag(s),'inf')) > sqrt(eps);
    warning('Accuracy of d2c conversion may be poor.')
end
s = real(s);
a = s(1:n,1:n);
if length(b)
    b(:,nonzero) = s(1:n,n+1:n+nz);
end


text:
/* Auto-generated by genfincode_stat.sh - DO NOT EDIT! */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define RTPP_FINCODE
#include "rtpp_types.h"
#include "rtpp_debug.h"
#include "rtpp_pcount.h"
#include "rtpp_pcount_fin.h"
static void rtpp_pcount_get_stats_fin(void *pub) {
    fprintf(stderr, "Method rtpp_pcount@%p::get_stats (rtpp_pcount_get_stats) is invoked after destruction\x0a", pub);
    RTPP_AUTOTRAP();
}
static void rtpp_pcount_reg_drop_fin(void *pub) {
    fprintf(stderr, "Method rtpp_pcount@%p::reg_drop (rtpp_pcount_reg_drop) is invoked after destruction\x0a", pub);
    RTPP_AUTOTRAP();
}
static void rtpp_pcount_reg_ignr_fin(void *pub) {
    fprintf(stderr, "Method rtpp_pcount@%p::reg_ignr (rtpp_pcount_reg_ignr) is invoked after destruction\x0a", pub);
    RTPP_AUTOTRAP();
}
static void rtpp_pcount_reg_reld_fin(void *pub) {
    fprintf(stderr, "Method rtpp_pcount@%p::reg_reld (rtpp_pcount_reg_reld) is invoked after destruction\x0a", pub);
    RTPP_AUTOTRAP();
}
static const struct rtpp_pcount_smethods rtpp_pcount_smethods_fin = {
    .get_stats = (rtpp_pcount_get_stats_t)&rtpp_pcount_get_stats_fin,
    .reg_drop = (rtpp_pcount_reg_drop_t)&rtpp_pcount_reg_drop_fin,
    .reg_ignr = (rtpp_pcount_reg_ignr_t)&rtpp_pcount_reg_ignr_fin,
    .reg_reld = (rtpp_pcount_reg_reld_t)&rtpp_pcount_reg_reld_fin,
};
void rtpp_pcount_fin(struct rtpp_pcount *pub) {
    RTPP_DBG_ASSERT(pub->smethods->get_stats != (rtpp_pcount_get_stats_t)NULL);
    RTPP_DBG_ASSERT(pub->smethods->reg_drop != (rtpp_pcount_reg_drop_t)NULL);
    RTPP_DBG_ASSERT(pub->smethods->reg_ignr != (rtpp_pcount_reg_ignr_t)NULL);
    RTPP_DBG_ASSERT(pub->smethods->reg_reld != (rtpp_pcount_reg_reld_t)NULL);
    RTPP_DBG_ASSERT(pub->smethods != &rtpp_pcount_smethods_fin &&
      pub->smethods != NULL);
    pub->smethods = &rtpp_pcount_smethods_fin;
}
#if defined(RTPP_FINTEST)
#include <assert.h>
#include <stddef.h>
#include "rtpp_mallocs.h"
#include "rtpp_refcnt.h"
#include "rtpp_linker_set.h"
#define CALL_TFIN(pub, fn) ((void (*)(typeof(pub)))((pub)->smethods->fn))(pub)

void
rtpp_pcount_fintest()
{
    int naborts_s;

    struct {
        struct rtpp_pcount pub;
    } *tp;

    naborts_s = _naborts;
    tp = rtpp_rzmalloc(sizeof(*tp), offsetof(typeof(*tp), pub.rcnt));
    assert(tp != NULL);
    assert(tp->pub.rcnt != NULL);
    static const struct rtpp_pcount_smethods dummy = {
        .get_stats = (rtpp_pcount_get_stats_t)((void *)0x1),
        .reg_drop = (rtpp_pcount_reg_drop_t)((void *)0x1),
        .reg_ignr = (rtpp_pcount_reg_ignr_t)((void *)0x1),
        .reg_reld = (rtpp_pcount_reg_reld_t)((void *)0x1),
    };
    tp->pub.smethods = &dummy;
    CALL_SMETHOD(tp->pub.rcnt, attach, (rtpp_refcnt_dtor_t)&rtpp_pcount_fin,
      &tp->pub);
    RTPP_OBJ_DECREF(&(tp->pub));
    CALL_TFIN(&tp->pub, get_stats);
    CALL_TFIN(&tp->pub, reg_drop);
    CALL_TFIN(&tp->pub, reg_ignr);
    CALL_TFIN(&tp->pub, reg_reld);
    assert((_naborts - naborts_s) == 4);
    free(tp);
}
const static void *_rtpp_pcount_ftp = (void *)&rtpp_pcount_fintest;
DATA_SET(rtpp_fintests, _rtpp_pcount_ftp);
#endif /* RTPP_FINTEST */


text:
import uuid

import mock
from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_utils import timeutils
import six
import webob

from jacket.api.compute.openstack.compute.legacy_v2 import server_metadata \
        as server_metadata_v2
from jacket.api.compute.openstack.compute import server_metadata \
        as server_metadata_v21
from jacket.compute.cloud import rpcapi as compute_rpcapi
from jacket.compute.cloud import vm_states
import jacket.db.compute
from jacket.compute import exception
from jacket.objects import compute
from jacket.compute import test
from jacket.tests.compute.unit.api.openstack import fakes
from jacket.tests.compute.unit import fake_instance

CONF = cfg.CONF

def return_create_instance_metadata_max(context, server_id, metadata, delete):
    return stub_max_server_metadata()

def return_create_instance_metadata(context, server_id, metadata, delete):
    return stub_server_metadata()

def fake_instance_save(inst, **kwargs):
    inst.metadata = stub_server_metadata()
    inst.obj_reset_changes()

def return_server_metadata(context, server_id):
    if not isinstance(server_id, six.string_types) or not len(server_id) == 36:
        msg = 'id %s must be a uuid in return server metadata' % server_id
        raise Exception(msg)
    return stub_server_metadata()

def return_empty_server_metadata(context, server_id):
    return {}

def delete_server_metadata(context, server_id, key):
    pass

def stub_server_metadata():
    metadata = {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3",
    }
    return metadata

def stub_max_server_metadata():
    metadata = {"metadata": {}}
    for num in range(CONF.quota_metadata_items):
        metadata['metadata']['key%i' % num] = "blah"
    return metadata

def return_server(context, server_id, columns_to_join=None):
    return fake_instance.fake_db_instance(
        **{'id': server_id,
           'uuid': '0cc3346e-9fef-4445-abe6-5d2b2690ec64',
           'name': 'fake',
           'locked': False,
           'launched_at': timeutils.utcnow(),
           'vm_state': vm_states.ACTIVE})

def return_server_by_uuid(context, server_uuid,
                          columns_to_join=None, use_slave=False):
    return fake_instance.fake_db_instance(
        **{'id': 1,
           'uuid': '0cc3346e-9fef-4445-abe6-5d2b2690ec64',
           'name': 'fake',
           'locked': False,
           'launched_at': timeutils.utcnow(),
           'metadata': stub_server_metadata(),
           'vm_state': vm_states.ACTIVE})

def return_server_nonexistent(context, server_id,
        columns_to_join=None, use_slave=False):
    raise exception.InstanceNotFound(instance_id=server_id)

def fake_change_instance_metadata(self, context, instance, diff):
    pass

class ServerMetaDataTestV21(test.TestCase):
    validation_ex = exception.ValidationError
    validation_ex_large = validation_ex

    def setUp(self):
        super(ServerMetaDataTestV21, self).setUp()
        fakes.stub_out_key_pair_funcs(self.stubs)
        self.stub_out('jacket.compute.instance_get', return_server)
        self.stub_out('jacket.compute.instance_get_by_uuid',
                      return_server_by_uuid)

        self.stub_out('jacket.compute.instance_metadata_get',
                      return_server_metadata)

        self.stubs.Set(compute_rpcapi.JacketAPI, 'change_instance_metadata',
                       fake_change_instance_metadata)
        self._set_up_resources()

    def _set_up_resources(self):
        self.controller = server_metadata_v21.ServerMetadataController()
        self.uuid = str(uuid.uuid4())
        self.url = '/fake/servers/%s/metadata' % self.uuid

    def _get_request(self, param_url=''):
        return fakes.HTTPRequestV21.blank(self.url + param_url)

    def test_index(self):
        req = self._get_request()
        res_dict = self.controller.index(req, self.uuid)

        expected = {
            'metadata': {
                'key1': 'value1',
                'key2': 'value2',
                'key3': 'value3',
            },
        }
        self.assertEqual(expected, res_dict)

    def test_index_nonexistent_server(self):
        self.stub_out('jacket.compute.instance_metadata_get',
                       return_server_nonexistent)
        req = self._get_request()
        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.index, req, self.url)

    def test_index_no_data(self):
        self.stub_out('compute.db.instance_metadata_get',
                       return_empty_server_metadata)
        req = self._get_request()
        res_dict = self.controller.index(req, self.uuid)
        expected = {'metadata': {}}
        self.assertEqual(expected, res_dict)

    def test_show(self):
        req = self._get_request('/key2')
        res_dict = self.controller.show(req, self.uuid, 'key2')
        expected = {"meta": {'key2': 'value2'}}
        self.assertEqual(expected, res_dict)

    def test_show_nonexistent_server(self):
        self.stub_out('jacket.compute.instance_metadata_get',
                      return_server_nonexistent)
        req = self._get_request('/key2')
        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.show, req, self.uuid, 'key2')

    def test_show_meta_not_found(self):
        self.stub_out('compute.db.instance_metadata_get',
                      return_empty_server_metadata)
        req = self._get_request('/key6')
        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.show, req, self.uuid, 'key6')

    def test_delete(self):
        self.stub_out('jacket.compute.instance_metadata_get',
                      return_server_metadata)
        self.stub_out('compute.db.instance_metadata_delete',
                      delete_server_metadata)
        req = self._get_request('/key2')
        req.method = 'DELETE'
        res = self.controller.delete(req, self.uuid, 'key2')

        self.assertIsNone(res)

    def test_delete_nonexistent_server(self):
        self.stub_out('compute.db.instance_get_by_uuid',
                      return_server_nonexistent)
        req = self._get_request('/key1')
        req.method = 'DELETE'
        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.delete, req, self.uuid, 'key1')

    def test_delete_meta_not_found(self):
        self.stub_out('jacket.compute.instance_metadata_get',
                      return_empty_server_metadata)
        req = self._get_request('/key6')
        req.method = 'DELETE'
        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.delete, req, self.uuid, 'key6')

    def test_create(self):
        self.stubs.Set(compute.Instance, 'save', fake_instance_save)
        req = self._get_request()
        req.method = 'POST'
        req.content_type = "application/json"
        body = {"metadata": {"key9": "value9"}}
        req.body = jsonutils.dump_as_bytes(body)
        res_dict = self.controller.create(req, self.uuid, body=body)

        body['metadata'].update({
            "key1": "value1",
            "key2": "value2",
            "key3": "value3",
        })
        self.assertEqual(body, res_dict)

    def test_create_empty_body(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request()
        req.method = 'POST'
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.create, req, self.uuid, body=None)

    def test_create_item_empty_key(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/key1')
        req.method = 'PUT'
        body = {"metadata": {"": "value1"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.create, req, self.uuid, body=body)

    def test_create_item_non_dict(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/key1')
        req.method = 'PUT'
        body = {"metadata": None}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.create, req, self.uuid, body=body)

    def test_create_item_key_too_long(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/key1')
        req.method = 'PUT'
        body = {"metadata": {("a" * 260): "value1"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex_large,
                          self.controller.create,
                          req, self.uuid, body=body)

    def test_create_malformed_container(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = fakes.HTTPRequest.blank(self.url + '/key1')
        req.method = 'PUT'
        body = {"meta": {}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.create, req, self.uuid, body=body)

    def test_create_malformed_data(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = fakes.HTTPRequest.blank(self.url + '/key1')
        req.method = 'PUT'
        body = {"metadata": ['asdf']}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.create, req, self.uuid, body=body)

    def test_create_nonexistent_server(self):
        self.stub_out('jacket.compute.instance_get_by_uuid',
                      return_server_nonexistent)
        req = self._get_request()
        req.method = 'POST'
        body = {"metadata": {"key1": "value1"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.create, req, self.uuid, body=body)

    def test_update_metadata(self):
        self.stubs.Set(compute.Instance, 'save', fake_instance_save)
        req = self._get_request()
        req.method = 'POST'
        req.content_type = 'application/json'
        expected = {
            'metadata': {
                'key1': 'updatedvalue',
                'key29': 'newkey',
            }
        }
        req.body = jsonutils.dump_as_bytes(expected)
        response = self.controller.update_all(req, self.uuid, body=expected)
        self.assertEqual(expected, response)

    def test_update_all(self):
        self.stubs.Set(compute.Instance, 'save', fake_instance_save)
        req = self._get_request()
        req.method = 'PUT'
        req.content_type = "application/json"
        expected = {
            'metadata': {
                'key10': 'value10',
                'key99': 'value99',
            },
        }
        req.body = jsonutils.dump_as_bytes(expected)
        res_dict = self.controller.update_all(req, self.uuid, body=expected)

        self.assertEqual(expected, res_dict)

    def test_update_all_empty_container(self):
        self.stubs.Set(compute.Instance, 'save', fake_instance_save)
        req = self._get_request()
        req.method = 'PUT'
        req.content_type = "application/json"
        expected = {'metadata': {}}
        req.body = jsonutils.dump_as_bytes(expected)
        res_dict = self.controller.update_all(req, self.uuid, body=expected)

        self.assertEqual(expected, res_dict)

    def test_update_all_empty_body_item(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = fakes.HTTPRequest.blank(self.url + '/key1')
        req.method = 'PUT'
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.update_all, req, self.uuid,
                          body=None)

    def test_update_all_with_non_dict_item(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = fakes.HTTPRequest.blank(self.url + '/bad')
        req.method = 'PUT'
        body = {"metadata": None}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.update_all, req, self.uuid,
                          body=body)

    def test_update_all_malformed_container(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request()
        req.method = 'PUT'
        req.content_type = "application/json"
        expected = {'meta': {}}
        req.body = jsonutils.dump_as_bytes(expected)

        self.assertRaises(self.validation_ex,
                          self.controller.update_all, req, self.uuid,
                          body=expected)

    def test_update_all_malformed_data(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request()
        req.method = 'PUT'
        req.content_type = "application/json"
        expected = {'metadata': ['asdf']}
        req.body = jsonutils.dump_as_bytes(expected)

        self.assertRaises(self.validation_ex,
                          self.controller.update_all, req, self.uuid,
                          body=expected)

    def test_update_all_nonexistent_server(self):
        self.stub_out('compute.db.instance_get', return_server_nonexistent)
        req = self._get_request()
        req.method = 'PUT'
        req.content_type = "application/json"
        body = {'metadata': {'key10': 'value10'}}
        req.body = jsonutils.dump_as_bytes(body)

        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.update_all, req, '100', body=body)

    def test_update_all_non_dict(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request()
        req.method = 'PUT'
        body = {"metadata": None}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex, self.controller.update_all,
                          req, self.uuid, body=body)

    def test_update_item(self):
        self.stubs.Set(compute.Instance, 'save', fake_instance_save)
        req = self._get_request('/key1')
        req.method = 'PUT'
        body = {"meta": {"key1": "value1"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"
        res_dict = self.controller.update(req, self.uuid, 'key1', body=body)
        expected = {"meta": {'key1': 'value1'}}
        self.assertEqual(expected, res_dict)

    def test_update_item_nonexistent_server(self):
        self.stub_out('jacket.compute.instance_get_by_uuid',
                      return_server_nonexistent)
        req = self._get_request('/key1')
        req.method = 'PUT'
        body = {"meta": {"key1": "value1"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.update, req, self.uuid, 'key1',
                          body=body)

    def test_update_item_empty_body(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/key1')
        req.method = 'PUT'
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.update, req, self.uuid, 'key1',
                          body=None)

    def test_update_malformed_container(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = fakes.HTTPRequest.blank(self.url)
        req.method = 'PUT'
        expected = {'meta': {}}
        req.body = jsonutils.dump_as_bytes(expected)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.update, req, self.uuid, 'key1',
                          body=expected)

    def test_update_malformed_data(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = fakes.HTTPRequest.blank(self.url)
        req.method = 'PUT'
        expected = {'metadata': ['asdf']}
        req.body = jsonutils.dump_as_bytes(expected)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.update, req, self.uuid, 'key1',
                          body=expected)

    def test_update_item_empty_key(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/key1')
        req.method = 'PUT'
        body = {"meta": {"": "value1"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.update, req, self.uuid, '',
                          body=body)

    def test_update_item_key_too_long(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/key1')
        req.method = 'PUT'
        body = {"meta": {("a" * 260): "value1"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex_large,
                          self.controller.update,
                          req, self.uuid, ("a" * 260), body=body)

    def test_update_item_value_too_long(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/key1')
        req.method = 'PUT'
        body = {"meta": {"key1": ("a" * 260)}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex_large,
                          self.controller.update,
                          req, self.uuid, "key1", body=body)

    def test_update_item_too_many_keys(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/key1')
        req.method = 'PUT'
        body = {"meta": {"key1": "value1", "key2": "value2"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.update, req, self.uuid, 'key1',
                          body=body)

    def test_update_item_body_uri_mismatch(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/bad')
        req.method = 'PUT'
        body = {"meta": {"key1": "value1"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.update, req, self.uuid, 'bad',
                          body=body)

    def test_update_item_non_dict(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request('/bad')
        req.method = 'PUT'
        body = {"meta": None}
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.update, req, self.uuid, 'bad',
                          body=body)

    def test_update_empty_container(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        req = fakes.HTTPRequest.blank(self.url)
        req.method = 'PUT'
        expected = {'metadata': {}}
        req.body = jsonutils.dump_as_bytes(expected)
        req.headers["content-type"] = "application/json"

        self.assertRaises(self.validation_ex,
                          self.controller.update, req, self.uuid, 'bad',
                          body=expected)

    def test_too_many_metadata_items_on_create(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        data = {"metadata": {}}
        for num in range(CONF.quota_metadata_items + 1):
            data['metadata']['key%i' % num] = "blah"
        req = self._get_request()
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes(data)
        req.headers["content-type"] = "application/json"

        self.assertRaises(webob.exc.HTTPForbidden,
                          self.controller.create, req, self.uuid, body=data)

    def test_invalid_metadata_items_on_create(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request()
        req.method = 'POST'
        req.headers["content-type"] = "application/json"

        # test for long key
        data = {"metadata": {"a" * 260: "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(self.validation_ex_large,
                          self.controller.create, req, self.uuid, body=data)

        # test for long value
        data = {"metadata": {"key": "v" * 260}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(self.validation_ex_large,
                          self.controller.create, req, self.uuid, body=data)

        # test for empty key.
        data = {"metadata": {"": "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(self.validation_ex,
                          self.controller.create, req, self.uuid, body=data)

    def test_too_many_metadata_items_on_update_item(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        data = {"metadata": {}}
        for num in range(CONF.quota_metadata_items + 1):
            data['metadata']['key%i' % num] = "blah"
        req = self._get_request()
        req.method = 'PUT'
        req.body = jsonutils.dump_as_bytes(data)
        req.headers["content-type"] = "application/json"

        self.assertRaises(webob.exc.HTTPForbidden, self.controller.update_all,
                          req, self.uuid, body=data)

    def test_invalid_metadata_items_on_update_item(self):
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        self.stub_out('jacket.compute.instance_metadata_update',
                      return_create_instance_metadata)
        data = {"metadata": {}}
        for num in range(CONF.quota_metadata_items + 1):
            data['metadata']['key%i' % num] = "blah"
        req = self._get_request()
        req.method = 'PUT'
        req.body = jsonutils.dump_as_bytes(data)
        req.headers["content-type"] = "application/json"

        # test for long key
        data = {"metadata": {"a" * 260: "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(self.validation_ex_large,
                          self.controller.update_all, req, self.uuid,
                          body=data)

        # test for long value
        data = {"metadata": {"key": "v" * 260}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(self.validation_ex_large,
                          self.controller.update_all, req, self.uuid,
                          body=data)

        # test for empty key.
        data = {"metadata": {"": "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(self.validation_ex,
                          self.controller.update_all, req, self.uuid,
                          body=data)

class ServerMetaDataTestV2(ServerMetaDataTestV21):
    validation_ex = webob.exc.HTTPBadRequest
    validation_ex_large = webob.exc.HTTPRequestEntityTooLarge

    def _set_up_resources(self):
        self.controller = server_metadata_v2.Controller()
        self.uuid = str(uuid.uuid4())
        self.url = '/v1.1/fake/servers/%s/metadata' % self.uuid

    def _get_request(self, param_url=''):
        return fakes.HTTPRequest.blank(self.url + param_url)

class BadStateServerMetaDataTestV21(test.TestCase):

    def setUp(self):
        super(BadStateServerMetaDataTestV21, self).setUp()
        fakes.stub_out_key_pair_funcs(self.stubs)
        self.stub_out('jacket.compute.instance_metadata_get',
                      return_server_metadata)
        self.stubs.Set(compute_rpcapi.JacketAPI, 'change_instance_metadata',
                       fake_change_instance_metadata)
        self.stub_out('jacket.compute.instance_get', self._return_server_in_build)
        self.stub_out('compute.db.instance_get_by_uuid',
                      self._return_server_in_build_by_uuid)
        self.stub_out('compute.db.instance_metadata_delete',
                      delete_server_metadata)
        self._set_up_resources()

    def _set_up_resources(self):
        self.controller = server_metadata_v21.ServerMetadataController()
        self.uuid = str(uuid.uuid4())
        self.url = '/fake/servers/%s/metadata' % self.uuid

    def _get_request(self, param_url=''):
        return fakes.HTTPRequestV21.blank(self.url + param_url)

    def test_invalid_state_on_delete(self):
        req = self._get_request('/key2')
        req.method = 'DELETE'
        self.assertRaises(webob.exc.HTTPConflict, self.controller.delete,
                          req, self.uuid, 'key2')

    def test_invalid_state_on_update_metadata(self):
        self.stub_out('compute.db.instance_metadata_update',
                      return_create_instance_metadata)
        req = self._get_request()
        req.method = 'POST'
        req.content_type = 'application/json'
        expected = {
            'metadata': {
                'key1': 'updatedvalue',
                'key29': 'newkey',
            }
        }
        req.body = jsonutils.dump_as_bytes(expected)
        self.assertRaises(webob.exc.HTTPConflict, self.controller.update_all,
                req, self.uuid, body=expected)

    def _return_server_in_build(self, context, server_id,
                                columns_to_join=None):
        return fake_instance.fake_db_instance(
            **{'id': server_id,
               'uuid': '0cc3346e-9fef-4445-abe6-5d2b2690ec64',
               'name': 'fake',
               'locked': False,
               'vm_state': vm_states.BUILDING})

    def _return_server_in_build_by_uuid(self, context, server_uuid,
                                        columns_to_join=None, use_slave=False):
        return fake_instance.fake_db_instance(
            **{'id': 1,
               'uuid': '0cc3346e-9fef-4445-abe6-5d2b2690ec64',
               'name': 'fake',
               'locked': False,
               'vm_state': vm_states.BUILDING})

    @mock.patch.object(jacket.compute.compute.api.API, 'update_instance_metadata',
                       side_effect=exception.InstanceIsLocked(instance_uuid=0))
    def test_instance_lock_update_metadata(self, mock_update):
        req = self._get_request()
        req.method = 'POST'
        req.content_type = 'application/json'
        expected = {
            'metadata': {
                'keydummy': 'newkey',
            }
        }
        req.body = jsonutils.dump_as_bytes(expected)
        self.assertRaises(webob.exc.HTTPConflict, self.controller.update_all,
                req, self.uuid, body=expected)

class BadStateServerMetaDataTestV2(BadStateServerMetaDataTestV21):
    def _set_up_resources(self):
        self.controller = server_metadata_v2.Controller()
        self.uuid = str(uuid.uuid4())
        self.url = '/v1.1/fake/servers/%s/metadata' % self.uuid

    def _get_request(self, param_url=''):
        return fakes.HTTPRequest.blank(self.url + param_url)

class ServerMetaPolicyEnforcementV21(test.NoDBTestCase):

    def setUp(self):
        super(ServerMetaPolicyEnforcementV21, self).setUp()
        self.controller = server_metadata_v21.ServerMetadataController()
        self.req = fakes.HTTPRequest.blank('')

    def test_create_policy_failed(self):
        rule_name = "os_compute_api:server-metadata:create"
        self.policy.set_rules({rule_name: "project:non_fake"})
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller.create, self.req, fakes.FAKE_UUID,
            body={'metadata': {}})
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())

    def test_index_policy_failed(self):
        rule_name = "os_compute_api:server-metadata:index"
        self.policy.set_rules({rule_name: "project:non_fake"})
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller.index, self.req, fakes.FAKE_UUID)
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())

    def test_update_policy_failed(self):
        rule_name = "os_compute_api:server-metadata:update"
        self.policy.set_rules({rule_name: "project:non_fake"})
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller.update, self.req, fakes.FAKE_UUID, fakes.FAKE_UUID,
            body={'meta': {'fake_meta': 'fake_meta'}})
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())

    def test_update_all_policy_failed(self):
        rule_name = "os_compute_api:server-metadata:update_all"
        self.policy.set_rules({rule_name: "project:non_fake"})
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller.update_all, self.req, fakes.FAKE_UUID,
            body={'metadata': {}})
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())

    def test_delete_policy_failed(self):
        rule_name = "os_compute_api:server-metadata:delete"
        self.policy.set_rules({rule_name: "project:non_fake"})
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller.delete, self.req, fakes.FAKE_UUID, fakes.FAKE_UUID)
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())

    def test_show_policy_failed(self):
        rule_name = "os_compute_api:server-metadata:show"
        self.policy.set_rules({rule_name: "project:non_fake"})
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller.show, self.req, fakes.FAKE_UUID, fakes.FAKE_UUID)
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())


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

namespace CAT.Model.ExternalInterface.JSONMessages
{
    /// <summary>
    /// This is an Execution Report came from Broker
    /// </summary>
    [DataContract]
    public class ExecutionReport : Command
    {
        /// <summary>
        /// The name of this class (action)
        /// </summary>
        public const string CLASSNAME = "ExecutionReport";

        /// <summary>
        /// Buy side constant
        /// </summary>
        public const string SIDE_BUY = "Buy";
        /// <summary>
        /// Sell side constant
        /// </summary>
        public const string SIDE_SELL = "Sell";

        /// <summary>
        /// Order Type - Limited constant
        /// </summary>
        public const string OT_LIMIT = "Limit";
        /// <summary>
        ///  Order Type - Stop Limit constant
        /// </summary>
        public const string OT_STOP_LIMIT = "Stop";
        /// <summary>
        ///  Order Type - Stop Gain Loss constant
        /// </summary>
        public const string OT_STOP_GAIN_LOSS = "Stop Gain Loss";

        /// <summary>
        /// Validity type - Dated constant
        /// </summary>
        public const string VAL_DATED = "Dated";
        /// <summary>
        /// Validity type - Today constant
        /// </summary>
        public const string VAL_TODAY = "Today";
        /// <summary>
        /// Validity type - Until Cancel constant
        /// </summary>
        public const string VAL_UNTIL_CANCEL = "Until Cancel";

        /// <summary>
        /// Order Status - Processed constant
        /// </summary>
        public const string OS_PROCESSED = "Processed";
        /// <summary>
        /// Order Status - New constant
        /// </summary>
        public const string OS_NEW = "New";
        /// <summary>
        /// Order Status - Canceled constant
        /// </summary>
        public const string OS_CANCELED = "Canceled";
        /// <summary>
        /// Order Status - Pending Order constant
        /// </summary>
        public const string OS_PENDING = "Pendente";
        /// <summary>
        /// Order Status - Partially Filled constant
        /// </summary>
        public const string OS_PARTIALLY_FILLED = "Partially Filled";
        /// <summary>
        /// Order Status - Filled constant
        /// </summary>
        public const string OS_FILLED = "Filled";
        /// <summary>
        /// Order Status - Rejected constant
        /// </summary>
        public const string OS_REJECTED = "Rejected";

        /// <summary>
        /// The order ID
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public string orderId;

        /// <summary>
        /// Security Symbol
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public string symbol;

        /// <summary>
        /// Security Description
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public string securityDesc;

        /// <summary>
        /// The side of this order - Buy or Sell
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public string side;

        /// <summary>
        /// Order Quantity
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public int qtty;

        /// <summary>
        /// Order Type.
        /// </summary>
        [DataMember(IsRequired = true, EmitDefaultValue = true)]
        public string orderType = "";

        /// <summary>
        /// Limit Price
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public decimal price;

        /// <summary>
        /// Limit Price of Stop Loss
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public decimal limitLossPrice;

        /// <summary>
        /// Trigger Price of Stop Loss
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public decimal triggerLossPrice;

        /// <summary>
        /// Limit Price of Stop Gain
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public decimal limitGainPrice;

        /// <summary>
        /// Trigger Price of Stop Gain
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public decimal triggerGainPrice;

        /// <summary>
        /// Order Validity
        /// </summary>
        [DataMember(IsRequired = true, EmitDefaultValue = true)]
        public string validity = "";

        /// <summary>
        /// Order Validity Data
        /// </summary>
        [DataMember(IsRequired = true, EmitDefaultValue = true)]
        public string validityDate = "";

        /// <summary>
        /// Order Status
        /// </summary>
        [DataMember(IsRequired = true, EmitDefaultValue = true)]
        public string orderStatus = "";

        /// <summary>
        /// Date and Time of the Order Creation
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public string creationDateTime;

        /// <summary>
        /// Date and Time of the last Transaction
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public string transactionDateTime;

        /// <summary>
        /// Quantity still pending
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public int pendingQtty;

        /// <summary>
        /// Quantity already executed
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public int cumQtty;

        /// <summary>
        /// Average Price of this Execution
        /// </summary>
        [DataMember(IsRequired = false, EmitDefaultValue = false)]
        public decimal averagePrice;

        /// <summary>
        /// The Identification created locally by client
        /// </summary>
        public string clientOrderID = "";

        public new string Serialize()
        {
            string s = JSONSerializer.Serialize<ExecutionReport>(this);
            return s.Replace("\\/", "/");
        }

        public new static ExecutionReport Deserialize(string serialized)
        {
            return JSONSerializer.Deserialize<ExecutionReport>(serialized);
        }

        public override string ToString()
        {
            return this.Serialize();
        }

    }
}


text:
package armmaintenance

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// ConfigurationsClient contains the methods for the MaintenanceConfigurations group.
// Don't use this type directly, use NewConfigurationsClient() instead.
type ConfigurationsClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewConfigurationsClient creates a new instance of ConfigurationsClient with the specified values.
// subscriptionID - Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ConfigurationsClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &ConfigurationsClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// CreateOrUpdate - Create or Update configuration record
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-09-01-preview
// resourceGroupName - Resource Group Name
// resourceName - Maintenance Configuration Name
// configuration - The configuration
// options - ConfigurationsClientCreateOrUpdateOptions contains the optional parameters for the ConfigurationsClient.CreateOrUpdate
// method.
func (client *ConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, configuration Configuration, options *ConfigurationsClientCreateOrUpdateOptions) (ConfigurationsClientCreateOrUpdateResponse, error) {
	req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, resourceName, configuration, options)
	if err != nil {
		return ConfigurationsClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ConfigurationsClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ConfigurationsClientCreateOrUpdateResponse{}, runtime.NewResponseError(resp)
	}
	return client.createOrUpdateHandleResponse(resp)
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *ConfigurationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, configuration Configuration, options *ConfigurationsClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Maintenance/maintenanceConfigurations/{resourceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, configuration)
}

// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *ConfigurationsClient) createOrUpdateHandleResponse(resp *http.Response) (ConfigurationsClientCreateOrUpdateResponse, error) {
	result := ConfigurationsClientCreateOrUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Configuration); err != nil {
		return ConfigurationsClientCreateOrUpdateResponse{}, err
	}
	return result, nil
}

// Delete - Delete Configuration record
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-09-01-preview
// resourceGroupName - Resource Group Name
// resourceName - Maintenance Configuration Name
// options - ConfigurationsClientDeleteOptions contains the optional parameters for the ConfigurationsClient.Delete method.
func (client *ConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, resourceName string, options *ConfigurationsClientDeleteOptions) (ConfigurationsClientDeleteResponse, error) {
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, resourceName, options)
	if err != nil {
		return ConfigurationsClientDeleteResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ConfigurationsClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) {
		return ConfigurationsClientDeleteResponse{}, runtime.NewResponseError(resp)
	}
	return client.deleteHandleResponse(resp)
}

// deleteCreateRequest creates the Delete request.
func (client *ConfigurationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, options *ConfigurationsClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Maintenance/maintenanceConfigurations/{resourceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// deleteHandleResponse handles the Delete response.
func (client *ConfigurationsClient) deleteHandleResponse(resp *http.Response) (ConfigurationsClientDeleteResponse, error) {
	result := ConfigurationsClientDeleteResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Configuration); err != nil {
		return ConfigurationsClientDeleteResponse{}, err
	}
	return result, nil
}

// Get - Get Configuration record
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-09-01-preview
// resourceGroupName - Resource Group Name
// resourceName - Maintenance Configuration Name
// options - ConfigurationsClientGetOptions contains the optional parameters for the ConfigurationsClient.Get method.
func (client *ConfigurationsClient) Get(ctx context.Context, resourceGroupName string, resourceName string, options *ConfigurationsClientGetOptions) (ConfigurationsClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, resourceName, options)
	if err != nil {
		return ConfigurationsClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ConfigurationsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ConfigurationsClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *ConfigurationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, options *ConfigurationsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Maintenance/maintenanceConfigurations/{resourceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *ConfigurationsClient) getHandleResponse(resp *http.Response) (ConfigurationsClientGetResponse, error) {
	result := ConfigurationsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Configuration); err != nil {
		return ConfigurationsClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - Get Configuration records within a subscription
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-09-01-preview
// options - ConfigurationsClientListOptions contains the optional parameters for the ConfigurationsClient.List method.
func (client *ConfigurationsClient) NewListPager(options *ConfigurationsClientListOptions) *runtime.Pager[ConfigurationsClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[ConfigurationsClientListResponse]{
		More: func(page ConfigurationsClientListResponse) bool {
			return false
		},
		Fetcher: func(ctx context.Context, page *ConfigurationsClientListResponse) (ConfigurationsClientListResponse, error) {
			req, err := client.listCreateRequest(ctx, options)
			if err != nil {
				return ConfigurationsClientListResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return ConfigurationsClientListResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return ConfigurationsClientListResponse{}, runtime.NewResponseError(resp)
			}
			return client.listHandleResponse(resp)
		},
	})
}

// listCreateRequest creates the List request.
func (client *ConfigurationsClient) listCreateRequest(ctx context.Context, options *ConfigurationsClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Maintenance/maintenanceConfigurations"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *ConfigurationsClient) listHandleResponse(resp *http.Response) (ConfigurationsClientListResponse, error) {
	result := ConfigurationsClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ListMaintenanceConfigurationsResult); err != nil {
		return ConfigurationsClientListResponse{}, err
	}
	return result, nil
}

// Update - Patch configuration record
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-09-01-preview
// resourceGroupName - Resource Group Name
// resourceName - Maintenance Configuration Name
// configuration - The configuration
// options - ConfigurationsClientUpdateOptions contains the optional parameters for the ConfigurationsClient.Update method.
func (client *ConfigurationsClient) Update(ctx context.Context, resourceGroupName string, resourceName string, configuration Configuration, options *ConfigurationsClientUpdateOptions) (ConfigurationsClientUpdateResponse, error) {
	req, err := client.updateCreateRequest(ctx, resourceGroupName, resourceName, configuration, options)
	if err != nil {
		return ConfigurationsClientUpdateResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ConfigurationsClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ConfigurationsClientUpdateResponse{}, runtime.NewResponseError(resp)
	}
	return client.updateHandleResponse(resp)
}

// updateCreateRequest creates the Update request.
func (client *ConfigurationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, configuration Configuration, options *ConfigurationsClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Maintenance/maintenanceConfigurations/{resourceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, configuration)
}

// updateHandleResponse handles the Update response.
func (client *ConfigurationsClient) updateHandleResponse(resp *http.Response) (ConfigurationsClientUpdateResponse, error) {
	result := ConfigurationsClientUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Configuration); err != nil {
		return ConfigurationsClientUpdateResponse{}, err
	}
	return result, nil
}


text:
// we want to test the built aerospike module
var aerospike = require('../build/Release/aerospike');
var options = require('./util/options');
var assert = require('assert');
var expect = require('expect.js');

var keygen = require('./generators/key');
var metagen = require('./generators/metadata');
var recgen = require('./generators/record');
var putgen = require('./generators/put');
var valgen = require('./generators/value');

var status = aerospike.status;
var policy = aerospike.policy;

describe('client.exists()', function() {

    var config = options.getConfig();
    var client = aerospike.client(config);

    before(function(done) {
        client.connect(function(err){
            done();
        });
    });

    after(function(done) {
        client.close();
        client = null;
        done();
    });

    it('should find the record', function(done) {

        // generators
        var kgen = keygen.string(options.namespace, options.set, {prefix: "test/exists/"});
        var mgen = metagen.constant({ttl: 1000});
        var rgen = recgen.record({i: valgen.integer(), s: valgen.string(), b: valgen.bytes()});

        // values
        var key     = kgen();
        var meta    = mgen(key);
        var record  = rgen(key,meta);

        // write the record then check
        client.put(key, record, meta, function(err, key) {
            client.exists(key, function(err, metadata, key) {
                expect(err).to.be.ok();
                expect(err.code).to.equal(status.AEROSPIKE_OK);
                client.remove(key, function(err, key){
                    done();
                });
            });
        });
    });

    it('should not find the record', function(done) {

        // generators
        var kgen = keygen.string(options.namespace, options.set, {prefix: "test/exists/fail/"});

        // values
        var key = kgen();

        // write the record then check
        client.exists(key, function(err, metadata, key) {
            expect(err).to.be.ok();
            if(err.code != 602) {
                expect(err.code).to.equal(status.AEROSPIKE_ERR_RECORD_NOT_FOUND);
            }
            else {
                expect(err.code).to.equal(602);
            }
            done();
        });
    });

});


text:
package org.juz.seed.base.security;

import org.juz.common.command.CommandHandler;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class UserCrudHandler implements CommandHandler<UserCrudCommand, Long> {

	private UserRepository userRepository;

	private RoleRepository roleRepository;

	public UserCrudHandler(UserRepository userRepository, RoleRepository roleRepository) {
		this.userRepository = userRepository;
		this.roleRepository = roleRepository;
	}

	@Override
	public Long execute(UserCrudCommand command) {
		switch (command.getOperation()) {
			case CREATE:
				return doCreate(command);
			case UPDATE:
				return doUpdate(command);
			case DELETE:
				return doDelete(command);
			default:
				throw new UnsupportedOperationException("Unknown operation: " + command.getOperation());
		}
	}

	private Long doCreate(UserCrudCommand command) {
		User user = new User();
		user.setUsername(command.getUsername());
		Role role = loadRequiredRole(command.getRoleName());
		user.setRole(role);
		userRepository.save(user);
		return user.getId();
	}

	private Long doUpdate(UserCrudCommand command) {
		User user = loadRequiredUser(command);
		user.setUsername(command.getUsername());
		Role role = loadRequiredRole(command.getRoleName());
		user.setRole(role);
		return user.getId();
	}

	private User loadRequiredUser(UserCrudCommand command) {
		return userRepository.findOne(command.getId())
				.orElseThrow(() -> new IllegalArgumentException("Can't find user: " + command.getId()));
	}

	private Role loadRequiredRole(String roleName) {
		return roleRepository.findByName(roleName)
				.orElseThrow(() -> new IllegalArgumentException("Can't find role: " + roleName));
	}

	private Long doDelete(UserCrudCommand command) {
		User user = loadRequiredUser(command);
		userRepository.delete(user);
		return user.getId();
	}
}


text:
			<?php echo_h($lightbox_library_label)?>

			<select name="lightbox_library_id" id="lightbox_library">
				<?php foreach ($libs as $lib) { ?>
                    <option value="<?php echo esc_attr($lib->$id_field)?>"
                            <?php selected($lib->name, $selected, TRUE)?>
                            data-library-name='<?php echo $lib->name; ?>'>
                        <?php if (isset($lib->title) && $lib->title) { ?>
                            <?php echo_h($lib->title) ?>
                        <?php } else { ?>
                            <?php echo_h($lib->name) ?>
                        <?php } ?>
                    </option>
				<?php } ?>
			</select>

    <?php foreach ($sub_fields as $name => $form) { ?>
        <tbody class="lightbox_library_settings hidden" id="lightbox_library_<?php print $name; ?>">
            <?php echo $form; ?>

    <?php } ?>

			<a href="#"
			   id="lightbox_library_advanced_toggle"
			   data-hidden_label="<?php echo esc_attr(_('(Show Advanced Settings)'))?>"
			   data-active_label="<?php echo esc_attr(_('(Hide Advanced Settings)'))?>"
               data-currently-hidden='true'>
                <?php echo_h(_("(Show Advanced Settings)"))?>

    <?php foreach ($adv_fields as $name => $form) { ?>
        <tbody class="lightbox_library_advanced_settings hidden" id="lightbox_library_<?php print $name; ?>_advanced">
            <?php echo $form; ?>

    <?php } ?>


text:
//
// $Id: shared_defs.cpp 196 2012-09-13 14:36:33Z dasari $
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The Original Code is the Bumbershoot core library.
//
// The Initial Developer of the Original Code is Matt Chambers.
//
// Copyright 2009 Vanderbilt University
//
// Contributor(s): Surendra Dasari
//

// Globals defined for common usage

#include "stdafx.h"
#include "shared_defs.h"
#include "shared_funcs.h"

using namespace freicore;

namespace freicore
{
	fileList_t			g_inputFilenames;
	string				g_dbFilename;	// name of FASTA file, e.g. "file.fasta"
	string				g_dbPath;		// path to FASTA database, e.g. "/dir"
    string              g_spectralLibName;

	ResidueMap*			g_residueMap;
	BaseRunTimeConfig*	g_rtSharedConfig;
	lnFactorialTable	g_lnFactorialTable;

	bool				g_normalizeOnMode;

	int					g_pid;
	int					g_endianType;
	int					g_numProcesses;
	int					g_numChildren;
	int					g_numWorkers;
	string				g_hostString;

	vector< Profiler >	g_profilers;

	#ifdef USE_MPI
		MPI_Status		st;
		void*			g_mpiBuffer;
		MPI_Datatype	mpi_flatSpectrum;
		MPI_Datatype	mpi_flatPeakData;
		MPI_Datatype	mpi_flatTagInfo;
	#endif

	ResidueFilter::operator string () const
	{
		stringstream ostr;
		for( size_t i=20; i < 128; ++i )
			if( m_filter[i] )
				ostr << (char) i;
		return ostr.str();
	}

	const char UniqueModCharList[] = "0123456789`~!@#$%^&*-_=|:;,./?abcdefghjiklmnopqrstuvwxyz";

	void DynamicModSet::clear()
	{
		set<DynamicMod>::clear();
		uniqueToUserMap.clear();
		userToUniqueMap.clear();
	}

	void DynamicModSet::erase( const DynamicMod& mod )
	{
	}

	SetInsertPair(set<DynamicMod>) DynamicModSet::insert( const DynamicMod& mod )
	{
		// Is the mod's userModChar already used as either a user mod char or a unique mod char?
		// - if true and it's for the same unmodChar and modMass, it's a duplicate mod: return existing itr and false
		// - else: assign a new uniqueModChar and insert as usual
		if( userToUniqueMap[mod.userModChar].size() > 0 )
		{
			vector< DynamicMod >& modsAtUserChar = userToUniqueMap[mod.userModChar];
			for( size_t i=0; i < modsAtUserChar.size(); ++i )
				if( modsAtUserChar[i].unmodChar == mod.unmodChar && modsAtUserChar[i].modMass == mod.modMass )
					return SetInsertPair(set<DynamicMod>)( set<DynamicMod>::find( modsAtUserChar[i] ), false );
		}
		const_cast< DynamicMod& >( mod ).uniqueModChar = UniqueModCharList[ uniqueToUserMap.size() ];

		// Store the mapping between the user and unique mod chars, and insert the mod as usual
		uniqueToUserMap[mod.uniqueModChar] = mod;
		userToUniqueMap[mod.userModChar].push_back( mod );
		return set<DynamicMod>::insert( mod );
	}

	void DynamicModSet::initialize( const string& cfgStr, bool noUserChar )
	{
		boost::char_separator<char> delim(" ");
		stokenizer parser( cfgStr.begin(), cfgStr.begin() + cfgStr.length(), delim );
		stokenizer::iterator itr = parser.begin();
		while( itr != parser.end() )
		{
			string motif = *itr;
			char userModChar = '@';
            if(!noUserChar)
                userModChar = (*(++itr))[0];
			double modMass = lexical_cast<double>( *(++itr) );
			parseMotif( motif, userModChar, modMass );
			++itr;
		}
	}

	DynamicModSet::operator string () const
	{
		stringstream modStr;
		for( const_iterator itr = begin(); itr != end(); ++itr )
		{
			modStr << ( itr == begin() ? "" : " " );

			for( size_t i=0; i < itr->NTerminalFilters.size(); ++i )
			{
				size_t filterSize = itr->NTerminalFilters[i].m_filter.size();
				if( filterSize == 0 )
					continue;
				else if( filterSize == 1 )
					modStr << (string) itr->NTerminalFilters[i];
				else
					modStr << '[' << (string) itr->NTerminalFilters[i] << ']';
			}

			modStr << itr->unmodChar;
			if( !itr->CTerminalFilters.empty() )
				modStr << '!';

			for( size_t i=0; i < itr->CTerminalFilters.size(); ++i )
			{
				size_t filterSize = itr->CTerminalFilters[i].m_filter.size();
				if( filterSize == 0 )
					continue;
				else if( filterSize == 1 )
					modStr << (string) itr->CTerminalFilters[i];
				else
					modStr << '[' << (string) itr->CTerminalFilters[i] << ']';
			}

			modStr << " " << itr->userModChar << " " << itr->modMass;
		}
		return modStr.str();
	}

	void DynamicModSet::parseMotif( const string& motif, char modChar, double modMass )
	{
		vector<DynamicMod> mods;
		vector<AminoAcidResidue> multiResidueBlock;
		int multiResidueBlockMode = 0; // 0=off 1=contained residues are included 2=contained residues are excluded
		bool hasModifiedSite = false;
		vector<ResidueFilter> NTerminalFilters;
		vector<ResidueFilter> CTerminalFilters;
		ResidueMap defaultResidueMap;

		for( size_t i=0; i < motif.size(); ++i )
		{
			switch( motif[i] )
			{
				case '{':
				case '[':
					// start multi residue block
					if( multiResidueBlockMode > 0 )
					{
						cerr << "Warning: invalid nested multi-residue block opening bracket in motif \"" << motif << "\"" << endl;
						continue;
					}
					multiResidueBlockMode = ( motif[i] == '[' ? 1 : 2 );
					break;

				case '}':
				case ']':
					// close multi residue block
					if( multiResidueBlockMode == 0 ||
						( multiResidueBlockMode == 1 && motif[i] == '}' ) ||
						( multiResidueBlockMode == 2 && motif[i] == ']' ) )
					{
						cerr << "Warning: mismatched multi-residue block closing bracket in motif \"" << motif << "\"" << endl;
						continue;
					}

					if( motif.size()-2 == multiResidueBlock.size() ||
						( i+1 < motif.size() && motif[i+1] == '!' ) ||
						( i+1 == motif.size() && !hasModifiedSite ) )
					{
						if( multiResidueBlockMode == 2 )
						{
							for( set<char>::const_iterator itr = defaultResidueMap.getResidues().begin(); itr != defaultResidueMap.getResidues().end(); ++itr )
								if( std::find( multiResidueBlock.begin(), multiResidueBlock.end(), *itr ) == multiResidueBlock.end() )
									mods.push_back( DynamicMod( *itr, modChar, modMass ) );
						} else
						{
							for( size_t j=0; j < multiResidueBlock.size(); ++j )
								mods.push_back( DynamicMod( multiResidueBlock[j], modChar, modMass ) );
						}
					} else
					{
						if( hasModifiedSite )
						{
							CTerminalFilters.push_back( ResidueFilter() );
							bool inclusionMode = true;
							if( multiResidueBlockMode == 2 )
							{
								for( set<char>::const_iterator itr = defaultResidueMap.getResidues().begin(); itr != defaultResidueMap.getResidues().end(); ++itr )
									CTerminalFilters.back().m_filter[ *itr ] = true;
								inclusionMode = false;
							}
							for( size_t j=0; j < multiResidueBlock.size(); ++j )
								CTerminalFilters.back().m_filter[ multiResidueBlock[j] ] = inclusionMode;
						} else
						{
							NTerminalFilters.push_back( ResidueFilter() );
							bool inclusionMode = true;
							if( multiResidueBlockMode == 2 )
							{
								for( set<char>::const_iterator itr = defaultResidueMap.getResidues().begin(); itr != defaultResidueMap.getResidues().end(); ++itr )
									NTerminalFilters.back().m_filter[ *itr ] = true;
								inclusionMode = false;
							}
							for( size_t j=0; j < multiResidueBlock.size(); ++j )
								NTerminalFilters.back().m_filter[ multiResidueBlock[j] ] = inclusionMode;
						}
					}
					multiResidueBlockMode = 0;
					multiResidueBlock.clear();
					break;
				case '!':
					// set last block as the modification site
					if( i == 0 )
						cerr << "Warning: mod site specifier (!) does not occur after a residue or multi-residue block in motif \"" << motif << "\"" << endl;
					else if( multiResidueBlockMode > 0 )
						cerr << "Warning: mod site specifier (!) is invalid inside a multi-residue block in motif \"" << motif << "\"" << endl;
					else
						hasModifiedSite = true;
					break;
				//case '<':
					// N terminus (must be in first block)
					break;
				//case '>':
					// C terminus (must be in last block)
					break;
				default:
					// all other characters are assumed to be residues (A to V bounds checking?)
					if( multiResidueBlockMode > 0 )
						multiResidueBlock.push_back( motif[i] );
					else if( hasModifiedSite )
					{
						CTerminalFilters.push_back( ResidueFilter() );
						CTerminalFilters.back().m_filter[ motif[i] ] = true;
					} else if( i+1 == motif.size() || ( i+1 < motif.size() && motif[i+1] == '!' ) )
					{
							mods.push_back( DynamicMod( motif[i], modChar, modMass ) );
					} else
					{
						NTerminalFilters.push_back( ResidueFilter() );
						NTerminalFilters.back().m_filter[ motif[i] ] = true;
					}
			}
		}
		if( multiResidueBlockMode > 0 )
			cerr << "Warning: mismatched multi-residue block opening bracket in motif \"" << motif << "\"" << endl;

		for( size_t i=0; i < mods.size(); ++i )
		{
			mods[i].NTerminalFilters = NTerminalFilters;
			mods[i].CTerminalFilters = CTerminalFilters;
			insert( mods[i] );
		}
	}

    /*
        This function takes a possible delta mass and tries to snap it to user-supplied "preferred delta masses".
        The function tries to snap the mods in two stages. In the first state, the whole delta mass is snapped
        to the PDMs. In the second stage, the delta mass is split into two or more masses. The split masses are
        in turn get snapped to the user-supplied PDMs.
    */
    vector<DynamicModSet> PreferredDeltaMassesList::getMatchingMassShifts(float modMass, float tolerance)
    {
        vector<DynamicModSet> candidateModSets;
        // Get all possible PDMs for this delta mass
        PreferredDeltaMassesList::iterator begin = lower_bound(modMass - tolerance);
        PreferredDeltaMassesList::iterator end = lower_bound(modMass + tolerance);
        for(PreferredDeltaMassesList::iterator cur = begin; cur != end; ++cur)
        {
            DynamicModSet candidateMods;
            for(DynamicModSet::iterator modIter = cur->second.begin(); modIter != cur->second.end(); ++modIter)
                candidateMods.insert((*modIter));
            candidateModSets.push_back(candidateMods);
        }
        return candidateModSets;
    }

    bool PreferredDeltaMassesList::containsMassShift(float modMass, float tolerance)
    {
        // Get all possible PDMs for this delta mass
        PreferredDeltaMassesList::iterator begin = lower_bound(modMass - tolerance);
        PreferredDeltaMassesList::iterator end = lower_bound(modMass + tolerance);
        if(begin == end)
            return false;
        return true;
    }

	void MvhTable::ConvertToPValues()
	{
		//START_PROFILER(11);
		typedef multimap< double, iterator > KeyByProbability;
		KeyByProbability keyByProbability;
		for( iterator itr = begin(); itr != end(); ++itr )
			keyByProbability.insert( KeyByProbability::value_type( itr->second, itr ) );
		//STOP_PROFILER(11);
		//START_PROFILER(12);
		double pSum = 0;
		for( KeyByProbability::iterator itr = keyByProbability.begin(); itr != keyByProbability.end(); )
		{
			pSum += exp( itr->first );
			itr->second->second = pSum;
			double curProbability = itr->first;
			do { ++itr; } while( itr != keyByProbability.end() && curProbability == itr->first );
		}
		//STOP_PROFILER(12);
	}
}

namespace std
{
	ostream& operator<< ( ostream& o, const SpectrumId& s )
	{
		return ( o << s.id );
	}

	istream& operator>> ( istream& i, DynamicMod& rhs )
	{
		return ( i >> rhs.unmodChar >> rhs.userModChar >> rhs.modMass );
	}

	istream& operator>> ( istream& i, StaticMod& rhs )
	{
		return ( i >> rhs.name >> rhs.mass );
	}

	ostream& operator<< ( ostream& o, const DynamicMod& rhs )
	{
		return ( o << rhs.unmodChar << " " << rhs.userModChar << " " << rhs.modMass );
	}

	ostream& operator<< ( ostream& o, const StaticMod& rhs )
	{
		return ( o << rhs.name << " " << rhs.mass );
	}

}


text:
// ExtractCallbackConsole.h

#include "StdAfx.h"

#include "ExtractCallbackConsole.h"
#include "UserInputUtils.h"
#include "ConsoleClose.h"

#include "Common/Wildcard.h"

#include "Windows/FileDir.h"
#include "Windows/FileFind.h"
#include "Windows/Time.h"
#include "Windows/Defs.h"
#include "Windows/PropVariant.h"
#include "Windows/Error.h"
#include "Windows/PropVariantConversions.h"

#include "../../Common/FilePathAutoRename.h"

#include "../Common/ExtractingFilePath.h"

using namespace NWindows;
using namespace NFile;
using namespace NDirectory;

static const char *kTestString    =  "Testing     ";
static const char *kExtractString =  "Extracting  ";
static const char *kSkipString   =  "Skipping    ";

// static const char *kCantAutoRename = "can not create file with auto name\n";
// static const char *kCantRenameFile = "can not rename existing file\n";
// static const char *kCantDeleteOutputFile = "can not delete output file ";
static const char *kError = "ERROR: ";
static const char *kMemoryExceptionMessage = "Can't allocate required memory!";

static const char *kProcessing = "Processing archive: ";
static const char *kEverythingIsOk = "Everything is Ok";
static const char *kNoFiles = "No files to process";

static const char *kUnsupportedMethod = "Unsupported Method";
static const char *kCrcFailed = "CRC Failed";
static const char *kCrcFailedEncrypted = "CRC Failed in encrypted file. Wrong password?";
static const char *kDataError = "Data Error";
static const char *kDataErrorEncrypted = "Data Error in encrypted file. Wrong password?";
static const char *kUnknownError = "Unknown Error";

STDMETHODIMP CExtractCallbackConsole::SetTotal(UInt64)
{
  if (NConsoleClose::TestBreakSignal())
    return E_ABORT;
  return S_OK;
}

STDMETHODIMP CExtractCallbackConsole::SetCompleted(const UInt64 *)
{
  if (NConsoleClose::TestBreakSignal())
    return E_ABORT;
  return S_OK;
}

STDMETHODIMP CExtractCallbackConsole::AskOverwrite(
    const wchar_t *existName, const FILETIME *, const UInt64 *,
    const wchar_t *newName, const FILETIME *, const UInt64 *,
    Int32 *answer)
{
  (*OutStream) << "file " << existName <<
    "\nalready exists. Overwrite with " << endl;
  (*OutStream) << newName;

  NUserAnswerMode::EEnum overwriteAnswer = ScanUserYesNoAllQuit(OutStream);

  switch(overwriteAnswer)
  {
    case NUserAnswerMode::kQuit:  return E_ABORT;
    case NUserAnswerMode::kNo:     *answer = NOverwriteAnswer::kNo; break;
    case NUserAnswerMode::kNoAll:  *answer = NOverwriteAnswer::kNoToAll; break;
    case NUserAnswerMode::kYesAll: *answer = NOverwriteAnswer::kYesToAll; break;
    case NUserAnswerMode::kYes:    *answer = NOverwriteAnswer::kYes; break;
    case NUserAnswerMode::kAutoRenameAll: *answer = NOverwriteAnswer::kAutoRename; break;
    default: return E_FAIL;
  }
  return S_OK;
}

STDMETHODIMP CExtractCallbackConsole::PrepareOperation(const wchar_t *name, bool /* isFolder */, Int32 askExtractMode, const UInt64 *position)
{
  switch (askExtractMode)
  {
    case NArchive::NExtract::NAskMode::kExtract: (*OutStream) << kExtractString; break;
    case NArchive::NExtract::NAskMode::kTest:    (*OutStream) << kTestString; break;
    case NArchive::NExtract::NAskMode::kSkip:    (*OutStream) << kSkipString; break;
  };
  (*OutStream) << name;
  if (position != 0)
    (*OutStream) << " <" << *position << ">";
  return S_OK;
}

STDMETHODIMP CExtractCallbackConsole::MessageError(const wchar_t *message)
{
  (*OutStream) << message << endl;
  NumFileErrorsInCurrentArchive++;
  NumFileErrors++;
  return S_OK;
}

STDMETHODIMP CExtractCallbackConsole::SetOperationResult(Int32 operationResult, bool encrypted)
{
  switch(operationResult)
  {
    case NArchive::NExtract::NOperationResult::kOK:
      break;
    default:
    {
      NumFileErrorsInCurrentArchive++;
      NumFileErrors++;
      (*OutStream) << "     ";
      switch(operationResult)
      {
        case NArchive::NExtract::NOperationResult::kUnSupportedMethod:
          (*OutStream) << kUnsupportedMethod;
          break;
        case NArchive::NExtract::NOperationResult::kCRCError:
          (*OutStream) << (encrypted ? kCrcFailedEncrypted: kCrcFailed);
          break;
        case NArchive::NExtract::NOperationResult::kDataError:
          (*OutStream) << (encrypted ? kDataErrorEncrypted : kDataError);
          break;
        default:
          (*OutStream) << kUnknownError;
      }
    }
  }
  (*OutStream) << endl;
  return S_OK;
}

#ifndef _NO_CRYPTO

HRESULT CExtractCallbackConsole::SetPassword(const UString &password)
{
  PasswordIsDefined = true;
  Password = password;
  return S_OK;
}

STDMETHODIMP CExtractCallbackConsole::CryptoGetTextPassword(BSTR *password)
{
  if (!PasswordIsDefined)
  {
    Password = GetPassword(OutStream);
    PasswordIsDefined = true;
  }
  return StringToBstr(Password, password);
}

#endif

HRESULT CExtractCallbackConsole::BeforeOpen(const wchar_t *name)
{
  NumArchives++;
  NumFileErrorsInCurrentArchive = 0;
  (*OutStream) << endl << kProcessing << name << endl;
  return S_OK;
}

HRESULT CExtractCallbackConsole::OpenResult(const wchar_t * /* name */, HRESULT result, bool encrypted)
{
  (*OutStream) << endl;
  if (result != S_OK)
  {
    (*OutStream) << "Error: ";
    if (result == S_FALSE)
    {
      (*OutStream) << (encrypted ?
        "Can not open encrypted archive. Wrong password?" :
        "Can not open file as archive");
    }
    else
    {
      if (result == E_OUTOFMEMORY)
        (*OutStream) << "Can't allocate required memory";
      else
        (*OutStream) << NError::MyFormatMessage(result);
    }
    (*OutStream) << endl;
    NumArchiveErrors++;
  }
  return S_OK;
}

HRESULT CExtractCallbackConsole::ThereAreNoFiles()
{
  (*OutStream) << endl << kNoFiles << endl;
  return S_OK;
}

HRESULT CExtractCallbackConsole::ExtractResult(HRESULT result)
{
  if (result == S_OK)
  {
    (*OutStream) << endl;
    if (NumFileErrorsInCurrentArchive == 0)
      (*OutStream) << kEverythingIsOk << endl;
    else
    {
      NumArchiveErrors++;
      (*OutStream) << "Sub items Errors: " << NumFileErrorsInCurrentArchive << endl;
    }
  }
  if (result == S_OK)
    return result;
  NumArchiveErrors++;
  if (result == E_ABORT || result == ERROR_DISK_FULL)
    return result;
  (*OutStream) << endl << kError;
  if (result == E_OUTOFMEMORY)
    (*OutStream) << kMemoryExceptionMessage;
  else
  {
    UString message;
    NError::MyFormatMessage(result, message);
    (*OutStream) << message;
  }
  (*OutStream) << endl;
  return S_OK;
}


text:
namespace Xamarin.CommunityToolkit.Sample.Pages.Behaviors
{
	public partial class UriValidationBehaviorPage
	{
		public UriValidationBehaviorPage()
			=> InitializeComponent();
	}
}


text:
import os
import os.path as op
from unittest.mock import Mock, patch

import pytest
import numpy as np

import mnefun

def test_exits_with_warning_if_all_epochs_autorejected(params):
    """Test that save_epochs fails gracefully if no epochs remain."""
    params.subject_indices = np.arange(1)
    params.subjects = ['x']
    params.run_names = ['%s']
    params.analyses = ['x']
    params.out_names = [[]]
    params.out_numbers = [[]]
    params.must_match = [[]]
    os.makedirs(op.join(params.work_dir, params.subjects[0], 'sss_pca_fif'))
    with patch('mnefun._epoching.read_raw_fif'), \
            patch('mnefun._scoring.concatenate_events'), \
            patch('mnefun._epoching._fix_raw_eog_cals'), \
            patch('mnefun._scoring.get_event_fnames'), \
            patch('mnefun._epoching.Epochs') as Epochs:
        epochs = Mock()
        epochs.info = {'sfreq': 1000}
        epochs.events = np.zeros((0, 3))
        Epochs.return_value = epochs
        with pytest.raises(ValueError, match='No valid'):
            mnefun.do_processing(params, write_epochs=True,
                                 print_status=False)


text:
jsaspmvclocalize
================

sample project to localize easily javascript in asp.net mvc SharePoint apps

related projects
https://github.com/baywet/jsaspnetwebformslocalize
https://github.com/baywet/jsfulltrustlocalize

Blog post about it
http://microsofttouch.fr/english/b/vince365/archive/2014/08/13/localizing-javascript-of-a-full-trust-solution.aspx


text:
/**
 * @class L.EditToolbar.Delete
 * @aka EditToolbar.Delete
 */
L.EditToolbar.Delete = L.Handler.extend({
	statics: {
		TYPE: 'remove' // not delete as delete is reserved in js
	},

	includes: L.Mixin.Events,

	// @method intialize(): void
	initialize: function (map, options) {
		L.Handler.prototype.initialize.call(this, map);

		L.Util.setOptions(this, options);

		// Store the selectable layer group for ease of access
		this._deletableLayers = this.options.featureGroup;

		if (!(this._deletableLayers instanceof L.FeatureGroup)) {
			throw new Error('options.featureGroup must be a L.FeatureGroup');
		}

		// Save the type so super can fire, need to do this as cannot do this.TYPE :(
		this.type = L.EditToolbar.Delete.TYPE;
	},

	// @method enable(): void
	// Enable the delete toolbar
	enable: function () {
		if (this._enabled || !this._hasAvailableLayers()) {
			return;
		}
		this.fire('enabled', { handler: this.type });

		this._map.fire(L.Draw.Event.DELETESTART, { handler: this.type });

		L.Handler.prototype.enable.call(this);

		this._deletableLayers
			.on('layeradd', this._enableLayerDelete, this)
			.on('layerremove', this._disableLayerDelete, this);
	},

	// @method disable(): void
	// Disable the delete toolbar
	disable: function () {
		if (!this._enabled) {
			return;
		}

		this._deletableLayers
			.off('layeradd', this._enableLayerDelete, this)
			.off('layerremove', this._disableLayerDelete, this);

		L.Handler.prototype.disable.call(this);

		this._map.fire(L.Draw.Event.DELETESTOP, { handler: this.type });
		this.fire('disabled', { handler: this.type });
	},

	// @method addHooks(): void
	// Add listener hooks to this handler
	addHooks: function () {
		var map = this._map;

		if (map) {
			map.getContainer().focus();

			this._deletableLayers.eachLayer(this._enableLayerDelete, this);
			this._deletedLayers = new L.LayerGroup();

			this._tooltip = new L.Draw.Tooltip(this._map);
			this._tooltip.updateContent({ text: L.drawLocal.edit.handlers.remove.tooltip.text });

			this._map.on('mousemove', this._onMouseMove, this);
			L.DomEvent.on(this._map._container, 'keyup', this.keyCancel, this);
		}
	},

	keyCancel: function (e) {
		if (e.keyCode === 27) {
			this.disable();
		}
	},

	// @method removeHooks(): void
	// Remove listener hooks from this handler
	removeHooks: function () {
		if (this._map) {
			this._deletableLayers.eachLayer(this._disableLayerDelete, this);
			this._deletedLayers = null;

			this._tooltip.dispose();
			this._tooltip = null;

			this._map.off('mousemove', this._onMouseMove, this);
			L.DomEvent.off(this._map._container, 'keyup', this.keyCancel, this);
		}
	},

	// @method revertLayers(): void
	// Revert the deleted layers back to their prior state.
	revertLayers: function () {
		// Iterate of the deleted layers and add them back into the featureGroup
		this._deletedLayers.eachLayer(function (layer) {
			this._deletableLayers.addLayer(layer);
			layer.fire('revert-deleted', { layer: layer });
		}, this);
	},

	// @method save(): void
	// Save deleted layers
	save: function () {
		this._map.fire(L.Draw.Event.DELETED, { layers: this._deletedLayers });
	},

	// @method removeAllLayers(): void
	// Remove all delateable layers
	removeAllLayers: function () {
		// Iterate of the delateable layers and add remove them
		this._deletableLayers.eachLayer(function (layer) {
			this._removeLayer({ layer: layer });
		}, this);
		this.save();
	},

	// @method removeAllLayers(): void
	// Remove all delateable layers
	removeAllLayers: function () {
		// Iterate of the delateable layers and add remove them
		this._deletableLayers.eachLayer(function (layer) {
			this._removeLayer({ layer: layer });
		}, this);
		this.save();
	},

	_enableLayerDelete: function (e) {
		var layer = e.layer || e.target || e;

		layer.on('click', this._removeLayer, this);
	},

	_disableLayerDelete: function (e) {
		var layer = e.layer || e.target || e;

		layer.off('click', this._removeLayer, this);

		// Remove from the deleted layers so we can't accidentally revert if the user presses cancel
		this._deletedLayers.removeLayer(layer);
	},

	_removeLayer: function (e) {
		var layer;
		if (e.target instanceof L.FeatureGroup) {
			layer = e.target;
		}
		else {
			layer = e.layer || e.target || e;
		}

		this._deletableLayers.removeLayer(layer);

		this._deletedLayers.addLayer(layer);
		this._map.fire(L.Draw.Event.DELETEDLAYER, { layer: layer, drawHandler: this });

		layer.fire('deleted');
	},

	_onMouseMove: function (e) {
		this._tooltip.updatePosition(e.latlng);
	},

	_hasAvailableLayers: function () {
		return this._deletableLayers.getLayers().length !== 0;
	}
});