text:
define(function(require) {
  'use strict';

  var modules = require('modules');
  var states = require('states');
  var _ = require('lodash');

  modules.get('a4c-auth', ['ngResource']).factory('authService', ['$resource', '$state', '$http',
    function($resource, $state, $http) {
      var userStatusResource = $resource('rest/latest/auth/status', {}, {
        'query': {
          method: 'GET',
          isArray: false
        }
      });
      // get default 'all-users' group
      var defaultAllUsersGroup = $resource('rest/latest/auth/groups/allusers', {}, {
        'query': {
          method: 'GET',
          isArray: false
        }
      }).query();

      /* Permissions */
      var allAccessAdminRole = 'ADMIN';

      return {
        currentStatus: null,
        menu: states.rootMenu(),

        onCurrentStatus: function() {
          var self = this;
          _.each(this.menu, function(menuItem) {
            menuItem.hasRole = self.hasOneRoleIn(menuItem.roles);
          });
        },

        getStatus: function() {
          var self = this;
          if (this.currentStatus === null) {
            this.currentStatus = userStatusResource.query();
            this.currentStatus.$promise.then(function() {
              self.onCurrentStatus();
            });
          }
          return this.currentStatus;
        },

        authorizationCheck: function(checkCallback) {
          var self = this;
          if (typeof this.currentStatus.data !== 'undefined') {
            return checkCallback(this.currentStatus.data);
          } else {
            return this.getStatus().$promise.then(
              function() {
                return checkCallback(self.currentStatus.data);
              }
            );
          }
        },

        /** Checks if the user has one of the role requested. */
        hasOneRoleIn: function(roles) {
          if (!_.isEmpty(roles)) {
            return this.authorizationCheck(
              function(userData) {
                if (!userData.isLogged) {
                  return false;
                }
                if (userData.roles.indexOf(allAccessAdminRole) > -1) {
                  return true;
                }
                for (var i = 0; i < roles.length; i++) {
                  var hasRole = userData.roles.indexOf(roles[i]) > -1;
                  if (hasRole) {
                    return true;
                  }
                }
                return false;
              }
            );
          } else {
            // empty roles array => full access for authenticated user at least
            return true;
          }
        },

        getRolesForResource: function(resource, userStatus) {
          var allRoles;
          var userRoles = resource.userRoles[userStatus.username];
          if (!_.isEmpty(userRoles)) {
            allRoles = userRoles;
          }
          var groups = userStatus.groups;
          if (_.undefined(groups)) {
            groups = [];
          }
          if (_.defined(defaultAllUsersGroup.data)) {
            groups.push(defaultAllUsersGroup.data.id);
          }
          var groupRolesMap = resource.groupRoles;
          if (_.defined(groups) && !_.isEmpty(groups) && _.defined(groupRolesMap) && !_.isEmpty(groupRolesMap)) {
            for (var i = 0; i < groups.length; i++) {
              var group = groups[i];
              if (groupRolesMap.hasOwnProperty(group)) {
                allRoles = _.union(allRoles, groupRolesMap[group]);
              }
            }
          }
          return _.defined(allRoles) ? allRoles : [];
        },

        /** Check if a user has access to a resource. Return true if user has at least one of the given roles **/
        hasResourceRoleIn: function(resource, roles) {
          var self = this;
          return this.authorizationCheck(
            function(userStatus) {
              // check all accessible roles first
              if (userStatus.roles.indexOf(allAccessAdminRole) > -1) {
                return true;
              }
              // check if the user has the role.
              var currentUserRoles = self.getRolesForResource(resource, userStatus);
              for (var i = 0; i < roles.length; i++) {
                if (currentUserRoles.indexOf(roles[i]) >= 0) {
                  return true;
                }
              }
              return false;
            });
        },

        /**
         * LogOut and redirect to home.
         */
        logOut: function() {
          var self = this;
          $http.post('logout').success(function() {
            self.currentStatus = userStatusResource.query();
            $state.go('home', {}, {
              reload: true
            });
          });
        },
        /**
         * Login and redirect to target
         */
        logIn: function(data, scope) {
          var self = this;
          $http.post('login', data, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).success(function() {
            self.currentStatus = userStatusResource.query(function(loginResult) {
              // get the new status from server
              if (loginResult.data.isLogged === false) {
                var loginError = {
                  'show': true,
                  'data': 'Authentication error. Invalid username or password.'
                };
                scope.error = loginError;
              }
              $state.go('home', {}, {
                reload: true
              });
            });
            self.currentStatus.$promise.then(function() {
              self.onCurrentStatus();
            });

            return self.currentStatus;
          }).error(function() {
            self.currentStatus = {
              'data': {
                'isLogged': false
              }
            };
          });
        },

        /**
         * Checks if the current user has the requested role.
         */
        hasRole: function(role) {
          return this.hasOneRoleIn([role]);
        },

        /**
         * Check if a user has access to a resource. Return true if user has the given role
         */
        hasResourceRole: function(resource, role) {
          return this.hasResourceRoleIn(resource, [role]);
        }
      };
    }
  ]);
});


text:
import numpy as np
import pandas as pd
import string
import math
import csv
import collections
import os
import warnings
from echo_functions import *
from echo_base import *

__all__ = ["EchoSourceMaterial"]

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Epfremme\Swagger\Type;

/**
 * Marker interface for numeric types.
 */
interface NumericTypeInterface
{
}


text:
struct s_datatype {
   int handle;
   MPI_Datatype type;
};

int init_datatypes(void);

int free_datatype(datatype *type);
datatype *add_datatype(MPI_Datatype mtype);
datatype *handle_to_datatype(EMPI_Datatype handle);
EMPI_Datatype datatype_to_handle(datatype *d);
int is_derived_datatype(EMPI_Datatype type);

#endif


text:
layout: post
title: "Economy Watch - Home prices in..."
---
Economy Watch - Home prices in Las Vegas have a 91 percent chance of declining in the next two years. -


text:
select
  l_orderkey,
  count(*) as cnt,
  row_number() over (order by count(*) desc) row_num
from
  lineitem
group by
  l_orderkey


text:
<?php
/**
 * Export
 *
 * PHP version 7.3
 *
 * @category Class
 * @package  OpenAPI\Client
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * Lob
 *
 * The Lob API is organized around REST. Our API is designed to have predictable, resource-oriented URLs and uses HTTP response codes to indicate any API errors. <p> Looking for our [previous documentation](https://lob.github.io/legacy-docs/)?
 *
 * The version of the OpenAPI document: 1.3.0
 * Contact: lob-openapi@lob.com
 * Generated by: https://openapi-generator.tech
 * OpenAPI Generator version: 5.2.1
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

namespace OpenAPI\Client\Model;

use \ArrayAccess;
use \OpenAPI\Client\ObjectSerializer;

/**
 * Export Class Doc Comment
 *
 * @category Class
 * @package  OpenAPI\Client
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 * @implements \ArrayAccess<TKey, TValue>
 * @template TKey int|null
 * @template TValue mixed|null
 */
class Export implements ModelInterface, ArrayAccess, \JsonSerializable
{
    public const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $openAPIModelName = 'export';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $openAPITypes = [
        'id' => 'string',
        'date_created' => '\DateTime',
        'date_modified' => '\DateTime',
        'deleted' => 'bool',
        's3_url' => 'string',
        'state' => 'string',
        'type' => 'string',
        'upload_id' => 'string'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      * @phpstan-var array<string, string|null>
      * @psalm-var array<string, string|null>
      */
    protected static $openAPIFormats = [
        'id' => null,
        'date_created' => 'date-time',
        'date_modified' => 'date-time',
        'deleted' => null,
        's3_url' => null,
        'state' => null,
        'type' => null,
        'upload_id' => null
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function openAPITypes()
    {
        return self::$openAPITypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function openAPIFormats()
    {
        return self::$openAPIFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'id' => 'id',
        'date_created' => 'dateCreated',
        'date_modified' => 'dateModified',
        'deleted' => 'deleted',
        's3_url' => 's3Url',
        'state' => 'state',
        'type' => 'type',
        'upload_id' => 'uploadId'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'id' => 'setId',
        'date_created' => 'setDateCreated',
        'date_modified' => 'setDateModified',
        'deleted' => 'setDeleted',
        's3_url' => 'setS3Url',
        'state' => 'setState',
        'type' => 'setType',
        'upload_id' => 'setUploadId'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'id' => 'getId',
        'date_created' => 'getDateCreated',
        'date_modified' => 'getDateModified',
        'deleted' => 'getDeleted',
        's3_url' => 'getS3Url',
        'state' => 'getState',
        'type' => 'getType',
        'upload_id' => 'getUploadId'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$openAPIModelName;
    }

    const STATE_IN_PROGRESS = 'in_progress';
    const STATE_FAILED = 'failed';
    const STATE_SUCCEEDED = 'succeeded';
    const TYPE_ALL = 'all';
    const TYPE_FAILURES = 'failures';
    const TYPE_SUCCESSES = 'successes';

    /**
     * Gets allowable values of the enum
     *
     * @return string[]
     */
    public function getStateAllowableValues()
    {
        return [
            self::STATE_IN_PROGRESS,
            self::STATE_FAILED,
            self::STATE_SUCCEEDED,
        ];
    }

    /**
     * Gets allowable values of the enum
     *
     * @return string[]
     */
    public function getTypeAllowableValues()
    {
        return [
            self::TYPE_ALL,
            self::TYPE_FAILURES,
            self::TYPE_SUCCESSES,
        ];
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['id'] = $data['id'] ?? null;
        $this->container['date_created'] = $data['date_created'] ?? null;
        $this->container['date_modified'] = $data['date_modified'] ?? null;
        $this->container['deleted'] = $data['deleted'] ?? null;
        $this->container['s3_url'] = $data['s3_url'] ?? null;
        $this->container['state'] = $data['state'] ?? null;
        $this->container['type'] = $data['type'] ?? null;
        $this->container['upload_id'] = $data['upload_id'] ?? null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if ($this->container['id'] === null) {
                $invalidProperties[] = "'id' can't be null";
            }
        }
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if (!preg_match("/^ex_[a-zA-Z0-9]+$/", $this->container['id'])) {
                $invalidProperties[] = "invalid value for 'id', must be conform to the pattern /^ex_[a-zA-Z0-9]+$/.";
            }

        }
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if ($this->container['date_created'] === null) {
                $invalidProperties[] = "'date_created' can't be null";
            }
        }
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if ($this->container['date_modified'] === null) {
                $invalidProperties[] = "'date_modified' can't be null";
            }
        }
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if ($this->container['deleted'] === null) {
                $invalidProperties[] = "'deleted' can't be null";
            }
        }
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if ($this->container['state'] === null) {
                $invalidProperties[] = "'state' can't be null";
            }
        }
        $allowedValues = $this->getStateAllowableValues();
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if (!is_null($this->container['state']) && !in_array($this->container['state'], $allowedValues, true)) {
                $invalidProperties[] = sprintf(
                    "invalid value '%s' for 'state', must be one of '%s'",
                    $this->container['state'],
                    implode("', '", $allowedValues)
                );
            }
        }

        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if ($this->container['type'] === null) {
                $invalidProperties[] = "'type' can't be null";
            }
        }
        $allowedValues = $this->getTypeAllowableValues();
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if (!is_null($this->container['type']) && !in_array($this->container['type'], $allowedValues, true)) {
                $invalidProperties[] = sprintf(
                    "invalid value '%s' for 'type', must be one of '%s'",
                    $this->container['type'],
                    implode("', '", $allowedValues)
                );
            }
        }

        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if ($this->container['upload_id'] === null) {
                $invalidProperties[] = "'upload_id' can't be null";
            }
        }
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if (!preg_match("/^upl_[a-zA-Z0-9]+$/", $this->container['upload_id'])) {
                $invalidProperties[] = "invalid value for 'upload_id', must be conform to the pattern /^upl_[a-zA-Z0-9]+$/.";
            }

        }
        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets id
     *
     * @return string
     */
    public function getId()
    {
        return $this->container['id'];
    }

    /**
     * Sets id
     *
     * @param string $id Unique identifier prefixed with `ex_`.
     *
     * @return self
     */
    public function setId($id)
    {
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {

            if ((!preg_match("/^ex_[a-zA-Z0-9]+$/", $id))) {
                throw new \InvalidArgumentException("invalid value for $id when calling Export., must conform to the pattern /^ex_[a-zA-Z0-9]+$/.");
            }

        }
        $this->container['id'] = $id;

        return $this;
    }

    /**
     * Gets date_created
     *
     * @return \DateTime
     */
    public function getDateCreated()
    {
        return $this->container['date_created'];
    }

    /**
     * Sets date_created
     *
     * @param \DateTime $date_created A timestamp in ISO 8601 format of the date the export was created
     *
     * @return self
     */
    public function setDateCreated($date_created)
    {
        $this->container['date_created'] = $date_created;

        return $this;
    }

    /**
     * Gets date_modified
     *
     * @return \DateTime
     */
    public function getDateModified()
    {
        return $this->container['date_modified'];
    }

    /**
     * Sets date_modified
     *
     * @param \DateTime $date_modified A timestamp in ISO 8601 format of the date the export was last modified
     *
     * @return self
     */
    public function setDateModified($date_modified)
    {
        $this->container['date_modified'] = $date_modified;

        return $this;
    }

    /**
     * Gets deleted
     *
     * @return bool
     */
    public function getDeleted()
    {
        return $this->container['deleted'];
    }

    /**
     * Sets deleted
     *
     * @param bool $deleted Returns as `true` if the resource has been successfully deleted.
     *
     * @return self
     */
    public function setDeleted($deleted)
    {
        $this->container['deleted'] = $deleted;

        return $this;
    }

    /**
     * Gets s3_url
     *
     * @return string|null
     */
    public function getS3Url()
    {
        return $this->container['s3_url'];
    }

    /**
     * Sets s3_url
     *
     * @param string|null $s3_url The URL for the generated export file.
     *
     * @return self
     */
    public function setS3Url($s3_url)
    {
        $this->container['s3_url'] = $s3_url;

        return $this;
    }

    /**
     * Gets state
     *
     * @return string
     */
    public function getState()
    {
        return $this->container['state'];
    }

    /**
     * Sets state
     *
     * @param string $state The state of the export file, which can be `in_progress`, `failed` or `succeeded`.
     *
     * @return self
     */
    public function setState($state)
    {
        $allowedValues = $this->getStateAllowableValues();
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if (!in_array($state, $allowedValues, true)) {
                throw new \InvalidArgumentException(
                    sprintf(
                        "Invalid value '%s' for 'state', must be one of '%s'",
                        $state,
                        implode("', '", $allowedValues)
                    )
                );
            }
        }

        $this->container['state'] = $state;

        return $this;
    }

    /**
     * Gets type
     *
     * @return string
     */
    public function getType()
    {
        return $this->container['type'];
    }

    /**
     * Sets type
     *
     * @param string $type The export file type, which can be `all`, `failures` or `successes`.
     *
     * @return self
     */
    public function setType($type)
    {
        $allowedValues = $this->getTypeAllowableValues();
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {
            if (!in_array($type, $allowedValues, true)) {
                throw new \InvalidArgumentException(
                    sprintf(
                        "Invalid value '%s' for 'type', must be one of '%s'",
                        $type,
                        implode("', '", $allowedValues)
                    )
                );
            }
        }

        $this->container['type'] = $type;

        return $this;
    }

    /**
     * Gets upload_id
     *
     * @return string
     */
    public function getUploadId()
    {
        return $this->container['upload_id'];
    }

    /**
     * Sets upload_id
     *
     * @param string $upload_id Unique identifier prefixed with `upl_`.
     *
     * @return self
     */
    public function setUploadId($upload_id)
    {
        if (!method_exists($this, 'getId') || (!empty($this->getId()) && strpos($this->getId(), "fakeId") === False)) {

            if ((!preg_match("/^upl_[a-zA-Z0-9]+$/", $upload_id))) {
                throw new \InvalidArgumentException("invalid value for $upload_id when calling Export., must conform to the pattern /^upl_[a-zA-Z0-9]+$/.");
            }

        }
        $this->container['upload_id'] = $upload_id;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    #[\ReturnTypeWillChange]
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed|null
     */
    #[\ReturnTypeWillChange]
    public function offsetGet($offset)
    {
        return $this->container[$offset] ?? null;
    }

    /**
     * Sets value based on offset.
     *
     * @param int|null $offset Offset
     * @param mixed    $value  Value to be set
     *
     * @return void
     */
    #[\ReturnTypeWillChange]
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     */
    #[\ReturnTypeWillChange]
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Serializes the object to a value that can be serialized natively by json_encode().
     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
     *
     * @return mixed Returns data which can be serialized by json_encode(), which is a value
     * of any type other than a resource.
     */
    #[\ReturnTypeWillChange]
    public function jsonSerialize()
    {
       return ObjectSerializer::sanitizeForSerialization($this);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        return json_encode(
            ObjectSerializer::sanitizeForSerialization($this),
            JSON_PRETTY_PRINT
        );
    }

    /**
     * Gets a header-safe presentation of the object
     *
     * @return string
     */
    public function toHeaderValue()
    {
        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
@interface PodsDummy_TWRDownloadManager : NSObject
@end
@implementation PodsDummy_TWRDownloadManager
@end


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Modal | Promafa Beta</title>
	<meta name="viewport"
	      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>

	<link rel="stylesheet" href="dist/css/villa.min.css"/>
	<link rel="stylesheet" href="css/main.css"/>
	<link rel="stylesheet" href="css/typography.css"/>
	<link rel="stylesheet" href="css/element.css"/>
	<link rel="stylesheet" href="css/mobile.css"/>
	<link rel="stylesheet" href="css/icon.css"/>
	<link rel="stylesheet" href="css/modal.css"/>

		Encontrar Representantes


text:
module Fog
  module Compute
    class OpenStack
      class Real
        def boot_from_snapshot(name, image_ref, flavor_ref, options={})
          data = {
            'server' => {
              'flavorRef'  => flavor_ref,
              'imageRef'   => image_ref,
              'name'       => name
            }
          }

          vanilla_options = ['metadata', 'accessIPv4', 'accessIPv6',
                             'availability_zone', 'user_data', 'block_device_mapping',
                             'key_name', 'security_groups']
          vanilla_options.select{|o| options[o]}.each do |key|
            data['server'][key] = options[key]
          end

          if options['personality']
            data['server']['personality'] = []
            for file in options['personality']
              data['server']['personality'] << {
                'contents'  => Base64.encode64(file['contents']),
                'path'      => file['path']
              }
            end
          end

          request(
            :body     => Fog::JSON.encode(data),
            :expects  => [200, 202],
            :method   => 'POST',
            :path     => '/os-volumes_boot.json'
          )
        end
      end
    end # class OpenStack
  end # module Compute
end # module Fog


text:
body {
    font-family: Verdana, Helvetica, sans-serif;
    background-color: #FFFFCC;
}

div.appName {
    font-size: 30px;
}


text:
import React from 'react'
import { storiesOf } from '@storybook/react-native'
import { action } from '@storybook/addon-actions'
import { linkTo } from '@storybook/addon-links'

import SvgComponent from 'app/icons/FilterIcon'

storiesOf('FilterIcon', module)
.add('default', () => (
<FilterIcon></FilterIcon>))


text:
using System.Collections;
using System.Diagnostics;

namespace System.Runtime.Serialization
{
    public readonly struct SerializationEntry
    {
        private readonly string _name;
        private readonly object? _value;
        private readonly Type _type;

        internal SerializationEntry(string entryName, object? entryValue, Type entryType)
        {
            _name = entryName;
            _value = entryValue;
            _type = entryType;
        }

        public object? Value => _value;
        public string Name => _name;
        public Type ObjectType => _type;
    }

    public sealed class SerializationInfoEnumerator : IEnumerator
    {
        private readonly string[] _members;
        private readonly object?[] _data;
        private readonly Type[] _types;
        private readonly int _numItems;
        private int _currItem;
        private bool _current;

        internal SerializationInfoEnumerator(string[] members, object?[] info, Type[] types, int numItems)
        {
            Debug.Assert(members != null, "[SerializationInfoEnumerator.ctor]members!=null");
            Debug.Assert(info != null, "[SerializationInfoEnumerator.ctor]info!=null");
            Debug.Assert(types != null, "[SerializationInfoEnumerator.ctor]types!=null");
            Debug.Assert(numItems >= 0, "[SerializationInfoEnumerator.ctor]numItems>=0");
            Debug.Assert(members.Length >= numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems");
            Debug.Assert(info.Length >= numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems");
            Debug.Assert(types.Length >= numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems");

            _members = members;
            _data = info;
            _types = types;

            // The MoveNext semantic is much easier if we enforce that [0..m_numItems] are valid entries
            // in the enumerator, hence we subtract 1.
            _numItems = numItems - 1;
            _currItem = -1;
            _current = false;
        }

        public bool MoveNext()
        {
            if (_currItem < _numItems)
            {
                _currItem++;
                _current = true;
            }
            else
            {
                _current = false;
            }

            return _current;
        }

        object? IEnumerator.Current => Current;

        public SerializationEntry Current
        {
            get
            {
                if (!_current)
                {
                    throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
                }
                return new SerializationEntry(_members[_currItem], _data[_currItem], _types[_currItem]);
            }
        }

        public void Reset()
        {
            _currItem = -1;
            _current = false;
        }

        public string Name
        {
            get
            {
                if (!_current)
                {
                    throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
                }
                return _members[_currItem];
            }
        }
        public object? Value
        {
            get
            {
                if (!_current)
                {
                    throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
                }
                return _data[_currItem];
            }
        }
        public Type ObjectType
        {
            get
            {
                if (!_current)
                {
                    throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
                }
                return _types[_currItem];
            }
        }
    }
}


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {assert, assertInstanceof} from '../assert.js';
import * as dom from '../dom.js';
import {reportError} from '../error.js';
import * as expert from '../expert.js';
import {FaceOverlay} from '../face.js';
import {Point} from '../geometry.js';
import {DeviceOperator, parseMetadata} from '../mojo/device_operator.js';
import {
  AndroidControlAeAntibandingMode,
  AndroidControlAeMode,
  AndroidControlAeState,
  AndroidControlAfMode,
  AndroidControlAfState,
  AndroidControlAwbMode,
  AndroidControlAwbState,
  AndroidStatisticsFaceDetectMode,
  CameraMetadata,
  CameraMetadataEntry,
  CameraMetadataTag,
  StreamType,
} from '../mojo/type.js';
import {
  closeEndpoint,
  MojoEndpoint,
} from '../mojo/util.js';
import * as nav from '../nav.js';
import * as state from '../state.js';
import {
  ErrorLevel,
  ErrorType,
  Facing,
  getVideoTrackSettings,
  PreviewVideo,
  Resolution,
} from '../type.js';
import * as util from '../util.js';
import {WaitableEvent} from '../waitable_event.js';

import {
  StreamConstraints,
  toMediaStreamConstraints,
} from './stream_constraints.js';

/**
 * Creates a controller for the video preview of Camera view.
 */
export class Preview {
  /**
   * Video element to capture the stream.
   */
  private video = dom.get('#preview-video', HTMLVideoElement);

  /**
   * The observer endpoint for preview metadata.
   */
  private metadataObserver: MojoEndpoint|null = null;

  /**
   * The face overlay for showing faces over preview.
   */
  private faceOverlay: FaceOverlay|null = null;

  /**
   * Current active stream.
   */
  private streamInternal: MediaStream|null = null;

  /**
   * Watchdog for stream-end.
   */
  private watchdog: number|null = null;

  /**
   * Unique marker for the current applying focus.
   */
  private focusMarker: symbol|null = null;

  private facing: Facing|null = null;

  private deviceId: string|null = null;

  private vidPid: string|null = null;

  private isSupportPTZInternal = false;

  /**
   * Device id to constraints to reset default PTZ setting.
   */
  private readonly deviceDefaultPTZ =
      new Map<string, MediaTrackConstraintSet>();

  private constraints: StreamConstraints|null = null;

  private onPreviewExpired: WaitableEvent|null = null;

  /**
   * @param onNewStreamNeeded Callback to request new stream.
   */
  constructor(private readonly onNewStreamNeeded: () => Promise<void>) {
    expert.addObserver(
        expert.ExpertOption.SHOW_METADATA, () => this.updateShowMetadata());
  }

  getVideo(): PreviewVideo {
    return new PreviewVideo(
        this.video,
        assertInstanceof(this.onPreviewExpired, WaitableEvent).wait(),
    );
  }

  /**
   * Current active stream.
   */
  get stream(): MediaStream {
    return assertInstanceof(this.streamInternal, MediaStream);
  }

  getVideoElement(): HTMLVideoElement {
    return this.video;
  }

  private getVideoTrack(): MediaStreamTrack {
    return this.stream.getVideoTracks()[0];
  }

  getFacing(): Facing {
    return util.assertEnumVariant(Facing, this.facing);
  }

  getDeviceId(): string|null {
    return this.deviceId;
  }

  /**
   * USB camera vid:pid identifier of the opened stream.
   *
   * @return Identifier formatted as "vid:pid" or null for non-USB camera.
   */
  getVidPid(): string|null {
    return this.vidPid;
  }

  getConstraints(): StreamConstraints {
    assert(this.constraints !== null);
    return this.constraints;
  }

  private async updateFacing() {
    const {facingMode} = this.getVideoTrack().getSettings();
    switch (facingMode) {
      case 'user':
        this.facing = Facing.USER;
        return;
      case 'environment':
        this.facing = Facing.ENVIRONMENT;
        return;
      default:
        this.facing = Facing.EXTERNAL;
        return;
    }
  }

  private async updatePTZ() {
    const deviceOperator = DeviceOperator.getInstance();
    const {pan, tilt, zoom} = this.getVideoTrack().getCapabilities();

    this.isSupportPTZInternal = await (async () => {
      if (pan === undefined && tilt === undefined && zoom === undefined) {
        return false;
      }
      if (deviceOperator === null) {
        // Enable PTZ on fake camera for testing.
        return true;
      }
      if (this.facing === Facing.EXTERNAL) {
        return true;
      } else if (expert.isEnabled(expert.ExpertOption.ENABLE_PTZ_FOR_BUILTIN)) {
        return true;
      }

      return false;
    })();

    if (!this.isSupportPTZInternal) {
      return;
    }

    const {deviceId} = getVideoTrackSettings(this.getVideoTrack());
    if (this.deviceDefaultPTZ.has(deviceId)) {
      return;
    }

    const defaultConstraints: MediaTrackConstraintSet = {};
    if (deviceOperator === null) {
      // VCD of fake camera will always reset to default when first opened. Use
      // current value at first open as default.
      if (pan !== undefined) {
        defaultConstraints.pan = pan;
      }
      if (tilt !== undefined) {
        defaultConstraints.tilt = tilt;
      }
      if (zoom !== undefined) {
        defaultConstraints.zoom = zoom;
      }
    } else {
      if (pan !== undefined) {
        defaultConstraints.pan = await deviceOperator.getPanDefault(deviceId);
      }
      if (tilt !== undefined) {
        defaultConstraints.tilt = await deviceOperator.getTiltDefault(deviceId);
      }
      if (zoom !== undefined) {
        defaultConstraints.zoom = await deviceOperator.getZoomDefault(deviceId);
      }
    }
    this.deviceDefaultPTZ.set(deviceId, defaultConstraints);
  }

  /**
   * If the preview camera support PTZ controls.
   */
  isSupportPTZ(): boolean {
    return this.isSupportPTZInternal;
  }

  async resetPTZ(): Promise<void> {
    if (this.streamInternal === null || !this.isSupportPTZInternal) {
      return;
    }
    const {deviceId} = getVideoTrackSettings(this.getVideoTrack());
    const defaultPTZ = this.deviceDefaultPTZ.get(deviceId);
    assert(defaultPTZ !== undefined);
    await this.getVideoTrack().applyConstraints({advanced: [defaultPTZ]});
  }

  /**
   * Preview resolution.
   */
  getResolution(): Resolution {
    const {videoWidth, videoHeight} = this.video;
    return new Resolution(videoWidth, videoHeight);
  }

  toString(): string {
    const {videoWidth, videoHeight} = this.video;
    return videoHeight ? `${videoWidth} x ${videoHeight}` : '';
  }

  /**
   * Sets video element's source.
   *
   * @param stream Stream to be the source.
   * @return Promise for the operation.
   */
  private async setSource(stream: MediaStream): Promise<void> {
    const tpl = util.instantiateTemplate('#preview-video-template');
    const video = dom.getFrom(tpl, 'video', HTMLVideoElement);
    await new Promise<void>((resolve) => {
      function handler() {
        video.removeEventListener('canplay', handler);
        resolve();
      }
      video.addEventListener('canplay', handler);
      video.srcObject = stream;
    });
    await video.play();
    assert(this.video.parentElement !== null);
    this.video.parentElement.replaceChild(tpl, this.video);
    this.video.srcObject = null;
    this.video = video;
    video.addEventListener('resize', () => this.onIntrinsicSizeChanged());
    video.addEventListener(
        'click',
        (event) => this.onFocusClicked(assertInstanceof(event, MouseEvent)));
    // Disable right click on video which let user show video control.
    video.addEventListener('contextmenu', (event) => event.preventDefault());
    return this.onIntrinsicSizeChanged();
  }

  private isStreamAlive(): boolean {
    assert(this.streamInternal !== null);
    return this.streamInternal.getVideoTracks().length !== 0 &&
        this.streamInternal.getVideoTracks()[0].readyState !== 'ended';
  }

  private clearWatchdog() {
    if (this.watchdog !== null) {
      clearInterval(this.watchdog);
      this.watchdog = null;
    }
  }

  /**
   * Opens preview stream.
   *
   * @param constraints Constraints of preview stream.
   * @return Promise resolved to opened preview stream.
   */
  async open(constraints: StreamConstraints): Promise<MediaStream> {
    this.constraints = constraints;
    this.streamInternal = await navigator.mediaDevices.getUserMedia(
        toMediaStreamConstraints(constraints));
    try {
      await this.setSource(this.streamInternal);
      // Use a watchdog since the stream.onended event is unreliable in the
      // recent version of Chrome. As of 55, the event is still broken.
      this.watchdog = setInterval(() => {
        if (!this.isStreamAlive()) {
          this.clearWatchdog();
          this.onNewStreamNeeded();
        }
      }, 100);
      await this.updateFacing();
      this.deviceId = getVideoTrackSettings(this.getVideoTrack()).deviceId;
      this.updateShowMetadata();
      await this.updatePTZ();

      const deviceOperator = DeviceOperator.getInstance();
      if (deviceOperator !== null) {
        const {deviceId} = getVideoTrackSettings(this.getVideoTrack());
        const isSuccess =
            await deviceOperator.setCameraFrameRotationEnabledAtSource(
                deviceId, false);
        if (!isSuccess) {
          reportError(
              ErrorType.FRAME_ROTATION_NOT_DISABLED, ErrorLevel.WARNING,
              new Error(
                  'Cannot disable camera frame rotation. ' +
                  'The camera is probably being used by another app.'));
        }
        this.vidPid = await deviceOperator.getVidPid(deviceId);
      }

      assert(this.onPreviewExpired === null);
      this.onPreviewExpired = new WaitableEvent();
      state.set(state.State.STREAMING, true);
    } catch (e) {
      await this.close();
      throw e;
    }
    return this.streamInternal;
  }

  /**
   * Closes the preview.
   */
  async close(): Promise<void> {
    this.clearWatchdog();
    // Pause video element to avoid black frames during transition.
    this.video.pause();
    this.disableShowMetadata();
    if (this.streamInternal !== null && this.isStreamAlive()) {
      const track = this.getVideoTrack();
      const {deviceId} = getVideoTrackSettings(track);
      track.stop();
      const deviceOperator = DeviceOperator.getInstance();
      if (deviceOperator !== null) {
        deviceOperator.dropConnection(deviceId);
      }
      assert(this.onPreviewExpired !== null);
    }
    this.streamInternal = null;

    if (this.onPreviewExpired !== null) {
      this.onPreviewExpired.signal();
      this.onPreviewExpired = null;
    }
    state.set(state.State.STREAMING, false);
  }

  /**
   * Checks preview whether to show preview metadata or not.
   */
  private updateShowMetadata() {
    if (expert.isEnabled(expert.ExpertOption.SHOW_METADATA)) {
      this.enableShowMetadata();
    } else {
      this.disableShowMetadata();
    }
  }

  /**
   * Creates an image blob of the current frame.
   *
   * @return Promise for the result.
   */
  toImage(): Promise<Blob> {
    const {canvas, ctx} = util.newDrawingCanvas(
        {width: this.video.videoWidth, height: this.video.videoHeight});
    ctx.drawImage(this.video, 0, 0);
    return util.canvasToJpegBlob(canvas);
  }

  /**
   * Displays preview metadata on preview screen.
   *
   * @return Promise for the operation.
   */
  private async enableShowMetadata(): Promise<void> {
    if (!this.streamInternal) {
      return;
    }

    for (const element of dom.getAll('.metadata.value', HTMLElement)) {
      element.style.display = 'none';
    }

    function displayCategory(selector: string, enabled: boolean) {
      dom.get(selector, HTMLElement).classList.toggle('mode-on', enabled);
    }

    function showValue(selector: string, val: string) {
      const element = dom.get(selector, HTMLElement);
      element.style.display = '';
      element.textContent = val;
    }

    function buildInverseLookupFunction(
        obj: Record<string, number>, prefix: string): (key: number) => string {
      const map = new Map<number, string>();
      for (const [key, val] of Object.entries(obj)) {
        if (!key.startsWith(prefix)) {
          continue;
        }
        if (map.has(val)) {
          reportError(
              ErrorType.METADATA_MAPPING_FAILURE, ErrorLevel.ERROR,
              new Error(`Duplicated value: ${val}`));
          continue;
        }
        map.set(val, key.slice(prefix.length));
      }
      return (key: number) => {
        const val = map.get(key);
        assert(val !== undefined);
        return val;
      };
    }

    const afStateNameLookup = buildInverseLookupFunction(
        AndroidControlAfState, 'ANDROID_CONTROL_AF_STATE_');
    const aeStateNameLookup = buildInverseLookupFunction(
        AndroidControlAeState, 'ANDROID_CONTROL_AE_STATE_');
    const awbStateNameLookup = buildInverseLookupFunction(
        AndroidControlAwbState, 'ANDROID_CONTROL_AWB_STATE_');
    const aeAntibandingModeNameLookup = buildInverseLookupFunction(
        AndroidControlAeAntibandingMode,
        'ANDROID_CONTROL_AE_ANTIBANDING_MODE_');

    let sensorSensitivity: number|null = null;
    let sensorSensitivityBoost = 100;
    function getSensitivity() {
      if (sensorSensitivity === null) {
        return 'N/A';
      }
      return sensorSensitivity * sensorSensitivityBoost / 100;
    }

    const tag = CameraMetadataTag;
    const metadataEntryHandlers: Record<string, (values: number[]) => void> = {
      [tag.ANDROID_LENS_FOCUS_DISTANCE]: ([value]) => {
        if (value === 0) {
          // Fixed-focus camera
          return;
        }
        const focusDistance = (100 / value).toFixed(1);
        showValue('#preview-focus-distance', `${focusDistance} cm`);
      },
      [tag.ANDROID_CONTROL_AF_STATE]: ([value]) => {
        showValue('#preview-af-state', afStateNameLookup(value));
      },
      [tag.ANDROID_SENSOR_SENSITIVITY]: ([value]) => {
        sensorSensitivity = value;
        const sensitivity = getSensitivity();
        showValue('#preview-sensitivity', `ISO ${sensitivity}`);
      },
      [tag.ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST]: ([value]) => {
        sensorSensitivityBoost = value;
        const sensitivity = getSensitivity();
        showValue('#preview-sensitivity', `ISO ${sensitivity}`);
      },
      [tag.ANDROID_SENSOR_EXPOSURE_TIME]: ([value]) => {
        const shutterSpeed = Math.round(1e9 / value);
        showValue('#preview-exposure-time', `1/${shutterSpeed}`);
      },
      [tag.ANDROID_SENSOR_FRAME_DURATION]: ([value]) => {
        const frameFrequency = Math.round(1e9 / value);
        showValue('#preview-frame-duration', `${frameFrequency} Hz`);
      },
      [tag.ANDROID_CONTROL_AE_ANTIBANDING_MODE]: ([value]) => {
        showValue(
            '#preview-ae-antibanding-mode', aeAntibandingModeNameLookup(value));
      },
      [tag.ANDROID_CONTROL_AE_STATE]: ([value]) => {
        showValue('#preview-ae-state', aeStateNameLookup(value));
      },
      [tag.ANDROID_COLOR_CORRECTION_GAINS]: ([valueRed, , , valueBlue]) => {
        const wbGainRed = valueRed.toFixed(2);
        showValue('#preview-wb-gain-red', `${wbGainRed}x`);
        const wbGainBlue = valueBlue.toFixed(2);
        showValue('#preview-wb-gain-blue', `${wbGainBlue}x`);
      },
      [tag.ANDROID_CONTROL_AWB_STATE]: ([value]) => {
        showValue('#preview-awb-state', awbStateNameLookup(value));
      },
      [tag.ANDROID_CONTROL_AF_MODE]: ([value]) => {
        displayCategory(
            '#preview-af',
            value !== AndroidControlAfMode.ANDROID_CONTROL_AF_MODE_OFF);
      },
      [tag.ANDROID_CONTROL_AE_MODE]: ([value]) => {
        displayCategory(
            '#preview-ae',
            value !== AndroidControlAeMode.ANDROID_CONTROL_AE_MODE_OFF);
      },
      [tag.ANDROID_CONTROL_AWB_MODE]: ([value]) => {
        displayCategory(
            '#preview-awb',
            value !== AndroidControlAwbMode.ANDROID_CONTROL_AWB_MODE_OFF);
      },
    };

    // These should be per session static information and we don't need to
    // recalculate them in every callback.
    const {videoWidth, videoHeight} = this.video;
    const resolution = `${videoWidth}x${videoHeight}`;
    const videoTrack = this.getVideoTrack();
    const deviceName = videoTrack.label;

    // Currently there is no easy way to calculate the fps of a video element.
    // Here we use the metadata events to calculate a reasonable approximation.
    const updateFps = (() => {
      const FPS_MEASURE_FRAMES = 100;
      const timestamps: number[] = [];
      return () => {
        const now = performance.now();
        timestamps.push(now);
        if (timestamps.length > FPS_MEASURE_FRAMES) {
          timestamps.shift();
        }
        if (timestamps.length === 1) {
          return null;
        }
        return (timestamps.length - 1) / (now - timestamps[0]) * 1000;
      };
    })();

    const deviceOperator = DeviceOperator.getInstance();
    if (!deviceOperator) {
      return;
    }

    const {deviceId} = getVideoTrackSettings(videoTrack);
    const activeArraySize = await deviceOperator.getActiveArraySize(deviceId);
    const cameraFrameRotation =
        await deviceOperator.getCameraFrameRotation(deviceId);
    this.faceOverlay =
        new FaceOverlay(activeArraySize, (360 - cameraFrameRotation) % 360);

    const updateFace =
        (mode: AndroidStatisticsFaceDetectMode, rects: number[]) => {
          assert(this.faceOverlay !== null);
          if (mode ===
              AndroidStatisticsFaceDetectMode
                  .ANDROID_STATISTICS_FACE_DETECT_MODE_OFF) {
            dom.get('#preview-num-faces', HTMLDivElement).style.display =
                'none';
            this.faceOverlay.clear();
            return;
          }
          assert(rects.length % 4 === 0);
          const numFaces = rects.length / 4;
          const label = numFaces >= 2 ? 'Faces' : 'Face';
          showValue('#preview-num-faces', `${numFaces} ${label}`);
          this.faceOverlay.show(rects);
        };

    const callback = (metadata: CameraMetadata) => {
      showValue('#preview-resolution', resolution);
      showValue('#preview-device-name', deviceName);
      const fps = updateFps();
      if (fps !== null) {
        showValue('#preview-fps', `${fps.toFixed(0)} FPS`);
      }

      let faceMode = AndroidStatisticsFaceDetectMode
                         .ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
      let faceRects: number[] = [];

      function tryParseFaceEntry(entry: CameraMetadataEntry) {
        switch (entry.tag) {
          case tag.ANDROID_STATISTICS_FACE_DETECT_MODE: {
            const data = parseMetadata(entry);
            assert(data.length === 1);
            faceMode = data[0];
            return true;
          }
          case tag.ANDROID_STATISTICS_FACE_RECTANGLES: {
            faceRects = parseMetadata(entry);
            return true;
          }
          default:
            return false;
        }
      }

      assert(metadata.entries !== undefined);
      for (const entry of metadata.entries) {
        if (entry.count === 0) {
          continue;
        }
        if (tryParseFaceEntry(entry)) {
          continue;
        }
        const handler = metadataEntryHandlers[entry.tag];
        if (handler === undefined) {
          continue;
        }
        handler(parseMetadata(entry));
      }

      // We always need to run updateFace() even if face rectangles are obsent
      // in the metadata, which may happen if there is no face detected.
      updateFace(faceMode, faceRects);
    };

    this.metadataObserver = await deviceOperator.addMetadataObserver(
        deviceId, callback, StreamType.PREVIEW_OUTPUT);
  }

  /**
   * Hide display preview metadata on preview screen.
   *
   * @return Promise for the operation.
   */
  private async disableShowMetadata(): Promise<void> {
    if (!this.streamInternal || this.metadataObserver === null) {
      return;
    }

    closeEndpoint(this.metadataObserver);
    this.metadataObserver = null;

    if (this.faceOverlay !== null) {
      this.faceOverlay.clear();
      this.faceOverlay = null;
    }
  }

  /**
   * Handles changed intrinsic size (first loaded or orientation changes).
   */
  private async onIntrinsicSizeChanged(): Promise<void> {
    if (this.video.videoWidth !== 0 && this.video.videoHeight !== 0) {
      nav.layoutShownViews();
    }
    this.cancelFocus();
  }

  /**
   * Apply point of interest to the stream.
   *
   * @param point The point in normalize coordidate system, which means both
   *     |x| and |y| are in range [0, 1).
   */
  setPointOfInterest(point: Point): Promise<void> {
    const constraints = {
      advanced: [{pointsOfInterest: [{x: point.x, y: point.y}]}],
    };
    const track = this.getVideoTrack();
    return track.applyConstraints(constraints);
  }

  /**
   * Handles clicking for focus.
   *
   * @param event Click event.
   */
  private onFocusClicked(event: MouseEvent) {
    this.cancelFocus();
    const marker = Symbol();
    this.focusMarker = marker;
    (async () => {
      try {
        // Normalize to square space coordinates by W3C spec.
        const x = event.offsetX / this.video.offsetWidth;
        const y = event.offsetY / this.video.offsetHeight;
        await this.setPointOfInterest(new Point(x, y));
      } catch {
        // The device might not support setting pointsOfInterest. Ignore the
        // error and return.
        return;
      }
      if (marker !== this.focusMarker) {
        return;  // Focus was cancelled.
      }
      const aim = dom.get('#preview-focus-aim', HTMLObjectElement);
      const clone = assertInstanceof(aim.cloneNode(true), HTMLObjectElement);
      clone.style.left = `${event.offsetX + this.video.offsetLeft}px`;
      clone.style.top = `${event.offsetY + this.video.offsetTop}px`;
      clone.hidden = false;
      assert(aim.parentElement !== null);
      aim.parentElement.replaceChild(clone, aim);
    })();
  }

  /**
   * Cancels the current applying focus.
   */
  private cancelFocus() {
    this.focusMarker = null;
    const aim = dom.get('#preview-focus-aim', HTMLObjectElement);
    aim.hidden = true;
  }
}


text:
@interface UIImage (TXAsset)

+ (void)imageFromPHAssets:(NSArray <PHAsset *> *)assets size:(CGSize )size resultHandler:(void (^ )(NSArray * images))resultHandler;

+ (void)imageDataFromPHAssets:(NSArray <PHAsset *> *)assets resultHandler:(void (^ )(NSArray * imageDatas))resultHandler;

+ (UIImage *)imageFromPHAsset:(PHAsset *)asset size:(CGSize )size;

+ (NSData *)imageDataFromPHAsset:(PHAsset *)asset;

@end


text:
Test: dojox.form.CheckedMultiSelect

		<form dojoType="dijit.form.Form" jsId="form">

Check Boxes

			<select jsId="ms1" multiple="true" name="ms1" dojoType="dojox.form.CheckedMultiSelect">
				<option value="TN">Tennessee</option>
				<option value="VA" selected="selected">Virginia</option>
				<option value="WA" selected="selected">Washington</option>
				<option value="FL">Florida</option>
				<option value="CA">California</option>
			</select>
			<select jsId="ms2" multiple="true" name="ms2" dojoType="dojox.form.CheckedMultiSelect">
				<option value="UT">Utah</option>
				<option value="TX" selected="selected">Texas</option>
				<option value="GA" selected="selected">Georgia</option>
				<option value="ID">Idaho</option>
				<option value="WY">Wyoming</option>
				<option value="OR">Oregon</option>
				<option value="PA">Pennsylvania</option>
			</select>
			<select jsId="ms3" multiple="true" name="ms3" dojoType="dojox.form.CheckedMultiSelect">
			</select>

Radio Buttons

			<select jsId="ss1" name="ss1" dojoType="dojox.form.CheckedMultiSelect">
				<option value="TN">Tennessee</option>
				<option value="VA" selected="selected">Virginia</option>
				<option value="WA">Washington</option>
				<option value="FL">Florida</option>
				<option value="CA">California</option>
			</select>
			<select jsId="ss2" name="ss2" value="TX" dojoType="dojox.form.CheckedMultiSelect">
				<option value="UT">Utah</option>
				<option value="TX">Texas</option>
				<option value="GA">Georgia</option>
				<option value="ID">Idaho</option>
				<option value="WY">Wyoming</option>
				<option value="OR">Oregon</option>
				<option value="PA">Pennsylvania</option>
			</select>
			<select jsId="ss3" name="ss3" dojoType="dojox.form.CheckedMultiSelect">
			</select>

			<button dojoType="dijit.form.Button">

				Get Values
			</button>
			<button dojoType="dijit.form.Button">

				Add Check Option
			</button>
			<button dojoType="dijit.form.Button">

				Add Radio Option
			</button>
			<button dojoType="dijit.form.Button">

				Toggle Disabled
			</button>
			<button dojoType="dijit.form.Button">

				Invert Selection
			</button>
		</form>


text:
package gov.sandia.cognition.learning.performance.categorization;

import gov.sandia.cognition.learning.data.DatasetUtil;
import gov.sandia.cognition.learning.data.TargetEstimatePair;
import gov.sandia.cognition.learning.performance.AbstractSupervisedPerformanceEvaluator;
import gov.sandia.cognition.util.AbstractCloneableSerializable;
import gov.sandia.cognition.util.ArgumentChecker;
import gov.sandia.cognition.util.Pair;
import gov.sandia.cognition.util.Summarizer;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;

/**
 * A default implementation of the {@code BinaryConfusionMatrix}. It stores the
 * four entries in the confusion matrix: true positives, false positives,
 * true negatives, and false negatives.
 *
 * @author  Justin Basilico
 * @author  Kevin R. Dixon
 * @since   3.1
 */
public class DefaultBinaryConfusionMatrix
    extends AbstractBinaryConfusionMatrix
{

    /** Number of true negatives. The (false, false) entry. */
    protected double trueNegativesCount;

    /** Number of false positives. The (false, true) entry. */
    protected double falsePositivesCount;

    /** Number of false negatives. The (true, false) entry. */
    protected double falseNegativesCount;

    /** Number of true positives. The (true, true) entry. */
    protected double truePositivesCount;

    /**
     * Creates a new, empty {@code DefaultBinaryConfusionMatrix}.
     */
    public DefaultBinaryConfusionMatrix()
    {
        super();

        this.setTruePositivesCount(0.0);
        this.setFalsePositivesCount(0.0);
        this.setTrueNegativesCount(0.0);
        this.setFalseNegativesCount(0.0);
    }

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

    @Override
    public void add(
        final Boolean target,
        final Boolean estimate,
        final double value)
    {
        if (target)
        {
            if (estimate)
            {
                this.truePositivesCount += value;
            }
            else
            {
                this.falseNegativesCount += value;
            }
        }
        else
        {
            if (estimate)
            {
                this.falsePositivesCount += value;
            }
            else
            {
                this.trueNegativesCount += value;
            }
        }
    }

    @Override
    public void clear()
    {
        this.setTruePositivesCount(0.0);
        this.setFalseNegativesCount(0.0);
        this.setTrueNegativesCount(0.0);
        this.setFalsePositivesCount(0.0);
    }

    @Override
    public double getTruePositivesCount()
    {
        return this.truePositivesCount;
    }

    /**
     * Sets the number of true positives in the matrix.
     *
     * @param   truePositivesCount
     *      The number of true positives. Cannot be negative.
     */
    public void setTruePositivesCount(
        final double truePositivesCount)
    {
        ArgumentChecker.assertIsNonNegative(
            "truePositivesCount", truePositivesCount);
        this.truePositivesCount = truePositivesCount;
    }

    @Override
    public double getFalsePositivesCount()
    {
        return this.falsePositivesCount;
    }

    /**
     * Sets the number of false positives in the matrix.
     *
     * @param   falsePositivesCount
     *      The number of false positives. Cannot be negative.
     */
    public void setFalsePositivesCount(
        final double falsePositivesCount)
    {
        ArgumentChecker.assertIsNonNegative(
            "falsePositivesCount", falsePositivesCount);
        this.falsePositivesCount = falsePositivesCount;
    }

    @Override
    public double getTrueNegativesCount()
    {
        return this.trueNegativesCount;
    }

    /**
     * Sets the number of true negatives in the matrix.
     *
     * @param   trueNegativesCount
     *      The number of true negatives. Cannot be negative.
     */
    public void setTrueNegativesCount(
        final double trueNegativesCount)
    {
        ArgumentChecker.assertIsNonNegative(
            "trueNegativesCount", trueNegativesCount);
        this.trueNegativesCount = trueNegativesCount;
    }

    @Override
    public double getFalseNegativesCount()
    {
        return this.falseNegativesCount;
    }

    /**
     * Sets the number of false negatives in the matrix.
     *
     * @param   falseNegativesCount
     *      The number of false negatives. Cannot be negative.
     */
    public void setFalseNegativesCount(
        final double falseNegativesCount)
    {
        ArgumentChecker.assertIsNonNegative(
            "falseNegativesCount", falseNegativesCount);
        this.falseNegativesCount = falseNegativesCount;
    }

    /**
     * Gets the rate of negative targets correctly classified. Computed as:
     * TrueNegatives / TotalNegatives = TrueNegatives / (TrueNegatives + FalsePositives)
     *
     * @return
     *      True negative rate, which is in [0,1].
     */
    public double getTrueNegativesRate()
    {
        double denom = this.getTrueNegativesCount() + this.getFalsePositivesCount();
        double retval;
        if (denom <= 0.0)
        {
            retval = 1.0;
        }
        else
        {
            retval = this.getTrueNegativesCount() / denom;
        }

        return retval;

    }

    /**
     * Gets the rate of target trues that were correctly classified as true.
     * Computed as:
     * TruePositives / TotalPositives = TruePositives / (TruePositives + FalseNegatives)
     *
     * @return
     *      True positives rate, which is in [0,1].
     */
    public double getTruePositivesRate()
    {
        double denom = this.getTruePositivesCount() + this.getFalseNegativesCount();
        double retval;
        if (denom <= 0.0)
        {
            retval = 1.0;
        }
        else
        {
            retval = this.getTruePositivesCount() / denom;
        }

        return retval;

    }

    /**
     * Gets the rate of false targets incorrectly classified as true. Computed
     * as:
     * FalsePositives / TotalNegatives = FalsePositives / (TrueNegatives + FalsePositives)
     *
     * @return
     *      Rate of false positives, which is in [0,1]. Equal to
     *      1 - trueNegativeRate.
     */
    public double getFalsePositivesRate()
    {
        return 1.0 - this.getTrueNegativesRate();
    }

    /**
     * Gets the rate of true targets incorrectly classified as false. Computed
     * as:
     * FalseNegatives / TotalPositives = FalseNegatives / (TruePositives + FalseNegatives)
     *
     * @return
     *      Rate of false negatives, which is in [0,1]. Equal to
     *      1 - truePositiveRate
     */
    public double getFalseNegativesRate()
    {
        return 1.0 - this.getTruePositivesRate();
    }

    @Override
    public String toString()
    {
        return
            "True Negatives: " + this.getTrueNegativesCount()
            + ", " + "False Positives: " + this.getFalsePositivesCount()
            + ", " + "False Negatives: " + this.getFalseNegativesCount()
            + ", " + "True Positives: " + this.getTruePositivesCount();
    }

    /**
     * Takes a general confusion matrix and creates a binary form of it using
     * true category. All other categories are considered false.
     *
     * @param <CategoryType>
     *      The true category type.
     * @param   matrix
     *      The general confusion matrix to binarize.
     * @param   trueCategory
     *      The value of the true category for the binary confusion matrix.
     * @return
     *      A new binary confusion matrix.
     */
    public static <CategoryType> DefaultBinaryConfusionMatrix binarizeOnTrueCategory(
        final ConfusionMatrix<CategoryType> matrix,
        final CategoryType trueCategory)
    {
        return binarizeOnTrueSet(matrix, Collections.singleton(trueCategory));
    }

    /**
     * Takes a general confusion matrix and creates a binary form of it using
     * the given set of true categories. All other categories are considered
     * false.
     *
     * @param <CategoryType>
     *      The true category type.
     * @param   matrix
     *      The general confusion matrix to binarize.
     * @param   trueSet
     *      The set of categories in the true set for the binary confusion
     *      matrix.
     * @return
     *      A new binary confusion matrix.
     */
    public static <CategoryType> DefaultBinaryConfusionMatrix binarizeOnTrueSet(
        final ConfusionMatrix<CategoryType> matrix,
        final Set<? super CategoryType> trueSet)
    {
        final DefaultBinaryConfusionMatrix result =
            new DefaultBinaryConfusionMatrix();

        for (CategoryType actual : matrix.getActualCategories())
        {
            final boolean actualBinary = trueSet.contains(actual);

            for (CategoryType predicted : matrix.getPredictedCategories(actual))
            {
                final boolean predictedBinary = trueSet.contains(predicted);
                result.add(actualBinary, predictedBinary,
                    matrix.getCount(actual, predicted));
            }
        }
        return result;
    }

    /**
     * Creates a new {@code DefaultConfusionMatrix} from the given
     * actual-predicted pairs.
     *
     * @param   pairs
     *      The actual-category pairs.
     * @return
     *      A new confusion matrix populated from the given actual-category
     *      pairs.
     */
    public static DefaultBinaryConfusionMatrix createFromActualPredictedPairs(
        final Collection<? extends Pair<? extends Boolean, ? extends Boolean>> pairs)
    {
        final DefaultBinaryConfusionMatrix result =
            new DefaultBinaryConfusionMatrix();
        for (Pair<? extends Boolean, ? extends Boolean> pair
            : pairs)
        {
            result.add(pair.getFirst(), pair.getSecond());
        }
        return result;
    }

    /**
     * Creates a new {@code DefaultBinaryConfusionMatrix} from the given
     * target-estimate pairs.
     *
     * @param   input
     *      The target-estimate pairs.
     * @return
     *      A new confusion matrix populated from the given target-estimate
     *      pairs.
     */
    public static DefaultBinaryConfusionMatrix create(
        final Iterable<? extends TargetEstimatePair<? extends Boolean, ? extends Boolean>> input)
    {
        return DefaultBinaryConfusionMatrix.create(input, true);
    }

    /**
     * Creates a new {@code DefaultBinaryConfusionMatrix} from the given
     * target-estimate pairs.
     *
     * @param   input
     *      The target-estimate pairs.
     * @param   weightIfAvailable
     *      True uses the weight of each item (or 1.0 if there is none); false
     *      means 1.0 is used regardless of weight.
     * @return
     *      A new confusion matrix populated from the given target-estimate
     *      pairs.
     */
    public static DefaultBinaryConfusionMatrix create(
        final Iterable<? extends TargetEstimatePair<? extends Boolean, ? extends Boolean>> input,
        final boolean weightIfAvailable )
    {
        double falsePositives = 0;
        double falseNegatives = 0;
        double truePositives = 0;
        double trueNegatives = 0;
        for (TargetEstimatePair<? extends Boolean, ? extends Boolean> pair
            : input)
        {
            double increment;
            if (weightIfAvailable)
            {
                increment = DatasetUtil.getWeight(pair);
            }
            else
            {
                increment = 1.0;
            }

            boolean target = pair.getTarget();
            boolean estimate = pair.getEstimate();
            if (target == true)
            {
                if (estimate == true)
                {
                    truePositives += increment;
                }
                else
                {
                    falseNegatives += increment;
                }
            }
            else
            {
                if (estimate == true)
                {
                    falsePositives += increment;
                }
                else
                {
                    trueNegatives += increment;
                }
            }

        }

        final DefaultBinaryConfusionMatrix result =
            new DefaultBinaryConfusionMatrix();
        result.setFalsePositivesCount(falsePositives);
        result.setFalseNegativesCount(falseNegatives);
        result.setTruePositivesCount(truePositives);
        result.setTrueNegativesCount(trueNegatives);
        return result;
    }

    /**
     * An implementation of the {@code SupervisedPerformanceEvaluator} interface
     * for creating a {@code DefaultBinaryConfusionMatrix}.
     *
     * @param   <InputType>
     *      Input type for the evaluator to compute the confusion over.
     */
    public static class PerformanceEvaluator<InputType>
        extends AbstractSupervisedPerformanceEvaluator<InputType, Boolean, Boolean, DefaultBinaryConfusionMatrix>
    {

        /**
         * Creates a new {@code PerformanceEvaluator}.
         */
        public PerformanceEvaluator()
        {
            super();
        }

        public DefaultBinaryConfusionMatrix evaluatePerformance(
            final Collection<? extends TargetEstimatePair<? extends Boolean, ? extends Boolean>> data )
        {
            return DefaultBinaryConfusionMatrix.create(data);
        }

    }

    /**
     * A confusion matrix summarizer that summarizes actual-predicted pairs.
     */
    public static class ActualPredictedPairSummarizer
        extends AbstractCloneableSerializable
        implements Summarizer<Pair<? extends Boolean, ? extends Boolean>, DefaultBinaryConfusionMatrix>
    {

        /**
         * Creates a new {@code CombineSummarizer}.
         */
        public ActualPredictedPairSummarizer()
        {
            super();
        }

        @Override
        public DefaultBinaryConfusionMatrix summarize(
            final Collection<? extends Pair<? extends Boolean, ? extends Boolean>> data)
        {
            return createFromActualPredictedPairs(data);
        }

    }

    /**
     * A confusion matrix summarizer that adds together confusion matrices.
     */
    public static class CombineSummarizer
        extends AbstractCloneableSerializable
        implements Summarizer<ConfusionMatrix<Boolean>, DefaultBinaryConfusionMatrix>
    {

        /**
         * Creates a new {@code CombineSummarizer}.
         */
        public CombineSummarizer()
        {
            super();
        }

        @Override
        public DefaultBinaryConfusionMatrix summarize(
            final Collection<? extends ConfusionMatrix<Boolean>> data)
        {
            final DefaultBinaryConfusionMatrix result =
                new DefaultBinaryConfusionMatrix();

            for (ConfusionMatrix<Boolean> item : data)
            {
                result.addAll(item);
            }

            return result;
        }

    }

}


text:
const Core = require('./core');

class Unreal2 extends Core {
    constructor() {
        super();
        this.encoding = 'latin1';
    }
    async run(state) {
        let extraInfoReader;
        {
            const b = await this.sendPacket(0, true);
            const reader = this.reader(b);
            state.raw.serverid = reader.uint(4);
            state.raw.ip = this.readUnrealString(reader);
            state.gamePort = reader.uint(4);
            state.raw.queryport = reader.uint(4);
            state.name = this.readUnrealString(reader, true);
            state.map = this.readUnrealString(reader, true);
            state.raw.gametype = this.readUnrealString(reader, true);
            state.raw.numplayers = reader.uint(4);
            state.maxplayers = reader.uint(4);
            this.logger.debug(log => {
                log("UNREAL2 EXTRA INFO", reader.buffer.slice(reader.i));
            });
            extraInfoReader = reader;
        }

        {
            const b = await this.sendPacket(1,true);
            const reader = this.reader(b);
            state.raw.mutators = [];
            state.raw.rules = {};
            while(!reader.done()) {
                const key = this.readUnrealString(reader,true);
                const value = this.readUnrealString(reader,true);
                this.logger.debug(key+'='+value);
                if(key === 'Mutator' || key === 'mutator') {
                    state.raw.mutators.push(value);
                } else if (key || value) {
                    if (state.raw.rules.hasOwnProperty(key)) {
                        state.raw.rules[key] += ',' + value;
                    } else {
                        state.raw.rules[key] = value;
                    }
                }
            }
            if('GamePassword' in state.raw.rules)
                state.password = state.raw.rules.GamePassword !== 'True';
        }

        if (state.raw.mutators.includes('KillingFloorMut')
            || state.raw.rules['Num trader weapons']
            || state.raw.rules['Server Version'] === '1065'
        ) {
            // Killing Floor
            state.raw.wavecurrent = extraInfoReader.uint(4);
            state.raw.wavetotal = extraInfoReader.uint(4);
            state.raw.ping = extraInfoReader.uint(4);
            state.raw.flags = extraInfoReader.uint(4);
            state.raw.skillLevel = this.readUnrealString(extraInfoReader, true);
        } else {
            state.raw.ping = extraInfoReader.uint(4);
            // These fields were added in later revisions of unreal engine
            if (extraInfoReader.remaining() >= 8) {
                state.raw.flags = extraInfoReader.uint(4);
                state.raw.skill = this.readUnrealString(extraInfoReader, true);
            }
        }

        {
            const b = await this.sendPacket(2,false);
            const reader = this.reader(b);

            state.raw.scoreboard = {};
            while(!reader.done()) {
                const player = {};
                player.id = reader.uint(4);
                player.name = this.readUnrealString(reader,true);
                player.ping = reader.uint(4);
                player.score = reader.int(4);
                player.statsId = reader.uint(4);
                this.logger.debug(player);

                if (!player.id) {
                    state.raw.scoreboard[player.name] = player.score;
                } else if (!player.ping) {
                    state.bots.push(player);
                } else {
                    state.players.push(player);
                }
            }
        }
    }

    readUnrealString(reader, stripColor) {
        let length = reader.uint(1), ucs2 = false;
        if(length >= 0x80) {
            // This is flagged as a UCS-2 String
            length = (length&0x7f)*2;
            ucs2 = true;

            // For UCS-2 strings, some unreal 2 games randomly insert an extra 0x01 here,
            // not included in the length. Skip it if present (hopefully this never happens legitimately)
            const peek = reader.uint(1);
            if (peek !== 1) reader.skip(-1);

            this.debugLog(log => {
                log("UCS2 STRING");
                log("UCS2 Length: " + length);
                log(reader.buffer.slice(reader.i,reader.i+length));
            });
        }

        let out = '';
        if (ucs2) {
            out = reader.string({encoding:'ucs2',length:length});
            this.debugLog("UCS2 String decoded: " + out);
        } else if (length > 0) {
            out = reader.string();
        }

        // Sometimes the string has a null at the end (included with the length)
        // Strip it if present
        if(out.charCodeAt(out.length-1) === 0) {
            out = out.substring(0, out.length - 1);
        }

        if(stripColor) {
            out = out.replace(/\x1b...|[\x00-\x1a]/gus,'');
        }

        return out;
    }

    async sendPacket(type,required) {
        const outbuffer = Buffer.from([0x79,0,0,0,type]);

        const packets = [];
        return await this.udpSend(outbuffer,(buffer) => {
            const reader = this.reader(buffer);
            const header = reader.uint(4);
            const iType = reader.uint(1);
            if(iType !== type) return;
            packets.push(reader.rest());
        }, () => {
            if(!packets.length && required) return;
            return Buffer.concat(packets);
        });
    }
}

module.exports = Unreal2;


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var TopicSchema = new Schema({
  title: { type: String },
  content: { type: String },
  face: { type: String }, //新增:文章缩略图,2012.11.01
  author_id: { type: ObjectId },
  top: { type: Boolean, default: false },
  reply_count: { type: Number, default: 0 },
  visit_count: { type: Number, default: 0 },
  collect_count: { type: Number, default: 0 },
  create_at: { type: Date, default: Date.now },
  update_at: { type: Date, default: Date.now },
  last_reply: { type: ObjectId },
  last_reply_at: { type: Date, default: Date.now },
  content_is_html: { type: Boolean }
});

mongoose.model('Topic', TopicSchema);


text:
package org.apache.tinkerpop.gremlin.spark.structure.io.gryo;

import org.apache.tinkerpop.gremlin.hadoop.structure.io.ObjectWritable;
import org.apache.tinkerpop.shaded.kryo.Kryo;
import org.apache.tinkerpop.shaded.kryo.Serializer;
import org.apache.tinkerpop.shaded.kryo.io.Input;
import org.apache.tinkerpop.shaded.kryo.io.Output;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public final class ObjectWritableSerializer<T> extends Serializer<ObjectWritable<T>> {

    @Override
    public void write(final Kryo kryo, final Output output, final ObjectWritable<T> objectWritable) {
        kryo.writeClassAndObject(output, objectWritable.get());
        output.flush();
    }

    @Override
    public ObjectWritable<T> read(final Kryo kryo, final Input input, final Class<ObjectWritable<T>> clazz) {
        return new ObjectWritable(kryo.readClassAndObject(input));
    }
}


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.
 */
package com.facebook.presto.sql.tree;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.List;

public class SimpleCaseExpression
        extends Expression
{
    private final Expression operand;
    private final List<WhenClause> whenClauses;
    private final Expression defaultValue;

    public SimpleCaseExpression(Expression operand, List<WhenClause> whenClauses, Expression defaultValue)
    {
        Preconditions.checkNotNull(operand, "operand is null");
        Preconditions.checkNotNull(whenClauses, "whenClauses is null");

        this.operand = operand;
        this.whenClauses = ImmutableList.copyOf(whenClauses);
        this.defaultValue = defaultValue;
    }

    public Expression getOperand()
    {
        return operand;
    }

    public List<WhenClause> getWhenClauses()
    {
        return whenClauses;
    }

    public Expression getDefaultValue()
    {
        return defaultValue;
    }

    @Override
    public <R, C> R accept(AstVisitor<R, C> visitor, C context)
    {
        return visitor.visitSimpleCaseExpression(this, context);
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        SimpleCaseExpression that = (SimpleCaseExpression) o;

        if (defaultValue != null ? !defaultValue.equals(that.defaultValue) : that.defaultValue != null) {
            return false;
        }
        if (!operand.equals(that.operand)) {
            return false;
        }
        if (!whenClauses.equals(that.whenClauses)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode()
    {
        int result = operand.hashCode();
        result = 31 * result + whenClauses.hashCode();
        result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0);
        return result;
    }
}


text:
package main

import "fmt"

type ItemRouteConflict struct {
	name, description, kind string
}

func (irc *ItemRouteConflict) Name() string {
	return irc.name
}

func (irc *ItemRouteConflict) Description() string {
	return irc.description
}

func (irc *ItemRouteConflict) Kind() string {
	return irc.kind
}

func (irc *ItemRouteConflict) Lint(config *Config, params LinterParams) (ResultMap, error) {
	resultRouteConflict := make(ResultMap)

	//populate map with key spec.host and value metadata.name
	//only one route (metadata.name) should resolve to a given FQDN stored in spec.host
	routeMap := make(map[string]string)

	var key, value string
	for _, item := range config.Items {
		if item.Kind != irc.Kind() {
			continue
		}

		if item.Metadata != nil && item.Spec != nil {
			//skip if host or targetPort field not present
			if item.Spec.Host == "" {
				continue
			}

			namespace := item.Metadata.Namespace

			key = item.Spec.Host + item.Spec.Path
			value = item.Metadata.Name

			if len(routeMap[key]) > 0 && routeMap[key] != value {
				problem := fmt.Sprintf("Route to '%s' defined twice: '%s' and '%s'", key, routeMap[key], value)
				if len(namespace) > 0 {
					problem += fmt.Sprintf(" (namespace '%s')", namespace)
				}
				resultRouteConflict[problem] = append(resultRouteConflict[problem], ContainerSpec{"", "", ""})
			} else {
				routeMap[key] = value
			}
		}
	}
	return resultRouteConflict, nil
}


text:
void RegisterExporters() {
  // For debugging, register exporters that just write to stdout.
  opencensus::exporters::stats::StdoutExporter::Register();
  opencensus::exporters::trace::StdoutExporter::Register();

  const char* project_id = getenv("STACKDRIVER_PROJECT_ID");
  if (project_id == nullptr) {
    std::cerr << "The STACKDRIVER_PROJECT_ID environment variable is not set: "
                 "not exporting to Stackdriver.\n";
  } else {
    std::cout << "RegisterStackdriverExporters:\n";
    std::cout << "  project_id = \"" << project_id << "\"\n";

    opencensus::exporters::stats::StackdriverOptions stats_opts;
    stats_opts.project_id = project_id;
    opencensus::exporters::stats::StackdriverExporter::Register(
        std::move(stats_opts));

    opencensus::exporters::trace::StackdriverOptions trace_opts;
    trace_opts.project_id = project_id;
    opencensus::exporters::trace::StackdriverExporter::Register(
        std::move(trace_opts));
  }

  const char* ocagent_address = getenv("OCAGENT_ADDRESS");
  if (ocagent_address == nullptr) {
    std::cerr << "The OCAGENT_ADDRESS environment variable is not set: not "
                 "exporting to OpenCensus Agent. (e.g. localhost:55678)\n";
  } else {
    opencensus::exporters::trace::OcAgentOptions opts;
    opts.address = ocagent_address;
    opencensus::exporters::trace::OcAgentExporter::Register(std::move(opts));
  }
}


text:
OctTree* oct_init(Hashmap* h)
{
	OctTree* tmp = malloc(sizeof(OctTree*));

	memcpy(tmp->data, h, sizeof(h));

	tmp->children = calloc(sizeof(OctTree*), 8);

	return tmp;
}

int oct_add(const Object* obj)
{
	return 1;
}

Object* oct_delete(Object* obj)
{
	return obj;
}

int oct_search(const Object* obj)
{
	return 1;
}


text:
package com.iovation.launchkey.sdk.integration.mobile.driver;

public class NullMobileDriver implements SampleAppMobileDriver {
    @Override
    public void unlinkDevice() {

    }

    @Override
    public void linkDevice(String sdkKey, String linkingCode) {

    }

    @Override
    public void linkDevice(String sdkKey, String linkingCode, String deviceName) {

    }

    @Override
    public void approveRequest() {

    }

    @Override
    public void denyRequest() {

    }

    @Override
    public void receiveAndAcknowledgeAuthFailure() {

    }

    @Override
    public void waitUntilLinkingIsFinished() {

    }
}


text:
package org.zalando.intellij.swagger.reference;

import com.intellij.json.psi.JsonLiteral;
import com.intellij.json.psi.JsonProperty;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.zalando.intellij.swagger.completion.traversal.JsonTraversal;

import java.util.List;
import java.util.stream.Collectors;

public class JsonParameterReference extends PsiReferenceBase<PsiElement> {

    private final String targetParameterKey;
    private final JsonTraversal jsonTraversal;

    public JsonParameterReference(@NotNull final JsonLiteral selectedElement,
                                  @NotNull final String targetParameterKey,
                                  @NotNull final JsonTraversal jsonTraversal) {
        super(selectedElement);
        this.targetParameterKey = targetParameterKey;
        this.jsonTraversal = jsonTraversal;
    }

    @Nullable
    @Override
    public PsiElement resolve() {
        return getParametersChildren().stream()
                .filter(jsonProperty -> targetParameterKey.equals(jsonProperty.getName()))
                .findFirst()
                .orElse(null);
    }

    private List<JsonProperty> getParametersChildren() {
        return jsonTraversal.getChildrenOf("parameters", getElement().getContainingFile()).stream()
                .filter(psiElement -> psiElement instanceof JsonProperty)
                .map(JsonProperty.class::cast)
                .collect(Collectors.toList());
    }

    @NotNull
    @Override
    public Object[] getVariants() {
        return new Object[0];
    }

    @Override
    public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
        return super.handleElementRename("#/parameters/" + newElementName);
    }
}


text:
#include "tensor/itensor.hpp"
#include "tensor/tensorshape.hpp"
#include "memory/default_alloc.hpp"
#include "proto/tenncor.pb.h"

#pragma once
#ifndef TENNCOR_TENSOR_HPP
#define TENNCOR_TENSOR_HPP

#include <stdexcept>
#include <string>
#include <type_traits>
#include <cstring>

namespace nnet
{

//! extremely common function fitting source data represented by inshape to
//! destination data represented by outshape
//! data not covered in source are padded with zero
template <typename T>
void fit_toshape (T* dest, const tensorshape& outshape, const T* src, const tensorshape& inshape);

template <typename T>
class itensor_handler;

template <typename T>
class tensor : public itensor<T>
{
public:
	//! create a rank 0 tensor and specific allocator
	tensor (void);

	//! Create a scalar tensor and specific allocator
	tensor (T scalar, size_t alloc_id = default_alloc::alloc_id);

	//! create a tensor of a specified shape and allocator
	//! if the shape is fully defined, then raw data is allocated
	//! otherwise, tensor will wait for a defined shape
	tensor (tensorshape shape, size_t alloc_id = default_alloc::alloc_id);

	//! deallocate tensor
	virtual ~tensor (void);

	// >>>> COPY && MOVE <<<<
	//! default copy constructor
	tensor (const tensor<T>& other) : tensor<T>(other, false) {}

	//! copy constructor
	tensor (const tensor<T>& other, bool shapeonly);

	//! move constructor
	tensor (tensor<T>&& other);

	// >>>> POLYMORPHIC CLONE && MOVES <<<<
	//! clone function
	tensor<T>* clone (bool shapeonly = false) const;

	//! move function
	tensor<T>* move (void);

	//! copy assignment
	virtual tensor<T>& operator = (const tensor<T>& other);

	//! move assignment
	virtual tensor<T>& operator = (tensor<T>&& other);

	// >>>> ACCESSORS <<<<
	// >>> SHAPE INFORMATION <<<
	//! get tensor shape (allocated if so, allowed shape otherwise)
	tensorshape get_shape (void) const;

	// >> SHAPE UTILITY <<
	//! get the amount of T elements allocated
	//! if uninitialized, return 0
	virtual size_t n_elems (void) const;

	//! get the tensor rank, number of dimensions
	virtual size_t rank (void) const;

	//! get vector dimension values
	std::vector<size_t> dims (void) const;

	// >> SHAPE COMPATIBILITY <<
	//! checks if input tensor has a compatible allowed tensorshape
	//! or if both this and other are allocated and the trimmed shapes are compatible
	bool is_same_size (const tensor<T>& other) const;

	//! check if other tensor's data is compatible with this shape
	bool is_compatible_with (const tensor<T>& other) const;

	//! check if input is compatible with tensor shape
	//! data is compatible if data.size() == (innate or external) shape size
	bool is_compatible_with (std::vector<T> data) const;

	//! data is loosely compatible if data.size() < (innate or external) shape size
	bool is_loosely_compatible_with (std::vector<T> data) const;

	//! return compatible shape with n_elems == data.size()
	//! or undefined if compatibility is impossible
	// implementation detail:
	// this algorithm attempts to cover up the first unknown with data.size() / n_known
	// iff data.size() % n_known == 0
	// todo: attempt to add lambda function as parameter to distribute data.size() / n_known among unknowns (same for loosely guess)
	optional<tensorshape> guess_shape (const std::vector<T>& data) const;

	//! return loosely compatible shape with n_elems <= data.size()
	//! or undefined if compatibility is impossible
	optional<tensorshape> loosely_guess_shape (const std::vector<T>& data) const;

	//! checks if tensorshape is aligned
	//! same number of column for each row
	virtual bool is_aligned (void) const;

	// >>> DATA INFORMATION <<<
	//! checks if memory is allocated
	virtual bool is_alloc (void) const;

	//! get bytes allocated
	virtual size_t total_bytes (void) const;

	//! get data at coordinate specified
	//! getting out of bound will throw out_of_range error
	//! coordinate values not specified are implied as 0
	virtual T get (std::vector<size_t> coord) const;

	//! exposing unallocated shape will cause assertion death
	//! otherwise return data array copy
	std::vector<T> expose (void) const;

	//! serialize protobuf tensor
	void serialize (tenncor::tensor_proto* proto) const;

	// >>>> MUTATOR <<<<
	//! get allocator from factory and set it as alloc_
	void set_allocator (size_t alloc_id);

	//! set a new allowed shape
	//! chop raw data outside of new shape
	//! worst case runtime: O(min(N, M))
	//! where N is the original shape size
	//! and M is the resulting shape size
	//! result is shape is compatible with allowed shape
	void set_shape (tensorshape shape);

	//! allocate raw data using allowed (innate) shape
	//! return true if successful
	virtual bool allocate (void);

	//! forcefully deallocate raw_data,
	//! invalidates allocated (external) shape
	//! could be useful when we want to preserve allowed shape
	//! since get_shape when allocated gives allocated shape
	virtual bool deallocate (void);

	//! allocate raw data using input shape
	//! if shape is compatible with allowed
	//! else return false
	virtual bool allocate (const tensorshape shape);

	//! copy raw_data from other expanded/compressed to input shape
	//! allowed shape will be adjusted similar to set_shape
	bool copy_from (const tensor& other, const tensorshape shape);

	//! read data and shape from other, take allocator as is
	bool from_proto (const tenncor::tensor_proto& other);

	//! read data and shape from other, reassign allocator
	bool from_proto (const tenncor::tensor_proto& other, size_t alloc_id);

	// slice along the first dimension
	tensor<T> slice (size_t dim_start, size_t limit);

	// bool shares_buffer_with (const tensor& other) const;
	// size_t buffer_hash (void) const;

protected:
	//! clone implementation
	virtual itensor<T>* clone_impl (bool shapeonly) const;

	//! move implementation
	virtual itensor<T>* move_impl (void);

	// >>>> PROTECTED MEMBERS <<<<
	T* raw_data_ = nullptr; //! raw data is available to tensor manipulators

	tensorshape alloc_shape_; //! allocated shape (must be defined)

	friend class itensor_handler<T>;

private:
	//! copy utility helper
	void copy_helper (const tensor<T>& other, bool shapeonly);

	//! move utility helper
	void move_helper (tensor<T>&& other);

	// >>>> PRIVATE MEMBERS <<<<
	//! allocator
	iallocator* alloc_;

	//! not necessarily defined shape
	tensorshape allowed_shape_;
};

}

#include "../../src/tensor/tensor.ipp"

#endif /* TENNCOR_TENSOR_HPP */


text:
from security_monkey.cloudaux_watcher import CloudAuxWatcher
from security_monkey.exceptions import SecurityMonkeyException
from cloudaux.aws.s3 import list_buckets
from cloudaux.orchestration.aws.s3 import get_bucket
from security_monkey import AWS_DEFAULT_REGION

class S3(CloudAuxWatcher):
    index = 's3'
    i_am_singular = 'S3 Bucket'
    i_am_plural = 'S3 Buckets'

    def __init__(self, *args, **kwargs):
        super(S3, self).__init__(*args, **kwargs)
        self.honor_ephemerals = True
        self.ephemeral_paths = ['GrantReferences', '_version']
        self.service_name = 's3'

    def list_method(self, **kwargs):
        buckets = list_buckets(**kwargs)['Buckets']
        return [bucket['Name'] for bucket in buckets]

    def get_name_from_list_output(self, item):
        return item

    def _get_regions(self):
        return [AWS_DEFAULT_REGION]

    def get_method(self, item_name, **kwargs):
        bucket = get_bucket(item_name, **kwargs)

        if bucket and bucket.get("Error"):
            raise SecurityMonkeyException("S3 Bucket: {} fetching error: {}".format(item_name, bucket["Error"]))

        return bucket


text:
<script type="text/javascript" src="somescript.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js" async="true"></script>
<meta charset="utf-8">


text:
'use babel';

/**
 * A thin wrapper for SpacePen text editor making it work with Etch
 */
const { TextEditorView } = require('atom-space-pen-views');
import etch from 'etch';

export class EtchTextEditorView extends TextEditorView {
	update(props, children) {}

	async destroy () {
		await etch.destroy(this);
	}
}