text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#ifndef EIGEN_EVAL_OMP_H
#define EIGEN_EVAL_OMP_H

/** \class EvalOMP
  *
  * \brief Parallel evaluation of an expression using OpenMP
  *
  * The template parameter Expression is the type of the expression that we are evaluating.
  *
  * This class is the return type of MatrixBase::evalOMP() and most of the time this is the
  * only way it is used.
  *
  * Note that if OpenMP is not enabled, then this class is equivalent to Eval.
  *
  * \sa MatrixBase::evalOMP(), class Eval, MatrixBase::eval()
  */
template<typename ExpressionType>
struct ei_traits<EvalOMP<ExpressionType> >
{
  typedef typename ExpressionType::Scalar Scalar;
  enum {
    RowsAtCompileTime = ExpressionType::RowsAtCompileTime,
    ColsAtCompileTime = ExpressionType::ColsAtCompileTime,
    MaxRowsAtCompileTime = ExpressionType::MaxRowsAtCompileTime,
    MaxColsAtCompileTime = ExpressionType::MaxColsAtCompileTime,
    Flags = ExpressionType::Flags & ~LazyBit
  };
};

template<typename ExpressionType> class EvalOMP : ei_no_assignment_operator,
  public Matrix< typename ExpressionType::Scalar,
                 ExpressionType::RowsAtCompileTime,
                 ExpressionType::ColsAtCompileTime,
                 ExpressionType::Flags,
                 ExpressionType::MaxRowsAtCompileTime,
                 ExpressionType::MaxColsAtCompileTime>
{
  public:

    /** The actual matrix type to evaluate to. This type can be used independently
      * of the rest of this class to get the actual matrix type to evaluate and store
      * the value of an expression.
      */
    typedef Matrix<typename ExpressionType::Scalar,
                   ExpressionType::RowsAtCompileTime,
                   ExpressionType::ColsAtCompileTime,
                   ExpressionType::Flags,
                   ExpressionType::MaxRowsAtCompileTime,
                   ExpressionType::MaxColsAtCompileTime> MatrixType;

    _EIGEN_GENERIC_PUBLIC_INTERFACE(EvalOMP, MatrixType)

    #ifdef _OPENMP
    explicit EvalOMP(const ExpressionType& other)
      : MatrixType(other.rows(), other.cols())
    {
      #ifdef __INTEL_COMPILER
      #pragma omp parallel default(none) shared(other)
      #else
      #pragma omp parallel default(none)
      #endif
      {
        if (this->cols()>this->rows())
        {
          #pragma omp for
          for(int j = 0; j < this->cols(); j++)
            for(int i = 0; i < this->rows(); i++)
              this->coeffRef(i, j) = other.coeff(i, j);
        }
        else
        {
          #pragma omp for
          for(int i = 0; i < this->rows(); i++)
            for(int j = 0; j < this->cols(); j++)
              this->coeffRef(i, j) = other.coeff(i, j);
        }
      }
    }
    #else
    explicit EvalOMP(const ExpressionType& other) : MatrixType(other) {}
    #endif
};

/** Evaluates *this in a parallel fashion using OpenMP and returns the obtained matrix.
  *
  * Of course, it only makes sense to call this function for complex expressions, and/or
  * large matrices (>32x32), \b and if there is no outer loop which can be parallelized.
  *
  * It is the responsibility of the user manage the OpenMP parameters, for instance:
  * \code
  * #include <omp.h>
  * // ...
  * omp_set_num_threads(omp_get_num_procs());
  * \endcode
  * You also need to enable OpenMP on your compiler (e.g., -fopenmp) during both compilation and linking.
  *
  * Note that if OpenMP is not enabled, then evalOMP() is equivalent to eval().
  *
  * \sa class EvalOMP, eval()
  */
template<typename Derived>
const EvalOMP<Derived> MatrixBase<Derived>::evalOMP() const
{
  return EvalOMP<Derived>(*static_cast<const Derived*>(this));
}

#endif // EIGEN_EVAL_OMP_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Internal;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication.Cookies;
using Xunit;

namespace E2ETests
{
    public partial class Validator
    {
        private static readonly string IdentityCookieName = CookieAuthenticationDefaults.CookiePrefix + new IdentityCookieOptions().ApplicationCookieAuthenticationScheme;
        private static readonly string ExternalLoginCookieName = CookieAuthenticationDefaults.CookiePrefix + new IdentityCookieOptions().ExternalCookieAuthenticationScheme;
        private HttpClient _httpClient;

        private HttpClientHandler _httpClientHandler;

        private readonly ILogger _logger;

        private readonly DeploymentResult _deploymentResult;

        public Validator(
            HttpClient httpClient,
            HttpClientHandler httpClientHandler,
            ILogger logger,
            DeploymentResult deploymentResult)
        {
            _httpClient = httpClient;
            _httpClientHandler = httpClientHandler;
            _logger = logger;
            _deploymentResult = deploymentResult;
        }

        private Task<HttpResponseMessage> DoGetAsync(string uri)
            => DoGetAsync(new Uri(uri, UriKind.RelativeOrAbsolute));

        private async Task<HttpResponseMessage> DoGetAsync(Uri uri)
        {
            _logger.LogInformation("GET {0}", uri.ToString());
            var resp= await _httpClient.GetAsync(uri);
            LogHeaders(resp, LogLevel.Information);
            return resp;
        }

        private Task<HttpResponseMessage> DoPostAsync(string uri, HttpContent content)
            => DoPostAsync(new Uri(uri, UriKind.RelativeOrAbsolute), content);

        private async Task<HttpResponseMessage> DoPostAsync(Uri uri, HttpContent content)
        {
            _logger.LogInformation("POST {0}", uri.ToString());
            var resp= await _httpClient.PostAsync(uri, content);
            LogHeaders(resp, LogLevel.Information);
            return resp;
        }
        private void LogHeaders(HttpResponseMessage response, LogLevel logLevel)
        {
            var requestHeaders = string.Join("\n", response.RequestMessage.Headers.Select(h => h.Key + "=" + string.Join(",", h.Value)));
            _logger.Log(logLevel, 0,
               new FormattedLogValues("Request headers: {0}", requestHeaders),
               exception: null,
               formatter: (o, e) => o.ToString());

            var responseHeaders = string.Join("\n", response.Headers.Select(h => h.Key + "=" + string.Join(",", h.Value)));
            _logger.Log(logLevel, 0,
                new FormattedLogValues("Response headers: {0}", responseHeaders),
                exception: null,
                formatter: (o, e) => o.ToString());
        }

        public async Task VerifyHomePage(
            HttpResponseMessage response,
            bool useNtlmAuthentication = false)
        {
            var responseContent = await response.Content.ReadAsStringAsync();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                _logger.LogInformation("Home page content : {0}", responseContent);
            }

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            ValidateLayoutPage(responseContent);
            Assert.Contains(PrefixBaseAddress("<a href=\"/{0}/Store/Details/"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("<title>Home Page – ASP.NET MVC Music Store</title>", responseContent, StringComparison.OrdinalIgnoreCase);

            if (!useNtlmAuthentication)
            {
                //We don't display these for Ntlm
                Assert.Contains("Register", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("Login", responseContent, StringComparison.OrdinalIgnoreCase);
            }

            Assert.Contains("www.github.com/aspnet/MusicStore", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("/Images/home-showcase.png", responseContent, StringComparison.OrdinalIgnoreCase);
            _logger.LogInformation("Application initialization successful.");

            _logger.LogInformation("Application runtime information");
            //var runtimeResponse = await DoGetAsync("runtimeinfo");

            // https://github.com/aspnet/Diagnostics/issues/108
            if (_deploymentResult.DeploymentParameters.RuntimeFlavor != RuntimeFlavor.CoreClr)
            {
                //Helpers.ThrowIfResponseStatusNotOk(runtimeResponse, _logger);
            }

            //var runtimeInfo = await runtimeResponse.Content.ReadAsStringAsync();
            //_logger.LogInformation(runtimeInfo);
        }

        public async Task VerifyNtlmHomePage(HttpResponseMessage response)
        {
            await VerifyHomePage(response, useNtlmAuthentication: true);

            var homePageContent = await response.Content.ReadAsStringAsync();

            //Check if the user name appears in the page
            Assert.Contains(
                string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("USERDOMAIN"), Environment.GetEnvironmentVariable("USERNAME")),
                homePageContent, StringComparison.OrdinalIgnoreCase);
        }

        public void ValidateLayoutPage(string responseContent)
        {
            Assert.Contains("ASP.NET MVC Music Store", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains(PrefixBaseAddress("
Home
"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains(PrefixBaseAddress("Store "), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("
", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("

", responseContent, StringComparison.OrdinalIgnoreCase);
        }

        public async Task VerifyStaticContentServed()
        {
            _logger.LogInformation("Validating if static contents are served..");
            _logger.LogInformation("Fetching favicon.ico..");
            var response = await DoGetAsync("favicon.ico");
            await ThrowIfResponseStatusNotOk(response);
            Assert.NotNull(response.Headers.ETag);
            _logger.LogInformation("Etag received: {etag}", response.Headers.ETag.Tag);

            //Check if you receive a NotModified on sending an etag
            _logger.LogInformation("Sending an IfNoneMatch header with e-tag");
            _httpClient.DefaultRequestHeaders.IfNoneMatch.Add(response.Headers.ETag);
            response = await DoGetAsync("favicon.ico");
            Assert.Equal(HttpStatusCode.NotModified, response.StatusCode);
            _httpClient.DefaultRequestHeaders.IfNoneMatch.Clear();
            _logger.LogInformation("Successfully received a NotModified status");

            _logger.LogInformation("Fetching /Content/bootstrap.css..");
            response = await DoGetAsync("Content/bootstrap.css");
            await ThrowIfResponseStatusNotOk(response);
            _logger.LogInformation("Verified static contents are served successfully");
        }

        public async Task AccessStoreWithPermissions()
        {
            _logger.LogInformation("Trying to access the store inventory..");
            var response = await DoGetAsync("Admin/StoreManager/");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            Assert.Equal<string>(_deploymentResult.ApplicationBaseUri + "Admin/StoreManager/", response.RequestMessage.RequestUri.AbsoluteUri);
            _logger.LogInformation("Successfully acccessed the store inventory");
        }

        private string PrefixBaseAddress(string url)
        {
            url = string.Format(url, string.Empty);

            return url.Replace("//", "/").Replace("%2F%2F", "%2F").Replace("%2F/", "%2F");
        }

        // Making a request to a protected resource that this user does not have access to - should
        // automatically redirect to the configured access denied page
        public async Task AccessStoreWithoutPermissions(string email = null)
        {
            _logger.LogInformation("Trying to access StoreManager that needs ManageStore claim with the current user : {email}", email ?? "Anonymous");
            var response = await DoGetAsync("Admin/StoreManager/");
            var responseContent = await response.Content.ReadAsStringAsync();
            ValidateLayoutPage(responseContent);

            if (email == null)
            {
                Assert.Contains("<title>Log in – ASP.NET MVC Music Store</title>", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("
Use a local account to log in.
", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Equal<string>(_deploymentResult.ApplicationBaseUri + PrefixBaseAddress("Account/Login?ReturnUrl=%2F{0}%2FAdmin%2FStoreManager%2F"), response.RequestMessage.RequestUri.AbsoluteUri);
                _logger.LogInformation("Redirected to login page as expected.");
            }
            else
            {
                Assert.Contains("<title>Access denied due to insufficient permissions – ASP.NET MVC Music Store</title>", responseContent, StringComparison.OrdinalIgnoreCase);
            }
        }

        public async Task RegisterUserWithNonMatchingPasswords()
        {
            _logger.LogInformation("Trying to create user with not matching password and confirm password");
            var response = await DoGetAsync("Account/Register");
            await ThrowIfResponseStatusNotOk(response);
            LogHeaders(response, LogLevel.Trace);

            var responseContent = await response.Content.ReadAsStringAsync();
            ValidateLayoutPage(responseContent);

            var generatedEmail = Guid.NewGuid().ToString().Replace("-", string.Empty) + "@test.com";
            _logger.LogInformation("Creating a new user with name '{email}'", generatedEmail);
            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("Email", generatedEmail),
                    new KeyValuePair<string, string>("Password", "Password~1"),
                    new KeyValuePair<string, string>("ConfirmPassword", "Password~2"),
                    new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Register")),
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/Register", content);
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(IdentityCookieName));
            Assert.Contains("

The password and confirmation password do not match.
", responseContent, StringComparison.OrdinalIgnoreCase);
            _logger.LogInformation("Server side model validator rejected the user '{email}''s registration as passwords do not match.", generatedEmail);
        }

        public async Task<string> RegisterValidUser()
        {
            var response = await DoGetAsync("Account/Register");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            ValidateLayoutPage(responseContent);

            var generatedEmail = Guid.NewGuid().ToString().Replace("-", string.Empty) + "@test.com";
            _logger.LogInformation("Creating a new user with name '{email}'", generatedEmail);
            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("Email", generatedEmail),
                    new KeyValuePair<string, string>("Password", "Password~1"),
                    new KeyValuePair<string, string>("ConfirmPassword", "Password~1"),
                    new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Register")),
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/Register", content);
            responseContent = await response.Content.ReadAsStringAsync();

            //Account verification
            Assert.Equal<string>(_deploymentResult.ApplicationBaseUri + "Account/Register", response.RequestMessage.RequestUri.AbsoluteUri);
            Assert.Contains("For DEMO only: You can click this link to confirm the email:", responseContent, StringComparison.OrdinalIgnoreCase);
            var startIndex = responseContent.IndexOf("[[<a href=\"", 0) + "[[link]]", startIndex);
            var confirmUrl = responseContent.Substring(startIndex, endIndex - startIndex);
            confirmUrl = WebUtility.HtmlDecode(confirmUrl);
            response = await DoGetAsync(confirmUrl);
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains("Thank you for confirming your email.", responseContent, StringComparison.OrdinalIgnoreCase);
            return generatedEmail;
        }

        public async Task RegisterExistingUser(string email)
        {
            _logger.LogInformation("Trying to register a user with name '{email}' again", email);
            var response = await DoGetAsync("Account/Register");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("Creating a new user with name '{email}'", email);
            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("Email", email),
                    new KeyValuePair<string, string>("Password", "Password~1"),
                    new KeyValuePair<string, string>("ConfirmPassword", "Password~1"),
                    new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Register")),
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/Register", content);
            responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains(string.Format("User name '{0}' is already taken.", email), responseContent, StringComparison.OrdinalIgnoreCase);
            _logger.LogInformation("Identity threw a valid exception that user '{email}' already exists in the system", email);
        }

        public async Task SignOutUser(string email)
        {
            _logger.LogInformation("Signing out from '{email}''s session", email);
            var response = await DoGetAsync(string.Empty);
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            ValidateLayoutPage(responseContent);
            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/LogOff")),
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/LogOff", content);
            responseContent = await response.Content.ReadAsStringAsync();

            if (!Helpers.RunningOnMono)
            {
                Assert.Contains("ASP.NET MVC Music Store", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("Register", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("Login", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("www.github.com/aspnet/MusicStore", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("/Images/home-showcase.png", responseContent, StringComparison.OrdinalIgnoreCase);
                //Verify cookie cleared on logout
                Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(IdentityCookieName));
                _logger.LogInformation("Successfully signed out of '{email}''s session", email);
            }
            else
            {
                //Bug in Mono - on logout the cookie is not cleared in the cookie container and not redirected. Work around by reinstantiating the httpClient.
                _httpClientHandler = new HttpClientHandler();
                _httpClient = new HttpClient(_httpClientHandler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };
            }
        }

        public async Task SignInWithInvalidPassword(string email, string invalidPassword)
        {
            var response = await DoGetAsync("Account/Login");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("Signing in with user '{email}'", email);
            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("Email", email),
                    new KeyValuePair<string, string>("Password", invalidPassword),
                    new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Login")),
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/Login", content);
            responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains("

Invalid login attempt.
", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie not sent
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(IdentityCookieName));
            _logger.LogInformation("Identity successfully prevented an invalid user login.");
        }

        public async Task SignInWithUser(string email, string password)
        {
            var response = await DoGetAsync("Account/Login");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("Signing in with user '{email}'", email);
            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("Email", email),
                    new KeyValuePair<string, string>("Password", password),
                    new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Login")),
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/Login", content);
            responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains(string.Format("Hello {0}!", email), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(IdentityCookieName));
            _logger.LogInformation("Successfully signed in with user '{email}'", email);
        }

        public async Task ChangePassword(string email)
        {
            var response = await DoGetAsync("Manage/ChangePassword");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("OldPassword", "Password~1"),
                    new KeyValuePair<string, string>("NewPassword", "Password~2"),
                    new KeyValuePair<string, string>("ConfirmPassword", "Password~2"),
                    new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Manage/ChangePassword")),
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Manage/ChangePassword", content);
            responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains("Your password has been changed.", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(IdentityCookieName));
            _logger.LogInformation("Successfully changed the password for user '{email}'", email);
        }

        public async Task<string> CreateAlbum()
        {
            var albumName = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12);
            _logger.LogInformation("Trying to create an album with name '{album}'", albumName);
            var response = await DoGetAsync("Admin/StoreManager/create");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Admin/StoreManager/create")),
                    new KeyValuePair<string, string>("GenreId", "1"),
                    new KeyValuePair<string, string>("ArtistId", "1"),
                    new KeyValuePair<string, string>("Title", albumName),
                    new KeyValuePair<string, string>("Price", "9.99"),
                    new KeyValuePair<string, string>("AlbumArtUrl", "http://myapp/testurl"),
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Admin/StoreManager/create", content);
            responseContent = await response.Content.ReadAsStringAsync();
            Assert.Equal<string>(_deploymentResult.ApplicationBaseUri + "Admin/StoreManager", response.RequestMessage.RequestUri.AbsoluteUri);
            Assert.Contains(albumName, responseContent);
            _logger.LogInformation("Successfully created an album with name '{album}' in the store", albumName);
            return albumName;
        }

        public async Task<string> FetchAlbumIdFromName(string albumName)
        {
            // Run some CORS validation.
            _logger.LogInformation("Fetching the album id of '{album}'", albumName);
            _httpClient.DefaultRequestHeaders.Add("Origin", "http://notpermitteddomain.com");
            var response = await DoGetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", albumName));
            await ThrowIfResponseStatusNotOk(response);
            IEnumerable<string> values;
            Assert.False(response.Headers.TryGetValues("Access-Control-Allow-Origin", out values));

            _httpClient.DefaultRequestHeaders.Remove("Origin");
            _httpClient.DefaultRequestHeaders.Add("Origin", "http://example.com");
            response = await DoGetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", albumName));
            await ThrowIfResponseStatusNotOk(response);
            Assert.Equal("http://example.com", response.Headers.GetValues("Access-Control-Allow-Origin").First());
            _httpClient.DefaultRequestHeaders.Remove("Origin");

            var albumId = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("Album id for album '{album}' is '{id}'", albumName, albumId);
            return albumId;
        }

        public async Task VerifyAlbumDetails(string albumId, string albumName)
        {
            _logger.LogInformation("Getting details of album with Id '{id}'", albumId);
            var response = await DoGetAsync(string.Format("Admin/StoreManager/Details?id={0}", albumId));
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains(albumName, responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("http://myapp/testurl", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains(PrefixBaseAddress(string.Format("Edit", "{0}", albumId)), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains(PrefixBaseAddress("Back to List"), responseContent, StringComparison.OrdinalIgnoreCase);
        }

        public async Task VerifyStatusCodePages()
        {
            _logger.LogInformation("Getting details of a non-existing album with Id '-1'");
            var response = await DoGetAsync("Admin/StoreManager/Details?id=-1");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains("Item not found.", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Equal(PrefixBaseAddress("/{0}/Home/StatusCodePage"), response.RequestMessage.RequestUri.AbsolutePath);
        }

        // This gets the view that non-admin users get to see.

        public async Task GetAlbumDetailsFromStore(string albumId, string albumName)
        {
            _logger.LogInformation("Getting details of album with Id '{id}'", albumId);
            var response = await DoGetAsync(string.Format("Store/Details/{0}", albumId));
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains(albumName, responseContent, StringComparison.OrdinalIgnoreCase);
        }

        public async Task AddAlbumToCart(string albumId, string albumName)
        {
            _logger.LogInformation("Adding album id '{albumId}' to the cart", albumId);
            var response = await DoGetAsync(string.Format("ShoppingCart/AddToCart?id={0}", albumId));
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains(albumName, responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("", responseContent, StringComparison.OrdinalIgnoreCase);
            _logger.LogInformation("Verified that album is added to cart");
        }

        public async Task CheckOutCartItems()
        {
            _logger.LogInformation("Checking out the cart contents...");
            var response = await DoGetAsync("Checkout/AddressAndPayment");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();

            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Checkout/AddressAndPayment")),
                    new KeyValuePair<string, string>("FirstName", "FirstNameValue"),
                    new KeyValuePair<string, string>("LastName", "LastNameValue"),
                    new KeyValuePair<string, string>("Address", "AddressValue"),
                    new KeyValuePair<string, string>("City", "Redmond"),
                    new KeyValuePair<string, string>("State", "WA"),
                    new KeyValuePair<string, string>("PostalCode", "98052"),
                    new KeyValuePair<string, string>("Country", "USA"),
                    new KeyValuePair<string, string>("Phone", "PhoneValue"),
                    new KeyValuePair<string, string>("Email", "email@email.com"),
                    new KeyValuePair<string, string>("PromoCode", "FREE"),
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Checkout/AddressAndPayment", content);
            responseContent = await response.Content.ReadAsStringAsync();
            Assert.Contains("
Checkout Complete
", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.StartsWith(_deploymentResult.ApplicationBaseUri + "Checkout/Complete/", response.RequestMessage.RequestUri.AbsoluteUri, StringComparison.OrdinalIgnoreCase);
        }

        public async Task DeleteAlbum(string albumId, string albumName)
        {
            _logger.LogInformation("Deleting album '{album}' from the store..", albumName);

            var formParameters = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("id", albumId)
                };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            var response = await DoPostAsync("Admin/StoreManager/RemoveAlbum", content);
            await ThrowIfResponseStatusNotOk(response);

            _logger.LogInformation("Verifying if the album '{album}' is deleted from store", albumName);
            response = await DoGetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", albumName));
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.LogInformation("Album '{album}' with id '{Id}' is successfully deleted from the store.", albumName, albumId);
        }

        private async Task ThrowIfResponseStatusNotOk(HttpResponseMessage response)
        {
            if (response.StatusCode != HttpStatusCode.OK)
            {
                LogHeaders(response, LogLevel.Information);
                var content = await response.Content.ReadAsStringAsync();
                _logger.LogError("Content: Length={0}\n{1}", content.Length, content);
                throw new Exception(string.Format("Received the above response with status code : {0}", response.StatusCode));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Drupal\statistics\Plugin\migrate\destination;

use Drupal\Core\Database\Connection;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\Plugin\migrate\destination\DestinationBase;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Destination for node counter.
 *
 * @MigrateDestination(
 *   id = "node_counter",
 *   destination_module = "statistics"
 * )
 */
class NodeCounter extends DestinationBase implements ContainerFactoryPluginInterface {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * Constructs a node counter plugin.
   *
   * @param array $configuration
   *   Plugin configuration.
   * @param string $plugin_id
   *   The plugin ID.
   * @param mixed $plugin_definition
   *   The plugin definition.
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   *   The current migration.
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, Connection $connection) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
    $this->connection = $connection;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $migration,
      $container->get('database')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return ['nid' => ['type' => 'integer']];
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return [
      'nid' => $this->t('The ID of the node to which these statistics apply.'),
      'totalcount' => $this->t('The total number of times the node has been viewed.'),
      'daycount' => $this->t('The total number of times the node has been viewed today.'),
      'timestamp' => $this->t('The most recent time the node has been viewed.'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function import(Row $row, array $old_destination_id_values = []) {
    $nid = $row->getDestinationProperty('nid');
    $daycount = $row->getDestinationProperty('daycount');
    $totalcount = $row->getDestinationProperty('totalcount');
    $timestamp = $row->getDestinationProperty('timestamp');

    $this->connection
      ->merge('node_counter')
      ->key('nid', $nid)
      ->fields([
        'daycount' => $daycount,
        'totalcount' => $totalcount,
        'timestamp' => $timestamp,
      ])
      ->expression('daycount', '[daycount] + :daycount', [':daycount' => $daycount])
      ->expression('totalcount', '[totalcount] + :totalcount', [':totalcount' => $totalcount])
      // Per Drupal policy: "A query may have any number of placeholders, but
      // all must have unique names even if they have the same value."
      // https://www.drupal.org/docs/8/api/database-api/static-queries#placeholders
      ->expression('timestamp', 'CASE WHEN [timestamp] > :timestamp1 THEN [timestamp] ELSE :timestamp2 END', [':timestamp1' => $timestamp, ':timestamp2' => $timestamp])
      ->execute();

    return [$row->getDestinationProperty('nid')];
  }

}


text:
package org.javers.repository.sql.schema;

import org.polyjdbc.core.PolyJDBC;
import org.polyjdbc.core.dialect.Dialect;
import org.polyjdbc.core.schema.*;
import org.polyjdbc.core.schema.model.Schema;
import org.polyjdbc.core.util.TheCloser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author bartosz walacik
 */
public class JaversSchemaManager {
    private static final Logger logger = LoggerFactory.getLogger(JaversSchemaManager.class);

    private SchemaInspector schemaInspector;
    private SchemaManager schemaManager;
    private final Dialect dialect;
    private final FixedSchemaFactory schemaFactory;
    private final PolyJDBC polyJDBC;

    public JaversSchemaManager(Dialect dialect, FixedSchemaFactory fixedSchemaFactory, PolyJDBC polyJDBC) {
        this.dialect = dialect;
        this.schemaFactory = fixedSchemaFactory;
        this.polyJDBC = polyJDBC;
    }

    public void ensureSchema() {
        this.schemaInspector = polyJDBC.schemaInspector();
        this.schemaManager = polyJDBC.schemaManager();

        for (Map.Entry<String, Schema> e : schemaFactory.allTablesSchema(dialect).entrySet()){
            ensureTable(e.getKey(), e.getValue());
        }

        TheCloser.close(schemaManager, schemaInspector);
    }

    private void ensureTable(String tableName, Schema schema){
        if (schemaInspector.relationExists(tableName)) {
            return;
        }
        logger.info("creating javers table {} ...", tableName);
        schemaManager.create(schema);
    }

    public void dropSchema(){
        throw new RuntimeException("not implemented");
    }
}


text:
package wint.mvc.flow;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.List;

/**
 * User: longyi
 * Date: 13-9-3
 * Time: 上午9:50
 */
public class ServletHttpSession implements Session {

    private HttpSession httpSession;

    public ServletHttpSession(HttpSession httpSession) {
        this.httpSession = httpSession;
    }

    public void setAttribute(String name, Object value) {
        httpSession.setAttribute(name, value);
    }

    public Object getAttribute(String name) {
        return httpSession.getAttribute(name);
    }

    public void removeAttribute(String name) {
        httpSession.removeAttribute(name);
    }

    public String getId() {
        return httpSession.getId();
    }

    public List<String> getAttributeNames() {
        return (List<String>)Collections.list(httpSession.getAttributeNames());
    }
}


text:
var mongoose = require('mongoose');

// define the schema for our user model
var medSchema = mongoose.Schema({
    _id: Number,
    name : String

});

// create the model for users and expose it to our app
module.exports = mongoose.model('medicines', medSchema);


text:
use strict;
use Bio::KBase::ObjectAPI::KBaseFBA::DB::FBAReactionVariable;
package Bio::KBase::ObjectAPI::KBaseFBA::FBAReactionVariable;
use Moose;
use namespace::autoclean;
extends 'Bio::KBase::ObjectAPI::KBaseFBA::DB::FBAReactionVariable';
#***********************************************************************************************************
# ADDITIONAL ATTRIBUTES:
#***********************************************************************************************************
has reactionID => ( is => 'rw', isa => 'Str',printOrder => '1', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildreactionID');
has reactionName => ( is => 'rw', isa => 'Str',printOrder => '2', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildreactionName');

#***********************************************************************************************************
# BUILDERS:
#***********************************************************************************************************
sub _buildreactionID {
	my ($self) = @_;
	return $self->modelreaction()->reaction()->id();
}
sub _buildreactionName {
	my ($self) = @_;
	return $self->modelreaction()->reaction()->name();
}

#***********************************************************************************************************
# CONSTANTS:
#***********************************************************************************************************

#***********************************************************************************************************
# FUNCTIONS:
#***********************************************************************************************************

=head3 clearProblem

Definition:
	Output = Bio::KBase::ObjectAPI::KBaseFBA::FBAModel->clearProblem();
	Output = {
		success => 0/1
	};
Description:
	Builds the FBA problem

=cut

__PACKAGE__->meta->make_immutable;
1;


text:
const NwBuilder = require( "nw-builder" );
const cdpConnection = require( "../common/cdp/cdpConnection" );
const cdpTestReporterQUnit = require( "../common/cdp/cdpTestReporterQUnit" );

const nwjsTaskOptions = require( "../configs/nwjs" ).options;
const currentPlatform = require( "../common/platforms" ).getPlatforms( [] );

module.exports = function( grunt ) {
	const task = "runtest";
	const descr = "Run the tests in NW.js";

	grunt.registerTask( task, descr, function() {
		const done = this.async();
		const options = this.options({
			startTimeout: 10000,
			testTimeout: 300000,
			host: "localhost",
			port: 8000
		});
		const isCoverage = !!this.flags.coverage;

		const nwjsOptions = Object.assign( {}, grunt.config.process( nwjsTaskOptions ), {
			platforms: currentPlatform,
			argv: [ `--remote-debugging-port=${options.port}` ],
			files: options.path,
			flavor: "sdk"
		});
		const nwjs = new NwBuilder( nwjsOptions );

		function kill() {
			if ( nwjs.isAppRunning() ) {
				const appProcess = nwjs.getAppProcess();

				// workaround for the close event log message
				appProcess.removeAllListeners( "close" );
				nwjs._nwProcess = undefined;

				// now kill the child process
				appProcess.kill();

				grunt.log.debug( "NW.js stopped" );
				process.removeListener( "exit", kill );
			}
		}

		function fail( err ) {
			kill();
			if ( err ) {
				grunt.fail.fatal( String( err ) );
			} else {
				grunt.util.exit( 1 );
			}
		}

		new Promise( ( resolve, reject ) => {
			process.on( "exit", kill );

			nwjs.on( "log", grunt.log.writeln.bind( grunt.log ) );
			nwjs.on( "stdout", grunt.log.writeln.bind( grunt.log ) );
			nwjs.on( "stderr", grunt.log.writeln.bind( grunt.log ) );

			// listen for the appstart event
			nwjs.on( "appstart", () => {
				grunt.log.debug( "NW.js started" );

				const nwjsProcess = nwjs.getAppProcess();
				nwjsProcess.on( "close", () => {
					reject( "NW.js exited prematurely" );
				});

				// connect to NW.js
				cdpConnection( options )
					.then( cdp => {
						grunt.log.debug( `Connected to ${options.host}:${options.port}` );

						// set up and start QUnit
						return cdpTestReporterQUnit( grunt, options, cdp, isCoverage );
					})
					// resolve on a successful test run
					.then( resolve, reject );
			});

			grunt.log.debug( "Starting NW.js..." );

			// start the NW.js process (or download NW.js first)
			// reject if NW.js exited prematurely
			nwjs.run().then( reject, reject );
		})
			// make sure to terminate the NW.js process
			.then( noShutdown => {
				if ( noShutdown !== true ) {
					kill();
				}
			})
			.then( done, fail );
	});
};


text:
git submodule update --init --recursive
git clone --depth 1 https://github.com/bytecodealliance/wasmtime-libfuzzer-corpus wasmtime-libfuzzer-corpus

# Note: This project creates Rust fuzz targets exclusively

build() {
  project=$1
  shift
  fuzzer_prefix=$1
  shift
  fuzz_targets=$1
  shift
  fuzz_target_path=$1
  shift
  PROJECT_DIR=$SRC/$project

  # ensure we get absolute paths for the coverage report
  cd $PROJECT_DIR
  crate_src_abspath=`cargo metadata --no-deps --format-version 1 | jq -r '.workspace_root'`
  while read i; do
    export RUSTFLAGS="$RUSTFLAGS --remap-path-prefix $i=$crate_src_abspath/$i"
  done <<< "$(find . -name "*.rs" | cut -d/ -f2 | uniq)"

  cd $PROJECT_DIR/fuzz && cargo fuzz build --strip-dead-code -O --debug-assertions "$@"

  FUZZ_TARGET_OUTPUT_DIR=$PROJECT_DIR/$fuzz_target_path/x86_64-unknown-linux-gnu/release

  if [ "x$fuzz_targets" = "x" ]; then
      fuzz_targets=$PROJECT_DIR/fuzz/fuzz_targets/*.rs
  fi

  for f in $fuzz_targets; do
      src_name=$(basename ${f%.*})
      dst_name=$fuzzer_prefix$src_name
      cp $FUZZ_TARGET_OUTPUT_DIR/$src_name $OUT/$dst_name

      if [[ -d $SRC/wasmtime/wasmtime-libfuzzer-corpus/$dst_name/ ]]; then
          zip -jr \
              $OUT/${dst_name}_seed_corpus.zip \
              $SRC/wasmtime/wasmtime-libfuzzer-corpus/$dst_name/
      fi

      if [[ -f $SRC/$dst_name.options ]]; then
        cp $SRC/$dst_name.options $OUT/$dst_name.options
      else
        cp $SRC/default.options $OUT/$dst_name.options
      fi
  done
}

# Ensure OCaml environment is set up prior to Wasmtime build.
eval $(opam env)

build wasmtime "" "" target
build wasm-tools wasm-tools- "" target --features wasmtime
build regalloc2 regalloc2- ion_checker fuzz/target

# In coverage builds copy the opam header files into the output so coverage can
# find the source files.
if [ "$SANITIZER" = "coverage" ]; then
  cp --recursive --dereference --no-preserve mode,ownership --parents \
    $HOME/.opam/4.11.2/lib/ocaml $OUT
fi


text:
{% extends "aldryn_events/plugins/upcoming/base.html" %}
{% load i18n %}

{% block plugin %}

        {% if plugin_configuration_error %}
            {% if request.user.is_staff or request.user.is_superuser %}

{{ plugin_configuration_error }}

            {% endif %}
        {% else %}

                {% for event in events %}

                        {{ event.get_title }}
                         {{ event.start|date }}

                {% empty %}

{% trans "No items available" %}

                {% endfor %}

        {% endif %}

{% endblock plugin %}


text:
const initialState = {
  location: null,
  date: { pickUp: null, dropOff: null },
  time: { pickUp: '12:00', dropOff: '12:00' },
};

const SearchReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'SET_PICK_UP_LOCATION':
      return Object.assign({}, state, {
        location: action.payload,
      });
    case 'SET_PICK_UP_DATE':
      return Object.assign({}, state, {
        date: Object.assign({}, state.date, { pickUp: action.payload }),
      });
    case 'SET_DROP_OFF_DATE':
      return Object.assign({}, state, {
        date: Object.assign({}, state.date, { dropOff: action.payload }),
      });
    case 'SET_PICK_UP_TIME':
      return Object.assign({}, state, {
        time: Object.assign({}, state.time, { pickUp: action.payload }),
      });
    case 'SET_DROP_OFF_TIME':
      return Object.assign({}, state, {
        time: Object.assign({}, state.time, { dropOff: action.payload }),
      });
    default:
      return state;
  }
};

export default SearchReducer;


text:
var $parkWrapper = $('[data-park="wrapper"]'); // this variable will be a link to our calendar wrapper

function AddTable(){    //Here we add clear tables for each level
    var dfr = $.Deferred();
    for (let l = 0; l < Data.info.levels.length; l++){
        var level = Data.info.levels[l];
        let result = '
Level '+(l+1)+'
\

';

        //let's draw time scale
        result += '

';
        for (let time = 0; time < 24; time++){
            result += '
'+time+':00
';
        }
        result += '

';

        //and now it's slots time
        result += '
\

';
        for (let time = 0; time < 24; time++){
            result += '
'
            for (let i = 0; i < level.slotsLength; i++){
                    result += '	'; //this one is for "calendar"
            }
            result+= '
';
        }
        result += '
\

\

\

\

';
        $parkWrapper.append(result);
    }
    dfr.resolve();
    return dfr;
}

function AddVehicle(level, slot, type, plate, sTime, eTime) {
    var typeClass = type == 2 ? "moto" : '',
        cellWidth = Tools.tableCell.width,
        cellHeight = Tools.tableCell.height,
        leftPos = cellWidth * slot,
        half = 0;
    //checking if data is coorect
    sTime = sTime < 0 ? 0 : sTime;
    eTime = eTime > 1440 ? 1440 : eTime;
    var topPos = Tools.tableMinute * sTime,
        duration = (eTime - sTime) < 60 ? 60 : (eTime - sTime), //this parameter must be used only for rendering!!!
        height = Tools.tableMinute * duration;
    if (type != 2){
        $('[data-park="tab_wrap"][data-level="'+level+'"] [data-park="vehicles"]').append('\

\
        '+plate+'
');
    }else { // if the vehicle type is motorcycle
        //looking if the any motorcycle already stands on this slot using data-attrs

        $('.component_vehicle[data-veh-type="2"][data-mlevel="'+level+'"][data-mslot="'+slot+'"]').each((ind,motoObj) => {
            let start = Math.floor($(motoObj).attr('data-mstart')),
                end = Math.floor($(motoObj).attr('data-mend')),
                place = $(motoObj).attr('data-half');
            if (((sTime >= start && sTime < end) || (eTime > start && eTime <= end)) && place == 0) {
//                neib++;
                if (place == 0){
                    leftPos += cellWidth * .5;
                    typeClass = "moto second";
                    half = 1;
                }
            }
        });

        //and now rendering moto vehicle
        $('[data-park="tab_wrap"][data-level="'+level+'"] [data-park="vehicles"]').append('\

\
        '+plate+'
');
    }
}

function CurrentTime() {
    $('.current_time').each((i,ct) => {
        $(ct).outerWidth((Data.info.levels[i].slotsLength + 1) * Tools.tableCell.width - 30); //calculating the width
    });

    var SetTimeLine = () => {
        var d = new Date(),
            minutes = d.getHours() * 60 + d.getMinutes();

        //calculates the time line position using the whole height of table and the line's height
        var yPos = Tools.tableMinute * minutes - 2;

        //and positions it
        $('.current_time').css({top: yPos});
    }
    SetTimeLine();
    var timeLineAnima = setInterval(SetTimeLine(), 60000); //update its position every minute
}

//open-close table accordion
$(document).on('click', '.level_head_button', function(event){ //here fat arrow is not used because I need the right scope to use THIS
    var level = $(this).attr('data-level'); //it should be string type
    if ($('.tabs_wrap[data-level="'+level+'"]').hasClass('active')) $('.tabs_wrap[data-level="'+level+'"]').removeClass('active');
    else $('.tabs_wrap[data-level="'+level+'"]').addClass('active');
    if ($(this).hasClass('active')) $(this).removeClass('active');
    else $(this).addClass('active');
});


text:
<?php namespace Fisharebest\Localization\Language;

use Fisharebest\Localization\PluralRule\PluralRule1;
use Fisharebest\Localization\Territory\TerritoryMw;

class LanguageNy extends AbstractLanguage implements LanguageInterface {
	public function code() {
		return 'ny';
	}

	public function defaultTerritory() {
		return new TerritoryMw;
	}

	public function pluralRule() {
		return new PluralRule1;
	}
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="40dp"
    android:height="40dp"
    android:viewportWidth="40"
    android:viewportHeight="40"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M25,32.167 L14.583,21.75H3V18.25H14.583L25,7.833L37.167,20Z"/>
</vector>


text:
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "size".
 *
 * @property integer $id
 * @property integer $product_id
 * @property string $size
 * @property string $description
 *
 * @property OrderProduct[] $orderProducts
 * @property Product $product
 */
class Size extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'size';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id', 'size', 'description'], 'required'],
            [['product_id'], 'integer'],
            [['size', 'description'], 'string', 'max' => 255],
            [['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'product_id' => 'Product ID',
            'size' => 'Size',
            'description' => 'Description',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrderProducts()
    {
        return $this->hasMany(OrderProduct::className(), ['size_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProduct()
    {
        return $this->hasOne(Product::className(), ['id' => 'product_id']);
    }
}


text:
=begin rdoc

== Overview
Install Open Source tripwire

== Usage

    tripwire do
      root_dir "/usr/wpt" # CHANGE THIS to something obscure. The idea is you *dont* want tripwire to be in a standard location.
      mailto   "admin@emaildomain"
      smtp_settings "host", "username", "password"
    end

== BUGS

* It doesn't yet actually use the email settings in a cron job
* It wont re-write your policy when your template changes unless you manually rm #{root_dir}/etc/tw.pol - this is a todo

== NOTES

When you configure this will copy your password to /tmp/tripwire_password and
then rm it when done. This may cause problems when nodes provision each other.

== References
* http://linuxgazette.net/107/tag/4.html
* http://www.linuxhelp.net/guides/tripwire/
=end

PoolParty::Resources::FileResource.searchable_paths << File.dirname(__FILE__)+'/templates/'

module PoolParty
  module Resources
    class Tripwire < Resource
      dsl_methods :root_dir,
                  :mailto

      def after_loaded(o={}, &block)
        do_once do
          install_from_src
        end
      end

      def install_from_src
        base_requirements
        install_dependencies
        download
        password_file
        configure_and_build
        write_policy
        initialize_database
        cleanup_password_files
      end

      def smtp_settings host, username, password, port=25
        has_variable "tripwire_smtp_settings", true
        @smtp_settings ||= {:host => host, :username => username, :password => password, :port => port}
        %w{host username password port}.each do |setting|
          has_variable "tripwire_smtp_#{setting}", eval(setting)
        end
      end

      private
      def base_requirements
        has_directory src_dir
        has_directory "/tmp"
      end

      def install_dependencies
        has_package "expect"
      end

      def download
        has_exec "download_tripwire",
          :command => "wget http://softlayer.dl.sourceforge.net/sourceforge/tripwire/tripwire-2.4.1.2-src.tar.bz2 -O /usr/local/src/tripwire-2.4.1.2-src.tar.bz2",
          :not_if => "test -e /usr/local/src/tripwire-2.4.1.2-src.tar.bz2"

        has_exec "unpack_tripwire",
          :command => "cd /usr/local/src && tar -xvvf /usr/local/src/tripwire-2.4.1.2-src.tar.bz2",
          :not_if => "test -d #{tripwire_src}",
          :requires => get_exec("download_tripwire")
      end

      def configure_and_build
        raise "tripwire requires a root_dir to be specified. Try using the `root_dir` directive to specify an arbitrary directory to install tripwire in" unless root_dir
        has_directory root_dir
        has_exec "configure_tripwire",
          :command => "cd #{tripwire_src} && ./configure --prefix=#{root_dir}",
          :requires => get_exec("unpack_tripwire"),
          :not_if => "test -e #{tripwire_src}/Makefile"

        has_exec "make_tripwire",
          :command => "cd #{tripwire_src} && make",
          :requires => get_exec("configure_tripwire"),
          :not_if => "test -e #{tripwire_src}/bin/tripwire"

        has_file :name => "#{tripwire_src}/install/install.cfg", :mode => "0644", :template => "install.cfg.erb" do
          requires get_exec("make_tripwire")
        end
        has_file :name => "#{tripwire_src}/make-install-tripwire.tcl", :mode => "0755", :template => "make-install-tripwire.tcl.erb" do
          requires get_exec("make_tripwire")
        end

        # TODO ----------- this is a huge security hole b/c it leaves the
        # password all over the place. todo figure this one out
        has_exec "touch_password",
          :not_if => "test -e #{root_dir}/etc/tw.cfg",
          :command => "cd #{tripwire_src} && /usr/bin/expect make-install-tripwire.tcl #{site_password_unix_line} #{local_password_unix_line}",
          :requires => get_exec("make_tripwire")

        has_file :name => "#{root_dir}/etc/twcfg.txt", :mode => "0644", :template => "twcfg.txt.erb", :requires => get_exec("make_tripwire")
        has_file :name => "#{root_dir}/etc/twpol.txt", :mode => "0644", :template => "twpol.txt.erb", :requires => get_exec("make_tripwire")
      end

      def write_policy
        has_exec "cd #{root_dir} && echo #{site_password_unix_line} | ./sbin/twadmin --create-polfile #{root_dir}/etc/twpol.txt",
          :not_if => "test -e #{root_dir}/etc/tw.pol" # really this should be only if twpol.txt changed (todo)
      end

      def initialize_database
        has_exec "cd #{root_dir} && echo #{local_password_unix_line} | ./sbin/tripwire --init",
          :not_if => "test -e #{root_dir}/lib/tripwire/\`hostname\`.twd",
          :requires => get_exec("make_tripwire")
      end

      def src_dir
        "/usr/local/src"
      end

      def tripwire_src
        "/usr/local/src/tripwire-2.4.1.2-src"
      end

      def ideas
         # chkrootkit
         # wget ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz
         # tar -xzvf chkrootkit.tar.gz
         # cd chkrootkit-version (whatever version is)
         # ./chkrootkit
      end

      # todo
      def site_password_unix_line
        '`cat /tmp/tripwire_password | head -n 1`'
      end

      # todo
      def local_password_unix_line
        '`cat /tmp/tripwire_password | tail -n 1`'
      end

      def check
        # #{root_dir}/sbin/tripwire --check > /tmp/report.txt
      end

      def password_file
        users_template = File.expand_path(File.dirname(clouds_dot_rb_file)/:templates/:tripwire/"tripwire_passwords")
        unless File.exists?(users_template)
          puts "***** WARNING #{users_template} does not exist. This is required to use the tripwire plugin. the format is the site password on the first line and local password in the second"
        end
        has_file :name => "/tmp/tripwire_password", :mode => "0644", :template => users_template
      end

      def cleanup_password_files
        %w{
           /tmp/tripwire_password
           /var/poolparty/dr_configure/etc/poolparty/secure/templates/tripwire/tripwire_passwords
           /var/poolparty/dr_configure/chef/cookbooks/poolparty/templates/default/tmp/tripwire_password.erb
          }.each do |dirty|
          has_exec "rm -f #{dirty}", :only_if => "test -e #{dirty}"
        end
      end

    end
  end
end


text:
const test = require('tape')
const loadDatabase = require('../../lib/load-database')

test('loads database', assert => {
  const e = {
    config: {
      databasePath: `${__dirname}/database.json`
    }
  }

  loadDatabase(e)

  assert.equal(e.db.entries instanceof Array, true, 'Database is loaded')

  assert.end()
})

test('empty object when database file not yet exists', assert => {
  const e = {
    config: {
      databasePath: `${__dirname}/not-exists.json`
    }
  }

  loadDatabase(e)

  assert.same(e.db, {}, 'Empty database fallback')

  assert.end()
})


text:
/// <reference path='fourslash.ts' />

// Should give completions for directories that are merged via the rootDirs compiler option

// @rootDirs: /sub/src1,/src2

// @Filename: /src2/test0.ts
//// import * as foo1 from "./mo/*import_as0*/
//// import foo2 = require("./mo/*import_equals0*/
//// var foo3 = require("./mo/*require0*/

// @Filename: /src2/inner/inner0.ts
////import * as s from ".//*inner*/";

// @Filename: /src2/inner/inner1.ts
////export const x = 0;

// @Filename: /src2/module0.ts
//// export var w = 0;

// @Filename: /sub/src1/module1.ts
//// export var x = 0;

// @Filename: /sub/src1/module2.ts
//// export var y = 0;

// @Filename: /sub/src1/more/module3.ts
//// export var z = 0;

// @Filename: f1.ts
////
// @Filename: f2.tsx
////
// @Filename: folder/f1.ts
////
// @Filename: f3.js
////
// @Filename: f4.jsx
////
// @Filename: e1.ts
////
// @Filename: e2.js
////

verify.completions(
    {
        marker: ["import_as0", "import_equals0", "require0"],
        exact: ["module1", "module2", "more", "module0", "inner"],
        isNewIdentifierLocation: true,
    },
    {
        marker: "inner",
        exact: "inner1",
        isNewIdentifierLocation: true,
    }
);


text:
package de.dqi11.quickStarter;

import de.dqi11.quickStarter.controller.MainController;

/**
 * The main-class.
 */
public class Main {

	/**
	 * Applications entry-point.
	 *
	 * @param args ignored
	 */
	public static void main(String[] args) {
		new MainController();
	}
}


text:
package com.calsoft.task.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import com.calsoft.task.dao.SaveTaskDao;
import com.calsoft.task.dao.factory.SaveTaskDaoFactory;
import com.calsoft.task.form.TaskForm;
import com.calsoft.task.model.Task;
import com.calsoft.user.model.User;
import com.calsoft.util.TimeConveterUtil;
import com.calsoft.util.TimeUtility;

@SuppressWarnings({"rawtypes", "deprecation"})
public class SaveTaskServiceImpl implements SaveTaskService {

	@Override
	public String[] saveTask (TaskForm taskForm,int userid) throws Exception{
		Task task=populateTaskFromForm(taskForm,userid);
		SaveTaskDao saveTaskDao=SaveTaskDaoFactory.getSaveTaskDao();
		String[] entryStatus = saveTaskDao.doSaveTask(task);
		return entryStatus;
	}
	public Task populateTaskFromForm(TaskForm taskForm, int userid)throws Exception {
		Task task = null;
		task = new Task();
		task.setBacklog_id(taskForm.getBacklog_id());
		task.setStatus(taskForm.getStatus());
		task.setId(taskForm.getId());
		DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		Date date = (Date) formatter.parse(taskForm.getTask_date());
		task.setTask_date(date);
		task.setTask_description(taskForm.getTask_description());
		User user = new User();
		user.setUser_Id(userid);
		task.setUser(user);
		task.setTask_id(taskForm.getTask_id());
		String time=taskForm.getTime();
		String afterConvertTime=TimeConveterUtil.timeConveter(time);
		task.setTime(afterConvertTime);
		task.setWork_status(taskForm.getWork_status());
		task.setEntry_time(Calendar.getInstance().getTime());
		return task;
	}
	/*public Task populateTaskFromForm1(TaskForm taskForm)throws Exception{
		Task task=null;
		task=new Task();
		DateFormat	formatter = new SimpleDateFormat("MM/dd/yyyy");
		Date date = (Date)formatter.parse(taskForm.getTask_date());
		task.setTask_date(date);
		task.setStatus(taskForm.getStatus());
		task.setTask_description(taskForm.getTask_description());
		task.setBacklog_id(taskForm.getBacklog_id());
		task.setId(taskForm.getId());
		//task.setUser(taskForm.getUser());
		task.setTask_id(taskForm.getTask_id());
		String time=TimeConveterUtil.timeConveter(taskForm.getTime());
		task.setTime(time);
		task.setWork_status(taskForm.getWork_status());
		User user=new User();
		user.setUser_Id(taskForm.getUserId());
		task.setUser(user);
		task.setEntry_time(Calendar.getInstance().getTime());
		return task;
	}*/
	public TaskForm populateTaskFormFromTask(Task task)throws Exception{
		TaskForm taskForm=new TaskForm();
		taskForm.setId(task.getId());
		taskForm.setBacklog_id(task.getBacklog_id());
		taskForm.setStatus(task.getStatus());
		taskForm.setUser(task.getUser());
		DateFormat	formatter = new SimpleDateFormat("MM/dd/yyyy");
		String date = formatter.format(task.getTask_date());
		taskForm.setTask_date(date);
		taskForm.setTask_description(task.getTask_description().replace("`", "'"));   // Modification Done by Prem for replacing ` to ' for displaying.
		taskForm.setTask_id(task.getTask_id());
		taskForm.setTime(task.getTime());
		taskForm.setWork_status(task.getWork_status());
		if(task.getUser()!=null){
			if(task.getUser().getUser_name()!=null&&!(task.getUser().getUser_name().equals(""))){
				taskForm.setUserName(task.getUser().getUser_name());
			}
		}
		return taskForm;
	}
	public TaskForm populateTaskFormFromTaskNew(Task task)throws Exception{
		TaskForm taskForm=new TaskForm();
		taskForm.setId(task.getId());
		taskForm.setBacklog_id(task.getBacklog_id());
		taskForm.setStatus(task.getStatus());
		taskForm.setUser(task.getUser());
		DateFormat	formatter = new SimpleDateFormat("MM/dd/yyyy");
		String date = formatter.format(task.getTask_date());
		taskForm.setTask_date(date);
		taskForm.setTask_description(task.getTask_description().replace("`", "'"));   // Modification Done by Prem for replacing ` to ' for displaying.
		taskForm.setTask_id(task.getTask_id());
		String time = task.getTime().substring(0,task.getTime().lastIndexOf(':'));     // Modification Done by Prem
		taskForm.setTime(time.replace(':', '.'));
		taskForm.setWork_status(task.getWork_status());
		if(task.getUser()!=null){
			if(task.getUser().getUser_name()!=null&&!(task.getUser().getUser_name().equals(""))){
				taskForm.setUserName(task.getUser().getUser_name());
			}
		}
		return taskForm;
	}
	public List<TaskForm> getTaskDetails(String month,int userId) throws Exception {
		List<TaskForm> taskFormList=new ArrayList<TaskForm>();
		SaveTaskDao saveTaskDao=SaveTaskDaoFactory.getSaveTaskDao();
		List<Task> eList = saveTaskDao.getTaskDetails(month,userId);
		Iterator<Task> itr=eList.iterator();
		while(itr.hasNext()){
			Task task = itr.next();
			TaskForm taskForm = populateTaskFormFromTask(task);
			taskFormList.add(taskForm);
		}
		return taskFormList;
	}
	public boolean doDelete(int taskId) {
		boolean flag = false;
		try {
			SaveTaskDao saveTaskDao=SaveTaskDaoFactory.getSaveTaskDao();
			flag = saveTaskDao.doDelete(taskId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	@Override
	public List<TaskForm> editTask(int id) throws Exception{
		List<TaskForm> taskFormList=new ArrayList<TaskForm>();
		SaveTaskDao saveTaskDao=SaveTaskDaoFactory.getSaveTaskDao();
		List<Task> taskList=saveTaskDao.editTask(id);
		Iterator itr=taskList.iterator();
		while(itr.hasNext())
		{
			Task task=(Task)itr.next();
			TaskForm taskForm=populateTaskFormFromTask(task);
			taskFormList.add(taskForm);
		}
		return taskFormList;
	}

	@Override
	public String editsaveTask(TaskForm taskForm,int id,int userId) throws Exception{
		String entryStatus = null;
		Task task = populateTaskFromForm(taskForm, userId);
		SaveTaskDao saveTaskDao=SaveTaskDaoFactory.getSaveTaskDao();
		entryStatus = saveTaskDao.editSaveTask(task,id,userId);
		return entryStatus;
	}
	@Override
	public List<TaskForm> getTaskDetailsUser(String[] allocatedResource,String year,String month) {
		List<List<Task>> supertasklist = new ArrayList<List<Task>>();
		List<TaskForm> superTaskFormList = new ArrayList<TaskForm>();
		DateFormat myFormat = new SimpleDateFormat("MM/yyyy");
		try{
			SaveTaskDao saveTaskDao = SaveTaskDaoFactory.getSaveTaskDao();
			supertasklist = saveTaskDao.getTaskDetailsUser(allocatedResource,year,month);
			Date dt = myFormat.parse(month+"/"+year);
			Date d1 = new Date();
			Iterator<List<Task>> itr = supertasklist.iterator();
			while(itr.hasNext()){
				List<TaskForm> taskFormList = new ArrayList<TaskForm>();
				TaskForm taskForm = new TaskForm();
				List<Task> taskList = itr.next();
				if(!taskList.isEmpty()){
					if(dt.getMonth() == d1.getMonth()){
						List<Task> taskListMissing = TimeUtility.checkDateAndAddMissing(d1, taskList);
						Iterator<Task> itr1 = taskListMissing.iterator();
						while(itr1.hasNext()){
							TaskForm taskform1 = populateTaskFormFromTaskNew(itr1.next());
							taskFormList.add(taskform1);
						}
						taskForm.setTaskFormList(taskFormList);
						if(taskFormList.size() > 0){
							superTaskFormList.add(taskForm);
						}
					}
					else{
						Calendar calendar = new GregorianCalendar(Integer.parseInt(year),Integer.parseInt(month)-1 , Calendar.DAY_OF_MONTH);
						calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
						List<Task> taskListMissing = TimeUtility.checkDateAndAddMissing(calendar.getTime(), taskList);
						Iterator<Task> itr1=taskListMissing.iterator();
						while(itr1.hasNext()){
							TaskForm taskform1 = populateTaskFormFromTaskNew(itr1.next());
							taskFormList.add(taskform1);
						}
						taskForm.setTaskFormList(taskFormList);
						if(taskFormList.size()>0){
							superTaskFormList.add(taskForm);
						}
					}
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return superTaskFormList;
	}
	@Override
	public List<String> saveAllTask(List<TaskForm> listForm, int userId) throws Exception {
		//iterate the form and convert into list of pojo
		List<String> mess = new ArrayList<String>();
		List<Task> taskList = new ArrayList<Task>();
		if(listForm!=null){
			for (TaskForm taskForm : listForm) {
				Task task = populateTaskFromForm(taskForm, userId);
				taskList.add(task);
			}
		}
		SaveTaskDao saveTaskDao=SaveTaskDaoFactory.getSaveTaskDao();
		mess = saveTaskDao.saveAllTask(taskList);
		return mess;
	}
	@Override
	public List<TaskForm> getTaskDetailsTeamWise(String[] detailsTeam, String year, String month, int user_id) throws Exception {
		List<List<Task>> supertasklist=new ArrayList<List<Task>>();
		List<TaskForm> superTaskFormList=new ArrayList<TaskForm>();
		try{
			SaveTaskDao saveTaskDao = SaveTaskDaoFactory.getSaveTaskDao();
			supertasklist = saveTaskDao.getTaskDetailsTeamWise(detailsTeam, year, month, user_id);
			Iterator<List<Task>> itr=supertasklist.iterator();
			while(itr.hasNext()){
				List<TaskForm> taskFormList=new ArrayList<TaskForm>();
				TaskForm taskForm=new TaskForm();
				List<Task> taskList=itr.next();
				DateFormat myFormat = new SimpleDateFormat("MM/yyyy");
				Date dt = myFormat.parse(month+"/"+year);
				if(!taskList.isEmpty()){
					Date d1 = new Date();
					if(dt.getMonth()==d1.getMonth()){
						List<Task> taskListMissing = TimeUtility.checkDateAndAddMissing(d1, taskList);
						Iterator<Task> itr1=taskListMissing.iterator();
						while(itr1.hasNext()){
							TaskForm taskform1=populateTaskFormFromTaskNew(itr1.next());
							taskFormList.add(taskform1);
						}
						taskForm.setTaskFormList(taskFormList);
						if(taskFormList.size()>0){
							superTaskFormList.add(taskForm);
						}
					}
					else{
						Calendar calendar = new GregorianCalendar(Integer.parseInt(year),Integer.parseInt(month)-1 , Calendar.DAY_OF_MONTH);
						calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
						List<Task> taskListMissing = TimeUtility.checkDateAndAddMissing(calendar.getTime(), taskList);
						Iterator<Task> itr1=taskListMissing.iterator();
						while(itr1.hasNext()){
							TaskForm taskform1=populateTaskFormFromTaskNew(itr1.next());
							taskFormList.add(taskform1);
						}
						taskForm.setTaskFormList(taskFormList);
						if(taskFormList.size()>0){
							superTaskFormList.add(taskForm);
						}
					}
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return superTaskFormList;
	}

	@Override
	public String getResourceLocation(int userId) throws Exception {
		// For getting resource location details.
		String locDetail = "";
		SaveTaskDao saveTaskDao=SaveTaskDaoFactory.getSaveTaskDao();
		locDetail = saveTaskDao.getResourceLocation(userId);
		return locDetail;
	}
	@Override
	public List<String> getMissingDateEntry(List<TaskForm> tList, int userId) throws Exception {
		List<String> listOfDate = new ArrayList<String>();
		DateFormat df = new SimpleDateFormat("dd");
		List<Task> taskList = new ArrayList<Task>();
		for (TaskForm form : tList) {
			Task t1 = populateTaskFromForm(form, userId);
			taskList.add(t1);
		}
		List<Task> missingDateList = TimeUtility.checkDateAndAddMissing(Calendar.getInstance().getTime(), taskList);
		for (Task task : missingDateList) {
			if(task.getTask_description().equalsIgnoreCase("Efforts not entered.")){
				listOfDate.add(df.format(task.getTask_date()));
			}
		}
		return listOfDate;
	}
	@Override
	public String freezeTimesheet(Integer resource_id, Calendar cal) throws Exception {
		// Freezing timesheet entry for current month.
		String freezingStatus = null;
		SaveTaskDao saveTaskDao = SaveTaskDaoFactory.getSaveTaskDao();
		freezingStatus = saveTaskDao.freezeTimesheet(resource_id, cal);
		return freezingStatus;
	}
	@Override
	public String unfreezeTimesheet(Integer resource_id, Calendar cal) throws Exception {
		// unfreezing time entry for current month and all next coming month.
		String unfreezingStatus = null;
		SaveTaskDao saveTaskDao = SaveTaskDaoFactory.getSaveTaskDao();
		unfreezingStatus = saveTaskDao.unfreezeTimesheet(resource_id, cal);
		return unfreezingStatus;
	}
	@Override
	public List<String> getEnteredTimesheetDateForPreviousMonth(Calendar c1, int user_id) {
		// All dates from previous months timesheet entry.
		List<String> allEnteredDates = new ArrayList<String>();
		SaveTaskDao saveTaskDao = SaveTaskDaoFactory.getSaveTaskDao();
		allEnteredDates = saveTaskDao.getEnteredTimesheetDateForPreviousMonth(c1, user_id);
		return allEnteredDates;
	}
}


text:
package org.alicep.collect;

import static java.util.Arrays.setAll;
import static org.alicep.collect.ItemFactory.longs;
import static org.alicep.collect.ItemFactory.strings;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.Supplier;

import org.alicep.benchmark.BenchmarkRunner;
import org.alicep.benchmark.BenchmarkRunner.Benchmark;
import org.alicep.benchmark.BenchmarkRunner.Configuration;
import org.alicep.benchmark.BenchmarkRunner.InterferenceWarning;
import org.junit.runner.RunWith;

import com.google.common.collect.ImmutableList;

@RunWith(BenchmarkRunner.class)
public class KiloSetPerformanceTests<T> {

  static class Config<T> {
    private final Supplier<Set<T>> setFactory;
    private final ItemFactory<T> itemFactory;

    public Config(
        Supplier<Set<T>> setFactory,
        ItemFactory<T> itemFactory) {
      this.setFactory = setFactory;
      this.itemFactory = itemFactory;
    }

    @Override
    public String toString() {
      String setType = setFactory.get().getClass().getSimpleName();
      String itemType = itemFactory.createItem(0).getClass().getSimpleName();
      return setType + "<" + itemType + ">";
    }
  }

  @Configuration
  public static final ImmutableList<Config<?>> CONFIGURATIONS = ImmutableList.of(
      new Config<>(HashSet::new, longs),
      new Config<>(LinkedHashSet::new, longs),
      new Config<>(ArraySet::new, longs),
      new Config<>(HashSet::new, strings),
      new Config<>(LinkedHashSet::new, strings),
      new Config<>(ArraySet::new, strings));

  private final Supplier<Set<T>> setFactory;
  private Set<T> kiloSet;

  @SuppressWarnings("unchecked")
  private final T[] items = (T[]) new Object[1000];
  @SuppressWarnings("unchecked")
  private final T[] hitItems = (T[]) new Object[5000];
  @SuppressWarnings("unchecked")
  private final T[] missItems = (T[]) new Object[5000];

  int i = 0;

  public KiloSetPerformanceTests(Config<T> config) {
    setFactory = config.setFactory;

    setAll(items, config.itemFactory::createItem);
    setAll(hitItems, i -> config.itemFactory.createItem(i % items.length));
    setAll(missItems, i -> config.itemFactory.createItem(i + items.length));
    kiloSet = setFactory.get();
    for (T item : items) {
      kiloSet.add(item);
    }
  }

  @Benchmark("Create a 1K-element set")
  public void create() {
    kiloSet = setFactory.get();
    for (T item : items) {
      kiloSet.add(item);
    }
  }

  @Benchmark("Iterate through a 1K-element set")
  @InterferenceWarning("This test sometimes JITs badly and consumes memory")
  public void iterate() {
    kiloSet.forEach(e -> assertNotNull(e));
  }

  @Benchmark("Hit in a 1K-element set, identical")
  public void identityHit() {
    assertTrue(kiloSet.contains(next(items)));
  }

  @Benchmark("Hit in a 1K-element set, not identical")
  public void hit() {
    assertTrue(kiloSet.contains(next(hitItems)));
  }

  @Benchmark("Miss in a 1K-element set")
  public void miss() {
    assertFalse(kiloSet.contains(next(missItems)));
  }

  private <V> V next(V[] array) {
    ++i;
    if (i == array.length) {
      i = 0;
    }
    return array[i];
  }
}