text:
import re
import warnings
from typing import Any, Dict, Optional, Sequence, Set

from monai.bundle.config_item import ConfigComponent, ConfigExpression, ConfigItem
from monai.bundle.utils import ID_REF_KEY, ID_SEP_KEY
from monai.utils import allow_missing_reference, look_up_option

__all__ = ["ReferenceResolver"]

class ReferenceResolver:
    """
    Utility class to manage a set of ``ConfigItem`` and resolve the references between them.

    This class maintains a set of ``ConfigItem`` objects and their associated IDs.
    The IDs must be unique within this set. A string in ``ConfigItem``
    starting with ``@`` will be treated as a reference to other ``ConfigItem`` objects by ID.
    Since ``ConfigItem`` may have a nested dictionary or list structure,
    the reference string may also contain a ``#`` character to refer to a substructure by
    key indexing for a dictionary or integer indexing for a list.

    In this class, resolving references is essentially substitution of the reference strings with the
    corresponding python objects. A typical workflow of resolving references is as follows:

        - Add multiple ``ConfigItem`` objects to the ``ReferenceResolver`` by ``add_item()``.
        - Call ``get_resolved_content()`` to automatically resolve the references. This is done (recursively) by:
            - Convert the items to objects, for those do not have references to other items.
                - If it is instantiable, instantiate it and cache the class instance in ``resolved_content``.
                - If it is an expression, evaluate it and save the value in ``resolved_content``.
            - Substitute the reference strings with the corresponding objects.

    Args:
        items: ``ConfigItem``s to resolve, this could be added later with ``add_item()``.

    """

    _vars = "__local_refs"
    sep = ID_SEP_KEY  # separator for key indexing
    ref = ID_REF_KEY  # reference prefix
    # match a reference string, e.g. "@id#key", "@id#key#0", "@_target_#key"
    id_matcher = re.compile(rf"{ref}(?:\w*)(?:{sep}\w*)*")
    # if `allow_missing_reference` and can't find a reference ID, will just raise a warning and don't update the config
    allow_missing_reference = allow_missing_reference

    def __init__(self, items: Optional[Sequence[ConfigItem]] = None):
        # save the items in a dictionary with the `ConfigItem.id` as key
        self.items: Dict[str, Any] = {} if items is None else {i.get_id(): i for i in items}
        self.resolved_content: Dict[str, Any] = {}

    def reset(self):
        """
        Clear all the added `ConfigItem` and all the resolved content.

        """
        self.items = {}
        self.resolved_content = {}

    def is_resolved(self) -> bool:
        return bool(self.resolved_content)

    def add_item(self, item: ConfigItem):
        """
        Add a ``ConfigItem`` to the resolver.

        Args:
            item: a ``ConfigItem``.

        """
        id = item.get_id()
        if id in self.items:
            return
        self.items[id] = item

    def get_item(self, id: str, resolve: bool = False, **kwargs):
        """
        Get the ``ConfigItem`` by id.

        If ``resolve=True``, the returned item will be resolved, that is,
        all the reference strings are substituted by the corresponding ``ConfigItem`` objects.

        Args:
            id: id of the expected config item.
            resolve: whether to resolve the item if it is not resolved, default to False.
            kwargs: keyword arguments to pass to ``_resolve_one_item()``.
                Currently support ``instantiate`` and ``eval_expr``. Both are defaulting to True.
        """
        if resolve and id not in self.resolved_content:
            self._resolve_one_item(id=id, **kwargs)
        return self.items.get(id)

    def _resolve_one_item(self, id: str, waiting_list: Optional[Set[str]] = None, **kwargs):
        """
        Resolve and return one ``ConfigItem`` of ``id``, cache the resolved result in ``resolved_content``.
        If it has unresolved references, recursively resolve the referring items first.

        Args:
            id: id name of ``ConfigItem`` to be resolved.
            waiting_list: set of ids pending to be resolved.
                It's used to detect circular references such as:
                `{"name": "A", "dep": "@B"}` and `{"name": "B", "dep": "@A"}`.
            kwargs: keyword arguments to pass to ``_resolve_one_item()``.
                Currently support ``instantiate``, ``eval_expr`` and ``default``.
                `instantiate` and `eval_expr` are defaulting to True, `default` is the target config item
                if the `id` is not in the config content, must be a `ConfigItem` object.

        """
        if id in self.resolved_content:
            return self.resolved_content[id]
        try:
            item = look_up_option(id, self.items, print_all_options=False, default=kwargs.get("default", "no_default"))
        except ValueError as err:
            raise KeyError(f"id='{id}' is not found in the config resolver.") from err
        item_config = item.get_config()

        if waiting_list is None:
            waiting_list = set()
        waiting_list.add(id)

        for t, v in self.items.items():
            if (
                t not in self.resolved_content
                and isinstance(v, ConfigExpression)
                and v.is_import_statement(v.get_config())
            ):
                self.resolved_content[t] = v.evaluate() if kwargs.get("eval_expr", True) else v
        for d in self.find_refs_in_config(config=item_config, id=id).keys():
            # if current item has reference already in the waiting list, that's circular references
            if d in waiting_list:
                raise ValueError(f"detected circular references '{d}' for id='{id}' in the config content.")
            # check whether the component has any unresolved references
            if d not in self.resolved_content:
                # this referring item is not resolved
                try:
                    look_up_option(d, self.items, print_all_options=False)
                except ValueError as err:
                    msg = f"the referring item `@{d}` is not defined in the config content."
                    if self.allow_missing_reference:
                        warnings.warn(msg)
                        continue
                    else:
                        raise ValueError(msg) from err
                # recursively resolve the reference first
                self._resolve_one_item(id=d, waiting_list=waiting_list, **kwargs)
                waiting_list.discard(d)

        # all references are resolved, then try to resolve current config item
        new_config = self.update_config_with_refs(config=item_config, id=id, refs=self.resolved_content)
        item.update_config(config=new_config)
        # save the resolved result into `resolved_content` to recursively resolve others
        if isinstance(item, ConfigComponent):
            self.resolved_content[id] = item.instantiate() if kwargs.get("instantiate", True) else item
        elif isinstance(item, ConfigExpression):
            run_eval = kwargs.get("eval_expr", True)
            self.resolved_content[id] = (
                item.evaluate(globals={f"{self._vars}": self.resolved_content}) if run_eval else item
            )
        else:
            self.resolved_content[id] = new_config
        return self.resolved_content[id]

    def get_resolved_content(self, id: str, **kwargs):
        """
        Get the resolved ``ConfigItem`` by id.

        Args:
            id: id name of the expected item.
            kwargs: keyword arguments to pass to ``_resolve_one_item()``.
                Currently support ``instantiate``, ``eval_expr`` and ``default``.
                `instantiate` and `eval_expr` are defaulting to True, `default` is the target config item
                if the `id` is not in the config content, must be a `ConfigItem` object.

        """
        return self._resolve_one_item(id=id, **kwargs)

    @classmethod
    def match_refs_pattern(cls, value: str) -> Dict[str, int]:
        """
        Match regular expression for the input string to find the references.
        The reference string starts with ``"@"``, like: ``"@XXX#YYY#ZZZ"``.

        Args:
            value: input value to match regular expression.

        """
        refs: Dict[str, int] = {}
        # regular expression pattern to match "@XXX" or "@XXX#YYY"
        result = cls.id_matcher.findall(value)
        value_is_expr = ConfigExpression.is_expression(value)
        for item in result:
            if value_is_expr or value == item:
                # only check when string starts with "$" or the whole content is "@XXX"
                id = item[len(cls.ref) :]
                refs[id] = refs.get(id, 0) + 1
        return refs

    @classmethod
    def update_refs_pattern(cls, value: str, refs: Dict) -> str:
        """
        Match regular expression for the input string to update content with the references.
        The reference part starts with ``"@"``, like: ``"@XXX#YYY#ZZZ"``.
        References dictionary must contain the referring IDs as keys.

        Args:
            value: input value to match regular expression.
            refs: all the referring components with ids as keys, default to `None`.

        """
        # regular expression pattern to match "@XXX" or "@XXX#YYY"
        result = cls.id_matcher.findall(value)
        value_is_expr = ConfigExpression.is_expression(value)
        for item in result:
            ref_id = item[len(cls.ref) :]  # remove the ref prefix "@"
            if ref_id not in refs:
                msg = f"can not find expected ID '{ref_id}' in the references."
                if cls.allow_missing_reference:
                    warnings.warn(msg)
                    continue
                else:
                    raise KeyError(msg)
            if value_is_expr:
                # replace with local code, `{"__local_refs": self.resolved_content}` will be added to
                # the `globals` argument of python `eval` in the `evaluate`
                value = value.replace(item, f"{cls._vars}['{ref_id}']")
            elif value == item:
                # the whole content is "@XXX", it will avoid the case that regular string contains "@"
                value = refs[ref_id]
        return value

    @classmethod
    def find_refs_in_config(cls, config, id: str, refs: Optional[Dict[str, int]] = None) -> Dict[str, int]:
        """
        Recursively search all the content of input config item to get the ids of references.
        References mean: the IDs of other config items (``"@XXX"`` in this config item), or the
        sub-item in the config is `instantiable`, or the sub-item in the config is `expression`.
        For `dict` and `list`, recursively check the sub-items.

        Args:
            config: input config content to search.
            id: ID name for the input config item.
            refs: dict of the ID name and count of found references, default to `None`.

        """
        refs_: Dict[str, int] = refs or {}
        if isinstance(config, str):
            for id, count in cls.match_refs_pattern(value=config).items():
                refs_[id] = refs_.get(id, 0) + count
        if not isinstance(config, (list, dict)):
            return refs_
        for k, v in config.items() if isinstance(config, dict) else enumerate(config):
            sub_id = f"{id}{cls.sep}{k}" if id != "" else f"{k}"
            if ConfigComponent.is_instantiable(v) or ConfigExpression.is_expression(v) and sub_id not in refs_:
                refs_[sub_id] = 1
            refs_ = cls.find_refs_in_config(v, sub_id, refs_)
        return refs_

    @classmethod
    def update_config_with_refs(cls, config, id: str, refs: Optional[Dict] = None):
        """
        With all the references in ``refs``, update the input config content with references
        and return the new config.

        Args:
            config: input config content to update.
            id: ID name for the input config.
            refs: all the referring content with ids, default to `None`.

        """
        refs_: Dict = refs or {}
        if isinstance(config, str):
            return cls.update_refs_pattern(config, refs_)
        if not isinstance(config, (list, dict)):
            return config
        ret = type(config)()
        for idx, v in config.items() if isinstance(config, dict) else enumerate(config):
            sub_id = f"{id}{cls.sep}{idx}" if id != "" else f"{idx}"
            if ConfigComponent.is_instantiable(v) or ConfigExpression.is_expression(v):
                updated = refs_[sub_id]
                if ConfigComponent.is_instantiable(v) and updated is None:
                    # the component is disabled
                    continue
            else:
                updated = cls.update_config_with_refs(v, sub_id, refs_)
            ret.update({idx: updated}) if isinstance(ret, dict) else ret.append(updated)
        return ret


text:
"""SCons.Tool.cyglink

Customization of gnulink for Cygwin (http://www.cygwin.com/)

There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.

"""

from __future__ import absolute_import, print_function

import re
import os

import SCons.Action
import SCons.Util
import SCons.Tool

#MAYBE:  from . import gnulink
from . import gnulink
from . import link

def _lib_generator(target, source, env, for_signature, **kw):
    try: cmd = kw['cmd']
    except KeyError: cmd = SCons.Util.CLVar(['$SHLINK'])

    try: vp = kw['varprefix']
    except KeyError: vp = 'SHLIB'

    dll = env.FindIxes(target, '%sPREFIX' % vp, '%sSUFFIX' % vp)
    if dll: cmd.extend(['-o', dll])

    cmd.extend(['$SHLINKFLAGS', '$__%sVERSIONFLAGS' % vp, '$__RPATH'])

    implib = env.FindIxes(target, 'IMPLIBPREFIX', 'IMPLIBSUFFIX')
    if implib:
        cmd.extend([
            '-Wl,--out-implib='+implib.get_string(for_signature),
            '-Wl,--export-all-symbols',
            '-Wl,--enable-auto-import',
            '-Wl,--whole-archive', '$SOURCES',
            '-Wl,--no-whole-archive', '$_LIBDIRFLAGS', '$_LIBFLAGS'
            ])
    else:
        cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS'])

    return [cmd]

def shlib_generator(target, source, env, for_signature):
    return _lib_generator(target, source, env, for_signature,
                          varprefix='SHLIB',
                          cmd = SCons.Util.CLVar(['$SHLINK']))

def ldmod_generator(target, source, env, for_signature):
    return _lib_generator(target, source, env, for_signature,
                          varprefix='LDMODULE',
                          cmd = SCons.Util.CLVar(['$LDMODULE']))

def _lib_emitter(target, source, env, **kw):
    Verbose = False

    if Verbose:
        print("_lib_emitter: target[0]=%r" % target[0].get_path())

    try: vp = kw['varprefix']
    except KeyError: vp = 'SHLIB'

    try: libtype = kw['libtype']
    except KeyError: libtype = 'ShLib'

    dll = env.FindIxes(target, '%sPREFIX' % vp, '%sSUFFIX' % vp)
    no_import_lib = env.get('no_import_lib', 0)

    if Verbose:
        print("_lib_emitter: dll=%r" % dll.get_path())

    if not dll or len(target) > 1:
        raise SCons.Errors.UserError("A shared library should have exactly one target with the suffix: %s" % env.subst("$%sSUFFIX" % vp))

    # Remove any "lib" after the prefix
    pre = env.subst('$%sPREFIX' % vp)
    if dll.name[len(pre):len(pre)+3] == 'lib':
        dll.name = pre + dll.name[len(pre)+3:]

    if Verbose:
        print("_lib_emitter: dll.name=%r" % dll.name)

    orig_target = target
    target = [env.fs.File(dll)]
    target[0].attributes.shared = 1

    if Verbose:
        print("_lib_emitter: after target=[env.fs.File(dll)]: target[0]=%r" % target[0].get_path())

    # Append an import lib target
    if not no_import_lib:
        # Create list of target libraries as strings
        target_strings = env.ReplaceIxes(orig_target[0],
                                         '%sPREFIX' % vp, '%sSUFFIX' % vp,
                                         'IMPLIBPREFIX', 'IMPLIBSUFFIX')
        if Verbose:
            print("_lib_emitter: target_strings=%r" % target_strings)

        implib_target = env.fs.File(target_strings)
        if Verbose:
            print("_lib_emitter: implib_target=%r" % implib_target.get_path())
        implib_target.attributes.shared = 1
        target.append(implib_target)

    symlinks = SCons.Tool.ImpLibSymlinkGenerator(env, implib_target,
                                                 implib_libtype=libtype,
                                                 generator_libtype=libtype+'ImpLib')
    if Verbose:
        print("_lib_emitter: implib symlinks=%r" % SCons.Tool.StringizeLibSymlinks(symlinks))
    if symlinks:
        SCons.Tool.EmitLibSymlinks(env, symlinks, implib_target, clean_targets = target[0])
        implib_target.attributes.shliblinks = symlinks

    return (target, source)

def shlib_emitter(target, source, env):
    return _lib_emitter(target, source, env, varprefix='SHLIB', libtype='ShLib')

def ldmod_emitter(target, source, env):
    return _lib_emitter(target, source, env, varprefix='LDMODULE', libtype='LdMod')

def _versioned_lib_suffix(env, suffix, version):
    """Generate versioned shared library suffix from a unversioned one.
       If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll'"""
    Verbose = False
    if Verbose:
        print("_versioned_lib_suffix: suffix= ", suffix)
        print("_versioned_lib_suffix: version= ", version)
    cygversion = re.sub(r'\.', '-', version)
    if not suffix.startswith('-' + cygversion):
        suffix = '-' + cygversion + suffix
    if Verbose:
        print("_versioned_lib_suffix: return suffix= ", suffix)
    return suffix

def _versioned_implib_name(env, libnode, version, prefix, suffix, **kw):
    return link._versioned_lib_name(env, libnode, version, prefix, suffix,
                                    SCons.Tool.ImpLibPrefixGenerator,
                                    SCons.Tool.ImpLibSuffixGenerator,
                                    implib_libtype=kw['libtype'])

def _versioned_implib_symlinks(env, libnode, version, prefix, suffix, **kw):
    """Generate link names that should be created for a versioned shared library.
       Returns a list in the form [ (link, linktarget), ... ]
    """
    Verbose = False

    if Verbose:
        print("_versioned_implib_symlinks: libnode=%r" % libnode.get_path())
        print("_versioned_implib_symlinks: version=%r" % version)

    try: libtype = kw['libtype']
    except KeyError: libtype = 'ShLib'

    linkdir = os.path.dirname(libnode.get_path())
    if Verbose:
        print("_versioned_implib_symlinks: linkdir=%r" % linkdir)

    name = SCons.Tool.ImpLibNameGenerator(env, libnode,
                                          implib_libtype=libtype,
                                          generator_libtype=libtype+'ImpLib')
    if Verbose:
        print("_versioned_implib_symlinks: name=%r" % name)

    major = version.split('.')[0]

    link0 = env.fs.File(os.path.join(linkdir, name))
    symlinks = [(link0, libnode)]

    if Verbose:
        print("_versioned_implib_symlinks: return symlinks=%r" % SCons.Tool.StringizeLibSymlinks(symlinks))

    return symlinks

shlib_action = SCons.Action.Action(shlib_generator, generator=1)
ldmod_action = SCons.Action.Action(ldmod_generator, generator=1)

def generate(env):
    """Add Builders and construction variables for cyglink to an Environment."""
    gnulink.generate(env)

    env['LINKFLAGS']   = SCons.Util.CLVar('-Wl,-no-undefined')

    env['SHLINKCOM'] = shlib_action
    env['LDMODULECOM'] = ldmod_action
    env.Append(SHLIBEMITTER = [shlib_emitter])
    env.Append(LDMODULEEMITTER = [ldmod_emitter])

    env['SHLIBPREFIX']         = 'cyg'
    env['SHLIBSUFFIX']         = '.dll'

    env['IMPLIBPREFIX']        = 'lib'
    env['IMPLIBSUFFIX']        = '.dll.a'

    # Variables used by versioned shared libraries
    env['_SHLIBVERSIONFLAGS']      = '$SHLIBVERSIONFLAGS'
    env['_LDMODULEVERSIONFLAGS']   = '$LDMODULEVERSIONFLAGS'

    # SHLIBVERSIONFLAGS and LDMODULEVERSIONFLAGS are same as in gnulink...

    # LINKCALLBACKS are NOT inherited from gnulink
    env['LINKCALLBACKS'] = {
        'VersionedShLibSuffix'          : _versioned_lib_suffix,
        'VersionedLdModSuffix'          : _versioned_lib_suffix,
        'VersionedImpLibSuffix'         : _versioned_lib_suffix,
        'VersionedShLibName'            : link._versioned_shlib_name,
        'VersionedLdModName'            : link._versioned_ldmod_name,
        'VersionedShLibImpLibName'      : lambda *args: _versioned_implib_name(*args, libtype='ShLib'),
        'VersionedLdModImpLibName'      : lambda *args: _versioned_implib_name(*args, libtype='LdMod'),
        'VersionedShLibImpLibSymlinks'  : lambda *args: _versioned_implib_symlinks(*args, libtype='ShLib'),
        'VersionedLdModImpLibSymlinks'  : lambda *args: _versioned_implib_symlinks(*args, libtype='LdMod'),
    }

    # these variables were set by gnulink but are not used in cyglink
    try: del env['_SHLIBSONAME']
    except KeyError: pass
    try: del env['_LDMODULESONAME']
    except KeyError: pass

def exists(env):
    return gnulink.exists(env)

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:

redpajama_set_name: RedPajamaGithub


text:
module Hickey
  module DomainDetector
    module Actions
      def self.included(base)
        base.send(:alias_method_chain, :visit_hash, :find_or_create_actions)
      end

      def visit_hash_with_find_or_create_actions(attribute, record)
        case record.keys.first
        when :find
          record = record[:find]
          attribute = find_action(attribute, record)
        when :create
          record = record[:create]
        when :find_or_create
          record = record[:find_or_create]
          if find_attribute = find_action(attribute, record)
            attribute = find_attribute
          end
        end
        visit_hash_without_find_or_create_actions(attribute, record)
      end

      def find_action(attribute, record)
        model_type = compute_type(attribute, record)
        conditions = record.inject({}) do |c, entity|
          key, value = entity
          unless [Hash, Array].include?(value.class)
            #added if to filter column name for fixing hickey on acitverecord 1.2.6
            c[key] = value if model_type.column_names.include?(key.to_s)
          end
          c
        end
        compute_type(attribute, record).find(:first, :conditions => conditions)
      end
    end
  end
end


text:
#ifndef _L4_DND_HANDLER
#define _L4_DND_HANDLER

#include "wimax_osal_types.h"

BOOL L4DnDHndlr_IsMonFiltered(UINT16 type);
BOOL L4DnDHndlr_PostMon(UINT8* buffer, UINT16 type, UINT16 length);

#endif //_L4_DND_HANDLER


text:
layout: posts_by_tag
tag: algorithm
title: Posts tagged Other
---


text:
java driver for metagraph

## 1. dependency

```
<dependency>
    <groupId>io.openmg</groupId>
    <artifactId>metagraph-driver-java</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
```

## 2. 用例

> `Metagraph`是一个重量级对象,用户在使用时,只需构建一个对象即可。

### 2.1 打开图
```
Metagraph metagraph = new Metagraph("http://localhost:8080", "username", "password");
Graph graph = metagraph.open("graphId");
String graphResponse = graph.gremlin("g.V()", "tp");
```

### 2.2 创建图

```
Metagraph metagraph = new Metagraph("http://localhost:8080", "username", "password");
Graph graph = metagraph.create("testGraph1");
```

### 2.3 获取所有的图

```
Metagraph metagraph = new Metagraph(new URL("http://localhost:8080"), "username", "password");
GraphsResponse graphs = metagraph.graphs();

```

### 2.4 执行traversal语句

```
Metagraph metagraph = new Metagraph("http://localhost:8080", "username", "password");
Graph graph = metagraph.open("graphId");
String graphResponse = graph.gremlin("g.V()", "tp");
```


text:
using System;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
using DG.DeExtensions;

namespace EA4S
{
    public enum ContinueScreenMode
    {
        /// Just background, just touch the screen to continue
        FullscreenBg,
        /// Button with no background, that needs to be clicked directly
        Button,
        /// Button with no background, the whole screen can be clicked (button will be placed on the side)
        ButtonFullscreen,
        /// Button with background, that needs to be clicked directly
        ButtonWithBg,
        /// Button with background, the whole screen can be clicked
        ButtonWithBgFullscreen
    }

    public class ContinueScreen : MonoBehaviour
    {
        [Header("Settings")]
        public ButtonSnapshot CenterSnapshot;
        public ButtonSnapshot SideSnapshot;
        [Header("References")]
        public Button Bg;
        public Button BtContinue;
        public RectTransform IcoContinue;

        public static bool IsShown { get; private set; }

        RectTransform btRT;
        ContinueScreenMode currMode;
        Action onContinueCallback;
        bool clicked;
        Tween showTween, showBgTween, btClickTween, btIdleTween;

        // ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
        // ■■■ PUBLIC METHODS

        ///
        /// Call this to show/hide the continue screen.
        ///
        /// <param name="_onContinue">Eventual callback to call when the user clicks to continue</param>
        /// <param name="_mode">Mode</param>
        public static void Show(Action _onContinue, ContinueScreenMode _mode = ContinueScreenMode.ButtonWithBg)
        {
            GlobalUI.Init();
            GlobalUI.ContinueScreen.DoShow(_onContinue, _mode);
        }

        void DoShow(Action _onContinue, ContinueScreenMode _mode = ContinueScreenMode.ButtonWithBg)
        {
            Debug.Log("ContinueScreen DoShow " + _onContinue);
            IsShown = true;
            clicked = false;
            currMode = _mode;
            onContinueCallback = _onContinue;
            Bg.gameObject.SetActive(_mode != ContinueScreenMode.Button);
            BtContinue.gameObject.SetActive(_mode != ContinueScreenMode.FullscreenBg);
            if (btIdleTween != null) btIdleTween.Rewind();
            btIdleTween = btRT.DOAnchorPosX(10, 0.5f).SetRelative().SetEase(Ease.InOutQuad).SetLoops(-1, LoopType.Yoyo)
                .SetUpdate(true).SetAutoKill(false).Pause();
            if (_mode == ContinueScreenMode.ButtonFullscreen) {
                SideSnapshot.Apply(btRT, IcoContinue);
            } else {
                CenterSnapshot.Apply(btRT, IcoContinue);
            }
            showBgTween.Rewind();
            showTween.Restart();
            if (_mode != ContinueScreenMode.Button && _mode != ContinueScreenMode.ButtonFullscreen)
                showBgTween.PlayForward();
            this.gameObject.SetActive(true);
        }

        ///
        /// Closes the continue screen without dispatching any callback
        ///
        /// <param name="_immediate">If TRUE, immmediately closes the screen without animation</param>
        public static void Close(bool _immediate)
        {
            GlobalUI.ContinueScreen.DoClose(_immediate);
        }

        void DoClose(bool _immediate)
        {
            if (!IsShown && !_immediate)
                return;

            IsShown = false;
            clicked = false;
            onContinueCallback = null;
            if (_immediate) {
                showTween.Rewind();
                showBgTween.Rewind();
                this.gameObject.SetActive(false);
            } else
                showTween.PlayBackwards();
            showBgTween.PlayBackwards();
        }

        // ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
        // ■■■ INTERNAL

        void Awake()
        {
            btRT = BtContinue.GetComponent<RectTransform>();
            CenterSnapshot.Apply(btRT, IcoContinue);

            const float duration = 0.5f;
            showTween = btRT.DOScale(0.1f, duration).From().SetEase(Ease.OutBack)
                .SetUpdate(true).SetAutoKill(false).Pause()
                .OnPlay(() => this.gameObject.SetActive(true))
                .OnRewind(() => {
                    this.gameObject.SetActive(false);
                    btIdleTween.Rewind();
                })
                .OnComplete(() => {
                    if (currMode == ContinueScreenMode.ButtonFullscreen)
                        btIdleTween.Restart();
                });

            showBgTween = Bg.image.DOFade(0, duration).From().SetEase(Ease.InSine)
                .SetUpdate(true).SetAutoKill(false).Pause();

            btClickTween = btRT.DOPunchRotation(new Vector3(0, 0, 20), 0.3f, 12, 0.5f).SetUpdate(true).SetAutoKill(false).Pause()
                .OnComplete(Continue);

//            btIdleTween = btRT.DOAnchorPosX(10, 0.5f).SetRelative().SetEase(Ease.InOutQuad).SetLoops(-1, LoopType.Yoyo)
//                .SetUpdate(true).SetAutoKill(false).Pause();

            CenterSnapshot.Apply(btRT, IcoContinue);
            this.gameObject.SetActive(false);

            // Listeners
            BtContinue.onClick.AddListener(() => OnClick(true));
            Bg.onClick.AddListener(() => OnClick(false));
        }

        void OnDestroy()
        {
            showTween.Kill();
            showBgTween.Kill();
            btClickTween.Kill();
            btIdleTween.Kill();
            BtContinue.onClick.RemoveAllListeners();
            Bg.onClick.RemoveAllListeners();
        }

        void Continue()
        {
            if (onContinueCallback != null)
                onContinueCallback();
            showTween.PlayBackwards();
            showBgTween.PlayBackwards();
        }

        void OnClick(bool _isButton)
        {
            if (clicked)
                return;

            if (_isButton || currMode == ContinueScreenMode.ButtonWithBgFullscreen || currMode == ContinueScreenMode.ButtonFullscreen) {
                clicked = true;
                btClickTween.Restart();
            } else if (currMode == ContinueScreenMode.FullscreenBg) {
                clicked = true;
                Continue();
            }
            if (clicked) {
                btIdleTween.Pause();
                AudioManager.I.PlaySfx(Sfx.UIButtonClick);
            }
        }
    }

    // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
    // ███ CLASS ███████████████████████████████████████████████████████████████████████████████████████████████████████████
    // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████

    [System.Serializable]
    public struct ButtonSnapshot
    {
        public Vector2 AnchoredPos, AnchorMin, AnchorMax, SizeDelta;
        public Vector2 IcoAnchoredPos;

        public ButtonSnapshot(Vector2 _anchoredPos, Vector2 _anchorMin, Vector2 _anchorMax, Vector2 _sizeDelta, Vector2 _icoAnchoredPos)
        {
            AnchoredPos = _anchoredPos;
            AnchorMin = _anchorMin;
            AnchorMax = _anchorMax;
            SizeDelta = _sizeDelta;
            IcoAnchoredPos = _icoAnchoredPos;
        }

        public void Apply(RectTransform _bt, RectTransform _ico)
        {
            _bt.anchorMin = AnchorMin;
            _bt.anchorMax = AnchorMax;
            _bt.anchoredPosition = AnchoredPos;
            _bt.sizeDelta = SizeDelta;
            _ico.anchoredPosition = IcoAnchoredPos;
        }
    }
}


text:
using content::BrowserContext;

namespace extensions {

// static
ProcessMap* ProcessMapFactory::GetForBrowserContext(BrowserContext* context) {
  return static_cast<ProcessMap*>(
      GetInstance()->GetServiceForBrowserContext(context, true));
}

// static
ProcessMapFactory* ProcessMapFactory::GetInstance() {
  return base::Singleton<ProcessMapFactory>::get();
}

ProcessMapFactory::ProcessMapFactory()
    : BrowserContextKeyedServiceFactory(
          "ProcessMap",
          BrowserContextDependencyManager::GetInstance()) {
  // No dependencies on other services.
}

ProcessMapFactory::~ProcessMapFactory() {}

KeyedService* ProcessMapFactory::BuildServiceInstanceFor(
    BrowserContext* context) const {
  ProcessMap* process_map = new ProcessMap();
  process_map->set_is_lock_screen_context(
      ExtensionsBrowserClient::Get()->IsLockScreenContext(context));
  return process_map;
}

BrowserContext* ProcessMapFactory::GetBrowserContextToUse(
    BrowserContext* context) const {
  // Redirected in incognito.
  return ExtensionsBrowserClient::Get()->GetOriginalContext(context);
}

}  // namespace extensions


text:
using System;

namespace MvvmCross.Plugins.Network.Rest
{
    public interface IMvxRestClient
    {
        void ClearSetting(string key);

        void SetSetting(string key, object value);

        IMvxAbortable MakeRequest(MvxRestRequest restRequest, Action<MvxRestResponse> successAction,
                         Action<Exception> errorAction);

        IMvxAbortable MakeRequest(MvxRestRequest restRequest, Action<MvxStreamRestResponse> successAction,
                         Action<Exception> errorAction);
    }
}


text:
package io.sundr.codegen.model;

import io.sundr.builder.Editable;

public class EditableWildcardRef extends WildcardRef implements Editable<WildcardRefBuilder> {

    public EditableWildcardRef() {
        super();
    }

    public EditableWildcardRef(java.util.List<TypeRef> bounds, java.util.Map<AttributeKey, Object> attributes) {
        super(bounds, attributes);
    }

    public WildcardRefBuilder edit() {
        return new WildcardRefBuilder(this);
    }

}


text:
using NMaier.SimpleDlna.Utilities;

namespace NMaier.SimpleDlna.Server.Views
{
  internal abstract class BaseView : Logging, IView
  {
    public abstract string Description { get; }

    public abstract string Name { get; }

    public virtual void SetParameters(AttributeCollection parameters)
    {
    }

    public override string ToString()
    {
      return string.Format("{0} - {1}", Name, Description);
    }

    public abstract IMediaFolder Transform(IMediaFolder root);
  }
}


text:
<?php

namespace Application\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Delete;
use Zend\Db\Sql\Update;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Expression;
use Zend\Paginator\Paginator;
use Zend\Db\ResultSet\ResultSet;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Db\Sql\Where;
use Zend\Db\Adapter\Driver\Pdo\Result;

class ProductCategoriesTable extends BasicTableAdapter {

    protected $sTable = 'ProductCategories';

    public function updateCatagoriesTable()
    {
        //echo "test"; die;
        $dbAdpr = $this->getDBAdapter();
        $dbAdpr->query( "TRUNCATE ProductCategories_for_processing;" )->execute();

        # CLOTHING -> OUTERWEAR	 -> DENIM
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '13', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value in ('428','434','417','438','425')
        	INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Fabric' AND p3.value = 'Denim'
        	WHERE p1.TYPE = 'categories' AND p1.value = '6'
        	UNION
        	select distinct productUID from ProductAttributes where TYPE = 'categories' AND value = '428' AND productUID NOT IN (
        		SELECT distinct p1.productUID
        		FROM ProductAttributes  p1
        		INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('428','434','417','438','425','440','439')
        		INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Fabric' AND p3.value IN ('Leather','Suede','Leatherette','Faux Leather','Pleather','Faux Suede')
        		WHERE p1.TYPE = 'categories' AND p1.value = '6'
        	)
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> OUTERWEAR	 -> LEATHER & SUEDE
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '15', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('428','434','417','438','425','440','439')
        	INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Fabric' AND p3.value IN ('Leather','Suede','Leatherette','Faux Leather','Pleather','Faux Suede')
        	WHERE p1.TYPE = 'categories' AND p1.value = '6'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> OUTERWEAR	 -> OVERCOATS & TRENCH COATS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '16', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('415','420','424','446','419','445')
        	WHERE p1.TYPE = 'categories' AND p1.value = '6'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> OUTERWEAR	 -> JACKETS & COATS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '14', 1 from (
        	SELECT distinct productUID FROM ProductAttributes  WHERE TYPE = 'categories' AND value = '6' AND productUID NOT IN (
        		SELECT distinct p1.productUID
        		FROM ProductAttributes  p1
        		INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value in ('428','434','417','438','425')
        		INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Fabric' AND p3.value = 'Denim'
        		WHERE p1.TYPE = 'categories' AND p1.value = '6'
        		UNION
        		select distinct productUID from ProductAttributes where TYPE = 'categories' AND value = '428' AND productUID NOT IN (
        			SELECT distinct p1.productUID
        			FROM ProductAttributes  p1
        			INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('428','434','417','438','425','440','439')
        			INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Fabric' AND p3.value IN ('Leather','Suede','Leatherette','Faux Leather','Pleather','Faux Suede')
        			WHERE p1.TYPE = 'categories' AND p1.value = '6'
        		)
        		UNION
        		SELECT distinct p1.productUID
        		FROM ProductAttributes  p1
        		INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('428','434','417','438','425','440','439')
        		INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Fabric' AND p3.value IN ('Leather','Suede','Leatherette','Faux Leather','Pleather','Faux Suede')
        		WHERE p1.TYPE = 'categories' AND p1.value = '6'
        		UNION
        		SELECT distinct p1.productUID
        		FROM ProductAttributes  p1
        		INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('415','420','424','446','419','445')
        		WHERE p1.TYPE = 'categories' AND p1.value = '6'
        		UNION
        		SELECT distinct p1.productUID
        		FROM ProductAttributes  p1
        		INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('432','430','436','442','444','416','1890','427','429','431','1140','1142','1149','7997',
        		'433','435','437','441','443','1145','1147','1153','7997','7999','7988')
        		INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Feature' AND p3.value IN ('ACTIVEWEAR')
        		WHERE p1.TYPE = 'categories' AND p1.value = '6'
        	)
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> TOPS	 -> DRESS SHIRT
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '17', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('1123','1125')
        	WHERE p1.TYPE = 'categories' AND p1.value = '7'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> TOPS	 -> T-SHIRT
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '18', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('1127','1129','1133','7992')
        	WHERE p1.TYPE = 'categories' AND p1.value = '7'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> TOPS	 -> LONGSLEEVE
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '19', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('1128','1130','1135','1197')
        	WHERE p1.TYPE = 'categories' AND p1.value = '7'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> TOPS	 -> SLEEVELESS SHIRT
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '20', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('1132','1146','1152')
        	WHERE p1.TYPE = 'categories' AND p1.value = '7'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> TOPS -> SWEATER
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '21', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('1145','1139','1145','7993','7994','7995','7996')
        	WHERE p1.TYPE = 'categories' AND p1.value = '7'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> TOPS	 -> CARDIGANS & ZIP UPS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '22', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value in ('431','1140','1142','1149','7997','7998','7999','8000')
        	WHERE p1.TYPE = 'categories' AND p1.value = '7'
        	UNION
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value in ('1147','427','1154','1139','1141','1145','7993','7994','7995','7996')
        	INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Fabric' AND p3.value IN ('Half Zipper','Full Zipper')
        	WHERE p1.TYPE = 'categories' AND p1.value = '7'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> TOPS -> SWEATSHIRT & HOODIES
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '23', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('1136','1143','1148','1154')
        	WHERE p1.TYPE = 'categories' AND p1.value = '7'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> SUITS & TUXEDOS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '7', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('15','36','1886','1887','2648','1888')
        	WHERE p1.TYPE = 'categories' AND p1.value = '36'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> SPORT JACKETS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '8', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('1889','416','1890','1891')
        	WHERE p1.TYPE = 'categories' AND p1.value = '36'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> BOTTOMS -> JEANS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '24', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('2605','2635','2661')
        	WHERE p1.TYPE = 'categories' AND p1.value = '37'
        	UNION
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'Fabric' AND p2.value IN ('Denim')
        	WHERE p1.TYPE = 'categories' AND p1.value = '37'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> BOTTOMS -> DRESS PANTS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '25', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('2606','2644','2671','2673','2613','2660')
        	WHERE p1.TYPE = 'categories' AND p1.value = '37'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> BOTTOMS -> KHAKIS & CHINOS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '26', 1 from (
        	SELECT distinct productUID FROM ProductAttributes  WHERE TYPE = 'categories' AND value = '37' AND productUID NOT IN (
        		SELECT distinct p1.productUID
        		FROM ProductAttributes  p1
        		INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('2605','2635','2661')
        		WHERE p1.TYPE = 'categories' AND p1.value = '37'
        		UNION
        		SELECT distinct p1.productUID
        		FROM ProductAttributes  p1
        		INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'Fabric' AND p2.value IN ('Denim')
        		WHERE p1.TYPE = 'categories' AND p1.value = '37'
        		UNION
        		SELECT distinct p1.productUID
        		FROM ProductAttributes  p1
        		INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('2606','2644','2671','2673','2613','2660')
        		WHERE p1.TYPE = 'categories' AND p1.value = '37'
        	)
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> BOTTOMS -> SHORTS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        	select productUID, '27', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('3371','3375')
        	WHERE p1.TYPE = 'categories' AND p1.value = '54'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> UNDERWEAR & SOCKS -> UNDERWEAR
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '28', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	WHERE p1.TYPE = 'categories' AND p1.value IN ('69')
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> UNDERWEAR & SOCKS -> SOCKS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '29', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	WHERE p1.TYPE = 'categories' AND p1.value IN ('70')
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> ACTIVEWEAR -> JACKETS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '30', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('432','430','436','442','444','416','1890','427','429','431','1140','1142','1149','7997',
        	'433','435','437','441','443','1145','1147','1153','7997','7999','7988')
        	INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Feature' AND p3.value IN ('ACTIVEWEAR')
        	WHERE p1.TYPE = 'categories' AND p1.value = '6'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> ACTIVEWEAR -> SHIRTS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '31', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('1129','1130','1131','7992','1132','1134','1136','1143','1145','1147','1153','7997','1128','1130',
        	'1133','1135','7992','1139','1141','1145','7993','7994','7995','7996','1144','1151','1146','1152','1148')
        	INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Feature' AND p3.value IN ('ACTIVEWEAR')
        	WHERE p1.TYPE = 'categories' AND p1.value = '7'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> ACTIVEWEAR -> SHORTS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '32', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('3376','3379','3380','3381')
        	INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Feature' AND p3.value IN ('ACTIVEWEAR')
        	WHERE p1.TYPE = 'categories' AND p1.value = '54'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> ACTIVEWEAR -> SWEAT PANTS
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '33', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('2663','2666','8005','2624','2674','2616')
        	INNER JOIN ProductAttributes  p3 on p2.productUID = p3.productUID and p3.TYPE = 'Feature' AND p3.value IN ('ACTIVEWEAR')
        	WHERE p1.TYPE = 'categories' AND p1.value = '37'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # CLOTHING -> SWIMWEAR
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select productUID, '12', 1 from (
        	SELECT distinct p1.productUID
        	FROM ProductAttributes  p1
        	INNER JOIN ProductAttributes  p2 on p1.productUID = p2.productUID and p2.TYPE = 'categories' AND p2.value IN ('3382','3372')
        	WHERE p1.TYPE = 'categories' AND p1.value = '54'
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # FOOTWEAR -> Sneakers
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select * from (SELECT productUID, 34, 1 FROM ProductAttributes  p1 WHERE p1.TYPE = 'categories' AND p1.value = '41') t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # FOOTWEAR -> Sandals
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select * from (SELECT productUID, 35, 1 FROM ProductAttributes  p1 WHERE p1.TYPE = 'categories' AND p1.value = '42') t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # FOOTWEAR -> Dress
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select * from (SELECT productUID, 36, 1 FROM ProductAttributes  p1 WHERE p1.TYPE = 'categories' AND p1.value = '46') t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # FOOTWEAR -> Casual
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select * from (SELECT productUID, 37, 1 FROM ProductAttributes  p1 WHERE p1.TYPE = 'categories' AND p1.value = '47') t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # FOOTWEAR ->  Boots
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select * from (SELECT productUID, 38, 1 FROM ProductAttributes  p1 WHERE p1.TYPE = 'categories' AND p1.value = '48') t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        # ACCESSORIES -> all
        $sQuery = "INSERT INTO `ProductCategories_for_processing`(`productUID`,`value`,`attribute_count`)
        select * from (
        	SELECT productUID,
        	 CASE
        			WHEN p1.value = '3'  THEN '39'
        			WHEN p1.value = '43'  THEN '40'
        			WHEN p1.value = '44'  THEN '41'
        			WHEN p1.value = '62'  THEN '42'
        			WHEN p1.value = '65'  THEN '43'
        			WHEN p1.value = '66'  THEN '44'
        			WHEN p1.value = '67'  THEN '45'
        			WHEN p1.value = '7959'  THEN '46'
        			WHEN p1.value = '7960'  THEN '47'
        			WHEN p1.value = '7961'  THEN '48'
        			WHEN p1.value = '7962'  THEN '49'
        			WHEN p1.value = '7963'  THEN '50'
        			WHEN p1.value = '7964'  THEN '51'
        			WHEN p1.value = '7965'  THEN '52'
        			WHEN p1.value = '7966'  THEN '53'
        			WHEN p1.value = '7967'  THEN '54'
        			WHEN p1.value = '7968'  THEN '55'
        			ELSE 0
        		END AS value
        	, 1
        	FROM ProductAttributes  p1
        	WHERE p1.TYPE = 'categories' AND p1.value  IN ('3','43','44','62','65','66','67','7959','7960','7961','7962','7963','7964','7965','7966','7967','7968')
        ) t
        ON DUPLICATE KEY UPDATE attribute_count = attribute_count + 1;";
        $dbAdpr->query($sQuery)->execute();

        $dbAdpr->query( 'DROP TABLE IF EXISTS `ProductCategories_temp`;' )->execute();
        $dbAdpr->query( 'ALTER TABLE `ProductCategories` RENAME TO  `ProductCategories_temp` ;' )->execute();
        $dbAdpr->query( 'ALTER TABLE `ProductCategories_for_processing` RENAME TO  `ProductCategories` ;' )->execute();
        $dbAdpr->query( 'ALTER TABLE `ProductCategories_temp` RENAME TO  `ProductCategories_for_processing` ;' )->execute();

        die;
    }

}


text:
import os from 'node:os'

describe('Mocha smoke test', () => {
    describe('middleware', () => {
        it('should wait for elements if not found immediately', async () => {
            /**
             * this fails in Windows CI even though passes locally
             * [firefox 64 mac #0-1] Error: Can't call click on element with selector "elem" because element wasn't found
             * [firefox 64 mac #0-1]     at implicitWait (file:///D:/a/webdriverio/webdriverio/packages/webdriverio/build/utils/implicitWait.js:29:19)
             * [firefox 64 mac #0-1]     at async Element.elementErrorHandlerCallbackFn
             */
            if (os.platform() === 'win32') {
                return
            }
            // @ts-expect-error custom command
            await browser.waitForElementScenario()
            const elem = await $('elem')
            //Element will be found
            await elem.click()
        })

        it('should refetch stale elements', async () => {
            // @ts-expect-error custom command
            await browser.staleElementRefetchScenario()

            const elem = await $('elem')
            await elem.click()
            // element becomes stale
            await elem.click()
        })
    })
})


text:
typedef struct
{
    GLFWwindow* window;
    const char* title;
    float r, g, b;
    thrd_t id;
} Thread;

static volatile int running = GLFW_TRUE;

static void error_callback(int error, const char* description)
{
    fprintf(stderr, "Error: %s\n", description);
}

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GLFW_TRUE);
}

static int thread_main(void* data)
{
    const Thread* thread = data;

    glfwMakeContextCurrent(thread->window);
    glfwSwapInterval(1);

    while (running)
    {
        const float v = (float) fabs(sin(glfwGetTime() * 2.f));
        glClearColor(thread->r * v, thread->g * v, thread->b * v, 0.f);

        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(thread->window);
    }

    glfwMakeContextCurrent(NULL);
    return 0;
}

int main(void)
{
    int i, result;
    Thread threads[] =
    {
        { NULL, "Red", 1.f, 0.f, 0.f, 0 },
        { NULL, "Green", 0.f, 1.f, 0.f, 0 },
        { NULL, "Blue", 0.f, 0.f, 1.f, 0 }
    };
    const int count = sizeof(threads) / sizeof(Thread);

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);

    for (i = 0;  i < count;  i++)
    {
        threads[i].window = glfwCreateWindow(200, 200,
                                             threads[i].title,
                                             NULL, NULL);
        if (!threads[i].window)
        {
            glfwTerminate();
            exit(EXIT_FAILURE);
        }

        glfwSetKeyCallback(threads[i].window, key_callback);

        glfwSetWindowPos(threads[i].window, 200 + 250 * i, 200);
        glfwShowWindow(threads[i].window);
    }

    glfwMakeContextCurrent(threads[0].window);
    gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
    glfwMakeContextCurrent(NULL);

    for (i = 0;  i < count;  i++)
    {
        if (thrd_create(&threads[i].id, thread_main, threads + i) !=
            thrd_success)
        {
            fprintf(stderr, "Failed to create secondary thread\n");

            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }

    while (running)
    {
        glfwWaitEvents();

        for (i = 0;  i < count;  i++)
        {
            if (glfwWindowShouldClose(threads[i].window))
                running = GLFW_FALSE;
        }
    }

    for (i = 0;  i < count;  i++)
        glfwHideWindow(threads[i].window);

    for (i = 0;  i < count;  i++)
        thrd_join(threads[i].id, &result);

    exit(EXIT_SUCCESS);
}


text:
class OverlayResponse;
// Completion callback for OverlayRequests.  If an overlay requires a completion
// block to be executed after its UI is dismissed, OverlayPresenter clients can
// provide a callback that uses the OverlayResponse provided to the request.
// `response` may be null if no response has been provided.
typedef base::OnceCallback<void(OverlayResponse* response)>
    OverlayCompletionCallback;

// Helper object owned by an OverlayRequest that is used to communicate overlay
// UI interaction information back to the overlay's requester.  Supports
// completion calllbacks, which are executed when the overlay is finished.
class OverlayCallbackManager {
 public:
  OverlayCallbackManager() = default;
  virtual ~OverlayCallbackManager() = default;

  // The completion response object for the request whose callbacks are being
  // managed by this object.  `response` is passed as the argument for
  // completion callbacks when the overlay UI is finished or the request is
  // cancelled.
  virtual void SetCompletionResponse(
      std::unique_ptr<OverlayResponse> response) = 0;
  virtual OverlayResponse* GetCompletionResponse() const = 0;

  // Adds a completion callback.  Provided callbacks are guaranteed to be
  // executed once with the completion response when the overlay UI is finished
  // or the request is cancelled.
  virtual void AddCompletionCallback(OverlayCompletionCallback callback) = 0;

  // Dispatches `response` to all callbacks that have been added for its
  // info type.  Used to send user interaction information back to the overlay's
  // requester for ongoing overlay UI.
  virtual void DispatchResponse(std::unique_ptr<OverlayResponse> response) = 0;

  // Adds `callback` to be executed for dispatched responses.  The provided
  // callbacks are not guaranteed to be called, as there is no guarantee that a
  // supported response will be sent for the overlay.
  virtual void AddDispatchCallback(OverlayDispatchCallback callback) = 0;
};

#endif  // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_OVERLAY_CALLBACK_MANAGER_H_


text:
#!/usr/bin/env python

"""

"""

import ConfigParser
import calendar
import os
import random
import time

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#       Device specific info when pushing data to server
#       Read from a file "deviceConfig.properties" in the same folder level
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
configParser = ConfigParser.RawConfigParser()
configFilePath = os.path.join(os.path.dirname(__file__), './deviceConfig.properties')
configParser.read(configFilePath)

DEVICE_OWNER = configParser.get('Device-Configurations', 'owner')
DEVICE_ID = configParser.get('Device-Configurations', 'deviceId')
DEVICE_NAME = configParser.get('Device-Configurations', 'device-name')
DEVICE_TYPE = configParser.get('Device-Configurations', 'device-type')
SERVER_NAME = configParser.get('Device-Configurations', 'server-name')
MQTT_EP = configParser.get('Device-Configurations', 'mqtt-ep')
AUTH_TOKEN = configParser.get('Device-Configurations', 'auth-token')
CONTROLLER_CONTEXT = configParser.get('Device-Configurations', 'controller-context')
DEVICE_INFO = '{"owner":"' + DEVICE_OWNER + '","deviceId":"' + DEVICE_ID + '"}'
HTTPS_EP = configParser.get('Device-Configurations', 'https-ep')
DEVICE_DATA = '"sensorValue":"{sensorValue}"'

global IS_REGISTERED
IS_REGISTERED = False

def isEmpty (string):
    if string and string.strip():
        #string is not None AND string is not empty or blank
        return False
    #string is None OR string is empty or blank
    return True

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#       This method generate a random sensor value between 15 and 40
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def generateRandomSensorValues():
    return random.randint(15, 40)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

currentTime = calendar.timegm(time.gmtime())
SENSOR_STATS = '{"event":{"metaData":{"owner":"' + DEVICE_OWNER + '","deviceType":"'+ DEVICE_TYPE +'","deviceId":"'+ DEVICE_ID + '",'


text:
<?php

class Redirect_controller extends CI_controller {

    // This calls for default function
    public function index(){
       $this->load->helper('url');
        /*Redirect the user to Google */

        redirect("http://www.google.co.in");

    }

    public function computer_graphics(){
        /*Load the URL helper

        https://en.wikipedia.org/wiki/Computer_graphics
        */

        $this->load->helper('url');
        //Redirect to computer graphics section

        redirect("https://en.wikipedia.org/wiki/Computer_graphics");

    }

}

?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<npc name="Captain Bluebear" script="Captain Bluebear.lua" walkinterval="2000" floorchange="0">
  <health now="100" max="100" />
  <look type="129" head="38" body="50" legs="87" feet="68" addons="0" />
<parameters>
<parameter key="message_farewell" value="Good bye. Recommend us if you were satisfied with our service." />
<parameter key="message_walkaway" value="Good bye. Recommend us if you were satisfied with our service." />
 <parameter key="module_keywords" value="1" />
 <parameter key="keywords" value="name;thais;darashia;" />
 <parameter key="keyword_reply1" value="My name is Captain Bluebear from the Royal Tibia Line." />
 <parameter key="keyword_reply2" value="This is Thais. Where do you want to go?" />
 <parameter key="keyword_reply3" value="I'm not sailing there. This route is afflicted by a ghost ship! However, I heard that Captain Fearless sails there from Venore." />
 <parameter key="message_greet" value="Welcome on board, |PLAYERNAME|. Where may I {sail} you today?"/>
</parameters>
</npc>


text:
(function () {
    'use strict';

    // load gulp module
    var gulp = require('gulp');

    // loads all the `gulp-` prefixed modules into the plugins namespace
    var plugins = require('gulp-load-plugins')();

    // define the task
    gulp.task('uncss', function () {

        // load the css files in the src directory into the gulp pipeline
        return gulp.src('./src/**/*.css')

            // handle any errors that might occur in the gulp pipeline
            .pipe(plugins.plumber())

            // run the uncss task
            .pipe(plugins.uncss({
                // load all html files in the src directory to which the styles will be applied
                html: ['./src/**/*.html']
            }))

            // apply formatting rules to the styles
            .pipe(plugins.csscomb())

            // write the output into the dest directory
            .pipe(gulp.dest('./dest/'));
    });

    // expose uncss as the default task
    gulp.task('default', ['uncss']);

}());


text:
// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==

#define DEBUG_PTRS

namespace System
{
    using System;
    using System.Reflection;
////using System.Reflection.Emit;
    using System.Runtime.ConstrainedExecution;
    using System.Diagnostics;
    using System.Runtime.Serialization;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
////using System.Runtime.Versioning;
////using System.Text;
    using System.Globalization;
////using System.Security;
////using Microsoft.Win32.SafeHandles;
////using StackCrawlMark = System.Threading.StackCrawlMark;

    [Microsoft.Zelig.Internals.WellKnownType( "System_RuntimeTypeHandle" )]
    [Serializable]
    public unsafe struct RuntimeTypeHandle /*: ISerializable*/
    {
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool IsInstanceOfType( Object o );
////
////    internal unsafe static IntPtr GetTypeHelper( IntPtr th, IntPtr pGenericArgs, int cGenericArgs, IntPtr pModifiers, int cModifiers )
////    {
////        RuntimeTypeHandle typeHandle = new RuntimeTypeHandle( th.ToPointer() );
////
////        Type type = typeHandle.GetRuntimeType();
////        if(type == null)
////        {
////            return th;
////        }
////
////        if(cGenericArgs > 0)
////        {
////            Type[] genericArgs   = new Type[cGenericArgs];
////            void** arGenericArgs = (void**)pGenericArgs.ToPointer();
////
////            for(int i = 0; i < genericArgs.Length; i++)
////            {
////                RuntimeTypeHandle genericArg = new RuntimeTypeHandle( (void*)Marshal.ReadIntPtr( (IntPtr)arGenericArgs, i * sizeof( void* ) ) );
////
////                genericArgs[i] = Type.GetTypeFromHandle( genericArg );
////                if(genericArgs[i] == null)
////                {
////                    return (IntPtr)0;
////                }
////            }
////
////            type = type.MakeGenericType( genericArgs );
////        }
////
////        if(cModifiers > 0)
////        {
////            int* arModifiers = (int*)pModifiers.ToPointer();
////            for(int i = 0; i < cModifiers; i++)
////            {
////                if((CorElementType)Marshal.ReadInt32( (IntPtr)arModifiers, i * sizeof( int ) ) == CorElementType.Ptr)
////                {
////                    type = type.MakePointerType();
////                }
////                else if((CorElementType)Marshal.ReadInt32( (IntPtr)arModifiers, i * sizeof( int ) ) == CorElementType.ByRef)
////                {
////                    type = type.MakeByRefType();
////                }
////                else if((CorElementType)Marshal.ReadInt32( (IntPtr)arModifiers, i * sizeof( int ) ) == CorElementType.SzArray)
////                {
////                    type = type.MakeArrayType();
////                }
////                else
////                {
////                    type = type.MakeArrayType( Marshal.ReadInt32( (IntPtr)arModifiers, ++i * sizeof( int ) ) );
////                }
////            }
////        }
////
////        return type.GetTypeHandleInternal().Value;
////    }

        public static bool operator ==( RuntimeTypeHandle left, object right )
        {
            return left.Equals( right );
        }

        public static bool operator ==( object left, RuntimeTypeHandle right )
        {
            return right.Equals( left );
        }

        public static bool operator !=( RuntimeTypeHandle left, object right )
        {
            return !left.Equals( right );
        }

        public static bool operator !=( object left, RuntimeTypeHandle right )
        {
            return !right.Equals( left );
        }

        /*
                internal new Type GetType()
                {
                    Console.WriteLine("RuntimeTypeHandle.GetType() called");
                    throw new Exception("RuntimeTypeHandle.GetType() called. Chances are you want to call GetRuntimeType()");
                    return base.GetType();
                }
        */
////    private const int MAX_CLASS_NAME = 1024;
////    internal static RuntimeTypeHandle EmptyHandle
////    {
////        get
////        {
////            return new RuntimeTypeHandle();
////        }
////    }
////
////    // this is the TypeHandle/MethodTable for the type
////#pragma warning disable 649 // Field 'field' is never assigned to, and will always have its default value 'value'
////    private IntPtr m_ptr;
////#pragma warning restore 649

        [MethodImpl( MethodImplOptions.InternalCall )]
        public extern override int GetHashCode();
////    {
////        return m_ptr.GetHashCode();
////    }

////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
        [MethodImpl( MethodImplOptions.InternalCall )]
        public extern override bool Equals( object obj );
////    {
////        if(!(obj is RuntimeTypeHandle))
////        {
////            return false;
////        }
////
////        return Equals( (RuntimeTypeHandle)obj );
////    }

////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
        [MethodImpl( MethodImplOptions.InternalCall )]
        public extern bool Equals( RuntimeTypeHandle handle );
////    {
////        return handle.m_ptr == m_ptr;
////    }

////    public IntPtr Value
////    {
////        get
////        {
////            return m_ptr;
////        }
////    }
////
////    internal RuntimeTypeHandle( void* rth )
////    {
////        m_ptr = new IntPtr( rth );
////    }
////
////    internal RuntimeTypeHandle( IntPtr rth )
////    {
////        m_ptr = rth;
////    }

        [MethodImpl( MethodImplOptions.InternalCall )]
        internal extern bool IsNullHandle();
////    {
////        return m_ptr.ToPointer() == null;
////    }

////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal static extern Object CreateInstance( RuntimeType type, bool publicOnly, bool noCheck, ref bool canBeCached, ref RuntimeMethodHandle ctor, ref bool bNeedSecurityCheck );
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern Object CreateCaInstance( RuntimeMethodHandle ctor );
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern Object Allocate();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern Object CreateInstanceForAnotherGenericParameter( Type genericParameter );
////
////    internal RuntimeType GetRuntimeType()
////    {
////        if(!IsNullHandle())
////        {
////            return (System.RuntimeType)Type.GetTypeFromHandle( this );
////        }
////        else
////        {
////            return null;
////        }
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern CorElementType GetCorElementType();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern IntPtr _GetAssemblyHandle();
////    internal AssemblyHandle GetAssemblyHandle()
////    {
////        return new AssemblyHandle( _GetAssemblyHandle() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    private extern IntPtr _GetModuleHandle();
////
////    [CLSCompliant( false )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    public ModuleHandle GetModuleHandle()
////    {
////        return new ModuleHandle( _GetModuleHandle() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _GetBaseTypeHandle();
////    internal RuntimeTypeHandle GetBaseTypeHandle()
////    {
////        return new RuntimeTypeHandle( _GetBaseTypeHandle() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern TypeAttributes GetAttributes();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _GetElementType();
////    internal RuntimeTypeHandle GetElementType()
////    {
////        return new RuntimeTypeHandle( _GetElementType() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern RuntimeTypeHandle GetCanonicalHandle();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern int GetArrayRank();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern int GetToken();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _GetMethodAt( int slot );
////    internal RuntimeMethodHandle GetMethodAt( int slot )
////    {
////        return new RuntimeMethodHandle( _GetMethodAt( slot ) );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _GetMethodDescChunk();
////    internal MethodDescChunkHandle GetMethodDescChunk()
////    {
////        return new MethodDescChunkHandle( _GetMethodDescChunk() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool GetFields( int** result, int* count );
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern RuntimeTypeHandle[] GetInterfaces();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern RuntimeTypeHandle[] GetConstraints();
////
////    [ResourceExposure( ResourceScope.AppDomain )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern IntPtr GetGCHandle( GCHandleType type );
////
////    [ResourceExposure( ResourceScope.AppDomain )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern void FreeGCHandle( IntPtr handle );
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _GetMethodFromToken( int tkMethodDef );
////    internal RuntimeMethodHandle GetMethodFromToken( int tkMethodDef )
////    {
////        return new RuntimeMethodHandle( _GetMethodFromToken( tkMethodDef ) );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern int GetNumVtableSlots();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern int GetInterfaceMethodSlots();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern int GetFirstSlotForInterface( IntPtr interfaceHandle );
////    internal int GetFirstSlotForInterface( RuntimeTypeHandle interfaceHandle )
////    {
////        return GetFirstSlotForInterface( interfaceHandle.Value );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern int GetInterfaceMethodImplementationSlot( IntPtr interfaceHandle, IntPtr interfaceMethodHandle );
////    [ResourceExposure( ResourceScope.None )]
////    [ResourceConsumption( ResourceScope.AppDomain, ResourceScope.AppDomain )]
////    internal int GetInterfaceMethodImplementationSlot( RuntimeTypeHandle interfaceHandle, RuntimeMethodHandle interfaceMethodHandle )
////    {
////        return GetInterfaceMethodImplementationSlot( interfaceHandle.Value, interfaceMethodHandle.Value );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool IsComObject( bool isGenericCOM );
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool IsContextful();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool IsVisible();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool _IsVisibleFromModule( IntPtr module );
////    [ResourceExposure( ResourceScope.None )]
////    [ResourceConsumption( ResourceScope.AppDomain, ResourceScope.AppDomain )]
////    internal bool IsVisibleFromModule( ModuleHandle module )
////    {
////        return _IsVisibleFromModule( (IntPtr)module.Value );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool HasProxyAttribute();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern string ConstructName( bool nameSpace, bool fullInst, bool assembly );
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _GetUtf8Name();
////
////    internal Utf8String GetUtf8Name()
////    {
////        return new Utf8String( _GetUtf8Name() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern bool CanCastTo( IntPtr target );
////    internal bool CanCastTo( RuntimeTypeHandle target )
////    {
////        return CanCastTo( target.Value );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern RuntimeTypeHandle GetDeclaringType();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _GetDeclaringMethod();
////    internal RuntimeMethodHandle GetDeclaringMethod()
////    {
////        return new RuntimeMethodHandle( _GetDeclaringMethod() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _GetDefaultConstructor();
////    internal RuntimeMethodHandle GetDefaultConstructor()
////    {
////        return new RuntimeMethodHandle( _GetDefaultConstructor() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool SupportsInterface( object target );
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern static void* _GetTypeByName( string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark, bool loadTypeFromPartialName );
////    internal static RuntimeTypeHandle GetTypeByName( string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark )
////    {
////        if(name == null || name.Length == 0)
////        {
////            if(throwOnError)
////            {
////                throw new TypeLoadException( Environment.GetResourceString( "Arg_TypeLoadNullStr" ) );
////            }
////
////            return new RuntimeTypeHandle();
////        }
////
////        return new RuntimeTypeHandle( _GetTypeByName( name, throwOnError, ignoreCase, reflectionOnly, ref stackMark, false ) );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern static void* _GetTypeByNameUsingCARules( string name, IntPtr scope );
////    internal static Type GetTypeByNameUsingCARules( string name, Module scope )
////    {
////        if(name == null || name.Length == 0)
////        {
////            throw new ArgumentException();
////        }
////
////        return new RuntimeTypeHandle( _GetTypeByNameUsingCARules( name, (IntPtr)scope.GetModuleHandle().Value ) ).GetRuntimeType();
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern RuntimeTypeHandle[] GetInstantiation();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _Instantiate( RuntimeTypeHandle[] inst );
////    internal RuntimeTypeHandle Instantiate( RuntimeTypeHandle[] inst )
////    {
////        return new RuntimeTypeHandle( _Instantiate( inst ) );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _MakeArray( int rank );
////    internal RuntimeTypeHandle MakeArray( int rank )
////    {
////        return new RuntimeTypeHandle( _MakeArray( rank ) );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _MakeSZArray();
////    internal RuntimeTypeHandle MakeSZArray()
////    {
////        return new RuntimeTypeHandle( _MakeSZArray() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _MakeByRef();
////    internal RuntimeTypeHandle MakeByRef()
////    {
////        return new RuntimeTypeHandle( _MakeByRef() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _MakePointer();
////    internal RuntimeTypeHandle MakePointer()
////    {
////        return new RuntimeTypeHandle( _MakePointer() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool HasInstantiation();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void* _GetGenericTypeDefinition();
////    internal RuntimeTypeHandle GetGenericTypeDefinition()
////    {
////        return new RuntimeTypeHandle( _GetGenericTypeDefinition() );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool IsGenericTypeDefinition();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool IsGenericVariable();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern int GetGenericVariableIndex();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool ContainsGenericVariables();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern bool SatisfiesConstraints( RuntimeTypeHandle[] typeContext, RuntimeTypeHandle[] methodContext, RuntimeTypeHandle toType );
////
////    private RuntimeTypeHandle( SerializationInfo info, StreamingContext context )
////    {
////        if(info == null)
////        {
////            throw new ArgumentNullException( "info" );
////        }
////
////        Type m = (RuntimeType)info.GetValue( "TypeObj", typeof( RuntimeType ) );
////
////        m_ptr = m.TypeHandle.Value;
////
////        if(m_ptr.ToPointer() == null)
////        {
////            throw new SerializationException( Environment.GetResourceString( "Serialization_InsufficientState" ) );
////        }
////    }
////
////    public void GetObjectData( SerializationInfo info, StreamingContext context )
////    {
////        if(info == null)
////        {
////            throw new ArgumentNullException( "info" );
////        }
////
////        if(m_ptr.ToPointer() == null)
////        {
////            throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidFieldState" ) );
////        }
////
////        RuntimeType type = (RuntimeType)Type.GetTypeFromHandle( this );
////
////        info.AddValue( "TypeObj", type, typeof( RuntimeType ) );
////    }
    }
}


text:
require 'spec_helper'

describe DocumentsController do
  render_views

  context "with public document" do
    before do
      @public_document = Factory(:public_document)
    end

    describe "when not authenticated" do
      it "should redirect to login" do
        get :index
        response.should redirect_to(:new_user_session)
      end

      it "should render receiver's index with public document included" do
        get :index, :user_id => @public_document.post_activity.receiver.to_param

        response.should be_success
        response.body.should =~ /#{ controller.dom_id(@public_document) }/
      end

      it "should render receiver's html show" do
        get :show, :id => @public_document.to_param
        response.should be_success
        response.headers["Content-Type"].should include('text/html')
      end

      it "should render receiver's format pdf download" do
        get :download, :id => @public_document.to_param
        response.should be_success
        response.headers["Content-Type"].should include('application/pdf')
      end
    end

    describe "when authenticated" do
      before do
        sign_in Factory(:user)
      end

      it "should render index" do
        get :index, :user_id => @public_document.post_activity.receiver.to_param

        response.should be_success
        response.body.should =~ /#{ controller.dom_id(@public_document) }/
      end

      it "should render html show" do
        get :show, :id => @public_document.to_param
        response.should be_success
        response.headers["Content-Type"].should include('text/html')
      end

      it "should render html new" do
        get :new
        response.should be_success
        response.headers["Content-Type"].should include('text/html')
      end

      it "should render format pdf download" do
        get :download, :id => @public_document.to_param, :format => :pdf
        response.should be_success
        response.headers["Content-Type"].should include('application/pdf')
      end
    end
  end #end of the context

  context "with private document" do
    before do
      @private_document = Factory(:private_document)
    end
    describe "when not authenticated" do
      it "should render receiver's index without private document" do
        get :index, :user_id => @private_document.post_activity.receiver.to_param

        response.should be_success
        response.body.should_not =~ /#{ controller.dom_id @private_document }/
      end
    end

    describe "when authenticated" do
      before do
        sign_in Factory(:user)
      end
      it "should render index" do
        get :index, :user_id => @private_document.post_activity.receiver.to_param

        response.should be_success
        response.body.should_not =~ /#{ controller.dom_id @private_document }/
      end

      it "should render show" do
        lambda {get :show, :id => @private_document.to_param}.should raise_error(CanCan::AccessDenied)
      end
    end
  end

  context "with public picture" do
    before do
      @public_picture = Factory(:public_picture)
    end

    describe "when not authenticated" do
      it "should render receiver's format png download" do
        get :download, :id => @public_picture.to_param
        response.should be_success
        response.headers["Content-Type"].should include('image/png')
      end
    end

    describe "when authenticated" do
      before do
        sign_in Factory(:user)
      end

      it "should render format png download" do
        get :download, :id => @public_picture.to_param
        response.should be_success
        response.headers["Content-Type"].should include('image/png')
      end
    end
  end
end