/*
 *  Copyright (C) 2014-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "GUIControllerButton.h"
#include "games/controllers/windows/GUIControllerDefines.h"

using namespace KODI;
using namespace GAME;

CGUIControllerButton::CGUIControllerButton(const CGUIButtonControl& buttonControl, const std::string& label, unsigned int index) :
  CGUIButtonControl(buttonControl)
{
  // Initialize CGUIButtonControl
  SetLabel(label);
  SetID(CONTROL_CONTROLLER_BUTTONS_START + index);
  SetVisible(true);
  AllocResources();
}


/*!
 * # Semantic UI - Nag
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

/*******************************
            Theme
*******************************/

@type    : 'module';
@element : 'nag';

@import (multiple) '../../theme.config';

/*******************************
             Nag
*******************************/

.ui.nag {
  display: none;
  opacity: @opacity;
  position: @position;

  top: @top;
  left: 0px;
  z-index: @zIndex;

  min-height: @minHeight;
  width: @width;

  margin: @margin;
  padding: @padding;

  background: @background;
  box-shadow: @boxShadow;

  font-size: @fontSize;
  text-align: @textAlign;
  color: @color;

  border-radius: @topBorderRadius;
  transition: @transition;
}

a.ui.nag {
  cursor: pointer;
}

.ui.nag > .title {
  display: inline-block;
  margin: @titleMargin;
  color: @titleColor;
}

.ui.nag > .close.icon {
  cursor: pointer;
  opacity: @closeOpacity;

  position: absolute;
  top: @closeTop;
  right: @closeRight;

  font-size: @closeSize;

  margin: @closeMargin;
  color: @closeColor;
  transition: @closeTransition;
}

/*******************************
             States
*******************************/

/* Hover */
.ui.nag:hover {
  background: @nagHoverBackground;
  opacity: @nagHoverOpacity;
}

.ui.nag .close:hover {
  opacity: @closeHoverOpacity;
}

/*******************************
           Variations
*******************************/

/*--------------
     Static
---------------*/

.ui.overlay.nag {
  position: absolute;
  display: block;
}

/*--------------
     Fixed
---------------*/

.ui.fixed.nag {
  position: fixed;
}

/*--------------
     Bottom
---------------*/

.ui.bottom.nags,
.ui.bottom.nag {
  border-radius: @bottomBorderRadius;
  top: auto;
  bottom: @bottom;
}

/*--------------
     White
---------------*/

.ui.inverted.nags .nag,
.ui.inverted.nag {
  background-color: @invertedBackground;
  color: @darkTextColor;
}
.ui.inverted.nags .nag .close,
.ui.inverted.nags .nag .title,
.ui.inverted.nag .close,
.ui.inverted.nag .title {
  color: @lightTextColor;
}

/*******************************
           Groups
*******************************/

.ui.nags .nag {
  border-radius: @groupedBorderRadius !important;
}
.ui.nags .nag:last-child {
  border-radius: @topBorderRadius;
}
.ui.bottom.nags .nag:last-child {
  border-radius: @bottomBorderRadius;
}

.loadUIOverrides();


//  Copyright (c) 2001-2011 Joel de Guzman
//  Copyright (c) 2001-2011 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(BOOST_SPIRIT_LEX_DOMAIN_MAR_13_2007_0140PM)
#define BOOST_SPIRIT_LEX_DOMAIN_MAR_13_2007_0140PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/support/meta_compiler.hpp>
#include <boost/spirit/home/support/info.hpp>

namespace boost { namespace spirit { namespace lex
{
    // lex's domain
    struct domain {};

    // bring in some of spirit parts into spirit::lex
    using spirit::unused;
    using spirit::unused_type;
    using spirit::compile;
    using spirit::info;

}}}

#endif


set hive.test.authz.sstd.hs2.mode=true;
set hive.security.authorization.manager=org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAuthorizerFactoryForTest;
set hive.security.authenticator.manager=org.apache.hadoop.hive.ql.security.SessionStateConfigUserAuthenticator;
set user.name=hive_admin_user;
set role admin;
drop role admin;


#define COMMON_FILE_SOCK_PERMS "ioctl", "read", "write", "create", \
    "getattr", "setattr", "lock", "relabelfrom", "relabelto", "append"

#define COMMON_FILE_PERMS COMMON_FILE_SOCK_PERMS, "unlink", "link", \
    "rename", "execute", "quotaon", "mounton", "audit_access", \
    "open", "execmod"

#define COMMON_SOCK_PERMS COMMON_FILE_SOCK_PERMS, "bind", "connect", \
    "listen", "accept", "getopt", "setopt", "shutdown", "recvfrom",  \
    "sendto", "name_bind"

#define COMMON_IPC_PERMS "create", "destroy", "getattr", "setattr", "read", \
	    "write", "associate", "unix_read", "unix_write"

#define COMMON_CAP_PERMS  "chown", "dac_override", "dac_read_search", \
	    "fowner", "fsetid", "kill", "setgid", "setuid", "setpcap", \
	    "linux_immutable", "net_bind_service", "net_broadcast", \
	    "net_admin", "net_raw", "ipc_lock", "ipc_owner", "sys_module", \
	    "sys_rawio", "sys_chroot", "sys_ptrace", "sys_pacct", "sys_admin", \
	    "sys_boot", "sys_nice", "sys_resource", "sys_time", \
	    "sys_tty_config", "mknod", "lease", "audit_write", \
	    "audit_control", "setfcap"

#define COMMON_CAP2_PERMS  "mac_override", "mac_admin", "syslog", \
		"wake_alarm", "block_suspend", "audit_read"

/*
 * Note: The name for any socket class should be suffixed by "socket",
 *	 and doesn't contain more than one substr of "socket".
 */
struct security_class_mapping secclass_map[] = {
	{ "security",
	  { "compute_av", "compute_create", "compute_member",
	    "check_context", "load_policy", "compute_relabel",
	    "compute_user", "setenforce", "setbool", "setsecparam",
	    "setcheckreqprot", "read_policy", "validate_trans", NULL } },
	{ "process",
	  { "fork", "transition", "sigchld", "sigkill",
	    "sigstop", "signull", "signal", "ptrace", "getsched", "setsched",
	    "getsession", "getpgid", "setpgid", "getcap", "setcap", "share",
	    "getattr", "setexec", "setfscreate", "noatsecure", "siginh",
	    "setrlimit", "rlimitinh", "dyntransition", "setcurrent",
	    "execmem", "execstack", "execheap", "setkeycreate",
	    "setsockcreate", NULL } },
	{ "system",
	  { "ipc_info", "syslog_read", "syslog_mod",
	    "syslog_console", "module_request", "module_load", NULL } },
	{ "capability",
	  { COMMON_CAP_PERMS, NULL } },
	{ "filesystem",
	  { "mount", "remount", "unmount", "getattr",
	    "relabelfrom", "relabelto", "associate", "quotamod",
	    "quotaget", NULL } },
	{ "file",
	  { COMMON_FILE_PERMS,
	    "execute_no_trans", "entrypoint", NULL } },
	{ "dir",
	  { COMMON_FILE_PERMS, "add_name", "remove_name",
	    "reparent", "search", "rmdir", NULL } },
	{ "fd", { "use", NULL } },
	{ "lnk_file",
	  { COMMON_FILE_PERMS, NULL } },
	{ "chr_file",
	  { COMMON_FILE_PERMS, NULL } },
	{ "blk_file",
	  { COMMON_FILE_PERMS, NULL } },
	{ "sock_file",
	  { COMMON_FILE_PERMS, NULL } },
	{ "fifo_file",
	  { COMMON_FILE_PERMS, NULL } },
	{ "socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "tcp_socket",
	  { COMMON_SOCK_PERMS,
	    "node_bind", "name_connect",
	    NULL } },
	{ "udp_socket",
	  { COMMON_SOCK_PERMS,
	    "node_bind", NULL } },
	{ "rawip_socket",
	  { COMMON_SOCK_PERMS,
	    "node_bind", NULL } },
	{ "node",
	  { "recvfrom", "sendto", NULL } },
	{ "netif",
	  { "ingress", "egress", NULL } },
	{ "netlink_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "packet_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "key_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "unix_stream_socket",
	  { COMMON_SOCK_PERMS, "connectto", NULL } },
	{ "unix_dgram_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "sem",
	  { COMMON_IPC_PERMS, NULL } },
	{ "msg", { "send", "receive", NULL } },
	{ "msgq",
	  { COMMON_IPC_PERMS, "enqueue", NULL } },
	{ "shm",
	  { COMMON_IPC_PERMS, "lock", NULL } },
	{ "ipc",
	  { COMMON_IPC_PERMS, NULL } },
	{ "netlink_route_socket",
	  { COMMON_SOCK_PERMS,
	    "nlmsg_read", "nlmsg_write", NULL } },
	{ "netlink_tcpdiag_socket",
	  { COMMON_SOCK_PERMS,
	    "nlmsg_read", "nlmsg_write", NULL } },
	{ "netlink_nflog_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_xfrm_socket",
	  { COMMON_SOCK_PERMS,
	    "nlmsg_read", "nlmsg_write", NULL } },
	{ "netlink_selinux_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_iscsi_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_audit_socket",
	  { COMMON_SOCK_PERMS,
	    "nlmsg_read", "nlmsg_write", "nlmsg_relay", "nlmsg_readpriv",
	    "nlmsg_tty_audit", NULL } },
	{ "netlink_fib_lookup_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_connector_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_netfilter_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_dnrt_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "association",
	  { "sendto", "recvfrom", "setcontext", "polmatch", NULL } },
	{ "netlink_kobject_uevent_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_generic_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_scsitransport_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_rdma_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "netlink_crypto_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "appletalk_socket",
	  { COMMON_SOCK_PERMS, NULL } },
	{ "packet",
	  { "send", "recv", "relabelto", "forward_in", "forward_out", NULL } },
	{ "key",
	  { "view", "read", "write", "search", "link", "setattr", "create",
	    NULL } },
	{ "dccp_socket",
	  { COMMON_SOCK_PERMS,
	    "node_bind", "name_connect", NULL } },
	{ "memprotect", { "mmap_zero", NULL } },
	{ "peer", { "recv", NULL } },
	{ "capability2",
	  { COMMON_CAP2_PERMS, NULL } },
	{ "kernel_service", { "use_as_override", "create_files_as", NULL } },
	{ "tun_socket",
	  { COMMON_SOCK_PERMS, "attach_queue", NULL } },
	{ "binder", { "impersonate", "call", "set_context_mgr", "transfer",
		      NULL } },
	{ "cap_userns",
	  { COMMON_CAP_PERMS, NULL } },
	{ "cap2_userns",
	  { COMMON_CAP2_PERMS, NULL } },
	{ NULL }
  };


<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>ip::basic_address_iterator< address_v4 >::operator==</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../ip__basic_address_iterator_lt__address_v4__gt_.html" title="ip::basic_address_iterator< address_v4 >">
<link rel="prev" href="operator_eq_.html" title="ip::basic_address_iterator< address_v4 >::operator=">
<link rel="next" href="pointer.html" title="ip::basic_address_iterator< address_v4 >::pointer">

ip::basic_address_iterator<
        address_v4 >::operator==

Compare two addresses for equality.

friend bool operator==(
    const basic_address_iterator & a,
    const basic_address_iterator & b);

          Requirements

          Header: asio/ip/address_v4_iterator.hpp

          Convenience header: asio.hpp

Copyright © 2003-2018 Christopher M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


global.THREE = require('three')

import fs from 'fs'
import path from 'path'

import {vec2, vec3, mat3} from 'gl-matrix'
import Delaunay from 'delaunay-fast'

import StandardFaceData from './standardfacedata'

const precision = (n, p = 3) => parseFloat(n.toPrecision(p))

class App {

  constructor() {
    console.log('start')
    let start = Date.now()

    let standardFace = new StandardFaceData()

    let standardFacePoints = []
    let position = standardFace.data.face.position
    for (let i = 0; i < position.length; i += 3) {
      standardFacePoints.push([position[i], position[i + 1]])
    }
    standardFacePoints.push([1, 1])
    standardFacePoints.push([1, -1])
    standardFacePoints.push([-1, -1])
    standardFacePoints.push([-1, 1])

    this.triangleIndices = Delaunay.triangulate(standardFacePoints)
    // console.log(JSON.stringify(this.triangleIndices))

    let keyframes = JSON.parse(fs.readFileSync('../../data/3 - JSON/keyframes.json', 'utf-8'))
    // console.log(keyframes)

    let morphWeights = keyframes.user.property.face_vertices.map((vertices) => {
      let weights = []
      for (let i = 0; i < vertices.length; i += 3) {
        let [index, coord] = this.getTriangleIndex([vertices[i], vertices[i + 1]], standardFacePoints)
        weights.push(this.triangleIndices[index + 0], this.triangleIndices[index + 1], this.triangleIndices[index + 2], precision(coord[0]), precision(coord[1]), precision(coord[2]), vertices[i + 2])
      }
      return weights
    })
    fs.writeFileSync('../17 - Deformable face geometry/public/morph.json', JSON.stringify(morphWeights))

    console.log(`done! (${Date.now() - start}ms)`)
  }

  getTriangleIndex(p, vertices) {
    for (let i = 0; i < this.triangleIndices.length; i += 3) {
      let uv = Delaunay.contains([vertices[this.triangleIndices[i]], vertices[this.triangleIndices[i + 1]], vertices[this.triangleIndices[i + 2]]], p)
      if (uv) {
        uv.unshift(1 - uv[0] - uv[1])
        return [i, uv]
      }
    }
  }

}

new App()


/*
 * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
/*
 * COMPONENT_NAME: idl.parser
 *
 * ORIGINS: 27
 *
 * Licensed Materials - Property of IBM
 * 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
 * RMI-IIOP v1.0
 *
 */

package com.sun.tools.corba.se.idl;

// NOTES:

import java.io.PrintWriter;
import java.util.Hashtable;

import com.sun.tools.corba.se.idl.constExpr.Expression;

public class StringEntry extends SymtabEntry
{
  protected StringEntry ()
  {
    super ();
    String override = (String)Parser.overrideNames.get ("string");
    if (override == null)
      name ("string");
    else
      name (override);
    repositoryID (Util.emptyID);
  } // ctor

  protected StringEntry (StringEntry that)
  {
    super (that);
    _maxSize = that._maxSize;
  } // ctor

  protected StringEntry (SymtabEntry that, IDLID clone)
  {
    super (that, clone);
    module ("");

    String override = (String)Parser.overrideNames.get ("string");
    if (override == null)
      name ("string");
    else
      name (override);
    repositoryID (Util.emptyID);
  } // ctor

  public Object clone ()
  {
    return new StringEntry (this);
  } // clone

  /** Invoke the string type generator.
      @param symbolTable the symbol table is a hash table whose key is
       a fully qualified type name and whose value is a SymtabEntry or
       a subclass of SymtabEntry.
      @param stream the stream to which the generator should sent its output.
      @see SymtabEntry */
  public void generate (Hashtable symbolTable, PrintWriter stream)
  {
    stringGen.generate (symbolTable, this, stream);
  } // generate

  /** Access the primitive type generator.
      @returns an object which implements the PrimitiveGen interface.
      @see PrimitiveGen */
  public Generator generator ()
  {
    return stringGen;
  } // generator

  /** The constant expression defining the maximum size of the string.
      If it is null, then the string is unbounded. */
  public void maxSize (Expression expr)
  {
    _maxSize = expr;
  } // maxSize

  /** The constant expression defining the maximum size of the string.
      If it is null, then the string is unbounded. */
  public Expression maxSize ()
  {
    return _maxSize;
  } // maxSize

  static StringGen  stringGen;

  private Expression _maxSize = null;
} // class StringEntry


//  (C) Copyright Howard Hinnant
//  (C) Copyright 2011 Vicente J. Botet Escriba
//  Copyright (c) Microsoft Corporation 2014
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).
//

#ifndef BOOST_CHRONO_IO_TIME_POINT_UNITS_HPP
#define BOOST_CHRONO_IO_TIME_POINT_UNITS_HPP

#include <boost/chrono/config.hpp>
#include <boost/chrono/process_cpu_clocks.hpp>
#include <boost/chrono/system_clocks.hpp>
#include <boost/chrono/thread_clock.hpp>
#include <boost/chrono/io/ios_base_state.hpp>
#include <string>
#include <iostream>
#include <ios>
#include <locale>
#include <algorithm>

namespace boost
{
  namespace chrono
  {
    /**
     * customization point to the epoch associated to the clock @c Clock
     * The default calls @c f.do_get_epoch(Clock()). The user can overload this function.
     * @return the string epoch associated to the @c Clock
     */
    template <typename CharT, typename Clock, typename TPUFacet>
    std::basic_string<CharT> get_epoch_custom(Clock, TPUFacet& f)
    {
      return f.do_get_epoch(Clock());
    }

    /**
     * @c time_point_units facet gives useful information about the time_point pattern,
     * the text associated to a time_point's epoch,
     */
    template <typename CharT=char>
    class time_point_units: public std::locale::facet
    {
    public:
      /**
       * Type of character the facet is instantiated on.
       */
      typedef CharT char_type;
      /**
       * Type of character string used by member functions.
       */
      typedef std::basic_string<char_type> string_type;

      /**
       * Unique identifier for this type of facet.
       */
      static std::locale::id id;

      /**
       * Construct a @c time_point_units facet.
       * @param refs
       * @Effects Construct a @c time_point_units facet.
       * If the @c refs argument is @c 0 then destruction of the object is
       * delegated to the @c locale, or locales, containing it. This allows
       * the user to ignore lifetime management issues. On the other had,
       * if @c refs is @c 1 then the object must be explicitly deleted;
       * the @c locale will not do so. In this case, the object can be
       * maintained across the lifetime of multiple locales.
       */
      explicit time_point_units(size_t refs = 0) :
        std::locale::facet(refs)
      {
      }

      /**
       * @return the pattern to be used by default.
       */
      virtual string_type get_pattern() const =0;

      /**
       * @return the epoch associated to the clock @c Clock calling @c do_get_epoch(Clock())
       */
      template <typename Clock>
      string_type get_epoch() const
      {
        return get_epoch_custom<CharT>(Clock(), *this);
      }

    protected:
      /**
       * Destroy the facet.
       */
      virtual ~time_point_units() {}

    public:

      /**
       *
       * @param c a dummy instance of @c system_clock.
       * @return The epoch string associated to the @c system_clock.
       */
      virtual string_type do_get_epoch(system_clock) const=0;

      /**
       *
       * @param c a dummy instance of @c steady_clock.
       * @return The epoch string associated to the @c steady_clock.
       */
      virtual string_type do_get_epoch(steady_clock) const=0;

#if defined(BOOST_CHRONO_HAS_PROCESS_CLOCKS)
      /**
       *
       * @param c a dummy instance of @c process_real_cpu_clock.
       * @return The epoch string associated to the @c process_real_cpu_clock.
       */
      virtual string_type do_get_epoch(process_real_cpu_clock) const=0;
#if ! BOOST_OS_WINDOWS || BOOST_PLAT_WINDOWS_DESKTOP
      /**
       *
       * @param c a dummy instance of @c process_user_cpu_clock.
       * @return The epoch string associated to the @c process_user_cpu_clock.
       */
      virtual string_type do_get_epoch(process_user_cpu_clock) const=0;
      /**
       *
       * @param c a dummy instance of @c process_system_cpu_clock.
       * @return The epoch string associated to the @c process_system_cpu_clock.
       */
      virtual string_type do_get_epoch(process_system_cpu_clock) const=0;
      /**
       *
       * @param c a dummy instance of @c process_cpu_clock.
       * @return The epoch string associated to the @c process_cpu_clock.
       */
      virtual string_type do_get_epoch(process_cpu_clock) const=0;
#endif
#endif
#if defined(BOOST_CHRONO_HAS_THREAD_CLOCK)
      /**
       *
       * @param c a dummy instance of @c thread_clock.
       * @return The epoch string associated to the @c thread_clock.
       */
      virtual string_type do_get_epoch(thread_clock) const=0;
#endif

    };

    template <typename CharT>
    std::locale::id time_point_units<CharT>::id;

    // This class is used to define the strings for the default English
    template <typename CharT=char>
    class time_point_units_default: public time_point_units<CharT>
    {
    public:
      /**
       * Type of character the facet is instantiated on.
       */
      typedef CharT char_type;
      /**
       * Type of character string returned by member functions.
       */
      typedef std::basic_string<char_type> string_type;

      explicit time_point_units_default(size_t refs = 0) :
        time_point_units<CharT> (refs)
      {
      }
      ~time_point_units_default() {}

      /**
       * @return the default pattern "%d%e".
       */
      string_type get_pattern() const
      {
        static const CharT t[] =
        { '%', 'd', '%', 'e' };
        static const string_type pattern(t, t + sizeof (t) / sizeof (t[0]));

        return pattern;
      }

    //protected:
      /**
       * @param c a dummy instance of @c system_clock.
       * @return The epoch string returned by @c clock_string<system_clock,CharT>::since().
       */
      string_type do_get_epoch(system_clock ) const
      {
        return clock_string<system_clock,CharT>::since();
      }
      /**
       * @param c a dummy instance of @c steady_clock.
       * @return The epoch string returned by @c clock_string<steady_clock,CharT>::since().
       */
      string_type do_get_epoch(steady_clock ) const
      {
        return clock_string<steady_clock,CharT>::since();
      }

#if defined(BOOST_CHRONO_HAS_PROCESS_CLOCKS)
      /**
       * @param c a dummy instance of @c process_real_cpu_clock.
       * @return The epoch string returned by @c clock_string<process_real_cpu_clock,CharT>::since().
       */
      string_type do_get_epoch(process_real_cpu_clock ) const
      {
        return clock_string<process_real_cpu_clock,CharT>::since();
      }
#if ! BOOST_OS_WINDOWS || BOOST_PLAT_WINDOWS_DESKTOP
      /**
       * @param c a dummy instance of @c process_user_cpu_clock.
       * @return The epoch string returned by @c clock_string<process_user_cpu_clock,CharT>::since().
       */
      string_type do_get_epoch(process_user_cpu_clock ) const
      {
        return clock_string<process_user_cpu_clock,CharT>::since();
      }
      /**
       * @param c a dummy instance of @c process_system_cpu_clock.
       * @return The epoch string returned by @c clock_string<process_system_cpu_clock,CharT>::since().
       */
      string_type do_get_epoch(process_system_cpu_clock ) const
      {
        return clock_string<process_system_cpu_clock,CharT>::since();
      }
      /**
       * @param c a dummy instance of @c process_cpu_clock.
       * @return The epoch string returned by @c clock_string<process_cpu_clock,CharT>::since().
       */
      string_type do_get_epoch(process_cpu_clock ) const
      {
        return clock_string<process_cpu_clock,CharT>::since();
      }

#endif
#endif
#if defined(BOOST_CHRONO_HAS_THREAD_CLOCK)
      /**
       * @param c a dummy instance of @c thread_clock.
       * @return The epoch string returned by @c clock_string<thread_clock,CharT>::since().
       */
      string_type do_get_epoch(thread_clock ) const
      {
        return clock_string<thread_clock,CharT>::since();
      }
#endif

    };

  } // chrono

} // boost

#endif  // header


$(eval $(call test,decision_tree_xor_test,boosting utils arch worker_task,boost))
$(eval $(call test,split_test,boosting,boost))
$(eval $(call test,decision_tree_multithreaded_test,boosting utils arch worker_task,boost))
$(eval $(call test,decision_tree_unlimited_depth_test,boosting utils arch worker_task,boost))
$(eval $(call test,glz_classifier_test,boosting utils arch worker_task,boost))
$(eval $(call test,probabilizer_test,boosting utils arch,boost))
$(eval $(call test,feature_info_test,boosting utils arch,boost))
$(eval $(call test,weighted_training_test,boosting,boost manual))

$(eval $(call program,dataset_nan_test,boosting utils arch boosting_tools))

ifeq ($(CUDA_ENABLED),1)
$(eval $(call test,split_cuda_test,boosting_cuda,boost))
endif # CUDA_ENABLED


#%Module
puts stderr "[module-info mode] [module-info name]"
conflict ih


<?php

namespace Drupal\Tests\image\Functional\Hal;

use Drupal\Tests\image\Functional\Rest\ImageStyleResourceTestBase;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;

/**
 * @group hal
 */
class ImageStyleHalJsonBasicAuthTest extends ImageStyleResourceTestBase {

  use BasicAuthResourceTestTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['hal', 'basic_auth'];

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * {@inheritdoc}
   */
  protected static $format = 'hal_json';

  /**
   * {@inheritdoc}
   */
  protected static $mimeType = 'application/hal+json';

  /**
   * {@inheritdoc}
   */
  protected static $auth = 'basic_auth';

}


/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     | Website:  https://openfoam.org
    \\  /    A nd           | Copyright (C) 2017-2020 OpenFOAM Foundation
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

Class
    Foam::fileOperations::hostCollatedFileOperation

Description
    Version of collatedFileOperation with multiple read/write ranks.

    In parallel it will assume ranks are sorted according to hostname
    and the lowest rank per hostname will be the IO rank. The output directories
    will get a unique name processors<N>_<low>-<high> where N is the overall
    number of processors and low and high is the range of ranks contained
    in the files. Each of these subsets uses its own communicator.

    Instead of using the hostnames the IO ranks can be assigned using the
    FOAM_IORANKS environment variable (also when running non-parallel), e.g.
    when decomposing into 4:

        FOAM_IORANKS='(0 2)' decomposePar -fileHandler hostCollated

    will generate

        processors4_0-1/
            containing data for processors 0 to 1
        processors4_2-3/
            containing data for processors 2 to 3

See also
    collatedFileOperation

SourceFiles
    hostCollatedFileOperation.C

\*---------------------------------------------------------------------------*/

#ifndef fileOperations_hostCollatedFileOperation_H
#define fileOperations_hostCollatedFileOperation_H

#include "collatedFileOperation.H"

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

namespace Foam
{
namespace fileOperations
{

/*---------------------------------------------------------------------------*\
                  Class hostCollatedFileOperation Declaration
\*---------------------------------------------------------------------------*/

class hostCollatedFileOperation
:
    public collatedFileOperation
{
   // Private Member Functions

        //- Get the list of processors part of this set
        static labelList subRanks(const label n);

public:

        //- Runtime type information
        TypeName("hostCollated");

    // Constructors

        //- Construct null
        hostCollatedFileOperation(const bool verbose);

    //- Destructor
    virtual ~hostCollatedFileOperation();
};

/*---------------------------------------------------------------------------*\
             Class hostCollatedFileOperationInitialise Declaration
\*---------------------------------------------------------------------------*/

class hostCollatedFileOperationInitialise
:
    public collatedFileOperationInitialise
{
public:

    // Constructors

        //- Construct from components
        hostCollatedFileOperationInitialise(int& argc, char**& argv)
        :
            collatedFileOperationInitialise(argc, argv)
        {}

    //- Destructor
    virtual ~hostCollatedFileOperationInitialise()
    {}
};

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

} // End namespace fileOperations
} // End namespace Foam

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

#endif

// ************************************************************************* //


/**
 * Copyright (c) 2013-2014 Tomas Dzetkulic
 * Copyright (c) 2013-2014 Pavol Rusnak
 * Copyright (c)      2015 Jochen Hoenicke
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include "rfc6979.h"
#include <string.h>
#include "hmac.h"
#include "memzero.h"

void init_rfc6979(const uint8_t *priv_key, const uint8_t *hash,
                  rfc6979_state *state) {
  uint8_t bx[2 * 32];
  uint8_t buf[32 + 1 + 2 * 32];

  memcpy(bx, priv_key, 32);
  memcpy(bx + 32, hash, 32);

  memset(state->v, 1, sizeof(state->v));
  memset(state->k, 0, sizeof(state->k));

  memcpy(buf, state->v, sizeof(state->v));
  buf[sizeof(state->v)] = 0x00;
  memcpy(buf + sizeof(state->v) + 1, bx, 64);
  hmac_sha256(state->k, sizeof(state->k), buf, sizeof(buf), state->k);
  hmac_sha256(state->k, sizeof(state->k), state->v, sizeof(state->v), state->v);

  memcpy(buf, state->v, sizeof(state->v));
  buf[sizeof(state->v)] = 0x01;
  memcpy(buf + sizeof(state->v) + 1, bx, 64);
  hmac_sha256(state->k, sizeof(state->k), buf, sizeof(buf), state->k);
  hmac_sha256(state->k, sizeof(state->k), state->v, sizeof(state->v), state->v);

  memzero(bx, sizeof(bx));
  memzero(buf, sizeof(buf));
}

// generate next number from deterministic random number generator
void generate_rfc6979(uint8_t rnd[32], rfc6979_state *state) {
  uint8_t buf[32 + 1];

  hmac_sha256(state->k, sizeof(state->k), state->v, sizeof(state->v), state->v);
  memcpy(buf, state->v, sizeof(state->v));
  buf[sizeof(state->v)] = 0x00;
  hmac_sha256(state->k, sizeof(state->k), buf, sizeof(state->v) + 1, state->k);
  hmac_sha256(state->k, sizeof(state->k), state->v, sizeof(state->v), state->v);
  memcpy(rnd, buf, 32);
  memzero(buf, sizeof(buf));
}

// generate K in a deterministic way, according to RFC6979
// http://tools.ietf.org/html/rfc6979
void generate_k_rfc6979(bignum256 *k, rfc6979_state *state) {
  uint8_t buf[32];
  generate_rfc6979(buf, state);
  bn_read_be(buf, k);
  memzero(buf, sizeof(buf));
}


/*
 * ATTRIB - Wine-compatible attrib program
 *
 * Copyright 2010-2012 Christian Costa
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include <windows.h>
#include <wine/debug.h>
#include "attrib.h"

WINE_DEFAULT_DEBUG_CHANNEL(attrib);

static const WCHAR starW[]  = {'*','\0'};

/* =========================================================================
 * Load a string from the resource file, handling any error
 * Returns string retrieved from resource file
 * ========================================================================= */
static WCHAR *ATTRIB_LoadMessage(UINT id)
{
    static WCHAR msg[MAXSTRING];
    const WCHAR failedMsg[]  = {'F', 'a', 'i', 'l', 'e', 'd', '!', 0};

    if (!LoadStringW(GetModuleHandleW(NULL), id, msg, ARRAY_SIZE(msg))) {
        WINE_FIXME("LoadString failed with %d\n", GetLastError());
        lstrcpyW(msg, failedMsg);
    }
    return msg;
}

/* =========================================================================
 * Output a formatted unicode string. Ideally this will go to the console
 *  and hence required WriteConsoleW to output it, however if file i/o is
 *  redirected, it needs to be WriteFile'd using OEM (not ANSI) format
 * ========================================================================= */
static int WINAPIV ATTRIB_wprintf(const WCHAR *format, ...)
{
    static WCHAR *output_bufW = NULL;
    static char  *output_bufA = NULL;
    static BOOL  toConsole    = TRUE;
    static BOOL  traceOutput  = FALSE;
#define MAX_WRITECONSOLE_SIZE 65535

    __ms_va_list parms;
    DWORD   nOut;
    int len;
    DWORD   res = 0;

    /*
     * Allocate buffer to use when writing to console
     * Note: Not freed - memory will be allocated once and released when
     * attrib ends
     */

    if (!output_bufW) output_bufW = HeapAlloc(GetProcessHeap(), 0,
                                              MAX_WRITECONSOLE_SIZE*sizeof(WCHAR));
    if (!output_bufW) {
        WINE_FIXME("Out of memory - could not allocate 2 x 64 KB buffers\n");
        return 0;
    }

    __ms_va_start(parms, format);
    len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING, format, 0, 0, output_bufW,
                   MAX_WRITECONSOLE_SIZE/sizeof(*output_bufW), &parms);
    __ms_va_end(parms);
    if (len == 0 && GetLastError() != ERROR_NO_WORK_DONE) {
        WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
        return 0;
    }

    /* Try to write as unicode all the time we think it's a console */
    if (toConsole) {
        res = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),
                            output_bufW, len, &nOut, NULL);
    }

    /* If writing to console has failed (ever) we assume it's file
       i/o so convert to OEM codepage and output                  */
    if (!res) {
        BOOL usedDefaultChar = FALSE;
        DWORD convertedChars;

        toConsole = FALSE;

        /*
         * Allocate buffer to use when writing to file. Not freed, as above
         */
        if (!output_bufA) output_bufA = HeapAlloc(GetProcessHeap(), 0,
                                                MAX_WRITECONSOLE_SIZE);
        if (!output_bufA) {
          WINE_FIXME("Out of memory - could not allocate 2 x 64 KB buffers\n");
          return 0;
        }

        /* Convert to OEM, then output */
        convertedChars = WideCharToMultiByte(GetConsoleOutputCP(), 0, output_bufW,
                            len, output_bufA, MAX_WRITECONSOLE_SIZE,
                            "?", &usedDefaultChar);
        WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), output_bufA, convertedChars,
                  &nOut, FALSE);
    }

    /* Trace whether screen or console */
    if (!traceOutput) {
        WINE_TRACE("Writing to console? (%d)\n", toConsole);
        traceOutput = TRUE;
    }
    return nOut;
}

/* =========================================================================
 * Handle the processing for a single directory, optionally recursing into
 *  subdirectories if needed.
 * Parameters:
 *  rootdir      [I]   The directory to search in
 *  filespec     [I]   The filespec to search for
 *  recurse      [I]   Whether to recurse (search subdirectories before
 *                          current directory)
 *  includedirs  [I]   Whether to set directory attributes as well
 *  attrib_set   [I]   Attributes to set
 *  attrib_clear [I]   Attributes to clear
 *
 * Returns TRUE if at least one file displayed / modified
 * ========================================================================= */
static BOOL ATTRIB_processdirectory(const WCHAR *rootdir, const WCHAR *filespec,
                                    BOOL recurse, BOOL includedirs,
                                    DWORD attrib_set, DWORD attrib_clear)
{
    BOOL found = FALSE;
    WCHAR buffer[MAX_PATH];
    HANDLE hff;
    WIN32_FIND_DATAW fd;
    WCHAR flags[] = {' ',' ',' ',' ',' ',' ',' ',' ','\0'};
    static const WCHAR slashW[] = {'\\','\0'};

    WINE_TRACE("Processing dir '%s', spec '%s', %d,%x,%x\n",
               wine_dbgstr_w(rootdir), wine_dbgstr_w(filespec),
               recurse, attrib_set, attrib_clear);

    if (recurse) {

      /* Build spec to search for */
      lstrcpyW(buffer, rootdir);
      lstrcatW(buffer, starW);

      /* Search for directories in the location and recurse if necessary */
      WINE_TRACE("Searching for directories with '%s'\n", wine_dbgstr_w(buffer));
      hff = FindFirstFileW(buffer, &fd);
      if (hff != INVALID_HANDLE_VALUE) {
          do {
              const WCHAR dot[] = {'.', 0};
              const WCHAR dotdot[] = {'.', '.', 0};

              /* Only interested in directories, and not . nor .. */
              if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
                  !lstrcmpW(fd.cFileName, dot) || !lstrcmpW(fd.cFileName, dotdot))
                  continue;

              /* Build new root dir to go searching in */
              lstrcpyW(buffer, rootdir);
              lstrcatW(buffer, fd.cFileName);
              lstrcatW(buffer, slashW);
              ATTRIB_processdirectory(buffer, filespec, recurse, includedirs,
                                      attrib_set, attrib_clear);

          } while (FindNextFileW(hff, &fd) != 0);
      }
      FindClose (hff);
    }

    /* Build spec to search for */
    lstrcpyW(buffer, rootdir);
    lstrcatW(buffer, filespec);
    WINE_TRACE("Searching for files as '%s'\n", wine_dbgstr_w(buffer));

    /* Search for files in the location with the filespec supplied */
    hff = FindFirstFileW(buffer, &fd);
    if (hff != INVALID_HANDLE_VALUE) {
        do {
            const WCHAR dot[] = {'.', 0};
            const WCHAR dotdot[] = {'.', '.', 0};
            DWORD count;
            WINE_TRACE("Found '%s'\n", wine_dbgstr_w(fd.cFileName));

            if (!lstrcmpW(fd.cFileName, dot) || !lstrcmpW(fd.cFileName, dotdot))
                continue;

            if (!includedirs && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
              continue;

            if (attrib_set || attrib_clear) {
                fd.dwFileAttributes &= ~attrib_clear;
                fd.dwFileAttributes |= attrib_set;
                if (!fd.dwFileAttributes)
                    fd.dwFileAttributes |= FILE_ATTRIBUTE_NORMAL;
                lstrcpyW(buffer, rootdir);
                lstrcatW(buffer, fd.cFileName);
                SetFileAttributesW(buffer, fd.dwFileAttributes);
                found = TRUE;
            } else {
                static const WCHAR fmt[] = {'%','1',' ',' ',' ',' ',' ','%','2','\n','\0'};
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
                    flags[4] = 'H';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
                    flags[1] = 'S';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
                    flags[0] = 'A';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
                    flags[5] = 'R';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
                    flags[6] = 'T';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
                    flags[7] = 'C';
                }
                lstrcpyW(buffer, rootdir);
                lstrcatW(buffer, fd.cFileName);
                ATTRIB_wprintf(fmt, flags, buffer);
                for (count = 0; count < (ARRAY_SIZE(flags) - 1); count++) flags[count] = ' ';
                found = TRUE;
            }
        } while (FindNextFileW(hff, &fd) != 0);
    }
    FindClose (hff);
    return found;
}

int __cdecl wmain(int argc, WCHAR *argv[])
{
    WCHAR name[MAX_PATH];
    WCHAR *namepart;
    WCHAR curdir[MAX_PATH];
    WCHAR originalname[MAX_PATH];
    DWORD attrib_set = 0;
    DWORD attrib_clear = 0;
    BOOL  attrib_recurse = FALSE;
    BOOL  attrib_includedirs = FALSE;
    static const WCHAR help_option[] = {'/','?','\0'};
    static const WCHAR wildcardsW[] = {'*','?','\0'};
    int i = 1;
    BOOL  found = FALSE;

    if ((argc >= 2) && !lstrcmpW(argv[1], help_option)) {
        ATTRIB_wprintf(ATTRIB_LoadMessage(STRING_HELP));
        return 0;
    }

    /* By default all files from current directory are taken into account */
    lstrcpyW(name, starW);

    while (i < argc) {
        WCHAR *param = argv[i++];
        WINE_TRACE("Processing arg: '%s'\n", wine_dbgstr_w(param));
        if ((param[0] == '+') || (param[0] == '-')) {
            DWORD attrib = 0;
            switch (param[1]) {
            case 'H': case 'h': attrib |= FILE_ATTRIBUTE_HIDDEN; break;
            case 'S': case 's': attrib |= FILE_ATTRIBUTE_SYSTEM; break;
            case 'R': case 'r': attrib |= FILE_ATTRIBUTE_READONLY; break;
            case 'A': case 'a': attrib |= FILE_ATTRIBUTE_ARCHIVE; break;
            default:
                ATTRIB_wprintf(ATTRIB_LoadMessage(STRING_NYI));
                return 0;
            }
            switch (param[0]) {
            case '+': attrib_set = attrib; break;
            case '-': attrib_clear = attrib; break;
            }
        } else if (param[0] == '/') {
            if (((param[1] == 'D') || (param[1] == 'd')) && !param[2]) {
                attrib_includedirs = TRUE;
            } else if (((param[1] == 'S') || (param[1] == 's')) && !param[2]) {
                attrib_recurse = TRUE;
            } else {
                WINE_FIXME("Unknown option %s\n", debugstr_w(param));
            }
        } else if (param[0]) {
            lstrcpyW(originalname, param);
        }
    }

    /* Name may be a relative or explicit path, so calculate curdir based on
       current locations, stripping off the filename                         */
    WINE_TRACE("Supplied name: '%s'\n", wine_dbgstr_w(originalname));
    GetFullPathNameW(originalname, ARRAY_SIZE(curdir), curdir, &namepart);
    WINE_TRACE("Result: '%s'\n", wine_dbgstr_w(curdir));
    if (namepart) {
        lstrcpyW(name, namepart);
        *namepart = 0;
    } else {
        name[0] = 0;
    }

    /* If a directory is explicitly supplied on the command line, and no
       wildcards are in the name, then allow it to be changed/displayed  */
    if (wcspbrk(originalname, wildcardsW) == NULL) attrib_includedirs = TRUE;

    /* Do all the processing based on the filename arg */
    found = ATTRIB_processdirectory(curdir, name, attrib_recurse,
                                    attrib_includedirs, attrib_set, attrib_clear);
    if (!found) {
      ATTRIB_wprintf(ATTRIB_LoadMessage(STRING_FILENOTFOUND), originalname);
    }
    return 0;
}


/**
 * Copyright 2018 Google LLC
 *
 * 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.
 */

output "project_id" {
  value = module.example.project_id
}

output "region" {
  value = module.example.region
}

output "network" {
  value = google_compute_network.main.name
}

output "subnetwork" {
  value = google_compute_subnetwork.main.name
}

output "ip_range_pods" {
  description = "The secondary IP range used for pods"
  value       = google_compute_subnetwork.main.secondary_ip_range[0].range_name
}

output "ip_range_services" {
  description = "The secondary IP range used for services"
  value       = google_compute_subnetwork.main.secondary_ip_range[1].range_name
}

output "location" {
  description = "Cluster location (zones)"
  value       = module.example.location
}

output "kubernetes_endpoint" {
  sensitive = true
  value     = module.example.kubernetes_endpoint
}

output "client_token" {
  sensitive = true
  value     = module.example.client_token
}

output "ca_certificate" {
  description = "The cluster CA certificate"
  value       = module.example.ca_certificate
}

output "service_account" {
  description = "The service account to default running nodes as if not overridden in `node_pools`."
  value       = module.example.service_account
}

output "registry_project_id" {
  value = var.registry_project_id
}

output "cluster_name" {
  description = "Cluster name"
  value       = module.example.cluster_name
}

output "k8s_service_account_email" {
  description = "K8S GCP service account."
  value       = module.example.k8s_service_account_email
}

output "k8s_service_account_name" {
  description = "K8S GCP service account name."
  value       = module.example.k8s_service_account_name
}


#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>
#include <windows.h>
#include <Wininet.h>
#include <tchar.h>
#include <ras.h>
#include <raserror.h>

#pragma comment(lib, "rasapi32.lib")
#pragma comment(lib, "Wininet.lib")

enum RET_ERRORS
{
    RET_NO_ERROR = 0,
    INVALID_FORMAT = 1,
    NO_PERMISSION = 2,
    SYSCALL_FAILED = 3,
    NO_MEMORY = 4,
    INVAILD_OPTION_COUNT = 5,
};

void usage(LPCTSTR binName)
{
    _tprintf(_T("Usage: %s global <proxy-server> [<bypass>]\n"), binName);
    _tprintf(_T("       %s pac <pac-url>\n"), binName);
    _tprintf(_T("       %s off\n"), binName);

    exit(INVALID_FORMAT);
}

void reportWindowsError(LPCTSTR action)
{
    LPTSTR pErrMsg = NULL;
    DWORD errCode = GetLastError();
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                                FORMAT_MESSAGE_FROM_SYSTEM |
                                                FORMAT_MESSAGE_ARGUMENT_ARRAY,
                                                NULL,
                                                errCode,
                                                LANG_NEUTRAL,
                                                (LPTSTR)&pErrMsg,
                                                0,
                                                NULL);
    _ftprintf(stderr, _T("Error %s: %lu %s\n"), action, errCode, pErrMsg);
}

void reportError(LPCTSTR action)
{
    _ftprintf(stderr, _T("Error %s\n"), action);
}

void initialize(INTERNET_PER_CONN_OPTION_LIST* options, int option_count)
{
    if (option_count < 1)
    {
        exit(INVAILD_OPTION_COUNT);
    }

    DWORD dwBufferSize = sizeof(INTERNET_PER_CONN_OPTION_LIST);
    options->dwSize = dwBufferSize;

    options->dwOptionCount = option_count;
    options->dwOptionError = 0;

    options->pOptions = (INTERNET_PER_CONN_OPTION*)calloc(option_count, sizeof(INTERNET_PER_CONN_OPTION));

    if (!options->pOptions)
    {
        exit(NO_MEMORY);
    }

    options->pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS;
}

int apply_connect(INTERNET_PER_CONN_OPTION_LIST* options, LPTSTR conn)
{
    options->pszConnection = conn;

    BOOL result = InternetSetOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, options, sizeof(INTERNET_PER_CONN_OPTION_LIST));
    if (!result)
    {
        reportWindowsError(_T("setting options"));
        return SYSCALL_FAILED;
    }

    result = InternetSetOption(NULL, INTERNET_OPTION_PROXY_SETTINGS_CHANGED, NULL, 0);
    if (!result)
    {
        reportWindowsError(_T("propagating changes"));
        return SYSCALL_FAILED;
    }

    result = InternetSetOption(NULL, INTERNET_OPTION_REFRESH, NULL, 0);
    if (!result)
    {
        reportWindowsError(_T("refreshing"));
        return SYSCALL_FAILED;
    }

    return RET_NO_ERROR;
}

int apply(INTERNET_PER_CONN_OPTION_LIST* options)
{
    DWORD dwCb = 0;
    DWORD dwRet;
    DWORD dwEntries = 0;

    dwRet = RasEnumEntries(NULL, NULL, NULL, &dwCb, &dwEntries);

    if (dwRet == ERROR_BUFFER_TOO_SMALL)
    {
        LPRASENTRYNAME lpRasEntryName = (LPRASENTRYNAME)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb);

        if (lpRasEntryName == NULL)
        {
            reportError(_T("HeapAlloc"));
            return NO_MEMORY;
        }

        for (DWORD i = 0; i < dwEntries; i++)
        {
            lpRasEntryName[i].dwSize = sizeof(RASENTRYNAME);
        }

        dwRet = RasEnumEntries(NULL, NULL, lpRasEntryName, &dwCb, &dwEntries);

        int ret;

        if (ERROR_SUCCESS != dwRet)
        {
            _ftprintf(stderr, _T("Error RasEnumEntries: %d\n"), dwRet);

            ret = SYSCALL_FAILED;
        }
        else
        {
            // First set default connection.
            ret = apply_connect(options, NULL);

            for (DWORD i = 0; i < dwEntries && ret == RET_NO_ERROR; i++)
            {
                ret = apply_connect(options, lpRasEntryName[i].szEntryName);
            }
        }

        HeapFree(GetProcessHeap(), 0, lpRasEntryName);

        return ret;
    }

    if (dwEntries >= 1)
    {
        reportError(_T("acquire buffer size"));
        return SYSCALL_FAILED;
    }

    // No ras entry, set default only.
    return apply_connect(options, NULL);
}

int _tmain(int argc, LPTSTR argv[])
{
#ifdef _UNICODE
    _setmode(_fileno(stdin), _O_U16TEXT);
    _setmode(_fileno(stdout), _O_U16TEXT);
    _setmode(_fileno(stderr), _O_U16TEXT);
#endif

    if (argc < 2)
    {
        usage(argv[0]);
    }

    INTERNET_PER_CONN_OPTION_LIST options;
    if (_tcscmp(argv[1], _T("off")) == 0)
    {
        initialize(&options, 1);

        options.pOptions[0].Value.dwValue = PROXY_TYPE_AUTO_DETECT | PROXY_TYPE_DIRECT;
    }
    else if (_tcscmp(argv[1], _T("global")) == 0 && argc >= 3)
    {
        if (argc > 4)
        {
            _ftprintf(stderr, _T("Error: bypass list shouldn't contain spaces, please check parameters.\n"));
            usage(argv[0]);
        }

        initialize(&options, 3);

        options.pOptions[0].Value.dwValue = PROXY_TYPE_PROXY | PROXY_TYPE_DIRECT;

        options.pOptions[1].dwOption = INTERNET_PER_CONN_PROXY_SERVER;
        options.pOptions[1].Value.pszValue = argv[2];

        options.pOptions[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS;

        if (argc == 4)
        {
            options.pOptions[2].Value.pszValue = argv[3];
        }
        else
        {
            options.pOptions[2].Value.pszValue = _T("<local>");
        }
    }
    else if (_tcscmp(argv[1], _T("pac")) == 0 && argc >= 3)
    {
        initialize(&options, 2);

        options.pOptions[0].Value.dwValue = PROXY_TYPE_AUTO_PROXY_URL | PROXY_TYPE_DIRECT;

        options.pOptions[1].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL;
        options.pOptions[1].Value.pszValue = argv[2];
    }
    else
    {
        usage(argv[0]);
    }

    int ret = apply(&options);

    free(options.pOptions);

    return ret;
}


package sat

import (
	"sort"

	"github.com/mitchellh/go-sat/cnf"
)

// AddFormula adds the given formula to the solver.
//
// This can only be called before Solve() is called.
func (s *Solver) AddFormula(f cnf.Formula) {
	for _, c := range f {
		s.AddClause(c)
	}
}

// AddClause adds a Clause to solve to the solver.
//
// This can only be called before Solve() is called.
func (s *Solver) AddClause(c cnf.Clause) {
	// Get the actual slice since we'll be modifying this directly.
	// The API docs say not to but its part of our package and we know
	// what we're doing. :)
	lits := c

	// Sort
	sort.Slice(lits, func(i, j int) bool {
		return lits[i] < lits[j]
	})

	// Keep track of an index since we'll be slicing as we go. We also
	// keep track of the last value so that we can find tautologies (X | !X)
	idx := 0
	last := cnf.LitUndef
	for _, current := range lits {
		// Due to the sorting X and !X will always be next to each other.
		// A cheap way to check for tautologies is to just check the last
		// value.
		if current == last.Neg() {
			if s.Trace {
				s.Tracer.Printf(
					"[TRACE] sat: addClause: not adding clause; tautology with var %s",
					current)
			}

			return
		}

		// Check if there is currently an assigned value of the literal.
		// If it is false then we already can skip this literal. If it is
		// true we can avoid adding the entire clause.
		switch s.valueLit(current) {
		case triFalse:
			if s.Trace {
				s.Tracer.Printf(
					"[TRACE] sat: addClause: not adding literal; literal %s false: %s",
					current, c)
			}

			continue

		case triTrue:
			if s.Trace {
				s.Tracer.Printf(
					"[TRACE] sat: addClause: not adding clause; literal %s already true: %s",
					current, c)
			}

			return
		}

		// Due to sorting, we can quickly eliminate duplicates by only copying
		// down when the values aren't the same.
		if current != last {
			lits[idx] = current
			last = current
			idx++
		}
	}

	// Reset the size of literals to account for removed duplicates
	lits = lits[:idx]

	// If the clause is empty, then this formula can already not be satisfied
	if len(lits) == 0 {
		if s.Trace {
			s.Tracer.Printf("[TRACE] sat: addClause: empty clause, forcing unsat")
		}

		s.result = satResultUnsat
		return
	}

	// Track the available decision variables
	for _, l := range lits {
		s.vars[l.Var()] = struct{}{}
	}

	// If this is a single literal clause then we assert it cause it must be
	if len(lits) == 1 {
		if s.Trace {
			s.Tracer.Printf("[TRACE] sat: addClause: single literal clause, asserting %s", lits[0])
		}

		s.assertLiteral(lits[0], nil)

		// Do unit propagation since this may solve already clauses
		s.propagate()

		// We also don't add this clause since we just asserted the value
		return
	}

	// Add it to our formula
	c = cnf.Clause(lits)
	s.clauses = append(s.clauses, c)
	s.watchClause(c)
}


/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_XMLOFF_SOURCE_CHART_SCHXMLCALCULATIONSETTINGSCONTEXT_HXX
#define INCLUDED_XMLOFF_SOURCE_CHART_SCHXMLCALCULATIONSETTINGSCONTEXT_HXX

#include <xmloff/xmlictxt.hxx>

class SchXMLCalculationSettingsContext : public SvXMLImportContext
{
    css::uno::Any m_aNullDate;
public:
    SchXMLCalculationSettingsContext( SvXMLImport& rImport,
                                    sal_uInt16 nPrefix,
                                    const OUString& rLocalName,
                                    const css::uno::Reference< css::xml::sax::XAttributeList >& xAttrList );

    virtual SvXMLImportContextRef CreateChildContext( sal_uInt16 nPrefix,
                                   const OUString& rLocalName,
                                   const css::uno::Reference< css::xml::sax::XAttributeList >& xAttrList ) override;

    virtual void EndElement() override;
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */


fileFormatVersion: 2
guid: ffadda4d55496724c8c302c007d78cd1
timeCreated: 1427393154
licenseType: Pro
MonoImporter:
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:


/*!
 * jQuery UI Datepicker 1.8.20
 *
 * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
 * Licensed under the MIT license.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Datepicker#theming
 */
.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; }
.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; }
.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
.ui-datepicker .ui-datepicker-prev { left:2px; }
.ui-datepicker .ui-datepicker-next { right:2px; }
.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
.ui-datepicker .ui-datepicker-next-hover { right:1px; }
.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px;  }
.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; }
.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
.ui-datepicker select.ui-datepicker-month,
.ui-datepicker select.ui-datepicker-year { width: 49%;}
.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0;  }
.ui-datepicker td { border: 0; padding: 1px; }
.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }

/* with multiple calendars */
.ui-datepicker.ui-datepicker-multi { width:auto; }
.ui-datepicker-multi .ui-datepicker-group { float:left; }
.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; }

/* RTL support */
.ui-datepicker-rtl { direction: rtl; }
.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
.ui-datepicker-rtl .ui-datepicker-group { float:right; }
.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }

/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
.ui-datepicker-cover {
    display: none; /*sorry for IE5*/
    display/**/: block; /*sorry for IE5*/
    position: absolute; /*must have*/
    z-index: -1; /*must have*/
    filter: mask(); /*must have*/
    top: -4px; /*must have*/
    left: -4px; /*must have*/
    width: 200px; /*must have*/
    height: 200px; /*must have*/
}


#ifndef _REGEX_H_
#define _REGEX_H_				/* never again */
/*
 * regular expressions
 *
 * Copyright (c) 1998, 1999 Henry Spencer.  All rights reserved.
 *
 * Development of this software was funded, in part, by Cray Research Inc.,
 * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics
 * Corporation, none of whom are responsible for the results.  The author
 * thanks all of them.
 *
 * Redistribution and use in source and binary forms -- with or without
 * modification -- are permitted for any purpose, provided that
 * redistributions in source form retain this entire copyright notice and
 * indicate the origin and nature of any modifications.
 *
 * I'd appreciate being given credit for this package in the documentation
 * of software which uses it, but that is not a requirement.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * HENRY SPENCER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * src/include/regex/regex.h
 */

/*
 * Add your own defines, if needed, here.
 */
#include "mb/pg_wchar.h"

/*
 * interface types etc.
 */

/*
 * regoff_t has to be large enough to hold either off_t or ssize_t,
 * and must be signed; it's only a guess that long is suitable.
 */
typedef long regoff_t;

/*
 * other interface types
 */

/* the biggie, a compiled RE (or rather, a front end to same) */
typedef struct
{
	int			re_magic;		/* magic number */
	size_t		re_nsub;		/* number of subexpressions */
	long		re_info;		/* information about RE */
#define  REG_UBACKREF		 000001
#define  REG_ULOOKAHEAD		 000002
#define  REG_UBOUNDS	 000004
#define  REG_UBRACES	 000010
#define  REG_UBSALNUM		 000020
#define  REG_UPBOTCH	 000040
#define  REG_UBBS		 000100
#define  REG_UNONPOSIX		 000200
#define  REG_UUNSPEC	 000400
#define  REG_UUNPORT	 001000
#define  REG_ULOCALE	 002000
#define  REG_UEMPTYMATCH	 004000
#define  REG_UIMPOSSIBLE	 010000
#define  REG_USHORTEST		 020000
	int			re_csize;		/* sizeof(character) */
	char	   *re_endp;		/* backward compatibility kludge */
	Oid			re_collation;	/* Collation that defines LC_CTYPE behavior */
	/* the rest is opaque pointers to hidden innards */
	char	   *re_guts;		/* `char *' is more portable than `void *' */
	char	   *re_fns;
} regex_t;

/* result reporting (may acquire more fields later) */
typedef struct
{
	regoff_t	rm_so;			/* start of substring */
	regoff_t	rm_eo;			/* end of substring */
} regmatch_t;

/* supplementary control and reporting */
typedef struct
{
	regmatch_t	rm_extend;		/* see REG_EXPECT */
} rm_detail_t;

/*
 * regex compilation flags
 */
#define REG_BASIC	000000		/* BREs (convenience) */
#define REG_EXTENDED	000001	/* EREs */
#define REG_ADVF	000002		/* advanced features in EREs */
#define REG_ADVANCED	000003	/* AREs (which are also EREs) */
#define REG_QUOTE	000004		/* no special characters, none */
#define REG_NOSPEC	REG_QUOTE	/* historical synonym */
#define REG_ICASE	000010		/* ignore case */
#define REG_NOSUB	000020		/* don't care about subexpressions */
#define REG_EXPANDED	000040	/* expanded format, white space & comments */
#define REG_NLSTOP	000100		/* \n doesn't match . or [^ ] */
#define REG_NLANCH	000200		/* ^ matches after \n, $ before */
#define REG_NEWLINE 000300		/* newlines are line terminators */
#define REG_PEND	000400		/* ugh -- backward-compatibility hack */
#define REG_EXPECT	001000		/* report details on partial/limited matches */
#define REG_BOSONLY 002000		/* temporary kludge for BOS-only matches */
#define REG_DUMP	004000		/* none of your business :-) */
#define REG_FAKE	010000		/* none of your business :-) */
#define REG_PROGRESS	020000	/* none of your business :-) */

/*
 * regex execution flags
 */
#define REG_NOTBOL	0001		/* BOS is not BOL */
#define REG_NOTEOL	0002		/* EOS is not EOL */
#define REG_STARTEND	0004	/* backward compatibility kludge */
#define REG_FTRACE	0010		/* none of your business */
#define REG_MTRACE	0020		/* none of your business */
#define REG_SMALL	0040		/* none of your business */

/*
 * error reporting
 * Be careful if modifying the list of error codes -- the table used by
 * regerror() is generated automatically from this file!
 */
#define REG_OKAY	 0			/* no errors detected */
#define REG_NOMATCH  1			/* failed to match */
#define REG_BADPAT	 2			/* invalid regexp */
#define REG_ECOLLATE	 3		/* invalid collating element */
#define REG_ECTYPE	 4			/* invalid character class */
#define REG_EESCAPE  5			/* invalid escape \ sequence */
#define REG_ESUBREG  6			/* invalid backreference number */
#define REG_EBRACK	 7			/* brackets [] not balanced */
#define REG_EPAREN	 8			/* parentheses () not balanced */
#define REG_EBRACE	 9			/* braces {} not balanced */
#define REG_BADBR	10			/* invalid repetition count(s) */
#define REG_ERANGE	11			/* invalid character range */
#define REG_ESPACE	12			/* out of memory */
#define REG_BADRPT	13			/* quantifier operand invalid */
#define REG_ASSERT	15			/* "can't happen" -- you found a bug */
#define REG_INVARG	16			/* invalid argument to regex function */
#define REG_MIXED	17			/* character widths of regex and string differ */
#define REG_BADOPT	18			/* invalid embedded option */
#define REG_ETOOBIG 19			/* regular expression is too complex */
#define REG_ECOLORS 20			/* too many colors */
#define REG_CANCEL	21			/* operation cancelled */
/* two specials for debugging and testing */
#define REG_ATOI	101			/* convert error-code name to number */
#define REG_ITOA	102			/* convert error-code number to name */
/* non-error result codes for pg_regprefix */
#define REG_PREFIX	(-1)		/* identified a common prefix */
#define REG_EXACT	(-2)		/* identified an exact match */

/*
 * the prototypes for exported functions
 */
extern int	pg_regcomp(regex_t *, const pg_wchar *, size_t, int, Oid);
extern int	pg_regexec(regex_t *, const pg_wchar *, size_t, size_t, rm_detail_t *, size_t, regmatch_t[], int);
extern int	pg_regprefix(regex_t *, pg_wchar **, size_t *);
extern void pg_regfree(regex_t *);
extern size_t pg_regerror(int, const regex_t *, char *, size_t);
extern void pg_set_regex_collation(Oid collation);

#endif   /* _REGEX_H_ */


Title: 使用 PS3 Media Server 构建 DLNA 家庭媒体网络
Date: 2012-08-17 17:38
Author: lovenemesis
Category: Featured
Tags: dlna
Slug: howto-setup-airplay-like-dlna-using-ps3-media-server

羡慕 [Win7 中的 Play
To](http://windows.microsoft.com/en-us/windows7/products/features/play-to)？
眼馋 [OS X 的 AirPlay](http://www.apple.com/itunes/airplay/)？ 您的
Linux 工作站也可以做到！

一年前本站介绍了 [DLNA 技术在 Linux
平台上的一些应用](http://linuxtoy.org/archives/linux-dlna.html)，这次将通过实例的方式说明如何使用
[ps3mediaserver](http://www.ps3mediaserver.org/) 架设 DLNA
服务，并允许家庭网络中各种设备浏览照片、音乐和视频。

**[PS3 Media Server](http://www.ps3mediaserver.org/) 介绍**

PS3 Media Server 是一款兼容 DLNA 协议的 UPnP 媒体服务器，使用 Java
实现跨平台图形界面和服务器进程，调用本地化的
[MEncoder](http://www.mplayerhq.hu/design7/news.html)、[FFmpeg](http://ffmpeg.org/)、[tsMuxeR](http://www.videohelp.com/tools/tsMuxeR)
实现媒体转换和重封装操作。

最初目标是为 PS3 提供媒体服务支持，现在已经成为全范围支持的 DLNA
媒体服务器，内置**适用于 XBox 360、Nokia N900、Android
手机、三星/索尼/飞利浦旗下电视以及各类进口/国产机顶盒的预置文件**，同时对前文中所介绍过的
XBMC 也有良好支持。

**PS3 Media Server
最强大的地方在于可以调用系统平台原生的转码和封装工具，将针对播放设备的特征在必要时进行格式实时转换，特别适合于影音文件类型复杂的用户。**

[![](http://linuxtoy.org/img/2012/08/pms-main.png "pms-main")](http://linuxtoy.org/img/2012/08/pms-main.png)

上图为同时连结了 XBMC、Sony 电视、PS3 和 Android 手机的 PS3 Media Server
。在 [1.6.0
版本](http://www.ps3mediaserver.org/forum/viewtopic.php?f=8&t=14861)中收录由在下**完全重做的简体中文本地化**，希望能进一步降低上手难度。

**[PS3 Media Server](http://www.ps3mediaserver.org/) 安装及配置**

这里以在 [Fedora 17 64
位系统](https://fedoraproject.org/zh_CN/get-fedora)为例。

在[配置好 RPMfusion
仓库](http://rpmfusion.org/)后，需要安装一些必要的软件包，可以在终端输入以下命令或者在添加/删除中搜索对应软件包：

`pkcon install java-1.7.0-openjdk ffmpeg mencoder`

当然后两者也完全可以自行从各自官网下载并编译。

在运行之前，根据情况需要打开 mDNS 防火墙的端口，Fedora
用户可以[参考该文中](http://linuxtoy.org/archives/howto-remote-control-linux-desktop-vlc-player-from-android-mobile.html)的“设置防火墙策略”部分。

PS3 Media Server 提供通用版本的预编译压缩包（内置 tsMuxer）和适用于 Deb
包管理系统的软件包，这里以通用版本为例。

双击解压后的目录中的 PMS.sh
文件，即可运行。第一次使用，可以到第三个标签页 General 那里设置下语言：

[![](http://linuxtoy.org/img/2012/08/pms-general.png "pms-general")](http://linuxtoy.org/img/2012/08/pms-general.png)

重启后生效。

默认情况下 PS3 Media Server 会将整个文件系统共享出来(当然依然遵循 Linux
文件权限)，这显然不是想要的。于是需要在“浏览/共享设定”页面中**将包含有视频、音乐和照片的目录**添加到共享列表中，如下图所示：

[![](http://linuxtoy.org/img/2012/08/pms-share.png "pms-share")](http://linuxtoy.org/img/2012/08/pms-share.png)

如果有需要调整编码器的设置，可以在下图的“转码设定”标签页中进行，不过默认的设置已经足够了：

[![](http://linuxtoy.org/img/2012/08/pms-transcode.png "pms-transcode")](http://linuxtoy.org/img/2012/08/pms-transcode.png)

这个页面中左侧列表中按类别区分了很多编码引擎，可以用下方的**上下箭头按钮调整使用顺序**，越靠上面的引擎越优先使用。如果想/不想使用某个引擎的话，可以用点击下方那个插头样的按钮进行切换。

所有配置完成之后记得点击最上方的“**重新启动服务器**”。

服务器端的配置就这些了，下面就来看看处于**同一个局域网内的各种播放设备**该怎么配置吧。

**其他操作系统上 [XBMC](http://xbmc.org/download/) 配置**

跨平台的 XBMC 是可谓是应用最为广泛的 HTPC 系统了，当下代号为 Eden 的
XBMC 11 默认就启动的 DLNA 客户端模式。

[![](http://linuxtoy.org/img/2012/08/xbmc-dlna.png "xbmc-dlna")](http://linuxtoy.org/img/2012/08/xbmc-dlna.png)

如上图，在添加文件中选择 UPnP Devices 即可看到网络中的 PS3 Media
Server。分别在照片、音乐和视频中配置添加即可。

**PS3 配置**

PS3 的设置很简单：

1.  确保网络设置中：打开了 UPnP 支持；允许连接媒体服务器。
2.  在 XMB
    跨界菜单的视频、音乐或者照片的任意一个分类下选择搜索媒体服务器，此时应该很快就能看到
    PS3 Media Server 的图标。
3.  点击进入即可执行回放或者其他操作。

对于 PS3 来说，会在分享目录下看到一些以 `#` 号包围的特殊目录，这些是 PS3
Media Server 虚拟出来的特殊目录，可以通过选定的方式直接实时调整 DLNA
服务器的一些设置，无需起身操作电脑。

更多详情可以参考[官方手册](http://manuals.playstation.net/document/en/ps3/current/settings/connectdlna.html)。

**Sony Bravia 电视配置**

Sony 从 2011 年开始上市的电视已经标配
DLNA，使用起来也很方便。在保证正常连接网络的情况下，按菜单键打开 XMB
跨界菜单，在视频、音乐和照片中就可以看到 PS3 Media Sever 的图标了。

**[Android 手机客户端
UPnPlay](https://play.google.com/store/apps/details?id=cx.hoohol.silanoid)
配置**

Android 平台上支持 DLNA 的程序非常多，这里以 UPnPlay
这款简单小巧的控制端/播放端为例。在安装 UPnPlay
启动后的首个屏幕上**点击左下角的地球样图标即可看到 PS3 Media Server**

[![](http://linuxtoy.org/img/2012/08/screenshot_2012-08-17_1318.png "screenshot_2012-08-17_1318")](http://linuxtoy.org/img/2012/08/screenshot_2012-08-17_1318.png)

之后通过 UPnPlay
就可以直接浏览共享目录下的文件，点击即可进行播放。UPnPlay
的视频播放是通过调用系统第三方播放器实现的，所以要保证手机上至少安装有一个视频播放器哦。

注意默认情况下点击文件右侧的加号是添加到播放列表，点击文件名是用当前文件替代现有播放列表，所以它会有“是否删除播放列表”的提示。

UPnPlay 除了可以实现在本地播放以外，还可以实现**控制其他 DLNA
客户端的播放**。比如在 Android 手机上选择文件，但是在另一台电脑或者 PS3
进行回放，在一个房间遥控另一个房间的电视去播放第三个房间电脑中文件不再是奢望（好拗口）！

**性能参考**

对于目标设备支持的格式来说，播放性能仅取决于网络带宽。

对于目标设备不支持的格式来说，需要分情况而说。若是仅仅是不支持所用封装容器，例如
SONY 电视仅支持播放封装在 MP4 容器中的 H264/AVC1
视频，无法直接播放常见使用 H264/AVC1 编码的 720P MKV。此时 PS3 Media
Server
仅需要做**重新封装**的操作，而无需重新编码，画质也是毫无损失的。在笔者的本本上**重新封装几乎是瞬时完成，不到
5 秒钟在客户端影片就可开始播放**。

若是使用的视频编码格式不兼容，例如在尝试在不具备 VP8
解码功能的设备上进行 WebM 格式的格式，PS3 Media Server 则会调用
**menconder** 进行实时转码，此时速度会比较慢，而且存在画质损失。

当然，纯音频文件的实时转码则是很快的，例如在 PS3 上播放 Ogg 音轨时。

**总结**

从中可以看出使用 PS3 Media Server 搭建可供各类设备访问的 DLNA
数字家庭网络是一件十分简单的事情，它独特的实时转码重封装功能可以允许某些设备播放缺乏原生支持的文件，比如
WebM、Ogg Vorbis 和 MKV 。通过调整 `PMS.conf` 也可以实现无 GUI
的启动模式，可以参考[论坛中的分享](http://www.ps3mediaserver.org/forum/viewtopic.php?f=3&t=902)。

相比 AirPlay 的特定设备需求，兼容 DLNA
的设备非常多，覆盖电视、手机、蓝光机、机顶盒、NAS
在内的各类产品。如果您的多媒体设备是 2011
年左右购入的外资品牌产品(国产机顶盒也有良好支持)，那么很大可能性已经支持
DLNA；也可以使用[DLNA
官方设备查找程序及智能手机程序](http://www.dlna.org/consumer-home/look-for-dlna)进行查看。


/*
Copyright The Kubernetes Authors.

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 v1alpha1

// This file contains a collection of methods that can be used from go-restful to
// generate Swagger API documentation for its models. Please read this PR for more
// information on the implementation: https://github.com/emicklei/go-restful/pull/215
//
// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if
// they are on one line! For multiple line or blocks that you want to ignore use ---.
// Any context after a --- is ignored.
//
// Those methods can be generated by using hack/update-generated-swagger-docs.sh

// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT.
var map_PodPreset = map[string]string{
	"": "PodPreset is a policy resource that defines additional runtime requirements for a Pod.",
}

func (PodPreset) SwaggerDoc() map[string]string {
	return map_PodPreset
}

var map_PodPresetList = map[string]string{
	"":         "PodPresetList is a list of PodPreset objects.",
	"metadata": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata",
	"items":    "Items is a list of schema objects.",
}

func (PodPresetList) SwaggerDoc() map[string]string {
	return map_PodPresetList
}

var map_PodPresetSpec = map[string]string{
	"":             "PodPresetSpec is a description of a pod preset.",
	"selector":     "Selector is a label query over a set of resources, in this case pods. Required.",
	"env":          "Env defines the collection of EnvVar to inject into containers.",
	"envFrom":      "EnvFrom defines the collection of EnvFromSource to inject into containers.",
	"volumes":      "Volumes defines the collection of Volume to inject into the pod.",
	"volumeMounts": "VolumeMounts defines the collection of VolumeMount to inject into containers.",
}

func (PodPresetSpec) SwaggerDoc() map[string]string {
	return map_PodPresetSpec
}

// AUTO-GENERATED FUNCTIONS END HERE


## vt hunting notification list

List notifications

### Synopsis

List malware hunting notifications.

This command list the malware hunting notifications associated to the currently
configured API key.

```
vt hunting notification list [flags]
```

### Options

```
  -c, --cursor string      cursor for continuing where the previous request left
  -x, --exclude strings    exclude fields matching the provided pattern
  -f, --filter string      filter
  -h, --help               help for list
  -I, --identifiers-only   print identifiers only
  -i, --include strings    include fields matching the provided pattern (default [**])
  -n, --limit int          maximum number of results (default 10)
```

### Options inherited from parent commands

```
  -k, --apikey string   api key
  -v, --verbose         verbose output
```

### SEE ALSO

* [vt hunting notification](vt_hunting_notification.md)	 - Manage malware hunting notifications
* [vt hunting notification list delete](vt_hunting_notification_list_delete.md)	 - Delete hunting notifications


/****************************************************************************
**
** This file is part of the LibreCAD project, a 2D CAD program
**
** Copyright (C) 2010 R. van Twisk (librecad@rvt.dds.nl)
** Copyright (C) 2001-2003 RibbonSoft. All rights reserved.
**
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file gpl-2.0.txt included in the
** packaging of this file.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
** This copyright notice MUST APPEAR in all copies of the script!
**
**********************************************************************/

#ifndef RS_DEBUG_H
#define RS_DEBUG_H

#include <iosfwd>
#ifdef __hpux
#include <sys/_size_t.h>
#endif

class QString;

/** print out a debug header*/
#define DEBUG_HEADER debugHeader(__FILE__, __func__, __LINE__);
void debugHeader(char const* file, char const* func, int line);
#define RS_DEBUG RS_Debug::instance()
#define RS_DEBUG_VERBOSE DEBUG_HEADER \
	RS_Debug::instance()

/**
 * Debugging facilities.
 *
 * @author Andrew Mustun
 */
class RS_Debug {

public:
    /**
     * Enum for debug levels. Only messages of the current
     * or a higher level are printed.
     *

     *
D_NOTHING:  nothing
     *
D_CRITICAL: critical messages
     *
D_ERROR:    errors
     *
D_WARNING:  warnings
     *
D_NOTICE:   notes
     *
D_INFORMATIONAL: infos
     *
D_DEBUGGING: very verbose
     *

     */
    enum RS_DebugLevel { D_NOTHING,
                         D_CRITICAL,
                         D_ERROR,
                         D_WARNING,
                         D_NOTICE,
                         D_INFORMATIONAL,
                         D_DEBUGGING };

private:
    RS_Debug();
	RS_Debug(const RS_Debug&)=delete;
	RS_Debug& operator = (const RS_Debug&)=delete;
	RS_Debug(RS_Debug&&)=delete;
	RS_Debug& operator = (RS_Debug&&)=delete;

public:
    static RS_Debug* instance();

    static void deleteInstance();
    void setLevel(RS_DebugLevel level);
    RS_DebugLevel getLevel();
    void print(RS_DebugLevel level, const char* format ...);
    void print(const char* format ...);
    void printUnicode(const QString& text);
    void timestamp();
    void setStream(FILE* s) {
        stream = s;
    }

private:
    static RS_Debug* uniqueInstance;

    RS_DebugLevel debugLevel;
    FILE* stream;
};

#endif
// EOF


/********************************************************************************
 * Copyright (C) 2018 Red Hat, Inc. and others.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the Eclipse
 * Public License v. 2.0 are satisfied: GNU General Public License, version 2
 * with the GNU Classpath Exception which is available at
 * https://www.gnu.org/software/classpath/license.html.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
 ********************************************************************************/

import { interfaces } from 'inversify';
import { RPCProtocol } from '../../common/rpc-protocol';
import { OpenDialogOptionsMain, SaveDialogOptionsMain, DialogsMain, UploadDialogOptionsMain } from '../../common/plugin-api-rpc';
import { DirNode, OpenFileDialogProps, SaveFileDialogProps, OpenFileDialogFactory, SaveFileDialogFactory, SaveFileDialog } from '@theia/filesystem/lib/browser';
import { WorkspaceService } from '@theia/workspace/lib/browser';
import { UriSelection } from '@theia/core/lib/common/selection';
import URI from '@theia/core/lib/common/uri';
import { FileUploadService } from '@theia/filesystem/lib/browser/file-upload-service';
import { FileService } from '@theia/filesystem/lib/browser/file-service';
import { FileStat } from '@theia/filesystem/lib/common/files';
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';

export class DialogsMainImpl implements DialogsMain {

    private workspaceService: WorkspaceService;
    private fileService: FileService;
    private environments: EnvVariablesServer;

    private openFileDialogFactory: OpenFileDialogFactory;
    private saveFileDialogFactory: SaveFileDialogFactory;
    private uploadService: FileUploadService;

    constructor(rpc: RPCProtocol, container: interfaces.Container) {
        this.workspaceService = container.get(WorkspaceService);
        this.fileService = container.get(FileService);
        this.environments = container.get(EnvVariablesServer);

        this.openFileDialogFactory = container.get(OpenFileDialogFactory);
        this.saveFileDialogFactory = container.get(SaveFileDialogFactory);
        this.uploadService = container.get(FileUploadService);
    }

    protected async getRootUri(defaultUri: string | undefined): Promise<FileStat | undefined> {
        let rootStat: FileStat | undefined;

        // Try to use default URI as root
        if (defaultUri) {
            try {
                rootStat = await this.fileService.resolve(new URI(defaultUri));
            } catch {
                rootStat = undefined;
            }
        }

        // Try to use as root the parent folder of existing file URI/non existing URI
        if (rootStat && !rootStat.isDirectory || !rootStat) {
            try {
                rootStat = await this.fileService.resolve(new URI(defaultUri).parent);
            } catch {
                rootStat = undefined;
            }
        }

        // Try to use workspace service root if there is no preconfigured URI
        if (!rootStat) {
            rootStat = (await this.workspaceService.roots)[0];
        }

        // Try to use current user home if root folder is still not taken
        if (!rootStat) {
            const homeDirUri = await this.environments.getHomeDirUri();
            try {
                rootStat = await this.fileService.resolve(new URI(homeDirUri));
            } catch { }
        }

        return rootStat;
    }

    async $showOpenDialog(options: OpenDialogOptionsMain): Promise<string[] | undefined> {
        const rootStat = await this.getRootUri(options.defaultUri ? options.defaultUri : undefined);

        // Fail if root not fount
        if (!rootStat) {
            throw new Error('Unable to find the rootStat');
        }

        // Take the info for root node
        const rootNode = DirNode.createRoot(rootStat);

        try {
            // Determine proper title for the dialog
            const canSelectFiles = typeof options.canSelectFiles === 'boolean' ? options.canSelectFiles : true;
            const canSelectFolders = typeof options.canSelectFolders === 'boolean' ? options.canSelectFolders : true;

            let title;
            if (canSelectFiles && canSelectFolders) {
                title = 'Open';
            } else {
                if (canSelectFiles) {
                    title = 'Open File';
                } else {
                    title = 'Open Folder';
                }

                if (options.canSelectMany) {
                    title += '(s)';
                }
            }

            // Create open file dialog props
            const dialogProps = {
                title: title,
                openLabel: options.openLabel,
                canSelectFiles: options.canSelectFiles,
                canSelectFolders: options.canSelectFolders,
                canSelectMany: options.canSelectMany,
                filters: options.filters
            } as OpenFileDialogProps;

            // Show open file dialog
            const dialog = this.openFileDialogFactory(dialogProps);
            dialog.model.navigateTo(rootNode);
            const result = await dialog.open();

            // Return the result
            return UriSelection.getUris(result).map(uri => uri.path.toString());
        } catch (error) {
            console.error(error);
        }

        return undefined;
    }

    async $showSaveDialog(options: SaveDialogOptionsMain): Promise<string | undefined> {
        const rootStat = await this.getRootUri(options.defaultUri ? options.defaultUri : undefined);

        // Fail if root not found
        if (!rootStat) {
            throw new Error('Unable to find the rootStat');
        }

        // Take the info for root node
        const rootNode = DirNode.createRoot(rootStat);

        // File name field should be empty unless the URI is a file
        let fileNameValue = '';
        if (options.defaultUri) {
            let defaultURIStat: FileStat | undefined;
            try {
                defaultURIStat = await this.fileService.resolve(new URI(options.defaultUri));
            } catch { }
            if (defaultURIStat && !defaultURIStat.isDirectory || !defaultURIStat) {
                fileNameValue = new URI(options.defaultUri).path.base;
            }
        }

        try {
            // Create save file dialog props
            const dialogProps = {
                title: 'Save',
                saveLabel: options.saveLabel,
                filters: options.filters,
                inputValue: fileNameValue
            } as SaveFileDialogProps;

            // Show save file dialog
            const dialog: SaveFileDialog = this.saveFileDialogFactory(dialogProps);
            dialog.model.navigateTo(rootNode);
            const result = await dialog.open();

            // Return the result
            if (result) {
                return result.path.toString();
            }

            return undefined;
        } catch (error) {
            console.error(error);
        }

        return undefined;
    }

    async $showUploadDialog(options: UploadDialogOptionsMain): Promise<string[] | undefined> {
        const rootStat = await this.getRootUri(options.defaultUri);

        // Fail if root not fount
        if (!rootStat) {
            throw new Error('Failed to resolve base directory where files should be uploaded');
        }

        const uploadResult = await this.uploadService.upload(rootStat.resource.toString());

        if (uploadResult) {
            return uploadResult.uploaded;
        }

        return undefined;
    }

}


<?php

use App\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class UpdateProfilePhotoTest extends TestCase
{
    use DatabaseMigrations;

    public function test_profile_photo_can_be_updated()
    {
        $file = new UploadedFile(
            public_path('img/color-logo.png'), 'color-logo.png', 'image/png', null, null, true
        );

        Storage::shouldReceive('disk')
                        ->once()
                        ->with('public')
                        ->andReturn($disk = Mockery::mock('StdClass'));

        $disk->shouldReceive('put');
        $disk->shouldReceive('url')->once()->andReturn('/profile/photo');

        $this->actingAs(factory(User::class)->create())
                ->json('POST', '/settings/photo', [
                    'photo' => $file,
                ]);

        $this->seeStatusCode(200);

        $this->seeInDatabase('users', [
            'photo_url' => '/profile/photo',
        ]);
    }
}


# Understanding Serverless Architecture Advantages and Limitations
[Reference](https://dzone.com/linkshttps://dzone.com/articles/understanding-serverless-architecture-advantages-a)

- Serverless architecture: your backend logic will run on some third party vendor's server infrastructure which you don't need to worry about.
- `BaaS`: Back-end logic as a service.
- `FasS`: Function-as-a-Service, like AWS Lambda and MS Azure Functions. With FaaS, app devs can implement their own backend logic and run them within the serverless framework. Running, scalability, reliability, security will be taken over by this framework.
- Things to think about:
  - Vendor locking.
  - Higher latency for initial request.
  - If server instances come and go, maintaining state of an app is hard.
  - Not suitable for long-running business processes since these function instances will get destroyed after a fix time duration.
  - Max transactions per second.

# The Benefits of a Serverless API Backend
[Reference](https://nordicapis.com/the-benefits-of-a-serverless-api-backend/)

- This is an event-driven setup without permanent infrastructure.
- Servers are auto-created on a per-need basis to the demands of your app.
- So less time on operations:
  - No more over capacity issues.
  - Servers are autoscaling.
  - You don't pay for idle time.
  - Consistent reliability and availability.
  - No load balancing, no security patches.
- Traditional Web Requests:
  - Apache/NGINX listen for events.
  - Convert this to a web server gateway.
  - Sent to application.
  - Web server sends response back.
  - Back to listening.
- Serverless Web Request:
  - Request comes in through an API gateway.
  - API request is mapped to a dictionary using Velocity Template Language.
  - A server is created.
  - The server then converts the dictionary to a standard Python WSGI and feeds it into the application.
  - The application returns it, and it passes through the API Gateway.
  - The server is destroyed.
- Why serverless?
  - Scalability.
  - Cost savings. Lambda charges $0.0000002 per request. Lambda also offers 1M free requests per month.
  - Good for microservices, APIs, IoT, chatbots.
- Designing Event-Driven Serverless Applications
  - Because code is only going to execute in response to events, what can we define as our event sources?
  - Ex: If someone uploads an image, you can use a serverless architecture to have a thumbnail services execute a response in an asynchronous and non-blocking way.
  - Ex: Support notifications like receiving an email, text, or Facebook message could be interpreted as events. Rather than polling for new emails to come in, an action could be executed specifically in response to these.
  - Ex: Database activity could be used as an event trigger. Treat the API as the primary source of truth in your application!

# What I Learned About Building Serverless Apps
[Reference](https://venturebeat.com/2017/04/30/what-i-learned-about-building-serverless-apps/)

- There is a lot of configuration involved with each Lambda function:
  - Uploading the code
  - Configuring the Lambda function
  - Creating the API endpoint
  - IAM role
  - Config HTTP request and HTTP response
  - Staging endpoint
  - Deploying
  - Same with microservice
- Few documentation.
- Find balance with tight cohesion/loose coupling.
  - Non-serverless: applications were assumed to exist within a larger cohesive application with shared memory and a call stack.
  - Few design patterns.
  - Do not expose every function as a Lambda, slow since every function invocation will be an out-of-process call.
- Workflow.
  - There is no "local" development environment.
  - Each process scope of each Lambda function is isolated, yet the functions exist within the larger context of a larger parent application.
  - Separate directory for the shared code outside the directories containing the code for each Lambda function.
  - Bash script to copy shared code from the parent directory into each of the Lambda function directories.
  - Script also uses the AWS CLI to update the Lambda functions in AWS.
- Automate serverless infrastructure with CloudFormation.
  - This creates the full application stack, including the DynamoDB database and all of the API Gateway and Lambda configurations.
  - You need a CloudFormation resource for each Lambda and its corresponding API Gateway endpoint.
  - Security settings; there are some settings that they use.
- Worth it? It streamlines work AFTER development, not BEFORE. The value is building scalable and highly-available applications with minimal maintenance or operational support.

# Use Cases for AWS Lambda
[Reference](https://www.contino.io/insights/5-killer-use-cases-for-aws-lambda)

- S3 hosted static websites.
  - Host the web front-end on S3.
  - Cloudfront caching.
  - Send request to Lambda functions via API Gateway HTTPS endpoints.
  - Fixed cost = the database service.
- Log analysis.
  - Use it to check log files from Cloudtrail or Cloudwatch, then send out notifications via SNS.
- Automated backups.
- Process uploaded S3 objects (making thumbnails).
- Filtering and transforming data on the fly (moving from S3, Redshift, Kinesis, database).
- Limitations:
  - For the runtime, disk space is limited to 512 MB.
  - Request body: 128KB, response payload: 6MB.

# The hidden costs of serverless
[Reference](https://medium.com/@amiram_26122/the-hidden-costs-of-serverless-6ced7844780b)

- Serverless is more than pay-per-trigger.
  - API Gateway, CloudWatch = costs.
- Code maintenance: more lines of code.
- Cold starts.
- An AWS Lambda function with 512 MB of memory costs $0.030024 compared to an On-Demand server with the same stats costing $0.0059. So when your CPU is being fully utilized all the time, running on Serverless may not be cost-efficient for your workload.
- API Gateway = huge chunk of Serverless costs when you connect to a lot of APIs.
- Other vendors: IBM OpenWhisk, Azure Functions, GCP Functions.

# A crash course on Serverless with Node.js
[Reference](https://hackernoon.com/a-crash-course-on-serverless-with-node-js-632b37d58b44)

- Functions as a service: all the services and endpoints you would usually keep in one place are now microservices and services.
- Lambda: Event-based system for running code in the cloud.
- API Gateway: Require an event to be triggered to invoke them. Gateway provides the REST endpoints which trigger the functions.
- Steps:
  - `$ npm install -g serverless`
  - Create an IAM user.s
  - Add permissions and enter IAM keys in the Serverless configuration.
  - Create a new service/template. `aws-node` to set the runtime to Node.js.
  - `serverless.yml` contains all the configuration settings for his service.

``` yaml
# serverless.yml

service: my-service

provider:
  name: aws
  runtime: nodejs6.10

# Lists all the functions in the service. Check out handler.js
functions:
  hello:
    handler: handler.hello
```

- `handler.js`:

``` js
'use strict';

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};
```

- Deploying: `serverless deploy -v`.
- Testing the function through the command line: `$ serverless invoke -f hello -l`.

## Testing without AWS

- `npm init` inside the service directory.
- `npm install serverless-offline --save-dev`
- Add it as a plugin.
- `serverless offline start`.
- Monitoring:
  - `CloudWatch` sucks. `Dashbird` rocks.

## Comments

- Stages are in the `serverless.yml` file.
- Serverless works with all the major cloud providers.

# Building a Serverless REST API with Node.js and MongoDB
[Reference](https://hackernoon.com/building-a-serverless-rest-api-with-node-js-and-mongodb-2e0ed0638f47)

- Tools: `$npm install --save mongoose dotenv`.
- MongoDB Atlas.

``` yaml
# serverless.yml

service: rest-api

provider:
  name: aws
  runtime: nodejs6.10 # set node.js runtime
  memorySize: 128 # set the maximum memory of the Lambdas in Megabytes
  timeout: 10 # the timeout is 10 seconds (default is 6 seconds)
  stage: dev # setting the env stage to dev, this will be visible in the routes
  region: us-east-1

functions: # add 4 functions for CRUD
  create:
    handler: handler.create # point to exported create function in handler.js
    events:
      - http:
          path: notes # path will be domain.name.com/dev/notes
          method: post
          cors: true
  getOne:
    handler: handler.getOne
    events:
      - http:
          path: notes/{id} # path will be domain.name.com/dev/notes/1
          method: get
          cors: true
  getAll:
    handler: handler.getAll # path will be domain.name.com/dev/notes
    events:
     - http:
         path: notes
         method: get
         cors: true
  update:
    handler: handler.update # path will be domain.name.com/dev/notes/1
    events:
     - http:
         path: notes/{id}
         method: put
         cors: true
  delete:
    handler: handler.delete
    events:
     - http:
         path: notes/{id} # path will be domain.name.com/dev/notes/1
         method: delete
         cors: true

plugins:
- serverless-offline # adding the plugin to be able to run the offline emulation
```