text:
@implementation DBFILESUploadSessionOffsetError

#pragma mark - Constructors

- (instancetype)initWithCorrectOffset:(NSNumber *)correctOffset {

  self = [super init];
  if (self) {
    _correctOffset = correctOffset;
  }
  return self;
}

#pragma mark - Serialization methods

+ (NSDictionary *)serialize:(id)instance {
  return [DBFILESUploadSessionOffsetErrorSerializer serialize:instance];
}

+ (id)deserialize:(NSDictionary *)dict {
  return [DBFILESUploadSessionOffsetErrorSerializer deserialize:dict];
}

#pragma mark - Description method

- (NSString *)description {
  return [[DBFILESUploadSessionOffsetErrorSerializer serialize:self] description];
}

@end

#pragma mark - Serializer Object

@implementation DBFILESUploadSessionOffsetErrorSerializer

+ (NSDictionary *)serialize:(DBFILESUploadSessionOffsetError *)valueObj {
  NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];

  jsonDict[@"correct_offset"] = valueObj.correctOffset;

  return jsonDict;
}

+ (DBFILESUploadSessionOffsetError *)deserialize:(NSDictionary *)valueDict {
  NSNumber *correctOffset = valueDict[@"correct_offset"];

  return [[DBFILESUploadSessionOffsetError alloc] initWithCorrectOffset:correctOffset];
}

@end


text:
package org.huahinframework.core.lib.input.creator;

import org.huahinframework.core.util.StringUtil;

/**
 * Split by a separator String data.
 */
public class StringSplitter implements Splitter {
    private String separator;

    /**
     * @param separator separator
     */
    public StringSplitter(String separator) {
        this.separator = separator;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String[] split(String str) {
        return StringUtil.split(str, separator, false);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<link rel="import" href="..\..\bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="../../bower_components/paper-menu/paper-menu.html">
<link rel="import" href="../../bower_components/paper-item/paper-item.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../beginner-assesment-service/beginner-assesment-service.html">
<link rel="import" href="../beginner-assesment-markentrysheet/beginner-assesment-markentrysheet.html">
<link rel="import" href="../component-service/component-service.html">
<link rel="import" href="../assesment-sheet-card/assesment-sheet-card.html">
<dom-module id="beginner-assesment-card">
  <template>

          <paper-dropdown-menu id="grade" label="Select Grade" disabled="{{read}}" required>
            <paper-menu  id="gradenam" class="dropdown-content"  on-iron-select="FnSelectGrade"  attr-for-selected="value" required>
              <template is="dom-repeat" items="{{gradearr}}">
                <paper-item value="{{item.grade_name}}">{{item.grade_name}}</paper-item>
              </template>
            </paper-menu>
          </paper-dropdown-menu>
          <paper-dropdown-menu id="section" label="Select Section" disabled="{{read}}" required>
            <paper-menu id="sectionnam" class="dropdown-content"  on-iron-select="FnSelectSection"  attr-for-selected="value" required>
              <template is="dom-repeat" items="{{sectionarr}}">
                <paper-item value="{{item.section_name}}">{{item.section_name}}</paper-item>
              </template>
            </paper-menu>
          </paper-dropdown-menu>
          <paper-dropdown-menu id="subject" label="Select Subject" disabled="{{read}}" required>
            <paper-menu id="subjectnam" class="dropdown-content"  on-iron-select="FnSelectSubject"  attr-for-selected="value" required>
              <paper-item value="English">English</paper-item>
              <paper-item value="Mathematics">Mathematics</paper-item>
              <paper-item value="EVS">EVS</paper-item>

            </paper-menu>
          </paper-dropdown-menu>

    <beginner-assesment-service id="bassesmentservice"></beginner-assesment-service>
    <component-service id="componentservice"></component-service>
  </template>

</dom-module>


text:
make
if [ ! -e text8 ]; then
  wget http://mattmahoney.net/dc/text8.zip -O text8.gz
  gzip -d text8.gz -f
fi
# 训练
time ./word2vec -train text8 -output vectors.bin -cbow 1 -size 200 -window 8 -negative 25 -hs 0 -sample 1e-4 -threads 20 -binary 1 -iter 15
# 计算准确率
./compute-accuracy vectors.bin 30000 < questions-words.txt
# to compute accuracy with the full vocabulary, use: ./compute-accuracy vectors.bin < questions-words.txt


text:
density_peak_clustering
=======================

the python implementation of  the clustering algorithm "Clustering by fast search and find of density peaks" described by Alex Rodriguez and Alessandro Laio.


text:
/* global Module */

/* Magic Mirror
 * Module: MMM-MotionEye
 *
 * By Cato Antonsen
 * MIT Licensed.
 */

Module.register("MMM-MotionEye",{

	// Default module config.
	defaults: {
		width: "400px",
		autoHide: false,
		autoHideDelay: 60000,
		debug: false,
        // Allow the module to force modules to be shown (if hidden and locked by another module ex. profile-switcher).
        allowForce: false,
		// The speed of the hide and show animation.
		animationSpeed: 2000,
		forcedRefreshInterval: 0
	},

	debug: function(msg) {
		if (this.config.debug) {
			console.log("MMM-MotionEye: " + msg)
		}
	},

	start: function() {
		this.refreshTimer = null;
		this.startForcedRefresh(this);

		this.sendSocketNotification("CONFIG", this.config);
	},

	resume: function() {
		this.startForcedRefresh(this);
	},

	suspend: function() {
		if (this.refreshTimer) window.clearInterval(this.refreshTimer);
	},

	// Override dom generator.
	getDom: function() {
		if (!this.hidden) {
			var img = document.createElement("img");
			img.setAttribute("class", "motionEyeImage");
			img.id = this.config.id;
			img.src = this.config.url;
			img.style.width = this.config.width;
			return img;
		}

		return document.createElement("div");
	},

	startForcedRefresh: function() {
		var self = this;

		if (self.config.forcedRefreshInterval > 0) {
			self.debug("Starting")
			if (self.refreshTimer) window.clearInterval(self.refreshTimer);

			self.refreshTimer = setInterval(function() {
				self.forceRefresh(self);
			}, this.config.forcedRefreshInterval);
		}
	},

	forceRefresh: function(self) {
		if (!self.hidden) {
			var images = document.getElementsByClassName("motionEyeImage");
			for (var i=0; i < images.length; i++) {
				var img = images[i];
				if (img.id == self.config.id) {
					var url = img.src.split((img.src.indexOf("&") > -1) ? "&" : "?"+"timestamp=")[0];
					img.src = url + ((url.indexOf("&") > -1) ? "&" : "?") + "timestamp=" + new Date().getTime();
					self.debug("Reloading " + url);
				}
			}
		}
	},

	socketNotificationReceived: function(notification, id) {
		this.debug("socketNotificationReceived notification: " + notification);
		this.debug("socketNotificationReceived notification id: " + id);
		this.debug("socketNotificationReceived notification config.id: " + this.config.id);

		if (notification === "MotionEyeShow" && this.config.id == id) {
			this.debug("socketNotificationReceived notification is MotionEyeShow");

			if (this.timeOutID != undefined) {
				clearTimeout(this.timeOutID);
				this.timeOutID = undefined;
			}

			this.debug("Showing module")
			this.show(this.config.animationSpeed, {force: this.config.allowForce});

			if (this.config.autoHide && this.config.autoHideDelay > 0) {
				this.debug("Module will autohide in " + this.config.autoHideDelay + " ms")
				var self = this;
				this.timeOutID = setTimeout(function() {
					self.debug("Autohiding ...");
					self.hide(this.config.animationSpeed);
				}, self.config.autoHideDelay);
			} else {
				this.debug("AutoHide is not enabled or autoHideDelay is 0")
			}
		} else if (notification == "MotionEyeHide" && this.config.id == id) {
			this.debug("socketNotificationReceived notification is MotionEyeHide");
			var self = this;
			this.hide(this.config.animationSpeed);
		}
	}
});


text:
package tw.funymph.commons.sort;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * This class provides a set of methods to sort elements in Java Collection with
 * sort descriptors.
 *
 * @author Pin-Ying Tu
 * @version 1.0
 * @since 1.0
 */
public class SortUtils {

	/**
	 * Get the sorted items with the given sort descriptors. This method supports multiple sort
	 * criteria that sorts the items by the first descriptor, if there are items whose order
	 * can not be determined by the descriptor, the method uses the second descriptor in
	 * the array and so on. Each descriptor can decide to sort items ascending or descending.
	 * Note that the ordering of the items in the collection remains unchanged.
	 *
	 * @param items the items to sort
	 * @param descriptors the sort descriptors
	 * @param <InputType> the type of the elements to be sorted
	 * @return the sort items
	 * @throws IllegalArgumentException either {@code items} is null or {@code descriptors} is null
	 */
	public static <InputType> List<InputType> sortedList(Collection<InputType> items, final List<SortDescriptor<InputType>> descriptors) {
		if (items == null || descriptors == null) {
			throw new IllegalArgumentException();
		}

		List<InputType> result = new ArrayList<InputType>(items);
		sort(result, descriptors);
		return result;
	}

	/**
	 * Sort the items with the given sort descriptors. This method supports multiple sort
	 * criteria that sorts the items by the first descriptor, if there are items whose order
	 * can not be determined by the descriptor, the method uses the second descriptor in
	 * the array and so on. Each descriptor can decide to sort items ascending or descending.
	 *
	 * @param items the items to sort
	 * @param descriptors the sort descriptors
	 * @param <InputType> the type of the elements to be sorted
	 * @throws IllegalArgumentException either {@code items} is null or {@code descriptors} is null
	 */
	@SuppressWarnings("unchecked")
	public static <InputType> void sort(List<InputType> items, final List<SortDescriptor<InputType>> descriptors) {
		if (items == null || descriptors == null) {
			throw new IllegalArgumentException();
		}

		Collections.sort(items, new Comparator<InputType>() {

			@Override
			public int compare(InputType item1, InputType item2) {
				return compare(item1, item2, 0);
			}

			/**
			 * Compare the given two items with the descriptor specified by the index.
			 *
			 * @param item1 the first item to compare
			 * @param item2 the second item to compare
			 * @param descriptorIndex the descriptor index in the array
			 * @return the compare result
			 */
			@SuppressWarnings({ "rawtypes" })
			private int compare(InputType item1, InputType item2, int descriptorIndex) {
				SortDescriptor<InputType> descriptor = descriptors.get(descriptorIndex);
				Comparable key1 = descriptor.transform(item1);
				Comparable key2 = descriptor.transform(item2);
				int result = 0;
				if (key1 != null && key2 != null) {
					result = descriptor.isAscending()? key1.compareTo(key2) : key2.compareTo(key1);
				}
				if (key1 != null && key2 == null) {
					return descriptor.isAscending()? 1 : -1;
				}
				if (key1 == null && key2 != null) {
					return descriptor.isAscending()? -1 : 1;
				}
				if (result == 0 && hasNextDescriptor(descriptorIndex)) {
					return compare(item1, item2, descriptorIndex + 1);
				}
				return result;
			}

			/**
			 * Check whether the given index has the next descriptor.
			 *
			 * @param index the current descriptor index
			 * @return true if has the next descriptor
			 */
			private boolean hasNextDescriptor(int index) {
				return (index + 1) < descriptors.size();
			}
		});
	}
}


text:
const path = require('path');
const fs = require('fs');
const { serializeTags } = require('remark-mdx/lib/serialize/mdx-element');
const serializeMdxExpression = require('remark-mdx/lib/serialize/mdx-expression');
const toH = require('hast-to-hyperscript');
const { toTemplateLiteral } = require('@mdx-js/util');
const { parse } = require('@patternfly/ast-helpers');
const { capitalize } = require('../../helpers/capitalize');
const { slugger } = require('../../helpers/slugger');
const { liveCodeTypes } = require('../../helpers/liveCodeTypes');

// Adapted from https://github.com/mdx-js/mdx/blob/next/packages/mdx/mdx-hast-to-jsx.js
function toJSX(node, parentNode = {}, options = {}) {
  options.examples = options.examples || {};
  options.indent = options.indent || 2;
  if (node.type === 'root') {
    return serializeRoot(node, options);
  }

  if (node.type === 'element') {
    return serializeElement(node, options, parentNode);
  }

  // Wraps text nodes inside template string, so that we don't run into escaping issues.
  if (node.type === 'text') {
    return serializeText(node, options, parentNode);
  }

  if (node.type === 'mdxBlockExpression' || node.type === 'mdxSpanExpression') {
    return serializeMdxExpression(node);
  }

  if (node.type === 'mdxBlockElement' || node.type === 'mdxSpanElement') {
    return serializeComponent(node, options, parentNode);
  }
}

function compile(options = { }) {
  this.Compiler = function(tree) {
    return toJSX(tree, {}, options);
  }
}

function serializeRoot(node, options) {
  const { getOutPath, getRelPath, getPageData, examples } = options;
  const pageData = {...getPageData()};
  // Save some kb
  delete pageData.toc;
  const exportName = pageData.slug.replace(/[\/-](.)?/g, (_, match) => capitalize(match)) + 'Docs';
  const groups = {
    import: [],
    rest: []
  };

  for (const child of node.children) {
    let kind = 'rest'

    if (child.type === 'import') {
      kind = child.type
    }

    groups[kind].push(child)
  }

  const thumbnailFolder = path.join(path.dirname(getOutPath()), pageData.source);
  const thumbnails = fs.existsSync(thumbnailFolder) ? fs.readdirSync(thumbnailFolder) : [];
  const thumbnailImports = thumbnails.map(img =>
    `import srcImport${path.basename(img, '.png').replace(/-/g, '')} from './${pageData.source}/${img}';`)

  const importStatements = groups.import
    .map(node => node.value)
    .map(imp => imp.replace(/(['"])\./g, (_, match) => `${match}${getRelPath()}${path.posix.sep}\.`));

  // Map relative import name to '@package...'
  const relativeImportsRegex = /(?:[\.\/]+.*)(@.*)['"]/gm;
  let relativeImportMatch;
  let relativeImportMatches = {};
  while (relativeImportMatch = relativeImportsRegex.exec(importStatements[0])) {
    const [_match, absoluteImportPath] = relativeImportMatch;
    if (absoluteImportPath && !absoluteImportPath.includes('srcImport')) {
      // `@patternfly/react-core/src/demos/./examples/DashboardWrapper` to `DashboardWrapper`
      let relativeFileImport = /(\.+\/.*)/gm.exec(absoluteImportPath);
      if (relativeFileImport) {
        // Build map of relative imports (from example.js code) to npm package import path (used in codesandbox.js)
        const relativeFilePath = relativeFileImport[0];
        const relativeImportName = relativeFilePath
          .split('/')
          .pop()
          .split('.')
          .shift();
        relativeImportMatches[relativeImportName] = absoluteImportPath;
      }
    }
  }

  const importStatementsWithThumbnails = importStatements
    .concat(thumbnailImports)
    .join('\n');

  // https://astexplorer.net/#/gist/9c531dd372dfc57e194c13c2889d31c3/03f2d6e889db1a733c6a079554e8af7784863739
  options.importSpecifiers = parse(importStatementsWithThumbnails).body
    .map(node => node.specifiers)
    .flat(1)
    .map(spec => spec.local ? spec.local.name : null)
    .filter(Boolean);
  const liveContext = options.importSpecifiers
    .filter(localName => !/srcImport.*/.test(localName)) // Images in MD like [!img](./src)
    .join(',\n  ');
  const childNodes = groups.rest
    .map(childNode => toJSX(childNode, node, options))
    .join('');

  let res = `import React from 'react';
import { AutoLinkHeader, Example, Link as PatternflyThemeLink } from '@patternfly/documentation-framework/components';
${importStatementsWithThumbnails}
const pageData = ${JSON.stringify(pageData, null, 2)};
`;
  if (liveContext) {
    res += `pageData.liveContext = {\n${
      '  ' + liveContext
    }\n};\n`
  }
  if (relativeImportMatches) {
    res += `pageData.relativeImports = {\n${
      '  ' + Object.entries(relativeImportMatches)
        .map(([key, val]) => `'${key}': '${val}'`)
        .join(',\n  ')
    }\n};\n`;
  }
  if (examples) {
    res += `pageData.examples = {\n${
      '  ' + Object.entries(examples)
        .map(([key, val]) => `'${key}': ${val}`)
        .join(',\n  ')
    }\n};\n`;
  }
  res += `\nconst Component = () => (
  <React.Fragment>${childNodes.replace(/\n\s*\n/g, '\n')}
  </React.Fragment>
);
Component.displayName = '${exportName}';
Component.pageData = pageData;

export default Component;\n`;

  return res;
}

function serializeElement(node, options) {
  const { indent, examples } = options;
  const { type, props } = toH(
    fakeReactCreateElement,
    Object.assign({}, node, {children: []}),
    {prefix: false}
  );
  const content = serializeChildren(node, {...options});

  delete props.key;

  const srcImport = node.properties.src;
  if (type === 'img') {
    delete props.src;
    delete props.isResponsive;
  }
  const spread = Object.keys(props).length === 0
    ? null
    : JSON.stringify(props);

  const indentText = '  '.repeat(indent);
  let res = '\n';
  const isFullscreenExample = type === 'Example'
    && liveCodeTypes.includes(props.lang)
    && !props.noLive;
  res += `${indentText}<${type}`;
  if (isFullscreenExample) {
    res += ' {...pageData} {...props}';
    const thumbnailImport = `srcImport${slugger(props.title).replace(/-/g, '')}`;
    if (options.importSpecifiers.includes(thumbnailImport)) {
      res += ` thumbnail={${thumbnailImport}}`;
    }
  }
  else if (type === 'img') {
    res += ` src={${srcImport}}`;
    if (node.properties.isResponsive) {
      if (!props.width) {
        res += ` width={${srcImport}.width}`;
        res += ` height={${srcImport}.height}`;
      }
      else {
        props.width = props.width.replace('px', '');
        res += ` height={${srcImport}.height * ${props.width} / ${srcImport}.width}`;
      }
    }
  }
  if (spread) {
    res += ` {...${spread}}`;
  }
  res += `>\n${indentText}  ${content}`;
  res += `\n${indentText}</${type}>`;
  if (isFullscreenExample) {
    // Props lets us pass `isFullscreenPreview` to <Example> so it knows to take 100% height
    examples[props.title] = `props => ${res}`;
    res = `\n${indentText}{React.createElement(pageData.examples[${
      JSON.stringify(props.title)
    }])}`;
  }

  return res;
}

function serializeComponent(node, options) {
  let content = serializeChildren(node, options);
  const tags = serializeTags(
    Object.assign({}, node, {children: content ? ['!'] : []})
  );

  if (node.type === 'mdxBlockElement' && content) {
    content = '\n' + content + '\n';
  }

  const indentText = '  '.repeat(options.indent);
  return `${indentText}${tags.open}${content}${tags.close || ''}`;
}

function serializeText(node, options, parentNode) {
  // Don't wrap newlines unless specifically instructed to by the flag,
  // to avoid issues like React warnings caused by text nodes in tables.
  const shouldPreserveNewlines = options.preserveNewlines || parentNode.tagName === 'p';

  if (node.value === '\n' && !shouldPreserveNewlines) {
    return node.value;
  }

  return toTemplateLiteral(node.value);
}

function serializeChildren(node, options) {
  const children = node.children || [];
  const childOptions = Object.assign({}, options, {
    // Tell all children inside <pre> tags to preserve newlines as text nodes
    preserveNewlines: options.preserveNewlines || node.tagName === 'pre',
    indent: options.indent + 1
  });

  const indentText = '  '.repeat(options.indent + 1);

  return children
    .map(childNode => toJSX(childNode, node, childOptions))
    .join(`\n${indentText}`);
}

// We only do this for the props, so we're ignoring children.
function fakeReactCreateElement(name, props) {
  return {
    type: name,
    props: props,
    // Needed for `toH` to think this is React.
    key: null,
    _owner: null
  }
}

module.exports = compile;


text:
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// 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.

#pragma once
#include <llvm/Support/SourceMgr.h>
#include <mlir/IR/Diagnostics.h>

#include <memory>

namespace infrt {
namespace dialect {

/**
 * A scoped diagnostic handler to help debug MLIR process.
 */
class MyScopedDiagnosicHandler : public mlir::SourceMgrDiagnosticHandler {
 public:
  MyScopedDiagnosicHandler(mlir::MLIRContext* ctx, bool propagate);

  mlir::LogicalResult handler(mlir::Diagnostic* diag);

  ~MyScopedDiagnosicHandler();

 private:
  class Impl;
  std::unique_ptr<Impl> impl_;
};

}  // namespace dialect
}  // namespace infrt


text:
<?php
namespace PhpMongoAdmin\Base;

/**
 * Class HttpException is a base http exception
 * @package PhpMongoAdmin\Base
 */
class HttpException extends \Exception{

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace RegExpBuilderTests
{
    [TestClass]
    public class RegExpBuilderTests
    {
        [TestMethod]
        public void GetRegExp()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder.Digit().ToRegExp();

            Assert.IsTrue(r.Match("1").Success);
            Assert.IsFalse(r.Match("a").Success);
        }

        [TestMethod]
        public void IsDigit()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder.Digit().ToRegExp();

            Assert.IsTrue(r.Match("1").Success);
            Assert.IsTrue(r.Match("11").Success);
            Assert.IsFalse(r.Match("a").Success);
        }

        [TestMethod]
        public void IsOnlyOneDigit()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .Digit()
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("1").Success);
            Assert.IsFalse(r.Match("11").Success);
            Assert.IsFalse(r.Match("a").Success);
        }

        [TestMethod]
        public void IsSomeDigit()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .OneOrMore()
                .Digit()
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("11").Success);
            Assert.IsFalse(r.Match("a").Success);
        }

        [TestMethod]
        public void IsLetters()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .Digit()
                .Letters()
                .Digit()
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("1a1").Success);
            Assert.IsTrue(r.Match("1aa1").Success);
            Assert.IsFalse(r.Match("a").Success);
        }

        [TestMethod]
        public void IsLetter()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .Letter()
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("a").Success);
            Assert.IsFalse(r.Match("aa").Success);
        }

        [TestMethod]
        public void ZeroOrOneLetter()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .ZeroOrOne()
                .Letter()
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("").Success, "None");
            Assert.IsTrue(r.Match("a").Success, "One");
            Assert.IsFalse(r.Match("aa").Success, "Multiple");
        }

        [TestMethod]
        public void Min3Letter()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .MinimumOf(3)
                .Letters()
                .ToRegExp();

            Assert.IsTrue(r.Match("aaa").Success, "Three Letters");
            Assert.IsTrue(r.Match("bbbb").Success, "Four Letters");
            Assert.IsFalse(r.Match("aa").Success, "Two Letters");
        }

        [TestMethod]
        public void Max3Letter()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .MaximumOf(3)
                .Letters()
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("aaa").Success, "Three Letters");
            Assert.IsTrue(r.Match("aa").Success, "Two Letters");
            Assert.IsFalse(r.Match("bbbb").Success, "Four Letters");
        }

        [TestMethod]
        public void Min3Max4Letter()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .MinimumOf(3)
                .MaximumOf(4)
                .Letters()
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("aaa").Success, "Three Letters");
            Assert.IsTrue(r.Match("aaaa").Success, "Four Letters");
            Assert.IsFalse(r.Match("bbbbb").Success, "Five Letters");
            Assert.IsFalse(r.Match("bb").Success, "Two Letters");
        }

        [TestMethod]
        public void Exactly()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .Exactly(3)
                .Letters()
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("aaa").Success, "Three Letters");
            Assert.IsFalse(r.Match("aaaa").Success, "four Letters");
            Assert.IsFalse(r.Match("bb").Success, "two Letters");
        }

        [TestMethod]
        public void ExactlyOfCustom()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .Exactly(3)
                .Of("a")
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("aaa").Success, "Three Letters");
            Assert.IsFalse(r.Match("aaaa").Success, "four Letters");
            Assert.IsFalse(r.Match("aa").Success, "two Letters");
        }

        [TestMethod]
        public void Or()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
            .StartOfLine()
            .Exactly(1).Of("github")
            .Or()
            .Exactly(1).Of("bitbucket")
            .EndOfLine()
            .ToRegExp();

            string regex = r.ToString();

            Assert.IsTrue(r.Match("github").Success, "Found one Github");
            Assert.IsTrue(r.Match("bitbucket").Success, "Found one Bitbucket");

            Assert.IsFalse(r.Match("githubgithub").Success, "Oops, Found too Many Github");
            Assert.IsFalse(r.Match("bitbucketbitbucket").Success, "Oops, Found too Many Github");
        }

        [TestMethod]
        public void MultipleOr()
        {

            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfLine()
                .Exactly(1)
                .Of("a")
                .Or()
                .Exactly(1).Of("b")
                .Or()
                .MinimumOf(3).Of("x")
                .EndOfLine()
                .ToRegExp();

            Assert.IsTrue(r.Match("a").Success, "a");
            Assert.IsTrue(r.Match("b").Success, "b");
            Assert.IsTrue(r.Match("xxxx").Success, "many x");

            Assert.IsFalse(r.Match("ab").Success, "two Letters");
            Assert.IsFalse(r.Match("aa").Success, "two Letters");
        }

        [TestMethod]
        public void ValidateEmailExample()
        {
            // you should never validate emaildresses using regex, but here is one way:
            // This filter will not allow gmail-like, "+ syntax",  tagging: "info+skipinbox@example.com"
            var builder = new Builder.RegExpBuilder();
            var r = builder
                .StartOfInput()
                .Letter() // Must start with letter a-z
                .Letters() // any number of letters
                .Or()
                .Digits() // any number of numbers
                .Exactly(1).Of("@")
                .Letters() // domain
                .Exactly(1).Of(".")
                .Letters() // top-level domain
                .EndOfInput()
                .ToRegExp();

            Assert.IsTrue(r.Match("anders@andersaberg.com").Success);
            Assert.IsTrue(r.Match("a1@a.com").Success);

            // Invalid
            Assert.IsFalse(r.Match("1a@a.com").Success);
        }
    }
}


text:
package org.kie.server.services.optaplanner;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;

import org.drools.core.impl.InternalKieContainer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.server.api.model.ServiceResponse;
import org.kie.server.api.model.instance.SolverInstance;
import org.kie.server.services.api.KieServerRegistry;
import org.kie.server.services.impl.KieContainerInstanceImpl;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
import org.optaplanner.core.config.domain.ScanAnnotatedClassesConfig;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class SolverServiceBaseTest {

    private static final String CONTAINER_ID = "CONTAINER_ID";
    private static final String SOLVER_ID = "SOLVER_ID";
    private static final String SOLVER_CONFIG = "org/kie/server/services/optaplanner/SolverConfig.xml";
    private static final String SOLVER_CONFIG_WRONG = "org/kie/server/services/optaplanner/SolverConfigWrong.xml";
    private static final String SOLVER_CONFIG_GLOBAL_SCAN_SET = "org/kie/server/services/optaplanner/SolverConfigGlobalScanSet.xml";
    private static final String SOLVER_CONFIG_FILTERED_SCAN_SET = "org/kie/server/services/optaplanner/SolverConfigFilteredScanSet.xml";

    private static final String PRE_CONFIGURED_PACKAGE_INCLUDE = "pre.configured.package.include";
    private static final String PRE_CONFIGURED_PACKAGE_EXCLUDE = "pre.configured.package.exclude";

    private static final String CREATE_SOLVER_FOR_CONTAINER_ERROR = "Failed to create solver for container %s";
    private static final String CREATE_SOLVER_CONTAINER_NOT_EXISTS_ERROR = "Failed to create solver. Container does not exist: %s";
    private static final String CREATING_SOLVER_FACTORY_ERROR = "Error creating solver factory for solver: %s";
    private static final String SOLVER_ALREADY_EXISTS_ERROR = "Failed to create solver. Solver '%s' already exists for container '%s'.";
    private static final String SOLVER_CREATED_SUCCESSFULLY_MESSAGE = "Solver '%s' successfully created in container '%s'";

    @Mock
    private KieServerRegistry context;

    @Mock
    private ExecutorService executorService;

    @Mock
    private SolverInstance solverInstance;

    @Mock
    private KieContainerInstanceImpl containerInstance;

    @Mock
    private InternalKieContainer internalKieContainer;

    @Captor
    private ArgumentCaptor<SolverFactory<Object>> solverFactory;

    @Mock
    private Solver<Object> solver;

    private SolverServiceBase serviceBase;

    @Before
    public void setUp() {
        solverInstance = new SolverInstance();
        solverInstance.setContainerId(CONTAINER_ID);
        solverInstance.setSolverId(SOLVER_ID);
        solverInstance.setSolverConfigFile(SOLVER_CONFIG);

        doReturn(internalKieContainer).when(containerInstance).getKieContainer();
        doReturn(getClass().getClassLoader()).when(internalKieContainer).getClassLoader();
        doReturn(containerInstance).when(context).getContainer(CONTAINER_ID);

        serviceBase = spy(new SolverServiceBase(context, executorService));
    }

    @Test
    public void createSolverWithInstanceNullFailure() {
        ServiceResponse<SolverInstance> response = serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, null);
        assertFailure(response, String.format(CREATE_SOLVER_FOR_CONTAINER_ERROR, CONTAINER_ID));
    }

    @Test
    public void createSolverWithConfigFileNullFailure() {
        solverInstance.setSolverConfigFile(null);
        ServiceResponse<SolverInstance> response = serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, solverInstance);
        assertFailure(response, String.format(CREATE_SOLVER_FOR_CONTAINER_ERROR, CONTAINER_ID));
    }

    @Test
    public void createSolverWithContainerNotExistsFailure() {
        when(context.getContainer(CONTAINER_ID)).thenReturn(null);
        ServiceResponse<SolverInstance> response = serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, solverInstance);
        assertFailure(response, String.format(CREATE_SOLVER_CONTAINER_NOT_EXISTS_ERROR, CONTAINER_ID));
    }

    @Test
    public void createSolverWithSolverConfigurationFileWrongFailure() {
        solverInstance.setSolverConfigFile(SOLVER_CONFIG_WRONG);
        ServiceResponse<SolverInstance> response = serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, solverInstance);
        assertFailure(response, String.format(CREATING_SOLVER_FACTORY_ERROR, ""));
    }

    @Test
    public void createSolverWithErrorCreatingSolverFailure() {
        String internalError = "An error was produced";
        doThrow(new RuntimeException(internalError))
                .when(serviceBase)
                .newSolver(any(SolverFactory.class));

        ServiceResponse<SolverInstance> response = serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, solverInstance);
        assertBuildFactoryWasInvoked(null);
        assertFailure(response, String.format(CREATING_SOLVER_FACTORY_ERROR, internalError));
    }

    @Test
    public void createSolverWithSolverAlreadyExistsFailure() {
        doReturn(solver).when(serviceBase).newSolver(any(SolverFactory.class));

        serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, solverInstance);
        assertBuildFactoryWasInvoked(null);

        ServiceResponse<SolverInstance> response = serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, solverInstance);
        assertFailure(response, String.format(SOLVER_ALREADY_EXISTS_ERROR, SOLVER_ID, CONTAINER_ID));
    }

    @Test
    public void createSolverWithNoScanSetSuccessful() {
        doReturn(solver).when(serviceBase).newSolver(any(SolverFactory.class));

        ServiceResponse<SolverInstance> response = serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, solverInstance);
        assertBuildFactoryWasInvoked(null);
        assertSuccess(response, String.format(SOLVER_CREATED_SUCCESSFULLY_MESSAGE, SOLVER_ID, CONTAINER_ID));
    }

    @Test
    public void createSolverWithGlobalScanSetSuccessful() {
        solverInstance.setSolverConfigFile(SOLVER_CONFIG_GLOBAL_SCAN_SET);
        doReturn(solver).when(serviceBase).newSolver(any(SolverFactory.class));

        ServiceResponse<SolverInstance> response = serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, solverInstance);
        assertBuildFactoryWasInvoked(Arrays.asList(TestConfigProvider1.PACKAGE1,
                                                   TestConfigProvider1.PACKAGE2,
                                                   TestConfigProvider1.PACKAGE3,
                                                   TestConfigProvider2.PACKAGE1));
        assertSuccess(response, String.format(SOLVER_CREATED_SUCCESSFULLY_MESSAGE, SOLVER_ID, CONTAINER_ID));
    }

    @Test
    public void createSolverWithFilteredScanSetSuccessful() {
        solverInstance.setSolverConfigFile(SOLVER_CONFIG_FILTERED_SCAN_SET);
        doReturn(solver).when(serviceBase).newSolver(any(SolverFactory.class));

        ServiceResponse<SolverInstance> response = serviceBase.createSolver(CONTAINER_ID, SOLVER_ID, solverInstance);
        assertBuildFactoryWasInvoked(Collections.singletonList(PRE_CONFIGURED_PACKAGE_INCLUDE),
                                     Arrays.asList(TestConfigProvider1.PACKAGE1,
                                                   TestConfigProvider1.PACKAGE2,
                                                   TestConfigProvider1.PACKAGE3,
                                                   TestConfigProvider2.PACKAGE1,
                                                   PRE_CONFIGURED_PACKAGE_EXCLUDE));
        assertSuccess(response, String.format(SOLVER_CREATED_SUCCESSFULLY_MESSAGE, SOLVER_ID, CONTAINER_ID));
    }

    private void assertFailure(ServiceResponse<SolverInstance> response, String messagePrefix) {
        assertThat(response.getType()).isEqualTo(ServiceResponse.ResponseType.FAILURE);
        assertThat(response.getMsg()).startsWith(messagePrefix);
    }

    private void assertSuccess(ServiceResponse<SolverInstance> response, String messagePrefix) {
        assertThat(response.getType()).isEqualTo(ServiceResponse.ResponseType.SUCCESS);
        assertThat(response.getMsg()).startsWith(messagePrefix);
    }

    private void assertBuildFactoryWasInvoked(List<String> expectedExcludedPackages) {
        assertBuildFactoryWasInvoked(null, expectedExcludedPackages);
    }

    private void assertBuildFactoryWasInvoked(List<String> expectedIncludedPackages, List<String> expectedExcludedPackages) {
        verify(serviceBase).newSolver(solverFactory.capture());
        ScanAnnotatedClassesConfig config = solverFactory.getValue().getSolverConfig().getScanAnnotatedClassesConfig();
        if (expectedExcludedPackages != null) {
            assertThat(config).isNotNull();
            assertThat(config.getPackageExcludeList())
                    .containsExactlyInAnyOrder(expectedExcludedPackages.toArray(new String[0]));
        } else {
            assertThat(config).isNull();
        }
        if (expectedIncludedPackages != null) {
            assertThat(config).isNotNull();
            assertThat(config.getPackageIncludeList())
                    .containsExactlyInAnyOrder(expectedIncludedPackages.toArray(new String[0]));
        }
    }
}


text:
<?php

use Base\Pedidos as BasePedidos;

/**
 * Skeleton subclass for representing a row from the 'pedidos' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 */
class Pedidos extends BasePedidos
{

}


text:
- Is app engine up? If not, just have to sit tight. You can check the status
here: [https://code.google.com/status/appengine](https://code.google.com/status/appengine)
- Check the [main app engine dashboard page](https://console.developers.google.com/appengine?project=chromeperf&moduleId=default).
- Are we over quota?
- Look at the error rates on the dashboard.
- Check the task queues.
- Test data not showing up
  - Check [/new\_tests](https://chromeperf.appspot.com/new_tests).
  - Search the logs
  - Is the test internal-only and the user is logged out?

## Handling stackdriver alerts

We use stackdriver monitoring to check if the dashboard is running as expected.
When you get an alert mail from stackdriver, you should do the following:

**Understand what alerted**, and find the relevant code. We have two main types
of alerts:

1. **Metric Absence on Custom Metrics**. When we have some piece of code which
   absolutely must run regularly, we call `utils.TickMonitoringCustomMetric`
   every time the code completes. If that call is **not** made, it generally
   means the code failed, and we send an alert. You'll want to search the code
   for the call to tick the metric with that name, so you can understand where
   the likely failure is.
2. **Metric Threshold on Task Queue new-points-queue**. When this happens, we are
   seeing too many errors adding data to the datastore in `add_point_queue.py`.

**Analyze the logs for errors**. Once you have a basic idea what codepath is
failing, you'll want to look at the logs. There are two main entry points for
this:

1. **[Error Reporting Page](http://go/chromeperf-errors)**. This page
   lists common errors that have occurred recently, grouped together. You'll
   want to look out especially for ones marked `NEW ERROR`. Click through to
   look at callstacks and relevant logs.
2. **[Logs page](http://go/chromeperf-logs)**. This page allows you to search
   all the logs. You'll want to try and find log entries on the URLs where the
   problem occurred.
   ([Logs page help](https://cloud.google.com/logging/docs/view/logs_viewer))

**File a bug and follow up**. The bug should be labeled `P0`, `Perf Dashboard`,
`Bug`. If it is clear the problem is with bisect, add that label as well. Reply
to the email and link the bug, and update the bug with your findings as you
understand the problem better.

## Scheduled downtime

If it's necessary at some point to have scheduled downtime, announce
it ahead of time. At least 2 days before the downtime (ideally more),
announce in these ways:

 1. Send an email to any Chromium perf sheriffs who will be affected,
    or all perf sheriffs (`perf-sheriffs@chromium.org`).
 2. Send an email to `chrome-perf-dashboard-announce@google.com`.

If possible, it's probably best to schedule it for Saturday, when usage
is likely to be relatively low.

## Routine tasks

There are several routine tasks to do to set up the dashboard for a
user. The official process for this is to file bugs on crbug.com
with labels:

- `Performance-Dashboard-IPWhitelist`
- `Performance-Dashboard-BotWhitelist`
- `Performance-Dashboard-MonitoringRequest`

### Editing sheriff rotations

You can view, create and edit sheriff rotations
at [/edit\_sheriffs](https://chromeperf.appspot.com/edit_sheriffs).

#### Adding a new sheriff

It's fine to add a new sheriff rotation any time a team wants alerts
to go to a new email address. It's fine to make a temporary sheriff
rotation for monitoring new tests before they are stable. Here are the
fields that need to be filled out:

 - **Name**: This is the name of the sheriff
   rotation. It will be listed in the drop-down
   at [/alerts](https://chromeperf.appspot.com/alerts).
 - **Rotation URL**: Some sheriff rotations have a URL for specifying
   the email of the sheriff. For example, the Chromium Perf Sheriff URL
   is [http://chromium-build.appspot.com/p/chromium/sheriff\_perf.js](http://chromium-build.appspot.com/p/chromium/sheriff_perf.js).
   Most sheriff rotations don't have a URL, and if not it's fine to leave
   this blank and just specify an email address.
 - **Notification Email**:
   This is usually a mailing list that alerts should go to. However,
   there's nothing stopping it from being an individual's email
   account. It must be specified if there is no Rotation URL, but it's
   optional otherwise.
 - **Internal-only**: If the tests this sheriff is monitoring are internal-only,
   or the name of the sheriff rotation is sensitive, please
   set this to "Yes". If set to "Yes", the sheriff rotation will only
   show up on the alerts page for users logged in with google.com accounts.
 - **Summarize Email**: By default, the perf dashboard sends one email
   for each alert, as soon as it gets the alert. If that will add up to
   too much mail, setting this to "Yes" will switch to a daily summary.

#### Monitoring tests

After creating a sheriffing rotation, you need to add the individual
tests to monitor. You do this by clicking on "Set a sheriff for a
group of tests". It asks for a pattern. Patterns match test paths,
which are of the form "Master/Bot/test-suite/graph/trace". You can replace
any part of the test path with a `*` for a wildcard.

The dashboard will list the matching tests before allowing you to apply
the pattern, so you'll be able to check if the pattern is correct.

To remove a pattern, click "Remove a sheriff from a group of tests".

If you want to keep alerting on most of the tests in a pattern and
just disable alerting on a few noisy ones, you can add the "Disable
Alerting" anomaly threshold config to the noisy tests (see "Modify
anomaly threshold configs" below).

### Setting up alert threshold configs

The default alert thresholds should work reasonably well for most test
data, but there are some graphs for which it may not be correct. If
there are invalid alerts, or the dashboard is not sending alerts when
you expect them, you may want to modify an alert threshold config.

To edit alert threshold configs, go
to [/edit\_anomaly\_configs](https://chromeperf.appspot.com/edit_anomaly_configs).
Add a new config with a descriptive name and a JSON mapping of parameters
to values.

### Anomaly config debugger page

Start off by using the anomaly threshold debugging
page: [/debug\_alert](https://chromeperf.appspot.com/debug_alert). The
page shows the segmentation of the data that was given by the anomaly
finding algorithm. Based on the documentation, change the config
parameters to get the alerts where you want them.

### Automatically applying labels to bugs

The dashboard can automatically apply labels to bugs filed on alerts,
based on which test triggered the alert. This is useful for flagging
the relevant teams attention. For example, the dashboard automatically
applies the label "Cr-Blink-JavaScript" to dromaeo regressions,
which cuts down on a lot of CC-ing by hand.

To make a label automatically applied to a bug, go
to [/edit\_sheriffs](https://chromeperf.appspot.com/edit_sheriffs) and
click "Set a bug lable to automatically apply to a group of
tests". Then type in a pattern as described in "Edit Sheriff
Rotations -> Monitoring Tests" section above, and type in the bug
label. You'll see a list of tests the label will be applied to before
you confirm.

To remove a label, go
to [/edit\_sheriffs](https://chromeperf.appspot.com/edit_sheriffs) and
click "Remove a bug label that automatically applies to a group of
tests".

### Migrating and renaming data

When a test name changes, it is possible to migrate
the existing test data to use the new name. You
can do this by entering a pattern for the test name
at [/migrate\_test\_names](https://chromeperf.appspot.com/migrate_test_names).

### Whitelisting senders of data

There are two types of whitelisting on the perf dashboard:

The IP whitelist is a list of IP addresses of machines which
are allowed to post data to /add\_point. This is to prevent
/add\_point from being spammed. You can add a bot to the IP whitelist
at [/ip\_whitelist](https://chromeperf.appspot.com/ip_whitelist). If
you're seeing 403 errors on your buildbots, the IPs to add are likely
already in the logs. Note that if you are seeing 500 errors, those are
not related to IP whitelisting. They are usually caused by an error in
the JSON data sent by the buildbot. If you can't tell by looking at
the JSON data what is going wrong, the easiest thing to do is to add a
unit test with the JSON to `add_point_test.py` and debug it from there.

The bot whitelist is a list of bot names which are publicly visible. If a
bot is not on the list, users must be logged into google.com accounts to
see the data for that bot. You can add or remove a bot from the whitelist
using the dev console by importing `dashboard.change_internal_only`.


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">admin123</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/my_schema</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping class="com.mkyong.common.Stock"></mapping>
    </session-factory>
</hibernate-configuration>


text:
require 'net/ftp'
require 'csv'

module Silverpop
  module Util
    class << self

      def upload_xml_and_csv(host, username, password, xml_filename, xml_content, csv_filename, csv_lines)
        xml_file = Tempfile.new(xml_filename)
        csv_file = Tempfile.new(csv_filename)
        begin
          xml_file.write(xml_content)
          xml_file.rewind
          CSV.open(csv_file, "wb") do |csv|
            csv_lines.each { |line| csv << line }
          end
          dir = '/upload/'
          Net::SFTP.start(host, username, {password: password}) do |sftp|
            sftp.upload!(xml_file.path, File.join(dir, xml_filename))
            sftp.upload!(csv_file.path, File.join(dir, csv_filename))
          end
        ensure
          xml_file.close!
          csv_file.close!
        end
      end

      def wait_for_job_completion(client, job_id, retries = 3, timeout = 1)
        response = client.get_job_status(job_id)
        raise Silverpop::JobResultError unless response.success
        status = response.result['JOB_STATUS']
        while response.success && status != 'COMPLETE'
          raise Silverpop::JobCannotComplete unless ['WAITING', 'RUNNING'].include?(status)
          raise Silverpop::LimitExceeded if retries <= 0
          sleep timeout
          response = client.get_job_status(job_id)
          status = response.result['JOB_STATUS']
          retries -= 1
        end
        true
      end
    end
  end
end


text: Programas


text:
'use strict';

(function() {
	// Accounts Controller Spec
	describe('Accounts Controller Tests', function() {
		// Initialize global variables
		var AccountsController,
		scope,
		$httpBackend,
		$stateParams,
		$location;

		// The $resource service augments the response object with methods for updating and deleting the resource.
		// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
		// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
		// When the toEqualData matcher compares two objects, it takes only object properties into
		// account and ignores methods.
		beforeEach(function() {
			jasmine.addMatchers({
				toEqualData: function(util, customEqualityTesters) {
					return {
						compare: function(actual, expected) {
							return {
								pass: angular.equals(actual, expected)
							};
						}
					};
				}
			});
		});

		// Then we can start by loading the main application module
		beforeEach(module(ApplicationConfiguration.applicationModuleName));

		// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
		// This allows us to inject a service but then attach it to a variable
		// with the same name as the service.
		beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
			// Set a new global scope
			scope = $rootScope.$new();

			// Point global variables to injected services
			$stateParams = _$stateParams_;
			$httpBackend = _$httpBackend_;
			$location = _$location_;

			// Initialize the Accounts controller.
			AccountsController = $controller('AccountsController', {
				$scope: scope
			});
		}));

		it('$scope.find() should create an array with at least one Account object fetched from XHR', inject(function(Accounts) {
			// Create sample Account using the Accounts service
			var sampleAccount = new Accounts({
				name: 'New Account'
			});

			// Create a sample Accounts array that includes the new Account
			var sampleAccounts = [sampleAccount];

			// Set GET response
			$httpBackend.expectGET('accounts').respond(sampleAccounts);

			// Run controller functionality
			scope.find();
			$httpBackend.flush();

			// Test scope value
			expect(scope.accounts).toEqualData(sampleAccounts);
		}));

		it('$scope.findOne() should create an array with one Account object fetched from XHR using a accountId URL parameter', inject(function(Accounts) {
			// Define a sample Account object
			var sampleAccount = new Accounts({
				name: 'New Account'
			});

			// Set the URL parameter
			$stateParams.accountId = '525a8422f6d0f87f0e407a33';

			// Set GET response
			$httpBackend.expectGET(/accounts\/([0-9a-fA-F]{24})$/).respond(sampleAccount);

			// Run controller functionality
			scope.findOne();
			$httpBackend.flush();

			// Test scope value
			expect(scope.account).toEqualData(sampleAccount);
		}));

		it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Accounts) {
			// Create a sample Account object
			var sampleAccountPostData = new Accounts({
				name: 'New Account'
			});

			// Create a sample Account response
			var sampleAccountResponse = new Accounts({
				_id: '525cf20451979dea2c000001',
				name: 'New Account'
			});

			// Fixture mock form input values
			scope.name = 'New Account';

			// Set POST response
			$httpBackend.expectPOST('accounts', sampleAccountPostData).respond(sampleAccountResponse);

			// Run controller functionality
			scope.create();
			$httpBackend.flush();

			// Test form inputs are reset
			expect(scope.name).toEqual('');

			// Test URL redirection after the Account was created
			expect($location.path()).toBe('/accounts/' + sampleAccountResponse._id);
		}));

		it('$scope.update() should update a valid Account', inject(function(Accounts) {
			// Define a sample Account put data
			var sampleAccountPutData = new Accounts({
				_id: '525cf20451979dea2c000001',
				name: 'New Account'
			});

			// Mock Account in scope
			scope.account = sampleAccountPutData;

			// Set PUT response
			$httpBackend.expectPUT(/accounts\/([0-9a-fA-F]{24})$/).respond();

			// Run controller functionality
			scope.update();
			$httpBackend.flush();

			// Test URL location to new object
			expect($location.path()).toBe('/accounts/' + sampleAccountPutData._id);
		}));

		it('$scope.remove() should send a DELETE request with a valid accountId and remove the Account from the scope', inject(function(Accounts) {
			// Create new Account object
			var sampleAccount = new Accounts({
				_id: '525a8422f6d0f87f0e407a33'
			});

			// Create new Accounts array and include the Account
			scope.accounts = [sampleAccount];

			// Set expected DELETE response
			$httpBackend.expectDELETE(/accounts\/([0-9a-fA-F]{24})$/).respond(204);

			// Run controller functionality
			scope.remove(sampleAccount);
			$httpBackend.flush();

			// Test array after successful delete
			expect(scope.accounts.length).toBe(0);
		}));
	});
}());


text:
import React from 'react';
import ReactTHREE from 'react-three';
import THREE from 'three';
import Constants from '../constants';
import RobotRobbyComponent from './models/robotRobby';
import RobotMechComponent from './models/robotMech';

const ROBOT_ROBBY_Y = -25,
      ROBOT_MECH_Y = 0;

class SceneComponent extends React.Component {

    constructor(props) {

        super(props);

        this.state = {
            modelPosition: new THREE.Vector3(0,0,0),
            modelRotation: 0
        };

        this._animate = this._animate.bind(this);
    }

    componentDidMount() {

        // Kick off animation
        this._animate();

    }

    render() {

        let x = this.state.modelPosition.x,
            y = this.state.modelPosition.y,
            z = this.state.modelPosition.z;

        // Adjust relative positions
        let robotRobbyPosition = new THREE.Vector3( x, y + ROBOT_ROBBY_Y, z ),
            robotMechPosition = new THREE.Vector3( x, y + ROBOT_MECH_Y, z );

        let modelEuler = new THREE.Euler(0, this.state.modelRotation),
            modelQuaternion = new THREE.Quaternion().setFromEuler(modelEuler);

        let CameraElement = React.createElement(
            ReactTHREE.PerspectiveCamera,   // type
            {                               // config
                name: 'camera',
                fov: 75,
                aspect: window.innerWidth / window.innerHeight,
                near: 1,
                far: 1000,
                position: new THREE.Vector3(0, 0, 50),
                lookat: new THREE.Vector3(0, 0, 0)
            }
        );

        let RobotRobbyElement = React.createElement(
            RobotRobbyComponent,
            {
                position: robotRobbyPosition,
                quaternion: modelQuaternion,
                visible: (this.props.robot === Constants.ROBOT.ROBBY),
                scale: 7
            }
        );

        let RobotMechElement = React.createElement(
            RobotMechComponent,
            {
                position: robotMechPosition,
                quaternion: modelQuaternion,
                visible: (this.props.robot === Constants.ROBOT.MECH),
                scale: 5
            }
        );

        let AmbientLight = React.createElement(
            ReactTHREE.AmbientLight,
            {
                color: new THREE.Color(0x333333),
                intensity: 0.5,
                target: new THREE.Vector3(0, 0, 0)
            }
        );

        let DirectionalLight = React.createElement(
            ReactTHREE.DirectionalLight,
            {
                color: new THREE.Color(0xFFFFFF),
                intensity: 1.5,
                position: new THREE.Vector3(0, 0, 60)
            }
        );

        return React.createElement(
            ReactTHREE.Scene,
            {
                width: window.innerWidth,
                height: window.innerHeight,
                camera: 'camera',
                antialias: true,
                background: 0xEEEEEE
            },
            CameraElement,
            RobotRobbyElement,
            RobotMechElement,
            AmbientLight,
            DirectionalLight
        )
    }

    _animate() {

        let spinAmount = this.props.spinSpeed * Constants.SPIN_SPEED_MULTIPLIER;

        this.setState({modelRotation: this.state.modelRotation +
        (this.props.spinDirection === Constants.SPIN.LEFT ? spinAmount : -spinAmount)});

        requestAnimationFrame(this._animate);

    }

}

export default SceneComponent;


text:
package wsbench;

import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.eclipse.jetty.websocket.api.Session;

import java.io.IOException;

public class TestWebSocketServlet extends WebSocketServlet {

  @Override
  public void configure(WebSocketServletFactory factory) {
    factory.register(EventSocket.class);
  }
}

class EventSocket extends WebSocketAdapter {

  protected Session session;

  @Override
  public void onWebSocketConnect(Session session) {
    this.session = session;
  }

  @Override
  public void onWebSocketText(String message) {
    try {
      session.getRemote().sendString(message);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}


text:
// Defines the GpuTimer type - the CUDA-specific implementation of the generic
// StreamExecutor Timer interface.

#ifndef TENSORFLOW_COMPILER_XLA_STREAM_EXECUTOR_CUDA_CUDA_TIMER_H_
#define TENSORFLOW_COMPILER_XLA_STREAM_EXECUTOR_CUDA_CUDA_TIMER_H_

#include "tensorflow/compiler/xla/stream_executor/gpu/gpu_timer.h"

namespace stream_executor {
namespace cuda {

using CUDATimer = gpu::GpuTimer;

}  // namespace cuda
}  // namespace stream_executor

#endif  // TENSORFLOW_COMPILER_XLA_STREAM_EXECUTOR_CUDA_CUDA_TIMER_H_


text:
"use strict";
exports.__esModule = true;
exports.hello = void 0;
function hello() { }
exports.hello = hello;


text:
class AddAllowWebSubmitsFieldToAssignmentsTable < ActiveRecord::Migration
  def self.up
    add_column :assignments, :allow_web_submits, :boolean, :default => true
  end

  def self.down
    remove_column :assignments, :allow_web_submits
  end
end


text:
package com.baidu.rigel.biplatform.ma.resource;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baidu.rigel.biplatform.ac.util.PropertiesFileUtils;
import com.baidu.rigel.biplatform.ma.report.utils.ContextManager;
import com.google.gson.Gson;

/**
 * 配置文件刷新
 *
 * @author luowenlei
 *
 *         2015-11-03
 */
@RestController
@RequestMapping("/silkroad/properties")
public class PropertiesFileResource extends BaseResource {

    /**
     * logger
     */
    private Logger logger = LoggerFactory.getLogger(PropertiesFileResource.class);

    /**
     * 刷新配置文件
     *
     * @param request
     * @return ResponseResult
     */
    @RequestMapping(value = "/refresh", method = { RequestMethod.GET })
    public ResponseResult refreshProperties(HttpServletRequest request) {
        PropertiesFileUtils.readPropertiesFile();
        ResponseResult responseResult = new ResponseResult();
        responseResult.setData("success");
        responseResult.setStatus(0);
        responseResult.setStatusInfo("success");
        logger.info("productline:{} propertiesFile:{} refreshed properties file。",
                ContextManager.getProductLine(), new Gson().toJson(PropertiesFileUtils.propertiesMap));
        return responseResult;
    }

}


text:
//
//  ASAlbum.h
//  yeti
//
//  Created by Charles Morss on 1/7/13.
//  Copyright (c) 2013 Audiosocket. All rights reserved.
//

#import "ASObject.h"
#import "ASPaginator.h"

/**
* Album containing ASTrack instances for a particular artist.
*/

@interface ASAlbum : ASObject

/**
* Collection of tracks on this ASAlbum. The method loadTracksWithSuccess:failure:
* is used to create and populate this attribute.
*/

@property(nonatomic) ASPaginator *tracks;

/**
* Issue a request to load the paginated collection of ASTrack instances
* belonging to this ASAlbum.
*
* @param success Callback to invoke when the request to load tracks has been
*                successful. 'self' instance of ASAlbum is passed to the block.
*
* @param failure Callback to invoke when an error has occurred.
*
* @return        this.tracks. Note: when first returned this paginator is not
*                very useful. However after the success callback has been invoked
*                you may then access the objects fetched as well as page through
*                to additional results.
*/

- (ASPaginator *)loadTracksWithSuccess:(void (^)(ASAlbum * album))success
                               failure:(void (^)(NSError *))failure;

@end


text:
from collections import OrderedDict
import functools
import re
from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union

from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.api_core.client_options import ClientOptions
from google.auth import credentials as ga_credentials  # type: ignore
from google.oauth2 import service_account  # type: ignore
import pkg_resources

try:
    OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError:  # pragma: NO COVER
    OptionalRetry = Union[retries.Retry, object]  # type: ignore

from google.api_core import operation  # type: ignore
from google.api_core import operation_async  # type: ignore

from google.cloud.retail_v2beta.types import completion_service, import_config

from .client import CompletionServiceClient
from .transports.base import DEFAULT_CLIENT_INFO, CompletionServiceTransport
from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport

class CompletionServiceAsyncClient:
    """Auto-completion service for retail.
    This feature is only available for users who have Retail Search
    enabled. Enable Retail Search on Cloud Console before using this
    feature.
    """

    _client: CompletionServiceClient

    DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT
    DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT

    catalog_path = staticmethod(CompletionServiceClient.catalog_path)
    parse_catalog_path = staticmethod(CompletionServiceClient.parse_catalog_path)
    common_billing_account_path = staticmethod(
        CompletionServiceClient.common_billing_account_path
    )
    parse_common_billing_account_path = staticmethod(
        CompletionServiceClient.parse_common_billing_account_path
    )
    common_folder_path = staticmethod(CompletionServiceClient.common_folder_path)
    parse_common_folder_path = staticmethod(
        CompletionServiceClient.parse_common_folder_path
    )
    common_organization_path = staticmethod(
        CompletionServiceClient.common_organization_path
    )
    parse_common_organization_path = staticmethod(
        CompletionServiceClient.parse_common_organization_path
    )
    common_project_path = staticmethod(CompletionServiceClient.common_project_path)
    parse_common_project_path = staticmethod(
        CompletionServiceClient.parse_common_project_path
    )
    common_location_path = staticmethod(CompletionServiceClient.common_location_path)
    parse_common_location_path = staticmethod(
        CompletionServiceClient.parse_common_location_path
    )

    @classmethod
    def from_service_account_info(cls, info: dict, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            info.

        Args:
            info (dict): The service account private key info.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            CompletionServiceAsyncClient: The constructed client.
        """
        return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs)  # type: ignore

    @classmethod
    def from_service_account_file(cls, filename: str, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            CompletionServiceAsyncClient: The constructed client.
        """
        return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs)  # type: ignore

    from_service_account_json = from_service_account_file

    @classmethod
    def get_mtls_endpoint_and_cert_source(
        cls, client_options: Optional[ClientOptions] = None
    ):
        """Return the API endpoint and client cert source for mutual TLS.

        The client cert source is determined in the following order:
        (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
        client cert source is None.
        (2) if `client_options.client_cert_source` is provided, use the provided one; if the
        default client cert source exists, use the default one; otherwise the client cert
        source is None.

        The API endpoint is determined in the following order:
        (1) if `client_options.api_endpoint` if provided, use the provided one.
        (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
        default mTLS endpoint; if the environment variabel is "never", use the default API
        endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
        use the default API endpoint.

        More details can be found at https://google.aip.dev/auth/4114.

        Args:
            client_options (google.api_core.client_options.ClientOptions): Custom options for the
                client. Only the `api_endpoint` and `client_cert_source` properties may be used
                in this method.

        Returns:
            Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
                client cert source to use.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If any errors happen.
        """
        return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options)  # type: ignore

    @property
    def transport(self) -> CompletionServiceTransport:
        """Returns the transport used by the client instance.

        Returns:
            CompletionServiceTransport: The transport used by the client instance.
        """
        return self._client.transport

    get_transport_class = functools.partial(
        type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)
    )

    def __init__(
        self,
        *,
        credentials: ga_credentials.Credentials = None,
        transport: Union[str, CompletionServiceTransport] = "grpc_asyncio",
        client_options: ClientOptions = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
    ) -> None:
        """Instantiates the completion service client.

        Args:
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            transport (Union[str, ~.CompletionServiceTransport]): The
                transport to use. If set to None, a transport is chosen
                automatically.
            client_options (ClientOptions): Custom options for the client. It
                won't take effect if a ``transport`` instance is provided.
                (1) The ``api_endpoint`` property can be used to override the
                default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
                environment variable can also be used to override the endpoint:
                "always" (always use the default mTLS endpoint), "never" (always
                use the default regular endpoint) and "auto" (auto switch to the
                default mTLS endpoint if client certificate is present, this is
                the default value). However, the ``api_endpoint`` property takes
                precedence if provided.
                (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
                is "true", then the ``client_cert_source`` property can be used
                to provide client certificate for mutual TLS transport. If
                not provided, the default SSL client certificate will be used if
                present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
                set, no client certificate will be used.

        Raises:
            google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
                creation failed for any reason.
        """
        self._client = CompletionServiceClient(
            credentials=credentials,
            transport=transport,
            client_options=client_options,
            client_info=client_info,
        )

    async def complete_query(
        self,
        request: Union[completion_service.CompleteQueryRequest, dict] = None,
        *,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> completion_service.CompleteQueryResponse:
        r"""Completes the specified prefix with keyword
        suggestions.
        This feature is only available for users who have Retail
        Search enabled. Enable Retail Search on Cloud Console
        before using this feature.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import retail_v2beta

            async def sample_complete_query():
                # Create a client
                client = retail_v2beta.CompletionServiceAsyncClient()

                # Initialize request argument(s)
                request = retail_v2beta.CompleteQueryRequest(
                    catalog="catalog_value",
                    query="query_value",
                )

                # Make the request
                response = await client.complete_query(request=request)

                # Handle the response
                print(response)

        Args:
            request (Union[google.cloud.retail_v2beta.types.CompleteQueryRequest, dict]):
                The request object. Auto-complete parameters.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.cloud.retail_v2beta.types.CompleteQueryResponse:
                Response of the auto-complete query.
        """
        # Create or coerce a protobuf request object.
        request = completion_service.CompleteQueryRequest(request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.complete_query,
            default_timeout=None,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("catalog", request.catalog),)),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    async def import_completion_data(
        self,
        request: Union[import_config.ImportCompletionDataRequest, dict] = None,
        *,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> operation_async.AsyncOperation:
        r"""Bulk import of processed completion dataset.
        Request processing is asynchronous. Partial updating is
        not supported.
        The operation is successfully finished only after the
        imported suggestions are indexed successfully and ready
        for serving. The process takes hours.
        This feature is only available for users who have Retail
        Search enabled. Enable Retail Search on Cloud Console
        before using this feature.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import retail_v2beta

            async def sample_import_completion_data():
                # Create a client
                client = retail_v2beta.CompletionServiceAsyncClient()

                # Initialize request argument(s)
                input_config = retail_v2beta.CompletionDataInputConfig()
                input_config.big_query_source.dataset_id = "dataset_id_value"
                input_config.big_query_source.table_id = "table_id_value"

                request = retail_v2beta.ImportCompletionDataRequest(
                    parent="parent_value",
                    input_config=input_config,
                )

                # Make the request
                operation = client.import_completion_data(request=request)

                print("Waiting for operation to complete...")

                response = await operation.result()

                # Handle the response
                print(response)

        Args:
            request (Union[google.cloud.retail_v2beta.types.ImportCompletionDataRequest, dict]):
                The request object. Request message for
                ImportCompletionData methods.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.api_core.operation_async.AsyncOperation:
                An object representing a long-running operation.

                The result type for the operation will be :class:`google.cloud.retail_v2beta.types.ImportCompletionDataResponse` Response of the
                   [ImportCompletionDataRequest][google.cloud.retail.v2beta.ImportCompletionDataRequest].
                   If the long running operation is done, this message
                   is returned by the
                   google.longrunning.Operations.response field if the
                   operation is successful.

        """
        # Create or coerce a protobuf request object.
        request = import_config.ImportCompletionDataRequest(request)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.import_completion_data,
            default_timeout=None,
            client_info=DEFAULT_CLIENT_INFO,
        )

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Wrap the response in an operation future.
        response = operation_async.from_gapic(
            response,
            self._client._transport.operations_client,
            import_config.ImportCompletionDataResponse,
            metadata_type=import_config.ImportMetadata,
        )

        # Done; return the response.
        return response

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc, tb):
        await self.transport.close()

try:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
        gapic_version=pkg_resources.get_distribution(
            "google-cloud-retail",
        ).version,
    )
except pkg_resources.DistributionNotFound:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()

__all__ = ("CompletionServiceAsyncClient",)


text:
/**
 *
 */
package com.github.nnest.arcteryx.event;

/**
 * Component registration event listener
 *
 * @author brad.wu
 */
public interface IResourceRegistrationEventListener extends IResourceEventListener {
	/**
	 * resource will register
	 *
	 * @param evt
	 */
	void resourceWillRegister(ResourceRegistrationEvent evt);

	/**
	 * resource did register
	 *
	 * @param evt
	 */
	void resourceDidRegister(ResourceRegistrationEvent evt);

	/**
	 * resource should unregister
	 *
	 * @param evt
	 */
	void resourceShouldUnregister(ResourceRegistrationEvent evt);

	/**
	 * resource will unregister
	 *
	 * @param evt
	 *
	 */
	void resourceWillUnregister(ResourceRegistrationEvent evt);

	/**
	 * resource did unregister
	 *
	 * @param evt
	 */
	void resourceDidUnregister(ResourceRegistrationEvent evt);
}


text: module.exports = require("npm:domelementtype@1.3.0/index.js");


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

import java.math.*;

import javax.annotation.Generated;

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

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

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

    public RouteTableIdentifier unmarshall(JsonUnmarshallerContext context) throws Exception {
        RouteTableIdentifier routeTableIdentifier = new RouteTableIdentifier();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("TransitGatewayRouteTableArn", targetDepth)) {
                    context.nextToken();
                    routeTableIdentifier.setTransitGatewayRouteTableArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("CoreNetworkSegmentEdge", targetDepth)) {
                    context.nextToken();
                    routeTableIdentifier.setCoreNetworkSegmentEdge(CoreNetworkSegmentEdgeIdentifierJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return routeTableIdentifier;
    }

    private static RouteTableIdentifierJsonUnmarshaller instance;

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


text:
using System;
using System.Linq;
using Jurassic.Library;
using ExoWeb.Templates.JavaScript;

namespace ExoWeb.Templates.MicrosoftAjax
{
	/// <summary>
	/// Represents a toggle control for conditionally rendering content.
	/// </summary>
	internal class Toggle : Control
	{
		private Binding className;

		/// <summary>
		/// Gets or sets the value that will be toggled on
		/// </summary>
		public Binding On { get; internal set; }

		/// <summary>
		/// When using addClass/removeClass mode, gets or sets
		/// the value of the css class that will be added or removed
		/// </summary>
		public Binding ClassName
		{
			get { return className; }
			internal set
			{
				if (value != null)
				{
					if (className != null)
						throw new Exception("Property toggle:classname has already been set.");

					className = value;
				}
			}
		}

		/// <summary>
		/// When using addClass/removeClass mode, gets or sets
		/// the value of the css class that will be added or removed
		/// </summary>
		public Binding Class
		{
			get { return className; }
			internal set
			{
				if (value != null)
				{
					if (className != null)
						throw new Exception("Toggle has both toggle:class and toggle:classname attributes.");

					className = value;
				}
			}
		}

		/// <summary>
		/// Gets or sets the toggling action
		/// </summary>
		public Binding Action { get; internal set; }

		/// <summary>
		/// Gets or sets the group name used by toggle group
		/// to identify this toggle as a member of a group
		/// </summary>
		public Binding GroupName { get; internal set; }

		/// <summary>
		/// Gets or sets a value indicating whether the toggle
		/// should check strictly for a boolean valuej
		/// </summary>
		public Binding StrictMode { get; internal set; }

		/// <summary>
		/// Gets or sets the logic or value that defines when the
		/// toggle is active
		/// </summary>
		public Binding When { get; internal set; }

		/// <summary>
		///
		/// </summary>
		/// <returns></returns>
		internal bool IsTemplate()
		{
			return IsTemplate(null);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="page"></param>
		/// <returns></returns>
		internal bool IsTemplate(AjaxPage page)
		{
			bool result = false;

			if (Action != null)
			{
				// action is literal render/dispose
				if (Action.Expression == "render" || Action.Expression == "dispose")
					result = true;
				else
				{
					// if not within a dataview or template, then any binding expressions
					// for toggle action would not be dependent on template context data,
					// so use the newly created page instance with a null context
					var action = Action.Evaluate(page == null ? Page.Current as AjaxPage : page);
					if (action.IsValid && (action.DisplayValue == "render" || action.DisplayValue == "dispose"))
						result = true;
				}
			}

			return result;
		}

		internal override void Abort(AjaxPage page, string[] templateNames, System.IO.TextWriter writer)
		{
			// Write out a render/dispose toggle since it will be interpreted as a template
			// and conditionally render.  Otherwise, the content within the toggle is not affected
			// by the toggle from a rendering perspective.
			if (IsTemplate(page))
				base.Abort(page, templateNames, writer);
			else
			{
				AttributeBinding contentTemplateBinding;
				if (!TryContentTemplate(page, templateNames, writer, out contentTemplateBinding))
				{
					base.Abort(page, templateNames, writer);
					return;
				}

				var ownTemplateNames = contentTemplateBinding != null ?
					((string) contentTemplateBinding.Value).Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries) :
					new string[0];

				RenderStartTag(page, writer,
					// replace data-sys-attach attribute with sys:attach and add data-continue attribute to notify client that children were allowed to render
					attributes => MergeAttribute(AbortSysAttachDataAttribute(attributes), "data-continue", value => "data-continue"),
					// abort rendering
					true,
					// pass in all binding attributes
					If == null ? null : If.Evaluate(page),
					On == null ? null : On.Evaluate(page),
					ClassName == null ? null : ClassName.Evaluate(page),
					Action == null ? null : Action.Evaluate(page),
					GroupName == null ? null : GroupName.Evaluate(page),
					StrictMode == null ? null : StrictMode.Evaluate(page),
					When == null ? null : When.Evaluate(page),
					contentTemplateBinding);

				// continue rendering child blocks in the same data context
				foreach (var block in Blocks)
					block.Render(page, templateNames.Concat(ownTemplateNames).ToArray(), writer);

				RenderEndTag(writer);
			}
		}

		internal override void Render(AjaxPage page, string[] templateNames, System.IO.TextWriter writer)
		{
			bool canRender;
			AttributeBinding ifBinding;
			if (!TryRenderIf(page, templateNames, writer, out ifBinding, out canRender))
			{
				Abort(page, templateNames, writer);
				return;
			}

			if (!canRender)
				return;

			// Output the original template if toggle on was not specified
			if (On == null)
			{
				Abort(page, templateNames, writer);
				return;
			}

			// Get the data associated with the data view
			var onBinding = On.Evaluate(page);

			// Output the original template if no data for on was found
			if (!onBinding.IsValid)
			{
				Abort(page, templateNames, writer);
				return;
			}

			var onValue = onBinding.Value;

			var classValue = "";
			var classBinding = (AttributeBinding)null;

			if (ClassName != null)
			{
				classBinding = ClassName.Evaluate(page);

				// Output the original template if no data for class was found
				if (!classBinding.IsValid)
				{
					Abort(page, templateNames, writer);
					return;
				}

				classValue = (string)classBinding.Value;
			}

			ToggleAction? actionValue;

			var actionBinding = (AttributeBinding)null;

			// Get the value of the toggle action (i.e.: show, hide, etc.)
			if (Action != null)
			{
				actionBinding = Action.Evaluate(page);

				// Output the original template if no data for action was found
				if (!actionBinding.IsValid)
				{
					Abort(page, templateNames, writer);
					return;
				}

				actionValue = (ToggleAction)Enum.Parse(typeof(ToggleAction), (string)actionBinding.Value, true);
			}
			else if (!string.IsNullOrEmpty(classValue))
				actionValue = ToggleAction.AddClass;
			else
				actionValue = ToggleAction.Show;

			var groupNameBinding = (AttributeBinding)null;

			if (GroupName != null)
			{
				groupNameBinding = GroupName.Evaluate(page);

				// Output the original template if no data for group name was found
				if (!groupNameBinding.IsValid)
				{
					Abort(page, templateNames, writer);
					return;
				}
			}

			var strictModeValue = false;
			var strictModeBinding = (AttributeBinding)null;

			if (StrictMode != null)
			{
				strictModeBinding = StrictMode.Evaluate(page);

				// Output the original template if no data for strict mode was found
				if (!strictModeBinding.IsValid)
				{
					Abort(page, templateNames, writer);
					return;
				}

				if (strictModeBinding.Value is bool)
					strictModeValue = (bool)strictModeBinding.Value;
				else
					strictModeValue = bool.Parse((string)strictModeBinding.Value);
			}

			bool? equals;

			var whenBinding = (AttributeBinding)null;

			// Evaluate whether the on and when conditions are equal or
			// satisified, which determines whether the toggle is on or off
			if (When == null)
			{
				if (strictModeValue)
				{
					// In strict mode the on value must be a boolean true
					if (!(onValue is bool))
						throw new ApplicationException(string.Format("With strict mode enabled, toggle:on should be a value of type Boolean, actual type \"{0}\".", onValue == null ? "null" : onValue.GetType().Name));

					equals = (bool) onValue;
				}
				else if (onValue is System.Collections.IEnumerable)
				{
					equals = false;

					// Satisfied if there are any items
					foreach (object o in (System.Collections.IEnumerable)onValue)
					{
						equals = true;
						break;
					}
				}
				else
				{
					// Otherwise, check to see that the on value is "truthy"
					equals = JavaScriptHelpers.IsTruthy(onValue);
				}
			}
			else
			{
				whenBinding = When.Evaluate(page);

				var whenValue = whenBinding.Value;

				if (whenValue == null)
					equals = (onValue == null);
				else if (whenValue is FunctionInstance)
				{
					object result;

					try
					{
						result = Page.ScriptMarshaller.Unwrap(((FunctionInstance)whenValue).Call(null, Page.ScriptMarshaller.Wrap(onValue)));
					}
					catch
					{
						Abort(page, templateNames, writer);
						return;
					}

					if (strictModeValue)
					{
						if (!(result is bool))
							throw new ApplicationException(string.Format("With strict mode enabled, toggle:when function should return a value of type Boolean, found type \"{0}\".", result == null ? "null" : result.GetType().Name));
						equals = (bool)result;
					}
					else
					{
						equals = JavaScriptHelpers.IsTruthy(result);
					}
				}
				else
				{
					equals = whenValue.Equals(onValue);
				}
			}

			// If no class value is defined then abort
			if ((actionValue == ToggleAction.AddClass || actionValue == ToggleAction.RemoveClass) && string.IsNullOrEmpty(classValue))
			{
				Abort(page, templateNames, writer);
				return;
			}

			bool render = actionValue == ToggleAction.Render || actionValue == ToggleAction.Dispose;

			AttributeBinding contentTemplateBinding;
			if (!TryContentTemplate(page, templateNames, writer, out contentTemplateBinding))
			{
				Abort(page, templateNames, writer);
				return;
			}

			var ownTemplateNames = contentTemplateBinding != null ?
				((string) contentTemplateBinding.Value).Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries) :
				new string[0];

			using (var context = render ? page.BeginContext(page.Context.DataItem, null) : null)
			{
				RenderStartTag(page, writer, attrs => MergeAttribute(MergeAttribute(MergeAttribute(attrs,
					"class", value =>
					{
						if (actionValue == ToggleAction.AddClass || actionValue == ToggleAction.RemoveClass)
						{
							if ((actionValue == ToggleAction.AddClass && equals.Value) || (actionValue == ToggleAction.RemoveClass && !equals.Value))
								value = AttributeHelper.EnsureClassName(value, classValue);
							else
								value = AttributeHelper.RemoveClassName(value, classValue);
						}

						// Add/remove the "toggle-on" and "toggle-off" classes based on state
						value = AttributeHelper.EnsureClassName(value, equals.Value ? "toggle-on" : "toggle-off");
						value = AttributeHelper.RemoveClassName(value, equals.Value ? "toggle-off" : "toggle-on");

						return value;
					}).ToArray(),
					"style", value =>
					{
						if (actionValue == ToggleAction.Show || actionValue == ToggleAction.Hide ||
							actionValue == ToggleAction.Render || actionValue == ToggleAction.Dispose)
						{
							if (((actionValue == ToggleAction.Show || actionValue == ToggleAction.Render) && equals.Value) ||
								((actionValue == ToggleAction.Hide || actionValue == ToggleAction.Dispose) && !equals.Value))
							{
								if (AttributeHelper.GetCssStyle(value, "display") == "none")
									value = AttributeHelper.RemoveCssStyle(value, "display");
							}
							else
								value = AttributeHelper.EnsureCssStyle(value, "display", "none");
						}

						return value;
					}).ToArray(),
					"disabled", value =>
					{
						if (actionValue == ToggleAction.Enable || actionValue == ToggleAction.Disable)
						{
							if ((actionValue == ToggleAction.Enable && equals.Value) || (actionValue == ToggleAction.Disable && !equals.Value))
								value = null;
							else
								value = "disabled";
						}

						return value;
					}), ifBinding, onBinding, classBinding, actionBinding, groupNameBinding, strictModeBinding, whenBinding, contentTemplateBinding,
					// If this is render/dispose, include the nested template index as a special attribute
					render ? new AttributeBinding(new Attribute() { Name = "data-sys-tmplidx", Value = NestedTemplateIndex.ToString() }, null) : null,
					render ? new AttributeBinding(new Attribute() { Name = "data-sys-tcindex", Value = context.Id }, null) : null);

				// Only render the inner blocks if the template would be rendered client-side
				if (!render || (actionValue == ToggleAction.Render && equals.Value) || (actionValue == ToggleAction.Dispose && !equals.Value))
				{
					foreach (var block in Blocks)
						block.Render(page, templateNames.Concat(ownTemplateNames).ToArray(), writer);
				}

				RenderEndTag(writer);
			}
		}

		public override string ToString()
		{
			return "<toggle on=\"" + On + "\" when=\"" + When + "\" strictmode=\"" + StrictMode + "\" groupname=\"" + GroupName + "\" classname=\"" + ClassName + "\" action=\"" + Action + "\" >";
		}

		/// <summary>
		/// Specifies the action that the toggle control will take
		/// depending on whether or not the condition evaulates to true.
		/// </summary>
		internal enum ToggleAction
		{
			/// <summary>
			/// The toggle element will only render if the condition passses.
			/// </summary>
			Render,

			/// <summary>
			/// The toggle element will NOT render if the condition passses.
			/// </summary>
			Dispose,

			/// <summary>
			/// The toggle element will be shown if the condition passses.
			/// </summary>
			Show,

			/// <summary>
			/// The toggle element will be hidden if the condition passses.
			/// </summary>
			Hide,

			/// <summary>
			/// Children of the toggle element will be enabled if the condition passses.
			/// </summary>
			Enable,

			/// <summary>
			/// Children of the toggle element will be disabled if the condition passses.
			/// </summary>
			Disable,

			/// <summary>
			/// The specified CSS class will be added to the toggle element if the condition passses.
			/// </summary>
			AddClass,

			/// <summary>
			/// The specified CSS class will be removed from the toggle element if the condition passses.
			/// </summary>
			RemoveClass
		}
	}
}