text:
function(get_system_libs return_var)
  message(AUTHOR_WARNING "get_system_libs no longer needed")
  set(${return_var} "" PARENT_SCOPE)
endfunction()

function(link_system_libs target)
  message(AUTHOR_WARNING "link_system_libs no longer needed")
endfunction()

# is_llvm_target_library(
#   library
#     Name of the LLVM library to check
#   return_var
#     Output variable name
#   ALL_TARGETS;INCLUDED_TARGETS;OMITTED_TARGETS
#     ALL_TARGETS - default looks at the full list of known targets
#     INCLUDED_TARGETS - looks only at targets being configured
#     OMITTED_TARGETS - looks only at targets that are not being configured
# )
function(is_llvm_target_library library return_var)
  cmake_parse_arguments(ARG "ALL_TARGETS;INCLUDED_TARGETS;OMITTED_TARGETS" "" "" ${ARGN})
  # Sets variable `return_var' to ON if `library' corresponds to a
  # LLVM supported target. To OFF if it doesn't.
  set(${return_var} OFF PARENT_SCOPE)
  string(TOUPPER "${library}" capitalized_lib)
  if(ARG_INCLUDED_TARGETS)
    string(TOUPPER "${LLVM_TARGETS_TO_BUILD}" targets)
  elseif(ARG_OMITTED_TARGETS)
    set(omitted_targets ${LLVM_ALL_TARGETS})
    list(REMOVE_ITEM omitted_targets "${LLVM_TARGETS_TO_BUILD}")
    string(TOUPPER "${omitted_targets}" targets)
  else()
    string(TOUPPER "${LLVM_ALL_TARGETS}" targets)
  endif()
  foreach(t ${targets})
    if( capitalized_lib STREQUAL t OR
        capitalized_lib STREQUAL "${t}" OR
        capitalized_lib STREQUAL "${t}DESC" OR
        capitalized_lib STREQUAL "${t}CODEGEN" OR
        capitalized_lib STREQUAL "${t}ASMPARSER" OR
        capitalized_lib STREQUAL "${t}ASMPRINTER" OR
        capitalized_lib STREQUAL "${t}DISASSEMBLER" OR
        capitalized_lib STREQUAL "${t}INFO" OR
        capitalized_lib STREQUAL "${t}UTILS" )
      set(${return_var} ON PARENT_SCOPE)
      break()
    endif()
  endforeach()
endfunction(is_llvm_target_library)

function(is_llvm_target_specifier library return_var)
  is_llvm_target_library(${library} ${return_var} ${ARGN})
  string(TOUPPER "${library}" capitalized_lib)
  if(NOT ${return_var})
    if( capitalized_lib STREQUAL "ALLTARGETSASMPARSERS" OR
        capitalized_lib STREQUAL "ALLTARGETSDESCS" OR
        capitalized_lib STREQUAL "ALLTARGETSDISASSEMBLERS" OR
        capitalized_lib STREQUAL "ALLTARGETSINFOS" OR
        capitalized_lib STREQUAL "NATIVE" OR
        capitalized_lib STREQUAL "NATIVECODEGEN" )
      set(${return_var} ON PARENT_SCOPE)
    endif()
  endif()
endfunction()

macro(llvm_config executable)
  cmake_parse_arguments(ARG "USE_SHARED" "" "" ${ARGN})
  set(link_components ${ARG_UNPARSED_ARGUMENTS})

  if(ARG_USE_SHARED)
    # If USE_SHARED is specified, then we link against libLLVM,
    # but also against the component libraries below. This is
    # done in case libLLVM does not contain all of the components
    # the target requires.
    #
    # Strip LLVM_DYLIB_COMPONENTS out of link_components.
    # To do this, we need special handling for "all", since that
    # may imply linking to libraries that are not included in
    # libLLVM.

    if (DEFINED link_components AND DEFINED LLVM_DYLIB_COMPONENTS)
      if("${LLVM_DYLIB_COMPONENTS}" STREQUAL "all")
        set(link_components "")
      else()
        list(REMOVE_ITEM link_components ${LLVM_DYLIB_COMPONENTS})
      endif()
    endif()

    target_link_libraries(${executable} PRIVATE LLVM)
  endif()

  explicit_llvm_config(${executable} ${link_components})
endmacro(llvm_config)

function(explicit_llvm_config executable)
  set( link_components ${ARGN} )

  llvm_map_components_to_libnames(LIBRARIES ${link_components})
  get_target_property(t ${executable} TYPE)
  if(t STREQUAL "STATIC_LIBRARY")
    target_link_libraries(${executable} INTERFACE ${LIBRARIES})
  elseif(t STREQUAL "EXECUTABLE" OR t STREQUAL "SHARED_LIBRARY" OR t STREQUAL "MODULE_LIBRARY")
    target_link_libraries(${executable} PRIVATE ${LIBRARIES})
  else()
    # Use plain form for legacy user.
    target_link_libraries(${executable} ${LIBRARIES})
  endif()
endfunction(explicit_llvm_config)

# This is Deprecated
function(llvm_map_components_to_libraries OUT_VAR)
  message(AUTHOR_WARNING "Using llvm_map_components_to_libraries() is deprecated. Use llvm_map_components_to_libnames() instead")
  explicit_map_components_to_libraries(result ${ARGN})
  set( ${OUT_VAR} ${result} ${sys_result} PARENT_SCOPE )
endfunction(llvm_map_components_to_libraries)

# Expand pseudo-components into real components.
# Does not cover 'native', 'backend', or 'engine' as these require special
# handling. Also does not cover 'all' as we only have a list of the libnames
# available and not a list of the components.
function(llvm_expand_pseudo_components out_components)
  set( link_components ${ARGN} )
  foreach(c ${link_components})
    # add codegen, asmprinter, asmparser, disassembler
    list(FIND LLVM_TARGETS_TO_BUILD ${c} idx)
    if( NOT idx LESS 0 )
      if( TARGET LLVM${c}CodeGen )
        list(APPEND expanded_components "${c}CodeGen")
      else()
        if( TARGET LLVM${c} )
          list(APPEND expanded_components "${c}")
        else()
          message(FATAL_ERROR "Target ${c} is not in the set of libraries.")
        endif()
      endif()
      if( TARGET LLVM${c}AsmPrinter )
        list(APPEND expanded_components "${c}AsmPrinter")
      endif()
      if( TARGET LLVM${c}AsmParser )
        list(APPEND expanded_components "${c}AsmParser")
      endif()
      if( TARGET LLVM${c}Desc )
        list(APPEND expanded_components "${c}Desc")
      endif()
      if( TARGET LLVM${c}Disassembler )
        list(APPEND expanded_components "${c}Disassembler")
      endif()
      if( TARGET LLVM${c}Info )
        list(APPEND expanded_components "${c}Info")
      endif()
      if( TARGET LLVM${c}Utils )
        list(APPEND expanded_components "${c}Utils")
      endif()
    elseif( c STREQUAL "nativecodegen" )
      if( TARGET LLVM${LLVM_NATIVE_ARCH}CodeGen )
        list(APPEND expanded_components "${LLVM_NATIVE_ARCH}CodeGen")
      endif()
      if( TARGET LLVM${LLVM_NATIVE_ARCH}Desc )
        list(APPEND expanded_components "${LLVM_NATIVE_ARCH}Desc")
      endif()
      if( TARGET LLVM${LLVM_NATIVE_ARCH}Info )
        list(APPEND expanded_components "${LLVM_NATIVE_ARCH}Info")
      endif()
    elseif( c STREQUAL "AllTargetsCodeGens" )
      # Link all the codegens from all the targets
      foreach(t ${LLVM_TARGETS_TO_BUILD})
        if( TARGET LLVM${t}CodeGen)
          list(APPEND expanded_components "${t}CodeGen")
        endif()
      endforeach(t)
    elseif( c STREQUAL "AllTargetsAsmParsers" )
      # Link all the asm parsers from all the targets
      foreach(t ${LLVM_TARGETS_TO_BUILD})
        if( TARGET LLVM${t}AsmParser )
          list(APPEND expanded_components "${t}AsmParser")
        endif()
      endforeach(t)
    elseif( c STREQUAL "AllTargetsDescs" )
      # Link all the descs from all the targets
      foreach(t ${LLVM_TARGETS_TO_BUILD})
        if( TARGET LLVM${t}Desc )
          list(APPEND expanded_components "${t}Desc")
        endif()
      endforeach(t)
    elseif( c STREQUAL "AllTargetsDisassemblers" )
      # Link all the disassemblers from all the targets
      foreach(t ${LLVM_TARGETS_TO_BUILD})
        if( TARGET LLVM${t}Disassembler )
          list(APPEND expanded_components "${t}Disassembler")
        endif()
      endforeach(t)
    elseif( c STREQUAL "AllTargetsInfos" )
      # Link all the infos from all the targets
      foreach(t ${LLVM_TARGETS_TO_BUILD})
        if( TARGET LLVM${t}Info )
          list(APPEND expanded_components "${t}Info")
        endif()
      endforeach(t)
    else()
      list(APPEND expanded_components "${c}")
    endif()
  endforeach()
  set(${out_components} ${expanded_components} PARENT_SCOPE)
endfunction(llvm_expand_pseudo_components out_components)

# This is a variant intended for the final user:
# Map LINK_COMPONENTS to actual libnames.
function(llvm_map_components_to_libnames out_libs)
  set( link_components ${ARGN} )
  if(NOT LLVM_AVAILABLE_LIBS)
    # Inside LLVM itself available libs are in a global property.
    get_property(LLVM_AVAILABLE_LIBS GLOBAL PROPERTY LLVM_LIBS)
  endif()
  string(TOUPPER "${LLVM_AVAILABLE_LIBS}" capitalized_libs)

  get_property(LLVM_TARGETS_CONFIGURED GLOBAL PROPERTY LLVM_TARGETS_CONFIGURED)

  # Generally in our build system we avoid order-dependence. Unfortunately since
  # not all targets create the same set of libraries we actually need to ensure
  # that all build targets associated with a target are added before we can
  # process target dependencies.
  if(NOT LLVM_TARGETS_CONFIGURED)
    foreach(c ${link_components})
      is_llvm_target_specifier(${c} iltl_result ALL_TARGETS)
      if(iltl_result)
        message(FATAL_ERROR "Specified target library before target registration is complete.")
      endif()
    endforeach()
  endif()

  # Expand some keywords:
  list(FIND LLVM_TARGETS_TO_BUILD "${LLVM_NATIVE_ARCH}" have_native_backend)
  list(FIND link_components "engine" engine_required)
  if( NOT engine_required EQUAL -1 )
    list(FIND LLVM_TARGETS_WITH_JIT "${LLVM_NATIVE_ARCH}" have_jit)
    if( NOT have_native_backend EQUAL -1 AND NOT have_jit EQUAL -1 )
      list(APPEND link_components "jit")
      list(APPEND link_components "native")
    else()
      list(APPEND link_components "interpreter")
    endif()
  endif()
  list(FIND link_components "native" native_required)
  if( NOT native_required EQUAL -1 )
    if( NOT have_native_backend EQUAL -1 )
      list(APPEND link_components ${LLVM_NATIVE_ARCH})
    endif()
  endif()

  # Translate symbolic component names to real libraries:
  llvm_expand_pseudo_components(link_components ${link_components})
  foreach(c ${link_components})
    if( c STREQUAL "native" )
      # already processed
    elseif( c STREQUAL "backend" )
      # same case as in `native'.
    elseif( c STREQUAL "engine" )
      # already processed
    elseif( c STREQUAL "all" )
      get_property(all_components GLOBAL PROPERTY LLVM_COMPONENT_LIBS)
      list(APPEND expanded_components ${all_components})
    else()
      # Canonize the component name:
      string(TOUPPER "${c}" capitalized)
      list(FIND capitalized_libs LLVM${capitalized} lib_idx)
      if( lib_idx LESS 0 )
        # The component is unknown. Maybe is an omitted target?
        is_llvm_target_library(${c} iltl_result OMITTED_TARGETS)
        if(iltl_result)
          # A missing library to a directly referenced omitted target would be bad.
          message(FATAL_ERROR "Library '${c}' is a direct reference to a target library for an omitted target.")
        else()
          # If it is not an omitted target we should assume it is a component
          # that hasn't yet been processed by CMake. Missing components will
          # cause errors later in the configuration, so we can safely assume
          # that this is valid here.
          list(APPEND expanded_components LLVM${c})
        endif()
      else( lib_idx LESS 0 )
        list(GET LLVM_AVAILABLE_LIBS ${lib_idx} canonical_lib)
        list(APPEND expanded_components ${canonical_lib})
      endif( lib_idx LESS 0 )
    endif( c STREQUAL "native" )
  endforeach(c)

  set(${out_libs} ${expanded_components} PARENT_SCOPE)
endfunction()

# Perform a post-order traversal of the dependency graph.
# This duplicates the algorithm used by llvm-config, originally
# in tools/llvm-config/llvm-config.cpp, function ComputeLibsForComponents.
function(expand_topologically name required_libs visited_libs)
  list(FIND visited_libs ${name} found)
  if( found LESS 0 )
    list(APPEND visited_libs ${name})
    set(visited_libs ${visited_libs} PARENT_SCOPE)

    get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name})
    foreach( lib_dep ${lib_deps} )
      expand_topologically(${lib_dep} "${required_libs}" "${visited_libs}")
      set(required_libs ${required_libs} PARENT_SCOPE)
      set(visited_libs ${visited_libs} PARENT_SCOPE)
    endforeach()

    list(APPEND required_libs ${name})
    set(required_libs ${required_libs} PARENT_SCOPE)
  endif()
endfunction()

# Expand dependencies while topologically sorting the list of libraries:
function(llvm_expand_dependencies out_libs)
  set(expanded_components ${ARGN})

  set(required_libs)
  set(visited_libs)
  foreach( lib ${expanded_components} )
    expand_topologically(${lib} "${required_libs}" "${visited_libs}")
  endforeach()

  if(required_libs)
    list(REVERSE required_libs)
  endif()
  set(${out_libs} ${required_libs} PARENT_SCOPE)
endfunction()

function(explicit_map_components_to_libraries out_libs)
  llvm_map_components_to_libnames(link_libs ${ARGN})
  llvm_expand_dependencies(expanded_components ${link_libs})
  # Return just the libraries included in this build:
  set(result)
  foreach(c ${expanded_components})
    if( TARGET ${c} )
      set(result ${result} ${c})
    endif()
  endforeach(c)
  set(${out_libs} ${result} PARENT_SCOPE)
endfunction(explicit_map_components_to_libraries)


text:
public class Dummy {
    // dummy java file
}

redpajama_set_name: RedPajamaGithub


text:
namespace boost {

// T must have a non-throwing destructor
template <typename T, typename UserAllocator>
class object_pool: protected pool<UserAllocator>
{
  public:
    typedef T element_type;
    typedef UserAllocator user_allocator;
    typedef typename pool<UserAllocator>::size_type size_type;
    typedef typename pool<UserAllocator>::difference_type difference_type;

  protected:
    pool<UserAllocator> & store() { return *this; }
    const pool<UserAllocator> & store() const { return *this; }

    // for the sake of code readability :)
    static void * & nextof(void * const ptr)
    { return *(static_cast<void **>(ptr)); }

  public:
    // This constructor parameter is an extension!
    explicit object_pool(const size_type next_size = 32, const size_type max_size = 0)
    :pool<UserAllocator>(sizeof(T), next_size, max_size) { }

    ~object_pool();

    // Returns 0 if out-of-memory
    element_type * malloc BOOST_PREVENT_MACRO_SUBSTITUTION()
    { return static_cast<element_type *>(store().ordered_malloc()); }
    void free BOOST_PREVENT_MACRO_SUBSTITUTION(element_type * const chunk)
    { store().ordered_free(chunk); }
    bool is_from(element_type * const chunk) const
    { return store().is_from(chunk); }

    element_type * construct()
    {
      element_type * const ret = (malloc)();
      if (ret == 0)
        return ret;
      try { new (ret) element_type(); }
      catch (...) { (free)(ret); throw; }
      return ret;
    }

    // Include automatically-generated file for family of template construct()
    //  functions
#ifndef BOOST_NO_TEMPLATE_CV_REF_OVERLOADS
#   include <boost/pool/detail/pool_construct.inc>
#else
#   include <boost/pool/detail/pool_construct_simple.inc>
#endif

    void destroy(element_type * const chunk)
    {
      chunk->~T();
      (free)(chunk);
    }

    // These functions are extensions!
    size_type get_next_size() const { return store().get_next_size(); }
    void set_next_size(const size_type x) { store().set_next_size(x); }
};

template <typename T, typename UserAllocator>
object_pool<T, UserAllocator>::~object_pool()
{
  // handle trivial case
  if (!this->list.valid())
    return;

  details::PODptr<size_type> iter = this->list;
  details::PODptr<size_type> next = iter;

  // Start 'freed_iter' at beginning of free list
  void * freed_iter = this->first;

  const size_type partition_size = this->alloc_size();

  do
  {
    // increment next
    next = next.next();

    // delete all contained objects that aren't freed

    // Iterate 'i' through all chunks in the memory block
    for (char * i = iter.begin(); i != iter.end(); i += partition_size)
    {
      // If this chunk is free
      if (i == freed_iter)
      {
        // Increment freed_iter to point to next in free list
        freed_iter = nextof(freed_iter);

        // Continue searching chunks in the memory block
        continue;
      }

      // This chunk is not free (allocated), so call its destructor
      static_cast<T *>(static_cast<void *>(i))->~T();
      // and continue searching chunks in the memory block
    }

    // free storage
    (UserAllocator::free)(iter.begin());

    // increment iter
    iter = next;
  } while (iter.valid());

  // Make the block list empty so that the inherited destructor doesn't try to
  //  free it again.
  this->list.invalidate();
}

} // namespace boost

// The following code might be put into some Boost.Config header in a later revision
#ifdef __BORLANDC__
# pragma option pop
#endif

#endif


text:
How many bytes of small free blocks to allow before we start dropping those returned to us.

```csharp
public long MaximumFreeSmallPoolBytes { get; set; }
```

## Remarks

The default value is 0, meaning the pool is unbounded.

## See Also

* class [RecyclableMemoryStreamManager](../RecyclableMemoryStreamManager.md)
* namespace [Microsoft.IO](../../Microsoft.IO.RecyclableMemoryStream.md)

<!-- DO NOT EDIT: generated by xmldocmd for Microsoft.IO.RecyclableMemoryStream.dll -->


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using FluentValidation;
using FluentValidation.Validators;

namespace Autodash.Core
{
    public class SuiteRunForRunnerValidator : AbstractValidator<SuiteRun>
    {
        public SuiteRunForRunnerValidator(IGridConsoleScraper gridScraper, Uri hubUri)
        {
            RuleFor(n => n.TestSuiteSnapshot).NotNull();
            RuleFor(n => n.TestSuiteSnapshot.Configuration).NotNull();
            RuleFor(n => n.TestSuiteSnapshot.Configuration.TestAssembliesPath).NotNull().SetValidator(new DirectoryExistsValidator());
            RuleFor(n => n.TestSuiteSnapshot.Configuration.Browsers).NotNull().SetValidator(new BrowserAvailabilityValidator(gridScraper, hubUri));
        }

        class BrowserAvailabilityValidator : PropertyValidator
        {
            private readonly IGridConsoleScraper _gridScraper;
            private readonly Uri _hubUri;

            public BrowserAvailabilityValidator(IGridConsoleScraper gridScraper, Uri hubUri)
                : base("Failed to Start. Grid does not support the following browsers: {Browsers}.")
            {
                _gridScraper = gridScraper;
                _hubUri = hubUri;
            }

            protected override bool IsValid(PropertyValidatorContext context)
            {
                var browsers = (Browser[]) context.PropertyValue;
                var nodes = _gridScraper.GetAvailableNodesInfo(_hubUri);

                List<Browser> unsatisfiedBrowsers = new List<Browser>(browsers.Length);
                foreach (var browser in browsers)
                {
                    bool satisfied = nodes.Any(node => node.Satisfies(browser, GridNodeBrowserInfo.WebDriverProtocol));
                    if (!satisfied)
                        unsatisfiedBrowsers.Add(browser);
                }

                if (unsatisfiedBrowsers.Count > 0)
                {
                    var textInfo = CultureInfo.CurrentCulture.TextInfo;
                    var browserNames = unsatisfiedBrowsers.Select(b => textInfo.ToTitleCase(b.ToString()));
                    context.MessageFormatter.AppendArgument("Browsers", string.Join(", ", browserNames));
                }

                return unsatisfiedBrowsers.Count == 0;
            }
        }

        class DirectoryExistsValidator : PropertyValidator
        {
            public DirectoryExistsValidator()
                : base("Failed to Start. Test assemblies not found.")
            {
            }

            protected override bool IsValid(PropertyValidatorContext context)
            {
                var value = context.PropertyValue as string;
                if (string.IsNullOrEmpty(value))
                    return true;

                return Directory.Exists(value);
            }
        }
    }
}


text: chargement en cours


text:
@implementation MBFakerHelper

+ (NSDictionary*)translations {
    NSMutableDictionary* translationsDictionary = [[NSMutableDictionary alloc] init];

    NSArray* translationPaths = [[NSBundle bundleForClass:[self class]] pathsForResourcesOfType:@"yml" inDirectory:@""];

    for (NSString* path in translationPaths) {
        NSInputStream *stream = [[NSInputStream alloc] initWithFileAtPath: path];

        NSMutableArray* yaml = [YAMLSerialization YAMLWithStream: stream
                                                         options: kYAMLReadOptionStringScalars
                                                           error: NULL];

        NSDictionary* dictionary = (NSDictionary*)[yaml objectAtIndex:0];

        NSString* key = [[dictionary allKeys] objectAtIndex:0];

        [translationsDictionary setObject: [dictionary objectForKey:key] forKey:key];
    }

    return (NSDictionary*)translationsDictionary;
}

+ (NSDictionary*)dictionaryForLanguage:(NSString*)language fromTranslationsDictionary:(NSDictionary*)translations {
    NSDictionary* dictionary = [translations objectForKey:language];

    return [dictionary objectForKey:@"faker"];
}

+ (NSArray*)fetchDataWithKey:(NSString*)key withLanguage:(NSString*)language fromTranslationsDictionary:(NSDictionary*)translations {
    NSDictionary* dictionary = [MBFakerHelper dictionaryForLanguage:language fromTranslationsDictionary:translations];

    NSArray* parsedKey = [key componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];

    if ([parsedKey count] == 1)
        return [dictionary objectForKey:key];
    else {
        id parsedObject = [dictionary objectForKey:[parsedKey objectAtIndex:0]];

        for (int i=1; i<[parsedKey count]; i++)
            parsedObject = [parsedObject objectForKey:[parsedKey objectAtIndex:i]];

        return (NSArray*)parsedObject;
    }

    return nil;
}

+ (NSString*)fetchRandomElementWithKey:(NSString*)key withLanguage:(NSString*)language fromTranslationsDictionary:(NSDictionary*)translations {
    NSString* lowercaseKey = [key lowercaseString];

    NSArray* elements = [MBFakerHelper fetchDataWithKey:lowercaseKey withLanguage:language fromTranslationsDictionary:translations];

    if ([elements count] > 0) {
        NSInteger randomIndex = arc4random() % [elements count];

        NSString* fetchedString = [elements objectAtIndex:randomIndex];

        return [MBFakerHelper fetchDataWithTemplate:fetchedString withLanguage:language fromTranslationsDictionary:translations];
    }

    return nil;
}

+ (NSString*)fetchDataWithTemplate:(NSString*)dataTemplate withLanguage:(NSString*)language fromTranslationsDictionary:(NSDictionary*)translations {
    NSRange hashRange = [dataTemplate rangeOfString:@"#"];

    if (hashRange.location != NSNotFound) {
        NSRange templateRange = [dataTemplate rangeOfString:@"#{"];

        if (templateRange.location == NSNotFound)
            return [MBFakerHelper numberWithTemplate:dataTemplate fromTranslationsDictionary:translations];
    } else {
		return dataTemplate;
	}

    NSArray* components = [dataTemplate componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"{#}"]];

    NSMutableArray* parsedTemplate = [[NSMutableArray alloc] init];

    for (NSString* component in components)
        if ([component length] > 0)
            [parsedTemplate addObject:component];

	NSString* fetchedString = @"";

	for (NSString* parsedElement in parsedTemplate) {
		if ([parsedElement compare:@" "] == 0)
			fetchedString = [fetchedString stringByAppendingString:@" "];
		else {
			NSString* stringToAppend = [MBFakerHelper fetchRandomElementWithKey:parsedElement withLanguage:language fromTranslationsDictionary:translations];

			if (stringToAppend)
				fetchedString = [fetchedString stringByAppendingString:stringToAppend];
			else
				fetchedString = [fetchedString stringByAppendingString:parsedElement];
		}

	}

	if ([fetchedString compare:@""] == 0)
		return nil;
	else
		return fetchedString;
}

+ (NSString*)numberWithTemplate:(NSString *)numberTemplate fromTranslationsDictionary:(NSDictionary*)translations {
    NSString* numberString = @"";

    for (int i=0; i<[numberTemplate length]; i++) {
        if ([numberTemplate characterAtIndex:i] == '#')
            numberString = [numberString stringByAppendingFormat:@"%d", arc4random()%10];
        else
            numberString = [numberString stringByAppendingString:[numberTemplate substringWithRange:NSMakeRange(i, 1)]];
    }

    return numberString;
}

@end


text:
import curses
import sh
import subprocess

MAIN_SCREEN = 1
DETAILS_SCREEN = 2
screen_mode = None

screen = None
GREET_WIDTH = 8
HINT_WIDTH = 3
CHANGE_IP_WIDTH = 5
platform = open("/virt_env").read().strip()

class DHCPMisconfiguration(Exception):
    pass

def make_greet_window():
    H, W = screen.getmaxyx()
    greet_win = screen.subwin(GREET_WIDTH, W, 0, 0)
    greet_win.box()
    greet_win.addstr(1, 2, "Kaa Sandbox")
    greet_win.addstr(2, 2, "http://kaaproject.org")

def make_ip_window():
    H, W = screen.getmaxyx()
    ip_win = screen.subwin(H - GREET_WIDTH - HINT_WIDTH, W, GREET_WIDTH, 0)
    ip_win.box()
    try:
        import socket
        sandbox_port = "9080"
        ip = socket.gethostbyname(socket.gethostname())

        if ip == "127.0.0.1":
            raise DHCPMisconfiguration()
    except sh.ErrorReturnCode:
        ip_win.addstr(1, 2, "===================================")
        ip_win.addstr(2, 2, "Connectivity issues detected!")
        ip_win.addstr(3, 2, "===================================")
        ip_win.addstr(4, 2, "Check VM setup instructions")
        ip_win.addstr(6, 2, "For details, see VM setup instructions")
    except DHCPMisconfiguration:
        ip_win.addstr(1, 2, "===================================")
        ip_win.addstr(2, 2, "Connectivity issues detected!")
        ip_win.addstr(3, 2, "===================================")
        ip_win.addstr(4, 2, "Check connection of network interface")
        ip_win.addstr(7, 2, "For details, see VM setup instructions")
    else:
        if platform == "vbox" and ip == "10.0.2.15":
                ip_win.addstr(1, 2, "NAT networking mode is detected.")

                ip_win.addstr(3, 2, "Please, make sure all of the Kaa ports are properly forwarded")
                ip_win.addstr(4, 2, "(and do not conflict with other services on your machine).")
                ip_win.addstr(5, 2, "Make sure Kaa \"host/IP\" is set to real host machine's IP address")
                ip_win.addstr(6, 2, "in \"Sandbox Management\".")

                ip_win.addstr(8, 2, "Also you can use bridged adapter networking mode.")
                ip_win.addstr(9, 2, "Follow this short tutorial for instructions on setting it up:")
                ip_win.addstr(10, 2, "https://goo.gl/I7sml2")

                ip_win.addstr(12, 2, "========================================================")
                ip_win.addstr(13, 2, "Kaa Sandbox Web UI : http://%s:%s" % ("127.0.0.1",sandbox_port))
                ip_win.addstr(14, 2, "SSH access to VM   : ssh kaa@%s -p 2222" % "127.0.0.1")
                ip_win.addstr(15, 2, "========================================================")

                ip_win.addstr(17, 2, "Type 'd' for more details.")
        else:
                ip_win.addstr(1, 2, "The Kaa Sandbox web interface is available at:")
                ip_win.addstr(2, 2, "http://%s:%s/sandbox" % (ip,sandbox_port))
                ip_win.addstr(4, 2, "To SSH into this VM use $ ssh kaa@%s" % ip)
                ip_win.addstr(6, 2, "Type 'd' for more details.")

def make_hint_window():
    global screen_mode
    H, W = screen.getmaxyx()
    hint_win = screen.subwin(HINT_WIDTH, W, H - HINT_WIDTH, 0)
    hint_win.box()
    if screen_mode == MAIN_SCREEN:
        if platform == "vmware":
            hint_win.addstr(
                1, 1, "Log in to this virtual machine: Linux/Windows <Alt+F5>, Mac OS X <Ctrl+Alt+F5>")
        else:
            hint_win.addstr(
                1, 1, "Log in to this virtual machine: Linux/Windows <Alt+F5>, Mac OS X <Fn+Alt+F5>")
    elif screen_mode == DETAILS_SCREEN:
        hint_win.addstr(
            1, 1, "Type 'r' to return to main screen.")

def make_web_details_window():
    H, W = screen.getmaxyx()
    det_win = screen.subwin(H - CHANGE_IP_WIDTH - HINT_WIDTH, W, 0, 0)
    det_win.box()
    det_win.addstr(
        1, 2, "Administrative web accounts details:")
    det_win.addstr(
        3, 2, "To login as 'Kaa admin' use:")
    det_win.addstr(
        4, 2, "username: kaa")
    det_win.addstr(
        5, 2, "password: kaa123")
    det_win.addstr(
        7, 2, "To login as 'Tenant admin' use:")
    det_win.addstr(
        8, 2, "username: admin")
    det_win.addstr(
        9, 2, "password: admin123")
    det_win.addstr(
        11, 2, "To login as 'Tenant developer' use:")
    det_win.addstr(
        12, 2, "username: devuser")
    det_win.addstr(
        13, 2, "password: devuser123")

def make_change_ip_window():
    H, W = screen.getmaxyx()
    det_win = screen.subwin(CHANGE_IP_WIDTH, W, H - CHANGE_IP_WIDTH - HINT_WIDTH, 0)
    det_win.box()
    det_win.addstr(
        1, 2, "You can change kaa services host/ip by executing script:")
    det_win.addstr(
        3, 2, "sudo /usr/lib/kaa-sandbox/bin/change_kaa_host.sh <new host/ip>")

def init_main_screen():
    global screen_mode
    screen_mode = MAIN_SCREEN
    curses.noecho()

    make_greet_window()
    make_ip_window()
    make_hint_window()

def init_details_screen():
    global screen_mode
    screen_mode = DETAILS_SCREEN
    curses.noecho()
    make_web_details_window()
    make_change_ip_window()
    make_hint_window()

def show_netinfo():
    commands = [
        "route -n",
        "getent ahosts",
        "ip addr",
        "cat /etc/resolv.conf",
        "cat /etc/hosts",
    ]

    f = file("/tmp/netinfo", "w")
    for cmd in commands:
        f.write("====  %s ==== \n" % cmd)
        f.write(subprocess.Popen(cmd, shell=True,
                stdout=subprocess.PIPE).communicate()[0])
        f.write("\n")
    f.close()
    subprocess.call("less /tmp/netinfo", shell=True)

def main():
    global screen
    global screen_mode
    screen = curses.initscr()
    init_main_screen()

    screen.refresh()

    curses.curs_set(0)

    import sys
    if len(sys.argv) > 1 and sys.argv[1] == "-s":
        screen.getch()
    else:
        while True:
            try:
                c = screen.getch()
                if c == ord('n'):
                    curses.endwin()
                    show_netinfo()
                    screen = curses.initscr()
                    init_main_screen()
                elif c == ord('d'):
                    curses.endwin()
                    screen = curses.initscr()
                    screen.clear()
                    init_details_screen()
                elif c == ord('r'):
                    curses.endwin()
                    screen = curses.initscr()
                    screen.clear()
                    init_main_screen()
                screen.refresh()
            except KeyboardInterrupt:
                pass

    curses.endwin()

if __name__ == '__main__':
    main()


text:
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 9
_modified_time = 1396998168.948757
_enable_loop = True
_template_filename = 'C:\\app\\manage\\templates/Setup_Default_Store.html'
_template_uri = 'Setup_Default_Store.html'
_source_encoding = 'ascii'
import os, os.path, re
_exports = ['content']

def _mako_get_namespace(context, name):
    try:
        return context.namespaces[(__name__, name)]
    except KeyError:
        _mako_generate_namespaces(context)
        return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
    pass
def _mako_inherit(template, context):
    _mako_generate_namespaces(context)
    return runtime._inherit_from(context, 'base.htm', _template_uri)
def render_body(context,**pageargs):
    __M_caller = context.caller_stack._push_frame()
    try:
        __M_locals = __M_dict_builtin(pageargs=pageargs)
        def content():
            return render_content(context._locals(__M_locals))
        __M_writer = context.writer()
        # SOURCE LINE 2
        __M_writer('\n\n\n')
        if 'parent' not in context._data or not hasattr(context._data['parent'], 'content'):
            context['self'].content(**pageargs)

        # SOURCE LINE 11
        __M_writer('  \n')
        return ''
    finally:
        context.caller_stack._pop_frame()

def render_content(context,**pageargs):
    __M_caller = context.caller_stack._push_frame()
    try:
        def content():
            return render_content(context)
        __M_writer = context.writer()
        # SOURCE LINE 5
        __M_writer('\n\n\n
 Setup Complete
\n
 The Default Values for the Store have been set up!
  \n\n')
        return ''
    finally:
        context.caller_stack._pop_frame()


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

package org.chromium.chrome.browser.payments.ui;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.widget.TintedDrawable;

import java.util.List;

import javax.annotation.Nullable;

/**
 * Represents a single section in the {@link PaymentRequestUI} that flips between multiple states.
 *
 * The row is broken up into three major, vertically-centered sections:
 * .............................................................................................
 * . TITLE                                                          |                |         .
 * .................................................................|                |         .
 * . LEFT SUMMARY TEXT                        |  RIGHT SUMMARY TEXT |    ADD or LOGO | CHEVRON .
 * .................................................................|                |         .
 * . MAIN SECTION CONTENT                                           |                |         .
 * .............................................................................................
 *
 * 1) MAIN CONTENT
 *    The main content is on the left side of the UI.  This includes the title of the section and
 *    two bits of optional summary text.  Subclasses may extend this class to append more controls
 *    via the {@link #createMainSectionContent} function.
 *
 * 2) ADD or LOGO
 *    Displays an optional logo (e.g. a credit card image) that floats to the right of the main
 *    content.  May eventually be used to show an "ADD" button.
 *
 * 3) CHEVRON
 *    Drawn to indicate that the current section may be expanded.  Displayed only when the view is
 *    in the {@link #DISPLAY_MODE_EXPANDABLE} state.
 *
 * There are three states that the UI may flip between; see {@link #DISPLAY_MODE_NORMAL},
 * {@link #DISPLAY_MODE_EXPANDABLE}, and {@link #DISPLAY_MODE_FOCUSED} for details.
 *
 * TODO(dfalcantara): Replace this with a RelativeLayout once mocks are finalized.
 */
public abstract class PaymentRequestSection extends LinearLayout {
    public static final String TAG = "PaymentRequestUI";

    /** Handles clicking on the widgets. */
    public static interface PaymentsSectionDelegate extends View.OnClickListener {
        /**
         * Called when the user selects a radio button option from an {@link OptionSection}.
         *
         * @param section Section that was changed.
         * @param option  {@link PaymentOption} that was selected.
         */
        void onPaymentOptionChanged(OptionSection section, PaymentOption option);

        /** Checks whether or not the user should be allowed to click on controls. */
        boolean isAcceptingUserInput();
    }

    /** Normal mode: White background, displays the item assuming the user accepts it as is. */
    static final int DISPLAY_MODE_NORMAL = 0;

    /** Editable mode: White background, displays the item with an edit chevron. */
    static final int DISPLAY_MODE_EXPANDABLE = 1;

    /** Focused mode: Gray background, more padding, no edit chevron. */
    static final int DISPLAY_MODE_FOCUSED = 2;

    protected final PaymentsSectionDelegate mDelegate;
    protected final int mLargeSpacing;

    private final int mVerticalSpacing;
    private final int mFocusedBackgroundColor;
    private final LinearLayout mMainSection;
    private final ImageView mLogoView;
    private final ImageView mChevronView;

    private TextView mTitleView;
    private LinearLayout mSummaryLayout;
    private TextView mSummaryLeftTextView;
    private TextView mSummaryRightTextView;

    private int mLogoResourceId;
    private int mDisplayMode;
    private boolean mIsSummaryAllowed = true;

    /**
     * Constructs an PaymentRequestSection.
     *
     * @param context     Context to pull resources from.
     * @param sectionName Title of the section to display.
     * @param delegate    Delegate to alert when something changes in the dialog.
     */
    private PaymentRequestSection(
            Context context, String sectionName, PaymentsSectionDelegate delegate) {
        super(context);
        mDelegate = delegate;
        setOnClickListener(delegate);
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);

        // Set the styling of the view.
        mFocusedBackgroundColor = ApiCompatibilityUtils.getColor(
                getResources(), R.color.payments_section_edit_background);
        mLargeSpacing =
                getResources().getDimensionPixelSize(R.dimen.payments_section_large_spacing);
        mVerticalSpacing =
                getResources().getDimensionPixelSize(R.dimen.payments_section_vertical_spacing);
        setPadding(0, mVerticalSpacing, 0, mVerticalSpacing);

        TintedDrawable chevron =
                TintedDrawable.constructTintedDrawable(getResources(), R.drawable.ic_expanded);
        chevron.setTint(ApiCompatibilityUtils.getColorStateList(
                getResources(), R.color.payments_section_chevron));

        // Create the main content.
        mMainSection = prepareMainSection(sectionName);
        mLogoView = isLogoNecessary() ? createAndAddLogoView(this, 0, 0, mLargeSpacing) : null;
        mChevronView = createAndAddImageView(this, chevron, 0, mLargeSpacing);
        setDisplayMode(DISPLAY_MODE_NORMAL);
    }

    /**
     * Sets what logo should be displayed.
     *
     * @param resourceId ID of the logo to display.
     */
    protected void setLogoResource(int resourceId) {
        assert isLogoNecessary();
        mLogoResourceId = resourceId;
        mLogoView.setImageResource(resourceId);
        updateLogoVisibility();
    }

    /**
     * Updates what Views are displayed and how they look.
     *
     * @param displayMode What mode the widget is being displayed in.
     */
    public void setDisplayMode(int displayMode) {
        mDisplayMode = displayMode;
        setBackgroundColor(
                displayMode == DISPLAY_MODE_FOCUSED ? mFocusedBackgroundColor : Color.WHITE);
        updateLogoVisibility();
        mChevronView.setVisibility(displayMode == DISPLAY_MODE_EXPANDABLE ? VISIBLE : GONE);

        // The title gains extra spacing when there is another visible view in the main section.
        int numVisibleMainViews = 0;
        for (int i = 0; i < mMainSection.getChildCount(); i++) {
            if (mMainSection.getChildAt(i).getVisibility() == VISIBLE) numVisibleMainViews += 1;
        }
        boolean isTitleMarginNecessary =
                numVisibleMainViews > 1 && displayMode == DISPLAY_MODE_FOCUSED;
        ((ViewGroup.MarginLayoutParams) mTitleView.getLayoutParams()).bottomMargin =
                isTitleMarginNecessary ? mVerticalSpacing : 0;
    }

    /**
     * Changes what is being displayed in the summary.
     *
     * @param leftText  Text to display on the left side.  If null, the whole row hides.
     * @param rightText Text to display on the right side.  If null, only the right View hides.
     */
    public void setSummaryText(
            @Nullable CharSequence leftText, @Nullable CharSequence rightText) {
        mSummaryLeftTextView.setText(leftText);
        mSummaryRightTextView.setText(rightText);
        mSummaryRightTextView.setVisibility(TextUtils.isEmpty(rightText) ? GONE : VISIBLE);
        updateSummaryVisibility();
    }

    /**
     * Sets how the summary text should be displayed.
     *
     * @param leftTruncate How to truncate the left summary text.  Set to null to clear.
     * @param rightTruncate How to truncate the right summary text.  Set to null to clear.
     */
    public void setSummaryProperties(@Nullable TruncateAt leftTruncate, boolean leftIsSingleLine,
            @Nullable TruncateAt rightTruncate, boolean rightIsSingleLine) {
        mSummaryLeftTextView.setEllipsize(leftTruncate);
        mSummaryLeftTextView.setSingleLine(leftIsSingleLine);

        mSummaryRightTextView.setEllipsize(rightTruncate);
        mSummaryRightTextView.setSingleLine(rightIsSingleLine);
    }

    /**
     * Subclasses may override this method to add additional controls to the layout.
     *
     * @param mainSectionLayout Layout containing all of the main content of the section.
     */
    protected abstract void createMainSectionContent(LinearLayout mainSectionLayout);

    /**
     * Sets whether or not the summary text can be displayed.
     *
     * @param isAllowed Whether or not do display the summary text.
     */
    protected void setIsSummaryAllowed(boolean isAllowed) {
        mIsSummaryAllowed = isAllowed;
        updateSummaryVisibility();
    }

    /** @return Whether or not the logo should be displayed. */
    protected boolean isLogoNecessary() {
        return false;
    }

    /**
     * Creates the main section.  Subclasses must call super#createMainSection() immediately to
     * guarantee that Views are added in the correct order.
     *
     * @param sectionName Title to display for the section.
     */
    private final LinearLayout prepareMainSection(String sectionName) {
        // The main section is a vertical linear layout that subclasses can append to.
        LinearLayout mainSectionLayout = new LinearLayout(getContext());
        mainSectionLayout.setOrientation(VERTICAL);
        LinearLayout.LayoutParams mainParams = new LayoutParams(0, LayoutParams.WRAP_CONTENT);
        mainParams.weight = 1;
        ApiCompatibilityUtils.setMarginStart(mainParams, mLargeSpacing);
        ApiCompatibilityUtils.setMarginEnd(mainParams, mLargeSpacing);
        addView(mainSectionLayout, mainParams);

        // The title is always displayed for the row at the top of the main section.
        mTitleView = new TextView(getContext());
        mTitleView.setText(sectionName);
        ApiCompatibilityUtils.setTextAppearance(
                mTitleView, R.style.PaymentsUiSectionHeader);
        mainSectionLayout.addView(
                mTitleView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        // Create the two TextViews for showing the summary text.
        mSummaryLeftTextView = new TextView(getContext());
        ApiCompatibilityUtils.setTextAppearance(
                mSummaryLeftTextView, R.style.PaymentsUiSectionDefaultText);

        mSummaryRightTextView = new TextView(getContext());
        ApiCompatibilityUtils.setTextAppearance(
                mSummaryRightTextView, R.style.PaymentsUiSectionDefaultText);
        ApiCompatibilityUtils.setTextAlignment(mSummaryRightTextView, TEXT_ALIGNMENT_TEXT_END);

        // The main TextView sucks up all the available space.
        LinearLayout.LayoutParams leftLayoutParams = new LinearLayout.LayoutParams(
                0, LayoutParams.WRAP_CONTENT);
        leftLayoutParams.weight = 1;

        LinearLayout.LayoutParams rightLayoutParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ApiCompatibilityUtils.setMarginStart(
                rightLayoutParams,
                getContext().getResources().getDimensionPixelSize(
                        R.dimen.payments_section_small_spacing));

        // The summary section displays up to two TextViews side by side.
        mSummaryLayout = new LinearLayout(getContext());
        mSummaryLayout.addView(mSummaryLeftTextView, leftLayoutParams);
        mSummaryLayout.addView(mSummaryRightTextView, rightLayoutParams);
        mainSectionLayout.addView(mSummaryLayout, new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        setSummaryText(null, null);

        createMainSectionContent(mainSectionLayout);
        return mainSectionLayout;
    }

    private static ImageView createAndAddLogoView(
            ViewGroup parent, int resourceId, int startMargin, int endMargin) {
        ImageView view = new ImageView(parent.getContext());
        view.setBackgroundResource(R.drawable.payments_ui_logo_bg);
        if (resourceId != 0) view.setImageResource(resourceId);

        // The logo has a pre-defined height and width.
        LayoutParams params = new LayoutParams(
                parent.getResources().getDimensionPixelSize(R.dimen.payments_section_logo_width),
                parent.getResources().getDimensionPixelSize(R.dimen.payments_section_logo_height));
        ApiCompatibilityUtils.setMarginStart(params, startMargin);
        ApiCompatibilityUtils.setMarginEnd(params, endMargin);
        parent.addView(view, params);
        return view;
    }

    private static ImageView createAndAddImageView(
            ViewGroup parent, @Nullable Drawable drawable, int startMargin, int endMargin) {
        ImageView view = new ImageView(parent.getContext());
        view.setImageDrawable(drawable);

        // Wrap whatever image is passed in.
        LayoutParams params =
                new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ApiCompatibilityUtils.setMarginStart(params, startMargin);
        ApiCompatibilityUtils.setMarginEnd(params, endMargin);
        parent.addView(view, params);
        return view;
    }

    private void updateSummaryVisibility() {
        boolean show = mIsSummaryAllowed && !TextUtils.isEmpty(mSummaryLeftTextView.getText());
        mSummaryLayout.setVisibility(show ? VISIBLE : GONE);
    }

    private void updateLogoVisibility() {
        if (mLogoView == null) return;
        boolean show = mLogoResourceId != 0 && mDisplayMode != DISPLAY_MODE_FOCUSED;
        mLogoView.setVisibility(show ? VISIBLE : GONE);
    }

    /**
     * Section with a secondary TextView beneath the summary to show additional details.
     *
     * ............................................................................
     * . TITLE                                                          |         .
     * .................................................................|         .
     * . LEFT SUMMARY TEXT                        |  RIGHT SUMMARY TEXT | CHEVRON .
     * .................................................................|         .
     * . EXTRA TEXT                                                     |         .
     * ............................................................................
     */
    public static class ExtraTextSection extends PaymentRequestSection {
        private TextView mExtraTextView;

        public ExtraTextSection(
                Context context, String sectionName, PaymentsSectionDelegate delegate) {
            super(context, sectionName, delegate);
            setExtraText(null);
        }

        @Override
        protected void createMainSectionContent(LinearLayout mainSectionLayout) {
            Context context = mainSectionLayout.getContext();

            mExtraTextView = new TextView(context);
            ApiCompatibilityUtils.setTextAppearance(
                    mExtraTextView, R.style.PaymentsUiSectionDescriptiveText);
            mainSectionLayout.addView(mExtraTextView, new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        }

        /**
         * Sets the CharSequence that is displayed in the secondary TextView.
         *
         * @param text Text to display.
         */
        public void setExtraText(CharSequence text) {
            mExtraTextView.setText(text);
            mExtraTextView.setVisibility(TextUtils.isEmpty(text) ? GONE : VISIBLE);
        }
    }

    /**
     * Section with an additional Layout for showing a total and how it is broken down.
     *
     * Normal mode:     Just the summary is displayed.
     *                  If no option is selected, the "empty label" is displayed in its place.
     * Expandable mode: Same as Normal, but shows the chevron.
     * Focused mode:    Hides the summary and chevron, then displays the full set of options.
     *
     * ............................................................................
     * . TITLE                                                          |         .
     * .................................................................|         .
     * . LEFT SUMMARY TEXT                        |  RIGHT SUMMARY TEXT |         .
     * .................................................................| CHEVRON .
     * .                                      | Line item 1 |    $13.99 |         .
     * .                                      | Line item 2 |      $.99 |         .
     * .                                      | Line item 3 |     $2.99 |         .
     * ............................................................................
     */
    public static class LineItemBreakdownSection extends PaymentRequestSection {
        private GridLayout mBreakdownLayout;

        public LineItemBreakdownSection(
                Context context, String sectionName, PaymentsSectionDelegate delegate) {
            super(context, sectionName, delegate);
        }

        @Override
        protected void createMainSectionContent(LinearLayout mainSectionLayout) {
            Context context = mainSectionLayout.getContext();

            // The breakdown is represented by an end-aligned GridLayout that takes up only as much
            // space as it needs.  The GridLayout ensures a consistent margin between the columns.
            mBreakdownLayout = new GridLayout(context);
            mBreakdownLayout.setColumnCount(2);
            LayoutParams breakdownParams =
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            breakdownParams.gravity = Gravity.END;
            mainSectionLayout.addView(mBreakdownLayout, breakdownParams);
        }

        /**
         * Updates the breakdown, with the last item representing the full total.
         *
         * @param lineItems List of {@link LineItem}s.  The last item is assumed to be the total,
         *                  while the others show how the total is broken down.
         */
        public void update(List<LineItem> lineItems) {
            Context context = mBreakdownLayout.getContext();

            // Update the summary to display information about the total.
            CharSequence totalLabel = null;
            CharSequence totalValue = null;
            if (lineItems.size() != 0) {
                LineItem totalItem = lineItems.get(lineItems.size() - 1);
                totalLabel = totalItem.getLabel();
                totalValue = createValueString(totalItem.getCurrency(), totalItem.getPrice(), true);
            }
            setSummaryText(totalLabel, totalValue);

            // Update the breakdown, using one row per {@link LineItem}.
            int numItems = lineItems.size() - 1;
            mBreakdownLayout.removeAllViews();
            mBreakdownLayout.setRowCount(numItems);
            for (int i = 0; i < numItems; i++) {
                LineItem item = lineItems.get(i);

                TextView description = new TextView(context);
                ApiCompatibilityUtils.setTextAppearance(
                        description, R.style.PaymentsUiSectionDescriptiveText);
                description.setText(item.getLabel());

                TextView amount = new TextView(context);
                ApiCompatibilityUtils.setTextAppearance(
                        amount, R.style.PaymentsUiSectionDescriptiveText);
                amount.setText(createValueString(item.getCurrency(), item.getPrice(), false));

                // Each item is represented by a row in the GridLayout.
                GridLayout.LayoutParams descriptionParams = new GridLayout.LayoutParams(
                        GridLayout.spec(i, 1, GridLayout.END),
                        GridLayout.spec(0, 1, GridLayout.END));
                GridLayout.LayoutParams amountParams = new GridLayout.LayoutParams(
                        GridLayout.spec(i, 1, GridLayout.END),
                        GridLayout.spec(1, 1, GridLayout.END));
                ApiCompatibilityUtils.setMarginStart(amountParams,
                        context.getResources().getDimensionPixelSize(
                                R.dimen.payments_section_descriptive_item_spacing));

                mBreakdownLayout.addView(description, descriptionParams);
                mBreakdownLayout.addView(amount, amountParams);
            }
        }

        /**
         * Builds a CharSequence that displays a value in a particular currency.
         *
         * @param currency    Currency of the value being displayed.
         * @param value       Value to display.
         * @param isValueBold Whether or not to bold the item.
         * @return CharSequence that represents the whole value.
         */
        private CharSequence createValueString(String currency, String value, boolean isValueBold) {
            SpannableStringBuilder valueBuilder = new SpannableStringBuilder();
            valueBuilder.append(currency);
            valueBuilder.append(" ");

            int boldStartIndex = valueBuilder.length();
            valueBuilder.append(value);

            if (isValueBold) {
                valueBuilder.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), boldStartIndex,
                        boldStartIndex + value.length(), 0);
            }

            return valueBuilder;
        }

        @Override
        public void setDisplayMode(int displayMode) {
            super.setDisplayMode(displayMode);
            mBreakdownLayout.setVisibility(displayMode == DISPLAY_MODE_FOCUSED ? VISIBLE : GONE);
        }
    }

    /**
     * Section that allows selecting one thing from a set of mutually-exclusive options.
     *
     * Normal mode:     The summary text displays the selected option, and the icon for the option
     *                  is displayed in the logo section (if it exists).
     *                  If no option is selected, the "empty label" is displayed in its place.
     *                  This is important for shipping options (e.g.) because there will be no
     *                  option selected by default and a prompt can be displayed.
     * Expandable mode: Same as Normal, but shows the chevron.
     * Focused mode:    Hides the summary and chevron, then displays the full set of options.
     *
     * .............................................................................................
     * . TITLE                                                          |                |         .
     * .................................................................|                |         .
     * . LEFT SUMMARY TEXT                        |  RIGHT SUMMARY TEXT |                |         .
     * .................................................................|    ADD or LOGO | CHEVRON .
     * . O Option 1                                              ICON 1 |                |         .
     * . O Option 2                                              ICON 2 |                |         .
     * . O Option 3                                              ICON 3 |                |         .
     * .............................................................................................
     */
    public static class OptionSection extends PaymentRequestSection implements OnClickListener {
        /** Displays a row representing a selectable option. */
        private class OptionRow extends LinearLayout {
            private final PaymentOption mOption;
            private final RadioButton mRadioButton;

            public OptionRow(Context context, PaymentOption item, boolean isSelected) {
                super(context);
                setGravity(Gravity.CENTER_VERTICAL);
                mOption = item;

                // The radio button hugs left.
                mRadioButton = new RadioButton(context);
                mRadioButton.setChecked(isSelected);
                LinearLayout.LayoutParams radioParams = new LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                ApiCompatibilityUtils.setMarginEnd(radioParams, mLargeSpacing);
                addView(mRadioButton, radioParams);

                // The description takes up all leftover space.
                TextView descriptionView = new TextView(context);
                descriptionView.setText(convertOptionToString(item));
                ApiCompatibilityUtils.setTextAppearance(
                        descriptionView, R.style.PaymentsUiSectionDefaultText);
                LinearLayout.LayoutParams descriptionParams =
                        new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT);
                descriptionParams.weight = 1;
                addView(descriptionView, descriptionParams);

                // If there's an icon to display, it floats to the right of everything.
                int resourceId = item.getDrawableIconId();
                if (resourceId != 0) createAndAddLogoView(this, resourceId, mLargeSpacing, 0);

                // Making the radio button unclickable makes clicks fall through to the row.
                mRadioButton.setClickable(false);
                setOnClickListener(OptionSection.this);
            }

            /** Sets the selected state of this item, alerting the delegate if selected. */
            public void setChecked(boolean isChecked) {
                mRadioButton.setChecked(isChecked);

                if (isChecked) {
                    updateSelectedItem(mOption);
                    mDelegate.onPaymentOptionChanged(OptionSection.this, mOption);
                }
            }
        }

        /** Text to display in the summary when there is no selected option. */
        private final CharSequence mEmptyLabel;

        /** Top and bottom margins for each item. */
        private final int mVerticalMargin;

        /** Layout containing all the {@link OptionRow}s. */
        private LinearLayout mOptionLayout;

        /**
         * Constructs an OptionSection.
         *
         * @param context     Context to pull resources from.
         * @param sectionName Title of the section to display.
         * @param emptyLabel  An optional string to display when no item is selected.
         * @param delegate    Delegate to alert when something changes in the dialog.
         */
        public OptionSection(Context context, String sectionName, @Nullable CharSequence emptyLabel,
                PaymentsSectionDelegate delegate) {
            super(context, sectionName, delegate);
            mVerticalMargin = context.getResources().getDimensionPixelSize(
                    R.dimen.payments_section_small_spacing);
            mEmptyLabel = emptyLabel;
            setSummaryText(emptyLabel, null);
        }

        @Override
        public void onClick(View v) {
            if (!mDelegate.isAcceptingUserInput()) return;

            for (int i = 0; i < mOptionLayout.getChildCount(); i++) {
                OptionRow row = (OptionRow) mOptionLayout.getChildAt(i);
                row.setChecked(v == row || v == row.mRadioButton);
            }
        }

        @Override
        protected boolean isLogoNecessary() {
            return true;
        }

        @Override
        protected void createMainSectionContent(LinearLayout mainSectionLayout) {
            Context context = mainSectionLayout.getContext();

            mOptionLayout = new LinearLayout(context);
            mOptionLayout.setOrientation(VERTICAL);
            mainSectionLayout.addView(mOptionLayout, new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        }

        /** Updates the View to account for the new {@link SectionInformation} being passed in. */
        public void update(SectionInformation information) {
            PaymentOption selectedItem = information.getSelectedItem();
            updateSelectedItem(selectedItem);
            updateOptionList(information, selectedItem);
        }

        @Override
        public void setDisplayMode(int displayMode) {
            super.setDisplayMode(displayMode);

            if (displayMode == DISPLAY_MODE_FOCUSED) {
                setIsSummaryAllowed(false);
                mOptionLayout.setVisibility(VISIBLE);
            } else {
                setIsSummaryAllowed(true);
                mOptionLayout.setVisibility(GONE);
            }
        }

        private void updateSelectedItem(PaymentOption selectedItem) {
            if (selectedItem == null) {
                setLogoResource(0);
                if (TextUtils.isEmpty(mEmptyLabel)) {
                    setIsSummaryAllowed(false);
                } else {
                    setSummaryText(mEmptyLabel, null);
                }
            } else {
                setLogoResource(selectedItem.getDrawableIconId());
                setSummaryText(convertOptionToString(selectedItem), null);
            }
        }

        private void updateOptionList(SectionInformation information, PaymentOption selectedItem) {
            mOptionLayout.removeAllViews();
            if (information.isEmpty()) return;

            for (int i = 0; i < information.getSize(); i++) {
                PaymentOption item = information.getItem(i);
                OptionRow row = new OptionRow(getContext(), item, item == selectedItem);
                LinearLayout.LayoutParams rowParams = new LinearLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                rowParams.topMargin = mVerticalMargin;
                rowParams.bottomMargin = mVerticalMargin;
                mOptionLayout.addView(row, rowParams);
            }
        }

        private CharSequence convertOptionToString(PaymentOption item) {
            if (TextUtils.isEmpty(item.getSublabel())) return item.getLabel();
            return new StringBuilder(item.getLabel()).append("\n").append(item.getSublabel());
        }
    }

    /**
     * Drawn as a 1dp separator.  Initially drawn without being expanded to the full width of the
     * UI, but can be expanded to separate sections fully.
     */
    public static class SectionSeparator extends View {
        /** Creates the View and adds it to the parent. */
        public SectionSeparator(ViewGroup parent) {
            this(parent, -1);
        }

        /** Creates the View and adds it to the parent at the given index. */
        public SectionSeparator(ViewGroup parent, int index) {
            super(parent.getContext());
            Resources resources = parent.getContext().getResources();
            setBackgroundColor(ApiCompatibilityUtils.getColor(
                    resources, R.color.payments_section_separator));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT,
                    resources.getDimensionPixelSize(R.dimen.payments_section_separator_height));

            int margin = resources.getDimensionPixelSize(R.dimen.payments_section_large_spacing);
            ApiCompatibilityUtils.setMarginStart(params, margin);
            ApiCompatibilityUtils.setMarginEnd(params, margin);
            parent.addView(this, index, params);
        }

        /** Expand the separator to be the full width of the dialog. */
        public void expand() {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) getLayoutParams();
            ApiCompatibilityUtils.setMarginStart(params, 0);
            ApiCompatibilityUtils.setMarginEnd(params, 0);
        }
    }
}


text:
<?php
/**
 * @file HttpClientInterface.php
 */
namespace Wesnick\RingCentral\Http;

interface HttpClientInterface
{
    /**
     * @param string $host
     * @param string $resource
     * @return string
     *   Return the response body from the HTTP request
     */
    public function doRequest($host, $resource);
}


text:
FOUNDATION_EXPORT double SwiftDataStructuresVersionNumber;

//! Project version string for SwiftDataStructures.
FOUNDATION_EXPORT const unsigned char SwiftDataStructuresVersionString[];


text:
package org.jenkinsci.plugins.ewm.steps;

import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Result;
import hudson.model.StringParameterDefinition;
import hudson.model.StringParameterValue;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.jenkinsci.plugins.ewm.TestUtil;
import org.jenkinsci.plugins.ewm.definitions.Disk;
import org.jenkinsci.plugins.ewm.definitions.DiskPool;
import org.jenkinsci.plugins.ewm.nodes.NodeDisk;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.jvnet.hudson.test.BuildWatcher;
import org.jvnet.hudson.test.JenkinsRule;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Collections;

import static java.lang.String.format;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.jenkinsci.plugins.ewm.TestUtil.*;
import static org.junit.Assert.assertThat;

/**
 * Tests the custom workspace path on disk feature.
 *
 * @author Alexandru Somai
 */
public class CustomWorkspaceTest {

    @ClassRule
    public static JenkinsRule j = new JenkinsRule();

    @ClassRule
    public static BuildWatcher watcher = new BuildWatcher();

    @Rule
    public TemporaryFolder tmp = new TemporaryFolder();

    private File tmpFolder;

    @Before
    public void setUp() throws IOException {
        Disk disk = new Disk(DISK_ID_ONE, null, "mount", null, null);
        DiskPool diskPool = new DiskPool(DISK_POOL_ID, null, null, null, null, null, Collections.singletonList(disk));
        setUpDiskPools(j.jenkins, diskPool);

        tmpFolder = tmp.newFolder();
        NodeDisk nodeDisk = new NodeDisk(DISK_ID_ONE, tmpFolder.getAbsolutePath());
        addExternalWorkspaceNodeProperty(j.jenkins, DISK_POOL_ID, nodeDisk);
    }

    @After
    public void tearDown() throws IOException {
        removeExternalWorkspaceNodeProperty(j.jenkins);
        removeDiskPools(j.jenkins);
    }

    @Test
    public void customWorkspaceUsingPathParameter() throws Exception {
        WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, RandomStringUtils.randomAlphanumeric(7));
        job.setDefinition(new CpsFlowDefinition(format("" +
                "def customPath = \"${env.JOB_NAME}/${PR_BUILD_NUMBER}/${env.BUILD_NUMBER}\" \n" +
                "def extWorkspace = exwsAllocate diskPoolId: '%s', path: customPath \n" +
                "node { \n" +
                "   exws (extWorkspace) { \n" +
                "       writeFile file: 'foobar.txt', text: 'foobar' \n" +
                "   } \n" +
                "} \n", DISK_POOL_ID)));

        job.addProperty(new ParametersDefinitionProperty(
                new StringParameterDefinition("PR_BUILD_NUMBER", "")));

        String prBuildNumberValue = "22";
        ParameterValue parameterValue = new StringParameterValue("PR_BUILD_NUMBER", prBuildNumberValue);
        ParametersAction parameterValues = new ParametersAction(parameterValue);

        WorkflowRun run = j.assertBuildStatusSuccess(job.scheduleBuild2(0, parameterValues));
        verifyWorkspacePath(run, job.getFullName(), prBuildNumberValue, Integer.toString(run.getNumber()));
    }

    @Test
    public void customWorkspacePathParameterIsAbsolute() throws Exception {
        WorkflowRun run = createWorkflowJobAndRun(format("" +
                "def customPath = \"/${env.JOB_NAME}/${env.BUILD_NUMBER}\" \n" +
                "def extWorkspace = exwsAllocate diskPoolId: '%s', path: customPath", DISK_POOL_ID));

        j.assertBuildStatus(Result.FAILURE, run);
        j.assertLogContains(format("ERROR: The custom path: /%s/%d must be a relative path", run.getParent().getFullName(), run.getNumber()), run);
    }

    @Test
    public void customWorkspaceUsingPathParameterWithConstantFolder() throws Exception {
        String folder = "constant";
        WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, RandomStringUtils.randomAlphanumeric(7));
        job.setDefinition(new CpsFlowDefinition(format("" +
                "def customPath = \"%s/${env.JOB_NAME}/${env.BUILD_NUMBER}\" \n" +
                "def extWorkspace = exwsAllocate diskPoolId: '%s', path: customPath \n" +
                "node { \n" +
                "   exws (extWorkspace) { \n" +
                "       writeFile file: 'foobar.txt', text: 'foobar' \n" +
                "   } \n" +
                "} \n", folder, DISK_POOL_ID)));

        WorkflowRun run = j.assertBuildStatusSuccess(job.scheduleBuild2(0));
        verifyWorkspacePath(run, folder, job.getFullName(), Integer.toString(run.getNumber()));
    }

    @Test
    public void wrongStringInterpolation() throws Exception {
        // the script uses single quotes, instead of double quotes for String interpolation.
        WorkflowRun run = createWorkflowJobAndRun(format("" +
                "def customPath = '${env.JOB_NAME}/${env.BUILD_NUMBER}' \n" +
                "def extWorkspace = exwsAllocate diskPoolId: '%s', path: customPath", DISK_POOL_ID));

        j.assertBuildStatus(Result.FAILURE, run);
        j.assertLogContains("The custom path: ${env.JOB_NAME}/${env.BUILD_NUMBER} contains '${' characters. Did you resolve correctly the parameters with Build DSL?", run);
    }

    @Test
    public void globalWorkspaceTemplate() throws Exception {
        setGlobalWorkspaceTemplate("${JOB_NAME}/${PR_BUILD_NUMBER}/${BUILD_NUMBER}");

        String prBuildNumberValue = "30";
        WorkflowRun run = createWorkflowJobAndRun(format("" +
                "def extWorkspace = null \n" +
                "withEnv (['PR_BUILD_NUMBER=%s']) { \n" +
                "   extWorkspace = exwsAllocate diskPoolId: '%s' \n" +
                "} \n" +
                "node { \n" +
                "   exws (extWorkspace) { \n" +
                "       writeFile file: 'foobar.txt', text: 'foobar' \n" +
                "   } \n" +
                "} \n", prBuildNumberValue, DISK_POOL_ID));

        j.assertBuildStatusSuccess(run);
        verifyWorkspacePath(run, run.getParent().getFullName(), prBuildNumberValue, Integer.toString(run.getNumber()));
    }

    @Test
    public void globalWorkspaceTemplateWithConstantFolder() throws Exception {
        String folder = "constant";
        setGlobalWorkspaceTemplate(format("%s/${JOB_NAME}/${BUILD_NUMBER}", folder));

        WorkflowRun run = createWorkflowJobAndRun(format("" +
                "def extWorkspace = exwsAllocate diskPoolId: '%s' \n" +
                "node { \n" +
                "   exws (extWorkspace) { \n" +
                "       writeFile file: 'foobar.txt', text: 'foobar' \n" +
                "   } \n" +
                "} \n", DISK_POOL_ID));

        j.assertBuildStatusSuccess(run);
        verifyWorkspacePath(run, folder, run.getParent().getFullName(), Integer.toString(run.getNumber()));
    }

    @Test
    public void globalWorkspaceTemplatePathIsAbsolute() throws Exception {
        setGlobalWorkspaceTemplate(Paths.get(File.separator, "${JOB_NAME}", File.separator, "${BUILD_NUMBER}").toString());

        WorkflowRun run = createWorkflowJobAndRun(format("def extWorkspace = exwsAllocate diskPoolId: '%s'", DISK_POOL_ID));

        j.assertBuildStatus(Result.FAILURE, run);
        j.assertLogContains(format("ERROR: Workspace template defined for Disk Pool '%s' must be a relative path", DISK_POOL_ID), run);
    }

    @Test
    public void globalWorkspaceTemplateWithTypo() throws Exception {
        setGlobalWorkspaceTemplate("${JOB_NAME_WITH_TYPO}/${BUILD_NUMBER}");

        WorkflowRun run = createWorkflowJobAndRun(format("def extWorkspace = exwsAllocate diskPoolId: '%s'", DISK_POOL_ID));

        j.assertBuildStatus(Result.FAILURE, run);
        j.assertLogContains("ERROR: Can't resolve the following workspace template: ${JOB_NAME_WITH_TYPO}" + File.separator + "${BUILD_NUMBER}. " +
                "The resulting path is: ${JOB_NAME_WITH_TYPO}" + File.separator + "1. Did you provide all the needed environment variables?", run);
    }

    private static void setGlobalWorkspaceTemplate(String template) {
        Disk disk = new Disk(DISK_ID_ONE, null, "mount", null, null);
        DiskPool diskPool = new DiskPool(DISK_POOL_ID, null, null, FilenameUtils.separatorsToSystem(template), null, null, Collections.singletonList(disk));
        setUpDiskPools(j.jenkins, diskPool);
    }

    private void verifyWorkspacePath(WorkflowRun run, String pathName, String... pathNames) throws Exception {
        String computedCustomPath = Paths.get(pathName, pathNames).toString();
        File customWorkspace = new File(tmpFolder, computedCustomPath);
        File[] files = customWorkspace.listFiles();

        j.assertLogContains(format("The path on Disk is: %s", computedCustomPath), run);
        j.assertLogContains(format("Running in %s", Paths.get(tmpFolder.getAbsolutePath(), computedCustomPath)), run);
        assertThat(files, notNullValue());
        assertThat(files, arrayWithSize(1));
        assertThat(files[0].getName(), is("foobar.txt"));
    }

    private WorkflowRun createWorkflowJobAndRun(String script) throws Exception {
        return TestUtil.createWorkflowJobAndRun(j.jenkins, script);
    }
}


text:
title: Creating a Simple Context Menu
page_title: Creating a Simple Context Menu | RadMenu for ASP.NET AJAX Documentation
description: Creating a Simple Context Menu
slug: menu/getting-started/creating-a-simple-context-menu
tags: creating,a,simple,context,menu
published: True
position: 2
---

# Creating a Simple Context Menu

##

This tutorial will walk you through creating a simple **RadContextMenu** and shows how to:

* Use the **RadMenu Item Editor** to build a simple context menu.

* Use the Targets collection to attach the context menu to another control.

1. Drag a **RadContextMenu** component from the toolbox onto your Web page. The **RadContextMenu** [Smart Tag]({%slug menu/design-time/smart-tag%}) should appear automatically:
![RadMenu Smart Tag](images/menu_smarttag.png)

1. On the Smart Tag, choose **Edit Items.** The [RadMenu Item Builder]({%slug menu/design-time/radmenu-item-builder%}) appears:![Contextmenu ItemBuilder](images/menu_contextmenuitembuilder.png)

1. Click the **Add root item** button (![RadMenu Add Root Item](images/menu_addrootitem.png)) to add a root item to your menu.

1. With the root item selected, click the **Add child item** button (![RadMenu Add Child Item](images/menu_addchilditem.png)) to add a child to your root item.

1. Add some more root items, and child items using the **Add root item** button and the **Add child item** button:![Contextmenu SampleMenu](images/menu_contextmenusamplemenu.png)

1. Select one of the child items, and change its **IsSeparator** property to **True** and its **Text** property to an empty string (""):![Contextmenu IsSeparator](images/menu_contextmenuisseparator.png)

1. Click **OK** to confirm and exit.

1. Right click on the **RadContextMenu**, and from its context menu, choose **Properties**.

1. From the Standard area of the toolbox, drag a **Label** onto your page. Set its **Text** property to "Label1".

1. Move to the Source view of your Web page and locate the declaration of your **RadContextMenu**.

1. Select **Edit Targets** from the smart tag.![RadContextMenu Targets](images/menu_targets.png)

1. From the **Target Editor** select to **Add Control Target**. This attaches your context menu to a specific control, based on its ID:![RadContextMenu Control Target](images/menu_controltarget.png)

1. Select the ControlID attribute from the dropdown that appears:![RadContextMenu ControlID](images/menu_controlid.png)

1. Select **Ok** and run the application. Right-click on the label and see your context menu appear:![RadContextMenu](images/menu_contextmenu1.png)

# See Also

 * [RadContextMenu Object]({%slug menu/context-menus/radcontextmenu-object%})


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.esotericsoftware.kryo.util Class Hierarchy</title>
<meta name="date" content="2013-11-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.esotericsoftware.kryo.util

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.esotericsoftware.kryo.util.DefaultClassResolver (implements com.esotericsoftware.kryo.ClassResolver)

com.esotericsoftware.kryo.util.DefaultStreamFactory (implements com.esotericsoftware.kryo.StreamFactory)

com.esotericsoftware.kryo.util.FastestStreamFactory (implements com.esotericsoftware.kryo.StreamFactory)

com.esotericsoftware.kryo.util.IdentityMap<K,V>

com.esotericsoftware.kryo.util.IdentityMap.Entries<K,V> (implements java.lang.Iterable<T>, java.util.Iterator<E>)

com.esotericsoftware.kryo.util.IdentityMap.Entry<K,V>

com.esotericsoftware.kryo.util.IdentityMap.Keys<K> (implements java.lang.Iterable<T>, java.util.Iterator<E>)

com.esotericsoftware.kryo.util.IdentityMap.Values<V> (implements java.lang.Iterable<T>, java.util.Iterator<E>)

com.esotericsoftware.kryo.util.IdentityObjectIntMap<K>

com.esotericsoftware.kryo.util.IntArray

com.esotericsoftware.kryo.util.IntMap<V>

com.esotericsoftware.kryo.util.ListReferenceResolver (implements com.esotericsoftware.kryo.ReferenceResolver)

com.esotericsoftware.kryo.util.MapReferenceResolver (implements com.esotericsoftware.kryo.ReferenceResolver)

com.esotericsoftware.kryo.util.ObjectMap<K,V>

com.esotericsoftware.kryo.util.ObjectMap.Entries<K,V> (implements java.lang.Iterable<T>, java.util.Iterator<E>)

com.esotericsoftware.kryo.util.ObjectMap.Entry<K,V>

com.esotericsoftware.kryo.util.ObjectMap.Keys<K> (implements java.lang.Iterable<T>, java.util.Iterator<E>)

com.esotericsoftware.kryo.util.ObjectMap.Values<V> (implements java.lang.Iterable<T>, java.util.Iterator<E>)

com.esotericsoftware.kryo.util.UnsafeUtil

com.esotericsoftware.kryo.util.Util

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
#ifndef PID_H_
#define PID_H_

typedef struct
{
		double Kp;
		double Ki;
		double Kd;
		double pPart;
		double iPart;
		double dPart;
		int32_t SetPoint;
		double PIDResult;
		double PIDResultTemp;
		int32_t PIDError;
		int32_t PIDErrorTemp1;
		int32_t PIDErrorTemp2;
		uint8_t Enable;
} PIDType;

void PIDSpeedSet(PIDType *p_PIDVer, int32_t SpeedSet);
void PIDPositionSet(PIDType *p_PID, int32_t SetPoint);
void PIDPosCalc(PIDType *p_PIDPos, int32_t Position, int32_t MaxResponse);
void PIDWallCalc(PIDType *p_PIDWall, int32_t Distance, int32_t MaxResponse);
void PIDVerCalc(PIDType *p_PIDVer, int32_t *Speed, int32_t MaxResponse);
void WallFollow(uint8_t AvailDirection);
void Move(int32_t PositionLeft, int32_t PositionRight);

#endif /* PID_H_ */


text:
FOUNDATION_EXPORT double Pods_NHTestVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_NHTestVersionString[];


text:
using namespace std;

#include "Ruleset.hpp"

namespace PCGGrammar {

    // Generator class
    //
    // Instantiate and set the ruleset to be used with instance.SetRuleset(&rulesetinstance)
    // then call instance.Generate("COMPOSITE_SYMBOL_YOU_WANT_TO_GENERATE") to generate the
    // stuff you want.

    class Generator {
        public:
            Generator();
            Generator(string seed);
            ~Generator();
        private:
            Ruleset* mpRuleset;
            string mSeedString;
        public:
            void SetRuleset(Ruleset* ruleset);
            ComponentVector Generate(string baseRule) const;
    };

}

#endif


text:
package com.android.aft.test.TestAFCuteJsonParser;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

import com.android.aft.AFCoreTools.DebugTools;
import com.android.aft.AFCuteJsonParser.AFArrayJsonAction;
import com.android.aft.AFCuteJsonParser.AFCuteJsonParser;
import com.android.aft.AFCuteJsonParser.AFCuteJsonParserResult;
import com.android.aft.AFCuteJsonParser.AFJsonValue;
import com.android.aft.AFCuteJsonParser.AFJsonValue.JsonValueType;
import com.android.aft.AFCuteJsonParser.AFObjectJsonAction;
import com.android.aft.AFCuteJsonParser.AFRootObjectJsonAction;
import com.android.aft.test.TestAFCuteJsonParser.R;

public class StartUpActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Init debug
        DebugTools.init("TestNFCuteJsonParser");

        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                launchParsing();
            }
        });
    }

    private void launchParsing() {
        AFCuteJsonParser parser = getParser();

        AFCuteJsonParserResult result = parser.parse(getResources().openRawResource(R.raw.test1));
        DebugTools.d("Json parsing " + (result.status() ? "Success" : "Failed") + " - " + result.getData());
    }

    private AFCuteJsonParser getParser() {
        // Create the parser
        AFCuteJsonParser parser = new AFCuteJsonParser();

        // Add an action on root object
        parser.addAction(new AFRootObjectJsonAction<Object>() {
            @Override
            public void onObject(Object cookie) {
                DebugTools.d("On root object with:");

                AFJsonValue value;

                // Try to get an no existing value
                value = getValueOf("foo");
                DebugTools.d(" - 'foo': " + (value == null ? "(null)" : value));

                // Try to get an int value
                value = getValueOf("root_value");
                DebugTools.d(" - 'root_value': " + (value == null ? "(null)" : value));

                // Try to get an object value
                value = getValueOf("menu");
                DebugTools.d(" - 'menu': " + (value == null ? "(null)" : value));

                // Read all object values
                read_values();
            }
        });

        // Add an action on root object
        parser.addAction(new AFObjectJsonAction<Object>("menu") {
            @Override
            public void onObject(Object cookie) {
                DebugTools.d("On menu object with:");

                getContext().getResult().setData(new Integer(getIntValueOf("id")));

                AFJsonValue value_ici = getValueOf("ici");
                if (value_ici.getType() == JsonValueType.JsonNull)
                	;
                else
                	;
            }
        });

        // Add an action on the array 'menuitem'
        parser.addAction(new AFArrayJsonAction<Object>("menuitem") {
            @Override
            public void onArray(Object cookie) {
                DebugTools.d("On 'menuitem' array with " + getNumberOfEntry() + " elements");

                // Iterate on each value in array
                int i = 0;
                for (AFJsonValue value: getValues()) {
                    DebugTools.d(" - [" + i + "]: " + (value == null ? "(null)" : value));

                    if (value.getType() == AFJsonValue.JsonValueType.JsonNull)
                        ;

                    ++i;
                }

                // Try to get an no existing value
                AFJsonValue value = getValue(10);
                DebugTools.d(" - [10]: " + (value == null ? "(null)" : value));

                // Read all array values
                read_values();
            }
        });

        return parser;
    }

}


text:
from lib.hachoir_parser import Parser
from lib.hachoir_core.field import (Field, FieldSet, createOrphanField,
    NullBits, Bit, Bits, Enum, Fragment, MissingField, ParserError,
    UInt8, UInt16, UInt24, UInt32, UInt64,
    RawBytes, String, PascalString32, NullBytes)
from lib.hachoir_core.stream import FragmentedStream, InputStreamError
from lib.hachoir_core.endian import LITTLE_ENDIAN, BIG_ENDIAN
from lib.hachoir_core.tools import humanDurationNanosec
from lib.hachoir_core.text_handler import textHandler, hexadecimal

MAX_FILESIZE = 1000 * 1024 * 1024

class XiphInt(Field):
    """
    Positive integer with variable size. Values bigger than 254 are stored as
    (255, 255, ..., rest): value is the sum of all bytes.

    Example: 1000 is stored as (255, 255, 255, 235), total = 255*3+235 = 1000
    """
    def __init__(self, parent, name, max_size=None, description=None):
        Field.__init__(self, parent, name, size=0, description=description)
        value = 0
        addr = self.absolute_address
        while max_size is None or self._size < max_size:
            byte = parent.stream.readBits(addr, 8, LITTLE_ENDIAN)
            value += byte
            self._size += 8
            if byte != 0xff:
                break
            addr += 8
        self.createValue = lambda: value

class Lacing(FieldSet):
    def createFields(self):
        size = self.size
        while size:
            field = XiphInt(self, 'size[]', size)
            yield field
            size -= field.size

def parseVorbisComment(parent):
    yield PascalString32(parent, 'vendor', charset="UTF-8")
    yield UInt32(parent, 'count')
    for index in xrange(parent["count"].value):
        yield PascalString32(parent, 'metadata[]', charset="UTF-8")
    if parent.current_size != parent.size:
        yield UInt8(parent, "framing_flag")

PIXEL_FORMATS = {
    0: "4:2:0",
    2: "4:2:2",
    3: "4:4:4",
}

def formatTimeUnit(field):
    return humanDurationNanosec(field.value * 100)

def parseVideoHeader(parent):
    yield NullBytes(parent, "padding[]", 2)
    yield String(parent, "fourcc", 4)
    yield UInt32(parent, "size")
    yield textHandler(UInt64(parent, "time_unit", "Frame duration"), formatTimeUnit)
    yield UInt64(parent, "sample_per_unit")
    yield UInt32(parent, "default_len")
    yield UInt32(parent, "buffer_size")
    yield UInt16(parent, "bits_per_sample")
    yield NullBytes(parent, "padding[]", 2)
    yield UInt32(parent, "width")
    yield UInt32(parent, "height")
    yield NullBytes(parent, "padding[]", 4)

def parseTheoraHeader(parent):
    yield UInt8(parent, "version_major")
    yield UInt8(parent, "version_minor")
    yield UInt8(parent, "version_revision")
    yield UInt16(parent, "width", "Width*16 in pixel")
    yield UInt16(parent, "height", "Height*16 in pixel")

    yield UInt24(parent, "frame_width")
    yield UInt24(parent, "frame_height")
    yield UInt8(parent, "offset_x")
    yield UInt8(parent, "offset_y")

    yield UInt32(parent, "fps_num", "Frame per second numerator")
    yield UInt32(parent, "fps_den", "Frame per second denominator")
    yield UInt24(parent, "aspect_ratio_num", "Aspect ratio numerator")
    yield UInt24(parent, "aspect_ratio_den", "Aspect ratio denominator")

    yield UInt8(parent, "color_space")
    yield UInt24(parent, "target_bitrate")
    yield Bits(parent, "quality", 6)
    yield Bits(parent, "gp_shift", 5)
    yield Enum(Bits(parent, "pixel_format", 2), PIXEL_FORMATS)
    yield Bits(parent, "spare_config", 3)

def parseVorbisHeader(parent):
    yield UInt32(parent, "vorbis_version")
    yield UInt8(parent, "audio_channels")
    yield UInt32(parent, "audio_sample_rate")
    yield UInt32(parent, "bitrate_maximum")
    yield UInt32(parent, "bitrate_nominal")
    yield UInt32(parent, "bitrate_minimum")
    yield Bits(parent, "blocksize_0", 4)
    yield Bits(parent, "blocksize_1", 4)
    yield UInt8(parent, "framing_flag")

class Chunk(FieldSet):
    tag_info = {
        "vorbis": {
            3: ("comment", parseVorbisComment),
            1: ("vorbis_hdr", parseVorbisHeader),
        }, "theora": {
            128: ("theora_hdr", parseTheoraHeader),
            129: ("comment", parseVorbisComment),
        }, "video\0": {
            1: ("video_hdr", parseVideoHeader),
        },
    }
    def __init__(self, *args, **kw):
        FieldSet.__init__(self, *args, **kw)
        if 7*8 <= self.size:
            try:
                self._name, self.parser = self.tag_info[self["codec"].value][self["type"].value]
                if self._name == "theora_hdr":
                    self.endian = BIG_ENDIAN
            except KeyError:
                self.parser = None
        else:
            self.parser = None

    def createFields(self):
        if 7*8 <= self.size:
            yield UInt8(self, 'type')
            yield String(self, 'codec', 6)
        if self.parser:
            for field in self.parser(self):
                yield field
        else:
            size = (self.size - self.current_size) // 8
            if size:
                yield RawBytes(self, "raw", size)

class Packets:
    def __init__(self, first):
        self.first = first

    def __iter__(self):
        fragment = self.first
        size = None
        while fragment is not None:
            page = fragment.parent
            continued_packet = page["continued_packet"].value
            for segment_size in page.segment_size:
                if continued_packet:
                    size += segment_size
                    continued_packet = False
                else:
                    if size:
                        yield size * 8
                    size = segment_size
            fragment = fragment.next
        if size:
            yield size * 8

class Segments(Fragment):
    def __init__(self, parent, *args, **kw):
        Fragment.__init__(self, parent, *args, **kw)
        if parent['last_page'].value:
            next = None
        else:
            next = self.createNext
        self.setLinks(parent.parent.streams.setdefault(parent['serial'].value, self), next)

    def _createInputStream(self, **args):
        if self.first is self:
            return FragmentedStream(self, packets=Packets(self), tags=[("id","ogg_stream")], **args)
        return Fragment._createInputStream(self, **args)

    def _getData(self):
        return self

    def createNext(self):
        parent = self.parent
        index = parent.index
        parent = parent.parent
        first = self.first
        try:
            while True:
                index += 1
                next = parent[index][self.name]
                if next.first is first:
                    return next
        except MissingField:
            pass

    def createFields(self):
        for segment_size in self.parent.segment_size:
            if segment_size:
                yield Chunk(self, "chunk[]", size=segment_size*8)

class OggPage(FieldSet):
    MAGIC = "OggS"

    def __init__(self, *args):
        FieldSet.__init__(self, *args)
        size = 27
        self.lacing_size = self['lacing_size'].value
        if self.lacing_size:
            size += self.lacing_size
            lacing = self['lacing']
            self.segment_size = [ field.value for field in lacing ]
            size += sum(self.segment_size)
        self._size = size * 8

    def createFields(self):
        yield String(self, 'capture_pattern', 4, charset="ASCII")
        if self['capture_pattern'].value != self.MAGIC:
            self.warning('Invalid signature. An Ogg page must start with "%s".' % self.MAGIC)
        yield UInt8(self, 'stream_structure_version')
        yield Bit(self, 'continued_packet')
        yield Bit(self, 'first_page')
        yield Bit(self, 'last_page')
        yield NullBits(self, 'unused', 5)
        yield UInt64(self, 'abs_granule_pos')
        yield textHandler(UInt32(self, 'serial'), hexadecimal)
        yield UInt32(self, 'page')
        yield textHandler(UInt32(self, 'checksum'), hexadecimal)
        yield UInt8(self, 'lacing_size')
        if self.lacing_size:
            yield Lacing(self, "lacing", size=self.lacing_size*8)
            yield Segments(self, "segments", size=self._size-self._current_size)

    def validate(self):
        if self['capture_pattern'].value != self.MAGIC:
            return "Wrong signature"
        if self['stream_structure_version'].value != 0:
            return "Unknown structure version (%s)" % self['stream_structure_version'].value
        return ""

class OggFile(Parser):
    PARSER_TAGS = {
        "id": "ogg",
        "category": "container",
        "file_ext": ("ogg", "ogm"),
        "mime": (
            u"application/ogg", u"application/x-ogg",
            u"audio/ogg", u"audio/x-ogg",
            u"video/ogg", u"video/x-ogg",
            u"video/theora", u"video/x-theora",
         ),
        "magic": ((OggPage.MAGIC, 0),),
        "subfile": "skip",
        "min_size": 28*8,
        "description": "Ogg multimedia container"
    }
    endian = LITTLE_ENDIAN

    def validate(self):
        magic = OggPage.MAGIC
        if self.stream.readBytes(0, len(magic)) != magic:
            return "Invalid magic string"
        # Validate first 3 pages
        for index in xrange(3):
            try:
                page = self[index]
            except MissingField:
                if self.done:
                    return True
                return "Unable to get page #%u" % index
            except (InputStreamError, ParserError):
                return "Unable to create page #%u" % index
            err = page.validate()
            if err:
                return "Invalid page #%s: %s" % (index, err)
        return True

    def createMimeType(self):
        if "theora_hdr" in self["page[0]/segments"]:
            return u"video/theora"
        elif "vorbis_hdr" in self["page[0]/segments"]:
            return u"audio/vorbis"
        else:
            return u"application/ogg"

    def createDescription(self):
        if "theora_hdr" in self["page[0]"]:
            return u"Ogg/Theora video"
        elif "vorbis_hdr" in self["page[0]"]:
            return u"Ogg/Vorbis audio"
        else:
            return u"Ogg multimedia container"

    def createFields(self):
        self.streams = {}
        while not self.eof:
            yield OggPage(self, "page[]")

    def createLastPage(self):
        start = self[0].size
        end = MAX_FILESIZE * 8
        if True:
            # FIXME: This doesn't work on all files (eg. some Ogg/Theora)
            offset = self.stream.searchBytes("OggS\0\5", start, end)
            if offset is None:
                offset = self.stream.searchBytes("OggS\0\4", start, end)
            if offset is None:
                return None
            return createOrphanField(self, offset, OggPage, "page")
        else:
            # Very slow version
            page = None
            while True:
                offset = self.stream.searchBytes("OggS\0", start, end)
                if offset is None:
                    break
                page = createOrphanField(self, offset, OggPage, "page")
                start += page.size
            return page

    def createContentSize(self):
        page = self.createLastPage()
        if page:
            return page.absolute_address + page.size
        else:
            return None

class OggStream(Parser):
    PARSER_TAGS = {
        "id": "ogg_stream",
        "category": "container",
        "subfile": "skip",
        "min_size": 7*8,
        "description": "Ogg logical stream"
    }
    endian = LITTLE_ENDIAN

    def validate(self):
        return False

    def createFields(self):
        for size in self.stream.packets:
            yield RawBytes(self, "packet[]", size//8)