text:
# Copyright (c) 2011 Tencent Inc.
# All rights reserved.
#
# Author: Huan Yu <huanyu@tencent.com>
#         Feng Chen <phongchen@tencent.com>
#         Yi Wang <yiwang@tencent.com>
#         Chong Peng <michaelpeng@tencent.com>
# Date:   October 20, 2011

"""
 This is the scons rules genearator module which invokes all
 the builder objects or scons objects to generate scons rules.

"""

import os
import socket
import subprocess
import string
import time

import configparse
import console

from blade_platform import CcFlagsManager

def _incs_list_to_string(incs):
    """ Convert incs list to string
    ['thirdparty', 'include'] -> -I thirdparty -I include
    """
    return ' '.join(['-I ' + path for path in incs])

def escape_c_string(s):
    all_chars = (chr(x) for x in range(256))
    trans_table = dict((c, c) for c in all_chars)
    trans_table.update({'"': r'\"'})
    return "".join(trans_table[c] for c in s)

class SconsFileHeaderGenerator(object):
    """SconsFileHeaderGenerator class"""
    def __init__(self, options, build_dir, gcc_version,
                 python_inc, cuda_inc, build_environment, svn_roots):
        """Init method. """
        self.rules_buf = []
        self.options = options
        self.build_dir = build_dir
        self.gcc_version = gcc_version
        self.python_inc = python_inc
        self.cuda_inc = cuda_inc
        self.build_environment = build_environment
        self.ccflags_manager = CcFlagsManager(options)
        self.env_list = ['env_with_error', 'env_no_warning']

        self.svn_roots = svn_roots
        self.svn_info_map = {}

        self.version_cpp_compile_template = string.Template("""
env_version = Environment(ENV = os.environ)
env_version.Append(SHCXXCOMSTR = console.erasable('%s$updateinfo%s' % (colors('cyan'), colors('end'))))
env_version.Append(CPPFLAGS = '-m$m')
version_obj = env_version.SharedObject('$filename')
""")
        self.blade_config = configparse.blade_config
        self.distcc_enabled = self.blade_config.get_config(
                              'distcc_config').get('enabled', False)
        self.dccc_enabled = self.blade_config.get_config(
                              'link_config').get('enable_dccc', False)

    def _add_rule(self, rule):
        """Append one rule to buffer. """
        self.rules_buf.append('%s\n' % rule)

    def _append_prefix_to_building_var(
                self,
                prefix='',
                building_var='',
                condition=False):
        """A helper method: append prefix to building var if condition is True."""
        if condition:
            return '%s %s' % (prefix, building_var)
        else:
            return building_var

    def _exec_get_version_info(self, cmd, cwd, dirname):
        lc_all_env = os.environ
        lc_all_env['LC_ALL'] = 'POSIX'
        p = subprocess.Popen(cmd,
                             env=lc_all_env,
                             cwd=cwd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             shell=True)
        std_out, std_err = p.communicate()
        if p.returncode:
            return False
        else:
            self.svn_info_map[dirname] = std_out.replace('\n', '\\n\\\n')
            return True

    def _get_version_info(self):
        """Gets svn root dir info. """

        blade_root_dir = self.build_environment.blade_root_dir
        if os.path.exists("%s/.git" % blade_root_dir):
          cmd = "git log -n 1"
          self._exec_get_version_info(cmd, None, os.path.dirname(blade_root_dir))
          return

        for root_dir in self.svn_roots:
            root_dir_realpath = os.path.realpath(root_dir)
            svn_working_dir = os.path.dirname(root_dir_realpath)
            svn_dir = os.path.basename(root_dir_realpath)

            cmd = 'svn info %s' % svn_dir
            cwd = svn_working_dir
            if not self._exec_get_version_info(cmd, cwd, root_dir):
                cmd = 'git ls-remote --get-url && git branch | grep "*" && git log -n 1'
                cwd = root_dir_realpath
                if  not self._exec_get_version_info(cmd, cwd, root_dir):
                    console.warning('failed to get version control info in %s' % root_dir)

    def generate_version_file(self):
        """Generate version information files. """
        self._get_version_info()
        svn_info_len = len(self.svn_info_map)

        if not os.path.exists(self.build_dir):
            os.makedirs(self.build_dir)
        version_cpp = open('%s/version.cpp' % self.build_dir, 'w')

        print >>version_cpp, '/* This file was generated by blade */'
        print >>version_cpp, 'extern "C" {'
        print >>version_cpp, 'namespace binary_version {'
        print >>version_cpp, 'extern const int kSvnInfoCount = %d;' % svn_info_len

        svn_info_array = '{'
        for idx in range(svn_info_len):
            key_with_idx = self.svn_info_map.keys()[idx]
            svn_info_line = '"%s"' % escape_c_string(self.svn_info_map[key_with_idx])
            svn_info_array += svn_info_line
            if idx != (svn_info_len - 1):
                svn_info_array += ','
        svn_info_array += '}'

        print >>version_cpp, 'extern const char* const kSvnInfo[%d] = %s;' % (
                svn_info_len, svn_info_array)
        print >>version_cpp, 'extern const char kBuildType[] = "%s";' % self.options.profile
        print >>version_cpp, 'extern const char kBuildTime[] = "%s";' % time.asctime()
        print >>version_cpp, 'extern const char kBuilderName[] = "%s";' % os.getenv('USER')
        print >>version_cpp, (
                'extern const char kHostName[] = "%s";' % socket.gethostname())
        compiler = 'GCC %s' % self.gcc_version
        print >>version_cpp, 'extern const char kCompiler[] = "%s";' % compiler
        print >>version_cpp, '}}'

        version_cpp.close()

        self._add_rule('VariantDir("%s", ".", duplicate=0)' % self.build_dir)
        self._add_rule(self.version_cpp_compile_template.substitute(
            updateinfo='Updating version information',
            m=self.options.m,
            filename='%s/version.cpp' % self.build_dir))

    def generate_imports_functions(self, blade_path):
        """Generates imports and functions. """
        self._add_rule(
            r"""
import sys
sys.path.insert(0, '%s')
""" % blade_path)
        self._add_rule(
            r"""
import os
import subprocess
import signal
import time
import socket
import glob

import blade_util
import console
import scons_helper

from build_environment import ScacheManager
from console import colors
from scons_helper import MakeAction
from scons_helper import create_fast_link_builders
from scons_helper import echospawn
from scons_helper import error_colorize
from scons_helper import generate_python_binary
from scons_helper import generate_resource_file
from scons_helper import generate_resource_index
""")

        if getattr(self.options, 'verbose', False):
            self._add_rule('scons_helper.option_verbose = True')

        self._add_rule((
                """if not os.path.exists('%s'):
    os.mkdir('%s')""") % (self.build_dir, self.build_dir))

    def generate_top_level_env(self):
        """generates top level environment. """
        self._add_rule('os.environ["LC_ALL"] = "C"')
        self._add_rule('top_env = Environment(ENV=os.environ)')
        # Optimization options, see http://www.scons.org/wiki/GoFastButton
        self._add_rule('top_env.Decider("MD5-timestamp")')
        self._add_rule('top_env.SetOption("implicit_cache", 1)')
        self._add_rule('top_env.SetOption("max_drift", 1)')

    def generate_compliation_verbose(self):
        """Generates color and verbose message. """
        self._add_rule('console.color_enabled=%s' % console.color_enabled)

        if not getattr(self.options, 'verbose', False):
            self._add_rule('top_env["SPAWN"] = echospawn')

        self._add_rule(
                """
compile_proto_cc_message = console.erasable('%sCompiling %s$SOURCE%s to cc source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_proto_java_message = console.erasable('%sCompiling %s$SOURCE%s to java source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_proto_php_message = console.erasable('%sCompiling %s$SOURCE%s to php source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_proto_python_message = console.erasable('%sCompiling %s$SOURCE%s to python source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

generate_proto_descriptor_message = console.inerasable('%sGenerating proto descriptor set %s$TARGET%s' % \
    (colors('cyan'), colors('purple'), colors('end')))

compile_thrift_cc_message = console.erasable('%sCompiling %s$SOURCE%s to cc source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_thrift_java_message = console.erasable('%sCompiling %s$SOURCE%s to java source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_thrift_python_message = console.erasable( '%sCompiling %s$SOURCE%s to python source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_fbthrift_cpp_message = console.erasable('%sCompiling %s$SOURCE%s to cpp source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_fbthrift_cpp2_message = console.erasable('%sCompiling %s$SOURCE%s to cpp2 source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_resource_index_message = console.erasable('%sGenerating resource index for %s$SOURCE_PATH/$TARGET_NAME%s%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_resource_message = console.erasable('%sCompiling %s$SOURCE%s as resource file%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_source_message = console.erasable('%sCompiling %s$SOURCE%s%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

assembling_source_message = console.erasable('%sAssembling %s$SOURCE%s%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

link_program_message = console.inerasable('%sLinking Program %s$TARGET%s%s' % \
    (colors('green'), colors('purple'), colors('green'), colors('end')))

link_library_message = console.inerasable('%sCreating Static Library %s$TARGET%s%s' % \
    (colors('green'), colors('purple'), colors('green'), colors('end')))

ranlib_library_message = console.inerasable('%sRanlib Library %s$TARGET%s%s' % \
    (colors('green'), colors('purple'), colors('green'), colors('end')))

link_shared_library_message = console.inerasable('%sLinking Shared Library %s$TARGET%s%s' % \
    (colors('green'), colors('purple'), colors('green'), colors('end')))

compile_java_jar_message = console.inerasable('%sGenerating java jar %s$TARGET%s%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_python_binary_message = console.erasable('%sGenerating python binary %s$TARGET%s%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_yacc_message = console.erasable('%sYacc %s$SOURCE%s to $TARGET%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_swig_python_message = console.erasable('%sCompiling %s$SOURCE%s to python source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_swig_java_message = console.erasable('%sCompiling %s$SOURCE%s to java source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))

compile_swig_php_message = console.erasable('%sCompiling %s$SOURCE%s to php source%s' % \
    (colors('cyan'), colors('purple'), colors('cyan'), colors('end')))
""")

        if not getattr(self.options, 'verbose', False):
            self._add_rule(
                    r"""
top_env.Append(
    CXXCOMSTR = compile_source_message,
    CCCOMSTR = compile_source_message,
    ASCOMSTR = assembling_source_message,
    SHCCCOMSTR = compile_source_message,
    SHCXXCOMSTR = compile_source_message,
    ARCOMSTR = link_library_message,
    RANLIBCOMSTR = ranlib_library_message,
    SHLINKCOMSTR = link_shared_library_message,
    LINKCOMSTR = link_program_message,
    JAVACCOMSTR = compile_source_message
)""")

    def _generate_fast_link_builders(self):
        """Generates fast link builders if it is specified in blade bash. """
        link_config = configparse.blade_config.get_config('link_config')
        enable_dccc = link_config['enable_dccc']
        if link_config['link_on_tmp']:
            if (not enable_dccc) or (
                    enable_dccc and not self.build_environment.dccc_env_prepared):
                self._add_rule('create_fast_link_builders(top_env)')

    def generate_builders(self):
        """Generates common builders. """
        # Generates builders specified in blade bash at first
        self._generate_fast_link_builders()

        proto_config = configparse.blade_config.get_config('proto_library_config')
        protoc_bin = proto_config['protoc']
        protobuf_path = proto_config['protobuf_path']

        protobuf_incs_str = _incs_list_to_string(proto_config['protobuf_incs'])
        protobuf_php_path = proto_config['protobuf_php_path']
        protoc_php_plugin = proto_config['protoc_php_plugin']
        # Genreates common builders now
        builder_list = []
        self._add_rule('time_value = Value("%s")' % time.asctime())
        self._add_rule(
            'proto_bld = Builder(action = MakeAction("%s --proto_path=. -I. %s'
            ' -I=`dirname $SOURCE` --cpp_out=%s $SOURCE", '
            'compile_proto_cc_message))' % (
                    protoc_bin, protobuf_incs_str, self.build_dir))
        builder_list.append('BUILDERS = {"Proto" : proto_bld}')

        self._add_rule(
            'proto_java_bld = Builder(action = MakeAction("%s --proto_path=. '
            '--proto_path=%s --java_out=%s/`dirname $SOURCE` $SOURCE", '
            'compile_proto_java_message))' % (
                    protoc_bin, protobuf_path, self.build_dir))
        builder_list.append('BUILDERS = {"ProtoJava" : proto_java_bld}')

        self._add_rule(
            'proto_php_bld = Builder(action = MakeAction("%s '
            '--proto_path=. --plugin=protoc-gen-php=%s '
            '-I. %s -I%s -I=`dirname $SOURCE` '
            '--php_out=%s/`dirname $SOURCE` '
            '$SOURCE", compile_proto_php_message))' % (
                    protoc_bin, protoc_php_plugin, protobuf_incs_str,
                    protobuf_php_path, self.build_dir))
        builder_list.append('BUILDERS = {"ProtoPhp" : proto_php_bld}')

        self._add_rule(
            'proto_python_bld = Builder(action = MakeAction("%s '
            '--proto_path=. '
            '-I. %s -I=`dirname $SOURCE` '
            '--python_out=%s '
            '$SOURCE", compile_proto_python_message))' % (
                    protoc_bin, protobuf_incs_str, self.build_dir))
        builder_list.append('BUILDERS = {"ProtoPython" : proto_python_bld}')

        self._add_rule(
            'proto_descriptor_bld = Builder(action = MakeAction("%s '
            '--proto_path=. '
            '-I. %s -I=`dirname $SOURCE` '
            '--descriptor_set_out=$TARGET --include_imports --include_source_info '
            '$SOURCES", generate_proto_descriptor_message))' % (
                    protoc_bin, protobuf_incs_str))
        builder_list.append('BUILDERS = {"ProtoDescriptors" : proto_descriptor_bld}')

        # Generate thrift library builders.
        thrift_config = configparse.blade_config.get_config('thrift_config')
        thrift_incs_str = _incs_list_to_string(thrift_config['thrift_incs'])
        thrift_bin = thrift_config['thrift']
        if thrift_bin.startswith('//'):
            thrift_bin = thrift_bin.replace('//', self.build_dir + '/')
            thrift_bin = thrift_bin.replace(':', '/')

        # Genreates common builders now
        self._add_rule(
            'thrift_bld = Builder(action = MakeAction("%s '
            '--gen cpp:include_prefix,pure_enums -I . %s -I `dirname $SOURCE` '
            '-out %s/`dirname $SOURCE` $SOURCE", compile_thrift_cc_message))' % (
                    thrift_bin, thrift_incs_str, self.build_dir))
        builder_list.append('BUILDERS = {"Thrift" : thrift_bld}')

        self._add_rule(
            'thrift_java_bld = Builder(action = MakeAction("%s '
            '--gen java -I . %s -I `dirname $SOURCE` -out %s/`dirname $SOURCE` '
            '$SOURCE", compile_thrift_java_message))' % (
                    thrift_bin, thrift_incs_str, self.build_dir))
        builder_list.append('BUILDERS = {"ThriftJava" : thrift_java_bld}')

        self._add_rule(
            'thrift_python_bld = Builder(action = MakeAction("%s '
            '--gen py -I . %s -I `dirname $SOURCE` -out %s/`dirname $SOURCE` '
            '$SOURCE", compile_thrift_python_message))' % (
                    thrift_bin, thrift_incs_str, self.build_dir))
        builder_list.append('BUILDERS = {"ThriftPython" : thrift_python_bld}')

        fbthrift_config = configparse.blade_config.get_config('fbthrift_config')
        fbthrift1_bin = fbthrift_config['fbthrift1']
        fbthrift2_bin = fbthrift_config['fbthrift2']
        fbthrift_incs_str = _incs_list_to_string(fbthrift_config['fbthrift_incs'])

        self._add_rule(
            'fbthrift1_bld = Builder(action = MakeAction("%s '
            '--gen cpp:templates,cob_style,include_prefix,enum_strict -I . %s -I `dirname $SOURCE` '
            '-o %s/`dirname $SOURCE` $SOURCE", compile_fbthrift_cpp_message))' % (
                    fbthrift1_bin, fbthrift_incs_str, self.build_dir))
        builder_list.append('BUILDERS = {"FBThrift1" : fbthrift1_bld}')

        self._add_rule(
            'fbthrift2_bld = Builder(action = MakeAction("%s '
            '--gen=cpp2:cob_style,include_prefix,future -I . %s -I `dirname $SOURCE` '
            '-o %s/`dirname $SOURCE` $SOURCE", compile_fbthrift_cpp2_message))' % (
                    fbthrift2_bin, fbthrift_incs_str, self.build_dir))
        builder_list.append('BUILDERS = {"FBThrift2" : fbthrift2_bld}')

        self._add_rule(
                     r"""
blade_jar_bld = Builder(action = MakeAction('jar cf $TARGET -C `dirname $SOURCE` .',
    compile_java_jar_message))

yacc_bld = Builder(action = MakeAction('bison $YACCFLAGS -d -o $TARGET $SOURCE',
    compile_yacc_message))

resource_index_bld = Builder(action = MakeAction(generate_resource_index,
    compile_resource_index_message))

resource_file_bld = Builder(action = MakeAction(generate_resource_file,
    compile_resource_message))

python_binary_bld = Builder(action = MakeAction(generate_python_binary,
    compile_python_binary_message))
""")
        builder_list.append('BUILDERS = {"BladeJar" : blade_jar_bld}')
        builder_list.append('BUILDERS = {"Yacc" : yacc_bld}')
        builder_list.append('BUILDERS = {"ResourceIndex" : resource_index_bld}')
        builder_list.append('BUILDERS = {"ResourceFile" : resource_file_bld}')
        builder_list.append('BUILDERS = {"PythonBinary" : python_binary_bld}')

        for builder in builder_list:
            self._add_rule('top_env.Append(%s)' % builder)

    def generate_compliation_flags(self):
        """Generates compliation flags. """
        toolchain_dir = os.environ.get('TOOLCHAIN_DIR', '')
        if toolchain_dir and not toolchain_dir.endswith('/'):
            toolchain_dir += '/'
        cpp_str = toolchain_dir + os.environ.get('CPP', 'cpp')
        cc_str = toolchain_dir + os.environ.get('CC', 'gcc')
        cxx_str = toolchain_dir + os.environ.get('CXX', 'g++')
        nvcc_str = toolchain_dir + os.environ.get('NVCC', 'nvcc')
        ld_str = toolchain_dir + os.environ.get('LD', 'g++')
        console.info('CPP=%s' % cpp_str)
        console.info('CC=%s' % cc_str)
        console.info('CXX=%s' % cxx_str)
        console.info('NVCC=%s' % nvcc_str)
        console.info('LD=%s' % ld_str)

        self.ccflags_manager.set_cpp_str(cpp_str)

        # To modify CC, CXX, LD according to the building environment and
        # project configuration
        build_with_distcc = (self.distcc_enabled and
                             self.build_environment.distcc_env_prepared)
        cc_str = self._append_prefix_to_building_var(
                         prefix='distcc',
                         building_var=cc_str,
                         condition=build_with_distcc)

        cxx_str = self._append_prefix_to_building_var(
                         prefix='distcc',
                         building_var=cxx_str,
                         condition=build_with_distcc)

        build_with_ccache = self.build_environment.ccache_installed
        cc_str = self._append_prefix_to_building_var(
                         prefix='ccache',
                         building_var=cc_str,
                         condition=build_with_ccache)

        cxx_str = self._append_prefix_to_building_var(
                         prefix='ccache',
                         building_var=cxx_str,
                         condition=build_with_ccache)

        build_with_dccc = (self.dccc_enabled and
                           self.build_environment.dccc_env_prepared)
        ld_str = self._append_prefix_to_building_var(
                        prefix='dccc',
                        building_var=ld_str,
                        condition=build_with_dccc)

        cc_env_str = 'CC="%s", CXX="%s"' % (cc_str, cxx_str)
        ld_env_str = 'LINK="%s"' % ld_str
        nvcc_env_str = 'NVCC="%s"' % nvcc_str

        cc_config = configparse.blade_config.get_config('cc_config')
        extra_incs = cc_config['extra_incs']
        extra_incs_str = ', '.join(['"%s"' % inc for inc in extra_incs])
        if not extra_incs_str:
            extra_incs_str = '""'

        (cppflags_except_warning, linkflags) = self.ccflags_manager.get_flags_except_warning()

        builder_list = []
        cuda_incs_str = ' '.join(['-I%s' % inc for inc in self.cuda_inc])
        self._add_rule(
            'nvcc_object_bld = Builder(action = MakeAction("%s -ccbin g++ %s '
            '$NVCCFLAGS -o $TARGET -c $SOURCE", compile_source_message))' % (
                    nvcc_str, cuda_incs_str))
        builder_list.append('BUILDERS = {"NvccObject" : nvcc_object_bld}')

        self._add_rule(
            'nvcc_binary_bld = Builder(action = MakeAction("%s %s '
            '$NVCCFLAGS -o $TARGET ", link_program_message))' % (
                    nvcc_str, cuda_incs_str))
        builder_list.append('BUILDERS = {"NvccBinary" : nvcc_binary_bld}')

        for builder in builder_list:
            self._add_rule('top_env.Append(%s)' % builder)

        self._add_rule('top_env.Replace(%s, %s, '
                       'CPPPATH=[%s, "%s", "%s"], '
                       'CPPFLAGS=%s, CFLAGS=%s, CXXFLAGS=%s, '
                       '%s, LINKFLAGS=%s)' %
                       (cc_env_str, nvcc_env_str,
                        extra_incs_str, self.build_dir, self.python_inc,
                        cc_config['cppflags'] + cppflags_except_warning,
                        cc_config['cflags'],
                        cc_config['cxxflags'],
                        ld_env_str, linkflags))

        self._setup_cache()

        if build_with_distcc:
            self.build_environment.setup_distcc_env()

        for rule in self.build_environment.get_rules():
            self._add_rule(rule)

        self._setup_warnings()

    def _setup_warnings(self):
        for env in self.env_list:
            self._add_rule('%s = top_env.Clone()' % env)

        (warnings, cxx_warnings, c_warnings) = self.ccflags_manager.get_warning_flags()
        self._add_rule('%s.Append(CPPFLAGS=%s, CFLAGS=%s, CXXFLAGS=%s)' % (
            self.env_list[0],
            warnings, c_warnings, cxx_warnings))

    def _setup_cache(self):
        if self.build_environment.ccache_installed:
            self.build_environment.setup_ccache_env()
        else:
            cache_dir = os.path.expanduser('~/.bladescache')
            cache_size = 4 * 1024 * 1024 * 1024
            if hasattr(self.options, 'cache_dir'):
                if not self.options.cache_dir:
                    return
                cache_dir = self.options.cache_dir
            else:
                console.info('using default cache dir: %s' % cache_dir)

            if hasattr(self.options, 'cache_size') and (self.options.cache_size != -1):
                cache_size = self.options.cache_size

            self._add_rule('CacheDir("%s")' % cache_dir)
            self._add_rule('scache_manager = ScacheManager("%s", cache_limit=%d)' % (
                        cache_dir, cache_size))
            self._add_rule('Progress(scache_manager, interval=100)')

            self._add_rule('console.info("using cache directory %s")' % cache_dir)
            self._add_rule('console.info("scache size %d")' % cache_size)

    def generate(self, blade_path):
        """Generates all rules. """
        self.generate_imports_functions(blade_path)
        self.generate_top_level_env()
        self.generate_compliation_verbose()
        self.generate_version_file()
        self.generate_builders()
        self.generate_compliation_flags()
        return self.rules_buf

class SconsRulesGenerator(object):
    """The main class to generate scons rules and outputs rules to SConstruct. """
    def __init__(self, scons_path, blade_path, blade):
        """Init method. """
        self.scons_path = scons_path
        self.blade_path = blade_path
        self.blade = blade
        self.scons_platform = self.blade.get_scons_platform()

        build_dir = self.blade.get_build_path()
        options = self.blade.get_options()
        gcc_version = self.scons_platform.get_gcc_version()
        python_inc = self.scons_platform.get_python_include()
        cuda_inc = self.scons_platform.get_cuda_include()

        self.scons_file_header_generator = SconsFileHeaderGenerator(
                options,
                build_dir,
                gcc_version,
                python_inc,
                cuda_inc,
                self.blade.build_environment,
                self.blade.svn_root_dirs)
        try:
            os.remove('blade-bin')
        except os.error:
            pass
        os.symlink(os.path.abspath(build_dir), 'blade-bin')

    def generate_scons_script(self):
        """Generates SConstruct script. """
        rules_buf = self.scons_file_header_generator.generate(self.blade_path)
        rules_buf += self.blade.gen_targets_rules()

        # Write to SConstruct
        self.scons_file_fd = open(self.scons_path, 'w')
        self.scons_file_fd.writelines(rules_buf)
        self.scons_file_fd.close()
        return rules_buf


text:
package com.google.api.ads.dfp.jaxws.v201511;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for AdRuleSlotError.Reason.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="AdRuleSlotError.Reason">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="DIFFERENT_STATUS_THAN_AD_RULE"/>
 *     <enumeration value="INVALID_VIDEO_AD_DURATION_RANGE"/>
 *     <enumeration value="INVALID_VIDEO_MIDROLL_FREQUENCY_TYPE"/>
 *     <enumeration value="MALFORMED_VIDEO_MIDROLL_FREQUENCY_CSV"/>
 *     <enumeration value="MALFORMED_VIDEO_MIDROLL_FREQUENCY_SINGLE_NUMBER"/>
 *     <enumeration value="INVALID_OVERLAY_AD_DURATION_RANGE"/>
 *     <enumeration value="INVALID_OVERLAY_MIDROLL_FREQUENCY_TYPE"/>
 *     <enumeration value="MALFORMED_OVERLAY_MIDROLL_FREQUENCY_CSV"/>
 *     <enumeration value="MALFORMED_OVERLAY_MIDROLL_FREQUENCY_SINGLE_NUMBER"/>
 *     <enumeration value="INVALID_BUMPER_MAX_DURATION"/>
 *     <enumeration value="UNKNOWN"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "AdRuleSlotError.Reason")
@XmlEnum
public enum AdRuleSlotErrorReason {

    /**
     *
     *                 Has a different status than the ad rule to which it belongs.
     *
     *
     */
    DIFFERENT_STATUS_THAN_AD_RULE,

    /**
     *
     *                 Min video ad duration is greater than max video ad duration.
     *
     *
     */
    INVALID_VIDEO_AD_DURATION_RANGE,

    /**
     *
     *                 Video mid-roll frequency type other than NONE for pre-roll or post-roll.
     *
     *
     */
    INVALID_VIDEO_MIDROLL_FREQUENCY_TYPE,

    /**
     *
     *                 Invalid format for video mid-roll frequency when expecting a CSV list of
     *                 numbers. Valid formats are the following:

     *
empty
     *
 comma-separated list of numbers (time milliseconds or cue points)
     *
a single number (every n milliseconds or cue points, or one
     *                 specific time / cue point)
     *

     *
     *
     */
    MALFORMED_VIDEO_MIDROLL_FREQUENCY_CSV,

    /**
     *
     *                 Invalid format for video mid-roll frequency when expecting a single
     *                 number only, e.g., every n seconds or every n cue points.
     *
     *
     */
    MALFORMED_VIDEO_MIDROLL_FREQUENCY_SINGLE_NUMBER,

    /**
     *
     *                 Min overlay ad duration is greater than max overlay ad duration.
     *
     *
     */
    INVALID_OVERLAY_AD_DURATION_RANGE,

    /**
     *
     *                 Overlay mid-roll frequency type other than NONE for pre-roll or
     *                 post-roll.
     *
     *
     */
    INVALID_OVERLAY_MIDROLL_FREQUENCY_TYPE,

    /**
     *
     *                 Invalid format for overlay mid-roll frequency for list of numbers. See
     *                 valid formats above.
     *
     *
     */
    MALFORMED_OVERLAY_MIDROLL_FREQUENCY_CSV,

    /**
     *
     *                 Invalid format for overlay mid-roll frequency for a single number.
     *
     *
     */
    MALFORMED_OVERLAY_MIDROLL_FREQUENCY_SINGLE_NUMBER,

    /**
     *
     *                 Non-positive bumper duration when expecting a positive number.
     *
     *
     */
    INVALID_BUMPER_MAX_DURATION,

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN;

    public String value() {
        return name();
    }

    public static AdRuleSlotErrorReason fromValue(String v) {
        return valueOf(v);
    }

}

redpajama_set_name: RedPajamaGithub


text:
import { dissocPath } from '../index';
export default dissocPath;


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Composition;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.NetCore.Analyzers.Performance;

namespace Microsoft.NetCore.CSharp.Analyzers.Performance
{
    /// <summary>
    /// CA1836: Prefer IsEmpty over Count when available.
    /// </summary>
    [ExportCodeFixProvider(LanguageNames.CSharp), Shared]
    public sealed class CSharpPreferIsEmptyOverCountFixer : PreferIsEmptyOverCountFixer
    {
        protected override SyntaxNode? GetObjectExpressionFromOperation(SyntaxNode node, string operationKey)
        {
            SyntaxNode? countNode = null;
            switch (operationKey)
            {
                case UseCountProperlyAnalyzer.OperationBinaryLeft:
                    if (node is BinaryExpressionSyntax binaryExpression)
                    {
                        countNode = binaryExpression.Left;
                    }
                    break;
                case UseCountProperlyAnalyzer.OperationBinaryRight:
                    if (node is BinaryExpressionSyntax binaryExpression2)
                    {
                        countNode = binaryExpression2.Right;
                    }
                    break;
                case UseCountProperlyAnalyzer.OperationEqualsArgument:
                    if (node is InvocationExpressionSyntax invocationExpression)
                    {
                        countNode = invocationExpression.ArgumentList.Arguments[0].Expression;
                    }
                    break;
                case UseCountProperlyAnalyzer.OperationEqualsInstance:
                    if (node is InvocationExpressionSyntax invocationExpression2)
                    {
                        SyntaxNode equalsMemberAccess = invocationExpression2.Expression;
                        if (equalsMemberAccess is MemberAccessExpressionSyntax memberAccess)
                        {
                            countNode = memberAccess.Expression;
                        }
                    }
                    break;
            }

            RoslynDebug.Assert(countNode != null);

            bool isParenthesizedOrCastExpression;
            do
            {
                isParenthesizedOrCastExpression = true;

                switch (countNode)
                {
                    case ParenthesizedExpressionSyntax parenthesizedExpression:
                        countNode = parenthesizedExpression.Expression;
                        break;
                    case CastExpressionSyntax castExpression:
                        countNode = castExpression.Expression;
                        break;
                    default:
                        isParenthesizedOrCastExpression = false;
                        break;
                }
            }
            while (isParenthesizedOrCastExpression);

            if (countNode is InvocationExpressionSyntax invocationExpression3)
            {
                countNode = invocationExpression3.Expression;
            }

            SyntaxNode? objectNode = null;

            if (countNode is MemberAccessExpressionSyntax memberAccess2)
            {
                objectNode = memberAccess2.Expression;
            }

            RoslynDebug.Assert(objectNode != null || countNode is IdentifierNameSyntax);
            return objectNode;
        }
    }
}


text:
#include <pluginlib/class_loader.h>
#include <ros/ros.h>
#include <move_itomp/move_itomp_util.h>
#include <move_itomp/rbprm_reader.h>
#include <move_itomp/bvh_writer.h>

const double INV_SQRT_2 = 1.0 / std::sqrt((long double) 2.0);

using namespace move_itomp_util;
using namespace rbprm_reader;

int main(int argc, char **argv)
{
	int motion = 0;
    std::string initialpath = "";
	if (argc >= 2)
	{
		motion = atoi(argv[1]);
        if(argc >=3)
        {
            initialpath = argv[2];
        }
	}
	printf("%d Motion %d\n", argc, motion);

	ros::init(argc, argv, "move_itomp");
	ros::AsyncSpinner spinner(1);
	spinner.start();
	ros::NodeHandle node_handle("~");

    robot_model_loader::RobotModelLoader robot_model_loader("robot_description");
	robot_model::RobotModelPtr robot_model = robot_model_loader.getModel();

    planning_scene::PlanningScenePtr planning_scene(new planning_scene::PlanningScene(robot_model));

	ros::Publisher planning_scene_diff_publisher;
    planning_scene_diff_publisher = node_handle.advertise<moveit_msgs::PlanningScene>("/planning_scene", 1);
	while (planning_scene_diff_publisher.getNumSubscribers() < 1)
	{
		ros::WallDuration sleep_t(0.5);
		sleep_t.sleep();
		ROS_INFO("Waiting planning_scene subscribers");
	}

    boost::scoped_ptr<pluginlib::ClassLoader<planning_interface::PlannerManager> > planner_plugin_loader;
    planning_interface::PlannerManagerPtr planner_instance;
    initializePlanner(planner_plugin_loader, planner_instance, node_handle, robot_model);

	loadStaticScene(node_handle, planning_scene, robot_model, planning_scene_diff_publisher);

	/* Sleep a little to allow time to startup rviz, etc. */
	ros::WallDuration sleep_time(1.0);
	sleep_time.sleep();

	std::vector<robot_state::RobotState> robot_states;

	robot_states.push_back(planning_scene->getCurrentStateNonConst());
    robot_states.push_back(robot_states.back());

	// set trajectory constraints
    std::vector<Eigen::VectorXd> waypoints;
    std::vector<Eigen::MatrixXd> contactPoints;
    std::vector<std::string> hierarchy;

    if(initialpath.empty())
    {
        ROS_ERROR("Initial path is empty");
    }

    hierarchy = InitTrajectoryFromFile(waypoints, contactPoints, initialpath);
    robot_state::RobotState rs(planning_scene->getCurrentStateNonConst());
    displayInitialWaypoints(rs, node_handle, robot_model, hierarchy, waypoints);

    moveit_msgs::DisplayTrajectory display_trajectory;
    unsigned int last = waypoints.size() - 2;
    for (unsigned int i = 1; i <= last; ++i)
    {
        planning_interface::MotionPlanRequest req;
        planning_interface::MotionPlanResponse res;

        for (unsigned int j = 0; j < waypoints[i].rows(); ++j)
        {
            double cur_pos = waypoints[i](j);
            double next_pos = waypoints[i + 1](j);
            while (next_pos - cur_pos > M_PI + 0.1)
                next_pos -= 2 * M_PI;
            while (next_pos - cur_pos < -M_PI - 0.1)
                next_pos += 2 * M_PI;
            waypoints[i + 1](j) = next_pos;
        }

        for (unsigned int j = i; j <= i + 1; ++j)
        {
            moveit_msgs::Constraints constraint;
            setRootJointConstraint(constraint, hierarchy, waypoints[j]);
            req.trajectory_constraints.constraints.push_back(constraint);
        }
        setRobotStateFrom(robot_states[0], hierarchy, waypoints, i);
        setRobotStateFrom(robot_states[1], hierarchy, waypoints, i + 1);

        displayStates(robot_states[0], robot_states[1], node_handle, robot_model);
        doPlan("whole_body", req, res, robot_states[0], robot_states[1], planning_scene, planner_instance);

        if (i == last)
        {
            for (int j = 0; j < 10; ++j)
                res.trajectory_->addSuffixWayPoint(res.trajectory_->getLastWayPoint(), 5000);
        }

        moveit_msgs::MotionPlanResponse response;
        res.getMessage(response);

        if (i == 0)
            display_trajectory.trajectory_start = response.trajectory_start;

        display_trajectory.trajectory.push_back(response.trajectory);
    }

    ROS_INFO("Visualizing the trajectory");
    static ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);

    display_publisher.publish(display_trajectory);
    ros::WallDuration timer(1.0);
    timer.sleep();

	ROS_INFO("Done");

    bvh_writer::writeWalkingTrajectoryBVHFile(robot_model, display_trajectory, "walking_optimized.bvh");

	return 0;
}


text:
package com.github.gustavofernandes.gameengine.common;

public class PlaceOccupiedException extends Exception {}


text:
import os
import webapp2 as webapp
from constants import VIRTUAL_ENV_DIR, HTTP_PORT, HTTP_HOST, PRODUCTION
from constants import USER_NAME

try:
    virtenv = VIRTUAL_ENV_DIR + '/virtenv/'
    virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
    execfile(virtualenv, dict(__file__=virtualenv))
#except IOError:
except:
    pass

from webpages.mainpage import RecPage
from webpages.statistics import UserStatisticsPage

application = webapp.WSGIApplication([('/', RecPage),
                                      ('/users/(.+)/(' + USER_NAME + ')', UserStatisticsPage)], debug=not PRODUCTION)

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    import webapp2 as webapp
    from paste.urlparser import StaticURLParser
    from paste.cascade import Cascade

    static_app = StaticURLParser("wsgi/")
    app = Cascade([static_app, application])

    httpd = make_server(HTTP_HOST, HTTP_PORT, app)
    httpd.serve_forever()


text:
package org.apache.ignite.ml.trainers.group;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.ignite.ml.math.functions.IgniteFunction;
import org.apache.ignite.ml.math.functions.IgniteSupplier;
import org.apache.ignite.ml.trainers.group.chain.EntryAndContext;

/**
 * {@link BaseLocalProcessorJob} specified to entry processing.
 *
 * @param <K> Type of cache used for group training.
 * @param <V> Type of values used for group training.
 * @param <C> Type of context.
 * @param <R> Type of result returned by worker.
 */
public class LocalEntriesProcessorJob<K, V, C, R extends Serializable> extends BaseLocalProcessorJob<K, V, EntryAndContext<K, V, C>, R> {
    /**
     * Supplier of context for worker.
     */
    private final IgniteSupplier<C> ctxSupplier;

    /**
     * Construct an instance of this class.
     *
     * @param ctxSupplier Supplier for context for worker.
     * @param worker Worker.
     * @param keySupplier Supplier of keys.
     * @param reducer Reducer.
     * @param trainingUUID UUID for training.
     * @param cacheName Name of cache used for training.
     */
    public LocalEntriesProcessorJob(IgniteSupplier<C> ctxSupplier,
        IgniteFunction<EntryAndContext<K, V, C>, ResultAndUpdates<R>> worker,
        IgniteSupplier<Stream<GroupTrainerCacheKey<K>>> keySupplier,
        IgniteFunction<List<R>, R> reducer,
        UUID trainingUUID, String cacheName) {
        super(worker, keySupplier, reducer, trainingUUID, cacheName);
        this.ctxSupplier = ctxSupplier;
    }

    /** {@inheritDoc} */
    @Override protected Stream<EntryAndContext<K, V, C>> toProcess() {
        C ctx = ctxSupplier.get();

        return selectLocalEntries().map(e -> new EntryAndContext<>(e, ctx));
    }

    /**
     * Select entries for processing by worker.
     *
     * @return Entries for processing by worker.
     */
    private Stream<Map.Entry<GroupTrainerCacheKey<K>, V>> selectLocalEntries() {
        Set<GroupTrainerCacheKey<K>> keys = keySupplier.get().
            filter(k -> Objects.requireNonNull(affinity().mapKeyToNode(k)).isLocal()).
            filter(k -> k.trainingUUID().equals(trainingUUID)).
            collect(Collectors.toSet());

        return cache().getAll(keys).entrySet().stream();
    }
}


text:
Attempting to rate publicly exposed dota2 players by parsing game results from the steam API

## Requirements
+ npm
+ mongodb
+ steam api key

## How to run
Install dependencies

    npm install

Edit config file to put your API key and database connection string

    config.key = 'YOUR_STEAM_API_KEY';
    config.connectionString = 'mongodb://127.0.0.1:27017/dota2';

Run it

    node app

And the players collection in the database will build. Rating algorithm used is [TrueSkill](https://github.com/izaakschroeder/trueskill)

## Querying the database
### Top 50
    db.players.find().sort({'rating.mu': -1}).limit(50)
### Average Rating
    db.players.aggregate([{$group:{_id:null,total:{$avg: '$rating.mu'}}}])


text:
jquery.redirect.js
==================

jQuery Form Redirect


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto

package com.google.cloud.compute.v1;

public interface NetworkOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.Network)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Deprecated in favor of subnet mode networks. The range of internal addresses that are legal on this network. This range is a CIDR specification, for example: 192.168.0.0/16. Provided by the client when the network is created.
   *

   *
   * optional string I_pv4_range = 59234358;
   *
   * @return Whether the iPv4Range field is set.
   */
  boolean hasIPv4Range();
  /**
   *
   *
   *

   * Deprecated in favor of subnet mode networks. The range of internal addresses that are legal on this network. This range is a CIDR specification, for example: 192.168.0.0/16. Provided by the client when the network is created.
   *

   *
   * optional string I_pv4_range = 59234358;
   *
   * @return The iPv4Range.
   */
  java.lang.String getIPv4Range();
  /**
   *
   *
   *

   * Deprecated in favor of subnet mode networks. The range of internal addresses that are legal on this network. This range is a CIDR specification, for example: 192.168.0.0/16. Provided by the client when the network is created.
   *

   *
   * optional string I_pv4_range = 59234358;
   *
   * @return The bytes for iPv4Range.
   */
  com.google.protobuf.ByteString getIPv4RangeBytes();

  /**
   *
   *
   *

   * Must be set to create a VPC network. If not set, a legacy network is created. When set to true, the VPC network is created in auto mode. When set to false, the VPC network is created in custom mode. An auto mode VPC network starts with one subnet per region. Each subnet has a predetermined range as described in Auto mode VPC network IP ranges. For custom mode VPC networks, you can add subnets using the subnetworks insert method.
   *

   *
   * optional bool auto_create_subnetworks = 256156690;
   *
   * @return Whether the autoCreateSubnetworks field is set.
   */
  boolean hasAutoCreateSubnetworks();
  /**
   *
   *
   *

   * Must be set to create a VPC network. If not set, a legacy network is created. When set to true, the VPC network is created in auto mode. When set to false, the VPC network is created in custom mode. An auto mode VPC network starts with one subnet per region. Each subnet has a predetermined range as described in Auto mode VPC network IP ranges. For custom mode VPC networks, you can add subnets using the subnetworks insert method.
   *

   *
   * optional bool auto_create_subnetworks = 256156690;
   *
   * @return The autoCreateSubnetworks.
   */
  boolean getAutoCreateSubnetworks();

  /**
   *
   *
   *

   * [Output Only] Creation timestamp in RFC3339 text format.
   *

   *
   * optional string creation_timestamp = 30525366;
   *
   * @return Whether the creationTimestamp field is set.
   */
  boolean hasCreationTimestamp();
  /**
   *
   *
   *

   * [Output Only] Creation timestamp in RFC3339 text format.
   *

   *
   * optional string creation_timestamp = 30525366;
   *
   * @return The creationTimestamp.
   */
  java.lang.String getCreationTimestamp();
  /**
   *
   *
   *

   * [Output Only] Creation timestamp in RFC3339 text format.
   *

   *
   * optional string creation_timestamp = 30525366;
   *
   * @return The bytes for creationTimestamp.
   */
  com.google.protobuf.ByteString getCreationTimestampBytes();

  /**
   *
   *
   *

   * An optional description of this resource. Provide this field when you create the resource.
   *

   *
   * optional string description = 422937596;
   *
   * @return Whether the description field is set.
   */
  boolean hasDescription();
  /**
   *
   *
   *

   * An optional description of this resource. Provide this field when you create the resource.
   *

   *
   * optional string description = 422937596;
   *
   * @return The description.
   */
  java.lang.String getDescription();
  /**
   *
   *
   *

   * An optional description of this resource. Provide this field when you create the resource.
   *

   *
   * optional string description = 422937596;
   *
   * @return The bytes for description.
   */
  com.google.protobuf.ByteString getDescriptionBytes();

  /**
   *
   *
   *

   * Enable ULA internal ipv6 on this network. Enabling this feature will assign a /48 from google defined ULA prefix fd20::/20. .
   *

   *
   * optional bool enable_ula_internal_ipv6 = 423757720;
   *
   * @return Whether the enableUlaInternalIpv6 field is set.
   */
  boolean hasEnableUlaInternalIpv6();
  /**
   *
   *
   *

   * Enable ULA internal ipv6 on this network. Enabling this feature will assign a /48 from google defined ULA prefix fd20::/20. .
   *

   *
   * optional bool enable_ula_internal_ipv6 = 423757720;
   *
   * @return The enableUlaInternalIpv6.
   */
  boolean getEnableUlaInternalIpv6();

  /**
   *
   *
   *

   * [Output Only] URL of the firewall policy the network is associated with.
   *

   *
   * optional string firewall_policy = 498173265;
   *
   * @return Whether the firewallPolicy field is set.
   */
  boolean hasFirewallPolicy();
  /**
   *
   *
   *

   * [Output Only] URL of the firewall policy the network is associated with.
   *

   *
   * optional string firewall_policy = 498173265;
   *
   * @return The firewallPolicy.
   */
  java.lang.String getFirewallPolicy();
  /**
   *
   *
   *

   * [Output Only] URL of the firewall policy the network is associated with.
   *

   *
   * optional string firewall_policy = 498173265;
   *
   * @return The bytes for firewallPolicy.
   */
  com.google.protobuf.ByteString getFirewallPolicyBytes();

  /**
   *
   *
   *

   * [Output Only] The gateway address for default routing out of the network, selected by GCP.
   *

   *
   * optional string gateway_i_pv4 = 178678877;
   *
   * @return Whether the gatewayIPv4 field is set.
   */
  boolean hasGatewayIPv4();
  /**
   *
   *
   *

   * [Output Only] The gateway address for default routing out of the network, selected by GCP.
   *

   *
   * optional string gateway_i_pv4 = 178678877;
   *
   * @return The gatewayIPv4.
   */
  java.lang.String getGatewayIPv4();
  /**
   *
   *
   *

   * [Output Only] The gateway address for default routing out of the network, selected by GCP.
   *

   *
   * optional string gateway_i_pv4 = 178678877;
   *
   * @return The bytes for gatewayIPv4.
   */
  com.google.protobuf.ByteString getGatewayIPv4Bytes();

  /**
   *
   *
   *

   * [Output Only] The unique identifier for the resource. This identifier is defined by the server.
   *

   *
   * optional uint64 id = 3355;
   *
   * @return Whether the id field is set.
   */
  boolean hasId();
  /**
   *
   *
   *

   * [Output Only] The unique identifier for the resource. This identifier is defined by the server.
   *

   *
   * optional uint64 id = 3355;
   *
   * @return The id.
   */
  long getId();

  /**
   *
   *
   *

   * When enabling ula internal ipv6, caller optionally can specify the /48 range they want from the google defined ULA prefix fd20::/20. The input must be a valid /48 ULA IPv6 address and must be within the fd20::/20. Operation will fail if the speficied /48 is already in used by another resource. If the field is not speficied, then a /48 range will be randomly allocated from fd20::/20 and returned via this field. .
   *

   *
   * optional string internal_ipv6_range = 277456807;
   *
   * @return Whether the internalIpv6Range field is set.
   */
  boolean hasInternalIpv6Range();
  /**
   *
   *
   *

   * When enabling ula internal ipv6, caller optionally can specify the /48 range they want from the google defined ULA prefix fd20::/20. The input must be a valid /48 ULA IPv6 address and must be within the fd20::/20. Operation will fail if the speficied /48 is already in used by another resource. If the field is not speficied, then a /48 range will be randomly allocated from fd20::/20 and returned via this field. .
   *

   *
   * optional string internal_ipv6_range = 277456807;
   *
   * @return The internalIpv6Range.
   */
  java.lang.String getInternalIpv6Range();
  /**
   *
   *
   *

   * When enabling ula internal ipv6, caller optionally can specify the /48 range they want from the google defined ULA prefix fd20::/20. The input must be a valid /48 ULA IPv6 address and must be within the fd20::/20. Operation will fail if the speficied /48 is already in used by another resource. If the field is not speficied, then a /48 range will be randomly allocated from fd20::/20 and returned via this field. .
   *

   *
   * optional string internal_ipv6_range = 277456807;
   *
   * @return The bytes for internalIpv6Range.
   */
  com.google.protobuf.ByteString getInternalIpv6RangeBytes();

  /**
   *
   *
   *

   * [Output Only] Type of the resource. Always compute#network for networks.
   *

   *
   * optional string kind = 3292052;
   *
   * @return Whether the kind field is set.
   */
  boolean hasKind();
  /**
   *
   *
   *

   * [Output Only] Type of the resource. Always compute#network for networks.
   *

   *
   * optional string kind = 3292052;
   *
   * @return The kind.
   */
  java.lang.String getKind();
  /**
   *
   *
   *

   * [Output Only] Type of the resource. Always compute#network for networks.
   *

   *
   * optional string kind = 3292052;
   *
   * @return The bytes for kind.
   */
  com.google.protobuf.ByteString getKindBytes();

  /**
   *
   *
   *

   * Maximum Transmission Unit in bytes. The minimum value for this field is 1300 and the maximum value is 8896. The suggested value is 1500, which is the default MTU used on the Internet, or 8896 if you want to use Jumbo frames. If unspecified, the value defaults to 1460.
   *

   *
   * optional int32 mtu = 108462;
   *
   * @return Whether the mtu field is set.
   */
  boolean hasMtu();
  /**
   *
   *
   *

   * Maximum Transmission Unit in bytes. The minimum value for this field is 1300 and the maximum value is 8896. The suggested value is 1500, which is the default MTU used on the Internet, or 8896 if you want to use Jumbo frames. If unspecified, the value defaults to 1460.
   *

   *
   * optional int32 mtu = 108462;
   *
   * @return The mtu.
   */
  int getMtu();

  /**
   *
   *
   *

   * Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be a lowercase letter, and all following characters (except for the last character) must be a dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
   *

   *
   * optional string name = 3373707;
   *
   * @return Whether the name field is set.
   */
  boolean hasName();
  /**
   *
   *
   *

   * Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be a lowercase letter, and all following characters (except for the last character) must be a dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
   *

   *
   * optional string name = 3373707;
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be a lowercase letter, and all following characters (except for the last character) must be a dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
   *

   *
   * optional string name = 3373707;
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();

  /**
   *
   *
   *

   * The network firewall policy enforcement order. Can be either AFTER_CLASSIC_FIREWALL or BEFORE_CLASSIC_FIREWALL. Defaults to AFTER_CLASSIC_FIREWALL if the field is not specified.
   * Check the NetworkFirewallPolicyEnforcementOrder enum for the list of possible values.
   *

   *
   * optional string network_firewall_policy_enforcement_order = 6504784;
   *
   * @return Whether the networkFirewallPolicyEnforcementOrder field is set.
   */
  boolean hasNetworkFirewallPolicyEnforcementOrder();
  /**
   *
   *
   *

   * The network firewall policy enforcement order. Can be either AFTER_CLASSIC_FIREWALL or BEFORE_CLASSIC_FIREWALL. Defaults to AFTER_CLASSIC_FIREWALL if the field is not specified.
   * Check the NetworkFirewallPolicyEnforcementOrder enum for the list of possible values.
   *

   *
   * optional string network_firewall_policy_enforcement_order = 6504784;
   *
   * @return The networkFirewallPolicyEnforcementOrder.
   */
  java.lang.String getNetworkFirewallPolicyEnforcementOrder();
  /**
   *
   *
   *

   * The network firewall policy enforcement order. Can be either AFTER_CLASSIC_FIREWALL or BEFORE_CLASSIC_FIREWALL. Defaults to AFTER_CLASSIC_FIREWALL if the field is not specified.
   * Check the NetworkFirewallPolicyEnforcementOrder enum for the list of possible values.
   *

   *
   * optional string network_firewall_policy_enforcement_order = 6504784;
   *
   * @return The bytes for networkFirewallPolicyEnforcementOrder.
   */
  com.google.protobuf.ByteString getNetworkFirewallPolicyEnforcementOrderBytes();

  /**
   *
   *
   *

   * [Output Only] A list of network peerings for the resource.
   *

   *
   * repeated .google.cloud.compute.v1.NetworkPeering peerings = 69883187;
   */
  java.util.List<com.google.cloud.compute.v1.NetworkPeering> getPeeringsList();
  /**
   *
   *
   *

   * [Output Only] A list of network peerings for the resource.
   *

   *
   * repeated .google.cloud.compute.v1.NetworkPeering peerings = 69883187;
   */
  com.google.cloud.compute.v1.NetworkPeering getPeerings(int index);
  /**
   *
   *
   *

   * [Output Only] A list of network peerings for the resource.
   *

   *
   * repeated .google.cloud.compute.v1.NetworkPeering peerings = 69883187;
   */
  int getPeeringsCount();
  /**
   *
   *
   *

   * [Output Only] A list of network peerings for the resource.
   *

   *
   * repeated .google.cloud.compute.v1.NetworkPeering peerings = 69883187;
   */
  java.util.List<? extends com.google.cloud.compute.v1.NetworkPeeringOrBuilder>
      getPeeringsOrBuilderList();
  /**
   *
   *
   *

   * [Output Only] A list of network peerings for the resource.
   *

   *
   * repeated .google.cloud.compute.v1.NetworkPeering peerings = 69883187;
   */
  com.google.cloud.compute.v1.NetworkPeeringOrBuilder getPeeringsOrBuilder(int index);

  /**
   *
   *
   *

   * The network-level routing configuration for this network. Used by Cloud Router to determine what type of network-wide routing behavior to enforce.
   *

   *
   * optional .google.cloud.compute.v1.NetworkRoutingConfig routing_config = 523556059;
   *
   * @return Whether the routingConfig field is set.
   */
  boolean hasRoutingConfig();
  /**
   *
   *
   *

   * The network-level routing configuration for this network. Used by Cloud Router to determine what type of network-wide routing behavior to enforce.
   *

   *
   * optional .google.cloud.compute.v1.NetworkRoutingConfig routing_config = 523556059;
   *
   * @return The routingConfig.
   */
  com.google.cloud.compute.v1.NetworkRoutingConfig getRoutingConfig();
  /**
   *
   *
   *

   * The network-level routing configuration for this network. Used by Cloud Router to determine what type of network-wide routing behavior to enforce.
   *

   *
   * optional .google.cloud.compute.v1.NetworkRoutingConfig routing_config = 523556059;
   */
  com.google.cloud.compute.v1.NetworkRoutingConfigOrBuilder getRoutingConfigOrBuilder();

  /**
   *
   *
   *

   * [Output Only] Server-defined URL for the resource.
   *

   *
   * optional string self_link = 456214797;
   *
   * @return Whether the selfLink field is set.
   */
  boolean hasSelfLink();
  /**
   *
   *
   *

   * [Output Only] Server-defined URL for the resource.
   *

   *
   * optional string self_link = 456214797;
   *
   * @return The selfLink.
   */
  java.lang.String getSelfLink();
  /**
   *
   *
   *

   * [Output Only] Server-defined URL for the resource.
   *

   *
   * optional string self_link = 456214797;
   *
   * @return The bytes for selfLink.
   */
  com.google.protobuf.ByteString getSelfLinkBytes();

  /**
   *
   *
   *

   * [Output Only] Server-defined URL for this resource with the resource id.
   *

   *
   * optional string self_link_with_id = 44520962;
   *
   * @return Whether the selfLinkWithId field is set.
   */
  boolean hasSelfLinkWithId();
  /**
   *
   *
   *

   * [Output Only] Server-defined URL for this resource with the resource id.
   *

   *
   * optional string self_link_with_id = 44520962;
   *
   * @return The selfLinkWithId.
   */
  java.lang.String getSelfLinkWithId();
  /**
   *
   *
   *

   * [Output Only] Server-defined URL for this resource with the resource id.
   *

   *
   * optional string self_link_with_id = 44520962;
   *
   * @return The bytes for selfLinkWithId.
   */
  com.google.protobuf.ByteString getSelfLinkWithIdBytes();

  /**
   *
   *
   *

   * [Output Only] Server-defined fully-qualified URLs for all subnetworks in this VPC network.
   *

   *
   * repeated string subnetworks = 415853125;
   *
   * @return A list containing the subnetworks.
   */
  java.util.List<java.lang.String> getSubnetworksList();
  /**
   *
   *
   *

   * [Output Only] Server-defined fully-qualified URLs for all subnetworks in this VPC network.
   *

   *
   * repeated string subnetworks = 415853125;
   *
   * @return The count of subnetworks.
   */
  int getSubnetworksCount();
  /**
   *
   *
   *

   * [Output Only] Server-defined fully-qualified URLs for all subnetworks in this VPC network.
   *

   *
   * repeated string subnetworks = 415853125;
   *
   * @param index The index of the element to return.
   * @return The subnetworks at the given index.
   */
  java.lang.String getSubnetworks(int index);
  /**
   *
   *
   *

   * [Output Only] Server-defined fully-qualified URLs for all subnetworks in this VPC network.
   *

   *
   * repeated string subnetworks = 415853125;
   *
   * @param index The index of the value to return.
   * @return The bytes of the subnetworks at the given index.
   */
  com.google.protobuf.ByteString getSubnetworksBytes(int index);
}


text:
var path = require('path')
var packagesPath = path.resolve(__dirname,'../packages')
//var nodeModulesPath = path.resolve(__dirname,'../node_modules')
// Place the packages path 1st in main paths
//require.main.paths.unshift(nodeModulesPath)

global.addToNodePath = function(newPath) {
	//console.log(`Adding new node path ${newPath}`)
	require.main.paths.unshift(newPath)

	// Then use this module - probably can remove
	require('app-module-path').addPath(newPath)
	//require('app-module-path').addPath(nodeModulesPath)

	// Then add to env path for forks
	process.env.NODE_PATH += ":" + newPath

}

addToNodePath(packagesPath)

//console.log('Require main paths',require.main.paths)


text:
#pragma once
//====================================================================================
//Meshes.h
//
//This code is part of Anubis Engine.
//
//Anubis Engine is a free game engine created as a fan project to be
//awesome platform for developing games!
//
//All sources can be found here:
//	https://github.com/Dgek/Anubis-Engine
//
//Demos based on Anubis Engine can be found here:
//	https://github.com/Dgek/Demos
//
//Copyright (c) 2013, Muralev Evgeny
//All rights reserved.
//
//Redistribution and use in source and binary forms, with
//or without modification, are permitted provided that the
//following conditions are met:
//
//Redistributions of source code must retain the above copyright notice,
//this list of conditions and the following disclaimer.
//
//Redistributions in binary form must reproduce the above copyright notice,
//this list of conditions and the following disclaimer in the documentation
//and/or other materials provided with the distribution.
//
//Neither the name of the Minotower Games nor the names of its contributors
//may be used to endorse or promote products derived from this software
//without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY MURALEV EVGENY "AS IS"
//AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
//ARE DISCLAIMED. IN NO EVENT SHALL MURALEV EVGENY BE LIABLE
//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//====================================================================================

#include "Final/Resources/Buffers/Buffers.h"
#include "../Other/Material.h"
#include "../Other/ShaderBunch.h"
#include "../../Math/Source/Mat4x4.h"

namespace Anubis
{
	struct NormalData
	{
		float3 normal;
		float3 tangent;
		float3 binormal;
	};

	class Renderer;
	class Mesh
	{
	private:
		Mat4x4			m_objectTransform;
		Mat4x4			m_worldTransform;

	protected:
		//Vertex buffers
		VertexBuffer*	m_pVertices;
		VertexBuffer*	m_pTexCoords;
		VertexBuffer*	m_pNormals;

		Material*		m_pMaterial;

		ShaderBunch*	m_pShaders;

	public:
		//Constructor and destructor
		Mesh();
		~Mesh();

		/**	Initialization **/
		//AVIRTUAL ABOOL VInitialize(ASTRING fileName) = 0;
		AVIRTUAL AVOID VSetMaterial(AWSTRING diffuseFileName, AWSTRING normalFileName,
									AWSTRING specularFileName,AWSTRING heightFileName);
		AVOID SetWorldTransform(const Mat4x4 & transform);
		AINLINE Mat4x4 GetWorldTransform() const { return m_worldTransform; }

		//Shaders
		//AVIRTUAL AVOID VSetVertexShader		(AWSTRING fileName, ASTRING shaderName);
		//AVIRTUAL AVOID VSetHullShader		(AWSTRING fileName, ASTRING shaderName);
		//AVIRTUAL AVOID VSetDomainShader		(AWSTRING fileName, ASTRING shaderName);
		//AVIRTUAL AVOID VSetGeometryShader	(AWSTRING fileName, ASTRING shaderName);
		//AVIRTUAL AVOID VSetPixelShader		(AWSTRING fileName, ASTRING shaderName);

		/** Rendering methods **/
		AVIRTUAL AVOID VPreRender(Renderer *pRenderer, const Mat4x4 & view, const Mat4x4 & viewprojection);		//change pipeline state if needed
		AVIRTUAL AVOID VRender(Renderer * pRenderer);		//render the mesh
		AVIRTUAL AVOID VPostRender(Renderer * pRenderer);			//restore previous pipeline state if needed

		AVOID GenerateShadowMap();
	};

	//useful typedefs
	typedef shared_ptr<Mesh> MeshPtr;
	typedef vector<MeshPtr> Meshes;

	/*struct Subset
	{
		~Subset()
		{
			SAFE_DELETE(m_pVerticesBuffer);
			SAFE_DELETE(m_pTexCoordBuffer);
			SAFE_DELETE(m_pNormalDataBuffer);
			SAFE_DELETE(m_pIndexBuffer);
		}

		VertexBuffer*	m_pVerticesBuffer;
		VertexBuffer*	m_pTexCoordBuffer;
		VertexBuffer*	m_pNormalDataBuffer;
		IndexBuffer*	m_pIndexBuffer;

		std::shared_ptr<Material>	m_pMaterial;
	}; */
	/*class ComplexMesh : public Mesh
	{
	protected:
		Subset*	m_pSubsets;
		AUINT32 m_uNumSubsets;

	public:

		ComplexMesh();
		~ComplexMesh();

		AVOID VPreRender(Renderer *pRenderer, const Mat4x4 & view, const Mat4x4 & viewprojection);		//change pipeline state if needed
		AVOID VRender(Renderer * pRenderer);		//render the mesh
		AVOID VPostRender(Renderer * pRenderer);			//restore previous pipeline state if needed

		AVOID GenerateShadowMap();
	}; */

	class IndexedMesh : public Mesh
	{
		friend class ObjResourceLoader;

	protected:
		IndexBuffer*	m_pIndexBuffer;

	public:
		IndexedMesh() : Mesh()
		{
			m_pIndexBuffer = nullptr;

			//initialize input layout
			INPUT_LAYOUT layout[] =
			{
				{ "POSITION", 0, TEX_R32G32B32_FLOAT, 0, 0,  IA_PER_VERTEX_DATA, 0},
				{ "TEXCOORDS", 0, TEX_R32G32_FLOAT,	  1, 0,  IA_PER_VERTEX_DATA, 0},
				{ "NORMAL",   0, TEX_R32G32B32_FLOAT, 2, 0,  IA_PER_VERTEX_DATA, 0},
				{ "TANGENT", 0, TEX_R32G32B32_FLOAT, 2, 12, IA_PER_VERTEX_DATA, 0},
				{ "BINORMAL",  0, TEX_R32G32B32_FLOAT, 2, 24, IA_PER_VERTEX_DATA, 0},
			};

			//Initialize shaders
			m_pShaders = new ShaderBunch();
			m_pShaders->VSetVertexShader(L"GBufferShader.hlsl", "VS", layout, 5, TOPOLOGY_TRIANGLELIST);
			m_pShaders->VSetPixelShader(L"GBufferShader.hlsl", "PS");
		}
		~IndexedMesh();

		/** Rendering methods **/
		AVOID VPreRender(Renderer *pRenderer, const Mat4x4 & view, const Mat4x4 & viewprojection);		//change pipeline state if needed
		AVOID VRender(Renderer * pRenderer);		//render the mesh

		AVOID GenerateShadowMap();
	};

}; //Anubis


text:
package de.renber.databinding.context;

import org.eclipse.core.databinding.observable.IObservable;
import org.eclipse.core.databinding.observable.value.IObservableValue;

public interface IValueDataContext extends IDataContext {

	public IValueDataContext value(String propertyPath);

	public IListDataContext list(String propertyPath);

	public Object getValue();
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Exception: ISO::IBAN::Invalid

    — Documentation by YARD 0.8.7.3

</title>

  <link rel="stylesheet" href="../../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../../css/common.css" type="text/css" charset="utf-8" />

    Index (I) »
    ISO » IBAN
     »
    Invalid

(no frames)

      Class List

      Method List

      File List

Exception: ISO::IBAN::Invalid

Inherits:

      ArgumentError

Object

ArgumentError

ISO::IBAN::Invalid

        show all

Defined in:

lib/iso/iban/invalid.rb

Overview

Raised by ISO::IBAN::parse!

Instance Attribute Summary (collapse)

      - (Array<Symbol>) errors

      readonly

The errors in the IBAN.

      - (ISO::IBAN) iban

      readonly

The faulty IBAN.

      Instance Method Summary
      (collapse)

      - (Invalid) initialize(iban)

    constructor

A new instance of Invalid.

Constructor Details

    - (<tt>Invalid</tt>) initialize(iban)

Returns a new instance of Invalid

Parameters:

        iban

        (<tt>ISO::IBAN</tt>)

        —

The faulty IBAN.

18
19
20
21
22

# File 'lib/iso/iban/invalid.rb', line 18

def initialize(iban)
  @iban   = iban
  @errors = iban.validate
  super("The IBAN #{@iban.formatted} is invalid (#{@errors.join(', ')})")
end

Instance Attribute Details

    - (<tt>Array<Symbol></tt>) errors  (readonly)

Returns The errors in the IBAN.

Returns:

        (<tt>Array<Symbol></tt>)

        —

The errors in the IBAN.

See Also:

ISO::IBAN#validate

11
12
13

# File 'lib/iso/iban/invalid.rb', line 11

def errors
  @errors
end

    - (<tt>ISO::IBAN</tt>) iban  (readonly)

Returns The faulty IBAN.

Returns:

        (<tt>ISO::IBAN</tt>)

        —

The faulty IBAN.

14
15
16

# File 'lib/iso/iban/invalid.rb', line 14

def iban
  @iban
end

  Generated on Mon Feb 17 23:14:53 2014 by
  yard
  0.8.7.3 (ruby-2.1.0).


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>tbb::blocked_range2d< RowValue, ColValue > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

tbb

blocked_range2d

Public Types |
Public Member Functions |
Static Public Attributes |
List of all members

tbb::blocked_range2d< RowValue, ColValue > Class Template Reference
Algorithms

A 2-dimensional range that models the Range concept.
 More...

#include <blocked_range2d.h>

Public Types

typedef blocked_range< RowValue > 	row_range_type

 	Type for size of an iteration range.

typedef blocked_range< ColValue > 	col_range_type

Public Member Functions

 	blocked_range2d (RowValue row_begin, RowValue row_end, typename row_range_type::size_type row_grainsize, ColValue col_begin, ColValue col_end, typename col_range_type::size_type col_grainsize)

 	blocked_range2d (RowValue row_begin, RowValue row_end, ColValue col_begin, ColValue col_end)

bool 	empty () const

 	True if range is empty.

bool 	is_divisible () const

 	True if range is divisible into two pieces.

 	blocked_range2d (blocked_range2d &r, split)

 	blocked_range2d (blocked_range2d &r, proportional_split &proportion)

template<typename Split >

void 	do_split (blocked_range2d &r, Split &split_obj)

const row_range_type & 	rows () const

 	The rows of the iteration space.

const col_range_type & 	cols () const

 	The columns of the iteration space.

Static Public Attributes

static const bool 	is_splittable_in_proportion = true

 	Static field to support proportional split.

Detailed Description

template<typename RowValue, typename ColValue = RowValue>

class tbb::blocked_range2d< RowValue, ColValue >

A 2-dimensional range that models the Range concept.

The documentation for this class was generated from the following file:

blocked_range2d.h

Copyright © 2005-2015 Intel Corporation.  All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.


text:
#ifndef __CLUSTERINGACCURACY_H__
#define __CLUSTERINGACCURACY_H__

#include <shogun/lib/config.h>

#include <shogun/evaluation/ClusteringEvaluation.h>

namespace shogun
{

/** @brief clustering accuracy
 */
class CClusteringAccuracy: public CClusteringEvaluation
{
public:
	/** constructor */
	CClusteringAccuracy(): CClusteringEvaluation() {}

	/** destructor */
	virtual ~CClusteringAccuracy() {}

	/** evaluate labels
	 * Make sure to call CClusteringEvaluation::best_map to map the predicted label
	 * before calculating accuracy.
	 *
	 * @param predicted labels for evaluating
	 * @param ground_truth labels assumed to be correct
	 * @return evaluation result
	 */
	virtual float64_t evaluate(CLabels* predicted, CLabels* ground_truth);

	/** @return whether criterium has to be maximized or minimized */
	virtual EEvaluationDirection get_evaluation_direction() const
	{
		return ED_MINIMIZE;
	}

	/** Returns the name of the SGSerializable instance.  It MUST BE
	 *  the CLASS NAME without the prefixed `C'.
	 *
	 *  @return name of the SGSerializable
	 */
	virtual const char* get_name() const
	{
		return "ClusteringAccuracy";
	}
};

} // namespace shogun

#endif /* end of include guard: __CLUSTERINGACCURACY_H__ */


text:
namespace NativeJIT
{
    // The DependentNode declares that a prerequisite node must be evaluated
    // before a dependent node can be evaluated. It is useful in scenarios with
    // side effects, f. ex. if a CallNode places an output value into a
    // StackVariableNode, dereferencing of the stack variable must be wrapped
    // into a DependentNode.
    template <typename T>
    class DependentNode : public Node<T>
    {
    public:
        DependentNode(ExpressionTree& tree,
                      Node<T>& dependentNode,
                      NodeBase& prerequisiteNode);

        //
        // Overrides of Node methods.
        //

        virtual Storage<T> CodeGenValue(ExpressionTree& tree) override;
        virtual void Print(std::ostream& out) const override;

    private:
        // WARNING: This class is designed to be allocated by an arena allocator,
        // so its destructor will never be called. Therefore, it should hold no
        // resources other than memory from the arena allocator.
        ~DependentNode();

        Node<T>& m_dependentNode;
        NodeBase& m_prerequisiteNode;
    };

    //*************************************************************************
    //
    // Template definitions for the DependentNode.
    //
    //*************************************************************************

    template <typename T>
    DependentNode<T>::DependentNode(ExpressionTree& tree,
                                    Node<T>& dependentNode,
                                    NodeBase& prerequisiteNode)
        : Node<T>(tree),
          m_dependentNode(dependentNode),
          m_prerequisiteNode(prerequisiteNode)
    {
        m_dependentNode.IncrementParentCount();
        // Note: not increasing parent count on prerequisite node as DependentNode
        // is not using its value but only ensuring that it has been evaluated.
    }

    template <typename T>
    Storage<T>
    DependentNode<T>::CodeGenValue(ExpressionTree& tree)
    {
        if (!m_prerequisiteNode.HasBeenEvaluated())
        {
            m_prerequisiteNode.CodeGenCache(tree);
        }

        return m_dependentNode.CodeGen(tree);
    }

    template <typename T>
    void DependentNode<T>::Print(std::ostream& out) const
    {
        this->PrintCoreProperties(out, "DependentNode");

        out << ", dependent = " << m_dependentNode.GetId();
        out << ", prerequisite = " << m_prerequisiteNode.GetId();
    }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.uiDesigner.propertyInspector.properties;

import com.intellij.uiDesigner.FormEditingUtil;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.propertyInspector.Property;
import com.intellij.uiDesigner.propertyInspector.PropertyEditor;
import com.intellij.uiDesigner.propertyInspector.PropertyRenderer;
import com.intellij.uiDesigner.propertyInspector.editors.BooleanEditor;
import com.intellij.uiDesigner.propertyInspector.renderers.BooleanRenderer;
import com.intellij.uiDesigner.propertyInspector.renderers.SizePolicyRenderer;
import com.intellij.uiDesigner.radComponents.RadComponent;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

/**
 * @author Anton Katilin
 * @author Vladimir Kondratyev
 */
public abstract class SizePolicyProperty extends Property<RadComponent, Integer> {
  private final Property[] myChildren;
  private final SizePolicyRenderer myRenderer;

  public SizePolicyProperty(@NonNls final String name){
    super(null, name);
    myChildren=new Property[]{
      new MyBooleanProperty("Can Shrink", GridConstraints.SIZEPOLICY_CAN_SHRINK),
      new MyBooleanProperty("Can Grow", GridConstraints.SIZEPOLICY_CAN_GROW),
      new MyBooleanProperty("Want Grow", GridConstraints.SIZEPOLICY_WANT_GROW)
    };
    myRenderer=new SizePolicyRenderer();
  }

  protected abstract int getValueImpl(GridConstraints constraints);

  protected abstract void setValueImpl(GridConstraints constraints,int policy);

  @Override
  public final Integer getValue(final RadComponent component) {
    return getValueImpl(component.getConstraints());
  }

  @Override
  protected final void setValueImpl(final RadComponent component, final Integer value) throws Exception {
    setValueImpl(component.getConstraints(), value.intValue());
  }

  @Override
  public final Property @NotNull [] getChildren(final RadComponent component){
    return myChildren;
  }

  @Override
  @NotNull public final PropertyRenderer<Integer> getRenderer(){
    return myRenderer;
  }

  @Override
  public final PropertyEditor<Integer> getEditor(){
    return null;
  }

  @Override public boolean isModified(final RadComponent component) {
    final GridConstraints defaultConstraints = FormEditingUtil.getDefaultConstraints(component);
    return getValueImpl(component.getConstraints()) != getValueImpl(defaultConstraints);
  }

  @Override public void resetValue(RadComponent component) throws Exception {
    setValueImpl(component, getValueImpl(FormEditingUtil.getDefaultConstraints(component)));
  }

  /**
   * Subproperty for "can shrink" bit
   */
  private class MyBooleanProperty extends Property<RadComponent, Boolean> {
    private final BooleanRenderer myRenderer;
    private final BooleanEditor myEditor;
    private final int myPropertyMask;

    MyBooleanProperty(@NonNls final String name, final int propertyMask) {
      super(SizePolicyProperty.this, name);
      myPropertyMask = propertyMask;
      myRenderer=new BooleanRenderer();
      myEditor=new BooleanEditor();
    }

    @Override
    public final Boolean getValue(final RadComponent component) {
      final GridConstraints constraints=component.getConstraints();
      return (getValueImpl(constraints) & myPropertyMask) != 0;
    }

    @Override
    protected final void setValueImpl(final RadComponent component, final Boolean value) throws Exception{
      final boolean canShrink=value.booleanValue();
      int newValue=getValueImpl(component.getConstraints());
      if(canShrink){
        newValue|=myPropertyMask;
      }else{
        newValue&=~myPropertyMask;
      }
      SizePolicyProperty.this.setValueImpl(component.getConstraints(),newValue);
    }

    @Override
    @NotNull
    public final PropertyRenderer<Boolean> getRenderer(){
      return myRenderer;
    }

    @Override
    public final PropertyEditor<Boolean> getEditor(){
      return myEditor;
    }
  }
}


text:
void outputHex(unsigned char *p, unsigned int n);

#endif


text:
@class NSObject<OS_dispatch_queue>, NSPredicate, NSRunLoop, NSString, NSTimer, XCTNSPredicateExpectation;

@interface _XCTNSPredicateExpectationImplementation : NSObject
{
    XCTNSPredicateExpectation *_expectation;
    id <XCTNSPredicateExpectationObject> _object;
    NSPredicate *_predicate;
    CDUnknownBlockType _handler;
    NSRunLoop *_timerRunLoop;
    NSTimer *_timer;
    double _pollingInterval;
    NSString *_debugDescription;
    NSObject<OS_dispatch_queue> *_queue;
    _Bool _hasCleanedUp;
    _Bool _isEvaluating;
}

@property double pollingInterval; // @synthesize pollingInterval=_pollingInterval;
@property(copy) NSString *debugDescription; // @synthesize debugDescription=_debugDescription;
@property(readonly, copy) NSPredicate *predicate; // @synthesize predicate=_predicate;
@property(readonly) id <XCTNSPredicateExpectationObject> object; // @synthesize object=_object;
- (void)cleanup;
- (_Bool)_shouldFulfillForExpectation:(id)arg1 object:(id)arg2 handler:(CDUnknownBlockType)arg3;
- (void)_considerFulfilling;
@property(copy) CDUnknownBlockType handler;
- (void)_scheduleTimer;
- (void)startPolling;
- (id)initWithPredicate:(id)arg1 object:(id)arg2 expectation:(id)arg3;
- (void)dealloc;

@end


text:
package org.mifos.accounts.financial.business.service.activity;

import java.util.ArrayList;
import java.util.List;

import org.mifos.accounts.business.AccountTrxnEntity;
import org.mifos.accounts.financial.business.service.activity.accountingentry.BaseAccountingEntry;
import org.mifos.accounts.financial.business.service.activity.accountingentry.FeesAccountingEntry;
import org.mifos.accounts.financial.business.service.activity.accountingentry.InterestAccountingEntry;
import org.mifos.accounts.financial.business.service.activity.accountingentry.PenaltyAccountingEntry;
import org.mifos.accounts.financial.business.service.activity.accountingentry.PrincipalAccountingEntry;

public class LoanRepaymentFinancialActivity extends BaseFinancialActivity {
    public LoanRepaymentFinancialActivity(AccountTrxnEntity accountTrxn) {
        super(accountTrxn);
    }

    @Override
    protected List<BaseAccountingEntry> getFinancialActionEntry() {
        List<BaseAccountingEntry> financialActionEntryList = new ArrayList<BaseAccountingEntry>();
        financialActionEntryList.add(new PrincipalAccountingEntry());
        financialActionEntryList.add(new InterestAccountingEntry());
        financialActionEntryList.add(new FeesAccountingEntry());
        financialActionEntryList.add(new PenaltyAccountingEntry());

        return financialActionEntryList;
    }

}


text:
namespace OpenALRF
{
   class IAutoPilot : public IModule
   {
   public:
   };
}


text:
package com.shaubert.network.service;

public class VoidResponse extends Response {
    private static final VoidResponse INSTANCE = new VoidResponse();

    public static VoidResponse get() {
        return INSTANCE;
    }

    private VoidResponse() {
        super(null);
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>渲染 jsx</title>


text:
Simple Document Store
=====================

This example shows a simple document store with a RESTful interface.

Documents are stored in the JSON format. The API is similar to the [CouchDB API](http://wiki.apache.org/couchdb/HTTP_Document_API) (but does not support databases).

API
---

        Method
        URL
        Description
        Example

        GET
        /
        List all documents
        curl -X GET http://simple-document-store/

        GET
        /:id
        Read a document with the ID :id
        curl -X GET http://simple-document-store/6e1295ed6c29495e54cc05947f18c8af

        PUT
        /:id
        Create/Update a document with the ID :id
        curl -X PUT http://simple-document-store/6e1295ed6c29495e54cc05947f18c8af -d '{"title":"There is Nothing Left to Lose","artist":"Foo Fighters"}'

        POST
        /
        Create a document with an auto-generated ID
        curl -X POST http://localhost -d '{"title":"There is Nothing Left to Lose","artist":"Foo Fighters"}'

        DELETE
        /:id
        Delete a document with the ID :id
        curl -X DELETE http://simple-document-store/6e1295ed6c29495e54cc05947f18c8af

Open [client.html](./client.html) for a simple HTML/JavaScript client.

Notes
------------

1. The ./data directory should be writeable from PHP, either by setting relevant permissions or changing the directories' ownership to the user under which HTTP requests are served. For example:

        sudo chown -R www-data:www-data ./data

2. Ensure that your Apache configuration allows the .htaccess to be executed (i.e. by setting `AllowOverride` to `All`) and has [mod_rewrite](http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html) enabled.


text:
@implementation LYXTabBarViewModel

@end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Framework.AI
{
    public class Parallel : CompositeNode<Parallel>
    {
        public override string Name
        {
            get { return "Parallel"; }
        }

        public override string Description
        {
            get { return "Executes children in parallel"; }
        }

        protected override NodeResult OnUpdate()
        {
            throw new System.NotImplementedException();
        }
    }
}


text:
package org.assertj.core.error;

import static java.lang.String.format;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.error.ShouldBeInSameSecondWindow.shouldBeInSameSecondWindow;
import static org.assertj.core.util.DateUtil.parseDatetimeWithMs;

import org.assertj.core.description.TextDescription;
import org.assertj.core.presentation.StandardRepresentation;
import org.junit.jupiter.api.Test;

/**
 * Tests for
 * <code>{@link ShouldBeInSameSecondWindow#create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation)}</code>
 * .
 *
 * @author Joel Costigliola
 * @author Mikhail Mazursky
 */
class ShouldBeInSameSecondWindow_create_Test {

  @Test
  void should_create_error_message() {
    // GIVEN
    ErrorMessageFactory factory = shouldBeInSameSecondWindow(parseDatetimeWithMs("2011-01-01T05:00:01.000"),
                                                             parseDatetimeWithMs("2011-01-01T05:00:02.001"));
    // WHEN
    String message = factory.create(new TextDescription("Test"), new StandardRepresentation());
    // THEN
    then(message).isEqualTo(format("[Test] %n" +
                                   "Expecting actual:%n" +
                                   "  2011-01-01T05:00:01.000 (java.util.Date)%n" +
                                   "to be close to:%n" +
                                   "  2011-01-01T05:00:02.001 (java.util.Date)%n" +
                                   "by less than one second (strictly) but difference was: 1s and 1ms"));
  }

}


text:
package org.squiddev.cctweaks.core.utils;

import com.google.common.base.CaseFormat;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.shared.computer.blocks.TileComputerBase;
import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.computer.core.ServerComputer;
import dan200.computercraft.shared.util.IDAssigner;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.squiddev.cctweaks.CCTweaks;

import javax.annotation.Nullable;
import java.io.File;

/**
 * Helper methods for various things
 */
public class Helpers {
	/**
	 * Translate any variant of a string
	 *
	 * @param strings The strings to try to translate
	 * @return The first translateable string
	 */
	public static String translateAny(String... strings) {
		return translateOrDefault(strings[strings.length - 1], strings);
	}

	/**
	 * Translate any variant of a string
	 *
	 * @param def     The fallback string
	 * @param strings The strings to try to translate
	 * @return The first translateable string or the default
	 */
	@SuppressWarnings("deprecation")
	public static String translateOrDefault(String def, String... strings) {
		for (String string : strings) {
			if (net.minecraft.util.text.translation.I18n.canTranslate(string)) {
				return net.minecraft.util.text.translation.I18n.translateToLocal(string);
			}
		}

		return def;
	}

	@SuppressWarnings("deprecation")
	public static String translateToLocal(String str) {
		return net.minecraft.util.text.translation.I18n.translateToLocal(str);
	}

	public static void twoWayCrafting(ItemStack a, ItemStack b) {
		GameRegistry.addShapelessRecipe(a, b);
		GameRegistry.addShapelessRecipe(b, a);
	}

	/**
	 * Add a series of crafting recipes with positions swapped.
	 *
	 * @param output The output stack
	 * @param a      The first item to swap
	 * @param b      The second item to swap
	 * @param args   Args as passed to {@link GameRegistry#addRecipe(net.minecraft.item.crafting.IRecipe)}
	 */
	public static void alternateCrafting(ItemStack output, char a, char b, Object... args) {
		GameRegistry.addRecipe(output, args);

		if (args[0] instanceof String[]) {
			String[] inputs = (String[]) args[0];

			for (int i = 0; i < inputs.length; i++) {
				inputs[i] = swapCharacters(inputs[i], a, b);
			}
		} else {
			int i = 0;
			while (args[i] instanceof String) {
				args[i] = swapCharacters((String) args[i], a, b);
				++i;
			}
		}

		GameRegistry.addRecipe(output, args);
	}

	/**
	 * Swap two characters in a string
	 *
	 * @param word The string to swap
	 * @param a    First character
	 * @param b    Second character
	 * @return Swapped string
	 */
	public static String swapCharacters(String word, char a, char b) {
		StringBuilder builder = new StringBuilder(word.length());

		for (int i = 0; i < word.length(); i++) {
			char c = word.charAt(i);
			if (c == a) {
				c = b;
			} else if (c == b) {
				c = a;
			}
			builder.append(c);
		}
		return builder.toString();
	}

	public static int nextId(World world, String type) {
		return IDAssigner.getNextIDFromFile(new File(ComputerCraft.getWorldDir(world), "computer/lastid_" + type + ".txt"));
	}

	public static int nextId(World world, IPeripheral peripheral) {
		return nextId(world, peripheral.getType());
	}

	public static boolean equals(Object a, Object b) {
		return a == b || (a != null && a.equals(b));
	}

	public static String snakeCase(String name) {
		return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
	}

	@SideOnly(Side.CLIENT)
	public static void setupModel(Item item, int damage, String name) {
		name = CCTweaks.ID + ":" + snakeCase(name);

		ModelResourceLocation res = new ModelResourceLocation(name, "inventory");
		ModelLoader.setCustomModelResourceLocation(item, damage, res);
	}

	@Nullable
	public static TileComputerBase getTile(ServerComputer computer) {
		World world = computer.getWorld();
		BlockPos pos = computer.getPosition();

		if (world != null && pos != null && world.isBlockLoaded(pos)) {
			TileEntity te = world.getTileEntity(pos);
			if (te instanceof TileComputerBase && ((TileComputerBase) te).getServerComputer() == computer) {
				return ((TileComputerBase) te);
			}
		}

		return null;
	}

	public static ComputerFamily guessFamily(ServerComputer computer) {
		TileComputerBase tile = getTile(computer);
		if (tile != null) return tile.getFamily();

		return computer.isColour() ? ComputerFamily.Advanced : ComputerFamily.Normal;
	}
}


text:
Scavenger
=========

Scavenger works with the Shodan API & Exploit-db to make vulnerability research easier.
	Note: you will need to spend $19.99 to buy a Shodan API key @ www.shodanhq.com
09-24-2013
 Starting to lay ground work for SQL database to store queries.

10-23-2013
+ Created a separate file for Exploit-DB searches.
+ Added more documentation


text:
class DropSpreeStoreCreditUpdateReasons < ActiveRecord::Migration[5.1]
  # This migration should run in a subsequent deploy after 20180710170104
  # has been already deployed. See also migration 20180710170104.

  # We can't add back the table in a `down` method here: a previous version
  # of migration 20180710170104 would fail with `table already exists` , as
  # it handles itself the add/remove of this table and column.
  def up
    if table_exists? :spree_store_credit_update_reasons
      drop_table :spree_store_credit_update_reasons
    end

    if column_exists? :spree_store_credit_events, :update_reason_id
      remove_column :spree_store_credit_events, :update_reason_id
    end
  end
end


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Septosporium xylostomum Bat.

### Remarks
null


text:
<?php
namespace Acelaya\Files;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Stdlib\AbstractOptions;

/**
 * Class Options
 * @author Alejandro Celaya Alastrué
 * @link http://www.wonnova.com
 */
class FilesOptions extends AbstractOptions
{
    /**
     * @var string
     */
    protected $basePath = '';
    /**
     * @var string
     */
    protected $maxSize = '1536MB';

    public function __construct(array $options = [])
    {
        $this->basePath = __DIR__ . '/../files';
        parent::__construct($options);
    }

    /**
     * @return string
     */
    public function getBasePath()
    {
        return $this->basePath;
    }

    /**
     * @param string $basePath
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function setBasePath($basePath)
    {
        if (! is_dir($basePath)) {
            throw new \InvalidArgumentException('Provided base path is not a valid directory');
        }
        $this->basePath = realpath($basePath);
        return $this;
    }

    /**
     * @return string
     */
    public function getMaxSize()
    {
        return $this->maxSize;
    }

    /**
     * @param string $maxSize
     * @return $this
     */
    public function setMaxSize($maxSize)
    {
        $this->maxSize = $maxSize;
        return $this;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace BoldTween.UI
{
	[Serializable]
	public struct EdgePadding
	{
		public float @in, @out;

		public EdgePadding ( float @in, float @out )
		{
			this.@in = @in;
			this.@out = @out;
		}
	}

	public enum Edge
	{
		None = 0,
		Left = 1,
		Right = 2,
		Top = 3,
		Bottom = 4
	}

	public class UIEdgeInterpolator : RectTransformInterpolator
	{
		[SerializeField]
		private bool invert;

		[SerializeField]
		private Edge edge;

		public Edge Edge
		{
			get
			{
				return edge;
			}

			set
			{
				edge = value;

				Sync();
			}
		}

		[SerializeField]
		private EdgePadding padding;

		public EdgePadding Padding
		{
			get
			{
				return padding;
			}

			set
			{
				padding = value;

				Sync();
			}
		}

#if UNITY_EDITOR
		[SerializeField]
		[HideInInspector]
		private Edge activeEdge;

		protected override void OnValidate ()
		{
			if ( activeEdge == Edge.None )
			{
				activeEdge = edge;

				switch ( edge )
				{
				case Edge.Left:
					position = target.pivot.x;
					break;
				case Edge.Right:
					position = 1.0f - target.pivot.x;
					break;
				case Edge.Top:
					position = target.pivot.y;
					break;
				case Edge.Bottom:
					position = 1.0f - target.pivot.y;
					break;
				}
			}

			base.OnValidate();
		}
#endif

		protected override void OnInterpolate ( RectTransform rect, float t )
		{
			tracker.Clear();

			if ( edge == Edge.None )
			{
				return;
			}

			if ( invert )
			{
				t = 1.0f - t;
			}

			float pad = OverLerp( -padding.@out, padding.@in, t );

			if ( edge < Edge.Top )
			{
				tracker.Add( this, rect, DrivenTransformProperties.PivotX );
				tracker.Add( this, rect, DrivenTransformProperties.AnchorMinX );
				tracker.Add( this, rect, DrivenTransformProperties.AnchorMaxX );
				tracker.Add( this, rect, DrivenTransformProperties.AnchoredPositionX );
			}
			else
			{
				tracker.Add( this, rect, DrivenTransformProperties.PivotY );
				tracker.Add( this, rect, DrivenTransformProperties.AnchorMinY );
				tracker.Add( this, rect, DrivenTransformProperties.AnchorMaxY );
				tracker.Add( this, rect, DrivenTransformProperties.AnchoredPositionY );
			}

			switch ( edge )
			{
			case Edge.Left:

				rect.pivot = OverLerp( new Vector2( 1.0f, rect.pivot.y ), new Vector2( 0.0f, rect.pivot.y ), t );
				rect.anchorMin = new Vector2( 0.0f, rect.anchorMin.y );
				rect.anchorMax = new Vector2( 0.0f, rect.anchorMax.y );
				rect.anchoredPosition = new Vector2( pad, rect.anchoredPosition.y );
				break;

			case Edge.Right:

				rect.pivot = OverLerp( new Vector2( 0.0f, rect.pivot.y ), new Vector2( 1.0f, rect.pivot.y ), t );
				rect.anchorMin = new Vector2( 1.0f, rect.anchorMin.y );
				rect.anchorMax = new Vector2( 1.0f, rect.anchorMax.y );
				rect.anchoredPosition = new Vector2( -pad, rect.anchoredPosition.y );
				break;

			case Edge.Top:

				rect.pivot = OverLerp( new Vector2( rect.pivot.x, 0.0f ), new Vector2( rect.pivot.x, 1.0f ), t );
				rect.anchorMin = new Vector2( rect.anchorMin.x, 1.0f );
				rect.anchorMax = new Vector2( rect.anchorMax.x, 1.0f );
				rect.anchoredPosition = new Vector2( rect.anchoredPosition.x, -pad );
				break;

			case Edge.Bottom:

				rect.pivot = OverLerp( new Vector2( rect.pivot.x, 1.0f ), new Vector2( rect.pivot.x, 0.0f ), t );
				rect.anchorMin = new Vector2( rect.anchorMin.x, 0.0f );
				rect.anchorMax = new Vector2( rect.anchorMax.x, 0.0f );
				rect.anchoredPosition = new Vector2( rect.anchoredPosition.x, pad );
				break;
			}
		}

		private float OverLerp ( float a, float b, float t )
		{
			if ( t == 0.0f )
			{
				return a;
			}

			if ( t == 1.0f )
			{
				return b;
			}

			return a += (b - a) * t;
		}

		private Vector2 OverLerp ( Vector2 a, Vector2 b, float t )
		{
			if ( t == 0.0f )
			{
				return a;
			}

			if ( t == 1.0f )
			{
				return b;
			}

			return a += (b - a) * t;
		}
	}
}