text:
namespace Rest4Net.BitLy.Responses
{
    public interface IAuthenticate
    {
        IAuthenticateItem Authenticate { get; }
    }

    public interface IAuthenticateItem
    {
        bool Successful { get; }
        string Username { get; }
        string ApiKey { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import {Observable, Subscription} from '@reactivex/rxjs';

export interface IMetaConfig {
  gid?: string | number;
  external?: string;
}

export interface INodeDef {
  name: string;
  type?: string;
  config?: any;
  metaConfig?: IMetaConfig;
  dataFrom?: number[] | number; // Only on non-source nodes
  id: number;
}

export interface ISourceNode {
  (config?): Observable<any>;
}

export interface ITransfNode {
  (iO: Observable<any>): Observable<any>;
  (config: Object, iO: Observable<any>): Observable<any>;
}

export interface ISinkNode {
  (iO: Observable<any>): Subscription<any>;
  (config: Object, iO: Observable<any>): Subscription<any>;
}

export interface ICoupler {
  config?: any;
  defaultName: string;
  getClient?(): any;
  from(name: string): Observable<any>;
  to(name: string, iO: Observable<any>): Subscription<any>;
}


text:
<?php

/**
 * TDbMetaData is the base class for retrieving metadata information, such as
 * table and columns information, from a database connection.
 *
 * Use the {@link getTableInfo} method to retrieve a table information.
 *
 * @author Wei Zhuo <weizho[at]gmail[dot]com>
 * @version $Id$
 * @package System.Data.Common
 * @since 3.1
 */
abstract class TDbMetaData extends TComponent
{
	private $_tableInfoCache=array();
	private $_connection;

	/**
	 * @var array
	 */
	protected static $delimiterIdentifier = array('[', ']', '"', '`', "'");

	/**
	 * @param TDbConnection database connection.
	 */
	public function __construct($conn)
	{
		$this->_connection=$conn;
	}

	/**
	 * @return TDbConnection database connection.
	 */
	public function getDbConnection()
	{
		return $this->_connection;
	}

	/**
	 * Obtain database specific TDbMetaData class using the driver name of the database connection.
	 * @param TDbConnection database connection.
	 * @return TDbMetaData database specific TDbMetaData.
	 */
	public static function getInstance($conn)
	{
		$conn->setActive(true); //must be connected before retrieving driver name
		$driver = $conn->getDriverName();
		switch(strtolower($driver))
		{
			case 'pgsql':
				Prado::using('System.Data.Common.Pgsql.TPgsqlMetaData');
				return new TPgsqlMetaData($conn);
			case 'mysqli':
			case 'mysql':
				Prado::using('System.Data.Common.Mysql.TMysqlMetaData');
				return new TMysqlMetaData($conn);
			case 'sqlite': //sqlite 3
			case 'sqlite2': //sqlite 2
				Prado::using('System.Data.Common.Sqlite.TSqliteMetaData');
				return new TSqliteMetaData($conn);
			case 'mssql': // Mssql driver on windows hosts
			case 'dblib': // dblib drivers on linux (and maybe others os) hosts
				Prado::using('System.Data.Common.Mssql.TMssqlMetaData');
				return new TMssqlMetaData($conn);
			case 'oci':
				Prado::using('System.Data.Common.Oracle.TOracleMetaData');
				return new TOracleMetaData($conn);
//			case 'ibm':
//				Prado::using('System.Data.Common.IbmDb2.TIbmDb2MetaData');
//				return new TIbmDb2MetaData($conn);
			default:
				throw new TDbException('ar_invalid_database_driver',$driver);
		}
	}

	/**
	 * Obtains table meta data information for the current connection and given table name.
	 * @param string table or view name
	 * @return TDbTableInfo table information.
	 */
	public function getTableInfo($tableName=null)
	{
		$key = $tableName===null?$this->getDbConnection()->getConnectionString():$tableName;
		if(!isset($this->_tableInfoCache[$key]))
		{
			$class = $this->getTableInfoClass();
			$tableInfo = $tableName===null ? new $class : $this->createTableInfo($tableName);
			$this->_tableInfoCache[$key] = $tableInfo;
		}
		return $this->_tableInfoCache[$key];
	}

	/**
	 * Creates a command builder for a given table name.
	 * @param string table name.
	 * @return TDbCommandBuilder command builder instance for the given table.
	 */
	public function createCommandBuilder($tableName=null)
	{
		return $this->getTableInfo($tableName)->createCommandBuilder($this->getDbConnection());
	}

	/**
	 * This method should be implemented by decendent classes.
	 * @return TDbTableInfo driver dependent create builder.
	 */
	abstract protected function createTableInfo($tableName);

	/**
	 * @return string TDbTableInfo class name.
	 */
	protected function getTableInfoClass()
	{
		return 'TDbTableInfo';
	}

	/**
	 * Quotes a table name for use in a query.
	 * @param string $name table name
	 * @param string $lft left delimiter
	 * @param string $rgt right delimiter
	 * @return string the properly quoted table name
	 */
	public function quoteTableName($name)
	{
		$name = str_replace(self::$delimiterIdentifier, '', $name);

		$args = func_get_args();
		$rgt = $lft = isset($args[1]) ? $args[1] : '';
		$rgt = isset($args[2]) ? $args[2] : $rgt;

		if(strpos($name, '.')===false)
			return $lft . $name . $rgt;
		$names=explode('.', $name);
		foreach($names as &$n)
			$n = $lft . $n . $rgt;
		return implode('.', $names);
	}

	/**
	 * Quotes a column name for use in a query.
	 * @param string $name column name
	 * @param string $lft left delimiter
	 * @param string $rgt right delimiter
	 * @return string the properly quoted column name
	 */
	public function quoteColumnName($name)
	{
		$args = func_get_args();
		$rgt = $lft = isset($args[1]) ? $args[1] : '';
		$rgt = isset($args[2]) ? $args[2] : $rgt;

		return $lft . str_replace(self::$delimiterIdentifier, '', $name) . $rgt;
	}

	/**
	 * Quotes a column alias for use in a query.
	 * @param string $name column alias
	 * @param string $lft left delimiter
	 * @param string $rgt right delimiter
	 * @return string the properly quoted column alias
	 */
	public function quoteColumnAlias($name)
	{
		$args = func_get_args();
		$rgt = $lft = isset($args[1]) ? $args[1] : '';
		$rgt = isset($args[2]) ? $args[2] : $rgt;

		return $lft . str_replace(self::$delimiterIdentifier, '', $name) . $rgt;
	}
}


text:
[![Source Code](http://img.shields.io/badge/source-siriusphp/form--renderer-blue.svg?style=flat-square)](https://github.com/siriusphp/form-renderer)
[![Latest Version](https://img.shields.io/packagist/v/siriusphp/form-renderer.svg?style=flat-square)](https://github.com/siriusphp/form-renderer/releases)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/siriusphp/form-renderer/blob/master/LICENSE)
[![Build Status](https://img.shields.io/travis/siriusphp/form-renderer/master.svg?style=flat-square)](https://travis-ci.org/siriusphp/form-renderer)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/siriusphp/form-renderer.svg?style=flat-square)](https://scrutinizer-ci.com/g/siriusphp/form-renderer/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/siriusphp/form-renderer.svg?style=flat-square)](https://scrutinizer-ci.com/g/siriusphp/form-renderer)

Sirius\FormsRenderer is a library that renders [Sirius\InputFilter](http://www.sirius.ro/php/sirius/input/) objects as forms using the [Sirius\Html](http://www.sirius.ro/php/sirius/html/) library.

##Elevator pitch

```php
$form = new \Sirius\Input\InputFilter();

$form->add('name', [
	'type' => 'text',
	'label' => 'Name',
	'rules' => ['required']
]);
$form->add('email', [
	'type' => 'text',
	'label' => 'Email',
	'rules' => ['required', 'email']
]);
$form->add('message', [
	'type' => 'textarea',
	'label' => 'Message',
	'hint' => 'Please write in detail the problem you are facing',
	'rules' => ['required']
]);
$form->add('recaptcha', [
	'type' => 'recaptch',
	'label' => 'Are you human or are you dancer?'
]);
$form->add('submit', [
	'type' => 'submit',
	'label' => 'Send request'
]);

$r = new \Sirius\FormsRenderer\Renderer;

echo $r->render($form);
```

For actual code examples you can check out the [Form Examples repository](https://github.com/siriusphp/form-examples)


text:
// Copyright 2021 The Oppia 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.

/**
 * @fileoverview Component for the translation modal.
 */

import isEqual from 'lodash/isEqual';

import { ChangeDetectorRef, Component, Input } from '@angular/core';
import { downgradeComponent } from '@angular/upgrade/static';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

import { AlertsService } from 'services/alerts.service';
import { CkEditorCopyContentService } from 'components/ck-editor-helpers/ck-editor-copy-content.service';
import { ContextService } from 'services/context.service';
import { ImageLocalStorageService } from 'services/image-local-storage.service';
import { SiteAnalyticsService } from 'services/site-analytics.service';
import { Status, TranslatableItem, TranslateTextService } from 'pages/contributor-dashboard-page/services/translate-text.service';
import { TranslationLanguageService } from 'pages/exploration-editor-page/translation-tab/services/translation-language.service';
import { UserService } from 'services/user.service';
import { AppConstants } from 'app.constants';
import constants from 'assets/constants';
import { OppiaAngularRootComponent } from 'components/oppia-angular-root.component';
import { ListSchema, UnicodeSchema } from 'services/schema-default-value.service';
import {
  TRANSLATION_DATA_FORMAT_SET_OF_NORMALIZED_STRING,
  TRANSLATION_DATA_FORMAT_SET_OF_UNICODE_STRING
} from 'domain/exploration/WrittenTranslationObjectFactory';

const INTERACTION_SPECS = require('interactions/interaction_specs.json');

class UiConfig {
  'hide_complex_extensions': boolean;
  'startupFocusEnabled'?: boolean;
  'language'?: string;
  'languageDirection'?: string;
}
export interface TranslationOpportunity {
  id: string;
  heading: string;
  subheading: string;
  progressPercentage: string;
  actionButtonTitle: string;
  inReviewCount: number;
  totalCount: number;
  translationsCount: number;
}
export interface HTMLSchema {
    'type': string;
    'ui_config': UiConfig;
}
export interface ImageDetails {
  filePaths: string[];
  alts: string[];
  descriptions: string[];
}
export class TranslationError {
  constructor(
    private _hasDuplicateAltTexts: boolean,
    private _hasDuplicateDescriptions: boolean,
    private _hasUntranslatedElements: boolean) {}

  get hasDuplicateDescriptions(): boolean {
    return this._hasDuplicateDescriptions;
  }
  get hasDuplicateAltTexts(): boolean {
    return this._hasDuplicateAltTexts;
  }
  get hasUntranslatedElements(): boolean {
    return this._hasUntranslatedElements;
  }
}

@Component({
  selector: 'oppia-translation-modal',
  templateUrl: './translation-modal.component.html'
})
export class TranslationModalComponent {
  @Input() opportunity: TranslationOpportunity;
  activeDataFormat: string;
  activeWrittenTranslation: string | string[] = '';
  activeContentType: string;
  activeRuleDescription: string;
  uploadingTranslation = false;
  subheading: string;
  heading: string;
  loadingData = true;
  moreAvailable = false;
  textToTranslate: string | string[] = '';
  languageDescription: string;
  activeStatus: Status;
  HTML_SCHEMA: {
    'type': string;
    'ui_config': UiConfig;
  };
  UNICODE_SCHEMA: UnicodeSchema = { type: 'unicode' };
  SET_OF_STRINGS_SCHEMA: ListSchema = {
    type: 'list',
    items: {
      type: 'unicode'
    }
  };
  TRANSLATION_TIPS = constants.TRANSLATION_TIPS;
  activeLanguageCode: string;
  isActiveLanguageReviewer: boolean = false;
  hadCopyParagraphError = false;
  hasImgTextError = false;
  hasIncompleteTranslationError = false;
  editorIsShown = true;
  ALLOWED_CUSTOM_TAGS_IN_TRANSLATION_SUGGESTION = [
    'oppia-noninteractive-image',
    'oppia-noninteractive-link',
    'oppia-noninteractive-math',
    'oppia-noninteractive-skillreview'
  ];

  constructor(
    private readonly activeModal: NgbActiveModal,
    private readonly alertsService: AlertsService,
    private readonly ckEditorCopyContentService: CkEditorCopyContentService,
    private readonly contextService: ContextService,
    private readonly imageLocalStorageService: ImageLocalStorageService,
    private readonly siteAnalyticsService: SiteAnalyticsService,
    private readonly translateTextService: TranslateTextService,
    private readonly translationLanguageService: TranslationLanguageService,
    private readonly userService: UserService,
    private readonly changeDetectorRef: ChangeDetectorRef
  ) {
    this.contextService = OppiaAngularRootComponent.contextService;
  }

  ngOnInit(): void {
    this.activeLanguageCode =
    this.translationLanguageService.getActiveLanguageCode();
    // We need to set the context here so that the rte fetches
    // images for the given ENTITY_TYPE and targetId.
    this.contextService.setCustomEntityContext(
      AppConstants.ENTITY_TYPE.EXPLORATION, this.opportunity.id);
    this.subheading = this.opportunity.subheading;
    this.heading = this.opportunity.heading;
    this.contextService.setImageSaveDestinationToLocalStorage();
    this.languageDescription = (
      this.translationLanguageService.getActiveLanguageDescription());
    this.translateTextService.init(
      this.opportunity.id,
      this.translationLanguageService.getActiveLanguageCode(),
      () => {
        const translatableItem = (
          this.translateTextService.getTextToTranslate());
        this.updateActiveState(translatableItem);
        ({more: this.moreAvailable} = translatableItem);
        this.loadingData = false;
      });
    this.userService.getUserContributionRightsDataAsync().then(
      userContributionRights => {
        const reviewableLanguageCodes = (
          userContributionRights.can_review_translation_for_language_codes);
        if (reviewableLanguageCodes.includes(this.activeLanguageCode)) {
          this.isActiveLanguageReviewer = true;
        }
      });
    this.HTML_SCHEMA = {
      type: 'html',
      ui_config: {
        // If this is made true, then the translation cannot be validated
        // properly since contributors will not be able to view and translate
        // complex extensions.
        hide_complex_extensions: false,
        language: this.translationLanguageService.getActiveLanguageCode(),
        languageDirection: (
          this.translationLanguageService.getActiveLanguageDirection())
      }
    };
  }

  // TODO(#13221): Remove this method completely after the change detection
  // issues in schema-based-editor have been resolved. The current workaround
  // used is to destroy and re-render the component in the view.
  resetEditor(): void {
    this.editorIsShown = false;
    this.changeDetectorRef.detectChanges();
    this.editorIsShown = true;
  }

  close(): void {
    this.activeModal.close();
  }

  getHtmlSchema(): HTMLSchema {
    return this.HTML_SCHEMA;
  }

  getUnicodeSchema(): UnicodeSchema {
    return this.UNICODE_SCHEMA;
  }

  getSetOfStringsSchema(): ListSchema {
    return this.SET_OF_STRINGS_SCHEMA;
  }

  updateActiveState(translatableItem: TranslatableItem): void {
    (
      {
        text: this.textToTranslate,
        more: this.moreAvailable,
        status: this.activeStatus,
        translation: this.activeWrittenTranslation,
        dataFormat: this.activeDataFormat
      } = translatableItem
    );
    const {
      contentType,
      ruleType,
      interactionId
    } = translatableItem;
    this.activeContentType = this.getFormattedContentType(
      contentType, interactionId
    );
    this.activeRuleDescription = this.getRuleDescription(
      ruleType, interactionId
    );
  }

  onContentClick(event: MouseEvent): boolean | void {
    if (this.triedToCopyParagraph(event)) {
      return this.hadCopyParagraphError = true;
    }
    this.hadCopyParagraphError = false;
    if (this.isCopyModeActive()) {
      event.stopPropagation();
    }
    this.ckEditorCopyContentService.broadcastCopy(event.target as HTMLElement);
  }

  triedToCopyParagraph($event: MouseEvent): boolean {
    // Mathematical equations are also wrapped by <p> elements.
    // Hence, math elements should be allowed to be copied.
    // See issue #11683.
    const target = $event.target as HTMLElement;
    const paragraphChildrenElements: Element[] = (
      target.localName === 'p') ? Array.from(
        target.children) : [];
    const mathElementsIncluded = paragraphChildrenElements.some(
      child => child.localName === 'oppia-noninteractive-math');
    return target.localName === 'p' && !mathElementsIncluded;
  }

  isCopyModeActive(): boolean {
    return this.ckEditorCopyContentService.copyModeActive;
  }

  updateHtml($event: string): void {
    if ($event !== this.activeWrittenTranslation) {
      this.activeWrittenTranslation = $event;
      this.changeDetectorRef.detectChanges();
    }
  }

  hasPreviousTranslations(): boolean {
    return this.translateTextService.getActiveIndex() > 0;
  }

  skipActiveTranslation(): void {
    const translatableItem = (
      this.translateTextService.getTextToTranslate());
    this.updateActiveState(translatableItem);
    ({more: this.moreAvailable} = translatableItem);
    this.resetEditor();
  }

  isSubmitted(): boolean {
    return this.activeStatus === 'submitted';
  }

  returnToPreviousTranslation(): void {
    const translatableItem = (
      this.translateTextService.getPreviousTextToTranslate());
    this.updateActiveState(translatableItem);
    this.moreAvailable = true;
    this.resetEditor();
  }

  isSetOfStringDataFormat(): boolean {
    return (
      this.activeDataFormat ===
        TRANSLATION_DATA_FORMAT_SET_OF_NORMALIZED_STRING ||
      this.activeDataFormat === TRANSLATION_DATA_FORMAT_SET_OF_UNICODE_STRING
    );
  }

  getFormattedContentType(
      contentType: string, interactionId: string): string {
    if (contentType === 'interaction') {
      return interactionId + ' interaction';
    } else if (contentType === 'rule') {
      return 'input rule';
    }
    return contentType;
  }

  getRuleDescription(ruleType: string, interactionId: string): string {
    if (!ruleType || !interactionId) {
      return '';
    }
    // To match, e.g. "{{x|TranslatableSetOfNormalizedString}},".
    const descriptionPattern = /\{\{\s*(\w+)\s*(\|\s*\w+\s*)?\}\}/;
    const ruleDescription = INTERACTION_SPECS[
      interactionId].rule_descriptions[ruleType];
    return 'Answer ' + ruleDescription.replace(
      descriptionPattern, 'the following choices:');
  }

  getElementAttributeTexts(
      elements: HTMLCollectionOf<Element>, type: string): string[] {
    const textWrapperLength = 6;
    const attributes = Array.from(elements, function(element: Element) {
      // A sample element would be as <oppia-noninteractive-image alt-with-value
      // ="&quot;Image description&quot;" caption-with-value=
      // "&quot;Image caption&quot;" filepath-with-value="&quot;
      // img_2021029_210552_zbmdt94_height_54_width_490.png&quot;">
      // </oppia-noninteractive-image>
      if (element.localName === 'oppia-noninteractive-image') {
        const attribute = element.attributes[type].value;
        return attribute.substring(
          textWrapperLength, attribute.length - textWrapperLength);
      }
    });
    return attributes.filter(attribute => attribute);
  }

  getImageAttributeTexts(
      htmlElements: HTMLCollectionOf<Element>): ImageDetails {
    return {
      filePaths: this.getElementAttributeTexts(
        htmlElements, 'filepath-with-value'),
      alts: this.getElementAttributeTexts(
        htmlElements, 'alt-with-value'),
      descriptions: this.getElementAttributeTexts(
        htmlElements, 'caption-with-value')
    };
  }

  hasSomeDuplicateElements(
      originalElements: string[],
      translatedElements: string[]): boolean {
    // This regular expression matches a number, optionally negative, with an
    // optional decimal number followed by zero or more operators (including
    // equals sign) and number pairs. It also allows for whitespace between
    // numbers and operators. Examples 1+1=2 1+1 1*1=1.
    const mathEquationRegex = new RegExp(
      /(?:(?:^|[-+_*/=])(?:\s*-?\d+(\.\d+)?(?:[eE][+-]?\d+)?\s*))+$/);
    if (originalElements.length === 0) {
      return false;
    }
    const hasMatchingTranslatedElement = element => (
      translatedElements.includes(element) && originalElements.length > 0 &&
      !mathEquationRegex.test(element));
    return originalElements.some(hasMatchingTranslatedElement);
  }

  isTranslationCompleted(
      originalElements: HTMLCollectionOf<Element>,
      translatedElements: HTMLCollectionOf<Element>): boolean {
    // Checks if there are custom tags present in the original content but not
    // in the translated content.
    const filteredOriginalElements = Array.from(
      originalElements, el => el.tagName.toLowerCase()).filter(
      tagName => this.ALLOWED_CUSTOM_TAGS_IN_TRANSLATION_SUGGESTION.includes(
        tagName)).sort();
    const filteredTranslatedElements = Array.from(
      translatedElements, el => el.tagName.toLowerCase()).filter(
      tagName => this.ALLOWED_CUSTOM_TAGS_IN_TRANSLATION_SUGGESTION.includes(
        tagName)).sort();
    return isEqual(filteredOriginalElements, filteredTranslatedElements);
  }

  validateTranslation(
      textToTranslate: HTMLCollectionOf<Element>,
      translatedText: HTMLCollectionOf<Element>): TranslationError {
    const translatedElements: ImageDetails = this.getImageAttributeTexts(
      translatedText);
    const originalElements: ImageDetails = this.getImageAttributeTexts(
      textToTranslate);

    const hasDuplicateAltTexts = this.hasSomeDuplicateElements(
      originalElements.alts,
      translatedElements.alts);
    const hasDuplicateDescriptions = this.hasSomeDuplicateElements(
      originalElements.descriptions,
      translatedElements.descriptions);
    const hasUntranslatedElements = !(this.isTranslationCompleted(
      textToTranslate, translatedText));

    return new TranslationError(
      hasDuplicateAltTexts,
      hasDuplicateDescriptions, hasUntranslatedElements);
  }

  suggestTranslatedText(): void {
    if (!this.isSetOfStringDataFormat()) {
      const domParser = new DOMParser();
      const originalElements = domParser.parseFromString(
        this.textToTranslate as string, 'text/html');
      const translatedElements = domParser.parseFromString(
        this.activeWrittenTranslation as string, 'text/html');

      const translationError = this.validateTranslation(
        originalElements.getElementsByTagName('*'),
        translatedElements.getElementsByTagName('*'));

      this.hasImgTextError = translationError.hasDuplicateAltTexts ||
        translationError.hasDuplicateDescriptions;
      this.hasIncompleteTranslationError = translationError.
        hasUntranslatedElements;

      if (this.hasImgTextError ||
        this.hasIncompleteTranslationError || this.uploadingTranslation ||
        this.loadingData) {
        return;
      }

      if (this.hadCopyParagraphError) {
        this.hadCopyParagraphError = false;
      }
    }

    if (!this.uploadingTranslation && !this.loadingData) {
      this.siteAnalyticsService
        .registerContributorDashboardSubmitSuggestionEvent('Translation');
      this.uploadingTranslation = true;
      const imagesData = this.imageLocalStorageService.getStoredImagesData();
      this.imageLocalStorageService.flushStoredImagesData();
      this.translateTextService.suggestTranslatedText(
        this.activeWrittenTranslation,
        this.translationLanguageService.getActiveLanguageCode(),
        imagesData, this.activeDataFormat, () => {
          this.alertsService.addSuccessMessage(
            'Submitted translation for review.');
          this.uploadingTranslation = false;
          if (this.moreAvailable) {
            this.skipActiveTranslation();
            this.resetEditor();
          } else {
            this.activeWrittenTranslation = '';
            this.resetEditor();
          }
        }, (errorReason: string) => {
          this.contextService.resetImageSaveDestination();
          this.alertsService.clearWarnings();
          this.alertsService.addWarning(errorReason);
          this.close();
        });
    }
    if (!this.moreAvailable) {
      this.contextService.resetImageSaveDestination();
      this.close();
    }
  }
}

angular.module('oppia').directive(
  'oppiaTranslationModal', downgradeComponent(
    {component: TranslationModalComponent}));


text:
import path from 'path';
import { existsSync as exists, readFileSync as read, writeFileSync as writeFile } from 'fs';
import createDebug from 'debug';
import { sync as commandExists } from 'command-exists';
import { addCertificateToNSSCertDB, assertNotTouchingFiles, openCertificateInFirefox, closeFirefox, removeCertificateFromNSSCertDB } from './shared';
import { run } from '../utils';
import { Options } from '../index';
import UI from '../user-interface';
import { Platform } from '.';

const debug = createDebug('devcert:platforms:linux');

export default class LinuxPlatform implements Platform {

  private FIREFOX_NSS_DIR = path.join(process.env.HOME, '.mozilla/firefox/*');
  private CHROME_NSS_DIR = path.join(process.env.HOME, '.pki/nssdb');
  private FIREFOX_BIN_PATH = '/usr/bin/firefox';
  private CHROME_BIN_PATH = '/usr/bin/google-chrome';

  private HOST_FILE_PATH = '/etc/hosts';

  /**
   * Linux is surprisingly difficult. There seems to be multiple system-wide
   * repositories for certs, so we copy ours to each. However, Firefox does it's
   * usual separate trust store. Plus Chrome relies on the NSS tooling (like
   * Firefox), but uses the user's NSS database, unlike Firefox (which uses a
   * separate Mozilla one). And since Chrome doesn't prompt the user with a GUI
   * flow when opening certs, if we can't use certutil to install our certificate
   * into the user's NSS database, we're out of luck.
   */
  async addToTrustStores(certificatePath: string, options: Options = {}): Promise<void> {

    debug('Adding devcert root CA to Linux system-wide trust stores');
    // run(`sudo cp ${ certificatePath } /etc/ssl/certs/devcert.crt`);
    run(`sudo cp "${ certificatePath }" /usr/local/share/ca-certificates/devcert.crt`);
    // run(`sudo bash -c "cat ${ certificatePath } >> /etc/ssl/certs/ca-certificates.crt"`);
    run(`sudo update-ca-certificates`);

    if (this.isFirefoxInstalled()) {
      // Firefox
      debug('Firefox install detected: adding devcert root CA to Firefox-specific trust stores ...');
      if (!commandExists('certutil')) {
        if (options.skipCertutilInstall) {
          debug('NSS tooling is not already installed, and `skipCertutil` is true, so falling back to manual certificate install for Firefox');
          openCertificateInFirefox(this.FIREFOX_BIN_PATH, certificatePath);
        } else {
          debug('NSS tooling is not already installed. Trying to install NSS tooling now with `apt install`');
          run('sudo apt install libnss3-tools');
          debug('Installing certificate into Firefox trust stores using NSS tooling');
          await closeFirefox();
          await addCertificateToNSSCertDB(this.FIREFOX_NSS_DIR, certificatePath, 'certutil');
        }
      }
    } else {
      debug('Firefox does not appear to be installed, skipping Firefox-specific steps...');
    }

    if (this.isChromeInstalled()) {
      debug('Chrome install detected: adding devcert root CA to Chrome trust store ...');
      if (!commandExists('certutil')) {
        UI.warnChromeOnLinuxWithoutCertutil();
      } else {
        await closeFirefox();
        await addCertificateToNSSCertDB(this.CHROME_NSS_DIR, certificatePath, 'certutil');
      }
    } else {
      debug('Chrome does not appear to be installed, skipping Chrome-specific steps...');
    }
  }

  removeFromTrustStores(certificatePath: string) {
    try {
      run(`sudo rm /usr/local/share/ca-certificates/devcert.crt`);
      run(`sudo update-ca-certificates`);
    } catch (e) {
      debug(`failed to remove ${ certificatePath } from /usr/local/share/ca-certificates, continuing. ${ e.toString() }`);
    }
    if (commandExists('certutil')) {
      if (this.isFirefoxInstalled()) {
        removeCertificateFromNSSCertDB(this.FIREFOX_NSS_DIR, certificatePath, 'certutil');
      }
      if (this.isChromeInstalled()) {
        removeCertificateFromNSSCertDB(this.CHROME_NSS_DIR, certificatePath, 'certutil');
      }
    }
  }

  async addDomainToHostFileIfMissing(domain: string) {
    let hostsFileContents = read(this.HOST_FILE_PATH, 'utf8');
    if (!hostsFileContents.includes(domain)) {
      run(`echo '127.0.0.1  ${ domain }' | sudo tee -a "${ this.HOST_FILE_PATH }" > /dev/null`);
    }
  }

  deleteProtectedFiles(filepath: string) {
    assertNotTouchingFiles(filepath, 'delete');
    run(`sudo rm -rf "${filepath}"`);
  }

  async readProtectedFile(filepath: string) {
    assertNotTouchingFiles(filepath, 'read');
    return (await run(`sudo cat "${filepath}"`)).toString().trim();
  }

  async writeProtectedFile(filepath: string, contents: string) {
    assertNotTouchingFiles(filepath, 'write');
    if (exists(filepath)) {
      await run(`sudo rm "${filepath}"`);
    }
    writeFile(filepath, contents);
    await run(`sudo chown 0 "${filepath}"`);
    await run(`sudo chmod 600 "${filepath}"`);
  }

  private isFirefoxInstalled() {
    return exists(this.FIREFOX_BIN_PATH);
  }

  private isChromeInstalled() {
    return exists(this.CHROME_BIN_PATH);
  }

}


text:
<?php

namespace Google\AdsApi\AdWords\v201705\o;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class TrafficEstimatorResult
{

    /**
     * @var \Google\AdsApi\AdWords\v201705\o\CampaignEstimate[] $campaignEstimates
     */
    protected $campaignEstimates = null;

    /**
     * @param \Google\AdsApi\AdWords\v201705\o\CampaignEstimate[] $campaignEstimates
     */
    public function __construct(array $campaignEstimates = null)
    {
      $this->campaignEstimates = $campaignEstimates;
    }

    /**
     * @return \Google\AdsApi\AdWords\v201705\o\CampaignEstimate[]
     */
    public function getCampaignEstimates()
    {
      return $this->campaignEstimates;
    }

    /**
     * @param \Google\AdsApi\AdWords\v201705\o\CampaignEstimate[] $campaignEstimates
     * @return \Google\AdsApi\AdWords\v201705\o\TrafficEstimatorResult
     */
    public function setCampaignEstimates(array $campaignEstimates)
    {
      $this->campaignEstimates = $campaignEstimates;
      return $this;
    }

}


text:
package com.example.tuanpd.myapplication;

import java.util.Timer;
import java.util.TimerTask;

public class LocationTimer {

    private Timer mTimer;

    private TimerTask mTask = new TimerTask() {
        @Override
        public void run() {
            //
        }
    };

    public void cancel() {
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    public void start(long intervalTime) {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        mTimer.scheduleAtFixedRate(mTask, 0, intervalTime);

    }
}


text:
package instructor;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import com.google.appengine.api.datastore.*;
import com.google.appengine.api.memcache.*;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.users.*;
import com.google.appengine.api.datastore.Query.*;
import java.util.*;
import java.util.logging.*;
import java.io.*;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.CompositeFilter;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

public class InstructorServe extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       BlobstoreService blobstore = BlobstoreServiceFactory.getBlobstoreService();
       String instructorID = request.getParameter("instructorID");
       Key imageKey = KeyFactory.createKey("Instructor", instructorID);
       DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
       Entity instructor = null;
       try{
       		instructor = datastore.get(imageKey);
       }catch(EntityNotFoundException e){
       		e.printStackTrace();
       }
       if(instructor!=null){
       		String blobKey = (String)instructor.getProperty("blobKey");
       		if(blobKey!=null){
       			BlobKey key = new BlobKey(blobKey);
       			blobstore.serve(key, response);
       		}
       }
       else{
       		response.sendRedirect("/instructorpersonal.jsp");
       }
    }
}


text:
package com.melodies.bandup.listeners;

import com.android.volley.VolleyError;

public interface BandUpErrorListener {
    void onBandUpErrorResponse(VolleyError error);
}


text:
/*globals define */
/*jshint browser: true */
/**
 * STRING CONSTANT DEFINITIONS USED IN METAEDITOR CONTROLLER
 *
 * @author rkereskenyi / https://github.com/rkereskenyi
 */

define(['js/Constants'], function (CONSTANTS) {
    'use strict';

    //return string constants
    return {
        META_ASPECT_SET_NAME: 'MetaAspectSet',
        RESERVED_POINTER_NAMES: [CONSTANTS.POINTER_BASE],
        META_ASPECT_CONTAINER_ID: CONSTANTS.PROJECT_ROOT_ID,
        META_ASPECT_SHEET_NAME_PREFIX: 'MetaAspectSet_'
    };
});


text:
1. `git clone git@github.com:chaserx/gems-cli.git`
1. Create a branch to add your feature/fix a bug: `git checkout -b my-new-feature`.
1. Add your feature/fix while following the [style guide](http://learning-things.cirrusmio.com/style-guides/ruby.html).
1. Check your style with rubocop `bundle exec rubocop`.
1. Commit and push your changes to the branch to Github.
1. [Create a new Pull Request](https://github.com/chaserx/gems-cli/compare).


text:
__version__ = '3.1.4'
__password__ = '123456'
__hostsdeny__ = ()  # __hostsdeny__ = ('.youtube.com', '.youku.com')
__content_type__ = 'image/gif'
__timeout__ = 20

try:
    import gevent
    import gevent.queue
    import gevent.monkey
    gevent.monkey.patch_all()
except ImportError:
    pass

import sys
import re
import time
import itertools
import functools
import logging
import string
import urlparse
import httplib
import struct
import zlib
import collections
import Queue

normcookie = functools.partial(re.compile(', ([^ =]+(?:=|$))').sub, '\\r\\nSet-Cookie: \\1')

def message_html(title, banner, detail=''):
    MESSAGE_TEMPLATE = '''

    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>$title</title>

Message

$banner

    $detail

    '''
    return string.Template(MESSAGE_TEMPLATE).substitute(title=title, banner=banner, detail=detail)

class XORCipher(object):
    """XOR Cipher Class"""
    def __init__(self, key):
        self.__key_gen = itertools.cycle([ord(x) for x in key]).next
        self.__key_xor = lambda s: ''.join(chr(ord(x) ^ self.__key_gen()) for x in s)
        if len(key) == 1:
            try:
                from Crypto.Util.strxor import strxor_c
                c = ord(key)
                self.__key_xor = lambda s: strxor_c(s, c)
            except ImportError:
                sys.stderr.write('Load Crypto.Util.strxor Failed, Use Pure Python Instead.\n')

    def encrypt(self, data):
        return self.__key_xor(data)

def decode_request(data):
    metadata_length, = struct.unpack('!h', data[:2])
    metadata = zlib.decompress(data[2:2+metadata_length], -zlib.MAX_WBITS)
    body = data[2+metadata_length:]
    headers = dict(x.split(':', 1) for x in metadata.splitlines() if x)
    method = headers.pop('G-Method')
    url = headers.pop('G-Url')
    kwargs = {}
    any(kwargs.__setitem__(x[2:].lower(), headers.pop(x)) for x in headers.keys() if x.startswith('G-'))
    if headers.get('Content-Encoding', '') == 'deflate':
        body = zlib.decompress(body, -zlib.MAX_WBITS)
        headers['Content-Length'] = str(len(body))
        del headers['Content-Encoding']
    return method, url, headers, kwargs, body

HTTP_CONNECTION_CACHE = collections.defaultdict(Queue.PriorityQueue)

def application(environ, start_response):
    if environ['REQUEST_METHOD'] == 'GET':
        start_response('302 Found', [('Location', 'https://www.google.com')])
        raise StopIteration

    post_data = environ['wsgi.input'].read(int(environ.get('CONTENT_LENGTH') or -1))
    method, url, headers, kwargs, body = decode_request(post_data)
    scheme, netloc, path, _, query, _ = urlparse.urlparse(url)
    cipher = XORCipher(__password__[0])

    if __password__ != kwargs.get('password'):
        start_response('403 Forbidden', [('Content-Type', 'text/html')])
        yield message_html('403 Wrong Password', 'Wrong Password(%s)' % kwargs.get('password'), detail='please edit proxy.ini')
        raise StopIteration

    if __hostsdeny__ and netloc.endswith(__hostsdeny__):
        start_response('200 OK', [('Content-Type', __content_type__)])
        yield cipher.encrypt('HTTP/1.1 403 Forbidden\r\nContent-type: text/html\r\n\r\n')
        yield cipher.encrypt(message_html('403 Forbidden Host', 'Hosts Deny(%s)' % netloc, detail='url=%r' % url))
        raise StopIteration

    timeout = int(kwargs.get('timeout') or __timeout__)
    fetchmax = int(kwargs.get('fetchmax') or 3)
    ConnectionType = httplib.HTTPSConnection if scheme == 'https' else httplib.HTTPConnection
    header_sent = False
    try:
        connection = None
        response = None
        for i in xrange(fetchmax):
            try:
                while True:
                    try:
                        mtime, connection = HTTP_CONNECTION_CACHE[(scheme, netloc)].get_nowait()
                        if time.time() - mtime < 16:
                            break
                        else:
                            connection.close()
                    except Queue.Empty:
                        connection = ConnectionType(netloc, timeout=timeout)
                        break
                connection.request(method, '%s?%s' % (path, query) if query else path, body=body, headers=headers)
                response = connection.getresponse(buffering=True)
                break
            except Exception as e:
                if i == fetchmax - 1:
                    raise
        need_encrypt = not response.getheader('Content-Type', '').startswith(('audio/', 'image/', 'video/', 'application/octet-stream'))
        start_response('200 OK', [('Content-Type', __content_type__ if need_encrypt else 'image/x-png')])
        header_sent = True
        if response.getheader('Set-Cookie'):
            response.msg['Set-Cookie'] = normcookie(response.getheader('Set-Cookie'))
        content = 'HTTP/1.1 %s %s\r\n%s\r\n' % (response.status, httplib.responses.get(response.status, 'Unknown'), ''.join('%s: %s\r\n' % (k.title(), v) for k, v in response.getheaders() if k.title() != 'Transfer-Encoding'))
        if need_encrypt:
            content = cipher.encrypt(content)
        yield content
        # bufsize = 32768 if int(response.getheader('Content-Length', 0)) > 512*1024 else 8192
        bufsize = 8192
        while True:
            data = response.read(bufsize)
            if not data:
                response.close()
                if connection.sock:
                    HTTP_CONNECTION_CACHE[(scheme, netloc)].put((time.time(), connection))
                return
            if need_encrypt:
                data = cipher.encrypt(data)
            yield data
            del data
    except Exception as e:
        import traceback
        if not header_sent:
            start_response('200 OK', [('Content-Type', __content_type__)])
        yield cipher.encrypt('HTTP/1.1 500 Internal Server Error\r\nContent-type: text/html\r\n\r\n')
        yield cipher.encrypt(message_html('500 Internal Server Error', 'urlfetch %r: %r' % (url, e), '
%s
' % traceback.format_exc()))
        raise StopIteration

try:
    import sae
    application = sae.create_wsgi_app(application)
except ImportError:
    pass

try:
    import bae.core.wsgi
    application = bae.core.wsgi.WSGIApplication(application)
except ImportError:
    pass

def run_wsgi_app(address, app):
    try:
        from gunicorn.app.wsgiapp import WSGIApplication
        class GunicornApplication(WSGIApplication):
            def init(self, parser, opts, args):
                return {'bind': '%s:%d' % (address[0], int(address[1])),
                        'workers': 2,
                        'worker_class': 'gevent'}
            def load(self):
                return application
        GunicornApplication().run()
    except ImportError:
        from gevent.wsgi import WSGIServer
        WSGIServer(address, app).serve_forever()

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format='%(levelname)s - - %(asctime)s %(message)s', datefmt='[%b %d %H:%M:%S]')
    host, _, port = sys.argv[1].rpartition(':')
    logging.info('local python application serving at %s:%s', host, port)
    run_wsgi_app((host, int(port)), application)


text:
<?php declare(strict_types=1);

namespace GraphQL\Tests\Validator;

use GraphQL\Type\Schema;
use GraphQL\Utils\BuildSchema;
use GraphQL\Validator\Rules\UniqueOperationTypes;

class UniqueOperationTypesTest extends ValidatorTestCase
{
    /**
     * @param array<int, array<string, mixed>> $errors
     */
    private function expectSDLErrors(string $sdlString, ?Schema $schema, array $errors): void
    {
        $this->expectSDLErrorsFromRule(new UniqueOperationTypes(), $sdlString, $schema, $errors);
    }

    /**
     * @see describe('Validate: Unique operation types')
     * @see it('no schema definition')
     */
    public function testNoSchemaDefinition(): void
    {
        $this->expectValidSDL(
            new UniqueOperationTypes(),
            '
      type Foo
            '
        );
    }

    /**
     * @see it('schema definition with all types')
     */
    public function testSchemaDefinitionWithAllTypes(): void
    {
        $this->expectValidSDL(
            new UniqueOperationTypes(),
            '
      type Foo

      schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }
            '
        );
    }

    /**
     * @see it('schema definition with single extension')
     */
    public function testSchemaDefinitionWithSingleExtension(): void
    {
        $this->expectValidSDL(
            new UniqueOperationTypes(),
            '
      type Foo

      schema { query: Foo }

      extend schema {
        mutation: Foo
        subscription: Foo
      }
            '
        );
    }

    /**
     * @see it('schema definition with separate extensions')
     */
    public function testSchemaDefinitionWithSeparateExtensions(): void
    {
        $this->expectValidSDL(
            new UniqueOperationTypes(),
            '
      type Foo

      schema { query: Foo }
      extend schema { mutation: Foo }
      extend schema { subscription: Foo }
            '
        );
    }

    /**
     * @see it('extend schema before definition')
     */
    public function testExtendSchemaBeforeDefinition(): void
    {
        $this->expectValidSDL(
            new UniqueOperationTypes(),
            '
      type Foo

      extend schema { mutation: Foo }
      extend schema { subscription: Foo }

      schema { query: Foo }
            '
        );
    }

    /**
     * @see it('duplicate operation types inside single schema definition')
     */
    public function testDuplicateOperationTypesInsideSingleSchemaDefinition(): void
    {
        $this->expectSDLErrors(
            '
      type Foo

      schema {
        query: Foo
        mutation: Foo
        subscription: Foo

        query: Foo
        mutation: Foo
        subscription: Foo
      }
            ',
            null,
            [
                [
                    'message' => 'There can be only one query type in schema.',
                    'locations' => [
                        ['line' => 5, 'column' => 9],
                        ['line' => 9, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one mutation type in schema.',
                    'locations' => [
                        ['line' => 6, 'column' => 9],
                        ['line' => 10, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one subscription type in schema.',
                    'locations' => [
                        ['line' => 7, 'column' => 9],
                        ['line' => 11, 'column' => 9],
                    ],
                ],
            ],
        );
    }

    /**
     * @see it('duplicate operation types inside schema extension')
     */
    public function testDuplicateOperationTypesInsideSchemaExtension(): void
    {
        $this->expectSDLErrors(
            '
      type Foo

      schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }

      extend schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }
            ',
            null,
            [
                [
                    'message' => 'There can be only one query type in schema.',
                    'locations' => [
                        ['line' => 5, 'column' => 9],
                        ['line' => 11, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one mutation type in schema.',
                    'locations' => [
                        ['line' => 6, 'column' => 9],
                        ['line' => 12, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one subscription type in schema.',
                    'locations' => [
                        ['line' => 7, 'column' => 9],
                        ['line' => 13, 'column' => 9],
                    ],
                ],
            ],
        );
    }

    /**
     * @see it('duplicate operation types inside schema extension twice')
     */
    public function testDuplicateOperationTypesInsideSchemaExtensionTwice(): void
    {
        $this->expectSDLErrors(
            '
      type Foo

      schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }

      extend schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }

      extend schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }
            ',
            null,
            [
                [
                    'message' => 'There can be only one query type in schema.',
                    'locations' => [
                        ['line' => 5, 'column' => 9],
                        ['line' => 11, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one mutation type in schema.',
                    'locations' => [
                        ['line' => 6, 'column' => 9],
                        ['line' => 12, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one subscription type in schema.',
                    'locations' => [
                        ['line' => 7, 'column' => 9],
                        ['line' => 13, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one query type in schema.',
                    'locations' => [
                        ['line' => 5, 'column' => 9],
                        ['line' => 17, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one mutation type in schema.',
                    'locations' => [
                        ['line' => 6, 'column' => 9],
                        ['line' => 18, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one subscription type in schema.',
                    'locations' => [
                        ['line' => 7, 'column' => 9],
                        ['line' => 19, 'column' => 9],
                    ],
                ],
            ],
        );
    }

    /**
     * @see it('duplicate operation types inside second schema extension')
     */
    public function testDuplicateOperationTypesInsideSecondSchemaExtension(): void
    {
        $this->expectSDLErrors(
            '
      type Foo

      schema {
        query: Foo
      }

      extend schema {
        mutation: Foo
        subscription: Foo
      }

      extend schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }
            ',
            null,
            [
                [
                    'message' => 'There can be only one query type in schema.',
                    'locations' => [
                        ['line' => 5, 'column' => 9],
                        ['line' => 14, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one mutation type in schema.',
                    'locations' => [
                        ['line' => 9, 'column' => 9],
                        ['line' => 15, 'column' => 9],
                    ],
                ],
                [
                    'message' => 'There can be only one subscription type in schema.',
                    'locations' => [
                        ['line' => 10, 'column' => 9],
                        ['line' => 16, 'column' => 9],
                    ],
                ],
            ],
        );
    }

    /**
     * @see it('define schema inside extension SDL')
     */
    public function testDefineSchemaInsideExtensionSdl(): void
    {
        $schema = BuildSchema::build('type Foo');
        $sdl = '
      schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }
        ';

        $this->expectValidSDL(new UniqueOperationTypes(), $sdl, $schema);
    }

    /**
     * @see it('define and extend schema inside extension SDL')
     */
    public function testDefineAndExtendSchemaInsideExtensionSdl(): void
    {
        $schema = BuildSchema::build('type Foo');
        $sdl = '
      schema { query: Foo }
      extend schema { mutation: Foo }
      extend schema { subscription: Foo }
        ';

        $this->expectValidSDL(new UniqueOperationTypes(), $sdl, $schema);
    }

    /**
     * @see it('adding new operation types to existing schema')
     */
    public function testAddingNewOperationTypesToExistingSchema(): void
    {
        $schema = BuildSchema::build('type Query');
        $sdl = '
      extend schema { mutation: Foo }
      extend schema { subscription: Foo }
        ';

        $this->expectValidSDL(new UniqueOperationTypes(), $sdl, $schema);
    }

    /**
     * @see it('adding conflicting operation types to existing schema')
     */
    public function testAddingConflictingOperationTypesToExistingSchema(): void
    {
        $schema = BuildSchema::build('
      type Query
      type Mutation
      type Subscription

      type Foo
        ');

        $sdl = '
      extend schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }
        ';

        $this->expectSDLErrors($sdl, $schema, [
            [
                'message' => 'Type for query already defined in the schema. It cannot be redefined.',
                'locations' => [['line' => 3, 'column' => 9]],
            ],
            [
                'message' => 'Type for mutation already defined in the schema. It cannot be redefined.',
                'locations' => [['line' => 4, 'column' => 9]],
            ],
            [
                'message' => 'Type for subscription already defined in the schema. It cannot be redefined.',
                'locations' => [['line' => 5, 'column' => 9]],
            ],
        ]);
    }

    /**
     * @see it('adding conflicting operation types to existing schema twice')
     */
    public function testAddingConflictingOperationTypesToExistingSchemaTwice(): void
    {
        $schema = BuildSchema::build('
      type Query
      type Mutation
      type Subscription
        ');

        $sdl = '
      extend schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }

      extend schema {
        query: Foo
        mutation: Foo
        subscription: Foo
      }
        ';

        $this->expectSDLErrors($sdl, $schema, [
            [
                'message' => 'Type for query already defined in the schema. It cannot be redefined.',
                'locations' => [['line' => 3, 'column' => 9]],
            ],
            [
                'message' => 'Type for mutation already defined in the schema. It cannot be redefined.',
                'locations' => [['line' => 4, 'column' => 9]],
            ],
            [
                'message' => 'Type for subscription already defined in the schema. It cannot be redefined.',
                'locations' => [['line' => 5, 'column' => 9]],
            ],
            [
                'message' => 'Type for query already defined in the schema. It cannot be redefined.',
                'locations' => [['line' => 9, 'column' => 9]],
            ],
            [
                'message' => 'Type for mutation already defined in the schema. It cannot be redefined.',
                'locations' => [['line' => 10, 'column' => 9]],
            ],
            [
                'message' => 'Type for subscription already defined in the schema. It cannot be redefined.',
                'locations' => [['line' => 11, 'column' => 9]],
            ],
        ]);
    }
}


text:
package com.badlogic.ashley.core;

import com.badlogic.ashley.core.Engine.ComponentOperationHandler;
import com.badlogic.ashley.signals.Signal;
import com.badlogic.ashley.utils.Bag;
import com.badlogic.ashley.utils.ImmutableArray;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Bits;

/**
 * Simple containers of {@link Component}s that give them "data". The component's data is then processed by {@link EntitySystem}s.
 * @author Stefan Bachmann
 */
public class Entity {
	/** A flag that can be used to bit mask this entity. Up to the user to manage. */
	public int flags;
	/** Will dispatch an event when a component is added. */
	public final Signal<Entity> componentAdded;
	/** Will dispatch an event when a component is removed. */
	public final Signal<Entity> componentRemoved;

	boolean scheduledForRemoval;
	ComponentOperationHandler componentOperationHandler;

	private Bag<Component> components;
	private Array<Component> componentsArray;
	private ImmutableArray<Component> immutableComponentsArray;
	private Bits componentBits;
	private Bits familyBits;

	/** Creates an empty Entity. */
	public Entity () {
		components = new Bag<Component>();
		componentsArray = new Array<Component>(false, 16);
		immutableComponentsArray = new ImmutableArray<Component>(componentsArray);
		componentBits = new Bits();
		familyBits = new Bits();
		flags = 0;

		componentAdded = new Signal<Entity>();
		componentRemoved = new Signal<Entity>();
	}

	/**
	 * Adds a {@link Component} to this Entity. If a {@link Component} of the same type already exists, it'll be replaced.
	 * @return The Entity for easy chaining
	 */
	public Entity add (Component component) {
		if (addInternal(component)) {
			if (componentOperationHandler != null) {
				componentOperationHandler.add(this);
			}
			else {
				notifyComponentAdded();
			}
		}

		return this;
	}

	/**
	 * Removes the {@link Component} of the specified type. Since there is only ever one component of one type, we don't need an
	 * instance reference.
	 * @return The removed {@link Component}, or null if the Entity did no contain such a component.
	 */
	public Component remove (Class<? extends Component> componentClass) {
		ComponentType componentType = ComponentType.getFor(componentClass);
		int componentTypeIndex = componentType.getIndex();
		Component removeComponent = components.get(componentTypeIndex);

		if (removeComponent != null && removeInternal(componentClass)) {
			if (componentOperationHandler != null) {
				componentOperationHandler.remove(this);
			}
			else {
				notifyComponentRemoved();
			}
		}

		return removeComponent;
	}

	/** Removes all the {@link Component}'s from the Entity. */
	public void removeAll () {
		while (componentsArray.size > 0) {
			remove(componentsArray.get(0).getClass());
		}
	}

	/** @return immutable collection with all the Entity {@link Component}s. */
	public ImmutableArray<Component> getComponents () {
		return immutableComponentsArray;
	}

	/**
	 * Retrieve a component from this {@link Entity} by class. Note: the preferred way of retrieving {@link Component}s is
	 * using {@link ComponentMapper}s. This method is provided for convenience; using a ComponentMapper provides O(1) access to
	 * components while this method provides only O(logn).
	 * @param componentClass the class of the component to be retrieved.
	 * @return the instance of the specified {@link Component} attached to this {@link Entity}, or null if no such
	 *         {@link Component} exists.
	 */
	public <T extends Component> T getComponent (Class<T> componentClass) {
		return getComponent(ComponentType.getFor(componentClass));
	}

	/**
	 * Internal use.
	 * @return The {@link Component} object for the specified class, null if the Entity does not have any components for that class.
	 */
	@SuppressWarnings("unchecked")
	<T extends Component> T getComponent (ComponentType componentType) {
		int componentTypeIndex = componentType.getIndex();

		if (componentTypeIndex < components.getCapacity()) {
			return (T)components.get(componentType.getIndex());
		} else {
			return null;
		}
	}

	/**
	 * @return Whether or not the Entity has a {@link Component} for the specified class.
	 */
	boolean hasComponent (ComponentType componentType) {
		return componentBits.get(componentType.getIndex());
	}

	/**
	 * @return This Entity's component bits, describing all the {@link Component}s it contains.
	 */
	Bits getComponentBits () {
		return componentBits;
	}

	/** @return This Entity's {@link Family} bits, describing all the {@link EntitySystem}s it currently is being processed by. */
	Bits getFamilyBits () {
		return familyBits;
	}

	/**
	 * @param component
	 * @return whether or not the component was added.
	 */
	boolean addInternal (Component component) {
		Class<? extends Component> componentClass = component.getClass();
		Component oldComponent = getComponent(componentClass);

		if (component == oldComponent) {
			return false;
		}

		if (oldComponent != null) {
			removeInternal(componentClass);
		}

		int componentTypeIndex = ComponentType.getIndexFor(componentClass);
		components.set(componentTypeIndex, component);
		componentsArray.add(component);
		componentBits.set(componentTypeIndex);

		return true;
	}

	/**
	 * @param componentClass
	 * @return whether or not a component with the specified class was found and removed.
	 */
	boolean removeInternal (Class<? extends Component> componentClass) {
		ComponentType componentType = ComponentType.getFor(componentClass);
		int componentTypeIndex = componentType.getIndex();
		Component removeComponent = components.get(componentTypeIndex);

		if (removeComponent != null) {
			components.set(componentTypeIndex, null);
			componentsArray.removeValue(removeComponent, true);
			componentBits.clear(componentTypeIndex);

			return true;
		}

		return false;
	}

	void notifyComponentAdded() {
		componentAdded.dispatch(this);
	}

	void notifyComponentRemoved() {
		componentRemoved.dispatch(this);
	}

	/** @return true if the entity is scheduled to be removed */
	public boolean isScheduledForRemoval () {
		return scheduledForRemoval;
	}
}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * AgentInformation represents the details needed to support both 1P and 3P partnerships for Home
 * Automation. Next ID: 7
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class AssistantVerticalsHomeautomationProtoAgentInformation extends com.google.api.client.json.GenericJson {

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String authType;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String deviceSource;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String executionPath;

  /**
   * Unique Agent ID which maps to a specific Agent. Not using Agent Name here as it may change over
   * time.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String id;

  /**
   * Agent's foreign key that uniquely identifies a user's device.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String key;

  /**
   * @return value or {@code null} for none
   */
  public java.lang.String getAuthType() {
    return authType;
  }

  /**
   * @param authType authType or {@code null} for none
   */
  public AssistantVerticalsHomeautomationProtoAgentInformation setAuthType(java.lang.String authType) {
    this.authType = authType;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.String getDeviceSource() {
    return deviceSource;
  }

  /**
   * @param deviceSource deviceSource or {@code null} for none
   */
  public AssistantVerticalsHomeautomationProtoAgentInformation setDeviceSource(java.lang.String deviceSource) {
    this.deviceSource = deviceSource;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.String getExecutionPath() {
    return executionPath;
  }

  /**
   * @param executionPath executionPath or {@code null} for none
   */
  public AssistantVerticalsHomeautomationProtoAgentInformation setExecutionPath(java.lang.String executionPath) {
    this.executionPath = executionPath;
    return this;
  }

  /**
   * Unique Agent ID which maps to a specific Agent. Not using Agent Name here as it may change over
   * time.
   * @return value or {@code null} for none
   */
  public java.lang.String getId() {
    return id;
  }

  /**
   * Unique Agent ID which maps to a specific Agent. Not using Agent Name here as it may change over
   * time.
   * @param id id or {@code null} for none
   */
  public AssistantVerticalsHomeautomationProtoAgentInformation setId(java.lang.String id) {
    this.id = id;
    return this;
  }

  /**
   * Agent's foreign key that uniquely identifies a user's device.
   * @return value or {@code null} for none
   */
  public java.lang.String getKey() {
    return key;
  }

  /**
   * Agent's foreign key that uniquely identifies a user's device.
   * @param key key or {@code null} for none
   */
  public AssistantVerticalsHomeautomationProtoAgentInformation setKey(java.lang.String key) {
    this.key = key;
    return this;
  }

  @Override
  public AssistantVerticalsHomeautomationProtoAgentInformation set(String fieldName, Object value) {
    return (AssistantVerticalsHomeautomationProtoAgentInformation) super.set(fieldName, value);
  }

  @Override
  public AssistantVerticalsHomeautomationProtoAgentInformation clone() {
    return (AssistantVerticalsHomeautomationProtoAgentInformation) super.clone();
  }

}


text:
@interface ICDErrorUtils : NSObject

+ (NSString *)errorTips:(NSError *)error;

+ (NSError *)errorWithDomain:(NSString *)domain code:(NSInteger)code message:(NSString *)msg;

+ (BOOL)isNotLoggedInError:(NSError *)error;

@end


text:
package scalajson.ast

import scala.scalajs.js

/** Represents a valid JSON Value
  *
  * @author Matthew de Detrich
  * @see https://www.ietf.org/rfc/rfc4627.txt
  */
sealed abstract class JValue extends Product with Serializable {

  /**
    * Converts a [[JValue]] to a [[unsafe.JValue]]. Note that
    * when converting [[JObject]], this can produce [[unsafe.JObject]] of
    * unknown ordering, since ordering on a [[scala.collection.Map]] isn't defined.
    * Duplicate keys will also be removed in an undefined manner.
    *
    * @see https://www.ietf.org/rfc/rfc4627.txt
    * @return
    */
  def toUnsafe: unsafe.JValue

  /**
    * Converts a [[JValue]] to a Javascript object/value that can be used within
    * Javascript
    *
    * @return
    */
  def toJsAny: js.Any
}

/** Represents a JSON null value
  *
  * @author Matthew de Detrich
  */
final case object JNull extends JValue {
  override def toUnsafe: unsafe.JValue = unsafe.JNull

  override def toJsAny: js.Any = null
}

/** Represents a JSON string value
  *
  * @author Matthew de Detrich
  */
final case class JString(value: String) extends JValue {
  override def toUnsafe: unsafe.JValue = unsafe.JString(value)

  override def toJsAny: js.Any = value
}

object JNumber {
  def apply(value: Int): JNumber = new JNumber(value.toString)

  def apply(value: Integer): JNumber = new JNumber(value.toString)

  def apply(value: Long): JNumber = new JNumber(value.toString)

  def apply(value: BigInt): JNumber = new JNumber(value.toString())

  def apply(value: BigDecimal): JNumber = new JNumber(value.toString())

  /**
    * @param value
    * @return Will return a JNull if value is a Nan or Infinity
    */
  def apply(value: Double): JValue = value match {
    case n if n.isNaN      => JNull
    case n if n.isInfinity => JNull
    case _                 => new JNumber(value.toString)
  }

  /**
    * @param value
    * @return Will return a JNull if value is a Nan or Infinity
    */
  def apply(value: Float): JValue = value match {
    case n if java.lang.Float.isNaN(n) => JNull
    case n if n.isInfinity             => JNull
    case _                             => new JNumber(value.toString)
  }

  def apply(value: String): Option[JNumber] =
    fromString(value)

  def fromString(value: String): Option[JNumber] =
    value match {
      case jNumberRegex(_*) => Some(new JNumber(value))
      case _                => None
    }
}

/** Represents a JSON number value. If you are passing in a
  * NaN or Infinity as a [[scala.Double]] or [[scala.Float]], [[JNumber]] will
  * return a [[JNull]].
  *
  * @author Matthew de Detrich
  */
final case class JNumber private[ast] (value: String) extends JValue {

  override def toUnsafe: unsafe.JValue = unsafe.JNumber(value)

  override def toJsAny: js.Any = value.toDouble match {
    case n if n.isNaN      => null
    case n if n.isInfinity => null
    case n                 => n
  }

  override def equals(obj: Any): Boolean =
    obj match {
      case jNumber: JNumber =>
        numericStringEquals(value, jNumber.value)
      case _ => false
    }

  override def hashCode: Int =
    numericStringHashcode(value)

  def copy(value: String): JNumber =
    value match {
      case jNumberRegex(_*) => new JNumber(value)
      case _                => throw new NumberFormatException(value)
    }

  def toInt: Option[Int] = scalajson.ast.toInt(value)

  def toBigInt: Option[BigInt] = scalajson.ast.toBigInt(value)

  def toLong: Option[Long] = scalajson.ast.toLong(value)

  def toDouble: Double = scalajson.ast.toDouble(value)

  def toFloat: Float = scalajson.ast.toFloat(value)

  def toBigDecimal: Option[BigDecimal] = scalajson.ast.toBigDecimal(value)
}

/** Represents a JSON Boolean value, which can either be a
  * [[JTrue]] or a [[JFalse]]
  *
  * @author Matthew de Detrich
  */
// Implements named extractors so we can avoid boxing
sealed abstract class JBoolean extends JValue {
  def isEmpty: Boolean = false
  def get: Boolean

  override def toJsAny: js.Any = get
}

object JBoolean {
  def apply(x: Boolean): JBoolean = if (x) JTrue else JFalse

  def unapply(x: JBoolean): Some[Boolean] = Some(x.get)
}

/** Represents a JSON Boolean true value
  *
  * @author Matthew de Detrich
  */
final case object JTrue extends JBoolean {
  override def get = true

  override def toUnsafe: unsafe.JValue = unsafe.JTrue
}

/** Represents a JSON Boolean false value
  *
  * @author Matthew de Detrich
  */
final case object JFalse extends JBoolean {
  override def get = false

  override def toUnsafe: unsafe.JValue = unsafe.JFalse
}

/** Represents a JSON Object value. Keys must be unique
  * and are unordered
  *
  * @author Matthew de Detrich
  */
final case class JObject(value: Map[String, JValue] = Map.empty)
    extends JValue {

  /**
    * Construct a JObject using Javascript's object type, i.e. {} or new Object
    *
    * @param value
    */
  def this(value: js.Dictionary[JValue]) = {
    this(value.toMap)
  }

  override def toUnsafe: unsafe.JValue = {
    if (value.isEmpty) {
      unsafe.JObject(js.Array[unsafe.JField]())
    } else {
      val array = js.Array[unsafe.JField]()
      value.iterator.foreach { x =>
        array.push(unsafe.JField(x._1, x._2.toUnsafe))
      }
      unsafe.JObject(array)
    }
  }

  override def toJsAny: js.Any = {
    if (value.isEmpty) {
      js.Dictionary[js.Any]().asInstanceOf[js.Object]
    } else {
      val dict = js.Dictionary[js.Any]()
      value.iterator.foreach { x =>
        dict(x._1) = x._2.toJsAny
      }
      dict.asInstanceOf[js.Object]
    }
  }
}

object JArray {
  def apply(value: JValue, values: JValue*): JArray =
    JArray(value +: values.toVector)
}

/** Represents a JSON Array value
  *
  * @author Matthew de Detrich
  */
final case class JArray(value: Vector[JValue] = Vector.empty) extends JValue {

  /**
    *
    * Construct a JArray using Javascript's array type, i.e. `[]` or `new Array`
    *
    * @param value
    */
  def this(value: js.Array[JValue]) = {
    this(value.toVector)
  }

  override def toUnsafe: unsafe.JValue = {
    if (value.isEmpty) {
      unsafe.JArray(js.Array[unsafe.JValue]())
    } else {
      val iterator = value.iterator
      val array = js.Array[unsafe.JValue]()
      while (iterator.hasNext) {
        array.push(iterator.next().toUnsafe)
      }
      unsafe.JArray(array)
    }
  }

  override def toJsAny: js.Any = {
    if (value.isEmpty) {
      js.Array[js.Any]()
    } else {
      val iterator = value.iterator
      val array = js.Array[js.Any]()
      while (iterator.hasNext) {
        array.push(iterator.next().toJsAny)
      }
      array
    }
  }
}


text:
package com.mediamonks.googleflip.pages.game.management.gamemessages.s2c;

import com.mediamonks.googleflip.pages.game.management.gamemessages.GameMessageType;
import com.mediamonks.googleflip.data.vo.PlayerScoreVO;
import com.mediamonks.googleflip.pages.game.management.gamemessages.GameMessage;

import java.util.List;

/**
 * Message sent from server to client when the score of one or more clients has changed
 */
public class S2CClientsScoreChangedMessage implements GameMessage {
    public List<PlayerScoreVO> playerScores;

    public S2CClientsScoreChangedMessage(List<PlayerScoreVO> playerScores) {
        this.playerScores = playerScores;
    }

    @Override
    public GameMessageType getType() {
        return GameMessageType.S2C_CLIENTS_SCORE_CHANGED;
    }
}


text:
var test = require('tap').test;
var bunyan = require('../lib/bunyan'),
    Logger = bunyan;

test('ensure Logger creation options', function (t) {
  t.throws(function () { new Logger(); },
    {name: 'TypeError', message: 'options (object) is required'},
    'no options should throw');

  t.throws(function () { new Logger({}); },
    {name: 'TypeError', message: 'options.name (string) is required'},
    'no options.name should throw');

  t.doesNotThrow(function () { new Logger({name: 'foo'}); },
    'just options.name should be sufficient');

  var options = {name: 'foo', stream: process.stdout, streams: []};
  t.throws(function () { new Logger(options); },
    'cannot use "stream" and "streams"');

  // https://github.com/trentm/node-bunyan/issues/3
  options = {name: 'foo', streams: {}};
  t.throws(function () { new Logger(options); },
    {name: 'TypeError', message: 'invalid options.streams: must be an array'},
    '"streams" must be an array');

  options = {name: 'foo', serializers: 'a string'};
  t.throws(function () { new Logger(options); },
    {
      name: 'TypeError',
      message: 'invalid options.serializers: must be an object'
    },
    '"serializers" cannot be a string');

  options = {name: 'foo', serializers: [1, 2, 3]};
  t.throws(function () { new Logger(options); },
    {
      name: 'TypeError',
      message: 'invalid options.serializers: must be an object'
    },
    '"serializers" cannot be an array');

  t.end();
});

test('ensure Logger creation options (createLogger)', function (t) {
  t.throws(function () { bunyan.createLogger(); },
    {name: 'TypeError', message: 'options (object) is required'},
    'no options should throw');

  t.throws(function () { bunyan.createLogger({}); },
    {name: 'TypeError', message: 'options.name (string) is required'},
    'no options.name should throw');

  t.doesNotThrow(function () { bunyan.createLogger({name: 'foo'}); },
    'just options.name should be sufficient');

  var options = {name: 'foo', stream: process.stdout, streams: []};
  t.throws(function () { bunyan.createLogger(options); },
    'cannot use "stream" and "streams"');

  // https://github.com/trentm/node-bunyan/issues/3
  options = {name: 'foo', streams: {}};
  t.throws(function () { bunyan.createLogger(options); },
    {name: 'TypeError', message: 'invalid options.streams: must be an array'},
    '"streams" must be an array');

  options = {name: 'foo', serializers: 'a string'};
  t.throws(function () { bunyan.createLogger(options); },
    {
      name: 'TypeError',
      message: 'invalid options.serializers: must be an object'
    },
    '"serializers" cannot be a string');

  options = {name: 'foo', serializers: [1, 2, 3]};
  t.throws(function () { bunyan.createLogger(options); },
    {
      name: 'TypeError',
      message: 'invalid options.serializers: must be an object'
    },
    '"serializers" cannot be an array');

  t.end();
});

test('ensure Logger child() options', function (t) {
  var log = new Logger({name: 'foo'});

  t.doesNotThrow(function () { log.child(); },
    'no options should be fine');

  t.doesNotThrow(function () { log.child({}); },
    'empty options should be fine too');

  t.throws(function () { log.child({name: 'foo'}); },
    {
      name: 'TypeError',
      message: 'invalid options.name: child cannot set logger name'
    },
    'child cannot change name');

  var options = {stream: process.stdout, streams: []};
  t.throws(function () { log.child(options); },
    'cannot use "stream" and "streams"');

  // https://github.com/trentm/node-bunyan/issues/3
  options = {streams: {}};
  t.throws(function () { log.child(options); },
    {name: 'TypeError', message: 'invalid options.streams: must be an array'},
    '"streams" must be an array');

  options = {serializers: 'a string'};
  t.throws(function () { log.child(options); },
    {
      name: 'TypeError',
      message: 'invalid options.serializers: must be an object'
    },
    '"serializers" cannot be a string');

  options = {serializers: [1, 2, 3]};
  t.throws(function () { log.child(options); },
    {
      name: 'TypeError',
      message: 'invalid options.serializers: must be an object'
    },
    '"serializers" cannot be an array');

  t.end();
});


text:
function openNav() {
    document.getElementById("mySidenav").style.width = "250px"; //Default: 250px. Edit to your liking.
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}


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

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.iottwinmaker.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ListScenesRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListScenesRequestMarshaller {

    private static final MarshallingInfo<String> WORKSPACEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
            .marshallLocationName("workspaceId").build();
    private static final MarshallingInfo<Integer> MAXRESULTS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("maxResults").build();
    private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("nextToken").build();

    private static final ListScenesRequestMarshaller instance = new ListScenesRequestMarshaller();

    public static ListScenesRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ListScenesRequest listScenesRequest, ProtocolMarshaller protocolMarshaller) {

        if (listScenesRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(listScenesRequest.getWorkspaceId(), WORKSPACEID_BINDING);
            protocolMarshaller.marshall(listScenesRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(listScenesRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
/*
test custom filename and content-type:
re: https://github.com/felixge/node-form-data/issues/29
*/

var common       = require('../common');
var assert       = common.assert;
var http         = require('http');
var fs           = require('fs');

var FormData     = require(common.dir.lib + '/form_data');
var IncomingForm = require('formidable').IncomingForm;

var options = {
  filename: 'test.png',
  contentType: 'image/gif'
};

var server = http.createServer(function(req, res) {

  var form = new IncomingForm({uploadDir: common.dir.tmp});

  form.parse(req);

  form
    .on('file', function(name, file) {
      assert.strictEqual(name, 'my_file');
      assert.strictEqual(file.name, options.filename);
      assert.strictEqual(file.type, options.contentType);
    })
    .on('end', function() {
      res.writeHead(200);
      res.end('done');
    });
});

server.listen(common.port, function() {
  var form = new FormData();

  form.append('my_file', fs.createReadStream(common.dir.fixture + '/unicycle.jpg'), options);

  form.submit('http://localhost:' + common.port + '/', function(err, res) {
    if (err) {
      throw err;
    }

    assert.strictEqual(res.statusCode, 200);
    server.close();
  });

});


text:
require 'spec_helper'

describe DistributeDeposit do
  let(:gateway) { double('gateway') }
  let(:action) { DistributeDeposit.new(gateway) }
  let(:transaction_date) { jan_this_year }
  let(:transaction) { Transaction.new posted_at: transaction_date }

  before(:each) do
    gateway.stub(:transaction_by_id) { transaction }
    gateway.stub(:credits) { [] }
  end

  it "credits categories" do
    args = {
      transaction_id: 1,
      credits: [
        {category: "cat1", amount: 5},
        {category: "cat2", amount: 7}
      ]
    }
    gateway.should_receive(:save).twice
    action.run args
  end

  it "removes credits if needed" do
    gateway.stub(:credits) { [Credit.new(transaction_id: 1,)] }
    gateway.should_receive(:delete)
    action.run transaction_id: 1, credits: []
  end

  it "updates credits if needed" do
    gateway.stub(:credits) { [Credit.new(transaction_id: 1, category: "cat1", amount: 10)] }
    gateway.should_receive(:delete)
    gateway.should_receive(:save)
    action.run transaction_id: 1, credits: [ {category: "cat1", amount: 5} ]
  end

  it "applies to next month after transaction date by default" do
    gateway.should_receive(:save) { |credit| credit.date_applied.should == transaction_date.to_date.next_month.to_time }
    action.run transaction_id: 1, credits: [ {category: "cat1", amount: 5} ]
  end

  it "can be applied to different months" do
    gateway.should_receive(:save) { |credit| credit.date_applied.should == jan_this_year }
    action.run transaction_id: 1, date_applied: jan_this_year, credits: [ {category: "cat1", amount: 5} ]
  end

  it "does not update credits when not needed" do
    gateway.stub(:credits) { [Credit.new(transaction_id: 1, category: "cat1", amount: 5, date_applied: last_month )] }
    gateway.should_not_receive(:delete)
    gateway.should_not_receive(:save)
    action.run transaction_id: 1, date_applied: last_month, credits: [ {category: "cat1", amount: 5} ]
  end
end


text:
Johan is playing a special version of the card game Yu-Gi-Oh! with Simon. In the game, each card has an attack value ATK and
a defense value DEF.

A card can be in one of two modes, attack mode or defense mode. When a card A in attack mode
attacks another card B in defense mode, card B is destroyed if ATK(A) is larger than DEF(B).
When a card A in attack mode attacks another card B in attack mode, card B is destroyed if ATK(A)
is larger than ATK(B), and the difference is dealt as damage to the defending players life points.

A card is only allowed to attack one other card per turn.

All of Johan's cards (there are 5 of them) are currently in attack mode, and all of Simon's cards (there are 5 of them) are currently in defense mode.
Now, the following procedure will play out:

Johan may attack some of Simon's cards

Johan ends his turn and gives the turn to Simon

All of Simon's cards will be put in attack mode

Simon may attack some of Johan's cards

Johan obviously want to lose as little life points as possible the next turn. If he attacks optimally this
turn, what is the maximum damage Simon can deal to him?

Input format

The first line contains 5 positive integers $0 \le ATK \le 3000$, the attack values of Johan's cards.
The second line contains 5 positive integers $0 \le ATK \le 3000$, the attack values of Simon's cards.
The third line contains 5 positive integers $0 \le DEF \le 3000$, the defense values of Simon's cards.

Output format

The first and only line should contain a single integer: the maximum number of life points Johan will lose
if he plays optimally.


text:
cookbook_file File.join(node['munin']['basedir'], "plugin-conf.d/omnibus_gitlab_sidekiq_rss.conf") do
  notifies :restart, "service[munin-node]"
end

cookbook_file File.join(node['munin']['plugin_dir'], "omnibus_gitlab_sidekiq_rss") do
  mode "0755"
  notifies :restart, "service[munin-node]"
end

munin_plugin 'omnibus_gitlab_sidekiq_rss' do
  notifies :restart, "service[munin-node]"
end


text:
data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord)

-- record 语法
-- data List a = Empty | Cons { listHead :: a, listTail :: List a } deriving (Show, Read, Eq, Ord)
infixr 5 :-:
data List1 a = Empty1 | a :-: (List1 a) deriving (Show, Read, Eq, Ord)

-- make a function that adds two of our lists together.
-- infixr 5 ++
-- (++) :: [a] -> [a] -> [a]
-- [] ++ ys = ys
-- (x:xs) ++ ys = x : (xs ++ ys)
infixr 5 .++
(.++) :: List1 a -> List1 a -> List1 a
Empty1 .++ ys = ys
(x :-: xs) .++ ys = x :-: (xs .++ ys)

-- Binary Search Trees

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

-- 写个函数, 参数为 tree 和一个新元素,并插入元素

-- 生成只有一个节点的树的函数

singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree

-- 插入新元素
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
    --  if the element we're inserting is equal to the root element, just return a tree that's the same. 如果插入元素等于 根节点就返回该树
    | x == a = Node x left right  -- edge condition
    | x < a = Node a (treeInsert x left) right
    | x > a = Node a left (treeInsert x right)

-- 检查元素是否在树里
treeElem :: (Ord a ) => a -> Tree a -> Bool
treeElem x EmptyTree = False
treeElem x (Node a left right)
    | x == a = True
    | x < a = treeElem x left
    | x > a = treeElem x right
-- foldr 中 treeInsert 是 fold function 参数为 list element 生成一个 new tree
-- EmptyTree 是 起始 accumulator.


text:
"""Module containing the class StorySet described below."""

import importlib
import os
import sys

from croissant.step.exceptions import *
from croissant.story.story import Story

class StorySet:

    """Class containing a set of user's story.

    Usually, an empty story set is created.  Then, stories and steps are
    loaded from a directory.  You can, however, create story sets that do
    not use the file system (or not in the same way) to load stories and
    steps.

    It contains:
        steps -- the user's steps
        stories -- the user's stories

    """

    def __init__(self):
        self.stories = {}
        self.steps = {}
        self.path = None

    def load(self, root):
        """Load the steps and stories in a directory.

        The stories are supposed to be stored in files with the '.feature'
        extension.  The steps, on the other hand, are stored in '.py'
        files.  The given directory could have two different structures:
        * Either it contains only sub-directories: in this case, each
          sub-directory is recursively browsed, but the root of
          the project is considered to be the sub-directory (see the
          example below).
        * Or the root directory contains files.  In this context,
          the root directory remains the root of the project.

        For instance:
          If you have the following directory structure:
            example/
                features/
                    fist.feature
                    second.feature
                steps/
                    first.py
                    second.py
          Then the step in 'example/steps/first.py' will be stored in
          the 'first' module (example and steps are not included).
          But if you have the following directory structure:
            example/
                fist.feature
                second.feature
                first.py
                second.py
          Then the root directory will be 'example'.

        """
        self.path = root
        sys.path.append(root)

        # If the root directory only contains sub-directory
        if all(os.path.isdir(os.path.join(root, name)) for name in \
                os.listdir(root)):
            min_depth = 1
        else:
            min_depth = 0

        self.load_directory(None, min_depth)

    def load_directory(self, directory, min_depth):
        """Recursively load a directory and its content.

        This method is automatically called by the 'load' method and
        should not be called directly by the user.  Its role is to be
        consistent with the structure of the root directory (which is
        analyzed in the 'load' method).

        """
        path = directory and os.path.join(self.path, directory) or self.path
        for file in os.listdir(path):
            rel_path = directory and os.path.join(directory, file) or file
            full_path = os.path.join(path, file)
            if file.endswith(".py"):
                self.load_step(rel_path, min_depth)
            elif file.endswith(".feature"):
                self.load_story(rel_path, min_depth)
            elif os.path.isdir(full_path):
                self.load_directory(rel_path, min_depth)

    def load_story(self, path, min_depth):
        """Load a specific story from a file."""
        full_path = os.path.join(self.path, path)
        with open(full_path, "r") as file:
            content = file.read()

        story = Story.parse(path, content)
        name = os.path.basename(path)[:-8]
        basename = self.get_base_name(path, min_depth)
        id_name = basename and basename + "." + name or name
        self.stories[id_name] = story

    def load_step(self, path, min_depth):
        """Load a step from a Python file.

        This method loads the module (built from the specified path) and
        use its content to find non-defined steps.  Parent steps are
        supposedly NOT loaded.

        """
        dir_name = os.path.dirname(path)
        basename = self.get_base_name(path, min_depth)
        name = os.path.basename(path)[:-3]
        package = dir_name.replace(os.path.sep, ".")
        module_name = package and package + "." + name or name
        id_name = basename and basename + "." + name or name
        module = importlib.import_module(module_name)
        classes = [value for value in module.__dict__.values() if \
                getattr(value, "croissant_path", None) == "unknown"]
        if len(classes) == 0:
            return
        elif len(classes) > 1:
            raise ValueError("multiple steps defined in the same file, it seems")
        else:
            class_object = classes[0]

        class_object.croissant_path = id_name
        self.steps[id_name] = class_object

    def run_story(self, name):
        """Run the specified story."""
        story = self.stories[name]
        for scenario in story.scenarios:
            self.run_scenario(name, scenario)

    def run_scenario(self, story_name, scenario):
        """Run the specified scenario."""
        # Create the step for this scenario
        class_object = self.steps[story_name]
        step = class_object(scenario)

        # Call the contexts
        for context in scenario.contexts:
            method_name = self.find_expression(class_object.contexts,
                    scenario, context)
            getattr(step, method_name)(context)

        # Call the event
        method_name = self.find_expression(class_object.events,
                scenario, scenario.event)
        getattr(step, method_name)(scenario.event)

        # Call the postconditions
        for postcondition in scenario.postconditions:
            method_name = self.find_expression(class_object.postconditions,
                    scenario, postcondition)
            getattr(step, method_name)(postcondition)

    @staticmethod
    def find_expression(expressions, scenario, message):
        """Find the method name corresponding to the specified expression."""
        for expression, method_name in expressions.items():
            if expression.search(message):
                return method_name

        raise StepNotFound(scenario, message)

    @staticmethod
    def get_base_name(path, min_depth):
        """Return the path's name without the root directory."""
        dirs = path.split(os.path.sep)
        if len(dirs) < min_depth + 1:
            raise ValueError("Invalid directory")

        del dirs[-1]
        for i in range(min_depth):
            del dirs[0]

        return ".".join(dirs)


text:
#include "iterator.h"
#include <stdlib.h>

/*
 * implementation for generic iterator
 *
 * patterned roughly after Java 6 Iterator class
 */

struct iterator {
    long next;
    long size;
    void **elements;
};

Iterator *it_create(long size, void **elements) {
    Iterator *it = (Iterator *)malloc(sizeof(Iterator));

    if (it != NULL) {
        it->next = 0L;
        it->size = size;
        it->elements = elements;
    }
    return it;
}

int it_hasNext(Iterator *it) {
    return (it->next < it->size) ? 1 : 0;
}

int it_next(Iterator *it, void **element) {
    int status = 0;
    if (it->next < it->size) {
        *element = it->elements[it->next++];
        status = 1;
    }
    return status;
}

void it_destroy(Iterator *it) {
    free(it->elements);
    free(it);
}


text:
echo "\\033[01;31mWARNING: ${0} is deprecated; please use \`php get-composer.php\` instead.\\033[0m" >&2
php get-composer.php


text:
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using Microsoft.Azure.Mobile.Server.Tables;
using PoliceDispatcher.Azure.DataObjects;

namespace PoliceDispatcher.Azure.Models
{
    public class MobileServiceContext : DbContext
    {
        private const string ConnectionStringName = "Name=PoliceDispatcherAzure";

        public MobileServiceContext() : base(ConnectionStringName)
        {
        }

        public DbSet<OfficerStatus> OfficerStatuses { get; set; }
        public DbSet<DispatcherAlert> Incidents { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Add(
                new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
                    "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
        }
    }
}


text:
package com.rentIT.security;

import com.rentIT.util.JwtSecurityDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Date;
import java.util.stream.Collectors;

@Component
@Slf4j
public class TokenProvider {

    private static final String AUTHORITIES_KEY = "auth";

    private String secretKey;
    private long tokenValidityInSeconds;

    @Autowired
    private JwtSecurityDetails jwtSecurityDetails;

    @PostConstruct
    private void init() {
        this.secretKey = jwtSecurityDetails.getSecretKey();
        this.tokenValidityInSeconds = 1000 * Long.valueOf(jwtSecurityDetails.getTokenValidityInSeconds());
    }

    public String createToken(Authentication authentication, Boolean rememberMe) {
        String authorities = authentication.getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority)
                                .collect(Collectors.joining(","));
        long now = (new Date()).getTime();
        Date validity = new Date(now + tokenValidityInSeconds);

        return Jwts.builder().setSubject(authentication.getName()).claim(AUTHORITIES_KEY, authorities)
                .signWith(SignatureAlgorithm.HS512, secretKey).setExpiration(validity).compact();

    }
    public boolean validateToken(String jwt) {
        try {
            Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt);
            return true;
        } catch (SignatureException e) {
            log.info("Invalid JWT signature: " + e.getMessage());
            return false;
        }
    }

    public Authentication getAuthentication(String jwt) {
        Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
        User principal = new User(claims.getSubject(),"", new ArrayList<>());
        return new UsernamePasswordAuthenticationToken(principal,"", new ArrayList<>());
    }
}


text:
import { StyleContainer } from '../style';

export interface ListVariables {
  root?: StyleContainer;
}