text:
package org.diorite.config.impl.actions.collections;

import java.util.Collection;
import java.util.Map;
import java.util.function.BiPredicate;
import java.util.function.Predicate;

import org.diorite.commons.reflections.MethodInvoker;
import org.diorite.config.AbstractPropertyAction;
import org.diorite.config.ConfigPropertyActionInstance;
import org.diorite.config.ConfigPropertyTemplate;

@SuppressWarnings({"unchecked", "rawtypes"})
public class RemoveFromCollectionIfPropertyAction extends AbstractPropertyAction
{
    public RemoveFromCollectionIfPropertyAction()
    {
        super("removeFromCollectionIf", "removeFrom(?<property>[A-Z0-9].*?)If", "remove(?<property>[A-Z0-9].*?)If");
    }

    @Override
    protected boolean matchesAction0(MethodInvoker method, Class<?>[] parameters)
    {
        if (parameters.length != 1)
        {
            return false;
        }
        if (method.isVarArgs())
        {
            return false;
        }
        Class<?> parameter = parameters[0];
        if (! Predicate.class.isAssignableFrom(parameter) && ! BiPredicate.class.isAssignableFrom(parameter))
        {
            return false;
        }
        Class<?> returnType = method.getReturnType();
        return (returnType == void.class) || (returnType == boolean.class);
    }

    @Override
    protected String getGroovyImplementation0(MethodInvoker method, ConfigPropertyTemplate<?> propertyTemplate, ConfigPropertyActionInstance actionInstance)
    {
        StringBuilder methodBuilder = new StringBuilder(500);
        // language=groovy
        methodBuilder.append("def v = $rawValue\n")
                     .append("if (v == null) $returnOrNothing false\n");

        Class<?> parameter = method.getParameterTypes()[0];
        if (Collection.class.isAssignableFrom(propertyTemplate.getRawType()))
        {
            if (BiPredicate.class.isAssignableFrom(parameter))
            {
                throw new IllegalStateException("BiPredicate can be only used on maps, not on: " + propertyTemplate.getGenericType());
            }
            // language=groovy
            methodBuilder.append("$returnOrNothing v.removeIf(var1)\n");
        }
        else if (Map.class.isAssignableFrom(propertyTemplate.getRawType()))
        {
            if (Predicate.class.isAssignableFrom(parameter))
            {
                // language=groovy
                methodBuilder.append("boolean any = false \n" +
                                     "for (Iterator<Map.Entry> iterator = v.entrySet().iterator(); iterator.hasNext(); )\n" +
                                     "{\n" +
                                     "    Map.Entry entry = iterator.next() \n" +
                                     "    if (var1.test(entry))\n" +
                                     "    {\n" +
                                     "        iterator.remove() \n" +
                                     "        any = true \n" +
                                     "    }\n" +
                                     "}\n" +
                                     "$returnOrNothing any");
            }
            else
            {
                // language=groovy
                methodBuilder.append("boolean any = false \n" +
                                     "for (Iterator<Map.Entry> iterator = v.entrySet().iterator(); iterator.hasNext(); )\n" +
                                     "{\n" +
                                     "    Map.Entry entry = iterator.next() \n" +
                                     "    if (var1.test(entry.getKey(), entry.getValue()))\n" +
                                     "    {\n" +
                                     "        iterator.remove() \n" +
                                     "        any = true \n" +
                                     "    }\n" +
                                     "}\n" +
                                     "$returnOrNothing any");
            }
        }
        else
        {
            throw new IllegalStateException("Unsupported type of property: " + propertyTemplate.getGenericType());
        }
        return methodBuilder.toString();
    }
}


text:
using UnityEngine;
using System.Collections;

namespace CompleteProject
{
    public class EnemyMovement : MonoBehaviour
    {
        Transform player;               // Reference to the player's position.
        PlayerHealth playerHealth;      // Reference to the player's health.
        EnemyHealth enemyHealth;        // Reference to this enemy's health.
        NavMeshAgent nav;               // Reference to the nav mesh agent.

        void Awake ()
        {
            // Set up the references.
            player = GameObject.FindGameObjectWithTag ("Player").transform;
            playerHealth = player.GetComponent <PlayerHealth> ();
            enemyHealth = GetComponent <EnemyHealth> ();
            nav = GetComponent <NavMeshAgent> ();
        }

        void Update ()
        {
            // If the enemy and the player have health left...
            if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
            {
                // ... set the destination of the nav mesh agent to the player.
                nav.SetDestination (player.position);
            }
            // Otherwise...
            else
            {
                // ... disable the nav mesh agent.
                nav.enabled = false;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// 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 Rodrigo B. de Oliveira 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.
#endregion

using System;

namespace Boo.Lang.Compiler.Steps
{
	using Boo.Lang.Compiler.Ast;
	using Boo.Lang.Compiler.TypeSystem;

	public class BindMethods : AbstractVisitorCompilerStep
	{
		public BindMethods()
		{
		}

		override public void OnMethod(Method node)
		{
			if (null == node.Entity)
			{
				if (node.GenericParameters.Count == 0)
				{
					node.Entity = new InternalMethod(TypeSystemServices, node);
				}
				else
				{
					node.Entity = new InternalGenericMethod(TypeSystemServices, node);
				}
			}
			Visit(node.ExplicitInfo);
		}

		override public void OnExplicitMemberInfo(ExplicitMemberInfo node)
		{
			Visit(node.InterfaceType);
		}

		override public void OnClassDefinition(ClassDefinition node)
		{
			Visit(node.Members);
		}

		override public void OnModule(Module node)
		{
			Visit(node.Members);
		}

		override public void Run()
		{
			NameResolutionService.Reset();
			Visit(CompileUnit.Modules);
		}
	}
}


text:
Mavatar::Engine.routes.draw do
  match "/avatar/:hash", controller: "image", action: "show", via: [:get]
end


text:
try:
    import coverage
    coverage.process_startup()
except ImportError:
    pass

import unittest
import sys, os, glob

test_root = os.path.dirname(os.path.abspath(__file__))
test_files = glob.glob(os.path.join(test_root, 'test_*.py'))

os.chdir(test_root)
sys.path.insert(0, os.path.dirname(test_root))
sys.path.insert(0, test_root)
test_names = [os.path.basename(name)[:-3] for name in test_files]

if 'help' in sys.argv or '-h' in sys.argv:
    sys.stdout.write('''Command line arguments:
    fast: Skip server adapter tests.
    verbose: Print tests even if they pass.
    ''')
    sys.exit(0)

if 'fast' in sys.argv:
    sys.stderr.write("Warning: The 'fast' keyword skipps server tests.\n")
    test_names.remove('test_server')

suite = unittest.defaultTestLoader.loadTestsFromNames(test_names)

def run():
    import bottle

    bottle.debug(True)
    vlevel = 2 if 'verbose' in sys.argv else 0
    result = unittest.TextTestRunner(verbosity=vlevel).run(suite)

    sys.exit((result.errors or result.failures) and 1 or 0)

if __name__ == '__main__':
    run()


text:
function(mitkFunctionCreateMatchPointDeployedAlgorithm)

  set(_function_params
      NAME                # Name of the algorithm/target
      PROFILE             # Profile of the algorithm that should be used
     )

  set(_function_multiparams
      DEPENDS                # list of modules this command line app depends on
      PACKAGE_DEPENDS        # list of "packages" this command line app depends on (e.g. ITK, VTK, etc.)
      TARGET_DEPENDS         # list of CMake targets this command line app depends on
      CPP_FILES              # (optional) list of cpp files, if it is not given NAME.cpp is assumed
      INCLUDE_DIRS           # include directories: [PUBLIC|PRIVATE|INTERFACE] <list>
      ADDITIONAL_LIBS        # list of addidtional private libraries linked to this module.
      H_FILES                # list of header files: [PUBLIC|PRIVATE] <list>
     )

  set(_function_options
       NO_PROFILE_GEN #Flag that indicates that no profile resource should be generated.
     )

  cmake_parse_arguments(ALG "${_function_options}" "${_function_params}" "${_function_multiparams}" ${ARGN})

  if( NOT (DEFINED MITK_USE_MatchPoint) OR NOT (${MITK_USE_MatchPoint}))
    message(FATAL_ERROR "Need package Matchpoint to deploy MatchPoint Algorithms.")
  endif()

  if(NOT ALG_NAME)
    message(FATAL_ERROR "NAME argument cannot be empty.")
  endif()

  set(ALG_TARGET "MDRA_${ALG_NAME}")

  if(NOT ALG_CPP_FILES)
    set(ALG_CPP_FILES "${ALG_NAME}.cpp")
  endif()

  if(NOT ALG_PROFILE)
    set(ALG_PROFILE "${ALG_NAME}.profile")
  endif()

  if(NOT ALG_NO_PROFILE_GEN)
    message(STATUS "Generate MDRA profile for ${ALG_NAME} (from ${ALG_PROFILE})")
    include(${MatchPoint_SOURCE_DIR}/CMake/mapFunctionCreateAlgorithmProfile.cmake)
    CREATE_ALGORITHM_PROFILE(${ALG_NAME} ${ALG_PROFILE})
  endif()

  message(STATUS "Deploy MDRA algorithm ${ALG_NAME}")
  ADD_LIBRARY(${ALG_TARGET} SHARED ${ALG_CPP_FILES} ${ALGORITHM_PROFILE_FILE})

  set_target_properties(${ALG_TARGET} PROPERTIES
    OUTPUT_NAME "mdra-${MatchPoint_VERSION_MAJOR}-${MatchPoint_VERSION_MINOR}_${ALG_NAME}"
    OUTPUT_NAME_DEBUG "mdra-D-${MatchPoint_VERSION_MAJOR}-${MatchPoint_VERSION_MINOR}_${ALG_NAME}"
    PREFIX ""
    FOLDER "${MITK_ROOT_FOLDER}/Modules/MatchPointAlgorithms")

  mitk_use_modules(TARGET ${ALG_TARGET}
                   MODULES ${ALG_DEPENDS}
                   PACKAGES PRIVATE MatchPoint ${ALG_PACKAGE_DEPENDS}
                   )

  if(ALG_TARGET_DEPENDS)
    target_link_libraries(${ALG_TARGET} ${ALG_TARGET_DEPENDS})
  endif()

  target_include_directories(${ALG_TARGET} PRIVATE ${ALG_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR})

  if(ALG_ADDITIONAL_LIBS)
    target_link_libraries(${ALG_TARGET} PRIVATE ${ALG_ADDITIONAL_LIBS})
    get_property(_mitk_additional_library_search_paths GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS)
    foreach(_lib_filepath ${ALG_ADDITIONAL_LIBS})
      get_filename_component(_search_path "${_lib_filepath}" PATH)
      if(_search_path)
        list(APPEND _mitk_additional_library_search_paths "${_search_path}")
      endif()
    endforeach()
    if(_mitk_additional_library_search_paths)
      list(REMOVE_DUPLICATES _mitk_additional_library_search_paths)
      set_property(GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS ${_mitk_additional_library_search_paths})
    endif()
  endif()

  MITK_INSTALL(TARGETS ${ALG_TARGET})

endfunction()


text:
function max_card_match=test_matching(A,m,varargin)
% TEST_MATCHING Tests if a matching is maximum cardinality
%
% max_card_match=test_matching(A,m) returns 1 if m is a maximum cardinality
% matching on A.
%
% This method works on undirected graphs (symmetric matrices) and ignores
% edge weights.
% The runtime is O(mn*alpha(m,n)).  The alpha function is the inverse
% Ackermann function and is <= 4 for all valid Matlab inputs.
%
% ... = test_matching(A,m,...) takes a set of
% key-value pairs or an options structure.  See set_matlab_bgl_options
% for the standard options.
%   There are no additional options for this function.
%
% Example:
%   load('graphs/matching_example.mat');
%   [m_not_max,v] = matching(A,struct('augmenting_path','none'));
%   test_matching(A,m_not_max)

%
% David Gleich
% Copyright, Stanford University, 2007
%

%% History
%  2007-07-12: Initial version
%%

[trans check full2sparse] = get_matlab_bgl_options(varargin{:});
if full2sparse && ~issparse(A), A = sparse(A); end
if check, check_matlab_bgl(A,struct('sym',1)); end % ensure input is symmetric
% no trans check because the input is symmetric

max_card_match = test_matching_mex(A,m);


text:
@interface ZWPGradient()

@property (nonatomic, strong) NSArray *colors;
@property (nonatomic, strong) NSArray *locations;
@property (nonatomic, assign) CGGradientRef gradient;

@end
@implementation ZWPGradient

#pragma mark - Initialization

- (instancetype)initWithStartingColor:(UIColor *)startingColor endingColor:(UIColor *)endingColor {
    return [self initWithColors:@[startingColor, endingColor]];
}
- (instancetype)initWithColors:(NSArray *)colors {
    NSMutableArray *locations = [NSMutableArray arrayWithCapacity:colors.count];
    CGFloat increment = 1.0 / (CGFloat)([colors count] - 1);
    [colors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [locations addObject:@(idx * increment)];
    }];
    return [self initWithColors:colors locations:locations];
}
- (instancetype)initWithColors:(NSArray *)colors locations:(NSArray *)locations {
    if((self = [super init])) {
        _colors = [colors copy];
        CFMutableArrayRef primitiveColors = CFArrayCreateMutable(kCFAllocatorDefault, [colors count], &kCFTypeArrayCallBacks);
        [_colors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            CFArrayAppendValue(primitiveColors, (const void *)[obj CGColor]);
        }];

        _locations = [locations copy];
        CGFloat *primitiveLocations = malloc(sizeof(CGFloat) * [locations count]);
        [_locations enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            primitiveLocations[idx] = (CGFloat)[obj doubleValue];
        }];

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        _gradient = CGGradientCreateWithColors(colorSpace, primitiveColors, primitiveLocations);
        CGColorSpaceRelease(colorSpace);
        CFRelease(primitiveColors);
        free(primitiveLocations);
    }
    return self;
}

#pragma mark - Primitive Drawing

- (void)drawFromPoint:(CGPoint)startPoint
              toPoint:(CGPoint)endPoint
              options:(ZWPGradientDrawingOptions)options {
    CGContextDrawLinearGradient(UIGraphicsGetCurrentContext(),
                                self.gradient,
                                startPoint,
                                endPoint,
                                options);
}
- (void)drawFromCenter:(CGPoint)startCenter
                radius:(CGFloat)startRadius
              toCenter:(CGPoint)endCenter
                radius:(CGFloat)endRadius
               options:(ZWPGradientDrawingOptions)options {
    CGContextDrawRadialGradient(UIGraphicsGetCurrentContext(),
                                self.gradient,
                                startCenter,
                                startRadius,
                                endCenter,
                                endRadius,
                                options);
}

#pragma mark - Properties

- (NSInteger)numberOfColorStops {
    return [self.colors count];
}
- (void)getColor:(__autoreleasing UIColor **)color location:(CGFloat *)location atIndex:(NSInteger)index {
    UIColor *c = [self.colors objectAtIndex:index];
    NSNumber *l = [self.locations objectAtIndex:index];

    if(color) {
        *color = c;
    }
    if(location) {
        *location = l.doubleValue;
    }
}

#pragma mark - Dealloc

- (void)dealloc {
    if(_gradient) {
        CGGradientRelease(_gradient);
        _gradient = nil;
    }
}

@end


text:
"""Pretty print logging."""

import logging
import pprint

from typing import Any

def log(level: int, x: Any) -> None:
    if logging.getLogger(None).isEnabledFor(level):
        for line in pprint.pformat(x).split('\n'):
            logging.log(level, line)

def info(x: Any) -> None:
    log(logging.INFO, x)

def debug(x: Any) -> None:
    log(logging.DEBUG, x)


text:
/**
 * Data Transfer Objects used by Spring MVC REST controllers.
 */
package com.ipublic.mashup.web.rest.dto;


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;

namespace IdentityServer4.Quickstart.UI
{
    public class ConsentService
    {
        private readonly IClientStore _clientStore;
        private readonly IResourceStore _resourceStore;
        private readonly IIdentityServerInteractionService _interaction;
        private readonly ILogger _logger;

        public ConsentService(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IResourceStore resourceStore,
            ILogger logger)
        {
            _interaction = interaction;
            _clientStore = clientStore;
            _resourceStore = resourceStore;
            _logger = logger;
        }

        public async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model)
        {
            var result = new ProcessConsentResult();

            ConsentResponse grantedConsent = null;

            // user clicked 'no' - send back the standard 'access_denied' response
            if (model.Button == "no")
            {
                grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied };
            }
            // user clicked 'yes' - validate the data
            else if (model.Button == "yes" && model != null)
            {
                // if the user consented to some scope, build the response model
                if (model.ScopesConsented != null && model.ScopesConsented.Any())
                {
                    var scopes = model.ScopesConsented;
                    if (ConsentOptions.EnableOfflineAccess == false)
                    {
                        scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess);
                    }

                    grantedConsent = new ConsentResponse
                    {
                        RememberConsent = model.RememberConsent,
                        ScopesValuesConsented = scopes.ToArray()
                    };
                }
                else
                {
                    result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
                }
            }
            else
            {
                result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
            }

            if (grantedConsent != null)
            {
                // validate return url is still valid
                var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
                if (request == null) return result;

                // communicate outcome of consent back to identityserver
                await _interaction.GrantConsentAsync(request, grantedConsent);

                // indicate that's it ok to redirect back to authorization endpoint
                result.RedirectUri = model.ReturnUrl;
            }
            else
            {
                // we need to redisplay the consent UI
                result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model);
            }

            return result;
        }

        public async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null)
        {
            var request = await _interaction.GetAuthorizationContextAsync(returnUrl);
            if (request != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(request.Client.ClientId);
                if (client != null)
                {
                    var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ValidatedResources.Resources.ToScopeNames());
                    if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any()))
                    {
                        return CreateConsentViewModel(model, returnUrl, request, client, resources);
                    }
                    else
                    {
                        _logger.LogError("No scopes matching: {0}", request.ValidatedResources.Resources.ToScopeNames().Aggregate((x, y) => x + ", " + y));
                    }
                }
                else
                {
                    _logger.LogError("Invalid client id: {0}", request.Client.ClientId);
                }
            }
            else
            {
                _logger.LogError("No consent request matching request: {0}", returnUrl);
            }

            return null;
        }

        private ConsentViewModel CreateConsentViewModel(
            ConsentInputModel model, string returnUrl,
            AuthorizationRequest request,
            Client client, Resources resources)
        {
            var vm = new ConsentViewModel();
            vm.RememberConsent = model?.RememberConsent ?? true;
            vm.ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>();

            vm.ReturnUrl = returnUrl;

            vm.ClientName = client.ClientName ?? client.ClientId;
            vm.ClientUrl = client.ClientUri;
            vm.ClientLogoUrl = client.LogoUri;
            vm.AllowRememberConsent = client.AllowRememberConsent;

            vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
            vm.ResourceScopes = resources.ApiScopes.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
            if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
            {
                vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] {
                    GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
                });
            }

            return vm;
        }

        public ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
        {
            return new ScopeViewModel
            {
                Name = identity.Name,
                DisplayName = identity.DisplayName,
                Description = identity.Description,
                Emphasize = identity.Emphasize,
                Required = identity.Required,
                Checked = check || identity.Required
            };
        }

        public ScopeViewModel CreateScopeViewModel(ApiScope scope, bool check)
        {
            return new ScopeViewModel
            {
                Name = scope.Name,
                DisplayName = scope.DisplayName,
                Description = scope.Description,
                Emphasize = scope.Emphasize,
                Required = scope.Required,
                Checked = check || scope.Required
            };
        }

        private ScopeViewModel GetOfflineAccessScope(bool check)
        {
            return new ScopeViewModel
            {
                Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
                DisplayName = ConsentOptions.OfflineAccessDisplayName,
                Description = ConsentOptions.OfflineAccessDescription,
                Emphasize = true,
                Checked = check
            };
        }
    }
}


text:
package org.sagebionetworks.repo.web.service;

import java.io.IOException;

import org.sagebionetworks.reflection.model.PaginatedResults;
import org.sagebionetworks.repo.model.AccessApproval;
import org.sagebionetworks.repo.model.BatchAccessApprovalInfoRequest;
import org.sagebionetworks.repo.model.BatchAccessApprovalInfoResponse;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.InvalidModelException;
import org.sagebionetworks.repo.model.RestrictableObjectDescriptor;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.dataaccess.AccessorGroupRequest;
import org.sagebionetworks.repo.model.dataaccess.AccessorGroupResponse;
import org.sagebionetworks.repo.model.dataaccess.AccessorGroupRevokeRequest;
import org.sagebionetworks.repo.web.NotFoundException;

public interface AccessApprovalService {

	public AccessApproval createAccessApproval(Long userId,
			AccessApproval accessApproval) throws DatastoreException,
			UnauthorizedException, NotFoundException, InvalidModelException,
			IOException;

	public AccessApproval getAccessApproval(
			Long userId, String approvalId)
			throws DatastoreException, UnauthorizedException,
			NotFoundException;

	public PaginatedResults<AccessApproval> getAccessApprovals(Long userId,
			RestrictableObjectDescriptor subjectId, Long limit, Long offset)
			throws DatastoreException, UnauthorizedException, NotFoundException;

	public void deleteAccessApproval(Long userId, String approvalId)
			throws DatastoreException, UnauthorizedException, NotFoundException;

	public void revokeAccessApprovals(Long userId, String accessRequirementId, String accessorId);

	public AccessorGroupResponse listAccessorGroup(Long userId, AccessorGroupRequest request);

	public void revokeGroup(Long userId, AccessorGroupRevokeRequest request);

	public BatchAccessApprovalInfoResponse getBatchAccessApprovalInfo(Long userId,
			BatchAccessApprovalInfoRequest request);

}


text:
class PatchSetCodes < Patch
  def call
    # Forced lower case for all codes
    each_set do |set|
      set["mci_code"] = set["mci_code"]&.downcase
      set["gatherer_code"] = set["gatherer_code"]&.downcase
      set["official_code"] = set["official_code"]&.downcase
    end

    each_set do |set|
      if %W[cm1 cma mps mp2 cp1 cp2 cp3 pgtw pwpn].include?(set["official_code"])
        set.delete("mci_code")
      end

      set["code"] = set["official_code"] || set["mci_code"]

      # v4 killed mci codes, so reapply them
      mci_code = mci_codes[set["code"]]
      if mci_code
        if set["mci_code"] and set["mci_code"] != mci_code
          warn "Mismatching MCI code for #{set["code"]}: #{set["mci_code"].inspect} != #{mci_code.inspect}"
        end
        set["mci_code"] = mci_code
      end

      set["alternative_code"] = set.delete("mci_code")

      # Delete if redundant
      set.delete("alternative_code") if set["alternative_code"] == set["code"]
      set.delete("gatherer_code") if set["gatherer_code"] == set["code"]
      set.delete("gatherer_code") if set["gatherer_code"] == set["alternative_code"]

      # Delete ones conflicting with official or alternative codes for different sets
      set.delete("gatherer_code") if %W[al st le mi].include?(set["gatherer_code"])
      set.delete("official_code")
    end

    duplicated_codes = @sets
      .group_by{|s| s["code"]}
      .transform_values(&:size)
      .select{|_,v| v > 1}
    unless duplicated_codes.empty?
      raise "There are duplicated set codes: #{duplicated_codes.keys}"
    end

    each_printing do |card|
      card["set_code"] = card["set"]["code"]
    end
  end

  def mci_codes
    @mci_codes ||= begin
      mci_codes_path = Indexer::ROOT + "mci_set_codes.txt"
      mci_codes_path.readlines.map(&:chomp).map{|x| x.split}.to_h
    end
  end
end


text:
/**
 * Created by mag94 on 12/1/15.
 */

var selectedBibsKey = "selectedBibs"; // defined in _header.html.erb
var selectedRaceKey = "selectedRace";
var selected_racers = [];
var selected_races = {
  "routeid": "",
  "points": []
};
var racer_markers = []; // array of markers that are displayed on map
var checkboxes = [];

var resetView = true;

function initializeLocalStorage() {
    // initialize array to store bibs if not yet created
    if (localStorage.getItem(selectedBibsKey) === null) {
        var selectedBibs = [];
        localStorage.setItem(selectedBibsKey, JSON.stringify(selectedBibs));
    }

    selected_racers = JSON.parse(localStorage.getItem(selectedBibsKey)); // view _header to see how bibs are stored

    // initialize array to store races if not yet created
    if (localStorage.getItem(selectedRaceKey) === null) {
        var selectedRaces = {
          "routeid": "",
          "points": []
        };
        localStorage.setItem(selectedRaceKey, JSON.stringify(selectedRaces));
    }

    selected_races = JSON.parse(localStorage.getItem(selectedRaceKey)); // view _header to see how bibs are stored
}

function initializeMarkers() {
    // initialize markers for selected racers so locations can be updated
    var n;
    for (n = 0; n < selected_racers.length; n++) {
        var marker = L.marker([0, 0], {opacity: 0});
        marker.addTo(map);
        racer_markers.push(marker);
    }
}

function isInArray(value, array) {
    return array.indexOf(value) > -1;
}

// Code for filter UI that allows users to remove and deselect racers
function createFilterUI() {
    // find reference to filter UI and set its title
    var filter = document.getElementById('checkbox-filter');

    // create a filter interface.
    for (var i = 0; i < selected_racers.length; i++) {
        // item will contain input checkbox and label
        var item = document.createElement('div');

        filter.appendChild(item);
        item.id = selected_racers[i];

        // create checkbox and div to contain it
        var checkbox_div = document.createElement('div');
        checkbox_div.className = "container-checkbox-inline";
        item.appendChild(checkbox_div);
        var checkbox = document.createElement('input');
        checkbox_div.appendChild(checkbox);
        checkbox.type = 'checkbox';
        checkbox.id = selected_racers[i]; // bib number is id for box
        checkbox.checked = false;
        checkboxes.push(checkbox);

        // create a label to the right of the checkbox with racer bib number
        var label = document.createElement('div');
        label.className = "container-label-inline";
        item.appendChild(label);
        label.innerHTML = "BibNo: " + selected_racers[i];
        label.setAttribute('for', selected_racers[i]);
    }
}

// function called whenever someone clicks remove button
// function removes racer's marker with checked checkbox
function remove(e) {
    e.preventDefault();

    var to_keep = [];
    var to_delete_filters = []; // array to identify which divs to remove in filter UI
    var to_delete_indices = []; // array to identify which markers to remove from map
    var i;
    // run through each checkbox and record whether it is checked
    // if it is, add id (aka bibNo) to to_keep so racer marker stays on map
    for (i = 0; i < checkboxes.length; i++) {
        if (!checkboxes[i].checked) {
            // keep bib number associated with checkbox
            to_keep.push(Number(checkboxes[i].id));
        }
        else {
            to_delete_filters.push(checkboxes[i].id);
            to_delete_indices.push(i);
        }
    }

    // delete racer from map and checkbox and label from filter UI
    var orig_len = to_delete_filters.length;
    for (i = 0; i < orig_len; i++) {
        // need to delete starting from end of list so indices do not get mixed up
        var index = orig_len - (i + 1);

        // delete marker from map
        var racer_marker = racer_markers[to_delete_indices[index]];
        racer_markers.splice(to_delete_indices[index], 1);
        map.removeLayer(racer_marker);

        // delete checkbox referencing marker from filter
        var checkbox_marker = to_delete_indices[index];
        checkboxes.splice(checkbox_marker, 1);

        // delete div from filter
        var div_marker = document.getElementById(to_delete_filters[index].toString());
        div_marker.remove();
    }

    localStorage.setItem(selectedBibsKey, JSON.stringify(to_keep));
}

function displayRoute(routeName) {
    // retrieve json for selected race
    var storedRacesJson = JSON.parse(localStorage.getItem(selectedRaceKey));

    // getting new race, clear storage of selected racers and routeid
    if (routeName != storedRacesJson['routeid'] && routeName.length != 0) {
        var selectedBibs = [];
        localStorage.setItem(selectedBibsKey, JSON.stringify(selectedBibs));

        var routeJSON = {
            "route": {
                "routeName": routeName
            }
        };

        console.log(routeJSON);
        $.ajax({
            type: 'GET',
	          async: false,
            url: '/welcome/route_to_points.json',
            data: routeJSON,
            success: function(data) {
                var coords3D = [];
                var i;
                for (i = 0; i < data.length; i ++) {
                    var lng = data[i].lng;
                    var lat = data[i].lat;
                    var alt = data[i].alt;
                    var coord = [lng, lat, alt];
                    coords3D.push(coord);
                }

                storedRacesJson = {
                  "routeid": routeName,
                  "points": coords3D
                };
                localStorage.setItem(selectedRaceKey, JSON.stringify(storedRacesJson));
                drawRouteV2(true, coords3D);
                // location.reload();
            }
        });
    }

    else if (routeName.length === 0) {
        // pass, let browser alert user to select valid race
    }

    else {
        //alert("Race has already been added to map.");
    }
}

function displayBib(bibNo) {
    // retrieve array of selected bibs
    var storedBibs = JSON.parse(localStorage.getItem(selectedBibsKey));

    // store new bibs in array
    if (!isInArray(bibNo, storedBibs)) {
        // check to make sure racer is signed up
        storedBibs.push(bibNo);
        localStorage.setItem(selectedBibsKey, JSON.stringify(storedBibs));
        console.log(localStorage.getItem(selectedBibsKey));
        location.reload();
    }
    else {
        alert("Athlete has already been added to map.");
    }
}

function isRacerActive(e, bool_bibNo, idString, activeList) {
    var bibKey = 'bib';
    var len = activeList.length;

    var bibNo;
    var racerJson;
    var i;

    for (i = 0; i < len; i++) {
        racerJson = activeList[i];
        bibNo = racerJson[bibKey];

        if (bool_bibNo[1] == bibNo) {
            //alert("Match bib number for: " + idString);
            displayBib(bibNo);
            reattachEvents(e);
            return;
        }
    }

    alert(idString + " is not yet active.");
}

function displayIfActive(e, arg1, arg2, callback) {
    var storedRacesJson = JSON.parse(localStorage.getItem(selectedRaceKey));
    var routeid = storedRacesJson["routeid"];

    var routeJSON = {
        "route": {
            "routeid": routeid
        }
    };
    if (routeid.length != 0) {
        $.ajax({
            type: 'GET',
            async: false,
	          url: '/welcome/updated_coords.json',
            data: routeJSON,
            success: function (data) {
                console.log(data);
                callback(e, arg1, arg2, data);
            }
        });
    }
}

function isRacerSignedUp(idString, racerList) {
    var idRacer = idString.toLowerCase();
    var fNameKey = 'firstname';
    var lNameKey = 'lastname';
    var bibKey = 'bib';
    var len = racerList.length;

    var result_list = [];

    var fName;
    var lName;
    var bibNo;
    var racerJson;
    var i;

    for (i = 0; i < len; i++) {
        var result = [];
        racerJson = racerList[i];

        fName = ( racerJson[fNameKey] ).toLowerCase();
        lName = ( racerJson[lNameKey] ).toLowerCase();

        // get bib value if it exists
        if ( racerJson[bibKey] != null) {
            bibNo = ( racerJson[bibKey] );
        }
        else {
            bibNo = "";
        }

        // try to match on first name
        if (idRacer == fName) {
            result[0] = true;
            result[1] = bibNo;
            result_list.push(result);
        }

        // try to match on last name
        else if (idRacer == lName) {
            result[0] = true;
            result[1] = bibNo;
            result_list.push(result);
        }

        // try to match on bib value
        else if (idString == bibNo) {
            result[0] = true;
            result[1] = bibNo;
            result_list.push(result);
        }
    }

    return result_list;
}

function lookupRacerBib(e, idString, racerList) {
    var bool_bibNo_list = isRacerSignedUp(idString, racerList);
    var len = bool_bibNo_list.length;

    // found racer(s) given by the identification string
    if (len > 0) {
        var bool_bibNo;
        // found exactly one match
        if (len == 1) {
            bool_bibNo = bool_bibNo_list[0];
            displayIfActive(e, bool_bibNo, idString, isRacerActive);
        }
        // found multiple matches
        else {
            var listOfMatches = "";
            var i;

            for (i = 0; i < len; i++) {
                bool_bibNo = bool_bibNo_list[i];
                listOfMatches = listOfMatches.concat(idString + ", bibNo: " + bool_bibNo[1].toString() + "\n");
            }

            alert("Found multiple matches. Please search for " + idString + " by bibNo.\n\n" + listOfMatches);
        }
    }
    // No matches were found
    else {
        alert(idString + " is not signed up for this race.");
    }
}

function displayRacer(e, arg, callback) {
    $.ajax({
        type: 'GET',
        async: false,
        url: '/racers.json',
        success: function(data) {
            console.log(data);
            callback(e, arg, data);
        }
    });
}

function getRacerInfo(bibNo, racerJsonList) {
    var racerBibKey = 'bib';
    var len = racerJsonList.length;
    var i;

    for (i = 0; i < len; i++) {
        var racerInfo = racerJsonList[i];
        if (racerInfo[racerBibKey] == bibNo) {
            return racerInfo;
        }
    }
}

function clearMap() {
    $.each(map._layers, function (ml) {
        if (map._layers[ml].feature) {
            map.removeLayer(map._layers[ml]);
        }
        else if (map._layers[ml].options) {
            if (map._layers[ml].options.title) {
                if (map._layers[ml].options.title == routeOptionsTitle) {
                    map.removeLayer(map._layers[ml]);
                }
            }
        }
    });
}

function drawRouteV2(resetView, coords3D) {
    clearMap();
    // var storedRacesJson = JSON.parse(localStorage.getItem(selectedRaceKey));
    // var coords3D = storedRacesJson["points"];

    drawNonEditableRoute(map, routeOptions, coords3D);
    var midLat = coords3D[ Math.round(coords3D.length/2) ][1];
    var midLng = coords3D[ Math.round(coords3D.length/2) ][0];
    var routeViewPoint = [midLat, midLng];

    if (resetView) {
        map.setView(routeViewPoint, 13);
    }
}

function drawRoute(resetView) {
    clearMap();
    var storedRacesJson = JSON.parse(localStorage.getItem(selectedRaceKey));
    var coords3D = storedRacesJson["points"];

    drawNonEditableRoute(map, routeOptions, coords3D);
    var midLat = coords3D[ Math.round(coords3D.length/2) ][1];
    var midLng = coords3D[ Math.round(coords3D.length/2) ][0];
    var routeViewPoint = [midLat, midLng];

    if (resetView) {
        map.setView(routeViewPoint, 13);
    }
}

// use json located in content from html to update coordinates for racers
function plotCoords(racers_json) {
    drawRoute(resetView);

    selected_racers = JSON.parse(localStorage.getItem(selectedBibsKey)); // view _header to see how bibs are stored
    console.log("Log2 - Selected Racers: " + selected_racers);
    // update markers for selected racers on map
    var i;
    for (i = 0; i < selected_racers.length; i++) {
        var bibNo = selected_racers[i];
        var current_racer = getRacerInfo(bibNo, racers_json);
        var racer_marker = racer_markers[i];

        console.log("Log3 - Race Information: " + racers_json);

        racer_marker.setLatLng([current_racer.latitude, current_racer.longitude]).update();
        racer_marker.unbindPopup();
        racer_marker.bindPopup("Racer: " + current_racer.bib + ", Time: " + current_racer.time);
        racer_marker.setOpacity(1);
    }
    resetView = false;
}

function updateCoords() {
    var storedRacesJson = JSON.parse(localStorage.getItem(selectedRaceKey));
    var routeid = storedRacesJson["routeid"];

    console.log("Log1 - Displayed Race Information: " + storedRacesJson);

    var routeJSON = {
        "route": {
            "routeid": routeid
        }
    };

    if (routeid.length != 0) {
        // ajax call to get racers info from another page
        $.ajax({
            type: 'GET',
	          async: false,
            url: "welcome/updated_coords.json",
            data: routeJSON,
            success: function(data) {
                // callback handler
                // debugger;
                plotCoords(data);
            }
        });
    }
    // setTimeout(updateCoords, 7000); // update every 10 seconds
}


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var hammer_1 = require('../../gestures/hammer');
var drag_gesture_1 = require('../../gestures/drag-gesture');
var dom_1 = require('../../util/dom');
var ItemSlidingGesture = (function (_super) {
    __extends(ItemSlidingGesture, _super);
    function ItemSlidingGesture(list, listEle) {
        var _this = this;
        _super.call(this, listEle, {
            direction: 'x',
            threshold: DRAG_THRESHOLD
        });
        this.list = list;
        this.listEle = listEle;
        this.canDrag = true;
        this.data = {};
        this.openItems = 0;
        this.preventDrag = false;
        this.dragEnded = true;
        this.listen();
        this.onTap = function (ev) {
            if (!isFromOptionButtons(ev.target)) {
                var didClose = _this.closeOpened();
                if (didClose) {
                    void 0;
                    preventDefault(ev);
                }
            }
        };
        this.onMouseOut = function (ev) {
            if (ev.target.tagName === 'ION-ITEM-SLIDING') {
                void 0;
                _this.onDragEnd(ev);
            }
        };
    }
    ItemSlidingGesture.prototype.onDragStart = function (ev) {
        var itemContainerEle = getItemConatiner(ev.target);
        if (!itemContainerEle) {
            void 0;
            return false;
        }
        this.closeOpened(itemContainerEle);
        var openAmout = this.getOpenAmount(itemContainerEle);
        var itemData = this.get(itemContainerEle);
        this.preventDrag = (openAmout > 0);
        if (this.preventDrag) {
            this.closeOpened();
            void 0;
            preventDefault(ev);
            return;
        }
        itemContainerEle.classList.add('active-slide');
        this.set(itemContainerEle, 'offsetX', openAmout);
        this.set(itemContainerEle, 'startX', ev.center[this.direction]);
        this.dragEnded = false;
        return true;
    };
    ItemSlidingGesture.prototype.onDrag = function (ev) {
        var _this = this;
        if (this.dragEnded || this.preventDrag || Math.abs(ev.deltaY) > 30) {
            void 0;
            this.preventDrag = true;
            return;
        }
        var itemContainerEle = getItemConatiner(ev.target);
        if (!itemContainerEle || !isActive(itemContainerEle)) {
            void 0;
            return;
        }
        var itemData = this.get(itemContainerEle);
        if (!itemData.optsWidth) {
            itemData.optsWidth = getOptionsWidth(itemContainerEle);
            if (!itemData.optsWidth) {
                void 0;
                return;
            }
        }
        var x = ev.center[this.direction];
        var delta = x - itemData.startX;
        var newX = Math.max(0, itemData.offsetX - delta);
        if (newX > itemData.optsWidth) {
            // Calculate the new X position, capped at the top of the buttons
            newX = -Math.min(-itemData.optsWidth, -itemData.optsWidth + (((delta + itemData.optsWidth) * 0.4)));
        }
        if (newX > 5 && ev.srcEvent.type.indexOf('mouse') > -1 && !itemData.hasMouseOut) {
            itemContainerEle.addEventListener('mouseout', this.onMouseOut);
            itemData.hasMouseOut = true;
        }
        dom_1.raf(function () {
            if (!_this.dragEnded && !_this.preventDrag) {
                isItemActive(itemContainerEle, true);
                _this.open(itemContainerEle, newX, false);
            }
        });
    };
    ItemSlidingGesture.prototype.onDragEnd = function (ev) {
        var _this = this;
        this.preventDrag = false;
        this.dragEnded = true;
        var itemContainerEle = getItemConatiner(ev.target);
        if (!itemContainerEle || !isActive(itemContainerEle)) {
            void 0;
            return;
        }
        // If we are currently dragging, we want to snap back into place
        // The final resting point X will be the width of the exposed buttons
        var itemData = this.get(itemContainerEle);
        var restingPoint = itemData.optsWidth;
        // Check if the drag didn't clear the buttons mid-point
        // and we aren't moving fast enough to swipe open
        if (this.getOpenAmount(itemContainerEle) < (restingPoint / 2)) {
            // If we are going left but too slow, or going right, go back to resting
            if (ev.direction & hammer_1.DIRECTION_RIGHT || Math.abs(ev.velocityX) < 0.3) {
                restingPoint = 0;
            }
        }
        itemContainerEle.removeEventListener('mouseout', this.onMouseOut);
        itemData.hasMouseOut = false;
        dom_1.raf(function () {
            _this.open(itemContainerEle, restingPoint, true);
        });
    };
    ItemSlidingGesture.prototype.closeOpened = function (doNotCloseEle) {
        var didClose = false;
        if (this.openItems) {
            var openItemElements = this.listEle.querySelectorAll('.active-slide');
            for (var i = 0; i < openItemElements.length; i++) {
                if (openItemElements[i] !== doNotCloseEle) {
                    this.open(openItemElements[i], 0, true);
                    didClose = true;
                }
            }
        }
        return didClose;
    };
    ItemSlidingGesture.prototype.open = function (itemContainerEle, openAmount, isFinal) {
        var _this = this;
        var slidingEle = itemContainerEle.querySelector('ion-item,[ion-item]');
        if (!slidingEle) {
            void 0;
            return;
        }
        this.set(itemContainerEle, 'openAmount', openAmount);
        clearTimeout(this.get(itemContainerEle).timerId);
        if (openAmount) {
            this.openItems++;
        }
        else {
            var timerId = setTimeout(function () {
                if (slidingEle.style[dom_1.CSS.transform] === '') {
                    isItemActive(itemContainerEle, false);
                    _this.openItems--;
                }
            }, 400);
            this.set(itemContainerEle, 'timerId', timerId);
        }
        slidingEle.style[dom_1.CSS.transition] = (isFinal ? '' : 'none');
        slidingEle.style[dom_1.CSS.transform] = (openAmount ? 'translate3d(' + -openAmount + 'px,0,0)' : '');
        if (isFinal) {
            if (openAmount) {
                isItemActive(itemContainerEle, true);
                this.on('tap', this.onTap);
            }
            else {
                this.off('tap', this.onTap);
            }
        }
    };
    ItemSlidingGesture.prototype.getOpenAmount = function (itemContainerEle) {
        return this.get(itemContainerEle).openAmount || 0;
    };
    ItemSlidingGesture.prototype.get = function (itemContainerEle) {
        return this.data[itemContainerEle && itemContainerEle.$ionSlide] || {};
    };
    ItemSlidingGesture.prototype.set = function (itemContainerEle, key, value) {
        if (!this.data[itemContainerEle.$ionSlide]) {
            this.data[itemContainerEle.$ionSlide] = {};
        }
        this.data[itemContainerEle.$ionSlide][key] = value;
    };
    ItemSlidingGesture.prototype.unlisten = function () {
        _super.prototype.unlisten.call(this);
        this.listEle = null;
    };
    return ItemSlidingGesture;
}(drag_gesture_1.DragGesture));
exports.ItemSlidingGesture = ItemSlidingGesture;
function isItemActive(ele, isActive) {
    ele.classList[isActive ? 'add' : 'remove']('active-slide');
    ele.classList[isActive ? 'add' : 'remove']('active-options');
}
function preventDefault(ev) {
    void 0;
    ev.preventDefault();
}
function getItemConatiner(ele) {
    return dom_1.closest(ele, 'ion-item-sliding', true);
}
function isFromOptionButtons(ele) {
    return !!dom_1.closest(ele, 'ion-item-options', true);
}
function getOptionsWidth(itemContainerEle) {
    var optsEle = itemContainerEle.querySelector('ion-item-options');
    if (optsEle) {
        return optsEle.offsetWidth;
    }
}
function isActive(itemContainerEle) {
    return itemContainerEle.classList.contains('active-slide');
}
var DRAG_THRESHOLD = 20;


text:
package hoverfly_test

import (
	"bytes"
	"io/ioutil"
	"net"
	"regexp"
	"strconv"
	"strings"

	"github.com/SpectoLabs/hoverfly/functional-tests"
	"github.com/SpectoLabs/hoverfly/functional-tests/testdata"
	"github.com/dghubble/sling"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pborman/uuid"
)

var _ = Describe("When I run Hoverfly", func() {

	var (
		hoverfly *functional_tests.Hoverfly
	)

	BeforeEach(func() {
		hoverfly = functional_tests.NewHoverfly()
	})

	AfterEach(func() {
		hoverfly.Stop()
	})

	Context("in simulate mode", func() {

		BeforeEach(func() {
			hoverfly.Start()
			hoverfly.SetMode("simulate")
		})

		It("should not template response if templating is disabled explicitely", func() {
			hoverfly.ImportSimulation(testdata.TemplatingDisabled)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com?one=foo"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal("{{ Request.QueryParam.singular }}"))
		})

		It("should not template response if templating is not explcitely enabled or disabled", func() {
			hoverfly.ImportSimulation(testdata.TemplatingDisabledByDefault)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com?one=foo"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal("{{ Request.QueryParam.one }}"))
		})

		It("should template response if templating is enabled and cache template not response", func() {
			hoverfly.ImportSimulation(testdata.TemplatingEnabled)

			hoverfly.WriteLogsIfError()

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com?one=foo"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal("foo"))

			resp = hoverfly.Proxy(sling.New().Get("http://test-server.com?one=bar"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err = ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal("bar"))
		})

		It("should be able to use state in templating", func() {
			hoverfly.ImportSimulation(testdata.TemplatingEnabledWithStateInBody)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/one"))
			Expect(resp.StatusCode).To(Equal(200))

			resp = hoverfly.Proxy(sling.New().Get("http://test-server.com/two"))
			Expect(resp.StatusCode).To(Equal(200))
			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())
			Expect(string(body)).To(Equal("state for eggs"))
		})

		It("should not crash when templating a response if templating variable does not exist", func() {
			hoverfly.ImportSimulation(testdata.TemplatingEnabled)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com?wrong=foo"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal(""))
		})

		It("should be able to use state in templating state transitions", func() {
			hoverfly.ImportSimulation(testdata.TemplatingEnabledWithStateInTransitionsState)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/one?status=connected"))
			Expect(resp.StatusCode).To(Equal(200))

			resp = hoverfly.Proxy(sling.New().Get("http://test-server.com/two"))
			Expect(resp.StatusCode).To(Equal(200))
			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())
			Expect(string(body)).To(Equal("status is connected"))
		})
	})

	Context("in simulate mode, template helpers", func() {

		BeforeEach(func() {
			hoverfly.Start()
			hoverfly.SetMode("simulate")
		})

		It("randomString", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomString"))
			Expect(resp.StatusCode).To(Equal(200))

			_, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())
		})

		It("randomStringLength10", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomStringLength10"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(len(string(body))).To(Equal(10))
		})

		It("randomBoolean", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomBoolean"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			_, err = strconv.ParseBool(string(body))
			Expect(err).To(BeNil())
		})

		It("randomInteger", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomInteger"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			parsedInt, err := strconv.ParseInt(string(body), 10, 0)
			Expect(err).To(BeNil())

			Expect(parsedInt > 0).To(BeTrue())
		})

		It("randomInteger in header", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomIntegerHeader"))
			Expect(resp.StatusCode).To(Equal(200))

			imageId := resp.Header.Get("X-Image-Id")
			Expect(imageId).NotTo(BeEmpty())

			parsedImageId, err := strconv.ParseInt(imageId, 10, 0)
			Expect(err).To(BeNil())

			Expect(parsedImageId > 0).To(BeTrue())
		})

		It("randomIntegerRange", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomIntegerRange1-10"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			parsedInt, err := strconv.ParseInt(string(body), 10, 0)
			Expect(err).To(BeNil())
			Expect(parsedInt >= 1 && parsedInt <= 10).To(BeTrue())
		})

		It("randomFloat", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomFloat"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			parsedFloat, err := strconv.ParseFloat(string(body), 1)
			Expect(err).To(BeNil())

			Expect(parsedFloat > 0).To(BeTrue())
		})

		It("randomFloatRange", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomFloatRange1-10"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			parsedFloat, err := strconv.ParseFloat(string(body), 1)
			Expect(err).To(BeNil())

			Expect(parsedFloat >= 1 && parsedFloat <= 10).To(BeTrue())
		})

		It("randomEmail", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomEmail"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(IsEmail(string(body))).To(BeTrue())
		})

		It("randomIPv4", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomIPv4"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(IsIPv4(string(body))).To(BeTrue())
		})

		It("randomIPv6", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomIPv6"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(IsIPv6(string(body))).To(BeTrue())
		})

		It("randomUuid", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/randomuuid"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())
			returnedUuid := uuid.Parse(string(body))

			Expect(returnedUuid).To(Not(BeNil()))
		})

		It("faker", func() {
			hoverfly.ImportSimulation(testdata.TemplatingHelpers)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/faker"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Not(BeEmpty()))
			Expect(string(body)).To(Not(Equal("{{ faker 'JobTitle' }}")))
		})
	})

	Context("in simulate mode, template request", func() {

		BeforeEach(func() {
			hoverfly.Start()
			hoverfly.SetMode("simulate")
		})

		It("Request", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/Request"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			// TODO: Handle this?
			Expect(string(body)).To(ContainSubstring("[Request] http %!s(func(string, string, *raymond.Options)"))
		})

		It("Request.Body jsonpath", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)
			resp := hoverfly.Proxy(sling.New().Post("http://test-server.com/Request.Body_jsonpath").BodyJSON(map[string]string{
				"test": "value",
			}))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal("value"))
		})

		It("Request.Body jsonpath incorect", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)
			resp := hoverfly.Proxy(sling.New().Post("http://test-server.com/Request.Body_jsonpath").BodyJSON(map[string]string{
				"nottest": "value",
			}))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal(""))
		})

		It("Request.Body xpath", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)
			resp := hoverfly.Proxy(sling.New().Post("http://test-server.com/Request.Body_xpath").Body(bytes.NewBuffer([]byte(`<?xml version="1.0" encoding="UTF-8"?><root><text>value</text></root>`))))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal("value"))
		})

		It("Request.Body xpath incorect", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)
			resp := hoverfly.Proxy(sling.New().Post("http://test-server.com/Request.Body_xpath").Body(bytes.NewBuffer([]byte(`<?xml version="1.0" encoding="UTF-8"?><root><nottext>test</text></root>`))))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal(""))
		})

		It("Request.Method", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/Request.Method"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal("GET"))
		})

		It("Request.Scheme", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/Request.Scheme"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal("http"))
		})

		It("Request.Path", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/one/two/three/Request.Path"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			// TODO: Handle this?
			Expect(string(body)).To(Equal("onetwothreeRequest.Path"))
		})

		It("Request.Path.[0]", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/one/two/three/Request.Path0"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			// TODO: Handle this?
			Expect(string(body)).To(Equal("one"))
		})

		It("Request.QueryParam", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/Request.QueryParam?query=param"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			// TODO: Handle this?
			Expect(string(body)).To(Equal("map[query:[param]]"))
		})

		It("Request.QueryParam.query", func() {
			hoverfly.ImportSimulation(testdata.TemplatingRequest)

			resp := hoverfly.Proxy(sling.New().Get("http://test-server.com/Request.QueryParam.query?query=param"))
			Expect(resp.StatusCode).To(Equal(200))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).To(BeNil())

			Expect(string(body)).To(Equal("param"))
		})

	})
})

// Credit: https://github.com/asaskevich/govalidator
func IsIPv4(input string) bool {
	ip := net.ParseIP(input)
	return ip != nil && strings.Contains(input, ".")
}

// Credit: https://github.com/asaskevich/govalidator
func IsIPv6(input string) bool {
	ip := net.ParseIP(input)
	return ip != nil && strings.Contains(input, ":")
}

// Credit: https://github.com/badoux/checkmai
func IsEmail(email string) bool {
	emailRegexp := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")

	if !emailRegexp.MatchString(email) {
		return false
	}
	return true
}


text:
#ifndef Parent_h
#define Parent_h

#include "Child.h"

#include <string>
#include <vector>

//! For collection of const children (i.e. each element immutable).
//! Overall collection is also not mutable
template<typename parent, typename child>
using childCollectionConstT = std::vector<std::shared_ptr<const child>> const;

//! Overall collection is not mutable, but each element is mutable
template<typename parent, typename child>
using childCollectionT = std::vector<std::shared_ptr<child>> const&;

//! The class for a parent object
template<typename parent, typename child>
class Parent :
  public std::enable_shared_from_this<parent> // Needed so that a reference to the parent object creating the child object can be stored by the child object.
{
    //! Children
    std::vector<std::shared_ptr<child>> children;

public:
    /** Get read-only collection of children
     *
     * Each child element is immutable.
     * \return The collection of children, read-only.
     */
    childCollectionConstT<parent, child> getChildrenReadOnly() const {
      childCollectionConstT<parent, child> childrenConst(children.begin(), children.end()); // Have to copy to get const version.
      return childrenConst;
    }

    /** Get collection of mutable children
     *
     * Each child element is mutable.
     * Overall membership of collection is still fixed.
     * \return The collection of mutable children.
     */
    childCollectionT<parent, child> getChildren() {
      return children;
    }

    /**
     * Create a child object, of which this object is the parent
     * \return a pointer the newly created child object.
     */
    std::shared_ptr<child> createChild() {
      std::shared_ptr<child> childp(Child<parent, child>::create(Parent<parent, child>::shared_from_this()));
      children.push_back(childp);
      return children.back();
    }

};

#endif


text:
package in.voiceme.app.voiceme.ProfilePage;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.util.List;
import in.voiceme.app.voiceme.R;
import in.voiceme.app.voiceme.infrastructure.Constants;

/**
 * Created by harish on 1/15/2017.
 */

public class FollowerDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final int VIEW_ITEM = 1;
    private final int VIEW_PROG = 0;
    public List<FollowerUserModel> dataSet;

    public FollowerDataAdapter(List<FollowerUserModel> persons) {
        this.dataSet = persons;
    }

    public void animateTo(List<FollowerUserModel> models) {
        applyAndAnimateRemovals(models);
        applyAndAnimateAdditions(models);
        applyAndAnimateMovedItems(models);
    }

    private void applyAndAnimateRemovals(List<FollowerUserModel> newModels) {
        for (int i = dataSet.size() - 1; i >= 0; i--) {
            final FollowerUserModel model = dataSet.get(i);
            if (!newModels.contains(model)) {
                removeItem(i);
            }
        }
    }

    private void applyAndAnimateAdditions(List<FollowerUserModel> newModels) {
        for (int i = 0, count = newModels.size(); i < count; i++) {
            final FollowerUserModel model = newModels.get(i);
            if (!dataSet.contains(model)) {
                addItem(i, model);
            }
        }
    }

    private void applyAndAnimateMovedItems(List<FollowerUserModel> newModels) {
        for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
            final FollowerUserModel model = newModels.get(toPosition);
            final int fromPosition = dataSet.indexOf(model);
            if (fromPosition >= 0 && fromPosition != toPosition) {
                moveItem(fromPosition, toPosition);
            }
        }
    }

    public void addItem(FollowerUserModel item) {
        if (!dataSet.contains(item)) {
            dataSet.add(item);
            notifyItemInserted(dataSet.size() - 1);
        }
    }

    public void addItem(int position, FollowerUserModel model) {
        dataSet.add(position, model);
        notifyItemInserted(position);
    }

    public void removeItem(FollowerUserModel item) {
        int indexOfItem = dataSet.indexOf(item);
        if (indexOfItem != -1) {
            this.dataSet.remove(indexOfItem);
            notifyItemRemoved(indexOfItem);
        }
    }

    public FollowerUserModel removeItem(int position) {
        final FollowerUserModel model = dataSet.remove(position);
        notifyItemRemoved(position);
        return model;
    }

    public void clearItem() {
        if (dataSet != null)
            dataSet.clear();
    }

    public void moveItem(int fromPosition, int toPosition) {
        final FollowerUserModel model = dataSet.remove(fromPosition);
        dataSet.add(toPosition, model);
        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public int getItemViewType(int position) {
        return dataSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
    }

    public FollowerUserModel getItem(int index) {
        if (dataSet != null && dataSet.get(index) != null) {
            return dataSet.get(index);
        } else {
            throw new IllegalArgumentException("Item with index " + index + " doesn't exist, dataSet is " + dataSet);
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        RecyclerView.ViewHolder vh = null;
        if (viewType == VIEW_ITEM) {
            View itemView = LayoutInflater.
                    from(parent.getContext()).
                    inflate(R.layout.item, parent, false);
            vh = new FollowerDataAdapter.PersonViewHolder(itemView);
        } else if (viewType == VIEW_PROG) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.progress_item, parent, false);
            vh = new FollowerDataAdapter.ProgressViewHolder(v);
        } else {
            throw new IllegalStateException("Invalid type, this type ot items " + viewType + " can't be handled");
        }

        return vh;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder personViewHolder, int position) {

        if (personViewHolder instanceof FollowerDataAdapter.PersonViewHolder) {
            FollowerUserModel dataItem = dataSet.get(position);
            ((FollowerDataAdapter.PersonViewHolder) personViewHolder).bind(dataItem);
        } else {
            ((FollowerDataAdapter.ProgressViewHolder) personViewHolder).progressBar.setIndeterminate(true);
        }
    }

    @Override
    public int getItemCount() {
        if (dataSet != null)
            return dataSet.size();
        else
            return 0;
    }

    public static class PersonViewHolder extends FollowerCardViewHolder {

        PersonViewHolder(View itemView) {
            super(itemView);

        }

        @Override
        protected void userNameClicked(View view) {
            Intent intent = new Intent(view.getContext(), SecondProfile.class);
            Toast.makeText(view.getContext(), "Post ID is " + dataItem.getIdUserName(), Toast.LENGTH_SHORT).show();
            intent.putExtra(Constants.SECOND_PROFILE_ID, dataItem.getIdUserName());
            view.getContext().startActivity(intent);
        }

        @Override
        protected void userProfileClicked(View view) {
            Intent intent = new Intent(view.getContext(), SecondProfile.class);
            Toast.makeText(view.getContext(), "Post ID is " + dataItem.getIdUserName(), Toast.LENGTH_SHORT).show();
            intent.putExtra(Constants.SECOND_PROFILE_ID, dataItem.getIdUserName());
            view.getContext().startActivity(intent);
        }

    }

    public static class ProgressViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
        }
    }
}


text:
<?php

/*if setting = 1  setting is open
if setting = 1 setting is closed
*/

//Close / Open registration
$registration_open = 1;
//Close / Open login
$login_open = 1;
//Close / Open dashboard
$dashboard_open = 1;
//Close / Open file uploads
$upload_open = 1;
//Close / Open Upload listing
$listing_open = 1;
//edit file
$editfile = 1;
?>


text:
title: Дочитка объекта данных
sidebar: flexberry-orm_sidebar
keywords: Обхекты данных, Flexberry ORM, дочитка данных, копии данных
summary: Описание способов дочитки данных
toc: true
permalink: ru/fo_additional-loading.html
lang: ru
---

Иногда требуется дочитать ранее не загруженные свойства [объекта данных](fo_data-object.html).

Пусть объект прочитан по [представлению](fd_view-definition.html) "НечтоE". Возможна ситуация, когда для реализации бизнес-логики, например, для выполнения проверок при сохранении объекта, требуется дополнительное подмножество свойств объекта, т.е. объект должен быть загружен по представлению "НечтоПлюсНовыеСвойстваE". Соответственно требуется Дочитать объект.

Существует несколько способов дочитки данных. Идеального способа, подходящего во всех случаях не существует. Для правильной дочитки данных следует прочитать руководство полностью и выберать наиболее походящий способ догрузки данных.

{% include note.html content="Если догружаемый объект только создан и ещё не сохранялся в базу ([статус](fo_object-status.html) `Created`), то само понятие `догрузка` к нему не применимо, так как он ни разу не загружался и не существует в базе данных." %}

## Особенности дочитки данных

* В зависимости от потребностей задачи должен быть выбран способ работы с [копией объекта данных](fo_data-object-copy.html). Если после дочитки будет выполняться сохранение объекта в БД, значения свойств в [копии](fo_data-object-copy.html) должны быть установлены таким образом, чтобы обеспечить сохранение для всех требуемых свойств.
* Если в объекте данных перед дочиткой были свойства с измененными значениями, для дочитки надо выбрать [представление](fd_view-definition.html) таким образом, чтобы не потерять эти новые значения.

## Подходы к дочитке данных

Существует два подхода к реализации дочитки:

* Логика дочитки полностью реализуется прикладным программистом с помощью использования перегрузки метода `LoadObject`.
В этом случае всю последовательность действий по определению догружаемых свойств и способ работы с [копией данных](fo_data-object-copy.html) выбирает сам программист. Это позволяет наиболее тонко учесть особенности дальнейшего использования объекта в прикладной ситуации.
* Догрузка выполняется с помощью метода `SecondLoadObject` класса `SQLDataService`.В данный метод уже `зашита` стандартная, наиболее часто требуемая, логика работы с копией данных, Flexberry Platform избавляет программиста от необходимости собственной реализации.

### Реализация дочитки данных в коде

Когда требуется догрузить данные, а не вычитать объект заново по указанному представлению, следует использовать [перегрузку] метода `LoadObject`(fo_data-service.html) с четырьмя параметрами. Третий из них - `ClearDataObject` - надо устанавливать в `False`.

``` csharp
/// <summary>
/// Загрузка одного объекта данных
/// </summary>
/// <param name="dataObjectView">представление</param>
/// <param name="dobject">бъект данных, который требуется загрузить</param>
/// <param name="ClearDataObject">очищать ли объект</param>
/// <param name="CheckExistingObject">проверять ли существование объекта в хранилище</param>
virtual public void LoadObject(
            ICSSoft.STORMNET.View dataObjectView,
            ICSSoft.STORMNET.DataObject dobj, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache)
```

Если указать `CheckExistingObject = true`, при отсутствии объекта в базе будет выдано исключение типа `CantFindDataObjectException`.

{% include important.html content="При дочитке происходит переинициализация копии данных объекта. Это значит, что изменения, внесённые в объект с момент загрузки объекта данных до момента дочитки объекта данных, не будут сохранены, т.к. при сохранении идёт сравнение значений полей с полями в [копии данных](fo_data-object-copy.html)."%}

При этом надо временно отключать переинициализацию копии данных:

``` csharp
dobj.DisableInitDataCopy(); // запрещаем инициализацию копии данных
ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj, false, false); // дочитка объекта данных
dobj.EnableInitDataCopy();// возвращаем инициализацию копии данных
dobj.GetStatus();//Для того чтобы статус объекта был вычислен по изменённым свойствам относительно копии данных.
```

Важно понимать что после дочитки [статус объекта данных](fo_object-status.html) будет установлен в `UnAltered`, поэтому, если планируется дальнейшее обновление объекта в БД, то не забудьте вызвать `dobj.GetStatus()`, что приведёт к перевычислению статуса по изменённым свойствам относительно [копии данных](fo_data-object-copy.html).

Данный вариант применим только к случаю, когда догружаемый объект используется только для чтения и не будет в дальнейшем сохраняться в базу. Приведённый код приведёт к тому, что в объекте поля, указанные в [представлении](fd_view-definition.html) дочитки, заполнятся, а в копии объекта данных останутся без изменений. Это, в свою очередь, приведёт к тому, что догруженные поля будут считаться изменёнными (так как расходятся с копией данных), и будут обновляться в базе данных. Поэтому если дочитываемый объект данных будет в дальнейшем сохраняться в базу, то необходимо привести в соответствие [копию данных](fo_data-object-copy.html):

``` csharp
dobj.DisableInitDataCopy(); // запрещаем инициализацию копии данных
ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj, false, false); // дочитка объекта данных

// вручную обновляем внутреннюю копию данных
ТипОбъекта внутренКопия = dobj.GetDataCopy();
внутренКопия.Поле1 = dobj.Поле1;
внутренКопия.Поле2 = dobj.Поле2;
//...

внутренКопия.ПолеN = dobj.ПолеN;

dobj.EnableInitDataCopy();// возвращаем инициализацию копии данных
```

Альтернативным вариантом догрузки данных является создания отдельного экземпляра того же типа с таким же [первичным ключом](fo_primary-keys-objects.html) и вычитка по необходимому [представлению](fd_view-definition.html). При этом [представление](fd_view-definition.html) может быть полное или содержать только те атрибуты, которые будут использоваться в дальнейшем:

``` csharp
	// Вручную обновляем внутреннюю копию данных
	ТипОбъекта dobj_forLoading = new ТипОбъекта();
	dobj_forLoading.SetExistingPrimaryKey(dobj.__PrimaryKey);
	// view - требуемое представление. Его состав зависит от задачи.
	ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj_forLoading);
```

{% include note.html content="Если при вызове метода `LoadObject` явно не указать [представление](fd_view-definition.html), то будут вычитываться все собственные поля объекта и ссылки на мастера без собственных полей мастеров. При этом детейлы объекта вычитываться **не будут**." %}

Чтобы дочитать объект таким образом, необходимо использовать перегрузку метода `LoadObject` без параметра типа `View`. К примеру, подойдет самая простая перегрузка:

```csharp
ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(dobj_forLoading);
```

В этом случае объект `dobj_forLoading` также не предназначен для сохранения в базу данных. При этом необходимо понимать, что если объект dobj имеет изменённые свойства (статус `Altered`), то в `dobj_forLoading` они не попадут, так как ещё не сохранены в базу данных. На практике логика не должна зависеть от этого фактора, так как перед дочиткой динамически определяется состав свойств, которые требуется догрузить, при этом изменённые свойства (при правильной проверке) не должны учитываться:

```csharp
View viewДочитки = new View();
viewДочитки.DefineClassType = this.GetType();
if (!dobj.CheckLoadedProperty("Эпизод"))
    viewДочитки.AddProperty("Эпизод");
if (!dobj.CheckLoadedProperty("Эпизод.УД"))
    viewДочитки.AddProperty("Эпизод.УД");
if (!dobj.CheckLoadedProperty("Эпизод.УД.РУОВД"))
    viewДочитки.AddProperty("Эпизод.УД.РУОВД");
if (!dobj.CheckLoadedProperty("Эпизод.УД.РУОВД.Наименование"))
    viewДочитки.AddProperty("Эпизод.УД.РУОВД.Наименование");
if (!dobj.CheckLoadedProperty("Эпизод.УД.ГодДокумента"))
    viewДочитки.AddProperty("Эпизод.УД.ГодДокумента");
if (!dobj.CheckLoadedProperty("Эпизод.УД.НомерУД"))
    viewДочитки.AddProperty("Эпизод.УД.НомерУД");
if (!dobj.CheckLoadedProperty("Эпизод.НомерЭпизода"))
    viewДочитки.AddProperty("Эпизод.НомерЭпизода");
if (!dobj.CheckLoadedProperty("ДатаПоступленияВИЦ"))
    viewДочитки.AddProperty("ДатаПоступленияВИЦ");
if (viewДочитки.Properties.Length > 0)
{
    // дочитка объекта
}
```

### Реализация дочитки средствами Flexberry ORM

Перед использованием данного метода догрузки следует ознакомится с тем, как обновляются значения свойств в обновляемом объекте и его копии, и учитывать это при подготовке объекта к дочитке и его дальнейшем использовании.
Метод имеет следующие параметры:

``` csharp
 /// <summary>
/// Метод для дочитки объекта данных. Загруженные ранее свойства не затираются, изменённые свойства не затираются. Подменяются поштучно свойства копии данных.
/// </summary>
/// <param name="dataObjectView">представление</param>
/// <param name="dataObject">бъект данных, который требуется загрузить</param>
/// <param name="checkExistingObject">проверять ли существование объекта в хранилище</param>
/// <param name="dataObjectCache"></param>
protected virtual void SecondLoadObject(
View dataObjectView,
DataObject dataObject, bool checkExistingObject, DataObjectCache dataObjectCache)
```

### Дочитка собственных свойств

* Все собственные свойства обновляются только если не были загружены ранее.

#### Копия данных

* Если свойство не было загружено, но было изменено, то обновится значение этого свойства в копии данных (т.е. значение в копии синхронизируется с БД).
* Если свойство было вычитано ранее, то значение в его копии данных не меняется.
* Если копия данных не была инициализирована ранее, то она инициализируется в этот раз относительно базы данных по новому представлению. Это означает что **loaded-свойства, которые достались от предыдущей зачитки останутся с неправильными значениями в копии данных, логика по определению изменённых свойств работать не будет, поэтому все свойства, обозначенные в представлении будут обновлены, кроме тех что есть в массиве loaded**
* Если в объекте отключена инициализация копии данных методом `DisableInitDataCopy()`, то копия данных после дочитки не будет инициализирована. По сути это означает что невозможно понять какие свойства были изменены, а какие нет. Массив LoadedProperties будет содержать массив загруженных свойств.

#### Дочитка мастеров

* Если мастер не был вычитан ранее, то он будет зачитан со всеми его мастерами
* Если мастер уже был вычитан, то будут обновлены его свойства по общему принципу
* **Если мастер был зачитан ранее, но был заменён на другой, то будет зачитан новый объект**
* При дочитке мастер проставляется в LoadedProperties даже если явно не был указан в представлении предка и в БД его нет (изменена [стандартная логика](fo_definition-loaded-properties.html)). Мастер не будет указан в LoadedProperties только если LoadingState объекта: `LoadingState.NotLoaded`

##### Копия данных

* По стандартной логике копия данных мастерового объекта инициализируется только первичным ключом.

#### Дочитка детейлов

* Если детейл не участвовал в loadedProperties, то он зачитывается отдельным массивом и присваивается
* Если детейл был загружен, то производится поэлементное слияние. Объекты, которые не были найдены в коллекции, но были загружены из БД будут добавлены


text:
package restclient

const version = "1.0.1"


text:
package org.wso2.carbon.iot.android.sense.event.streams;

import android.content.Context;
import org.wso2.carbon.iot.android.sense.event.streams.location.LocationDataReader;
import org.wso2.carbon.iot.android.sense.event.streams.sensor.SensorDataReader;
import org.wso2.carbon.iot.android.sense.event.streams.speed.SpeedDataReader;
import org.wso2.carbon.iot.android.sense.event.streams.audio.AudioDataReader;

/**
 * This class triggered by service to collect the sensor data.
 */
public class SenseDataCollector {
    public enum DataType {
        SENSOR, LOCATION,SPEED, AUDIO
    }

    public SenseDataCollector(Context ctx, DataType dt) {
        DataReader dr = null;
        switch (dt) {
            case SENSOR:
                dr = new SensorDataReader(ctx);
                break;
            case LOCATION:
                dr = new LocationDataReader(ctx);
                break;
            case SPEED:
                dr = new SpeedDataReader(ctx);
                break;
            case AUDIO:
                dr = new AudioDataReader(ctx);
                break;

        }
        if (dr != null) {
            Thread DataCollector = new Thread(dr);
            DataCollector.start();
        }
    }
}


text:
"""Utilities for exporting TensorFlow symbols to the API.

Exporting a function or a class:

To export a function or a class use tf_export decorator. For e.g.:
```python
@tf_export('foo', 'bar.foo')
def foo(...):
  ...
```

If a function is assigned to a variable, you can export it by calling
tf_export explicitly. For e.g.:
```python
foo = get_foo(...)
tf_export('foo', 'bar.foo')(foo)
```

Exporting a constant
```python
foo = 1
tf_export('consts.foo').export_constant(__name__, 'foo')
```
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import functools
import sys

from tensorflow.python.util import tf_decorator

ESTIMATOR_API_NAME = 'estimator'
TENSORFLOW_API_NAME = 'tensorflow'

# List of subpackage names used by TensorFlow components. Have to check that
# TensorFlow core repo does not export any symbols under these names.
SUBPACKAGE_NAMESPACES = [ESTIMATOR_API_NAME]

_Attributes = collections.namedtuple(
    'ExportedApiAttributes', ['names', 'constants'])

# Attribute values must be unique to each API.
API_ATTRS = {
    TENSORFLOW_API_NAME: _Attributes(
        '_tf_api_names',
        '_tf_api_constants'),
    ESTIMATOR_API_NAME: _Attributes(
        '_estimator_api_names',
        '_estimator_api_constants')
}

API_ATTRS_V1 = {
    TENSORFLOW_API_NAME: _Attributes(
        '_tf_api_names_v1',
        '_tf_api_constants_v1'),
    ESTIMATOR_API_NAME: _Attributes(
        '_estimator_api_names_v1',
        '_estimator_api_constants_v1')
}

class SymbolAlreadyExposedError(Exception):
  """Raised when adding API names to symbol that already has API names."""
  pass

class InvalidSymbolNameError(Exception):
  """Raised when trying to export symbol as an invalid or unallowed name."""
  pass

def get_canonical_name_for_symbol(
    symbol, api_name=TENSORFLOW_API_NAME,
    add_prefix_to_v1_names=False):
  """Get canonical name for the API symbol.

  Args:
    symbol: API function or class.
    api_name: API name (tensorflow or estimator).
    add_prefix_to_v1_names: Specifies whether a name available only in V1
      should be prefixed with compat.v1.

  Returns:
    Canonical name for the API symbol (for e.g. initializers.zeros) if
    canonical name could be determined. Otherwise, returns None.
  """
  if not hasattr(symbol, '__dict__'):
    return None
  api_names_attr = API_ATTRS[api_name].names
  _, undecorated_symbol = tf_decorator.unwrap(symbol)
  if api_names_attr not in undecorated_symbol.__dict__:
    return None
  api_names = getattr(undecorated_symbol, api_names_attr)
  deprecated_api_names = undecorated_symbol.__dict__.get(
      '_tf_deprecated_api_names', [])

  canonical_name = get_canonical_name(api_names, deprecated_api_names)
  if canonical_name:
    return canonical_name

  # If there is no V2 canonical name, get V1 canonical name.
  api_names_attr = API_ATTRS_V1[api_name].names
  api_names = getattr(undecorated_symbol, api_names_attr)
  v1_canonical_name = get_canonical_name(api_names, deprecated_api_names)
  if add_prefix_to_v1_names:
    return 'compat.v1.%s' % v1_canonical_name
  return v1_canonical_name

def get_canonical_name(api_names, deprecated_api_names):
  """Get preferred endpoint name.

  Args:
    api_names: API names iterable.
    deprecated_api_names: Deprecated API names iterable.
  Returns:
    Returns one of the following in decreasing preference:
    - first non-deprecated endpoint
    - first endpoint
    - None
  """
  non_deprecated_name = next(
      (name for name in api_names if name not in deprecated_api_names),
      None)
  if non_deprecated_name:
    return non_deprecated_name
  if api_names:
    return api_names[0]
  return None

class api_export(object):  # pylint: disable=invalid-name
  """Provides ways to export symbols to the TensorFlow API."""

  def __init__(self, *args, **kwargs):
    """Export under the names *args (first one is considered canonical).

    Args:
      *args: API names in dot delimited format.
      **kwargs: Optional keyed arguments.
        v1: Names for the TensorFlow V1 API. If not set, we will use V2 API
          names both for TensorFlow V1 and V2 APIs.
        overrides: List of symbols that this is overriding
          (those overrided api exports will be removed). Note: passing overrides
          has no effect on exporting a constant.
        api_name: Name of the API you want to generate (e.g. `tensorflow` or
          `estimator`). Default is `tensorflow`.
        allow_multiple_exports: Allow symbol to be exported multiple time under
          different names.
    """
    self._names = args
    self._names_v1 = kwargs.get('v1', args)
    self._api_name = kwargs.get('api_name', TENSORFLOW_API_NAME)
    self._overrides = kwargs.get('overrides', [])
    self._allow_multiple_exports = kwargs.get('allow_multiple_exports', False)

    self._validate_symbol_names()

  def _validate_symbol_names(self):
    """Validate you are exporting symbols under an allowed package.

    We need to ensure things exported by tf_export, estimator_export, etc.
    export symbols under disjoint top-level package names.

    For TensorFlow, we check that it does not export anything under subpackage
    names used by components (estimator, keras, etc.).

    For each component, we check that it exports everything under its own
    subpackage.

    Raises:
      InvalidSymbolNameError: If you try to export symbol under disallowed name.
    """
    all_symbol_names = set(self._names) | set(self._names_v1)
    if self._api_name == TENSORFLOW_API_NAME:
      for subpackage in SUBPACKAGE_NAMESPACES:
        if any(n.startswith(subpackage) for n in all_symbol_names):
          raise InvalidSymbolNameError(
              '@tf_export is not allowed to export symbols under %s.*' % (
                  subpackage))
    else:
      if not all(n.startswith(self._api_name) for n in all_symbol_names):
        raise InvalidSymbolNameError(
            'Can only export symbols under package name of component. '
            'e.g. tensorflow_estimator must export all symbols under '
            'tf.estimator')

  def __call__(self, func):
    """Calls this decorator.

    Args:
      func: decorated symbol (function or class).

    Returns:
      The input function with _tf_api_names attribute set.

    Raises:
      SymbolAlreadyExposedError: Raised when a symbol already has API names
        and kwarg `allow_multiple_exports` not set.
    """
    api_names_attr = API_ATTRS[self._api_name].names
    api_names_attr_v1 = API_ATTRS_V1[self._api_name].names
    # Undecorate overridden names
    for f in self._overrides:
      _, undecorated_f = tf_decorator.unwrap(f)
      delattr(undecorated_f, api_names_attr)
      delattr(undecorated_f, api_names_attr_v1)

    _, undecorated_func = tf_decorator.unwrap(func)
    self.set_attr(undecorated_func, api_names_attr, self._names)
    self.set_attr(undecorated_func, api_names_attr_v1, self._names_v1)
    return func

  def set_attr(self, func, api_names_attr, names):
    # Check for an existing api. We check if attribute name is in
    # __dict__ instead of using hasattr to verify that subclasses have
    # their own _tf_api_names as opposed to just inheriting it.
    if api_names_attr in func.__dict__:
      if not self._allow_multiple_exports:
        raise SymbolAlreadyExposedError(
            'Symbol %s is already exposed as %s.' %
            (func.__name__, getattr(func, api_names_attr)))  # pylint: disable=protected-access
    setattr(func, api_names_attr, names)

  def export_constant(self, module_name, name):
    """Store export information for constants/string literals.

    Export information is stored in the module where constants/string literals
    are defined.

    e.g.
    ```python
    foo = 1
    bar = 2
    tf_export("consts.foo").export_constant(__name__, 'foo')
    tf_export("consts.bar").export_constant(__name__, 'bar')
    ```

    Args:
      module_name: (string) Name of the module to store constant at.
      name: (string) Current constant name.
    """
    module = sys.modules[module_name]
    api_constants_attr = API_ATTRS[self._api_name].constants
    api_constants_attr_v1 = API_ATTRS_V1[self._api_name].constants

    if not hasattr(module, api_constants_attr):
      setattr(module, api_constants_attr, [])
    # pylint: disable=protected-access
    getattr(module, api_constants_attr).append(
        (self._names, name))

    if not hasattr(module, api_constants_attr_v1):
      setattr(module, api_constants_attr_v1, [])
    getattr(module, api_constants_attr_v1).append(
        (self._names_v1, name))

tf_export = functools.partial(api_export, api_name=TENSORFLOW_API_NAME)
estimator_export = functools.partial(api_export, api_name=ESTIMATOR_API_NAME)


text:
@interface CMRamotionSpinerLayer : CAShapeLayer

@property (nonatomic, assign) CGFloat circleWidth;
@property (nonatomic, strong) UIColor *ballColor;
@property (nonatomic, assign) CGFloat startAngle;
@property (nonatomic, assign) CGFloat endAngle;
@property (nonatomic, assign) CGFloat rotateAngle;
@property (nonatomic, assign) float displaySpeed;

- (void)startAnimation;
- (void)stopAnimation;

@end


text:
using System;
using System.Collections.Generic;
using BorderSkin.BorderSkinning.Skin;
using WinApiWrappers;

namespace BorderSkin.Execlusion
{
    class ExcludedWindow : IDisposable
    {

        private string _classNames;
        private readonly HashSet<string> _classNamesSet = new HashSet<string>();
        private bool _disposedValue;

        public ExcludedWindow(string exclusionName, string processName, string classNames, string skinName, string colorSchemeName, bool hasSkin)
        {
            ExclusionName = exclusionName;
            ProcessName = processName.ToLower();

            ClassNames = classNames;

            SkinName = skinName;
            ColorSchemeName = colorSchemeName;
            HasSkin = hasSkin;
            if (hasSkin)
            {
                Skin = WindowBorderSkinProvider.LoadTheme(skinName, colorSchemeName);
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue) {
                if (HasSkin) {
                    Skin.Dispose();
                }
            }
            _disposedValue = true;
        }

        public string ExclusionName { get; set; }

        public string ProcessName { get; set; }

        public string WindowName { get; set; }

        public string SkinName { get; set; }

        public string ColorSchemeName { get; set; }

        public bool HasSkin { get; set; }

        public WindowBorderSkin Skin { get; set; }

        public string ClassNames
        {
            get { return _classNames; }
            set
            {
                _classNames = value;

                foreach (var name in _classNames.Split(','))
                {
                    if (name != String.Empty)
                        _classNamesSet.Add(name.ToLower());
                }
            }
        }

        public bool ClassContains(string windowClassName)
        {
            return _classNamesSet.Count == 0 || _classNamesSet.Contains(windowClassName.ToLower());
        }

        public bool CheckWindow(TopLevelWindow window)
        {
            return ProcessName.Equals(window.ProcessName, StringComparison.OrdinalIgnoreCase) &&
                   ClassContains(window.ClassName);
        }
    }
}


text:
package sjph.life.user.database.schema;

/**
 * Database access constants.
 */
public interface DatabaseConstants {

    /**
     * The prefix to schema object names that is dynamically replaced typically with the
     * Oracle schema or MySQL database name.
     */
    String SCHEMA_OBJECT_PREFIX   = "/* ?. */";

    /**
     * The prefix to syslocal object names.
     */
    String SYSLOCAL_OBJECT_PREFIX = "/*SYSLOCAL*/";

    /**
     * The database role assigned to the shared connection pool user for accessing objects in
     * account schemas.
     */
    String SHARED_CONN_POOL_ROLE  = "SHARED_CONN_POOL_ROLE";
}