package cancel.service;

import cancel.entity.NotifyInfo;
import cancel.entity.Order;
import cancel.entity.User;
import edu.fudan.common.util.Response;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

@RunWith(JUnit4.class)
public class CancelServiceImplTest {

    @InjectMocks
    private CancelServiceImpl cancelServiceImpl;

    @Mock
    private RestTemplate restTemplate;

    private HttpHeaders headers = new HttpHeaders();
    private HttpEntity requestEntity = new HttpEntity(headers);

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testCancelOrder1() {
        //mock getOrderByIdFromOrder()
        Order order = new Order();
        order.setStatus(6);
        Response<Order> response = new Response<>(1, null, order);
        ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id",
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<Response<Order>>() {
                })).thenReturn(re);
        Response result = cancelServiceImpl.cancelOrder("order_id", "login_id", headers);
        Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result);
    }

    @Test
    public void testCancelOrder2() {
        //mock getOrderByIdFromOrder()
        Response<Order> response = new Response<>(0, null, null);
        ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id",
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<Response<Order>>() {
                })).thenReturn(re);
        //mock getOrderByIdFromOrderOther()
        Order order = new Order();
        order.setStatus(6);
        Response<Order> response2 = new Response<>(1, null, order);
        ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id",
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<Response<Order>>() {
                })).thenReturn(re2);
        Response result = cancelServiceImpl.cancelOrder("order_id", "login_id", headers);
        Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result);
    }

    @Test
    public void testSendEmail() {
        NotifyInfo notifyInfo = new NotifyInfo();
        HttpEntity requestEntity2 = new HttpEntity(notifyInfo, headers);
        ResponseEntity<Boolean> re = new ResponseEntity<>(true, HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                "http://ts-notification-service:17853/api/v1/notifyservice/notification/order_cancel_success",
                HttpMethod.POST,
                requestEntity2,
                Boolean.class)).thenReturn(re);
        Boolean result = cancelServiceImpl.sendEmail(notifyInfo, headers);
        Assert.assertTrue(result);
    }

    @Test
    public void testCalculateRefund1() {
        //mock getOrderByIdFromOrder()
        Order order = new Order();
        order.setStatus(6);
        Response<Order> response = new Response<>(1, null, order);
        ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id",
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<Response<Order>>() {
                })).thenReturn(re);
        Response result = cancelServiceImpl.calculateRefund("order_id", headers);
        Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted, Refound error", null), result);
    }

    @Test
    public void testCalculateRefund2() {
        //mock getOrderByIdFromOrder()
        Response<Order> response = new Response<>(0, null, null);
        ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id",
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<Response<Order>>() {
                })).thenReturn(re);
        //mock getOrderByIdFromOrderOther()
        Order order = new Order();
        order.setStatus(6);
        Response<Order> response2 = new Response<>(1, null, order);
        ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id",
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<Response<Order>>() {
                })).thenReturn(re2);
        Response result = cancelServiceImpl.calculateRefund("order_id", headers);
        Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result);
    }

    @Test
    public void testDrawbackMoney() {
        Response response = new Response<>(1, null, null);
        ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                "http://ts-inside-payment-service:18673/api/v1/inside_pay_service/inside_payment/drawback/" + "userId" + "/" + "money",
                HttpMethod.GET,
                requestEntity,
                Response.class)).thenReturn(re);
        Boolean result = cancelServiceImpl.drawbackMoney("money", "userId", headers);
        Assert.assertTrue(result);
    }

    @Test
    public void testGetAccount() {
        Response<User> response = new Response<>();
        ResponseEntity<Response<User>> re = new ResponseEntity<>(response, HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                "http://ts-user-service:12342/api/v1/userservice/users/id/" + "orderId",
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<Response<User>>() {
                })).thenReturn(re);
        Response<User> result = cancelServiceImpl.getAccount("orderId", headers);
        Assert.assertEquals(new Response<User>(null, null, null), result);
    }

}


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun  9 2015 22:53:21).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//

#import "NSObject-Protocol.h"

@protocol NCNotificationCenterMenu <NSObject>
- (void)ncMenuDNDToggle;
- (void)ncMenuMouseUp;
- (void)ncMenuMouseDown;
- (void)ncMenugetInitialState:(void (^)(_Bool))arg1;
@end


/**********************************************************************************************************************
This file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich.
Licensed under the BSD-2 license (see LICENSE file in main directory)
**********************************************************************************************************************/

#pragma once

#include "DerivativesCppadSettings.h"

namespace ct {
namespace core {

#ifdef CPPAD

//! Jacobian using Auto-Diff Codegeneration
/*!
 * Uses Auto-Diff code generation to compute the Jacobian \f$ J(x_s) = \frac{df}{dx} |_{x=x_s} \f$ of
 * a regular vector-valued mathematical function \f$ y = f(x) \f$ .
 *
 * x has IN_DIM dimension and y has OUT_DIM dimension. Thus, they can be
 * scalar functions (IN_DIM = 1, OUT_DIM = 1), fixed or variable size
 * (IN_DIM = -1, OUT_DIM = -1) functions.
 *
 * \note In fact, this class is called Jacobian but computes also zero order derivatives
 *
 * @tparam IN_DIM Input dimensionality of the function (use Eigen::Dynamic (-1) for dynamic size)
 * @tparam OUT_DIM Output dimensionailty of the function (use Eigen::Dynamic (-1) for dynamic size)
 */
template <int IN_DIM, int OUT_DIM>
class DerivativesCppad : public Derivatives<IN_DIM, OUT_DIM, double>  // double on purpose!
{
public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    typedef ADScalar AD_SCALAR;

    typedef Eigen::Matrix<AD_SCALAR, IN_DIM, 1> IN_TYPE_AD;    //!< function input vector type
    typedef Eigen::Matrix<AD_SCALAR, OUT_DIM, 1> OUT_TYPE_AD;  //!< function  output vector type

    typedef Eigen::Matrix<double, IN_DIM, 1> IN_TYPE_D;         //!< function input vector type double
    typedef Eigen::Matrix<double, OUT_DIM, 1> OUT_TYPE_D;       //!< function output vector type
    typedef Eigen::Matrix<double, OUT_DIM, IN_DIM> JAC_TYPE_D;  //!< Jacobian type
    typedef Eigen::Matrix<double, OUT_DIM, IN_DIM, Eigen::RowMajor>
        JAC_TYPE_ROW_MAJOR;  //!< Jocobian type in row-major format
    typedef Eigen::Matrix<double, IN_DIM, IN_DIM> HES_TYPE_D;
    typedef Eigen::Matrix<double, IN_DIM, IN_DIM, Eigen::RowMajor> HES_TYPE_ROW_MAJOR;

    typedef std::function<OUT_TYPE_AD(const IN_TYPE_AD&)> FUN_TYPE_AD;

    typedef Derivatives<IN_DIM, OUT_DIM> DerivativesBase;

    /**
     * @brief      Constructs the derivatives for autodiff without
     *             codegeneration using a FUN_TYPE_AD function
     *
     * @warning    If IN_DIM and/our OUT_DIM are set to dynamic (-1), then the
     *             actual dimensions of x and y have to be passed here.
     *
     * @param      f          The function to be autodiffed
     * @param[in]  inputDim   inputDim input dimension, must be specified if
     *                        template parameter IN_DIM is -1 (dynamic)
     * @param[in]  outputDim  outputDim output dimension, must be specified if
     *                        template parameter IN_DIM is -1 (dynamic)
     */
    DerivativesCppad(FUN_TYPE_AD& f, int inputDim = IN_DIM, int outputDim = OUT_DIM)
        : DerivativesBase(), adStdFun_(f), inputDim_(inputDim), outputDim_(outputDim)
    {
        update(f, inputDim, outputDim);
    }

    //! copy constructor
    DerivativesCppad(const DerivativesCppad& arg)
        : DerivativesBase(arg), adStdFun_(arg.adStdFun_), inputDim_(arg.inputDim_), outputDim_(arg.outputDim_)
    {
        adCppadFun_ = arg.adCppadFun_;
    }

    //! update the Jacobian with a new function
    /*!
     * \warning If IN_DIM and/our OUT_DIM are set to dynamic (-1), then the actual dimensions of
     * x and y have to be passed here.
     *
     * @param f new function to compute Jacobian of
     * @param inputDim input dimension, must be specified if template parameter IN_DIM is -1 (dynamic)
     * @param outputDim output dimension, must be specified if template parameter IN_DIM is -1 (dynamic)
     */
    void update(FUN_TYPE_AD& f, const size_t inputDim = IN_DIM, const size_t outputDim = OUT_DIM)
    {
        adStdFun_ = f;
        outputDim_ = outputDim;
        inputDim_ = inputDim;
        if (outputDim_ > 0 && inputDim_ > 0)
            recordAd();
    }

    //! destructor
    virtual ~DerivativesCppad() {}
    //! deep cloning of Jacobian
    DerivativesCppad* clone() const { return new DerivativesCppad<IN_DIM, OUT_DIM>(*this); }
    virtual OUT_TYPE_D forwardZero(const Eigen::VectorXd& x) { return adCppadFun_.Forward(0, x); }
    virtual JAC_TYPE_D jacobian(const Eigen::VectorXd& x)
    {
        if (outputDim_ <= 0)
            throw std::runtime_error("Outdim dim smaller 0; Define output dim in DerivativesCppad constructor");

        Eigen::VectorXd jac = adCppadFun_.Jacobian(x);

        JAC_TYPE_D out(outputDim_, x.rows());
        out = JAC_TYPE_ROW_MAJOR::Map(jac.data(), outputDim_, x.rows());
        return out;
    }

    virtual void sparseJacobian(const Eigen::VectorXd& x,
        Eigen::VectorXd& jac,
        Eigen::VectorXi& iRow,
        Eigen::VectorXi& jCol)
    {
        if (outputDim_ <= 0)
            throw std::runtime_error("Outdim dim smaller 0; Define output dim in DerivativesCppad constructor");

        jac = adCppadFun_.SparseJacobian(x);
    }

    virtual Eigen::VectorXd sparseJacobianValues(const Eigen::VectorXd& x)
    {
        if (outputDim_ <= 0)
            throw std::runtime_error("Outdim dim smaller 0; Define output dim in DerivativesCppad constructor");

        return adCppadFun_.SparseJacobian(x);
    }

    virtual HES_TYPE_D hessian(const Eigen::VectorXd& x, const Eigen::VectorXd& lambda)
    {
        if (outputDim_ <= 0)
            throw std::runtime_error("Outdim dim smaller 0; Define output dim in DerivativesCppad constructor");

        Eigen::VectorXd hessian = adCppadFun_.Hessian(x, lambda);
        HES_TYPE_D out(x.rows(), x.rows());
        out = HES_TYPE_ROW_MAJOR::Map(hessian.data(), x.rows(), x.rows());
        return out;
    }

    virtual void sparseHessian(const Eigen::VectorXd& x,
        const Eigen::VectorXd& lambda,
        Eigen::VectorXd& hes,
        Eigen::VectorXi& iRow,
        Eigen::VectorXi& jCol)
    {
        if (outputDim_ <= 0)
            throw std::runtime_error("Outdim dim smaller 0; Define output dim in DerivativesCppad constructor");

        hes = adCppadFun_.SparseHessian(x, lambda);
    }

    virtual Eigen::VectorXd sparseHessianValues(const Eigen::VectorXd& x, const Eigen::VectorXd& lambda)
    {
        if (outputDim_ <= 0)
            throw std::runtime_error("Outdim dim smaller 0; Define output dim in DerivativesCppad constructor");

        return adCppadFun_.SparseHessian(x, lambda);
    }

private:
    /**
     * @brief      Records the auto-diff terms
     */
    void recordAd()
    {
        // input vector, needs to be dynamic size
        Eigen::Matrix<AD_SCALAR, Eigen::Dynamic, 1> x(inputDim_);

        // declare x as independent
        CppAD::Independent(x);

        // output vector, needs to be dynamic size
        Eigen::Matrix<AD_SCALAR, Eigen::Dynamic, 1> y(outputDim_);

        y = adStdFun_(x);

        // store operation sequence in f: x -> y and stop recording
        CppAD::ADFun<double> fAd(x, y);

        fAd.optimize();

        std::cout << "AD FUn recorded" << std::endl;

        adCppadFun_ = fAd;
    }

    std::function<OUT_TYPE_AD(const IN_TYPE_AD&)> adStdFun_;

    int inputDim_;   //! function input dimension
    int outputDim_;  //! function output dimension

    CppAD::ADFun<double> adCppadFun_;
};

#endif

} /* namespace core */
} /* namespace ct */


package io.scalechain.blockchain.storage.index

import io.kotlintest.KTestJUnitRunner
import io.kotlintest.matchers.Matchers
import io.kotlintest.specs.FlatSpec
import io.scalechain.blockchain.proto.*
import io.scalechain.blockchain.proto.test.ProtoTestData
import io.scalechain.blockchain.script.hash
import io.scalechain.blockchain.storage.TransactionLocator
import io.scalechain.blockchain.storage.test.TestData
import io.scalechain.test.ShouldSpec
import io.scalechain.util.ListExt
import org.junit.runner.RunWith

/**
 * Created by kangmo on 15/12/2016.
 */
interface TransactionDescriptorIndexTestTrait : ShouldSpec, KeyValueCommonTrait, ProtoTestData {
  var db : KeyValueDatabase

  fun txDesc(height : Long, outputCount:Int) : TransactionDescriptor {
    return TransactionDescriptor(
      transactionLocator = FileRecordLocator(1, RecordLocator(2,3)),
      blockHeight = height,
      outputsSpentBy = ListExt.fill<InPoint?>( outputCount, null)
    )
  }

  fun addTests() {
    "getTransactionDescriptor" should "return null if the descriptor was not put" {
      val index = object : TransactionDescriptorIndex{}

      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe null
    }

    "getTransactionDescriptor" should "return descriptor if the descriptor was put" {
      val index = object : TransactionDescriptorIndex{}

      index.putTransactionDescriptor( db, transaction1().hash(), txDesc(1,1))
      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe txDesc(1,1)

      index.putTransactionDescriptor( db, transaction2().hash(), txDesc(2,2))
      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe txDesc(1,1)
      index.getTransactionDescriptor( db, transaction2().hash()) shouldBe txDesc(2,2)

      index.putTransactionDescriptor( db, transaction3().hash(), txDesc(3,3))
      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe txDesc(1,1)
      index.getTransactionDescriptor( db, transaction2().hash()) shouldBe txDesc(2,2)
      index.getTransactionDescriptor( db, transaction3().hash()) shouldBe txDesc(3,3)
    }

    "getTransactionDescriptor" should "overwrite an existing desciptor" {
      val index = object : TransactionDescriptorIndex{}

      index.putTransactionDescriptor( db, transaction1().hash(), txDesc(1,1))
      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe txDesc(1,1)

      index.putTransactionDescriptor( db, transaction1().hash(), txDesc(2,2))
      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe txDesc(2,2)
    }

    "getTransactionDescriptor" should "return null if the descriptor was deleted" {
      val index = object : TransactionDescriptorIndex{}

      index.putTransactionDescriptor( db, transaction1().hash(), txDesc(1,1))
      index.delTransactionDescriptor( db, transaction1().hash())
      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe null

      index.putTransactionDescriptor( db, transaction1().hash(), txDesc(1,1))
      index.putTransactionDescriptor( db, transaction2().hash(), txDesc(2,2))
      index.delTransactionDescriptor( db, transaction1().hash())

      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe null
      index.getTransactionDescriptor( db, transaction2().hash()) shouldBe txDesc(2,2)

      index.putTransactionDescriptor( db, transaction1().hash(), txDesc(1,1))
      index.putTransactionDescriptor( db, transaction2().hash(), txDesc(2,2))
      index.putTransactionDescriptor( db, transaction3().hash(), txDesc(3,3))
      index.delTransactionDescriptor( db, transaction2().hash())

      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe txDesc(1,1)
      index.getTransactionDescriptor( db, transaction2().hash()) shouldBe null
      index.getTransactionDescriptor( db, transaction3().hash()) shouldBe txDesc(3,3)

      index.delTransactionDescriptor( db, transaction1().hash())
      index.getTransactionDescriptor( db, transaction1().hash()) shouldBe null

      index.delTransactionDescriptor( db, transaction3().hash())
      index.getTransactionDescriptor( db, transaction3().hash()) shouldBe null
    }
  }
}


/*
 * A 32-bit implementation of the XTEA algorithm
 * Copyright (c) 2012 Samuel Pitoiset
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg 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.
 *
 * FFmpeg 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 FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#ifndef AVUTIL_XTEA_H
#define AVUTIL_XTEA_H

#include <stdint.h>

/**
 * @file
 * @brief Public header for libavutil XTEA algorithm
 * @defgroup lavu_xtea XTEA
 * @ingroup lavu_crypto
 * @{
 */

typedef struct AVXTEA {
    uint32_t key[16];
} AVXTEA;

/**
 * Initialize an AVXTEA context.
 *
 * @param ctx an AVXTEA context
 * @param key a key of 16 bytes used for encryption/decryption
 */
void av_xtea_init(struct AVXTEA *ctx, const uint8_t key[16]);

/**
 * Encrypt or decrypt a buffer using a previously initialized context.
 *
 * @param ctx an AVXTEA context
 * @param dst destination array, can be equal to src
 * @param src source array, can be equal to dst
 * @param count number of 8 byte blocks
 * @param iv initialization vector for CBC mode, if NULL then ECB will be used
 * @param decrypt 0 for encryption, 1 for decryption
 */
void av_xtea_crypt(struct AVXTEA *ctx, uint8_t *dst, const uint8_t *src,
                   int count, uint8_t *iv, int decrypt);

/**
 * @}
 */

#endif /* AVUTIL_XTEA_H */


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="monogamesamplesprimitivesandroid.monogamesamplesprimitivesandroid">
	<application android:label="MonoGame.Samples.Primitives.Android" android:debuggable="true">
	</application>
	<uses-sdk />
</manifest>


# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# pylint: disable=invalid-name
"""VGG16 model for Keras.

# Reference

- [Very Deep Convolutional Networks for Large-Scale Image
Recognition](https://arxiv.org/abs/1409.1556)

"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.contrib.keras.python.keras import backend as K
from tensorflow.contrib.keras.python.keras.applications.imagenet_utils import _obtain_input_shape
from tensorflow.contrib.keras.python.keras.applications.imagenet_utils import decode_predictions  # pylint: disable=unused-import
from tensorflow.contrib.keras.python.keras.applications.imagenet_utils import preprocess_input  # pylint: disable=unused-import
from tensorflow.contrib.keras.python.keras.engine.topology import get_source_inputs
from tensorflow.contrib.keras.python.keras.layers import Conv2D
from tensorflow.contrib.keras.python.keras.layers import Dense
from tensorflow.contrib.keras.python.keras.layers import Flatten
from tensorflow.contrib.keras.python.keras.layers import GlobalAveragePooling2D
from tensorflow.contrib.keras.python.keras.layers import GlobalMaxPooling2D
from tensorflow.contrib.keras.python.keras.layers import Input
from tensorflow.contrib.keras.python.keras.layers import MaxPooling2D
from tensorflow.contrib.keras.python.keras.models import Model
from tensorflow.contrib.keras.python.keras.utils import layer_utils
from tensorflow.contrib.keras.python.keras.utils.data_utils import get_file

WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels.h5'
WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'

def VGG16(include_top=True,
          weights='imagenet',
          input_tensor=None,
          input_shape=None,
          pooling=None,
          classes=1000):
  """Instantiates the VGG16 architecture.

  Optionally loads weights pre-trained
  on ImageNet. Note that when using TensorFlow,
  for best performance you should set
  `image_data_format="channels_last"` in your Keras config
  at ~/.keras/keras.json.

  The model and the weights are compatible with both
  TensorFlow and Theano. The data format
  convention used by the model is the one
  specified in your Keras config file.

  Arguments:
      include_top: whether to include the 3 fully-connected
          layers at the top of the network.
      weights: one of `None` (random initialization)
          or "imagenet" (pre-training on ImageNet).
      input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
          to use as image input for the model.
      input_shape: optional shape tuple, only to be specified
          if `include_top` is False (otherwise the input shape
          has to be `(224, 224, 3)` (with `channels_last` data format)
          or `(3, 224, 224)` (with `channels_first` data format).
          It should have exactly 3 inputs channels,
          and width and height should be no smaller than 48.
          E.g. `(200, 200, 3)` would be one valid value.
      pooling: Optional pooling mode for feature extraction
          when `include_top` is `False`.
          - `None` means that the output of the model will be
              the 4D tensor output of the
              last convolutional layer.
          - `avg` means that global average pooling
              will be applied to the output of the
              last convolutional layer, and thus
              the output of the model will be a 2D tensor.
          - `max` means that global max pooling will
              be applied.
      classes: optional number of classes to classify images
          into, only to be specified if `include_top` is True, and
          if no `weights` argument is specified.

  Returns:
      A Keras model instance.

  Raises:
      ValueError: in case of invalid argument for `weights`,
          or invalid input shape.
  """
  if weights not in {'imagenet', None}:
    raise ValueError('The `weights` argument should be either '
                     '`None` (random initialization) or `imagenet` '
                     '(pre-training on ImageNet).')

  if weights == 'imagenet' and include_top and classes != 1000:
    raise ValueError('If using `weights` as imagenet with `include_top`'
                     ' as true, `classes` should be 1000')
  # Determine proper input shape
  input_shape = _obtain_input_shape(
      input_shape,
      default_size=224,
      min_size=48,
      data_format=K.image_data_format(),
      include_top=include_top)

  if input_tensor is None:
    img_input = Input(shape=input_shape)
  else:
    img_input = Input(tensor=input_tensor, shape=input_shape)

  # Block 1
  x = Conv2D(
      64, (3, 3), activation='relu', padding='same',
      name='block1_conv1')(img_input)
  x = Conv2D(
      64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)
  x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)

  # Block 2
  x = Conv2D(
      128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)
  x = Conv2D(
      128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)
  x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)

  # Block 3
  x = Conv2D(
      256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)
  x = Conv2D(
      256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)
  x = Conv2D(
      256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)
  x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)

  # Block 4
  x = Conv2D(
      512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)
  x = Conv2D(
      512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)
  x = Conv2D(
      512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)
  x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)

  # Block 5
  x = Conv2D(
      512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)
  x = Conv2D(
      512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)
  x = Conv2D(
      512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)
  x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)

  if include_top:
    # Classification block
    x = Flatten(name='flatten')(x)
    x = Dense(4096, activation='relu', name='fc1')(x)
    x = Dense(4096, activation='relu', name='fc2')(x)
    x = Dense(classes, activation='softmax', name='predictions')(x)
  else:
    if pooling == 'avg':
      x = GlobalAveragePooling2D()(x)
    elif pooling == 'max':
      x = GlobalMaxPooling2D()(x)

  # Ensure that the model takes into account
  # any potential predecessors of `input_tensor`.
  if input_tensor is not None:
    inputs = get_source_inputs(input_tensor)
  else:
    inputs = img_input
  # Create model.
  model = Model(inputs, x, name='vgg16')

  # load weights
  if weights == 'imagenet':
    if include_top:
      weights_path = get_file(
          'vgg16_weights_tf_dim_ordering_tf_kernels.h5',
          WEIGHTS_PATH,
          cache_subdir='models')
    else:
      weights_path = get_file(
          'vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
          WEIGHTS_PATH_NO_TOP,
          cache_subdir='models')
    model.load_weights(weights_path)
    if K.backend() == 'theano':
      layer_utils.convert_all_kernels_in_model(model)

    if K.image_data_format() == 'channels_first':
      if include_top:
        maxpool = model.get_layer(name='block5_pool')
        shape = maxpool.output_shape[1:]
        dense = model.get_layer(name='fc1')
        layer_utils.convert_dense_weights_data_format(dense, shape,
                                                      'channels_first')
  return model


# Perform regexp replacement on a string or array of strings.
#
# @param target [String, Array[String]]
#      The string or array of strings to operate on.  If an array, the replacement will be
#      performed on each of the elements in the array, and the return value will be an array.
# @param pattern [String, Regexp, Type[Regexp]]
#      The regular expression matching the target string.  If you want it anchored at the start
#      and or end of the string, you must do that with ^ and $ yourself.
# @param replacement [String, Hash[String, String]]
#      Replacement string. Can contain backreferences to what was matched using \\0 (whole match),
#      \\1 (first set of parentheses), and so on.
#      If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.
# @param flags [Optional[Pattern[/^[GEIM]*$/]], Pattern[/^G?$/]]
#      Optional. String of single letter flags for how the regexp is interpreted (E, I, and M cannot be used
#      if pattern is a precompiled regexp):
#        - *E*         Extended regexps
#        - *I*         Ignore case in regexps
#        - *M*         Multiline regexps
#        - *G*         Global replacement; all occurrences of the regexp in each target string will be replaced.  Without this, only the first occurrence will be replaced.
# @param encoding [Enum['N','E','S','U']]
#      Optional. How to handle multibyte characters when compiling the regexp (must not be used when pattern is a
#      precompiled regexp). A single-character string with the following values:
#        - *N*         None
#        - *E*         EUC
#        - *S*         SJIS
#        - *U*         UTF-8
# @return [Array[String], String] The result of the substitution. Result type is the same as for the target parameter.
#
# @example Get the third octet from the node's IP address:
#     $i3 = regsubst($ipaddress,'^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$','\\3')
#
# @example Put angle brackets around each octet in the node's IP address:
#     $x = regsubst($ipaddress, /([0-9]+)/, '<\\1>', 'G')
#
Puppet::Functions.create_function(:regsubst) do
  dispatch :regsubst_string do
    param          'Variant[Array[String],String]',       :target
    param          'String',                              :pattern
    param          'Variant[String,Hash[String,String]]', :replacement
    optional_param 'Optional[Pattern[/^[GEIM]*$/]]',      :flags
    optional_param "Enum['N','E','S','U']",               :encoding
  end

  dispatch :regsubst_regexp do
    param          'Variant[Array[String],String]',       :target
    param          'Variant[Regexp,Type[Regexp]]',        :pattern
    param          'Variant[String,Hash[String,String]]', :replacement
    optional_param 'Pattern[/^G?$/]',                     :flags
  end

  def regsubst_string(target, pattern, replacement, flags = nil, encoding = nil)
    re_flags = 0
    operation = :sub
    if !flags.nil?
      flags.split(//).each do |f|
        case f
        when 'G' then operation = :gsub
        when 'E' then re_flags |= Regexp::EXTENDED
        when 'I' then re_flags |= Regexp::IGNORECASE
        when 'M' then re_flags |= Regexp::MULTILINE
        end
      end
    end
    inner_regsubst(target, Regexp.compile(pattern, re_flags, encoding), replacement, operation)
  end

  def regsubst_regexp(target, pattern, replacement, flags = nil)
    pattern = (pattern.pattern || '') if pattern.is_a?(Puppet::Pops::Types::PRegexpType)
    inner_regsubst(target, pattern, replacement, operation = flags == 'G' ? :gsub : :sub)
  end

  def inner_regsubst(target, re, replacement, op)
    target.respond_to?(op) ? target.send(op, re, replacement) : target.collect { |e| e.send(op, re, replacement) }
  end
  private :inner_regsubst
end


"""
Launchpad OpenId backend
"""

from .open_id import OpenIdAuth

class LaunchpadOpenId(OpenIdAuth):
    name = 'launchpad'
    URL = 'https://login.launchpad.net'
    USERNAME_KEY = 'nickname'


<!-- Copyright (c) 2012-2016 K Team. All Rights Reserved. -->

## Part 5: Defining Type Systems

In this part of the tutorial we will show that defining type systems for
languages is essentially no different from defining semantics.  The major
difference is that programs and fragments of programs now rewrite to their
types, instead of to concrete values.  In terms of K, we will learn how
to use it for a certain particular but important kind of applications.


/*
 * Copyright (c) 2008, 2016, Oracle and/or its affiliates.
 * All rights reserved. Use is subject to license terms.
 *
 * This file is available and licensed under the following license:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  - Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the distribution.
 *  - Neither the name of Oracle Corporation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "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 THE COPYRIGHT
 * OWNER OR CONTRIBUTORS 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.
 */
package ensemble.samples.animation.interpolator;

import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.effect.Lighting;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * A sample that shows various types of interpolation between key frames in a
 * timeline. There are five circles, each animated with a different
 * interpolation method. The Linear interpolator is the default. Use the
 * controls to reduce opacity to zero for some circles to compare with others,
 * or change circle color to distinguish between individual interpolators.
 *
 * @sampleName Interpolator
 * @preview preview.png
 * @docUrl http://docs.oracle.com/javase/8/javafx/visual-effects-tutorial/animations.htm#JFXTE149 JavaFX Transitions & Animation
 * @playground - (name="LINEAR")
 * @playground circle1.opacity (min=0, max=1)
 * @playground circle1.fill
 * @playground - (name="EASE_BOTH")
 * @playground circle2.opacity (min=0, max=1)
 * @playground circle2.fill
 * @playground - (name="EASE_IN")
 * @playground circle3.opacity (min=0, max=1)
 * @playground circle3.fill
 * @playground - (name="EASE_OUT")
 * @playground circle4.opacity (min=0, max=1)
 * @playground circle4.fill
 * @playground - (name="SPLINE")
 * @playground circle5.opacity (min=0, max=1)
 * @playground circle5.fill
 * @see javafx.animation.Interpolator
 * @see javafx.animation.KeyFrame
 * @see javafx.animation.KeyValue
 * @see javafx.animation.Timeline
 * @see javafx.util.Duration
 * @embedded
 *
 * @related /Graphics 2d/Bouncing Balls
 * @related /Graphics 2d/Display Shelf
 * @related /Scenegraph/Events/Key Stroke Motion
 * @related /Graphics 3d/Xylophone
 */
public class InterpolatorApp extends Application {

    private final Timeline timeline = new Timeline();
    private Circle circle1;
    private Circle circle2;
    private Circle circle3;
    private Circle circle4;
    private Circle circle5;

    public Parent createContent() {
        Pane root = new Pane();
        root.setPrefSize(245, 230);
        root.setMinSize(Pane.USE_PREF_SIZE, Pane.USE_PREF_SIZE);
        root.setMaxSize(Pane.USE_PREF_SIZE, Pane.USE_PREF_SIZE);

        // create circles by method createMovingCircle listed below
        // default interpolator
        circle1 = createMovingCircle(Interpolator.LINEAR,
                                     1, 0.7, Color.RED);
        // circle slows down when reached both ends of trajectory
        circle2 = createMovingCircle(Interpolator.EASE_BOTH,
                                     2, 0.45, Color.VIOLET);
        // circle slows down in the beginning of animation
        circle3 = createMovingCircle(Interpolator.EASE_IN,
                                     3, 0.2, Color.BLUE);
        // circle slows down in the end of animation
        circle4 = createMovingCircle(Interpolator.EASE_OUT,
                                     4, 0.35, Color.YELLOW);
        // one can define own behaviour of interpolator by spline method
        circle5 = createMovingCircle(Interpolator.SPLINE(0.5, 0.1, 0.1, 0.5),
                                     5, 0.7, Color.GREEN);

        root.getChildren().addAll(circle1, circle2, circle3, circle4, circle5);
        return root;
    }

    private Circle createMovingCircle(Interpolator interpolator, int which,
                                      double opacity, Color color) {
        // create a transparent circle
        Circle circle = new Circle(45, 45, 40, color);
        // set initial opacity
        circle.setOpacity(opacity);
        circle.setCenterY((which * 35) + 5);
        // add effect
        circle.setEffect(new Lighting());
        // create a timeline for moving the circle
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.setAutoReverse(true);
        // create a keyValue for horizontal translation of circle to
        // the position 155px with given interpolator
        KeyValue keyValue = new KeyValue(circle.translateXProperty(), 155,
                                         interpolator);
        // create a keyFrame with duration 4s
        KeyFrame keyFrame = new KeyFrame(Duration.seconds(4), keyValue);
        // add the keyframe to the timeline
        timeline.getKeyFrames().add(keyFrame);
        return circle;
    }

    public void play() {
        timeline.play();
    }

    @Override
    public void stop() {
        timeline.stop();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setResizable(false);
        primaryStage.setScene(new Scene(createContent()));
        primaryStage.show();
        play();
    }

    /**
     * Java main for when running without JavaFX launcher
     * @param args command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}


//=============================================================================
//  MusE
//  Linux Music Editor
//  $Id: stringparam.cpp,v 1.0.0.0 2010/04/24 01:01:01 terminator356 Exp $
//
//  Copyright (C) 1999-2011 by Werner Schweer and others
//  String parameter module added by Tim.
//
//  This program 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; version 2 of
//  the License, or (at your option) any later version.
//
//  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.
//=============================================================================

#include "stringparam.h"
#include "xml.h"

namespace MusECore {

//---------------------------------------------------------
//   findKey
//---------------------------------------------------------

iStringParamMap StringParamMap::findKey(const char* key)
{
  iStringParamMap icm = find(std::string(key));
  return icm;
}

//---------------------------------------------------------
//   set
//---------------------------------------------------------

void StringParamMap::set(const char* key, const char* value)
{
  iStringParamMap icm = find(std::string(key));
  if(icm == end())
    insert(std::pair<std::string, std::string>(key, value));
  else
    icm->second = std::string(value);
}

//---------------------------------------------------------
//   remove
//---------------------------------------------------------

void StringParamMap::remove(const char* key)
{
  erase(std::string(key));
}

//---------------------------------------------------------
//   read
//---------------------------------------------------------

void StringParamMap::read(Xml& xml, const QString& name)
{
  QString n;
  QString value;

  for (;;)
  {
    Xml::Token token = xml.parse();
    const QString tag = xml.s1();
    switch (token)
    {
      case Xml::Error:
      case Xml::End:
            return;
      case Xml::TagStart:
            xml.unknown(name.toLatin1().constData());
            break;
      case Xml::Attribut:
            if(tag == "name")
              n = xml.s2();
            else
            if(tag == "val")
              value = xml.s2();
            else
              xml.unknown(name.toLatin1().constData());
            break;
      case Xml::TagEnd:
            if(tag == name)
            {
              // Add or modify the item.
              set(n.toLatin1(), value.toLatin1());
              return;
            }
      default:
            break;
    }
  }
}

//---------------------------------------------------------
//   write
//---------------------------------------------------------

void StringParamMap::write(int level, Xml& xml, const char* name) const
{
  if(empty())
    return;

  for(ciStringParamMap r = begin(); r != end(); ++r)
    xml.tag(level, "%s name=\"%s\" val=\"%s\"/", name, r->first.c_str(), r->second.c_str());
}

} // namespace MusECore


var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var cleanCSS = require('gulp-clean-css');
var rename = require('gulp-rename');
var include = require("gulp-include");
var uglify = require('gulp-uglify');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var notify = require("gulp-notify");

gulp.task('sass', function () {
  return gulp.src('./assets/scss/landio.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({ errLogToConsole: false, }))
    .on('error', function(err) {
        notify({
          "sound": "Morse"
        }).write(err);
        this.emit('end');
    })
    .pipe(autoprefixer({
      browsers: [
        "Explorer >= 10",
        "iOS >= 9.3", // Apple iPhone 5
        "Android >= 5"
      ]
    }))
    .pipe(cleanCSS())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./assets/css'))
    .pipe(browserSync.stream());
});

gulp.task('js', function() {
  return gulp.src('./assets/js/landio.js')
    .pipe(sourcemaps.init())
    .pipe(include())
    .on('error', console.log)
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./assets/js/'))
    .pipe(browserSync.stream());
});

gulp.task('serve', ['sass', 'js'], function() {
  browserSync.init({
    port: 3355,
    server: {
      baseDir: "./",
      index: "index.html",
      logSnippet: false
    }
  });

  gulp.watch('./assets/**/*.scss', ['sass']);
  gulp.watch('./assets/js/landio.js', ['js']);
  gulp.watch('./*.html').on('change', reload);
});

gulp.task('default', ['serve']);


#!/usr/bin/env bash
#------------------------------------------------------------------------------
# Bash+ - Modern Bash Programming
#
# Copyright (c) 2013 Ingy döt Net
#------------------------------------------------------------------------------

set -e

#------------------------------------------------------------------------------
# Determine how `bash+` was called, and do the right thing:
#------------------------------------------------------------------------------
if [ "${BASH_SOURCE[0]}" != "$0" ]; then
  # 'bash+' is being sourced:
  [[ "${BASH_SOURCE[0]}" =~ /bin/bash\+$ ]] || {
    echo "Invalid Bash+ path '${BASH_SOURCE[0]}'" 2> /dev/null
    exit 1
  }
  source "${BASH_SOURCE[0]%/bin/*}"/lib/bash+.bash || return $?
  bash+:import "$@"
  return $?
else
  if [ $# -eq 1 -a "$1" == --version ]; then
    echo 'bash+   version 0.0.1'
  else
  cat <<...

Greetings modern Bash programmer. Welcome to Bash+!

Bash+ is framework that makes Bash programming more like Ruby and Perl.

See: https://github.com/bpan-org/bashplus

If you got here trying to use bash+ in a program, you need to source it:

    source bash+

Happy Bash Hacking!

...
  fi
fi


7.2.0 - Real-time Data Mart for AWS

7.2.0 - Real-time Data Mart: Apache Impala, Hue, Apache Kudu, Apache Spark


Buffer overflow in PowerFTP FTP server 2.24, and possibly other versions, allows remote attackers to cause a denial of service and possibly execute arbitrary code via a long USER argument.

20021005 Vulnerabilitie in PowerFTP server

20021012 Coolsoft PowerFTP <= v2.24 Denial of Service (Linux Source)


    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=7,IE=9" />

    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
    <title>OpenStreetMap- default options</title>
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.0/js/dojo/dijit/themes/claro/claro.css">

@model OSMWeb.Models.OsmConfig
@{
    ViewBag.Title = "Create";
}

Create new Feature Service

@Html.ActionLink("< Back to list", "Index")

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    @Html.Partial("_CreateOrEdit", Model)

What

Zoom and pan the map to the area for which you want to retrieve data from OpenStreetMap. More data takes longer to download.

            @Html.LabelFor(model => model.Extent)

            @Html.TextBoxFor(model => model.Extent, new { style = "width: 200px" })
            @Html.ValidationMessageFor(model => model.Extent)

How

        What should the service be named? What data should be symbolized (using the template dropdown below)? Do you want to synchronize with OpenStreetMap?

            @Html.LabelFor(model => model.FeatureDataSet)

            @Html.EditorFor(model => model.FeatureDataSet)
            @Html.ValidationMessageFor(model => model.FeatureDataSet)

            @Html.LabelFor(model => model.MxdTemplate)

            @{
    var mxdList = @ViewBag.mxdList as IEnumerable<SelectListItem>;
            }
            @Html.DropDownListFor(model => model.MxdTemplate, mxdList)

        <input type="checkbox" id="isSynchronized" /> Synchronize with OpenStreetMap?

            @Html.LabelFor(model => model.Username)

            @Html.EditorFor(model => model.Username)
            @Html.ValidationMessageFor(model => model.Username)

            @Html.LabelFor(model => model.Password)

            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)

            @ViewBag.AlphaCheck

            @Html.LabelFor(model => model.RefreshInterval)

            @{ var refreshList = @ViewBag.refreshList as IEnumerable<SelectListItem>;
            }
            @Html.DropDownListFor(model => model.RefreshInterval, refreshList)

        @*Make sure this return true makes a request and postback on all browsers*@

        <input type="submit" id="CreateButton" value="Create service" />

        @Html.ActionLink("Cancel", "Index")

        @**@

}


import { ServiceInputTypes, ServiceOutputTypes, WorkLinkClientResolvedConfig } from "../WorkLinkClient";
import { UntagResourceRequest, UntagResourceResponse } from "../models/models_0";
import {
  deserializeAws_restJson1UntagResourceCommand,
  serializeAws_restJson1UntagResourceCommand,
} from "../protocols/Aws_restJson1";
import { getSerdePlugin } from "@aws-sdk/middleware-serde";
import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@aws-sdk/protocol-http";
import { Command as $Command } from "@aws-sdk/smithy-client";
import {
  FinalizeHandlerArguments,
  Handler,
  HandlerExecutionContext,
  MiddlewareStack,
  HttpHandlerOptions as __HttpHandlerOptions,
  MetadataBearer as __MetadataBearer,
  SerdeContext as __SerdeContext,
} from "@aws-sdk/types";

export type UntagResourceCommandInput = UntagResourceRequest;
export type UntagResourceCommandOutput = UntagResourceResponse & __MetadataBearer;

export class UntagResourceCommand extends $Command<
  UntagResourceCommandInput,
  UntagResourceCommandOutput,
  WorkLinkClientResolvedConfig
> {
  // Start section: command_properties
  // End section: command_properties

  constructor(readonly input: UntagResourceCommandInput) {
    // Start section: command_constructor
    super();
    // End section: command_constructor
  }

  resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: WorkLinkClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<UntagResourceCommandInput, UntagResourceCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

    const stack = clientStack.concat(this.middlewareStack);

    const { logger } = configuration;
    const handlerExecutionContext: HandlerExecutionContext = {
      logger,
      inputFilterSensitiveLog: UntagResourceRequest.filterSensitiveLog,
      outputFilterSensitiveLog: UntagResourceResponse.filterSensitiveLog,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }

  private serialize(input: UntagResourceCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
    return serializeAws_restJson1UntagResourceCommand(input, context);
  }

  private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<UntagResourceCommandOutput> {
    return deserializeAws_restJson1UntagResourceCommand(output, context);
  }

  // Start section: command_body_extra
  // End section: command_body_extra
}


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

#import <objc/NSObject.h>

#import <PhotoFoundation/PFLoggerBackend-Protocol.h>

@class NSString;
@protocol OS_os_transaction;

@interface PFLoggerBackendAdapter : NSObject <PFLoggerBackend>
{
    // Error parsing type: AQ, name: _pendingTransactionCount
    NSObject<OS_os_transaction> *_transaction;
    BOOL _runningUnderDebugger;
}

+ (long long)parseByteSizeValueForKey:(id)arg1 inString:(id)arg2;
+ (long long)allFileSizeMaxBytesFromString:(id)arg1;
+ (long long)fileSizeMaxBytesFromString:(id)arg1;
+ (id)pathWithoutParametersFromString:(id)arg1;
+ (id)backendsFromUserDefaultsWithLogLevel:(int)arg1;
- (void).cxx_destruct;
@property BOOL runningUnderDebugger; // @synthesize runningUnderDebugger=_runningUnderDebugger;
- (void)flushWithCompletionHandler:(CDUnknownBlockType)arg1;
@property(readonly, nonatomic) BOOL outputsToDebuggerConsole;
@property(readonly, nonatomic) BOOL formatsMessage;
@property(readonly, nonatomic) BOOL allowsConcurrentAccess;
- (void)endTransaction;
- (void)beginTransaction;
- (void)logFromCodeLocation:(CDStruct_98c8119d)arg1 facility:(id)arg2 subsystem:(id)arg3 level:(int)arg4 message:(id)arg5 format:(id)arg6 args:(struct __va_list_tag [1])arg7;
- (id)init;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


package tech.wetech.weshop.common.exception;

import tech.wetech.weshop.common.utils.ResultStatus;

public class WeshopException extends RuntimeException {

    ResultStatus status;

	public WeshopException(ResultStatus status) {
        //不生成栈追踪信息
        super(status.getMsg(), null, false, false);
        this.status = status;
    }

    public ResultStatus getStatus() {
        return status;
    }

    public void setStatus(ResultStatus status) {
        this.status = status;
    }
}


/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */
package org.hibernate.engine.jdbc.dialect.internal;

import org.hibernate.dialect.Database;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolver;

/**
 * The standard DialectResolver implementation
 *
 * @author Steve Ebersole
 */
public final class StandardDialectResolver implements DialectResolver {

	@Override
	public Dialect resolveDialect(DialectResolutionInfo info) {

		for ( Database database : Database.values() ) {
			Dialect dialect = database.resolveDialect( info );
			if ( dialect != null ) {
				return dialect;
			}
		}

		return null;
	}
}


#region Copyright (C) 2007-2018 Team MediaPortal

/*
    Copyright (C) 2007-2018 Team MediaPortal
    http://www.team-mediaportal.com

    This file is part of MediaPortal 2

    MediaPortal 2 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.

    MediaPortal 2 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 MediaPortal 2. If not, see <http://www.gnu.org/licenses/>.
*/

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MediaPortal.Common;
using MediaPortal.Common.MediaManagement;
using MediaPortal.Common.SystemCommunication;

namespace MediaPortal.DevTools
{
  /// <summary>
  /// Media item aspect type registration class for the MediaPortal client. Stores all registered media item aspect types
  /// and automatically registers them at the connected server.
  /// </summary>
  public class MediaItemAspectTypeRegistration : IMediaItemAspectTypeRegistration
  {
    protected IDictionary<Guid, MediaItemAspectMetadata> _locallyKnownMediaItemAspectTypes = new Dictionary<Guid, MediaItemAspectMetadata>();
    protected IDictionary<Guid, MediaItemAspectMetadata> _locallySupportedReimportMediaItemAspectTypes = new Dictionary<Guid, MediaItemAspectMetadata>();

    public IDictionary<Guid, MediaItemAspectMetadata> LocallyKnownMediaItemAspectTypes
    {
      get { return _locallyKnownMediaItemAspectTypes; }
    }

    public IDictionary<Guid, MediaItemAspectMetadata> LocallySupportedReimportMediaItemAspectTypes
    {
      get { return _locallySupportedReimportMediaItemAspectTypes; }
    }

    public async Task RegisterLocallyKnownMediaItemAspectTypeAsync(IEnumerable<MediaItemAspectMetadata> miaTypes)
    {
      await Task.WhenAll(miaTypes.Select(RegisterLocallyKnownMediaItemAspectTypeAsync));
    }

    public Task RegisterLocallyKnownMediaItemAspectTypeAsync(MediaItemAspectMetadata miaType)
    {
      if (_locallyKnownMediaItemAspectTypes.ContainsKey(miaType.AspectId))
        return Task.CompletedTask;
      _locallyKnownMediaItemAspectTypes.Add(miaType.AspectId, miaType);
      IServerConnectionManager serverConnectionManager = ServiceRegistration.Get<IServerConnectionManager>();
      IContentDirectory cd = serverConnectionManager == null ? null :
          serverConnectionManager.ContentDirectory;
      if (cd != null)
        cd.AddMediaItemAspectStorageAsync(miaType).Wait();
      return Task.CompletedTask;
    }

    public Task RegisterLocallySupportedReimportMediaItemAspectTypeAsync(MediaItemAspectMetadata miaType)
    {
      Console.WriteLine("Registering reimport support " + miaType.Name);
      if (!_locallySupportedReimportMediaItemAspectTypes.ContainsKey(miaType.AspectId))
        _locallySupportedReimportMediaItemAspectTypes.Add(miaType.AspectId, miaType);
      return Task.CompletedTask;
    }
  }
}


(function() {
    'use strict';

    angular
        .module('erpApp')
        .config(stateConfig);

    stateConfig.$inject = ['$stateProvider'];

    function stateConfig($stateProvider) {
        $stateProvider.state('jhi-health', {
            parent: 'admin',
            url: '/health',
            data: {
                authorities: ['ROLE_ADMIN'],
                pageTitle: 'health.title'
            },
            views: {
                'content@app': {
                    templateUrl: 'app/admin/health/health.html',
                    controller: 'JhiHealthCheckController',
                    controllerAs: 'vm'
                }
            },
            resolve: {
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    $translatePartialLoader.addPart('health');
                    return $translate.refresh();
                }]
            }
        });
    }
})();


---
title: Exploring History
teaching: 25
exercises: 0
questions:
- "How can I identify old versions of files?"
- "How do I review my changes?"
- "How can I recover old versions of files?"
objectives:
- "Explain what the HEAD of a repository is and how to use it."
- "Identify and use Git commit numbers."
- "Compare various versions of tracked files."
- "Restore old versions of files."
keypoints:
- "`git diff` displays differences between commits."
- "`git checkout` recovers old versions of files."
---

As we saw in the previous lesson, we can refer to commits by their
identifiers.  You can refer to the _most recent commit_ of the working
directory by using the identifier `HEAD`.

We've been adding one line at a time to `mars.txt`, so it's easy to track our
progress by looking, so let's do that using our `HEAD`s.  Before we start,
let's make a change to `mars.txt`, adding yet another line.

~~~
$ nano mars.txt
$ cat mars.txt
~~~
{: .language-bash}

~~~
Cold and dry, but everything is my favorite color
The two moons may be a problem for Wolfman
But the Mummy will appreciate the lack of humidity
An ill-considered change
~~~
{: .output}

Now, let's see what we get.

~~~
$ git diff HEAD mars.txt
~~~
{: .language-bash}

~~~
diff --git a/mars.txt b/mars.txt
index b36abfd..0848c8d 100644
--- a/mars.txt
+++ b/mars.txt
@@ -1,3 +1,4 @@
 Cold and dry, but everything is my favorite color
 The two moons may be a problem for Wolfman
 But the Mummy will appreciate the lack of humidity
+An ill-considered change.
~~~
{: .output}

which is the same as what you would get if you leave out `HEAD` (try it).  The
real goodness in all this is when you can refer to previous commits.  We do
that by adding `~1`
(where "~" is "tilde", pronounced [**til**-d*uh*])
to refer to the commit one before `HEAD`.

~~~
$ git diff HEAD~1 mars.txt
~~~
{: .language-bash}

If we want to see the differences between older commits we can use `git diff`
again, but with the notation `HEAD~1`, `HEAD~2`, and so on, to refer to them:

~~~
$ git diff HEAD~3 mars.txt
~~~
{: .language-bash}

~~~
diff --git a/mars.txt b/mars.txt
index df0654a..b36abfd 100644
--- a/mars.txt
+++ b/mars.txt
@@ -1 +1,4 @@
 Cold and dry, but everything is my favorite color
+The two moons may be a problem for Wolfman
+But the Mummy will appreciate the lack of humidity
+An ill-considered change
~~~
{: .output}

We could also use `git show` which shows us what changes we made at an older commit as
well as the commit message, rather than the _differences_ between a commit and our
working directory that we see by using `git diff`.

~~~
$ git show HEAD~3 mars.txt
~~~
{: .language-bash}

~~~
commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
Author: Vlad Dracula <vlad@tran.sylvan.ia>
Date:   Thu Aug 22 09:51:46 2013 -0400

    Start notes on Mars as a base

diff --git a/mars.txt b/mars.txt
new file mode 100644
index 0000000..df0654a
--- /dev/null
+++ b/mars.txt
@@ -0,0 +1 @@
+Cold and dry, but everything is my favorite color
~~~
{: .output}

In this way,
we can build up a chain of commits.
The most recent end of the chain is referred to as `HEAD`;
we can refer to previous commits using the `~` notation,
so `HEAD~1`
means "the previous commit",
while `HEAD~123` goes back 123 commits from where we are now.

We can also refer to commits using
those long strings of digits and letters
that `git log` displays.
These are unique IDs for the changes,
and "unique" really does mean unique:
every change to any set of files on any computer
has a unique 40-character identifier.
Our first commit was given the ID
`f22b25e3233b4645dabd0d81e651fe074bd8e73b`,
so let's try this:

~~~
$ git diff f22b25e3233b4645dabd0d81e651fe074bd8e73b mars.txt
~~~
{: .language-bash}

~~~
diff --git a/mars.txt b/mars.txt
index df0654a..93a3e13 100644
--- a/mars.txt
+++ b/mars.txt
@@ -1 +1,4 @@
 Cold and dry, but everything is my favorite color
+The two moons may be a problem for Wolfman
+But the Mummy will appreciate the lack of humidity
+An ill-considered change
~~~
{: .output}

That's the right answer,
but typing out random 40-character strings is annoying,
so Git lets us use just the first few characters (typically seven for normal size projects):

~~~
$ git diff f22b25e mars.txt
~~~
{: .language-bash}

~~~
diff --git a/mars.txt b/mars.txt
index df0654a..93a3e13 100644
--- a/mars.txt
+++ b/mars.txt
@@ -1 +1,4 @@
 Cold and dry, but everything is my favorite color
+The two moons may be a problem for Wolfman
+But the Mummy will appreciate the lack of humidity
+An ill-considered change
~~~
{: .output}

All right! So
we can save changes to files and see what we've changed. Now, how
can we restore older versions of things?
Let's suppose we change our mind about the last update to
`mars.txt` (the "ill-considered change").

`git status` now tells us that the file has been changed,
but those changes haven't been staged:

~~~
$ git status
~~~
{: .language-bash}

~~~
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   mars.txt

no changes added to commit (use "git add" and/or "git commit -a")
~~~
{: .output}

We can put things back the way they were
by using `git checkout`:

~~~
$ git checkout HEAD mars.txt
$ cat mars.txt
~~~
{: .language-bash}

~~~
Cold and dry, but everything is my favorite color
The two moons may be a problem for Wolfman
But the Mummy will appreciate the lack of humidity
~~~
{: .output}

As you might guess from its name,
`git checkout` checks out (i.e., restores) an old version of a file.
In this case,
we're telling Git that we want to recover the version of the file recorded in `HEAD`,
which is the last saved commit.
If we want to go back even further,
we can use a commit identifier instead:

~~~
$ git checkout f22b25e mars.txt
~~~
{: .language-bash}

~~~
$ cat mars.txt
~~~
{: .language-bash}

~~~
Cold and dry, but everything is my favorite color
~~~
{: .output}

~~~
$ git status
~~~
{: .language-bash}

~~~
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   mars.txt

~~~
{: .output}

Notice that the changes are currently in the staging area.
Again, we can put things back the way they were
by using `git checkout`:

~~~
$ git checkout HEAD mars.txt
~~~
{: .language-bash}

> ## Don't Lose Your HEAD
>
> Above we used
>
> ~~~
> $ git checkout f22b25e mars.txt
> ~~~
> {: .language-bash}
>
> to revert `mars.txt` to its state after the commit `f22b25e`. But be careful!
> The command `checkout` has other important functionalities and Git will misunderstand
> your intentions if you are not accurate with the typing. For example,
> if you forget `mars.txt` in the previous command.
>
> ~~~
> $ git checkout f22b25e
> ~~~
> {: .language-bash}
> ~~~
> Note: checking out 'f22b25e'.
>
> You are in 'detached HEAD' state. You can look around, make experimental
> changes and commit them, and you can discard any commits you make in this
> state without impacting any branches by performing another checkout.
>
> If you want to create a new branch to retain commits you create, you may
> do so (now or later) by using -b with the checkout command again. Example:
>
>  git checkout -b <new-branch-name>
>
> HEAD is now at f22b25e Start notes on Mars as a base
> ~~~
> {: .error}
>
> The "detached HEAD" is like "look, but don't touch" here,
> so you shouldn't make any changes in this state.
> After investigating your repo's past state, reattach your `HEAD` with `git checkout master`.
{: .callout}

It's important to remember that
we must use the commit number that identifies the state of the repository
*before* the change we're trying to undo.
A common mistake is to use the number of
the commit in which we made the change we're trying to discard.
In the example below, we want to retrieve the state from before the most
recent commit (`HEAD~1`), which is commit `f22b25e`:

![Git Checkout](../fig/git-checkout.svg)

So, to put it all together,
here's how Git works in cartoon form:

![https://figshare.com/articles/How_Git_works_a_cartoon/1328266](../fig/git_staging.svg)

> ## Simplifying the Common Case
>
> If you read the output of `git status` carefully,
> you'll see that it includes this hint:
>
> ~~~
> (use "git checkout -- <file>..." to discard changes in working directory)
> ~~~
> {: .language-bash}
>
> As it says,
> `git checkout` without a version identifier restores files to the state saved in `HEAD`.
> The double dash `--` is needed to separate the names of the files being recovered
> from the command itself:
> without it,
> Git would try to use the name of the file as the commit identifier.
{: .callout}

The fact that files can be reverted one by one
tends to change the way people organize their work.
If everything is in one large document,
it's hard (but not impossible) to undo changes to the introduction
without also undoing changes made later to the conclusion.
If the introduction and conclusion are stored in separate files,
on the other hand,
moving backward and forward in time becomes much easier.

> ## Recovering Older Versions of a File
>
> Jennifer has made changes to the Python script that she has been working on for weeks, and the
> modifications she made this morning "broke" the script and it no longer runs. She has spent
> ~ 1hr trying to fix it, with no luck...
>
> Luckily, she has been keeping track of her project's versions using Git! Which commands below will
> let her recover the last committed version of her Python script called
> `data_cruncher.py`?
>
> 1. `$ git checkout HEAD`
>
> 2. `$ git checkout HEAD data_cruncher.py`
>
> 3. `$ git checkout HEAD~1 data_cruncher.py`
>
> 4. `$ git checkout <unique ID of last commit> data_cruncher.py`
>
> 5. Both 2 and 4
>
>
> > ## Solution
> >
> > The answer is (5)-Both 2 and 4.
> >
> > The `checkout` command restores files from the repository, overwriting the files in your working
> > directory. Answers 2 and 4 both restore the *latest* version *in the repository* of the file
> > `data_cruncher.py`. Answer 2 uses `HEAD` to indicate the *latest*, whereas answer 4 uses the
> > unique ID of the last commit, which is what `HEAD` means.
> >
> > Answer 3 gets the version of `data_cruncher.py` from the commit *before* `HEAD`, which is NOT
> > what we wanted.
> >
> > Answer 1 can be dangerous! Without a filename, `git checkout` will restore **all files**
> > in the current directory (and all directories below it) to their state at the commit specified.
> > This command will restore `data_cruncher.py` to the latest commit version, but it will also
> > restore *any other files that are changed* to that version, erasing any changes you may
> > have made to those files!
> > As discussed above, you are left in a *detached* `HEAD` state, and you don't want to be there.
> {: .solution}
{: .challenge}

> ## Reverting a Commit
>
> Jennifer is collaborating on her Python script with her colleagues and
> realizes her last commit to the project's repository contained an error and
> she wants to undo it.  `git revert [erroneous commit ID]` will create a new
> commit that reverses Jennifer's erroneous commit. Therefore `git revert` is
> different to `git checkout [commit ID]` because `git checkout` returns the
> files within the local repository to a previous state, whereas `git revert`
> reverses changes committed to the local and project repositories.
> Below are the right steps and explanations for Jennifer to use `git revert`,
> what is the missing command?
>
> 1. `________ # Look at the git history of the project to find the commit ID`
>
> 2. Copy the ID (the first few characters of the ID, e.g. 0b1d055).
>
> 3. `git revert [commit ID]`
>
> 4. Type in the new commit message.
>
> 5. Save and close
{: .challenge}

> ## Understanding Workflow and History
>
> What is the output of the last command in
>
> ~~~
> $ cd planets
> $ echo "Venus is beautiful and full of love" > venus.txt
> $ git add venus.txt
> $ echo "Venus is too hot to be suitable as a base" >> venus.txt
> $ git commit -m "Comment on Venus as an unsuitable base"
> $ git checkout HEAD venus.txt
> $ cat venus.txt #this will print the contents of venus.txt to the screen
> ~~~
> {: .language-bash}
>
> 1. ~~~
>    Venus is too hot to be suitable as a base
>    ~~~
>    {: .output}
> 2. ~~~
>    Venus is beautiful and full of love
>    ~~~
>    {: .output}
> 3. ~~~
>    Venus is beautiful and full of love
>    Venus is too hot to be suitable as a base
>    ~~~
>    {: .output}
> 4. ~~~
>    Error because you have changed venus.txt without committing the changes
>    ~~~
>    {: .output}
>
> > ## Solution
> >
> > The answer is 2.
> >
> > The command `git add venus.txt` places the current version of `venus.txt` into the staging area.
> > The changes to the file from the second `echo` command are only applied to the working copy,
> > not the version in the staging area.
> >
> > So, when `git commit -m "Comment on Venus as an unsuitable base"` is executed,
> > the version of `venus.txt` committed to the repository is the one from the staging area and
> > has only one line.
> >
> >  At this time, the working copy still has the second line (and
> >  `git status` will show that the file is modified). However, `git checkout HEAD venus.txt`
> >  replaces the working copy with the most recently committed version of `venus.txt`.
> >
> >  So, `cat venus.txt` will output
> >  ~~~
> >  Venus is beautiful and full of love.
> > ~~~
> > {: .output}
> {: .solution}
{: .challenge}

> ## Checking Understanding of `git diff`
>
> Consider this command: `git diff HEAD~9 mars.txt`. What do you predict this command
> will do if you execute it? What happens when you do execute it? Why?
>
> Try another command, `git diff [ID] mars.txt`, where [ID] is replaced with
> the unique identifier for your most recent commit. What do you think will happen,
> and what does happen?
{: .challenge}

> ## Getting Rid of Staged Changes
>
> `git checkout` can be used to restore a previous commit when unstaged changes have
> been made, but will it also work for changes that have been staged but not committed?
> Make a change to `mars.txt`, add that change, and use `git checkout` to see if
> you can remove your change.
{: .challenge}

> ## Explore and Summarize Histories
>
> Exploring history is an important part of Git, and often it is a challenge to find
> the right commit ID, especially if the commit is from several months ago.
>
> Imagine the `planets` project has more than 50 files.
> You would like to find a commit that modifies some specific text in `mars.txt`.
> When you type `git log`, a very long list appeared.
> How can you narrow down the search?
>
> Recall that the `git diff` command allows us to explore one specific file,
> e.g., `git diff mars.txt`. We can apply a similar idea here.
>
> ~~~
> $ git log mars.txt
> ~~~
> {: .language-bash}
>
> Unfortunately some of these commit messages are very ambiguous, e.g., `update files`.
> How can you search through these files?
>
> Both `git diff` and `git log` are very useful and they summarize a different part of the history
> for you.
> Is it possible to combine both? Let's try the following:
>
> ~~~
> $ git log --patch mars.txt
> ~~~
> {: .language-bash}
>
> You should get a long list of output, and you should be able to see both commit messages and
> the difference between each commit.
>
> Question: What does the following command do?
>
> ~~~
> $ git log --patch HEAD~9 *.txt
> ~~~
> {: .language-bash}
{: .challenge}


#region Copyright (C) 2007-2018 Team MediaPortal

/*
    Copyright (C) 2007-2018 Team MediaPortal
    http://www.team-mediaportal.com

    This file is part of MediaPortal 2

    MediaPortal 2 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.

    MediaPortal 2 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 MediaPortal 2. If not, see <http://www.gnu.org/licenses/>.
*/

#endregion

using System;
using System.Xml;

namespace UPnP.Infrastructure.Dv.DeviceTree
{
  /// <summary>
  /// Defines the range of allowed numeric values for a UPnP state variable.
  /// </summary>
  public class DvAllowedValueRange
  {
    protected DvDataType _dataType;
    protected double _minValue;
    protected double _maxValue;
    protected double? _step;

    public DvAllowedValueRange(DvDataType dataType, double minValue, double maxValue) :
        this(dataType, minValue, maxValue, null) { }

    public DvAllowedValueRange(DvDataType dataType, double minValue, double maxValue, double? step)
    {
      _minValue = minValue;
      _maxValue = maxValue;
      _dataType = dataType;
      _step = step;
    }

    public double MinValue
    {
      get { return _minValue; }
    }

    public double MaxValue
    {
      get { return _maxValue; }
    }

    public double? Step
    {
      get { return _step; }
    }

    public bool IsValueInRange(object value)
    {
      double doubleVal = (double) Convert.ChangeType(value, typeof(double));
      if (doubleVal < _minValue || doubleVal > _maxValue)
        return false;
      if (_step.HasValue)
      {
        double n = (doubleVal - _minValue) / _step.Value;
        return (n - (int) n) < 0.001;
      }
      return true;
    }

    #region Description generation

    internal void AddSCPDDescriptionForValueRange(XmlWriter writer)
    {
      writer.WriteStartElement("allowedValueRange");
      writer.WriteStartElement("minimum");
      _dataType.SoapSerializeValue(_minValue, true, writer);
      writer.WriteEndElement(); // minimum
      writer.WriteStartElement("maximum");
      _dataType.SoapSerializeValue(_maxValue, true, writer);
      writer.WriteEndElement(); // maximum
      if (_step.HasValue)
      {
        writer.WriteStartElement("step");
        _dataType.SoapSerializeValue(_step.Value, true, writer);
        writer.WriteEndElement(); // step
      }
      writer.WriteEndElement(); // allowedValueRange
    }

    #endregion
  }
}


/**
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

#pragma once
#include <aws/rds/RDS_EXPORTS.h>
#include <aws/rds/model/DBCluster.h>
#include <aws/rds/model/ResponseMetadata.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace RDS
{
namespace Model
{
  class AWS_RDS_API CreateDBClusterResult
  {
  public:
    CreateDBClusterResult();
    CreateDBClusterResult(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    CreateDBClusterResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    inline const DBCluster& GetDBCluster() const{ return m_dBCluster; }

    inline void SetDBCluster(const DBCluster& value) { m_dBCluster = value; }

    inline void SetDBCluster(DBCluster&& value) { m_dBCluster = std::move(value); }

    inline CreateDBClusterResult& WithDBCluster(const DBCluster& value) { SetDBCluster(value); return *this;}

    inline CreateDBClusterResult& WithDBCluster(DBCluster&& value) { SetDBCluster(std::move(value)); return *this;}

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }

    inline CreateDBClusterResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline CreateDBClusterResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:

    DBCluster m_dBCluster;

    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace RDS
} // namespace Aws


Fast-foods & Restaurants

Department Stores

Clothing & Accessories

Health & Cosmetics

Miscellaneous

Basement

GAP

Lorem ipsum

Petco

Lorem ipsum

Ground Floor

Sears

Sears depártment store

Macy's

Macy's <i>department</i> store

JCPenney

JCPenney department store

Walgreens

At the corner of Happy & Healthy

Sephora

Makeup, fragrance, skincare

Belk

Lorem ipsum

H&M

Lorem ipsum

Old Navy

Lorem ipsum

Sport Chek

Lorem ipsum

Starbucks

The coffee company

Zara

Lorem ipsum

First Floor

Applebee's

See you tomorrow

KFC

Kentucky Fried Chicken

McDonald's

Additional information

Pizza Hut

Make it great

Subway

Eat fresh.

CVS Pharmacy

Lorem ipsum dolor sit amet, consectetur.

Pull & Bear

Lorem ipsum

AMC Theatres

Additional information

AT&T

Additional information


# Lazy Loading

## [Krzysztof Grzybek](https://github.com/krzysztof-grzybek)

Lazy loading is a pattern in which we delay loading the data until it's actually needed. Lazy loading data from the database is usually achieved by Implementing proper Proxy class.

It might be useful if we have an object which requires a lot of data to be fetched from the database, but probably we don't need all the data in every case. It might reduce object initialization phase and memory usage.

On the other hand, we might end up with a lot of database queries to get small chunks of data, and it might cause performance problems. It's not so hard to do that because lazy loading is a very leaking abstraction.

Another pitfall, probably more important is that we might work with inconsistent data. If we loaded user data first, and then after some time we loaded user orders, we can't be sure that the orders data wasn't modified already by someone else.


fileFormatVersion: 2
guid: 2e3b9bbf2c1a3cd4f88883ca32882ec6
MonoImporter:
  externalObjects: {}
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:


/*
 * Copyright (c)  2018
 * All rights reserved.
 * 2018-08-22 19:58:32
 */
package com.ueboot.shiro.controller.resources;

import com.alibaba.fastjson.JSON;
import com.ueboot.core.http.response.Response;
import com.ueboot.shiro.controller.resources.vo.*;
import com.ueboot.shiro.entity.Resources;
import com.ueboot.shiro.service.resources.ResourcesService;
import com.ueboot.shiro.shiro.ShiroEventListener;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2018-08-22 19:58:32
 *
 * @author yangkui
 * @since 2.1.0 by ueboot-generator
 */
@Slf4j
@RestController
@RequestMapping(value = "/ueboot/resources")
public class ResourcesController {

    @Resource
    private ResourcesService resourcesService;

    // shiro权限记录
    @Resource
    private ShiroEventListener shiroEventListener;

    @RequiresPermissions("ueboot:resources:read")
    @PostMapping(value = "/list")
    public Response<List<ResourcesResp>> list() {
        List<Resources> all = this.resourcesService.findAll();
        List<ResourcesResp> retval = new ArrayList<>();
        all.forEach((r) -> {
            ResourcesResp resp = new ResourcesResp();
            BeanUtils.copyProperties(r, resp);
            if (r.getParent() != null) {
                resp.setParentId(r.getParent().getId());
            }
            retval.add(resp);
        });
        return new Response<>(retval);
    }

    @RequiresPermissions("ueboot:resources:read")
    @PostMapping(value = "/page")
    public Response<Page<ResourcesResp>> page(@PageableDefault(value = 15, sort = {"id"}, direction = Sort.Direction.ASC)
                                                      Pageable pageable, @RequestBody(required = false) ResourcesFindReq req) {
        Page<Resources> entities = null;
        entities = resourcesService.findByParentId(pageable, req.getParentId());
        Page<ResourcesResp> body = entities.map(entity -> {
            ResourcesResp resp = new ResourcesResp();
            BeanUtils.copyProperties(entity, resp);
            if (entity.getParent() != null) {
                resp.setParentId(entity.getParent().getId());
            }
            return resp;
        });

        return new Response<>(body);
    }

    @RequiresPermissions("ueboot:resources:save")
    @PostMapping(value = "/save")
    public Response<Void> save(@RequestBody ResourcesReq req) {
        Resources entity = null;
        if (req.getId() == null) {
            entity = new Resources();
        } else {
            entity = resourcesService.get(req.getId());
        }
        BeanUtils.copyProperties(req, entity);
        //菜单样式配置
        Map<String, String> theme = new HashMap<>();
        if (StringUtil.isNotBlank(req.getIconName())) {
            theme.put("iconName", req.getIconName());
        }
        if (StringUtil.isNotBlank(req.getFontColor())) {
            theme.put("fontColor", req.getFontColor());
        }
        if (theme.size() > 0) {
            entity.setThemeJson(JSON.toJSONString(theme));
        } else {
            entity.setThemeJson(null);
        }
        if (req.getParentId() != 0L) {
            Resources parent = resourcesService.findById(req.getParentId());
            Assert.notNull(parent, "父节点不存在");
            entity.setParent(parent);
            entity.setParentName(parent.getName());
        } else {
            entity.setParent(null);
            entity.setParentName(null);
        }

        resourcesService.save(entity);

        // 保存/修改资源日志记录
        String optUserName = (String) SecurityUtils.getSubject().getPrincipal();
        this.shiroEventListener.saveResourceEvent(optUserName, req.getName());
        return new Response<>();
    }

    @RequiresPermissions("ueboot:resources:delete")
    @PostMapping(value = "/delete")
    public Response<Void> delete(Long[] id) {
        resourcesService.deleteResource(id);
        return new Response<>();
    }

    @RequiresPermissions("ueboot:resources:read")
    @GetMapping(value = "/{id}")
    public Response<ResourcesResp> get(@PathVariable Long id) {
        Resources entity = resourcesService.get(id);
        ResourcesResp resp = new ResourcesResp();
        BeanUtils.copyProperties(entity, resp);
        return new Response<>(resp);
    }

}


/*
 * This file is part of the SDWebImage package.
 * (c) Olivier Poitrey <rs@dailymotion.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import <Foundation/Foundation.h>
#import "SDWebImageDownloader.h"
#import "SDWebImageOperation.h"

/**
 Describes a downloader operation. If one wants to use a custom downloader op, it needs to inherit from `NSOperation` and conform to this protocol
 For the description about these methods, see `SDWebImageDownloaderOperation`
 @note If your custom operation class does not use `NSURLSession` at all, do not implement the optional methods and session delegate methods.
 */
@protocol SDWebImageDownloaderOperation <NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
@required
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
                              inSession:(nullable NSURLSession *)session
                                options:(SDWebImageDownloaderOptions)options;

- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
                              inSession:(nullable NSURLSession *)session
                                options:(SDWebImageDownloaderOptions)options
                                context:(nullable SDWebImageContext *)context;

- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                            completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;

- (BOOL)cancel:(nullable id)token;

@property (strong, nonatomic, readonly, nullable) NSURLRequest *request;
@property (strong, nonatomic, readonly, nullable) NSURLResponse *response;

@optional
@property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask;
@property (strong, nonatomic, nullable) NSURLCredential *credential;
@property (assign, nonatomic) double minimumProgressInterval;

@end

/**
 The download operation class for SDWebImageDownloader.
 */
@interface SDWebImageDownloaderOperation : NSOperation <SDWebImageDownloaderOperation>

/**
 * The request used by the operation's task.
 */
@property (strong, nonatomic, readonly, nullable) NSURLRequest *request;

/**
 * The response returned by the operation's task.
 */
@property (strong, nonatomic, readonly, nullable) NSURLResponse *response;

/**
 * The operation's task
 */
@property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask;

/**
 * The credential used for authentication challenges in `-URLSession:task:didReceiveChallenge:completionHandler:`.
 *
 * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
 */
@property (strong, nonatomic, nullable) NSURLCredential *credential;

/**
 * The minimum interval about progress percent during network downloading. Which means the next progress callback and current progress callback's progress percent difference should be larger or equal to this value. However, the final finish download progress callback does not get effected.
 * The value should be 0.0-1.0.
 * @note If you're using progressive decoding feature, this will also effect the image refresh rate.
 * @note This value may enhance the performance if you don't want progress callback too frequently.
 * Defaults to 0, which means each time we receive the new data from URLSession, we callback the progressBlock immediately.
 */
@property (assign, nonatomic) double minimumProgressInterval;

/**
 * The options for the receiver.
 */
@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options;

/**
 * The context for the receiver.
 */
@property (copy, nonatomic, readonly, nullable) SDWebImageContext *context;

/**
 *  Initializes a `SDWebImageDownloaderOperation` object
 *
 *  @see SDWebImageDownloaderOperation
 *
 *  @param request        the URL request
 *  @param session        the URL session in which this operation will run
 *  @param options        downloader options
 *
 *  @return the initialized instance
 */
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
                              inSession:(nullable NSURLSession *)session
                                options:(SDWebImageDownloaderOptions)options;

/**
 *  Initializes a `SDWebImageDownloaderOperation` object
 *
 *  @see SDWebImageDownloaderOperation
 *
 *  @param request        the URL request
 *  @param session        the URL session in which this operation will run
 *  @param options        downloader options
 *  @param context        A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
 *
 *  @return the initialized instance
 */
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
                              inSession:(nullable NSURLSession *)session
                                options:(SDWebImageDownloaderOptions)options
                                context:(nullable SDWebImageContext *)context NS_DESIGNATED_INITIALIZER;

/**
 *  Adds handlers for progress and completion. Returns a tokent that can be passed to -cancel: to cancel this set of
 *  callbacks.
 *
 *  @param progressBlock  the block executed when a new chunk of data arrives.
 *                        @note the progress block is executed on a background queue
 *  @param completedBlock the block executed when the download is done.
 *                        @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue
 *
 *  @return the token to use to cancel this set of handlers
 */
- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                            completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;

/**
 *  Cancels a set of callbacks. Once all callbacks are canceled, the operation is cancelled.
 *
 *  @param token the token representing a set of callbacks to cancel
 *
 *  @return YES if the operation was stopped because this was the last token to be canceled. NO otherwise.
 */
- (BOOL)cancel:(nullable id)token;

@end


// Package truncindex provides a general 'index tree', used by Docker
// in order to be able to reference containers by only a few unambiguous
// characters of their id.
package truncindex

import (
	"errors"
	"fmt"
	"strings"
	"sync"

	"github.com/tchap/go-patricia/patricia"
)

var (
	// ErrEmptyPrefix is an error returned if the prefix was empty.
	ErrEmptyPrefix = errors.New("Prefix can't be empty")

	// ErrIllegalChar is returned when a space is in the ID
	ErrIllegalChar = errors.New("illegal character: ' '")

	// ErrNotExist is returned when ID or its prefix not found in index.
	ErrNotExist = errors.New("ID does not exist")
)

// ErrAmbiguousPrefix is returned if the prefix was ambiguous
// (multiple ids for the prefix).
type ErrAmbiguousPrefix struct {
	prefix string
}

func (e ErrAmbiguousPrefix) Error() string {
	return fmt.Sprintf("Multiple IDs found with provided prefix: %s", e.prefix)
}

// TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
// This is used to retrieve image and container IDs by more convenient shorthand prefixes.
type TruncIndex struct {
	sync.RWMutex
	trie *patricia.Trie
	ids  map[string]struct{}
}

// NewTruncIndex creates a new TruncIndex and initializes with a list of IDs.
func NewTruncIndex(ids []string) (idx *TruncIndex) {
	idx = &TruncIndex{
		ids: make(map[string]struct{}),

		// Change patricia max prefix per node length,
		// because our len(ID) always 64
		trie: patricia.NewTrie(patricia.MaxPrefixPerNode(64)),
	}
	for _, id := range ids {
		idx.addID(id)
	}
	return
}

func (idx *TruncIndex) addID(id string) error {
	if strings.Contains(id, " ") {
		return ErrIllegalChar
	}
	if id == "" {
		return ErrEmptyPrefix
	}
	if _, exists := idx.ids[id]; exists {
		return fmt.Errorf("id already exists: '%s'", id)
	}
	idx.ids[id] = struct{}{}
	if inserted := idx.trie.Insert(patricia.Prefix(id), struct{}{}); !inserted {
		return fmt.Errorf("failed to insert id: %s", id)
	}
	return nil
}

// Add adds a new ID to the TruncIndex.
func (idx *TruncIndex) Add(id string) error {
	idx.Lock()
	defer idx.Unlock()
	return idx.addID(id)
}

// Delete removes an ID from the TruncIndex. If there are multiple IDs
// with the given prefix, an error is thrown.
func (idx *TruncIndex) Delete(id string) error {
	idx.Lock()
	defer idx.Unlock()
	if _, exists := idx.ids[id]; !exists || id == "" {
		return fmt.Errorf("no such id: '%s'", id)
	}
	delete(idx.ids, id)
	if deleted := idx.trie.Delete(patricia.Prefix(id)); !deleted {
		return fmt.Errorf("no such id: '%s'", id)
	}
	return nil
}

// Get retrieves an ID from the TruncIndex. If there are multiple IDs
// with the given prefix, an error is thrown.
func (idx *TruncIndex) Get(s string) (string, error) {
	if s == "" {
		return "", ErrEmptyPrefix
	}
	var (
		id string
	)
	subTreeVisitFunc := func(prefix patricia.Prefix, item patricia.Item) error {
		if id != "" {
			// we haven't found the ID if there are two or more IDs
			id = ""
			return ErrAmbiguousPrefix{prefix: string(prefix)}
		}
		id = string(prefix)
		return nil
	}

	idx.RLock()
	defer idx.RUnlock()
	if err := idx.trie.VisitSubtree(patricia.Prefix(s), subTreeVisitFunc); err != nil {
		return "", err
	}
	if id != "" {
		return id, nil
	}
	return "", ErrNotExist
}

// Iterate iterates over all stored IDs and passes each of them to the given
// handler. Take care that the handler method does not call any public
// method on truncindex as the internal locking is not reentrant/recursive
// and will result in deadlock.
func (idx *TruncIndex) Iterate(handler func(id string)) {
	idx.Lock()
	defer idx.Unlock()
	idx.trie.Visit(func(prefix patricia.Prefix, item patricia.Item) error {
		handler(string(prefix))
		return nil
	})
}


using Android.Views;

namespace Camera2Basic.Listeners
{
    public class Camera2BasicSurfaceTextureListener : Java.Lang.Object, TextureView.ISurfaceTextureListener
    {
        private readonly Camera2BasicFragment owner;

        public Camera2BasicSurfaceTextureListener(Camera2BasicFragment owner)
        {
            if (owner == null)
                throw new System.ArgumentNullException("owner");
            this.owner = owner;
        }

        public void OnSurfaceTextureAvailable(Android.Graphics.SurfaceTexture surface, int width, int height)
        {
            owner.OpenCamera(width, height);
        }

        public bool OnSurfaceTextureDestroyed(Android.Graphics.SurfaceTexture surface)
        {
            return true;
        }

        public void OnSurfaceTextureSizeChanged(Android.Graphics.SurfaceTexture surface, int width, int height)
        {
            owner.ConfigureTransform(width, height);
        }

        public void OnSurfaceTextureUpdated(Android.Graphics.SurfaceTexture surface)
        {

        }
    }
}