text:
package com.android.tools.layoutlib.create;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

/**
 * Class that generates a new JAR from a list of classes, some of which are to be kept as-is
 * and some of which are to be stubbed partially or totally.
 */
public class AsmGenerator {

    /** Output logger. */
    private final Log mLog;
    /** The path of the destination JAR to create. */
    private final String mOsDestJar;
    /** List of classes to inject in the final JAR from _this_ archive. */
    private final Class<?>[] mInjectClasses;
    /** The set of methods to stub out. */
    private final Set<String> mStubMethods;
    /** All classes to output as-is, except if they have native methods. */
    private Map<String, ClassReader> mKeep;
    /** All dependencies that must be completely stubbed. */
    private Map<String, ClassReader> mDeps;
    /** All files that are to be copied as-is. */
    private Map<String, InputStream> mCopyFiles;
    /** All classes where certain method calls need to be rewritten. */
    private Set<String> mReplaceMethodCallsClasses;
    /** Counter of number of classes renamed during transform. */
    private int mRenameCount;
    /** FQCN Names of the classes to rename: map old-FQCN => new-FQCN */
    private final HashMap<String, String> mRenameClasses;
    /** FQCN Names of "old" classes that were NOT renamed. This starts with the full list of
     *  old-FQCN to rename and they get erased as they get renamed. At the end, classes still
     *  left here are not in the code base anymore and thus were not renamed. */
    private HashSet<String> mClassesNotRenamed;
    /** A map { FQCN => set { list of return types to delete from the FQCN } }. */
    private HashMap<String, Set<String>> mDeleteReturns;
    /** A map { FQCN => set { method names } } of methods to rewrite as delegates.
     *  The special name {@link DelegateClassAdapter#ALL_NATIVES} can be used as in internal set. */
    private final HashMap<String, Set<String>> mDelegateMethods;
    /** FQCN Names of classes to refactor. All reference to old-FQCN will be updated to new-FQCN.
     * map old-FQCN => new-FQCN */
    private final HashMap<String, String> mRefactorClasses;
    /** Methods to inject. FQCN of class in which method should be injected => runnable that does
     * the injection. */
    private final Map<String, ICreateInfo.InjectMethodRunnable> mInjectedMethodsMap;
    /** A map { FQCN => set { field names } } which should be promoted to public visibility */
    private final Map<String, Set<String>> mPromotedFields;

    /**
     * Creates a new generator that can generate the output JAR with the stubbed classes.
     *
     * @param log Output logger.
     * @param osDestJar The path of the destination JAR to create.
     * @param createInfo Creation parameters. Must not be null.
     */
    public AsmGenerator(Log log, String osDestJar, ICreateInfo createInfo) {
        mLog = log;
        mOsDestJar = osDestJar;
        ArrayList<Class<?>> injectedClasses =
                new ArrayList<Class<?>>(Arrays.asList(createInfo.getInjectedClasses()));
        // Search for and add anonymous inner classes also.
        ListIterator<Class<?>> iter = injectedClasses.listIterator();
        while (iter.hasNext()) {
            Class<?> clazz = iter.next();
            try {
                int i = 1;
                while(i < 100) {
                    iter.add(Class.forName(clazz.getName() + "$" + i));
                    i++;
                }
            } catch (ClassNotFoundException ignored) {
                // Expected.
            }
        }
        mInjectClasses = injectedClasses.toArray(new Class<?>[0]);
        mStubMethods = new HashSet<String>(Arrays.asList(createInfo.getOverriddenMethods()));

        // Create the map/set of methods to change to delegates
        mDelegateMethods = new HashMap<String, Set<String>>();
        addToMap(createInfo.getDelegateMethods(), mDelegateMethods);

        for (String className : createInfo.getDelegateClassNatives()) {
            className = binaryToInternalClassName(className);
            Set<String> methods = mDelegateMethods.get(className);
            if (methods == null) {
                methods = new HashSet<String>();
                mDelegateMethods.put(className, methods);
            }
            methods.add(DelegateClassAdapter.ALL_NATIVES);
        }

        // Create the map of classes to rename.
        mRenameClasses = new HashMap<String, String>();
        mClassesNotRenamed = new HashSet<String>();
        String[] renameClasses = createInfo.getRenamedClasses();
        int n = renameClasses.length;
        for (int i = 0; i < n; i += 2) {
            assert i + 1 < n;
            // The ASM class names uses "/" separators, whereas regular FQCN use "."
            String oldFqcn = binaryToInternalClassName(renameClasses[i]);
            String newFqcn = binaryToInternalClassName(renameClasses[i + 1]);
            mRenameClasses.put(oldFqcn, newFqcn);
            mClassesNotRenamed.add(oldFqcn);
        }

        // Create a map of classes to be refactored.
        mRefactorClasses = new HashMap<String, String>();
        String[] refactorClasses = createInfo.getJavaPkgClasses();
        n = refactorClasses.length;
        for (int i = 0; i < n; i += 2) {
            assert i + 1 < n;
            String oldFqcn = binaryToInternalClassName(refactorClasses[i]);
            String newFqcn = binaryToInternalClassName(refactorClasses[i + 1]);
            mRefactorClasses.put(oldFqcn, newFqcn);
        }

        // create the map of renamed class -> return type of method to delete.
        mDeleteReturns = new HashMap<String, Set<String>>();
        String[] deleteReturns = createInfo.getDeleteReturns();
        Set<String> returnTypes = null;
        String renamedClass = null;
        for (String className : deleteReturns) {
            // if we reach the end of a section, add it to the main map
            if (className == null) {
                if (returnTypes != null) {
                    mDeleteReturns.put(renamedClass, returnTypes);
                }

                renamedClass = null;
                continue;
            }

            // if the renamed class is null, this is the beginning of a section
            if (renamedClass == null) {
                renamedClass = binaryToInternalClassName(className);
                continue;
            }

            // just a standard return type, we add it to the list.
            if (returnTypes == null) {
                returnTypes = new HashSet<String>();
            }
            returnTypes.add(binaryToInternalClassName(className));
        }

        mPromotedFields = new HashMap<String, Set<String>>();
        addToMap(createInfo.getPromotedFields(), mPromotedFields);

        mInjectedMethodsMap = createInfo.getInjectedMethodsMap();
    }

    /**
     * For each value in the array, split the value on '#' and add the parts to the map as key
     * and value.
     */
    private void addToMap(String[] entries, Map<String, Set<String>> map) {
        for (String entry : entries) {
            int pos = entry.indexOf('#');
            if (pos <= 0 || pos >= entry.length() - 1) {
                return;
            }
            String className = binaryToInternalClassName(entry.substring(0, pos));
            String methodOrFieldName = entry.substring(pos + 1);
            Set<String> set = map.get(className);
            if (set == null) {
                set = new HashSet<String>();
                map.put(className, set);
            }
            set.add(methodOrFieldName);
        }
    }

    /**
     * Returns the list of classes that have not been renamed yet.
     *

     * The names are "internal class names" rather than FQCN, i.e. they use "/" instead "."
     * as package separators.
     */
    public Set<String> getClassesNotRenamed() {
        return mClassesNotRenamed;
    }

    /**
     * Utility that returns the internal ASM class name from a fully qualified binary class
     * name. E.g. it returns android/view/View from android.view.View.
     */
    String binaryToInternalClassName(String className) {
        if (className == null) {
            return null;
        } else {
            return className.replace('.', '/');
        }
    }

    /** Sets the map of classes to output as-is, except if they have native methods */
    public void setKeep(Map<String, ClassReader> keep) {
        mKeep = keep;
    }

    /** Sets the map of dependencies that must be completely stubbed */
    public void setDeps(Map<String, ClassReader> deps) {
        mDeps = deps;
    }

    /** Sets the map of files to output as-is. */
    public void setCopyFiles(Map<String, InputStream> copyFiles) {
        mCopyFiles = copyFiles;
    }

    public void setRewriteMethodCallClasses(Set<String> rewriteMethodCallClasses) {
        mReplaceMethodCallsClasses = rewriteMethodCallClasses;
    }

    /** Generates the final JAR */
    public void generate() throws IOException {
        TreeMap<String, byte[]> all = new TreeMap<String, byte[]>();

        for (Class<?> clazz : mInjectClasses) {
            String name = classToEntryPath(clazz);
            InputStream is = ClassLoader.getSystemResourceAsStream(name);
            ClassReader cr = new ClassReader(is);
            byte[] b = transform(cr, true);
            name = classNameToEntryPath(transformName(cr.getClassName()));
            all.put(name, b);
        }

        for (Entry<String, ClassReader> entry : mDeps.entrySet()) {
            ClassReader cr = entry.getValue();
            byte[] b = transform(cr, true);
            String name = classNameToEntryPath(transformName(cr.getClassName()));
            all.put(name, b);
        }

        for (Entry<String, ClassReader> entry : mKeep.entrySet()) {
            ClassReader cr = entry.getValue();
            byte[] b = transform(cr, true);
            String name = classNameToEntryPath(transformName(cr.getClassName()));
            all.put(name, b);
        }

        for (Entry<String, InputStream> entry : mCopyFiles.entrySet()) {
            try {
                byte[] b = inputStreamToByteArray(entry.getValue());
                all.put(entry.getKey(), b);
            } catch (IOException e) {
                // Ignore.
            }

        }
        mLog.info("# deps classes: %d", mDeps.size());
        mLog.info("# keep classes: %d", mKeep.size());
        mLog.info("# renamed     : %d", mRenameCount);

        createJar(new FileOutputStream(mOsDestJar), all);
        mLog.info("Created JAR file %s", mOsDestJar);
    }

    /**
     * Writes the JAR file.
     *
     * @param outStream The file output stream were to write the JAR.
     * @param all The map of all classes to output.
     * @throws IOException if an I/O error has occurred
     */
    void createJar(FileOutputStream outStream, Map<String,byte[]> all) throws IOException {
        JarOutputStream jar = new JarOutputStream(outStream);
        for (Entry<String, byte[]> entry : all.entrySet()) {
            String name = entry.getKey();
            JarEntry jar_entry = new JarEntry(name);
            jar.putNextEntry(jar_entry);
            jar.write(entry.getValue());
            jar.closeEntry();
        }
        jar.flush();
        jar.close();
    }

    /**
     * Utility method that converts a fully qualified java name into a JAR entry path
     * e.g. for the input "android.view.View" it returns "android/view/View.class"
     */
    String classNameToEntryPath(String className) {
        return className.replaceAll("\\.", "/").concat(".class");
    }

    /**
     * Utility method to get the JAR entry path from a Class name.
     * e.g. it returns something like "com/foo/OuterClass$InnerClass1$InnerClass2.class"
     */
    private String classToEntryPath(Class<?> clazz) {
        return classNameToEntryPath(clazz.getName());
    }

    /**
     * Transforms a class.
     *

     * There are 3 kind of transformations:
     *
     * 1- For "mock" dependencies classes, we want to remove all code from methods and replace
     * by a stub. Native methods must be implemented with this stub too. Abstract methods are
     * left intact. Modified classes must be overridable (non-private, non-final).
     * Native methods must be made non-final, non-private.
     *
     * 2- For "keep" classes, we want to rewrite all native methods as indicated above.
     * If a class has native methods, it must also be made non-private, non-final.
     *
     * Note that unfortunately static methods cannot be changed to non-static (since static and
     * non-static are invoked differently.)
     */
    byte[] transform(ClassReader cr, boolean stubNativesOnly) {

        boolean hasNativeMethods = hasNativeMethods(cr);

        // Get the class name, as an internal name (e.g. com/android/SomeClass$InnerClass)
        String className = cr.getClassName();

        String newName = transformName(className);
        // transformName returns its input argument if there's no need to rename the class
        if (!newName.equals(className)) {
            mRenameCount++;
            // This class is being renamed, so remove it from the list of classes not renamed.
            mClassesNotRenamed.remove(className);
        }

        mLog.debug("Transform %s%s%s%s", className,
                newName.equals(className) ? "" : " (renamed to " + newName + ")",
                hasNativeMethods ? " -- has natives" : "",
                stubNativesOnly ? " -- stub natives only" : "");

        // Rewrite the new class from scratch, without reusing the constant pool from the
        // original class reader.
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);

        ClassVisitor cv = cw;

        if (mReplaceMethodCallsClasses.contains(className)) {
            cv = new ReplaceMethodCallsAdapter(cv, className);
        }

        cv = new RefactorClassAdapter(cv, mRefactorClasses);
        if (!newName.equals(className)) {
            cv = new RenameClassAdapter(cv, className, newName);
        }

        String binaryNewName = newName.replace('/', '.');
        if (mInjectedMethodsMap.keySet().contains(binaryNewName)) {
            cv = new InjectMethodsAdapter(cv, mInjectedMethodsMap.get(binaryNewName));
        }
        cv = new TransformClassAdapter(mLog, mStubMethods, mDeleteReturns.get(className),
                newName, cv, stubNativesOnly);

        Set<String> delegateMethods = mDelegateMethods.get(className);
        if (delegateMethods != null && !delegateMethods.isEmpty()) {
            // If delegateMethods only contains one entry ALL_NATIVES and the class is
            // known to have no native methods, just skip this step.
            if (hasNativeMethods ||
                    !(delegateMethods.size() == 1 &&
                            delegateMethods.contains(DelegateClassAdapter.ALL_NATIVES))) {
                cv = new DelegateClassAdapter(mLog, cv, className, delegateMethods);
            }
        }

        Set<String> promoteFields = mPromotedFields.get(className);
        if (promoteFields != null && !promoteFields.isEmpty()) {
            cv = new PromoteFieldClassAdapter(cv, promoteFields);
        }
        cr.accept(cv, 0);
        return cw.toByteArray();
    }

    /**
     * Should this class be renamed, this returns the new name. Otherwise it returns the
     * original name.
     *
     * @param className The internal ASM name of the class that may have to be renamed
     * @return A new transformed name or the original input argument.
     */
    String transformName(String className) {
        String newName = mRenameClasses.get(className);
        if (newName != null) {
            return newName;
        }
        int pos = className.indexOf('$');
        if (pos > 0) {
            // Is this an inner class of a renamed class?
            String base = className.substring(0, pos);
            newName = mRenameClasses.get(base);
            if (newName != null) {
                return newName + className.substring(pos);
            }
        }

        return className;
    }

    /**
     * Returns true if a class has any native methods.
     */
    boolean hasNativeMethods(ClassReader cr) {
        ClassHasNativeVisitor cv = new ClassHasNativeVisitor();
        cr.accept(cv, 0);
        return cv.hasNativeMethods();
    }

    private byte[] inputStreamToByteArray(InputStream is) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[8192];  // 8KB
        int n;
        while ((n = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, n);
        }
        return buffer.toByteArray();
    }
}


text:
import * as Styled from '../styles';

import { FormFieldCost } from '~client/components/form-field';
import { FormFieldNumberInline } from '~client/components/form-field/number';
import { PlanningTaxRateInput, PlanningTaxThresholdInput } from '~client/types/gql';

export type PropsRateForm = {
  label: string;
  name: string;
  rate: PlanningTaxRateInput | undefined;
  setRate: (name: string, value?: number) => void;
};

export const RateForm: React.FC<PropsRateForm> = ({ label, name, rate, setRate }) => (
  <Styled.RatesForm>
    <Styled.RatesLabel>{label}</Styled.RatesLabel>
    <Styled.RatesValue>
      <FormFieldNumberInline
        value={rate ? rate.value * 100 : undefined}
        onChange={(value = 0): void => setRate(name, value / 100)}
        min={0}
        max={100}
      />
      %
    </Styled.RatesValue>
  </Styled.RatesForm>
);

export type PropsThresholdForm = Pick<PropsRateForm, 'label' | 'name'> & {
  threshold: PlanningTaxThresholdInput | undefined;
  setThreshold: (name: string, value?: number) => void;
};

export const ThresholdForm: React.FC<PropsThresholdForm> = ({
  label,
  name,
  threshold,
  setThreshold,
}) => (
  <Styled.RatesForm>
    <Styled.RatesLabel>{label}</Styled.RatesLabel>
    <Styled.ThresholdsValue>
      <FormFieldCost
        value={threshold?.value ?? 0}
        onChange={(value): void => setThreshold(name, value)}
      />
    </Styled.ThresholdsValue>
  </Styled.RatesForm>
);

redpajama_set_name: RedPajamaGithub


text:
namespace WCFService
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("_OrderItem")]
    public partial class C_OrderItem
    {
        public int id { get; set; }

        public int? orderId { get; set; }

        public int? productId { get; set; }

        public virtual C_Order C_Order { get; set; }

        public virtual C_Product C_Product { get; set; }
    }
}


text:
import asyncio
from pathlib import PurePosixPath
import re

from . import cache
from .error import PrintableError
from . import glob

class Rule:
    def __init__(self, name, copy, move, executable, drop, pick, export):
        self.name = name
        self.copy = copy
        self.move = move
        self.executable = executable
        self.drop = drop
        self.pick = pick
        self.export = export

    def _cache_key(self, input_tree):
        return cache.compute_key({
            'input_tree': input_tree,
            'copy': self.copy,
            'move': self.move,
            'executable': self.executable,
            'drop': self.drop,
            'pick': self.pick,
            'export': self.export,
        })

    @asyncio.coroutine
    def get_tree(self, runtime, input_tree):
        key = self._cache_key(input_tree)

        # As with Module, take a lock on the cache key to avoid running the
        # same rule (or identical rules) twice with the same input.
        cache_lock = runtime.cache_key_locks[key]
        with (yield from cache_lock):
            if key in runtime.cache.keyval:
                return runtime.cache.keyval[key]

            tree = input_tree
            if self.copy:
                tree = yield from copy_files(runtime.cache, tree, self.copy)
            if self.move:
                tree = yield from move_files(runtime.cache, tree, self.move)
            if self.drop:
                tree = yield from drop_files(
                    runtime.cache, tree, self.drop)
            if self.pick:
                tree = yield from pick_files(runtime.cache, tree, self.pick)
            if self.executable:
                tree = yield from make_files_executable(
                    runtime.cache, tree, self.executable)
            if self.export:
                tree = yield from get_export_tree(
                    runtime.cache, tree, self.export)

            runtime.cache.keyval[key] = tree

        return tree

@asyncio.coroutine
def _copy_files_modifications(_cache, tree, paths_multimap):
    modifications = {}
    for source in paths_multimap:
        source_info_dict = yield from _cache.ls_tree(tree, source)
        if not source_info_dict:
            raise NoMatchingFilesError(
                'Path "{}" does not exist.'.format(source))
        source_info = list(source_info_dict.items())[0][1]
        for dest in paths_multimap[source]:
            # If dest is a directory, put the source inside dest instead of
            # overwriting dest entirely.
            dest_is_dir = False
            dest_info_dict = yield from _cache.ls_tree(tree, dest)
            if dest_info_dict:
                dest_info = list(dest_info_dict.items())[0][1]
                dest_is_dir = (dest_info.type == cache.TREE_TYPE)
            adjusted_dest = dest
            if dest_is_dir:
                adjusted_dest = str(PurePosixPath(dest) /
                                    PurePosixPath(source).name)
            modifications[adjusted_dest] = source_info
    return modifications

@asyncio.coroutine
def copy_files(_cache, tree, paths_multimap):
    modifications = yield from _copy_files_modifications(
        _cache, tree, paths_multimap)
    tree = yield from _cache.modify_tree(tree, modifications)
    return tree

@asyncio.coroutine
def move_files(_cache, tree, paths_multimap):
    # First obtain the copies from the original tree. Moves are not ordered but
    # happen all at once, so if you move a->b and b->c, the contents of c will
    # always end up being b rather than a.
    modifications = yield from _copy_files_modifications(
        _cache, tree, paths_multimap)
    # Now add in deletions, but be careful not to delete a file that just got
    # moved. Note that if "a" gets moved into "dir", it will end up at "dir/a",
    # even if "dir" is deleted (because modify_tree always modifies parents
    # before decending into children, and deleting a dir is a modification of
    # that dir's parent).
    for source in paths_multimap:
        if source not in modifications:
            modifications[source] = None
    tree = yield from _cache.modify_tree(tree, modifications)
    return tree

@asyncio.coroutine
def _get_glob_entries(_cache, tree, globs_list):
    matches = {}
    for glob_str in globs_list:
        # Do an in-memory match of all the paths in the tree against the
        # glob expression. As an optimization, if the glob is something
        # like 'a/b/**/foo', only list the paths under 'a/b'.
        regex = glob.glob_to_path_regex(glob_str)
        prefix = glob.unglobbed_prefix(glob_str)
        entries = yield from _cache.ls_tree(tree, prefix, recursive=True)
        found = False
        for path, entry in entries.items():
            if re.match(regex, path):
                matches[path] = entry
                found = True
        if not found:
            raise NoMatchingFilesError(
                '"{}" didn\'t match any files.'.format(glob_str))
    return matches

@asyncio.coroutine
def pick_files(_cache, tree, globs_list):
    picks = yield from _get_glob_entries(_cache, tree, globs_list)
    tree = yield from _cache.modify_tree(None, picks)
    return tree

@asyncio.coroutine
def drop_files(_cache, tree, globs_list):
    drops = yield from _get_glob_entries(_cache, tree, globs_list)
    for path in drops:
        drops[path] = None
    tree = yield from _cache.modify_tree(tree, drops)
    return tree

@asyncio.coroutine
def make_files_executable(_cache, tree, globs_list):
    entries = yield from _get_glob_entries(_cache, tree, globs_list)
    exes = {}
    for path, entry in entries.items():
        # Ignore directories.
        if entry.type == cache.BLOB_TYPE:
            exes[path] = entry._replace(mode=cache.EXECUTABLE_FILE_MODE)
    tree = yield from _cache.modify_tree(tree, exes)
    return tree

@asyncio.coroutine
def get_export_tree(_cache, tree, export_path):
    entries = yield from _cache.ls_tree(tree, export_path)
    if not entries:
        raise NoMatchingFilesError('Export path "{}" doesn\'t exist.'
                                   .format(export_path))
    entry = list(entries.values())[0]
    if entry.type != cache.TREE_TYPE:
        raise NoMatchingFilesError('Export path "{}" is not a directory.'
                                   .format(export_path))
    return entry.hash

class NoMatchingFilesError(PrintableError):
    pass


text:
package com.jfinal.weixin.sdk.msg.out;

import com.jfinal.weixin.sdk.msg.in.InMsg;

/**
    转发多客服消息
	<xml>
		<ToUserName><![CDATA[toUser]]></ToUserName>
		<FromUserName><![CDATA[fromUser]]></FromUserName>
		<CreateTime>12345678</CreateTime>
		<MsgType><![CDATA[transfer_customer_service]]></MsgType>
	</xml>
 */
public class OutCustomMsg extends OutMsg {
	public static final String TEMPLATE =
			"<xml>\n" +
			"<ToUserName><![CDATA[${__msg.toUserName}]]></ToUserName>\n" +
			"<FromUserName><![CDATA[${__msg.fromUserName}]]></FromUserName>\n" +
			"<CreateTime>${__msg.createTime}</CreateTime>\n" +
			"<MsgType><![CDATA[${__msg.msgType}]]></MsgType>\n" +
			"</xml>";

	private String content;

	public OutCustomMsg() {
		this.msgType = "transfer_customer_service";
	}

	public OutCustomMsg(InMsg inMsg) {
		super(inMsg);
		this.msgType = "transfer_customer_service";
	}

	public String getContent() {
		return content;
	}

	public OutCustomMsg setContent(String content) {
		this.content = content;
		return this;
	}
}


text:
Cars module
--

Module for advertising cars with built-in xml import


text:
namespace wspp { namespace db {

class ConnectionHandle ;

class Exception: public std::runtime_error
{
public:
    Exception(const std::string &msg) ;
    Exception(ConnectionHandle &h) ;
};

} // namespace sqlite
} // namespace util

#endif


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Modulz – An open-source design system</title>

    <button class="InvisibleButton" data-toggle="sidedrawer" data-target="sideDrawer" style="position: fixed; top: 32px; left: 32px; z-index: 6;">
      <svg class="Icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <line x1="3" y1="12" x2="21" y2="12"></line>
        <line x1="3" y1="6" x2="21" y2="6"></line>
        <line x1="3" y1="18" x2="21" y2="18"></line>
      </svg>
    </button>
    ${require('partials/navigation.html')}

Visibility

Control the visibility of elements without modifying their display value. Useful for temporarily hiding content while still keeping it available to screen readers.

              Class
              Description

              .visibility-visible

Set an element box to be visible.

              .visibility-hidden

Set an element to be invisible. Layout will not be affected. The element cannot receive focus (such as when navigating through tab indexes).

    ${require('partials/footer.html')}


text:
#ifndef _BTLE_SECURITY_H_
#define _BTLE_SECURITY_H_

#include "ble/Gap.h"
#include "ble/SecurityManager.h"

/**
 * Enable Nordic's Device Manager, which brings in functionality from the
 * stack's Security Manager. The Security Manager implements the actual
 * cryptographic algorithms and protocol exchanges that allow two devices to
 * securely exchange data and privately detect each other.
 *
 * @param[in]  enableBonding Allow for bonding.
 * @param[in]  requireMITM   Require protection for man-in-the-middle attacks.
 * @param[in]  iocaps        To specify IO capabilities of this peripheral,
 *                           such as availability of a display or keyboard to
 *                           support out-of-band exchanges of security data.
 * @param[in]  passkey       To specify a static passkey.
 *
 * @return BLE_ERROR_NONE on success.
 */
ble_error_t btle_initializeSecurity(bool                                      enableBonding = true,
                                    bool                                      requireMITM   = true,
                                    SecurityManager::SecurityIOCapabilities_t iocaps        = SecurityManager::IO_CAPS_NONE,
                                    const SecurityManager::Passkey_t          passkey       = NULL);

/**
 * Get the security status of a link.
 *
 * @param[in]  connectionHandle
 *               Handle to identify the connection.
 * @param[out] securityStatusP
 *               security status.
 *
 * @return BLE_SUCCESS Or appropriate error code indicating reason for failure.
 */
ble_error_t btle_getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP);

/**
 * Function for deleting all peer device context and all related bonding
 * information from the database.
 *
 * @retval BLE_ERROR_NONE             On success, else an error code indicating reason for failure.
 * @retval BLE_ERROR_INVALID_STATE    If the API is called without module initialization and/or
 *                                    application registration.
 */
ble_error_t btle_purgeAllBondingState(void);

#endif /* _BTLE_SECURITY_H_ */


text:
import React, { PropTypes } from 'react';
import CreateComment from '../containers/create_comment.js';
import { Avatar, List, ListItem } from 'material-ui';
import { SocialPerson } from 'material-ui/svg-icons';

const CommentList = ({ comments, postId }) => (

      <CreateComment postId={postId} />

    <List className="comment-list">
      {comments.length === 0 ?
No Comments Yet!
 : null}
      {comments.map(comment => (
        <ListItem
          key={comment._id}
          className="comment"
          leftAvatar={<Avatar icon={<SocialPerson />} />}
          primaryText={comment.text}
          secondaryText={`${comment.author}${comment.saving ? '...' : ''}`}
        />
      ))}
    </List>

);

CommentList.propTypes = {
  comments: PropTypes.arrayOf(PropTypes.object).isRequired,
  postId:   PropTypes.string.isRequired,
};

export default CommentList;


text:
#include "../common/CAssoc.h"

class CAccount;
class CClient;
class CServerDef;
class CWebPageDef;

typedef CServerDef *CServerRef;

enum OF_TYPE	// option flags
{
	OF_NoDClickTarget			= 0x00001,
	OF_NoSmoothSailing			= 0x00002,
	OF_ScaleDamageByDurability	= 0x00004,
	OF_Command_Sysmsgs			= 0x00008,
	OF_PetSlots					= 0x00010,
	OF_OSIMultiSight			= 0x00020,
	OF_Items_AutoName			= 0x00040,
	OF_FileCommands				= 0x00080,
	OF_NoItemNaming				= 0x00100,
	OF_NoHouseMuteSpeech		= 0x00200,
	OF_MapBoundarySailing		= 0x00800,
	OF_Flood_Protection			= 0x01000,
	OF_Buffs					= 0x02000,
	OF_NoPrefix					= 0x04000,
	OF_DyeType					= 0x08000,
	OF_DrinkIsFood				= 0x10000,
	OF_NoDClickTurn				= 0x20000
};

enum EF_TYPE	// experimental flags
{
	EF_NoDiagonalCheckLOS		= 0x00001,
	EF_DynamicBackgroundSave	= 0x00002,
	EF_ItemStacking				= 0x00004,
	EF_ItemStackDrop			= 0x00008,
	EF_FastWalkPrevention		= 0x00010,
	EF_Intrinsic_Locals			= 0x00020,
	EF_Item_Strict_Comparison	= 0x00040,
	EF_AllowTelnetPacketFilter	= 0x00200,
	EF_Script_Profiler			= 0x00400,
	EF_UsePingServer			= 0x08000,
	EF_FixCanSeeInClosedConts	= 0x20000
};

enum MAGICFLAGS_TYPE
{
	MAGICF_NODIRCHANGE			= 0x0001,	// Not rotate player when casting/targeting
	MAGICF_PRECAST				= 0x0002,	// Precasting (cast spell before target prompt)
	MAGICF_IGNOREAR				= 0x0004,	// Magic damage ignore ar
	MAGICF_CANHARMSELF			= 0x0008,	// Magic can do damage on self
	MAGICF_STACKSTATS			= 0x0010,	// Different stat spells don't cancel each other out
	MAGICF_FREEZEONCAST			= 0x0020,	// No movement whilst casting
	MAGICF_SUMMONWALKCHECK		= 0x0040,	// Summoned creatures should be able to walk on the target location (e.g. water creatures to be summoned on water)
	MAGICF_NOFIELDSOVERWALLS	= 0x0080,	// Field spells cannot cross over blocking objects
	MAGICF_NOANIM				= 0x0100,	// Auto SPELLFLAG_NO_ANIM in every spell
	MAGICF_OSIFORMULAS			= 0x0200,	// Calculate spell damage and duration based on OSI formulas
	MAGICF_NOCASTFROZENHANDS	= 0x0400,	// Can't cast spells if got paralyzed holding something on hands
	MAGICF_POLYMORPHSTATS		= 0x0800,	// Polymorph spells give out stats based on base chars (old behaviour backwards)
	MAGICF_OVERRIDEFIELDS		= 0x1000	// Prevent cast multiple field spells on the same tile, making the new field tile remove the previous field
};

enum REVEALFLAGS_TYPE
{
	REVEALF_DETECTINGHIDDEN		= 0x01,		// Reveal when someone use Detecting Hidden skill
	REVEALF_LOOTINGSELF			= 0x02,		// Reveal when loot self bodies
	REVEALF_LOOTINGOTHERS		= 0x04,		// Reveal when loot others bodies
	REVEALF_SPEAK				= 0x08,		// Reveal when speak
	REVEALF_SPELLCAST			= 0x10		// Reveal when cast spells
};

enum CHATFLAGS_TYPE
{
	CHATF_AUTOJOIN				= 0x01,		// Auto join first static channel available (new chat system: join after client login / old chat system: join after open chat window)
	CHATF_CHANNELCREATION		= 0x02,		// Enable channel creation
	CHATF_CHANNELMODERATION		= 0x04,		// Enable channel moderation (old chat system only)
	CHATF_CUSTOMNAMES			= 0x08,		// Enable custom name selection when open chat window for the first time (old chat system only)
	CHATF_GLOBALCHAT			= 0x10		// Enable global chat system on clients >= 7.0.62.2 (INCOMPLETE)
};

enum RACIALFLAGS_TYPE
{
	RACIALF_HUMAN_STRONGBACK	= 0x001,	// Increase carrying capacity (+60 stones of weight)
	RACIALF_HUMAN_TOUGH			= 0x002,	// Regenerate hitpoints faster (+2 Hit Point Regeneration)
	RACIALF_HUMAN_WORKHORSE		= 0x004,	// Find more resources while gathering hides, ore and lumber
	RACIALF_HUMAN_JACKOFTRADES	= 0x008,	// Skill calculations always consider 20.0 minimum ability on untrained skills
	RACIALF_ELF_NIGHTSIGHT		= 0x010,	// Permanent night sight effect
	RACIALF_ELF_DIFFTRACK		= 0x020,	// Increase difficulty to be tracked while hidden/invisible
	RACIALF_ELF_WISDOM			= 0x040,	// Permanent max mana bonus (+20 Mana Increase)
	RACIALF_GARG_FLY			= 0x080,	// Enable gargoyle fly ability (FEATURE_AOS_UPDATE_B is required to enable gargoyle ability book)
	RACIALF_GARG_BERSERK		= 0x100,	// Increase ferocity in situations of danger (15% Damage Increase + 3% Spell Damage Increase for each 20hp lost)
	RACIALF_GARG_DEADLYAIM		= 0x200,	// Throwing calculations always consider 20.0 minimum ability when untrained
	RACIALF_GARG_MYSTICINSIGHT	= 0x400		// Mysticism calculations always consider 30.0 minimum ability when untrained
};

enum COMBATFLAGS_TYPE
{
	COMBAT_NODIRCHANGE			= 0x0001,	// Not rotate player when fighting (like was in 0.51a)
	COMBAT_FACECOMBAT			= 0x0002,	// Allow faced combat only (recommended)
	COMBAT_PREHIT				= 0x0004,	// Allow prehit for close combat. first hit is instant (delay 0.1sec)
	COMBAT_ELEMENTAL_ENGINE		= 0x0008,	// Use DAM*/RES* to split damage/resist into Physical/Fire/Cold/Poison/Energy (AOS) instead use old AR (pre-AOS)
	COMBAT_MAXITEMDURABILITY	= 0x0010,	// Make damageable items get destroyed when lose max durability instead current durability (OSI-like)
	COMBAT_DCLICKSELF_UNMOUNTS	= 0x0020,	// Unmount horse when dclicking self while in warmode
	COMBAT_ALLOWHITFROMSHIP		= 0x0040,	// Allow attacking opponents from ships
	COMBAT_NOPETDESERT			= 0x0080,	// Allow pet owner attack own pet without make it desert its owner
	COMBAT_ARCHERYCANMOVE		= 0x0100,	// Allow firing bow while moving
	COMBAT_STAYINRANGE			= 0x0200,	// Abort attack swing when out of range instead of waiting to come back in range
	COMBAT_ATTACKONNOTICE		= 0x0400,	// Make target instantly attack back when notice someone trying to attack it
	COMBAT_NPC_NOATTACKMSG		= 0x0800,	// Disable *is attacking* message on NPCs
	COMBAT_STACKARMOR			= 0x1000,	// If a region is covered by more than one armor part, all AR will count
	COMBAT_NOPOISONHIT			= 0x2000	// Disables old (55i like) poisoning style (0~100% chance based on Poisoning skill for monsters, or 50% chance for poisoned weapons)
};

enum TOOLTIPMODE_TYPE
{
	TOOLTIPMODE_SENDFULL		= 0x0,		// Always send full tooltip
	TOOLTIPMODE_SENDVERSION		= 0x1		// Send only tooltip version and wait for client to request full tooltip
};

#define DAMAGE_GOD			0x00001	// Nothing can block this.
#define DAMAGE_HIT_BLUNT	0x00002	// Physical hit of some sort.
#define DAMAGE_MAGIC		0x00004	// Magic blast of some sort. (we can be immune to magic to some extent)
#define DAMAGE_POISON		0x00008	// Or biological of some sort ? (HARM spell)
#define DAMAGE_FIRE			0x00010	// Fire damage of course (some creatures are immune to fire)
#define DAMAGE_ENERGY		0x00020	// lightning.
#define DAMAGE_GENERAL		0x00080	// All over damage. As apposed to hitting just one point.
#define DAMAGE_ACIDIC		0x00100	// damages armor
#define DAMAGE_COLD			0x00200	// cold or water based damage
#define DAMAGE_HIT_SLASH	0x00400	// sword
#define DAMAGE_HIT_PIERCE	0x00800	// spear.
#define DAMAGE_NODISTURB	0x02000	// victim won't be disturbed
#define DAMAGE_NOREVEAL		0x04000	// Attacker is not revealed for this
#define DAMAGE_NOUNPARALYZE	0x08000	// victim won't be unparalyzed
#define DAMAGE_FIXED		0x10000	// already fixed damage, don't do calcs ... only create blood, anim, sounds... and update memories and attacker

typedef DWORD DAMAGE_TYPE;

#define IsSetOF(flags)				(g_Cfg.m_iOptionFlags & flags)
#define IsSetEF(flags)				(g_Cfg.m_iExperimental & flags)
#define IsSetMagicFlags(flags)		(g_Cfg.m_iMagicFlags & flags)
#define IsSetCombatFlags(flags)		(g_Cfg.m_iCombatFlags & flags)

///////////////////////////////////////////////////////////
// CValueRangeDef

struct CValueRangeDef
{
	// Simple linearity

public:
	CValueRangeDef()
	{
		Init();
	}

public:
	INT64 m_iLo;
	INT64 m_iHi;

public:
	void Init()
	{
		m_iLo = LLONG_MIN;
		m_iHi = LLONG_MIN;
	}

	int GetRange() const
	{
		return static_cast<int>(m_iHi - m_iLo);
	}
	int GetLinear(int iPercent) const
	{
		// ARGS: iPercent = 0-1000
		const int iRange = GetRange();
		return static_cast<int>(m_iLo) + IMULDIV(iRange, iPercent, 1000);
	}
	int GetRandom() const
	{
		return static_cast<int>(m_iLo) + Calc_GetRandVal(GetRange());
	}
	int GetRandomLinear(int iPercent) const;

	bool Load(TCHAR *pszDef);
	const TCHAR *Write() const;
};

///////////////////////////////////////////////////////////
// CValueCurveDef

struct CValueCurveDef
{
	// Describe an arbitrary curve.
	// for a range from 0.0 to 100.0 (1000)
	// May be a list of probabilties from 0 skill to 100.0% skill.

public:
	CValueCurveDef() { };

public:
	CGTypedArray<int, int> m_aiValues;		// 0 to 100.0 skill levels

public:
	void Init()
	{
		m_aiValues.RemoveAll();
	}

	int GetLinear(int iSkillPercent) const;
	int GetChancePercent(int iSkillPercent) const;
	int GetRandom() const;
	int GetRandomLinear(int iPercent) const;

	bool Load(TCHAR *pszDef);
	const TCHAR *Write() const;

private:
	CValueCurveDef(const CValueCurveDef &copy);
	CValueCurveDef &operator=(const CValueCurveDef &other);
};

///////////////////////////////////////////////////////////
// CCharRefArray

class CCharRefArray
{
	// List of Players and NPC's involved in the quest/party/account etc..

public:
	static const char *m_sClassName;

	CCharRefArray() { };

private:
	CGTypedArray< CGrayUID, CGrayUID> m_uidCharArray;

public:
	size_t FindChar(const CChar *pChar) const;
	size_t AttachChar(const CChar *pChar);
	size_t InsertChar(const CChar *pChar, size_t i);
	void DetachChar(size_t i);
	size_t DetachChar(const CChar *pChar);
	void DeleteChars();
	void WritePartyChars(CScript &s);

	CGrayUID GetChar(size_t i) const
	{
		return m_uidCharArray[i];
	}
	size_t GetCharCount() const
	{
		return m_uidCharArray.GetCount();
	}

	bool IsCharIn(const CChar *pChar) const
	{
		return (FindChar(pChar) != m_uidCharArray.BadIndex());
	}

	bool IsValidIndex(size_t i) const
	{
		return m_uidCharArray.IsValidIndex(i);
	}
	inline size_t BadIndex() const
	{
		return m_uidCharArray.BadIndex();
	}

private:
	CCharRefArray(const CCharRefArray &copy);
	CCharRefArray &operator=(const CCharRefArray &other);
};

///////////////////////////////////////////////////////////
// CRegionResourceDef

enum RRTRIG_TYPE
{
	// XTRIG_UNKNOWN	= some named trigger not on this list.
	RRTRIG_RESOURCEFOUND = 1,
	RRTRIG_RESOURCEGATHER,
	RRTRIG_RESOURCETEST,
	RRTRIG_QTY
};

class CRegionResourceDef : public CResourceLink
{
	// RES_REGIONRESOURCE
	// When mining/lumberjacking etc. What can we get?

public:
	static const char *m_sClassName;
	static const LPCTSTR sm_szLoadKeys[];
	static const LPCTSTR sm_szTrigName[RRTRIG_QTY + 1];

	explicit CRegionResourceDef(RESOURCE_ID rid);
	virtual ~CRegionResourceDef();

public:
	ITEMID_TYPE m_ReapItem;				// ITEMID_ORE_1 most likely
	CValueCurveDef m_ReapAmount;		// How much can we reap at one time (based on skill)
	CValueCurveDef m_Amount;			// How is here total
	CValueCurveDef m_Skill;				// Skill levels required to mine this.
	CValueCurveDef m_iRegenerateTime;	// TICK_PER_SEC once found how long to regen this type.

public:
	TRIGRET_TYPE OnTrigger(LPCTSTR pszTrigName, CTextConsole *pSrc, CScriptTriggerArgs *pArgs = NULL);
	bool r_LoadVal(CScript &s);
	bool r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc = NULL);

private:
	CRegionResourceDef(const CRegionResourceDef &copy);
	CRegionResourceDef &operator=(const CRegionResourceDef &other);
};

///////////////////////////////////////////////////////////
// CSpellDef

enum SPTRIG_TYPE
{
	SPTRIG_EFFECT = 1,
	SPTRIG_FAIL,
	SPTRIG_SELECT,
	SPTRIG_START,
	SPTRIG_SUCCESS,
	SPTRIG_TARGETCANCEL,
	SPTRIG_QTY
};

class CSpellDef : public CResourceLink	// 1 based spells. See SPELL_*
{
	// RES_SPELL

public:
	static const char *m_sClassName;
	static const LPCTSTR sm_szLoadKeys[];
	static const LPCTSTR sm_szTrigName[SPTRIG_QTY + 1];

	explicit CSpellDef(SPELL_TYPE id);
	virtual ~CSpellDef() { }

private:
	#define SPELLFLAG_DIR_ANIM			0x00000001	// Evoke type cast or directed. (animation)
	#define SPELLFLAG_TARG_ITEM			0x00000002	// Need to target an object
	#define SPELLFLAG_TARG_CHAR			0x00000004	// Needs to target a living thing
	#define SPELLFLAG_TARG_OBJ			(SPELLFLAG_TARG_ITEM|SPELLFLAG_TARG_CHAR)
	#define SPELLFLAG_TARG_XYZ			0x00000008	// Can just target a location.
	#define SPELLFLAG_HARM				0x00000010	// The spell is in some way harmfull.
	#define SPELLFLAG_FX_BOLT			0x00000020	// Effect is a bolt to the target.
	#define SPELLFLAG_FX_TARG			0x00000040	// Effect is at the target.
	#define SPELLFLAG_FIELD				0x00000080	// create a field of stuff. (fire,poison,wall)
	#define SPELLFLAG_SUMMON			0x00000100	// summon a creature.
	#define SPELLFLAG_GOOD				0x00000200	// The spell is a good spell. u intend to help to receiver.
	#define SPELLFLAG_RESIST			0x00000400	// Allowed to resist this.
	#define SPELLFLAG_TARG_NOSELF		0x00000800
	#define SPELLFLAG_DISABLED			0x00008000
	#define SPELLFLAG_SCRIPTED			0x00010000
	#define SPELLFLAG_PLAYERONLY		0x00020000	// casted by players only
	#define SPELLFLAG_NOUNPARALYZE		0x00040000	// casted by players only
	#define SPELLFLAG_NO_CASTANIM		0x00080000	// play no anim while casting (also override SPELLFLAG_DIR_ANIM)
	#define SPELLFLAG_TARG_NO_PLAYER	0x00100000	// if a char may be targetted, it may not be a player
	#define SPELLFLAG_TARG_NO_NPC		0x00200000	// if a char may be targetted, it may not be an NPC
	#define SPELLFLAG_NOPRECAST			0x00400000	// disable precasting for this spell
	#define SPELLFLAG_NOFREEZEONCAST	0x00800000	// disable freeze on cast for this spell
	#define SPELLFLAG_AREA				0x01000000	// area effect (uses local.arearadius)
	#define SPELLFLAG_POLY				0x02000000
	#define SPELLFLAG_TARG_DEAD			0x04000000	// allowed to targ dead chars
	#define SPELLFLAG_DAMAGE			0x08000000	// damage intended
	#define SPELLFLAG_BLESS				0x10000000	// Benefitial spells like Bless, Agility, etc
	#define SPELLFLAG_CURSE				0x20000000	// Curses just like Weaken, Purge Magic, Curse, etc
	#define SPELLFLAG_HEAL				0x40000000	// Healing spell
	DWORD m_dwFlags;

	DWORD m_dwGroup;
	CGString m_sName;

public:
	SOUND_TYPE m_sound;				// What noise does it make when done.
	ITEMID_TYPE m_idSpell;			// The rune graphic for this.
	ITEMID_TYPE m_idScroll;			// The scroll graphic item for this.
	ITEMID_TYPE m_idEffect;			// Animation effect ID
	LAYER_TYPE m_idLayer;			// Where the layer buff/debuff/data is stored.
	WORD m_wManaUse;				// How much mana does it need.
	WORD m_wTithingUse;				// Tithing points required for this spell.

	CValueCurveDef m_CastTime;		// In TICK_PER_SEC.
	CValueCurveDef m_Interrupt;		// Chance to interrupt a spell
	CValueCurveDef m_Effect;		// Damage or effect level based on skill of caster.100% magery
	CValueCurveDef m_Duration;		// Length of effect. in TICK_PER_SEC

	CGString m_sTargetPrompt;		// Targetting prompt (if needed)
	CGString m_sRunes;				// Letter Runes for Words of power.

	CResourceQtyArray m_Reags;		// What reagents does it take ?
	CResourceQtyArray m_SkillReq;	// What skills/unused reagents does it need to cast.

public:
	bool IsSpellType(DWORD dwFlags) const
	{
		return (m_dwFlags & dwFlags);
	}

	LPCTSTR GetName() const
	{
		return m_sName;
	}

	bool r_LoadVal(CScript &s);
	bool r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc);

	bool GetPrimarySkill(int *piSkill = NULL, int *piQty = NULL) const;

private:
	CSpellDef(const CSpellDef &copy);
	CSpellDef &operator=(const CSpellDef &other);
};

///////////////////////////////////////////////////////////
// CRandGroupDef

class CRandGroupDef : public CResourceLink
{
	// A spawn group.
	// RES_SPAWN or RES_REGIONTYPE

public:
	static const char *m_sClassName;
	static const LPCTSTR sm_szLoadKeys[];

	explicit CRandGroupDef(RESOURCE_ID rid) : CResourceLink(rid)
	{
		m_iTotalWeight = 0;
	}
	virtual ~CRandGroupDef() { }

private:
	int m_iTotalWeight;
	CResourceQtyArray m_Members;

public:
	CGString m_sCategory;
	CGString m_sSubsection;
	CGString m_sDescription;

private:
	int CalcTotalWeight();

public:
	virtual bool r_LoadVal(CScript &s);
	virtual bool r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc = NULL);

	CResourceQty GetMember(size_t i) const
	{
		return m_Members[i];
	}
	RESOURCE_ID GetMemberID(size_t i) const
	{
		return m_Members[i].GetResourceID();
	}

	size_t GetRandMemberIndex(CChar *pCharSrc = NULL, bool fTrigger = true) const;
	size_t BadMemberIndex() const
	{
		return m_Members.BadIndex();
	}

private:
	CRandGroupDef(const CRandGroupDef &copy);
	CRandGroupDef &operator=(const CRandGroupDef &other);
};

///////////////////////////////////////////////////////////
// CSkillClassDef

enum STAT_TYPE
{
	// Stats
	STAT_NONE = -1,
	STAT_STR,
	STAT_INT,
	STAT_DEX,
	STAT_FOOD,		// just used as a regen rate (as karma does not decay)
	STAT_BASE_QTY = STAT_FOOD,

	// Notoriety
	STAT_KARMA,		// g_Cfg.m_iMinKarma to g_Cfg.m_iMaxKarma - also used as the food consumption main timer.
	STAT_FAME,		// 0 to g_Cfg.m_iMaxFame
	STAT_QTY
};

const LPCTSTR g_Stat_Name[STAT_QTY + 1] =
{
	"STR",
	"INT",
	"DEX",
	"FOOD",
	"KARMA",
	"FAME",
	NULL
};

class CSkillClassDef : public CResourceLink // For skill def table
{
	// Similar to character class.
	// RES_SKILLCLASS

public:
	static const char *m_sClassName;
	static const LPCTSTR sm_szLoadKeys[];

	explicit CSkillClassDef(RESOURCE_ID rid) : CResourceLink(rid)
	{
		// If there was none defined in scripts
		Init();
	}
	virtual ~CSkillClassDef() { }

public:
	DWORD m_SkillSumMax;
	WORD m_StatSumMax;
	WORD m_SkillLevelMax[SKILL_QTY];
	WORD m_StatMax[STAT_BASE_QTY];
	CGString m_sName;

private:
	void Init();

public:
	bool r_LoadVal(CScript &s);
	bool r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc);

	LPCTSTR GetName() const
	{
		return m_sName;
	}

private:
	CSkillClassDef(const CSkillClassDef &copy);
	CSkillClassDef &operator=(const CSkillClassDef &other);
};

///////////////////////////////////////////////////////////
// CSkillDef

enum SKTRIG_TYPE
{
	// All skills may be scripted.
	// XTRIG_UNKNOWN	= some named trigger not on this list.
	SKTRIG_ABORT = 1,		// Some odd thing went wrong.
	SKTRIG_FAIL,			// We failed the skill check.
	SKTRIG_GAIN,			// Called when there is a chance to gain skill
	SKTRIG_PRESTART,		// Called before any hardcoded messages
	SKTRIG_SELECT,			// Just selecting params for the skill
	SKTRIG_START,			// Params for skill are done. (stroke)
	SKTRIG_STROKE,			// Not really a trigger! Just a stage.
	SKTRIG_SUCCESS,			// We passed the skill check
	SKTRIG_TARGETCANCEL,	// Called when a target cursor is cancelled
	SKTRIG_USEQUICK,		// Called when a 'quick' usage of the skill is made
	SKTRIG_WAIT,			// Called when a test is made to see if the character must wait before starting
	SKTRIG_QTY
};

enum SKF_TYPE
{
	SKF_SCRIPTED	= 0x001,	// Fully scripted, no hardcoded behaviour
	SKF_FIGHT		= 0x002,	// Considered a fight skill, maintains fight active
	SKF_MAGIC		= 0x004,	// Considered a magic skill
	SKF_CRAFT		= 0x008,	// Considered a crafting skill, compatible with MAKEITEM function
	SKF_IMMOBILE	= 0x010,	// Fails skill if character moves
	SKF_SELECTABLE	= 0x020,	// Allows skill to be selected from the skill menu
	SKF_NOMINDIST	= 0x040,	// You can mine, fish, chop, hack on the same point you are standing on
	SKF_NOANIM		= 0x080,	// Prevents hardcoded animation from playing
	SKF_NOSFX		= 0x100,	// Prevents hardcoded sound from playing
	SKF_RANGED		= 0x200,	// Considered a ranged skill (combine with SKF_FIGHT)
	SKF_GATHER		= 0x400,	// Considered a gathering skill, using SkillStrokes as SKF_CRAFT
	SKF_DISABLED	= 0x800		// Disabled skill, can't be used.
};

struct CSkillDef : public CResourceLink
{
	// For skill def table
	// RES_SKILL

public:
	static const LPCTSTR sm_szLoadKeys[];
	static const LPCTSTR sm_szTrigName[SKTRIG_QTY + 1];

	explicit CSkillDef(SKILL_TYPE iSkill);
	virtual ~CSkillDef() { };

private:
	CGString m_sKey;			// script key word for skill.

public:
	CGString m_sName;			// Fancy skill name
	CGString m_sTitle;			// Title one gets if it's your specialty.
	CGString m_sTargetPrompt;	// Targetting prompt (if needed)

	CValueCurveDef m_Delay;		// The base delay for the skill (tenth of seconds)
	CValueCurveDef m_Effect;	// Depends on skill

	CValueCurveDef m_AdvRate;	// ADV_RATE defined "skill curve" 0 to 100 skill levels.
	CValueCurveDef m_Values;	// VALUES= influence for items made with 0 to 100 skill levels.
	int m_GainRadius;			// GAINRADIUS= max. amount of skill above the necessary skill for a task to gain from it
	int m_Range;
	DWORD m_dwFlags;
	DWORD m_dwGroup;

	// Stat effects.
	// You will tend toward these stat vals if you use this skill a lot.
	BYTE m_Stat[STAT_BASE_QTY];			// STAT_STR, STAT_INT, STAT_DEX
	BYTE m_StatPercent;					// BONUS_STATS = % of success depending on stats
	BYTE m_StatBonus[STAT_BASE_QTY];	// % of each stat toward success at skill, total 100

public:
	bool r_LoadVal(CScript &s);
	bool r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc);

	LPCTSTR GetKey() const
	{
		return m_sKey;
	}
	LPCTSTR GetName() const
	{
		return GetKey();
	}

private:
	CSkillDef(const CSkillDef &copy);
	CSkillDef &operator=(const CSkillDef &other);
};

///////////////////////////////////////////////////////////
// CSkillKeySortArray

class CSkillKeySortArray : public CGObSortArray<CValStr *, LPCTSTR>
{
public:
	CSkillKeySortArray() { };

public:
	int CompareKey(LPCTSTR pszKey, CValStr *pVal, bool fNoSpaces) const
	{
		UNREFERENCED_PARAMETER(fNoSpaces);
		ASSERT(pszKey);
		ASSERT(pVal->m_pszName);
		return strcmpi(pszKey, pVal->m_pszName);
	}

private:
	CSkillKeySortArray(const CSkillKeySortArray &copy);
	CSkillKeySortArray &operator=(const CSkillKeySortArray &other);
};

///////////////////////////////////////////////////////////
// CMultiDefArray

struct CMultiDefArray : public CGObSortArray<CGrayMulti *, MULTI_TYPE>
{
	// Store the static components of a IT_MULTI
	// Sorted array
	int CompareKey(MULTI_TYPE id, CGrayMulti *pBase, bool fNoSpaces) const
	{
		UNREFERENCED_PARAMETER(fNoSpaces);
		ASSERT(pBase);
		return id - pBase->GetMultiID();
	}
};

///////////////////////////////////////////////////////////
// CResource

extern class CResource : public CResourceBase
{
	// Script defined resources (not saved in world file)

public:
	static const char *m_sClassName;
	static const CAssocReg sm_szLoadKeys[];

	CResource();
	~CResource();

public:
	CServTime m_timePeriodic;				// When to perform the next periodic update

	// Begin INI file options
	int m_fUseHTTP;
	bool m_fUseAuthID;
	int m_iMapCacheTime;					// Time in sec to keep unused map data.
	int m_iSectorSleepMask;					// The mask for how long sectors will sleep.
	bool m_fUseMapDiffs;					// Whether or not to use map diff files.

	CGString m_sWorldBaseDir;				// "e:\graysvr\worldsave\" = world files go here.
	CGString m_sAcctBaseDir;				// Where do the account files go/come from ?

	bool m_fSecure;							// Secure mode. (will trap exceptions)
	int m_iFreezeRestartTime;				// # seconds before restarting.

#ifdef _DEBUG
	#define DEBUGF_NPC_EMOTE		0x0001
	#define DEBUGF_ADVANCE_STATS	0x0002
	#define DEBUGF_EXP				0x0200	// experience gain/loss
	#define DEBUGF_LEVEL			0x0400	// experience level changes
	#define DEBUGF_SCRIPTS			0x0800	// debug flags for scripts
	#define DEBUGF_LOS				0x1000	// debug flags for AdvancedLOS
	#define DEBUGF_WALK				0x2000	// debug flags for Walking stuff
	#define DEBUGF_PACKETS			0x4000	// log packets to file
	#define DEBUGF_NETWORK			0x8000	// debug flags for networking
	WORD m_wDebugFlags;						// DEBUG In game effects to turn on and off.
#endif

	// Decay
	int m_iDecay_Item;						// Base decay time in minutes.
	int m_iDecay_CorpsePlayer;				// Time for a playercorpse to decay (mins).
	int m_iDecay_CorpseNPC;					// Time for a NPC corpse to decay.

	// Save
	int m_iSaveNPCSkills;					// Only save NPC skills above this
	int m_iSavePeriod;						// Minutes between saves.
	int m_iSaveBackupLevels;				// How many backup levels.
	int m_iSaveBackgroundTime;				// Speed of the background save in minutes.
	unsigned int m_iSaveSectorsPerTick;		// max number of sectors per dynamic background save step
	unsigned int m_iSaveStepMaxComplexity;	// maximum "number of items+characters" saved at once during dynamic background save
	bool m_fSaveGarbageCollect;				// Always force a full garbage collection.

	// Account
	int m_iDeadSocketTime;
	unsigned int m_iClientsMax;				// Maximum (FD_SETSIZE) open connections to server
	int m_iClientsMaxIP;					// Maximum (FD_SETSIZE) open connections to server per IP
	int m_iConnectingMax;					// max clients connecting
	int m_iConnectingMaxIP;					// max clients connecting

	bool m_fAutoAccountCreation;			// Automatically create accounts when client try to login on nonexistent account
	int m_iClientLingerTime;				// How long logged out clients linger in seconds.
	int m_iMinCharDeleteTime;				// How old must a char be ? (minutes)
	BYTE m_iMaxCharsPerAccount;				// Maximum characters allowed on an account.
	bool m_fMd5Passwords;					// Should MD5 hashed passwords be used?

	// Magic
	bool m_fReagentsRequired;
	int m_iWordsOfPowerColor;
	int m_iWordsOfPowerFont;
	bool m_fWordsOfPowerPlayer;				// Words of Power for players
	bool m_fWordsOfPowerStaff;				// Words of Power for staff
	bool m_fEquippedCast;					// Allow casting while equipped.
	bool m_fReagentLossFail;				// ??? Lose reags when failed.
	int m_iMagicUnlockDoor;					// 1 in N chance of magic unlock working on doors -- 0 means never
	int m_iSpellTimeout;					// Length of time (in seconds) for a player to choose a target when casting

	ITEMID_TYPE m_iSpell_Teleport_Effect_NPC;
	SOUND_TYPE m_iSpell_Teleport_Sound_NPC;
	ITEMID_TYPE m_iSpell_Teleport_Effect_Players;
	SOUND_TYPE m_iSpell_Teleport_Sound_Players;
	ITEMID_TYPE m_iSpell_Teleport_Effect_Staff;
	SOUND_TYPE m_iSpell_Teleport_Sound_Staff;

	// Ingame effects
	int m_iLightDay;						// Outdoor light level.
	int m_iLightNight;						// Outdoor light level.
	int m_iLightDungeon;
	int m_iGameMinuteLength;				// Length of the game world minute in real world (TICK_PER_SEC) seconds.
	bool m_fNoWeather;						// Turn off all weather.
	bool m_fCharTags;						// Show [NPC] tags over chars.
	bool m_fVendorTradeTitle;				// Show job title on vendor names.
	bool m_fFlipDroppedItems;				// Flip dropped items.
	WORD m_iItemsMaxAmount;					// Max amount allowed for stackable items.
	bool m_fMonsterFight;					// Will creatures fight amoung themselves.
	bool m_fMonsterFear;					// will they run away if hurt ?
	DWORD m_iBankMaxItems;					// Maximum number of items allowed in bank.
	int m_iBankMaxWeight;					// Maximum weight in stones allowed in bank.
	int m_iBackpackMaxWeight;				// Maximum weight in stones allowed in main backpack.
	int m_iVendorMaxSell;					// Max things a vendor will sell in one shot.
	unsigned int m_iMaxCharComplexity;		// How many chars per sector.
	unsigned int m_iMaxItemComplexity;		// How many items per meter.
	unsigned int m_iMaxSectorComplexity;	// How many items per sector.
	bool m_fGenericSounds;					// Do players receive generic (not them-devoted) sounds
	bool m_fAutoNewbieKeys;					// Are house and boat keys newbied automatically?
	int m_iStamRunningPenalty;				// Weight penalty for running (+N% of max carry weight)
	int m_iStaminaLossAtWeight;				// %Weight at which characters begin to lose stamina
	int m_iHitpointPercentOnRez;			// How many hitpoints do they get when they are rez'd?
	int m_iHitsHungerLoss;					// How many % of HP will loose char on starving
	WORD m_iMaxBaseSkill;					// Maximum value for base skills at char creation
	WORD m_iTrainSkillCost;
	WORD m_iTrainSkillMax;
	int m_iTrainSkillPercent;				// How much can NPC's train up to ?
	int m_fDeadCannotSeeLiving;
	int m_iMediumCanHearGhosts;				// At this Spirit Speak skill level players can understand ghosts speech instead hear 'oOOoO ooO'
	bool m_iMountHeight;					// Do not allow entering under roof being on horse?
	int m_iMoveRate;						// The percent rate of NPC movement
	int m_iArcheryMinDist;
	int m_iArcheryMaxDist;
	int m_iHitsUpdateRate;					// how often send my hits updates to visible clients
	int m_iSpeedScaleFactor;				// fight skill delay = m_iSpeedScaleFactor / ( (dex + 100) * Weapon Speed )
	int m_iCombatArcheryMovementDelay;		// delay (in tenths of second) to start next swing on Archery skill after the char stop moving
	int m_iCombatDamageEra;					// define damage formula to use on physical combat
	int m_iCombatHitChanceEra;				// define hit chance formula to use on physical combat
	int m_iCombatSpeedEra;					// define swing speed formula to use on physical combat
	WORD m_iSkillPracticeMax;				// max skill level a player can practice on dummies/targets upto
	bool m_iPacketDeathAnimation;			// packet 02c

	// Flags for controlling pvp/pvm behaviour of players
	int m_iCombatFlags;						// combat flags
	int m_iMagicFlags;						// magic flags
	int m_iRacialFlags;						// racial traits flags
	int m_iRevealFlags;						// reveal flags used for SPELL_REVEAL (mostly for backwards).

	// Criminal/Karma
	bool m_fAttackingIsACrime;				// Is attacking (even before hitting) a crime?
	bool m_fGuardsInstantKill;				// Will guards kill instantly or follow normal combat rules?
	bool m_fGuardsOnMurderers;				// should guards be only called on criminals ?
	int m_iGuardLingerTime;					// How long do guards linger about.
	int m_iSnoopCriminal;					// 1 in # chance of getting criminalflagged when succesfully snooping.
	bool m_iTradeWindowSnooping;			// 1 means opening a container in trade window needs to use snooping, 0 direct open.
	int m_iMurderMinCount;					// amount of murders before we get title.
	int m_iMurderDecayTime;					// Length of time (in seconds) to decay a murder count
	bool m_fHelpingCriminalsIsACrime;		// If I help (rez, heal, etc) a criminal, do I become one too?
	bool m_fLootingIsACrime;				// Looting a blue corpse is bad.
	int m_iCriminalTimer;					// How many minutes are criminals flagged for?
	int m_iPlayerKarmaNeutral;				// How much bad karma makes a player neutral?
	int m_iPlayerKarmaEvil;					// How much bad karma makes a player evil?
	int m_iMinKarma;						// Minimum karma level
	int m_iMaxKarma;						// Maximum karma level
	int m_iMaxFame;							// Maximum fame level

	// Other
	bool m_fNoResRobe;
	int m_iLostNPCTeleport;
	int m_iExperimental;
	int m_iOptionFlags;
	int m_iWoolGrowthTime;					// Length of time (in minutes) to regen wool on sheep NPCs
	unsigned int m_iAttackerTimeout;		// Length of time (in seconds) for a char to remember his attacker (used for attacker keyword)
	unsigned int m_iNotoTimeout;			// Length of time (in seconds) to cache character on notoriety list
	unsigned int m_iMaxSkill;

	int m_iDistanceWhisper;
	int m_iDistanceYell;

	CGString m_sSpeechSelf;
	CGString m_sSpeechPet;
	CGString m_sSpeechOther;
	CGString m_sCommandTrigger;

	CGString m_sEventsPet;
	CResourceRefArray m_pEventsPetLink;

	CGString m_sEventsPlayer;
	CResourceRefArray m_pEventsPlayerLink;

	CGString m_sEventsRegion;
	CResourceRefArray m_pEventsRegionLink;

	CGString m_sEventsItem;
	CResourceRefArray m_iEventsItemLink;

	// Third-party tools
	CGString m_sStripPath;
	bool m_fCUOStatus;
	bool m_fUOGStatus;

	int m_iWalkBuffer;
	int m_iWalkRegen;

	int m_iCommandLog;

	bool m_fUsecrypt;
	bool m_fUsenocrypt;

	bool m_fPayFromPackOnly;				// Pay only from main pack?
	int m_iOverSkillMultiply;				// Multiplier to get over skillclass
	bool m_fSuppressCapitals;				// Enable/Disable capital letters suppression

	#define ADVANCEDLOS_DISABLED	0x0
	#define ADVANCEDLOS_PLAYER		0x1
	#define ADVANCEDLOS_NPC			0x2
	int m_iAdvancedLos;

	int m_iFeatureT2A;
	int m_iFeatureLBR;
	int m_iFeatureAOS;
	int m_iFeatureSE;
	int m_iFeatureML;
	int m_iFeatureKR;
	int m_iFeatureSA;
	int m_iFeatureTOL;
	int m_iFeatureExtra;

	int m_iMaxLoopTimes;

	#define STAT_FLAG_NORMAL		0x0		// MAX* status allowed (default)
	#define STAT_FLAG_DENYMAX		0x1		// MAX* denied
	#define STAT_FLAG_DENYMAXP		0x2		//		.. for players
	#define STAT_FLAG_DENYMAXN		0x4		//		.. for npcs
	int m_iStatFlag;

	#define NPC_AI_PATH				0x001	// Enable advanced NPC pathfinding engine (this can significantly increase server CPU usage)
	#define NPC_AI_FOOD				0x002	// Enable basic NPC food search (objects + grass) when hungry
	#define NPC_AI_EXTRA			0x004	// Make NPCs human (brain_human) equip/unequip weapons on combat or light sources at night
	#define NPC_AI_ALWAYSINT		0x008	// Make NPC_AI_PATH consider all NPCs as smart as possible to find better paths
	#define NPC_AI_INTFOOD			0x010	// Enable advanced NPC food search (more intelligent and trusworthy) when hungry
	#define NPC_AI_COMBAT			0x040	// Make NPCs cast good spells in his friends while in combat
	#define NPC_AI_LOOTING			0x100	// Make NPCs loot nearby corpses and items on ground
	#define NPC_AI_MOVEOBSTACLES	0x200	// Make NPCs with CAN=mt_usehands able to move items blocking its way
	#define NPC_AI_PERSISTENTPATH	0x400	// Make NPCs try to follow its target even when it is unreachable instead give up
	#define NPC_AI_THREAT			0x800	// Make NPCs select combat target based on highest threat level (damage done) instead closest distance
	int m_iNpcAi;

	// Experience system
	bool m_bExperienceSystem;
	#define EXP_MODE_RAISE_COMBAT	0x01
	#define EXP_MODE_RAISE_CRAFT	0x02
	#define EXP_MODE_ALLOW_DOWN		0x04
	#define EXP_MODE_DOWN_NOLEVEL	0x08
	#define EXP_MODE_AUTOSET_EXP	0x10
	int m_iExperienceMode;
	int m_iExperienceKoefPVP;
	int m_iExperienceKoefPVM;
	bool m_bLevelSystem;
	#define LEVEL_MODE_LINEAR		0
	#define LEVEL_MODE_DOUBLE		1
	int m_iLevelMode;
	unsigned int m_iLevelNextAt;

	bool m_bAutoResDisp;

	char m_cCommandPrefix;

	PLEVEL_TYPE m_iDefaultCommandLevel;

	// Notoriety colors
	HUE_TYPE m_iColorNotoGood;
	HUE_TYPE m_iColorNotoGuildSame;
	HUE_TYPE m_iColorNotoNeutral;
	HUE_TYPE m_iColorNotoCriminal;
	HUE_TYPE m_iColorNotoGuildWar;
	HUE_TYPE m_iColorNotoEvil;
	HUE_TYPE m_iColorNotoInvul;
	HUE_TYPE m_iColorNotoInvulGameMaster;
	HUE_TYPE m_iColorNotoDefault;

	HUE_TYPE m_iColorInvis;
	HUE_TYPE m_iColorInvisSpell;
	HUE_TYPE m_iColorHidden;

	// Notoriety inheritance
	int m_iPetsInheritNotoriety;

	int m_iClientLoginMaxTries;
	int m_iClientLoginTempBan;
	int m_iMaxShipPlankTeleport;

	// Chat system
	CGString m_sChatStaticChannels;
	int m_iChatFlags;

	// MySQL support
	bool m_bMySql;
	CGString m_sMySqlHost;
	CGString m_sMySqlUser;
	CGString m_sMySqlPass;
	CGString m_sMySqlDB;

	// Network settings
	unsigned int m_iNetworkThreads;			// number of network threads to create
	unsigned int m_iNetworkThreadPriority;	// priority of network threads
	int m_fUseAsyncNetwork;					// 0=normal send, 1=async send, 2=async send for 4.0.0+ only
	int m_iNetMaxPings;						// max pings before blocking an ip
	int m_iNetHistoryTTL;					// time to remember an ip
	int m_iNetMaxPacketsPerTick;			// max packets to send per tick (per queue)
	unsigned int m_iNetMaxLengthPerTick;	// max packet length to send per tick (per queue) (also max length of individual packets)
	int m_iNetMaxQueueSize;					// max packets to hold per queue (comment out for unlimited)
	bool m_fUsePacketPriorities;			// true to prioritise sending packets
	bool m_fUseExtraBuffer;					// true to queue packet data in an extra buffer

	int m_iTooltipCache;
	int m_iTooltipMode;

	int m_iRegenRate[STAT_QTY];
	int m_iTimerCall;
	bool m_bAllowLightOverride;
	CGString m_sZeroPoint;
	bool m_bAllowBuySellAgent;

	bool m_NPCNoFameTitle;

	int m_iMaxPolyStats;

	// End INI file options.

	CResourceScript m_scpIni;						// Keep this around so we can link to it
	CResourceScript m_scpCryptIni;					// Encryption keys are in here

public:
	CResourceScript m_scpTables;

	CStringSortArray m_ResourceList;				// Sections lists

	CStringSortArray m_Obscene;						// Bad Names/Words etc.
	CGObArray<CGString *> m_Fame;					// fame titles (fame.famous)
	CGObArray<CGString *> m_Karma;					// karma titles (karma.wicked)
	CGObArray<CGString *> m_Runes;					// Words of power. (A-Z)

	CGTypedArray<int, int> m_NotoKarmaLevels;		// karma levels for noto titles
	CGTypedArray<int, int> m_NotoFameLevels;		// fame levels for noto titles
	CGObArray<CGString *> m_NotoTitles;				// Noto titles.

	CMultiDefArray m_MultiDefs;						// read from the MUL files. Cached here on demand.

	CObNameSortArray m_SkillNameDefs;				// const CSkillDef* Name sorted
	CGPtrTypeArray<CSkillDef *> m_SkillIndexDefs;	// Defined Skills indexed by number
	CGObArray<CSpellDef *> m_SpellDefs;				// Defined Spells
	CGPtrTypeArray<CSpellDef *> m_SpellDefs_Sorted;	// Defined Spells, in skill order

	CStringSortArray m_PrivCommands[PLEVEL_QTY];	// what command are allowed for a priv level?

public:
	CObNameSortArray m_Servers;						// Servers list. we act like the login server with this.
	CObNameSortArray m_Functions;					// subroutines that can be used in scripts.
	CResourceHashArray m_WebPages;					// These can be linked back to the script.
	CRegionLinks m_RegionDefs;

	// static definition stuff from *TABLE.SCP mostly.
	CGObArray<const CStartLoc *> m_StartDefs;
	CValueCurveDef m_StatAdv[STAT_BASE_QTY];
	CGTypedArray<CPointBase, CPointBase &> m_MoonGates;

private:
	RESOURCE_ID ResourceGetNewID(RES_TYPE restype, LPCTSTR pszName, CVarDefContNum **ppVarNum, bool fNewStyleDef);

public:
	bool r_LoadVal(CScript &s);
	bool r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc);
	bool r_GetRef(LPCTSTR &pszKey, CScriptObj *&pRef);

	bool LoadIni();
	bool Load(bool fResync);
	void Unload(bool fResync);
	void OnTick(bool fNow);

	bool LoadResourceSection(CScript *pScript);
	void LoadSortSpells();
	CResourceDef *ResourceGetDef(RESOURCE_ID_BASE rid) const;

	// Specialized resource accessors.

	bool CanUsePrivVerb(const CScriptObj *pObjTarg, LPCTSTR pszCmd, CTextConsole *pSrc) const;
	PLEVEL_TYPE GetPrivCommandLevel(LPCTSTR pszCmd) const;

	static STAT_TYPE FindStatKey(LPCTSTR pszKey);
	bool IsObscene(LPCTSTR pszText) const;

	CWebPageDef *FindWebPage(LPCTSTR pszPath) const;

	CServerRef Server_GetDef(size_t index);

	const CSpellDef *GetSpellDef(SPELL_TYPE spell) const
	{
		if ( (spell == SPELL_NONE) || !m_SpellDefs.IsValidIndex(static_cast<size_t>(spell)) )
			return NULL;
		return m_SpellDefs[static_cast<size_t>(spell)];
	}
	CSpellDef *GetSpellDef(SPELL_TYPE spell)
	{
		if ( (spell == SPELL_NONE) || !m_SpellDefs.IsValidIndex(static_cast<size_t>(spell)) )
			return NULL;
		return m_SpellDefs[static_cast<size_t>(spell)];
	}

	LPCTSTR GetSkillKey(SKILL_TYPE skill) const
	{
		if ( (skill == SKILL_NONE) || !m_SkillIndexDefs.IsValidIndex(static_cast<size_t>(skill)) )
			return NULL;
		return m_SkillIndexDefs[static_cast<size_t>(skill)]->GetKey();
	}

	bool IsSkillFlag(SKILL_TYPE skill, SKF_TYPE flags) const
	{
		const CSkillDef *pSkillDef = GetSkillDef(skill);
		return (pSkillDef && (pSkillDef->m_dwFlags & flags));
	}

	const CSkillDef *GetSkillDef(SKILL_TYPE skill) const
	{
		if ( (skill == SKILL_NONE) || !m_SkillIndexDefs.IsValidIndex(static_cast<size_t>(skill)) )
			return NULL;
		return m_SkillIndexDefs[static_cast<size_t>(skill)];
	}

	CSkillDef *GetSkillDef(SKILL_TYPE skill)
	{
		if ( (skill == SKILL_NONE) || !m_SkillIndexDefs.IsValidIndex(static_cast<size_t>(skill)) )
			return NULL;
		return m_SkillIndexDefs[static_cast<size_t>(skill)];
	}

	const CSkillDef *FindSkillDef(LPCTSTR pszKey) const
	{
		// Find the skill name in the alpha sorted list
		size_t i = m_SkillNameDefs.FindKey(pszKey);
		if ( i == m_SkillNameDefs.BadIndex() )
			return NULL;
		return static_cast<const CSkillDef *>(m_SkillNameDefs[i]);
	}
	const CSkillDef *SkillLookup(LPCTSTR pszKey);
	SKILL_TYPE FindSkillKey(LPCTSTR pszKey) const;

	int GetSpellEffect(SPELL_TYPE spell, int iSkillval) const;

	LPCTSTR GetRune(TCHAR ch) const
	{
		size_t index = static_cast<size_t>(toupper(ch)) - 'A';
		if ( !m_Runes.IsValidIndex(index) )
			return "?";
		return m_Runes[index]->GetPtr();
	}

	LPCTSTR GetNotoTitle(int index, bool fFemale) const;

	const CGrayMulti *GetMultiItemDefs(CItem *pItem);
	const CGrayMulti *GetMultiItemDefs(ITEMID_TYPE itemid);

	bool IsConsoleCmd(TCHAR ch) const;

	CPointMap GetRegionPoint(LPCTSTR pszCmd) const;		// Decode a teleport location number into X/Y/Z
	CRegionBase *GetRegion(LPCTSTR pszKey) const;		// Find a region with the given name/defname

	int Calc_MaxCarryWeight(const CChar *pChar) const;
	int Calc_CombatAttackSpeed(CChar *pChar, CItem *pWeapon);
	int Calc_CombatChanceToHit(CChar *pChar, CChar *pCharTarg);
	int Calc_StealingItem(CChar *pCharThief, CItem *pItem, CChar *pCharMark);
	bool Calc_CrimeSeen(CChar *pCharThief, CChar *pCharViewer, SKILL_TYPE SkillToSee, bool fBonus);
	int Calc_FameKill(CChar *pKill);
	int Calc_KarmaKill(CChar *pKill, NOTO_TYPE NotoThem);
	int Calc_KarmaScale(int iKarma, int iKarmaChange);
	LPCTSTR Calc_MaptoSextant(CPointMap pt);

	#define SysMessageDefault(pszKey)		SysMessage(g_Cfg.GetDefaultMsg(pszKey))
	LPCTSTR GetDefaultMsg(LPCTSTR pszKey);
	LPCTSTR GetDefaultMsg(int iKeyNum);

	typedef std::map<DWORD, DWORD> KRGumpsMap;
	KRGumpsMap m_mapKRGumps;

	bool SetKRDialogMap(DWORD rid, DWORD dwKRDialogID);
	DWORD GetKRDialogMap(DWORD dwKRDialogID);
	DWORD GetKRDialog(DWORD rid);

	bool GenerateDefname(TCHAR *pszObjectName, size_t iInputLength, LPCTSTR pszPrefix, TCHAR *pszOutput, bool fCheckConflict = true, CVarDefMap *vDefnames = NULL);
	bool DumpUnscriptedItems(CTextConsole *pSrc, LPCTSTR pszFilename);

private:
	CResource(const CResource &copy);
	CResource &operator=(const CResource &other);
} g_Cfg;

///////////////////////////////////////////////////////////
// CDialogDef

class CDialogDef : public CResourceLink
{
public:
	explicit CDialogDef(RESOURCE_ID rid);
	virtual ~CDialogDef() { };

	static const char *m_sClassName;
	static const LPCTSTR sm_szLoadKeys[];

public:
	// Temporary placeholders (valid only during dialog setup)
	CGString m_sControl[1024];
	size_t m_iControlCount;

	CGString m_sText[512];
	size_t m_iTextCount;

	CObjBase *m_pObj;
	int m_x;
	int m_y;
	int m_iOriginX;
	int m_iOriginY;
	WORD m_wPage;
	bool m_fNoDispose;

public:
	bool GumpSetup(int iPage, CClient *pClientSrc, CObjBase *pObj, LPCTSTR pszArgs = "");
	size_t GumpAddText(LPCTSTR pszArgs);

	bool r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc);
	bool r_LoadVal(CScript &s);
	bool r_Verb(CScript &s, CTextConsole *pSrc);

private:
	CDialogDef(const CDialogDef &copy);
	CDialogDef &operator=(const CDialogDef &other);
};

///////////////////////////////////////////////////////////
// CItemTypeDef

class CItemTypeDef : public CResourceLink
{
public:
	static const char *m_sClassName;

	explicit CItemTypeDef(RESOURCE_ID rid) : CResourceLink(rid) { }

public:
	int GetItemType() const;
	bool r_LoadVal(CScript &s);

private:
	CItemTypeDef(const CItemTypeDef &copy);
	CItemTypeDef &operator=(const CItemTypeDef &other);
};

#endif	// _INC_CRESOURCE_H


text:
'use strict';
/**
 * Affix module.
 * @module widgets/Affix
 */
module.exports = Affix;

/**
 * @constructor Affix
 */
function Affix(element) {
    this.$element = $(element);
    console.log('Constructed', this.$element, this.$element.attr('id'));
    return Affix;
}


text:
package jodd.vtor;

import jodd.introspector.PropertyDescriptor;
import jodd.vtor.constraint.Max;
import jodd.vtor.constraint.Min;
import org.junit.Test;

import java.lang.annotation.*;
import java.util.ArrayList;
import java.util.List;

import static junit.framework.TestCase.fail;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

public class ValidationContextTest {

    @Test
    public void testResolveFor() throws Exception {
        //when
        //Class ForCheck1 contains two fields. field1 has two constraints. Second field2 has a non constraint annotation
        ValidationContext context = ValidationContext.resolveFor(ClassForCheck1.class);

        //then
        assertEquals("context must return a map with one element when resolve an object which has one field with constraint annotations", context.map.size(), 1);
        assertNotNull("context must return a map with key field1 when resolve an object which has field with name field1 and constraint annotations", context.map.get("field1"));
        assertNull("context must not return a map with key field2 when resolve an object which has a field with name field2 without constraint annotations", context.map.get("field2"));
        assertEquals("context must return a map with two checks when resolve an object which has a field with two constraint annotations", context.map.get("field1").size(), 2);
    }

    @Test(expected = VtorException.class)
    public void testAddClassThrowVtorException() throws Exception {
        ValidationContext context = new ValidationContext() {
            @Override
            protected <V extends ValidationConstraint> V newConstraint(Class<V> constraint, Class targetType) throws Exception {
                throw new RuntimeException("terrible error");
            }
        };
        context.addClassChecks(ClassForCheck1.class);
        fail("when newConstraint throws some Exception then method should throws VtorException");
    }

    @Test
    public void testCollectPropertyAnnotationChecks(){
        ValidationContext context = spy(new ValidationContext());
        PropertyDescriptor propertyDescriptor = mock(PropertyDescriptor.class);
        List<Check> list = new ArrayList<>();
        context.collectPropertyAnnotationChecks(list, propertyDescriptor);
        verify(context, never()).collectAnnotationChecks(any(List.class), any(Class.class),any(String.class), any(Annotation[].class));
    }

    @Test
    public void testAddClassChecksWithCache() throws Exception {
        ValidationContext context = spy(new ValidationContext());
        try {
            context.addClassChecks(ClassForCheck1.class);
            context.addClassChecks(ClassForCheck1.class);
        } finally {
            context.clearCache();
        }

        //collectProperty must be invoked only for first call of addClassChecks. Two calls for two annotations
        verify(context, times(2)).collectPropertyAnnotationChecks(any(List.class), any(PropertyDescriptor.class));
    }

    private static class ClassForCheck1 {
        @Max(20)
        @Min(10)
        private String field1;

        @NotConstraint
        private String field2;

        public String getField1() {
            return field1;
        }

        public void setField1(String field1) {
            this.field1 = field1;
        }

        public String getField2() {
            return field2;
        }

        public void setField2(String field2) {
            this.field2 = field2;
        }
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface NotConstraint {
    }

}


text:
        <canvas id="gameCanvas" width="1024" height="576"></canvas>

            FPS:


text:
"""Affine transformation matrices

The 3x3 augmented affine transformation matrix for transformations in two
dimensions is illustrated below.

  | x' |   | a  b  c | | x |
  | y' | = | d  e  f | | y |
  | 1  |   | 0  0  1 | | 1 |

The Affine package is derived from Casey Duncan's Planar package. See the
copyright statement below.
"""

#############################################################################
# Copyright (c) 2010 by Casey Duncan
# 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(s) of the copyright holders nor the names of its
#   contributors may be used to endorse or promote products derived from this
#   software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AS IS AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE COPYRIGHT HOLDERS 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.
#############################################################################

from __future__ import division

from collections import namedtuple
import math

__all__ = ['Affine']
__author__ = "Sean Gillies"
__version__ = "1.0"

EPSILON=1e-5
EPSILON2=EPSILON**2

def set_epsilon(epsilon):
    """Set the global absolute error value and rounding limit for approximate
    floating point comparison operations. This value is accessible via the
    :attr:`planar.EPSILON` global variable.

    The default value of ``0.00001`` is suitable for values
    that are in the "countable range". You may need a larger
    epsilon when using large absolute values, and a smaller value
    for very small values close to zero. Otherwise approximate
    comparison operations will not behave as expected.
    """
    EPSILON = float(epsilon)
    EPSILON2 = EPSILON**2

class TransformNotInvertibleError(Exception):
    """The transform could not be inverted"""

# Define assert_unorderable() depending on the language
# implicit ordering rules. This keeps things consistent
# across major Python versions
try:
    3 > ""
except TypeError: # pragma: no cover
    # No implicit ordering (newer Python)
    def assert_unorderable(a, b):
        """Assert that a and b are unorderable"""
        return NotImplemented
else: # pragma: no cover
    # Implicit ordering by default (older Python)
    # We must raise an exception ourselves
    # To prevent nonsensical ordering
    def assert_unorderable(a, b):
        """Assert that a and b are unorderable"""
        raise TypeError("unorderable types: %s and %s"
            % (type(a).__name__, type(b).__name__))

def cached_property(func):
    """Special property decorator that caches the computed
    property value in the object's instance dict the first
    time it is accessed.
    """
    name = func.__name__
    doc = func.__doc__
    def getter(self, name=name):
        try:
            return self.__dict__[name]
        except KeyError:
            self.__dict__[name] = value = func(self)
            return value
    getter.func_name = name
    return property(getter, doc=doc)

def cos_sin_deg(deg):
    """Return the cosine and sin for the given angle
    in degrees, with special-case handling of multiples
    of 90 for perfect right angles
    """
    deg = deg % 360.0
    if deg == 90.0:
        return 0.0, 1.0
    elif deg == 180.0:
        return -1.0, 0
    elif deg == 270.0:
        return 0, -1.0
    rad = math.radians(deg)
    return math.cos(rad), math.sin(rad)

class Affine(
        namedtuple('Affine', ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'))):
    """Two dimensional affine transform for linear mapping from 2D coordinates
    to other 2D coordinates. Parallel lines are preserved by these
    transforms. Affine transforms can perform any combination of translations,
    scales/flips, shears, and rotations.  Class methods are provided to
    conveniently compose transforms from these operations.

    Internally the transform is stored as a 3x3 transformation matrix.  The
    transform may be constructed directly by specifying the first two rows of
    matrix values as 6 floats. Since the matrix is an affine transform, the
    last row is always ``(0, 0, 1)``.

    :param members: 6 floats for the first two matrix rows.
    :type members: float
    """

    def __new__(self, *members):
        if len(members) == 6:
            mat3x3 = [x * 1.0 for x in members] + [0.0, 0.0, 1.0]
            return tuple.__new__(Affine, mat3x3)
        else:
            raise TypeError(
                "Expected 6 number args, got %s" % len(members))

    @classmethod
    def from_gdal(cls, c, a, b, f, d, e):
        members = [a, b, c, d, e, f]
        mat3x3 = [x * 1.0 for x in members] + [0.0, 0.0, 1.0]
        return tuple.__new__(Affine, mat3x3)

    @classmethod
    def identity(cls):
        """Return the identity transform.

        :rtype: Affine
        """
        return identity

    @classmethod
    def translate(cls, xoff, yoff):
        """Create a translation transform from an offset vector.

        :param xoff: Translation x offset.
        :type xoff: float
        :param yoff: Translation y offset.
        :type yoff: float
        :rtype: Affine
        """
        return tuple.__new__(cls,
            (1.0, 0.0, xoff,
             0.0, 1.0, yoff,
             0.0, 0.0, 1.0))

    @classmethod
    def scale(cls, *scaling):
        """Create a scaling transform from a scalar or vector.

        :param scaling: The scaling factor. A scalar value will
            scale in both dimensions equally. A vector scaling
            value scales the dimensions independently.
        :type scaling: float or sequence
        :rtype: Affine
        """
        if len(scaling) == 1:
            sx = sy = float(scaling[0])
        else:
            sx, sy = scaling
        return tuple.__new__(cls,
            (sx, 0.0, 0.0,
             0.0, sy, 0.0,
             0.0, 0.0, 1.0))

    @classmethod
    def shear(cls, x_angle=0, y_angle=0):
        """Create a shear transform along one or both axes.

        :param x_angle: Angle in degrees to shear along the x-axis.
        :type x_angle: float
        :param y_angle: Angle in degrees to shear along the y-axis.
        :type y_angle: float
        :rtype: Affine
        """
        sx = math.tan(math.radians(x_angle))
        sy = math.tan(math.radians(y_angle))
        return tuple.__new__(cls,
            (1.0, sy, 0.0,
             sx, 1.0, 0.0,
             0.0, 0.0, 1.0))

    @classmethod
    def rotate(cls, angle, pivot=None):
        """Create a rotation transform at the specified angle,
        optionally about the specified pivot point.

        :param angle: Rotation angle in degrees
        :type angle: float
        :param pivot: Point to rotate about, if omitted the
            rotation is about the origin.
        :type pivot: sequence
        :rtype: Affine
        """
        ca, sa = cos_sin_deg(angle)
        if pivot is None:
            return tuple.__new__(cls,
                (ca, sa, 0.0,
                -sa, ca, 0.0,
                 0.0, 0.0, 1.0))
        else:
            px, py = pivot
            return tuple.__new__(cls,
                (ca, sa, px - px*ca + py*sa,
                -sa, ca, py - px*sa - py*ca,
                 0.0, 0.0, 1.0))

    @classmethod
    def flip(cls, xflip=None, yflip=None):
        """Create a flip transform for one or two axis.

        :param xflip: Flip the x axis.
        :type xflip: boolean
        :param yflip: Flip the y axis.
        :type yflip: boolean
        :rtype: Affine
        """
        if xflip: xflip = -1
        else: xflip = 1
        if yflip: yflip = -1
        else: yflip = 1

        return tuple.__new__(cls,
            (xflip, 0.0, 0.0,
             0, yflip, 0,
             0.0, 0.0, 1.0))

    def __str__(self):
        """Concise string representation."""
        return ("|% .2f,% .2f,% .2f|\n"
                "|% .2f,% .2f,% .2f|\n"
                "|% .2f,% .2f,% .2f|") % self

    def __repr__(self):
        """Precise string representation."""
        return ("Affine(%r, %r, %r,\n"
                "       %r, %r, %r)") % self[:6]

    def to_gdal(self):
        return (self.c, self.a, self.b, self.f, self.d, self.e)

    @property
    def xoff(self):
        return self.c

    @property
    def yoff(self):
        return self.f

    @property
    def coefficients(self):
        return self[:6]

    @cached_property
    def determinant(self):
        """The determinant of the transform matrix. This value
        is equal to the area scaling factor when the transform
        is applied to a shape.
        """
        a, b, c, d, e, f, g, h, i = self
        return a*e - b*d

    @cached_property
    def is_identity(self):
        """True if this transform equals the identity matrix,
        within rounding limits.
        """
        return self is identity or self.almost_equals(identity)

    @cached_property
    def is_rectilinear(self):
        """True if the transform is rectilinear, i.e., whether a shape would
        remain axis-aligned, within rounding limits, after applying the
        transform.
        """
        a, b, c, d, e, f, g, h, i = self
        return ((abs(a) < EPSILON and abs(e) < EPSILON)
            or (abs(d) < EPSILON and abs(b) < EPSILON))

    @cached_property
    def is_conformal(self):
        """True if the transform is conformal, i.e., if angles between points
        are preserved after applying the transform, within rounding limits.
        This implies that the transform has no effective shear.
        """
        a, b, c, d, e, f, g, h, i = self
        return abs(a*b + d*e) < EPSILON

    @cached_property
    def is_orthonormal(self):
        """True if the transform is orthonormal, which means that the
        transform represents a rigid motion, which has no effective scaling or
        shear. Mathematically, this means that the axis vectors of the
        transform matrix are perpendicular and unit-length.  Applying an
        orthonormal transform to a shape always results in a congruent shape.
        """
        a, b, c, d, e, f, g, h, i = self
        return (self.is_conformal
            and abs(1.0 - (a*a + d*d)) < EPSILON
            and abs(1.0 - (b*b + e*e)) < EPSILON)

    @cached_property
    def is_degenerate(self):
        """True if this transform is degenerate, which means that it will
        collapse a shape to an effective area of zero. Degenerate transforms
        cannot be inverted.
        """
        return abs(self.determinant) < EPSILON

    @property
    def column_vectors(self):
        """The values of the transform as three 2D column vectors"""
        a, b, c, d, e, f, _, _, _ = self
        return (a, d), (b, e), (c, f)

    def almost_equals(self, other):
        """Compare transforms for approximate equality.

        :param other: Transform being compared.
        :type other: Affine
        :return: True if absolute difference between each element
            of each respective tranform matrix < ``EPSILON``.
        """
        for i in (0, 1, 2, 3, 4, 5):
            if abs(self[i] - other[i]) >= EPSILON:
                return False
        return True

    def __gt__(self, other):
        return assert_unorderable(self, other)

    __ge__ = __lt__ = __le__ = __gt__

    # Override from base class. We do not support entrywise
    # addition, subtraction or scalar multiplication because
    # the result is not an affine transform

    def __add__(self, other):
        raise TypeError("Operation not supported")

    __iadd__ = __add__

    def __mul__(self, other):
        """Apply the transform using matrix multiplication, creating a
        resulting object of the same type.  A transform may be applied to
        another transform, a vector, vector array, or shape.

        :param other: The object to transform.
        :type other: Affine, :class:`~planar.Vec2`,
            :class:`~planar.Vec2Array`, :class:`~planar.Shape`
        :rtype: Same as ``other``
        """
        sa, sb, sc, sd, se, sf, _, _, _ = self
        if isinstance(other, Affine):
            oa, ob, oc, od, oe, of, _, _, _ = other
            return tuple.__new__(Affine,
                (sa*oa + sb*od, sa*ob + sb*oe, sa*oc + sb*of + sc,
                 sd*oa + se*od, sd*ob + se*oe, sd*oc + se*of + sf,
                 0.0, 0.0, 1.0))
        else:
            try:
                vx, vy = other
            except Exception:
                return NotImplemented
            return (vx*sa + vy*sd + sc, vx*sb + vy*se + sf)

    def __rmul__(self, other):
        # We should not be called if other is an affine instance
        # This is just a guarantee, since we would potentially
        # return the wrong answer in that case
        assert not isinstance(other, Affine)
        return self.__mul__(other)

    def __imul__(self, other):
        if isinstance(other, Affine) or isinstance(other, tuple):
            return self.__mul__(other)
        else:
            return NotImplemented

    def itransform(self, seq):
        """Transform a sequence of points or vectors in place.

        :param seq: Mutable sequence of :class:`~planar.Vec2` to be
            transformed.
        :returns: None, the input sequence is mutated in place.
        """
        if self is not identity and self != identity:
            sa, sb, sc, sd, se, sf, _, _, _ = self
            for i, (x, y) in enumerate(seq):
                seq[i] = (x*sa + y*sd + sc, x*sb + y*se + sf)

    def __invert__(self):
        """Return the inverse transform.

        :raises: :except:`TransformNotInvertible` if the transform
            is degenerate.
        """
        if self.is_degenerate:
            raise TransformNotInvertibleError(
                "Cannot invert degenerate transform")
        idet = 1.0 / self.determinant
        sa, sb, sc, sd, se, sf, _, _, _ = self
        ra = se * idet
        rb = -sb * idet
        rd = -sd * idet
        re = sa * idet
        return tuple.__new__(Affine,
            (ra, rb, -sc*ra - sf*rb,
             rd, re, -sc*rd - sf*re,
             0.0, 0.0, 1.0))

    __hash__ = tuple.__hash__ # hash is not inherited in Py 3

identity = Affine(1, 0, 0, 0, 1, 0)
"""The identity transform"""

# vim: ai ts=4 sts=4 et sw=4 tw=78


text:
import * as Three from 'three';
import { List } from 'immutable';
import { COLORS } from '../../../shared-style';

export default function (width, height, grid, font) {
  let step = grid.properties.get('step');
  let colors = grid.properties.has('color') ? new List([grid.properties.get('color')]) : grid.properties.get('colors');

  let streak = new Three.Object3D();
  streak.name = 'streak';

  let counter = 0;

  for (let i = 0; i <= width; i += step) {

    let geometry = new Three.Geometry();
    geometry.vertices.push(new Three.Vector3(i, 0, 0));
    geometry.vertices.push(new Three.Vector3(i, 0, -height));
    let color = colors.get(counter % colors.size);
    let material = new Three.LineBasicMaterial({ color });

    if (counter % 5 == 0) {
      let shape = new Three.TextGeometry(('' + (counter * step)), {
        size: 16,
        height: 1,
        font: font
      });

      let wrapper = new Three.MeshBasicMaterial({ color: COLORS.black });
      let words = new Three.Mesh(shape, wrapper);

      words.rotation.x -= Math.PI / 2;
      words.position.set(i - 20, 0, 50);
      streak.add(words);
    }

    streak.add(new Three.LineSegments(geometry, material));
    counter++;
  }
  return streak;
}


text:
package transfer

const (
	perLastTimeLogin int64 = 60 //账号连续登录频率

	timeoutError     = "TIMEOUT_ERROR"
	jsonError        = "JSON_ERROR"
	internalError    = "INTERNAL_ERROR"
	balanceNotEnough = "BALANCE_NOT_ENOUGH"

	urlLogin   = "https://cfquantum.org/api/user/login"
	paramLogin = "json=%7B%22username%22%3A%22%v%22%2C%22password%22%3A%22%v%22%7D&lan=zh_CN&withCredentials=true" // %v  %v

	urlIsLogin = "https://cfquantum.org/api/user/is_login?ts=%v" //判断是否在线

	urlTransfer   = "https://www.cfquantum.org/api/tx/make"
	paramTransfer = "json=%7B%22recipient_addr%22%3A%22%v%22%2C%22selectedCurrency%22%3A%22CFQ%22%2C%22amount%22%3A%22%v%22%2C%22unlock_password%22%3A%22%v%22%2C%22status%22%3A%22prepare%22%7D"
	//json:{"recipient_addr":"ydcf002","selectedCurrency":"CFQ","amount":"1","unlock_password":"cb5678","status":"prepare"}
	//json=%7B%22recipient_addr%22%3A%22ydcf002%22%2C%22selectedCurrency%22%3A%22CFQ%22%2C%22amount%22%3A%221%22%2C%22unlock_password%22%3A%22cb5678%22%2C%22status%22%3A%22prepare%22%7D

	urlBalance = "https://www.cfquantum.org/api/user/balance?ts=%v" //获取余额

	urlTransfertx = "https://www.cfquantum.org/api/tx/account_tx?marker=null&ts=%v" //获取交易历史
)

const (
	// 获取Google验证的key
	urlResetGoogleSecret = "https://cfquantum.org/api/user/reset_google_secret" // POST
	urlUnlock            = "https://www.cfquantum.org/api/user/unlock"
	urlStepAuth          = "https://www.cfquantum.org/api/user/step_auth"
)

// google
type ResetGoogleSecretResponse struct {
	Data struct {
		ErrorCode string `json:"error_code"` // [ACCOUNT_LOCK]账号锁定
	} `json:"data"`
	Result struct {
		Secret string `json:"secret"`
	} `json:"result"`
	Status string `json:"status"` // [failed]失败
}

// 通用错误消息
type stNormalError struct {
	Data struct {
		ErrorCode string `json:"error_code"`
		Message   string `json:"message"`
	} `json:"data"`
	Status string `json:"status"`
}

type transferResult struct {
	Result struct {
		EngineResult string `json:"engine_result"` //: "tesSUCCESS",
	} `json:"result"`
	ID     int64  `json:"id"`     //: 0,
	Type   string `json:"type"`   //: "response",
	Status string `json:"status"` //: "success"
	Data   struct {
		ErrorCode string `json:"error_code"`
	} `json:"data"`
}

type balanceData struct {
	Result struct {
		AccountData struct {
			Balance                 int64 `json:"Balance,string"`
			ContractReservedBalance int64 `json:"ContractReservedBalance,string"`
		} `json:"account_data"`
	} `json:"result"`
	ID     int64  `json:"id"`     //: 0,
	Type   string `json:"type"`   //: "response",
	Status string `json:"status"` //: "success"

	Data struct {
		ErrorCode string `json:"error_code"`
	} `json:"data"`
}

type transferHistory struct {
	Transactions []struct {
		Date int64 `json:"date,string"`
		//Hash      string `json:"hash"`      //:"8F16B40236C7931B5F27C28059A63E303154FADC520E6D706AD1ACB5DCC102CC"
		//Recipient string `json:"recipient"` //:"cfwDX6yjno6BoEim325bd36BGSRz95Q2hb"
		//Sender    string `json:"sender"`    //:"c4uNDNX2ccuQEnRuZB12euyRWJxCi9PPf7"
		Type   string `json:"type"` //:"sent"
		Amount struct {
			Amount float64 `json:"amount,string"` //转账金额
		} `json:"amount"`
		Fee struct {
			Amount float64 `json:"amount,string"` //转账手续费
		} `json:"fee"`
	} `json:"transactions"`
}