text:
"""Upgrader for Python scripts according to an API change specification."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import ast
import os
import re
import shutil
import sys
import tempfile
import traceback

import pasta
import six

# Some regular expressions we will need for parsing
FIND_OPEN = re.compile(r"^\s*(\[).*$")
FIND_STRING_CHARS = re.compile(r"['\"]")

INFO = "INFO"
WARNING = "WARNING"
ERROR = "ERROR"

def full_name_node(name, ctx=ast.Load()):
  """Make an Attribute or Name node for name.

  Translate a qualified name into nested Attribute nodes (and a Name node).

  Args:
    name: The name to translate to a node.
    ctx: What context this name is used in. Defaults to Load()

  Returns:
    A Name or Attribute node.
  """
  names = name.split(".")
  names.reverse()
  node = ast.Name(id=names.pop(), ctx=ast.Load())
  while names:
    node = ast.Attribute(value=node, attr=names.pop(), ctx=ast.Load())

  # Change outermost ctx to the one given to us (inner ones should be Load).
  node.ctx = ctx
  return node

class APIChangeSpec(object):
  """This class defines the transformations that need to happen.

  This class must provide the following fields:

  * `function_keyword_renames`: maps function names to a map of old -> new
    argument names
  * `symbol_renames`: maps function names to new function names
  * `change_to_function`: a set of function names that have changed (for
    notifications)
  * `function_reorders`: maps functions whose argument order has changed to the
    list of arguments in the new order
  * `function_warnings`: maps full names of functions to warnings that will be
    printed out if the function is used. (e.g. tf.nn.convolution())
  * `function_transformers`: maps function names to custom handlers

  For an example, see `TFAPIChangeSpec`.
  """

class _PastaEditVisitor(ast.NodeVisitor):
  """AST Visitor that processes function calls.

  Updates function calls from old API version to new API version using a given
  change spec.
  """

  def __init__(self, api_change_spec):
    self._api_change_spec = api_change_spec
    self._log = []   # Holds 4-tuples: severity, line, col, msg.
    self._stack = []  # Allow easy access to parents.

  # Overridden to maintain a stack of nodes to allow for parent access
  def visit(self, node):
    self._stack.append(node)
    super(_PastaEditVisitor, self).visit(node)
    self._stack.pop()

  @property
  def errors(self):
    return [log for log in self._log if log[0] == ERROR]

  @property
  def warnings(self):
    return [log for log in self._log if log[0] == WARNING]

  @property
  def warnings_and_errors(self):
    return [log for log in self._log if log[0] in (WARNING, ERROR)]

  @property
  def info(self):
    return [log for log in self._log if log[0] == INFO]

  @property
  def log(self):
    return self._log

  def add_log(self, severity, lineno, col, msg):
    self._log.append((severity, lineno, col, msg))
    print("%s line %d:%d: %s" % (severity, lineno, col, msg))

  def add_logs(self, logs):
    """Record a log and print it.

    The log should be a tuple `(severity, lineno, col_offset, msg)`, which will
    be printed and recorded. It is part of the log available in the `self.log`
    property.

    Args:
      logs: The logs to add. Must be a list of tuples
        `(severity, lineno, col_offset, msg)`.
    """
    self._log.extend(logs)
    for log in logs:
      print("%s line %d:%d: %s" % log)

  def _get_applicable_entries(self, transformer_field, full_name, name):
    """Get all list entries indexed by name that apply to full_name or name."""
    # Transformers are indexed to full name, name, or no name
    # as a performance optimization.
    function_transformers = getattr(self._api_change_spec,
                                    transformer_field, {})

    glob_name = "*." + name if name else None
    transformers = []
    if full_name in function_transformers:
      transformers.append(function_transformers[full_name])
    if glob_name in function_transformers:
      transformers.append(function_transformers[glob_name])
    if "*" in function_transformers:
      transformers.append(function_transformers["*"])
    return transformers

  def _get_applicable_dict(self, transformer_field, full_name, name):
    """Get all dict entries indexed by name that apply to full_name or name."""
    # Transformers are indexed to full name, name, or no name
    # as a performance optimization.
    function_transformers = getattr(self._api_change_spec,
                                    transformer_field, {})

    glob_name = "*." + name if name else None
    transformers = function_transformers.get("*", {}).copy()
    transformers.update(function_transformers.get(glob_name, {}))
    transformers.update(function_transformers.get(full_name, {}))
    return transformers

  def _get_full_name(self, node):
    """Traverse an Attribute node to generate a full name, e.g., "tf.foo.bar".

    This is the inverse of `full_name_node`.

    Args:
      node: A Node of type Attribute.

    Returns:
      a '.'-delimited full-name or None if node was not Attribute or Name.
      i.e. `foo()+b).bar` returns None, while `a.b.c` would return "a.b.c".
    """
    curr = node
    items = []
    while not isinstance(curr, ast.Name):
      if not isinstance(curr, ast.Attribute):
        return None
      items.append(curr.attr)
      curr = curr.value
    items.append(curr.id)
    return ".".join(reversed(items))

  def _maybe_add_warning(self, node, full_name):
    """Adds an error to be printed about full_name at node."""
    function_warnings = self._api_change_spec.function_warnings
    if full_name in function_warnings:
      warning_message = function_warnings[full_name]
      warning_message = warning_message.replace("<function name>", full_name)
      self.add_log(WARNING, node.lineno, node.col_offset,
                   "%s requires manual check. %s" % (full_name,
                                                     warning_message))
      return True
    else:
      return False

  def _maybe_add_call_warning(self, node, full_name, name):
    """Print a warning when specific functions are called with selected args.

    The function _print_warning_for_function matches the full name of the called
    function, e.g., tf.foo.bar(). This function matches the function name that
    is called, as long as the function is an attribute. For example,
    `tf.foo.bar()` and `foo.bar()` are matched, but not `bar()`.

    Args:
      node: ast.Call object
      full_name: The precomputed full name of the callable, if one exists, None
        otherwise.
      name: The precomputed name of the callable, if one exists, None otherwise.

    Returns:
      Whether an error was recorded.
    """
    # Only look for *.-warnings here, the other will be handled by the Attribute
    # visitor. Also, do not warn for bare functions, only if the call func is
    # an attribute.
    warned = False
    if isinstance(node.func, ast.Attribute):
      warned = self._maybe_add_warning(node, "*." + name)

    # All arg warnings are handled here, since only we have the args
    arg_warnings = self._get_applicable_dict("function_arg_warnings",
                                             full_name, name)

    used_args = [kw.arg for kw in node.keywords]
    for (kwarg, arg), warning in arg_warnings.items():
      if kwarg in used_args or len(node.args) > arg:
        warned = True
        warning_message = warning.replace("<function name>", full_name or name)
        self.add_log(WARNING, node.lineno, node.col_offset,
                     "%s called with %s argument requires manual check: %s." %
                     (full_name or name, kwarg, warning_message))

    return warned

  def _maybe_rename(self, parent, node, full_name):
    """Replace node (Attribute or Name) with a node representing full_name."""
    new_name = self._api_change_spec.symbol_renames.get(full_name, None)
    if new_name:
      self.add_log(INFO, node.lineno, node.col_offset,
                   "Renamed %r to %r" % (full_name, new_name))
      new_node = full_name_node(new_name, node.ctx)
      ast.copy_location(new_node, node)
      pasta.ast_utils.replace_child(parent, node, new_node)
      return True
    else:
      return False

  def _maybe_change_to_function_call(self, parent, node, full_name):
    """Wraps node (typically, an Attribute or Expr) in a Call."""
    if full_name in self._api_change_spec.change_to_function:
      if not isinstance(parent, ast.Call):
        # ast.Call's constructor is really picky about how many arguments it
        # wants, and also, it changed between Py2 and Py3.
        if six.PY2:
          new_node = ast.Call(node, [], [], None, None)
        else:
          new_node = ast.Call(node, [], [])
        pasta.ast_utils.replace_child(parent, node, new_node)
        ast.copy_location(new_node, node)
        self.add_log(INFO, node.lineno, node.col_offset,
                     "Changed %r to a function call" % full_name)
        return True
    return False

  def _maybe_add_arg_names(self, node, full_name):
    """Make args into keyword args if function called full_name requires it."""
    function_reorders = self._api_change_spec.function_reorders

    if full_name in function_reorders:
      reordered = function_reorders[full_name]
      new_keywords = []
      for idx, arg in enumerate(node.args):
        if sys.version_info[:2] >= (3, 5) and isinstance(arg, ast.Starred):
          continue  # Can't move Starred to keywords
        keyword_arg = reordered[idx]
        keyword = ast.keyword(arg=keyword_arg, value=arg)
        new_keywords.append(keyword)

      if new_keywords:
        self.add_log(INFO, node.lineno, node.col_offset,
                     "Added keywords to args of function %r" % full_name)
        node.args = []
        node.keywords = new_keywords + (node.keywords or [])
        return True
    return False

  def _maybe_modify_args(self, node, full_name, name):
    """Rename keyword args if the function called full_name requires it."""
    renamed_keywords = self._get_applicable_dict("function_keyword_renames",
                                                 full_name, name)

    if not renamed_keywords:
      return False

    modified = False
    new_keywords = []
    for keyword in node.keywords:
      argkey = keyword.arg
      if argkey in renamed_keywords:
        modified = True
        if renamed_keywords[argkey] is None:
          lineno = getattr(keyword, "lineno", node.lineno)
          col_offset = getattr(keyword, "col_offset", node.col_offset)
          self.add_log(INFO, lineno, col_offset,
                       "Removed argument %s for function %s" % (
                           argkey, full_name or name))
        else:
          keyword.arg = renamed_keywords[argkey]
          lineno = getattr(keyword, "lineno", node.lineno)
          col_offset = getattr(keyword, "col_offset", node.col_offset)
          self.add_log(INFO, lineno, col_offset,
                       "Renamed keyword argument for %s from %s to %s" % (
                           full_name, argkey, renamed_keywords[argkey]))
          new_keywords.append(keyword)
      else:
        new_keywords.append(keyword)

    if modified:
      node.keywords = new_keywords
    return modified

  def visit_Call(self, node):  # pylint: disable=invalid-name
    """Handle visiting a call node in the AST.

    Args:
      node: Current Node
    """
    assert self._stack[-1] is node

    # Get the name for this call, so we can index stuff with it.
    full_name = self._get_full_name(node.func)
    if full_name:
      name = full_name.split(".")[-1]
    elif isinstance(node.func, ast.Name):
      name = node.func.id
    elif isinstance(node.func, ast.Attribute):
      name = node.func.attr
    else:
      name = None

    # Call standard transformers for this node.
    # Make sure warnings come first, since args or names triggering warnings
    # may be removed by the other transformations.
    self._maybe_add_call_warning(node, full_name, name)
    # Make all args into kwargs
    self._maybe_add_arg_names(node, full_name)
    # Argument name changes or deletions
    self._maybe_modify_args(node, full_name, name)

    # Call transformers. These have the ability to modify the node, and if they
    # do, will return the new node they created (or the same node if they just
    # changed it). The are given the parent, but we will take care of
    # integrating their changes into the parent if they return a new node.
    #
    # These are matched on the old name, since renaming is performed by the
    # Attribute visitor, which happens later.
    transformers = self._get_applicable_entries("function_transformers",
                                                full_name, name)

    parent = self._stack[-2]

    for transformer in transformers:
      logs = []
      new_node = transformer(parent, node, full_name, name, logs)
      self.add_logs(logs)
      if new_node:
        if new_node is not node:
          pasta.ast_utils.replace_child(parent, node, new_node)
          node = new_node
          self._stack[-1] = node

    self.generic_visit(node)

  def visit_Attribute(self, node):  # pylint: disable=invalid-name
    """Handle bare Attributes i.e. [tf.foo, tf.bar]."""
    assert self._stack[-1] is node

    full_name = self._get_full_name(node)
    if full_name:
      parent = self._stack[-2]

      # Make sure the warning comes first, otherwise the name may have changed
      self._maybe_add_warning(node, full_name)

      # Once we did a modification, node is invalid and not worth inspecting
      # further. Also, we only perform modifications for simple nodes, so
      # There'd be no point in descending further.
      if self._maybe_rename(parent, node, full_name):
        return
      if self._maybe_change_to_function_call(parent, node, full_name):
        return

    self.generic_visit(node)

class ASTCodeUpgrader(object):
  """Handles upgrading a set of Python files using a given API change spec."""

  def __init__(self, api_change_spec):
    if not isinstance(api_change_spec, APIChangeSpec):
      raise TypeError("Must pass APIChangeSpec to ASTCodeUpgrader, got %s" %
                      type(api_change_spec))
    self._api_change_spec = api_change_spec

  def process_file(self, in_filename, out_filename):
    """Process the given python file for incompatible changes.

    Args:
      in_filename: filename to parse
      out_filename: output file to write to
    Returns:
      A tuple representing number of files processed, log of actions, errors
    """

    # Write to a temporary file, just in case we are doing an implace modify.
    # pylint: disable=g-backslash-continuation
    with open(in_filename, "r") as in_file, \
        tempfile.NamedTemporaryFile("w", delete=False) as temp_file:
      ret = self.process_opened_file(in_filename, in_file, out_filename,
                                     temp_file)
    # pylint: enable=g-backslash-continuation

    shutil.move(temp_file.name, out_filename)
    return ret

  def format_log(self, log, in_filename):
    log_string = "%d:%d: %s: %s" % (log[1], log[2], log[0], log[3])
    if in_filename:
      return in_filename + ":" + log_string
    else:
      return log_string

  def update_string_pasta(self, text, in_filename):
    """Updates a file using pasta."""
    try:
      t = pasta.parse(text)
    except (SyntaxError, ValueError, TypeError):
      log = ["ERROR: Failed to parse.\n" + traceback.format_exc()]
      return 0, "", log, []

    visitor = _PastaEditVisitor(self._api_change_spec)
    visitor.visit(t)

    logs = [self.format_log(log, None) for log in visitor.log]
    errors = [self.format_log(error, in_filename)
              for error in visitor.warnings_and_errors]
    return 1, pasta.dump(t), logs, errors

  def _format_log(self, log, in_filename, out_filename):
    text = "-" * 80 + "\n"
    text += "Processing file %r\n outputting to %r\n" % (in_filename,
                                                         out_filename)
    text += "-" * 80 + "\n\n"
    text += "\n".join(log)
    text += "-" * 80 + "\n\n"
    return text

  def process_opened_file(self, in_filename, in_file, out_filename, out_file):
    """Process the given python file for incompatible changes.

    This function is split out to facilitate StringIO testing from
    tf_upgrade_test.py.

    Args:
      in_filename: filename to parse
      in_file: opened file (or StringIO)
      out_filename: output file to write to
      out_file: opened file (or StringIO)
    Returns:
      A tuple representing number of files processed, log of actions, errors
    """
    lines = in_file.readlines()
    processed_file, new_file_content, log, process_errors = (
        self.update_string_pasta("".join(lines), in_filename))

    if out_file and processed_file:
      out_file.write(new_file_content)

    return (processed_file,
            self._format_log(log, in_filename, out_filename),
            process_errors)

  def process_tree(self, root_directory, output_root_directory,
                   copy_other_files, in_place):
    """Processes upgrades on an entire tree of python files in place.

    Note that only Python files. If you have custom code in other languages,
    you will need to manually upgrade those.

    Args:
      root_directory: Directory to walk and process.
      output_root_directory: Directory to use as base.
      copy_other_files: Copy files that are not touched by this converter.
      in_place: Allow the conversion of an entire directory in place.

    Returns:
      A tuple of files processed, the report string ofr all files, and a dict
        mapping filenames to errors encountered in that file.
    """

    if output_root_directory == root_directory:
      if in_place:
        return self.process_tree_inplace(root_directory)
      else:
        print("In order to copy a directory in place the `--inplace` input "
              "arg must be set to `True`.")
        sys.exit(1)

    # make sure output directory doesn't exist
    if output_root_directory and os.path.exists(output_root_directory):
      print("Output directory %r must not already exist." %
            (output_root_directory))
      sys.exit(1)

    # make sure output directory does not overlap with root_directory
    norm_root = os.path.split(os.path.normpath(root_directory))
    norm_output = os.path.split(os.path.normpath(output_root_directory))
    if norm_root == norm_output:
      print("Output directory %r same as input directory %r" %
            (root_directory, output_root_directory))
      sys.exit(1)

    # Collect list of files to process (we do this to correctly handle if the
    # user puts the output directory in some sub directory of the input dir)
    files_to_process = []
    files_to_copy = []
    for dir_name, _, file_list in os.walk(root_directory):
      py_files = [f for f in file_list if f.endswith(".py")]
      copy_files = [f for f in file_list if not f.endswith(".py")]
      for filename in py_files:
        fullpath = os.path.join(dir_name, filename)
        fullpath_output = os.path.join(output_root_directory,
                                       os.path.relpath(fullpath,
                                                       root_directory))
        files_to_process.append((fullpath, fullpath_output))
      if copy_other_files:
        for filename in copy_files:
          fullpath = os.path.join(dir_name, filename)
          fullpath_output = os.path.join(output_root_directory,
                                         os.path.relpath(
                                             fullpath, root_directory))
          files_to_copy.append((fullpath, fullpath_output))

    file_count = 0
    tree_errors = {}
    report = ""
    report += ("=" * 80) + "\n"
    report += "Input tree: %r\n" % root_directory
    report += ("=" * 80) + "\n"

    for input_path, output_path in files_to_process:
      output_directory = os.path.dirname(output_path)
      if not os.path.isdir(output_directory):
        os.makedirs(output_directory)
      file_count += 1
      _, l_report, l_errors = self.process_file(input_path, output_path)
      tree_errors[input_path] = l_errors
      report += l_report
    for input_path, output_path in files_to_copy:
      output_directory = os.path.dirname(output_path)
      if not os.path.isdir(output_directory):
        os.makedirs(output_directory)
      shutil.copy(input_path, output_path)
    return file_count, report, tree_errors

  def process_tree_inplace(self, root_directory):
    """Process a directory of python files in place."""
    files_to_process = []
    for dir_name, _, file_list in os.walk(root_directory):
      py_files = [os.path.join(dir_name,
                               f) for f in file_list if f.endswith(".py")]
      files_to_process += py_files

    file_count = 0
    tree_errors = {}
    report = ""
    report += ("=" * 80) + "\n"
    report += "Input tree: %r\n" % root_directory
    report += ("=" * 80) + "\n"

    for path in files_to_process:
      file_count += 1
      _, l_report, l_errors = self.process_file(path, path)
      tree_errors[path] = l_errors
      report += l_report

    return file_count, report, tree_errors


text:
NORI_NAMESPACE_BEGIN

class WhittedIntegrator : public Integrator {
public:
    WhittedIntegrator(const PropertyList &props) {}

    Color3f Li(const Scene *scene, Sampler *sampler, const Ray3f &ray) const {
        Intersection its;
        if (!scene->rayIntersect(ray, its))
            return Color3f(0.0f);

        if (!its.mesh->getBSDF()->isDiffuse()) {
            if (sampler->next1D() > 0.95) return Color3f(0.0f);

            BSDFQueryRecord bsdfRecord{its.shFrame.toLocal(-ray.d)};
            const Color3f c = its.mesh->getBSDF()->sample(bsdfRecord, sampler->next2D());
            const Ray3f newRay{its.p, its.shFrame.toWorld(bsdfRecord.wo)};
            return c * this->Li(scene, sampler, newRay) / 0.95;
        }

        // Diffuse
        std::vector<const Mesh*> emitters;
        for (auto &m : scene->getMeshes())
            if (m->isEmitter()) emitters.push_back(m);

        DiscretePDF emitter_pdf;
        for (auto &e : emitters)
            emitter_pdf.append(1);
        emitter_pdf.normalize();

        int idx = emitter_pdf.sample(sampler->next1D());
        const Mesh* emitter = emitters[idx];

        Point3f p;
        Normal3f n;
        emitter->samplePosition(sampler->next2D(), p, n);

        // Directions
        Vector3f l2px = (p - its.p).normalized();

        // Emitter is seen?
        Intersection em_its;
        if ((!scene->rayIntersect(Ray3f{its.p, l2px}, em_its)) || (em_its.mesh != emitter)) return Color3f(0.0f);

        Vector3f l2px_local = its.shFrame.toLocal(l2px);

        BSDFQueryRecord bsdf_record{its.shFrame.toLocal(-ray.d), l2px_local, ESolidAngle};
        Color3f bsdf = its.mesh->getBSDF()->eval(bsdf_record);
        Color3f radiance = emitter->getEmitter()->eval(em_its, -l2px);

        // Geometric term
        float dot1 = std::max((-l2px_local).dot(its.shFrame.toLocal(n)), 0.0f);
        float dot2 = std::max(its.shFrame.cosTheta(l2px_local), 0.0f);
        float geo = dot1 * dot2 / ((p - its.p).dot(p - its.p));

        return radiance * bsdf * Color3f(geo / (emitter->PDF() * emitter_pdf[idx]));
    }

    std::string toString() const {
        return "WhittedIntegrator[]";
    }
};

NORI_REGISTER_CLASS(WhittedIntegrator, "whitted");
NORI_NAMESPACE_END

redpajama_set_name: RedPajamaGithub


text:
@interface NSDate (JKUtilities)
+ (NSCalendar *)jk_currentCalendar; // avoid bottlenecks

#pragma mark ----short time 格式化的时间
@property (nonatomic, readonly) NSString *jk_shortString;
@property (nonatomic, readonly) NSString *jk_shortDateString;
@property (nonatomic, readonly) NSString *jk_shortTimeString;
@property (nonatomic, readonly) NSString *jk_mediumString;
@property (nonatomic, readonly) NSString *jk_mediumDateString;
@property (nonatomic, readonly) NSString *jk_mediumTimeString;
@property (nonatomic, readonly) NSString *jk_longString;
@property (nonatomic, readonly) NSString *jk_longDateString;
@property (nonatomic, readonly) NSString *jk_longTimeString;

///使用dateStyle timeStyle格式化时间
- (NSString *)jk_stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle;

#pragma mark ---- 从当前日期相对日期时间
///明天
+ (NSDate *)jk_dateTomorrow;
///昨天
+ (NSDate *)jk_dateYesterday;
///今天后几天
+ (NSDate *)jk_dateWithDaysFromNow:(NSInteger)days;
///今天前几天
+ (NSDate *)jk_dateWithDaysBeforeNow:(NSInteger)days;
///当前小时后dHours个小时
+ (NSDate *)jk_dateWithHoursFromNow:(NSInteger)dHours;
///当前小时前dHours个小时
+ (NSDate *)jk_dateWithHoursBeforeNow:(NSInteger)dHours;
///当前分钟后dMinutes个分钟
+ (NSDate *)jk_dateWithMinutesFromNow:(NSInteger)dMinutes;
///当前分钟前dMinutes个分钟
+ (NSDate *)jk_dateWithMinutesBeforeNow:(NSInteger)dMinutes;

#pragma mark ---- Comparing dates 比较时间
///比较年月日是否相等
- (BOOL)jk_isEqualToDateIgnoringTime:(NSDate *)aDate;
///是否是今天
- (BOOL)jk_isToday;
///是否是明天
- (BOOL)jk_isTomorrow;
///是否是昨天
- (BOOL)jk_isYesterday;

///是否是同一周
- (BOOL)jk_isSameWeekAsDate:(NSDate *)aDate;
///是否是本周
- (BOOL)jk_isThisWeek;
///是否是本周的下周
- (BOOL)jk_isNextWeek;
///是否是本周的上周
- (BOOL)jk_isLastWeek;

///是否是同一月
- (BOOL)jk_isSameMonthAsDate:(NSDate *)aDate;
///是否是本月
- (BOOL)jk_isThisMonth;
///是否是本月的下月
- (BOOL)jk_isNextMonth;
///是否是本月的上月
- (BOOL)jk_isLastMonth;

///是否是同一年
- (BOOL)jk_isSameYearAsDate:(NSDate *)aDate;
///是否是今年
- (BOOL)jk_isThisYear;
///是否是今年的下一年
- (BOOL)jk_isNextYear;
///是否是今年的上一年
- (BOOL)jk_isLastYear;

///是否提前aDate
- (BOOL)jk_isEarlierThanDate:(NSDate *)aDate;
///是否晚于aDate
- (BOOL)jk_isLaterThanDate:(NSDate *)aDate;
///是否晚是未来
- (BOOL)jk_isInFuture;
///是否晚是过去
- (BOOL)jk_isInPast;

///是否是工作日
- (BOOL)jk_isTypicallyWorkday;
///是否是周末
- (BOOL)jk_isTypicallyWeekend;

#pragma mark ---- Adjusting dates 调节时间
///增加dYears年
- (NSDate *)jk_dateByAddingYears:(NSInteger)dYears;
///减少dYears年
- (NSDate *)jk_dateBySubtractingYears:(NSInteger)dYears;
///增加dMonths月
- (NSDate *)jk_dateByAddingMonths:(NSInteger)dMonths;
///减少dMonths月
- (NSDate *)jk_dateBySubtractingMonths:(NSInteger)dMonths;
///增加dDays天
- (NSDate *)jk_dateByAddingDays:(NSInteger)dDays;
///减少dDays天
- (NSDate *)jk_dateBySubtractingDays:(NSInteger)dDays;
///增加dHours小时
- (NSDate *)jk_dateByAddingHours:(NSInteger)dHours;
///减少dHours小时
- (NSDate *)jk_dateBySubtractingHours:(NSInteger)dHours;
///增加dMinutes分钟
- (NSDate *)jk_dateByAddingMinutes:(NSInteger)dMinutes;
///减少dMinutes分钟
- (NSDate *)jk_dateBySubtractingMinutes:(NSInteger)dMinutes;

#pragma mark ---- 时间间隔
///比aDate晚多少分钟
- (NSInteger)jk_minutesAfterDate:(NSDate *)aDate;
///比aDate早多少分钟
- (NSInteger)jk_minutesBeforeDate:(NSDate *)aDate;
///比aDate晚多少小时
- (NSInteger)jk_hoursAfterDate:(NSDate *)aDate;
///比aDate早多少小时
- (NSInteger)jk_hoursBeforeDate:(NSDate *)aDate;
///比aDate晚多少天
- (NSInteger)jk_daysAfterDate:(NSDate *)aDate;
///比aDate早多少天
- (NSInteger)jk_daysBeforeDate:(NSDate *)aDate;

///与anotherDate间隔几天
- (NSInteger)jk_distanceDaysToDate:(NSDate *)anotherDate;
///与anotherDate间隔几月
- (NSInteger)jk_distanceMonthsToDate:(NSDate *)anotherDate;
///与anotherDate间隔几年
- (NSInteger)jk_distanceYearsToDate:(NSDate *)anotherDate;
@end


text:
#ifndef TENSORFLOW_CORE_PROFILER_LIB_PROFILER_COLLECTION_H_
#define TENSORFLOW_CORE_PROFILER_LIB_PROFILER_COLLECTION_H_

#include <memory>
#include <vector>

#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/profiler/lib/profiler_interface.h"
#include "tensorflow/core/profiler/protobuf/xplane.pb.h"

namespace tensorflow {
namespace profiler {

// ProfilerCollection multiplexes ProfilerInterface calls into a collection of
// profilers.
class ProfilerCollection : public ProfilerInterface {
 public:
  explicit ProfilerCollection(
      std::vector<std::unique_ptr<ProfilerInterface>> profilers);

  Status Start() override;

  Status Stop() override;

  Status CollectData(tensorflow::profiler::XSpace* space) override;

 private:
  std::vector<std::unique_ptr<ProfilerInterface>> profilers_;
};

}  // namespace profiler
}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_PROFILER_LIB_PROFILER_COLLECTION_H_


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use app\models\Product;

class Cart extends Model {

    public static function add($id) {
        $session = Yii::$app->session;
        $last = $session['cart'] ?: [];
        if (!isset($last[$id])):
            $product = Product::getOne($id);
            $last[$id] = $product->attributes;
            $last[$id]['quantity'] = 1;
        else:
            $last[$id]['quantity'] = $last[$id]['quantity'] + 1;
        endif;
        $session->set('cart', $last);
    }

    public static function delete($id) {
        $session = Yii::$app->session;
        if (isset($session['cart'][$id])):
            unset($_SESSION['cart'][$id]);
            foreach ($_SESSION as $key => $value) {
                $session[$key] = $value;
            }
        endif;
    }

    public static function deleteAll() {
        $session = Yii::$app->session;
        if (isset($session['cart'])):
            unset($session['cart']);
        endif;
    }

    public static function update($post) {
        foreach ($post as $key=>$value):
            $session = Yii::$app->session;
            $last = $session['cart'] ?: [];
            if (isset($last[$key])):
                $last[$key]['quantity'] = $value;
                $session->set('cart', $last);
            endif;
        endforeach;
    }

}


text:
set -o errexit
set -o nounset
set -o pipefail

run_kubectl_run_tests() {
  set -o nounset
  set -o errexit

  create_and_use_new_namespace
  kube::log::status "Testing kubectl run"
  ## kubectl run should create deployments, jobs or cronjob
  # Pre-Condition: no Job exists
  kube::test::get_object_assert jobs "{{range.items}}{{${id_field:?}}}:{{end}}" ''
  # Command
  kubectl run pi --generator=job/v1 "--image=${IMAGE_PERL}" --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(20)' "${kube_flags[@]:?}"
  # Post-Condition: Job "pi" is created
  kube::test::get_object_assert jobs "{{range.items}}{{$id_field}}:{{end}}" 'pi:'
  # Describe command (resource only) should print detailed information
  kube::test::describe_resource_assert pods "Name:" "Image:" "Node:" "Labels:" "Status:" "Controlled By"
  # Clean up
  kubectl delete jobs pi "${kube_flags[@]}"
  # Post-condition: no pods exist.
  kube::test::wait_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''

  # Pre-Condition: no Deployment exists
  kube::test::get_object_assert deployment "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl run nginx-extensions "--image=${IMAGE_NGINX}" "${kube_flags[@]}"
  # Post-Condition: Deployment "nginx" is created
  kube::test::get_object_assert deployment.apps "{{range.items}}{{$id_field}}:{{end}}" 'nginx-extensions:'
  # new generator was used
  output_message=$(kubectl get deployment.apps/nginx-extensions -o jsonpath='{.spec.revisionHistoryLimit}')
  kube::test::if_has_string "${output_message}" '10'
  # Clean up
  kubectl delete deployment nginx-extensions "${kube_flags[@]}"
  # Command
  kubectl run nginx-apps "--image=${IMAGE_NGINX}" --generator=deployment/apps.v1 "${kube_flags[@]}"
  # Post-Condition: Deployment "nginx" is created
  kube::test::get_object_assert deployment.apps "{{range.items}}{{$id_field}}:{{end}}" 'nginx-apps:'
  # and new generator was used, iow. new defaults are applied
  output_message=$(kubectl get deployment/nginx-apps -o jsonpath='{.spec.revisionHistoryLimit}')
  kube::test::if_has_string "${output_message}" '10'
  # Clean up
  kubectl delete deployment nginx-apps "${kube_flags[@]}"

  # Pre-Condition: no Job exists
  kube::test::get_object_assert cronjobs "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl run pi --schedule="*/5 * * * *" --generator=cronjob/v1beta1 "--image=${IMAGE_PERL}" --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(20)' "${kube_flags[@]}"
  # Post-Condition: CronJob "pi" is created
  kube::test::get_object_assert cronjobs "{{range.items}}{{$id_field}}:{{end}}" 'pi:'

  # Pre-condition: cronjob has perl image, not custom image
  output_message=$(kubectl get cronjob/pi -o jsonpath='{..image}')
  kube::test::if_has_not_string "${output_message}" "custom-image"
  kube::test::if_has_string     "${output_message}" "${IMAGE_PERL}"
  # Set cronjob image
  kubectl set image cronjob/pi '*=custom-image'
  # Post-condition: cronjob has custom image, not perl image
  output_message=$(kubectl get cronjob/pi -o jsonpath='{..image}')
  kube::test::if_has_string     "${output_message}" "custom-image"
  kube::test::if_has_not_string "${output_message}" "${IMAGE_PERL}"

  # Clean up
  kubectl delete cronjobs pi "${kube_flags[@]}"

  set +o nounset
  set +o errexit
}

run_cmd_with_img_tests() {
  set -o nounset
  set -o errexit

  create_and_use_new_namespace
  kube::log::status "Testing cmd with image"

  # Test that a valid image reference value is provided as the value of --image in `kubectl run <name> --image`
  output_message=$(kubectl run test1 --image=validname)
  kube::test::if_has_string "${output_message}" 'deployment.apps/test1 created'
  kubectl delete deployments test1
  # test invalid image name
  output_message=$(! kubectl run test2 --image=InvalidImageName 2>&1)
  kube::test::if_has_string "${output_message}" 'error: Invalid image name "InvalidImageName": invalid reference format'

  set +o nounset
  set +o errexit
}


text:
namespace juce
{

//==============================================================================
/**
    A dialog-box style window.

    This class is a convenient way of creating a DocumentWindow with a close button
    that can be triggered by pressing the escape key.

    Any of the methods available to a DocumentWindow or ResizableWindow are also
    available to this, so it can be made resizable, have a menu bar, etc.

    You can either override or use an instance of the DialogWindow class directly,
    or you can use a DialogWindow::LaunchOptions structure to quickly set up and
    launch a box containing a content component.

    If you use the class directly, you'll need to override the
    DocumentWindow::closeButtonPressed() method to handle the user clicking the close
    button - for more info, see the DocumentWindow help.

    @see DocumentWindow, ResizableWindow

    @tags{GUI}
*/
class JUCE_API  DialogWindow   : public DocumentWindow
{
public:
    //==============================================================================
    /** Creates a DialogWindow.

        @param name                 the name to give the component - this is also
                                    the title shown at the top of the window. To change
                                    this later, use setName()
        @param backgroundColour     the colour to use for filling the window's background.
        @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
                                            close button to be triggered
        @param addToDesktop         if true, the window will be automatically added to the
                                    desktop; if false, you can use it as a child component
    */
    DialogWindow (const String& name,
                  Colour backgroundColour,
                  bool escapeKeyTriggersCloseButton,
                  bool addToDesktop = true);

    /** Destructor.
        If a content component has been set with setContentOwned(), it will be deleted.
    */
    ~DialogWindow() override;

    //==============================================================================
    /** This class defines a collection of settings to be used to open a DialogWindow.

        The easiest way to open a DialogWindow is to create yourself a LaunchOptions structure,
        initialise its fields with the appropriate details, and then call its launchAsync()
        method to launch the dialog.
    */
    struct JUCE_API  LaunchOptions
    {
        LaunchOptions() noexcept;

        /** The title to give the window. */
        String dialogTitle;

        /** The background colour for the window. */
        Colour dialogBackgroundColour = Colours::lightgrey;

        /** The content component to show in the window. This must not be null!
            Using an OptionalScopedPointer to hold this pointer lets you indicate whether
            you'd like the dialog to automatically delete the component when the dialog
            has terminated.
        */
        OptionalScopedPointer<Component> content;

        /** If this is not a nullptr, it indicates a component that you'd like to position this
            dialog box in front of. See the DocumentWindow::centreAroundComponent() method for
            more info about this parameter.
        */
        Component* componentToCentreAround = nullptr;

        /** If true, then the escape key will trigger the dialog's close button. */
        bool escapeKeyTriggersCloseButton = true;
        /** If true, the dialog will use a native title bar. See TopLevelWindow::setUsingNativeTitleBar() */
        bool useNativeTitleBar = true;
        /** If true, the window will be resizable. See ResizableWindow::setResizable() */
        bool resizable = true;
        /** Indicates whether to use a border or corner resizer component. See ResizableWindow::setResizable() */
        bool useBottomRightCornerResizer = false;

        /** Launches a new modal dialog window.
            This will create a dialog based on the settings in this structure,
            launch it modally, and return immediately. The window that is returned
            will be automatically deleted when the modal state is terminated.

            When the dialog's close button is clicked, it'll automatically terminate its
            modal state, but you can also do this programmatically by calling
            exitModalState (returnValue) on the DialogWindow.

            If your content component needs to find the dialog window that it is
            contained in, a quick trick is to do this:
            @code
            if (DialogWindow* dw = contentComponent->findParentComponentOfClass<DialogWindow>())
                dw->exitModalState (1234);
            @endcode
        */
        DialogWindow* launchAsync();

        /** Creates a new DialogWindow instance with these settings.
            This method simply creates the window, it doesn't run it modally. In most cases
            you'll want to use launchAsync() or runModal() instead.
        */
        DialogWindow* create();

       #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
        /** Launches and runs the dialog modally, returning the status code that was
            used to terminate the modal loop.

            Note that running modal loops inline is a BAD technique. If possible, always
            use launchAsync() instead of this method.
        */
        int runModal();
       #endif

        JUCE_DECLARE_NON_COPYABLE (LaunchOptions)
    };

    //==============================================================================
    /** Easy way of quickly showing a dialog box containing a given component.

        Note: This method has been superseded by the DialogWindow::LaunchOptions structure,
        which does the same job with some extra flexibility. The showDialog method is here
        for backwards compatibility, but please use DialogWindow::LaunchOptions in new code.

        This will open and display a DialogWindow containing a given component, making it
        modal, but returning immediately to allow the dialog to finish in its own time. If
        you want to block and run a modal loop until the dialog is dismissed, use showModalDialog()
        instead.

        To close the dialog programmatically, you should call exitModalState (returnValue) on
        the DialogWindow that is created. To find a pointer to this window from your
        contentComponent, you can do something like this:
        @code
        if (DialogWindow* dw = contentComponent->findParentComponentOfClass<DialogWindow>())
            dw->exitModalState (1234);
        @endcode

        @param dialogTitle          the dialog box's title
        @param contentComponent     the content component for the dialog box. Make sure
                                    that this has been set to the size you want it to
                                    be before calling this method. The component won't
                                    be deleted by this call, so you can re-use it or delete
                                    it afterwards
        @param componentToCentreAround  if this is not a nullptr, it indicates a component that
                                    you'd like to show this dialog box in front of. See the
                                    DocumentWindow::centreAroundComponent() method for more
                                    info on this parameter
        @param backgroundColour     a colour to use for the dialog box's background colour
        @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
                                            close button to be triggered
        @param shouldBeResizable    if true, the dialog window has either a resizable border, or
                                    a corner resizer
        @param useBottomRightCornerResizer     if shouldBeResizable is true, this indicates whether
                                    to use a border or corner resizer component. See ResizableWindow::setResizable()
    */
    static void showDialog (const String& dialogTitle,
                            Component* contentComponent,
                            Component* componentToCentreAround,
                            Colour backgroundColour,
                            bool escapeKeyTriggersCloseButton,
                            bool shouldBeResizable = false,
                            bool useBottomRightCornerResizer = false);

   #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
    /** Easy way of quickly showing a dialog box containing a given component.

        Note: This method has been superseded by the DialogWindow::LaunchOptions structure,
        which does the same job with some extra flexibility. The showDialog method is here
        for backwards compatibility, but please use DialogWindow::LaunchOptions in new code.

        This will open and display a DialogWindow containing a given component, returning
        when the user clicks its close button.

        It returns the value that was returned by the dialog box's runModalLoop() call.

        To close the dialog programmatically, you should call exitModalState (returnValue) on
        the DialogWindow that is created. To find a pointer to this window from your
        contentComponent, you can do something like this:
        @code
        if (DialogWindow* dw = contentComponent->findParentComponentOfClass<DialogWindow>())
            dw->exitModalState (1234);
        @endcode

        @param dialogTitle          the dialog box's title
        @param contentComponent     the content component for the dialog box. Make sure
                                    that this has been set to the size you want it to
                                    be before calling this method. The component won't
                                    be deleted by this call, so you can re-use it or delete
                                    it afterwards
        @param componentToCentreAround  if this is not a nullptr, it indicates a component that
                                    you'd like to show this dialog box in front of. See the
                                    DocumentWindow::centreAroundComponent() method for more
                                    info on this parameter
        @param backgroundColour     a colour to use for the dialog box's background colour
        @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
                                            close button to be triggered
        @param shouldBeResizable    if true, the dialog window has either a resizable border, or
                                    a corner resizer
        @param useBottomRightCornerResizer     if shouldBeResizable is true, this indicates whether
                                    to use a border or corner resizer component. See ResizableWindow::setResizable()
    */
    static int showModalDialog (const String& dialogTitle,
                                Component* contentComponent,
                                Component* componentToCentreAround,
                                Colour backgroundColour,
                                bool escapeKeyTriggersCloseButton,
                                bool shouldBeResizable = false,
                                bool useBottomRightCornerResizer = false);
   #endif

    /** Called when the escape key is pressed.
        This can be overridden to do things other than the default behaviour, which is to hide
        the window. Return true if the key has been used, or false if it was ignored.
    */
    virtual bool escapeKeyPressed();

protected:
    //==============================================================================
    /** @internal */
    void resized() override;
    /** @internal */
    bool keyPressed (const KeyPress&) override;

private:
    bool escapeKeyTriggersCloseButton;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow)
};

} // namespace juce


text:
$packageName = 'sandboxie.beta'
$packageId = 'sandboxie'

try {
	$fileType = 'EXE'
	$silentArgs = '/S /remove'
	$validExitCodes = @(0)
	$unPathx86 = 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
	$unPath = 'HKLM:SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
	$chocoRoot = $env:ChocolateyInstall
	if ($chocoRoot -eq $null) {
		$chocoRoot = "$env:programdata\chocolatey"
	}
	$chocoLib = Join-Path $chocoRoot 'lib'
	if (Test-Path $chocoLib\$packageId.install.[0-9]*) {
		Remove-Item "$chocoLib\$packageId.[0-9]*" -Force -Recurse -ErrorAction SilentlyContinue
		Write-Debug "Deleted $chocoLib\$packageId.*"
	}
	if (Test-Path $chocoLib\$packageId.[0-9]*) {
		Remove-Item "$chocoLib\$packageId.[0-9]*" -Force -Recurse -ErrorAction SilentlyContinue
		Write-Debug "Deleted $chocoLib\$packageId.*"
	}
	if (Test-Path $unPathx86\$packageId) {
		$unString = (Get-ItemProperty $unPathx86\$packageId UninstallString).UninstallString
	}
	if (Test-Path $unPath\$packageId) {
		$unString = (Get-ItemProperty $unPath\$packageId UninstallString).UninstallString
	}
	if ($unString | select-string -pattern / ) {
		$unProg = $unString | %{ $_.Split(' /')[0]; }
		Uninstall-ChocolateyPackage $packageName $fileType $silentArgs $unProg -validExitCodes $validExitCodes
  }
  Write-ChocolateySuccess $packageName
} catch {
	Write-ChocolateyFailure $packageName $($_.Exception.Message)
	throw
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/z_bg_c_act_publish_step"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:maxLines="100"
        android:padding="10dp"
        android:singleLine="false"
        android:textSize="12sp" />

    <include layout="@layout/z_view_line" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:cacheColorHint="@color/transparent"
        android:divider="@color/z_item_line"
        android:dividerHeight="0.5dp"
        android:fadingEdge="none"
        android:fadingEdgeLength="0dp"
        android:listSelector="@drawable/selector_list_item"
        android:scrollbars="none" />
</LinearLayout>


text:
/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include <unordered_map>

#include <caf/config_value.hpp>
#include <caf/none.hpp>

#include "vast/data.hpp"

#include "vast/system/key_value_store.hpp"

namespace vast::system {

template <class Key, class Value>
struct data_store_state {
  std::unordered_map<Key, Value> store;
  static inline const char* name = "data-store";
};

/// A key-value store that stores its data in a `std::unordered_map`.
/// @param self The actor handle.
template <class Key, class Value>
typename key_value_store_type<Key, Value>::behavior_type
data_store(
  typename key_value_store_type<Key, Value>::template stateful_pointer<
    data_store_state<Key, Value>
  > self) {
  return {
    [=](put_atom, const Key& key, Value& value) {
      self->state.store[key] = std::move(value);
      return ok_atom::value;
    },
    [=](add_atom, const Key& key, const Value& value) -> caf::result<Value> {
      auto& v = self->state.store[key];
      auto old = v;
      v += value;
      return old;
    },
    [=](delete_atom, const Key& key) {
      self->state.store.erase(key);
      return ok_atom::value;
    },
    [=](get_atom, const Key& key) -> caf::result<optional<Value>> {
      auto i = self->state.store.find(key);
      if (i == self->state.store.end())
        return caf::none;
      return i->second;
    },
    [=](status_atom) -> caf::config_value::dictionary {
      caf::dictionary<caf::config_value> result;
      result.emplace("store-size", self->state.store.size());
      return result;
    }
  };
}

} // namespace vast::system


text:
# Runs every time a package is installed in a project

param($installPath, $toolsPath, $package, $project)

# $installPath is the path to the folder where the package is installed.
# $toolsPath is the path to the tools directory in the folder where the package is installed.
# $package is a reference to the package object.
# $project is a reference to the project the package was installed to.

@"

============================================================
PowerTasks - Convention based task runner using Invoke-Build
============================================================
"@ | Write-Host

# Install the pt.bat file
Copy-Item "$installPath\pt.bat" .
Push-Location (Split-Path $project.FullName)
$packagesPath = (Split-Path $installPath | Resolve-Path -Relative)
Pop-Location
$content = Get-Content "pt.bat" |
	%{ $_ -replace "%POWERTASKS_PATH%", (Resolve-Path $installPath -Relative) } |
	%{ $_ -replace "%PROJECT_PATH%", (Split-Path $project.FullName | Resolve-Path -Relative) } |
	%{ $_ -replace "%PROJECT_NAME%", $project.Name } |
	%{ $_ -replace "%PACKAGES_PATH%", $packagesPath }
Set-Content "pt.bat" $content
Write-Host "Installed pt.bat"

# Make sure that the .Tasks file is set to build action "None"
$tasksItem = $project.ProjectItems.Item(".Tasks.ps1")
$tasksItem.Properties.Item("BuildAction").Value = [int]0

# Make sure that the packages file is set to build action "None"
$packagesItem = $project.ProjectItems.Item("packages.config")
$packagesItem.Properties.Item("BuildAction").Value = [int]0
$project.Save()


text:
'use strict';

var Chunk = require('prismarine-chunk')(require("../version"));
var Vec3 = require('vec3').Vec3;
var rand = require('random-seed');

function generation() {
  var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

  var seed = _ref.seed;
  var _ref$level = _ref.level;
  var level = _ref$level === undefined ? 50 : _ref$level;

  function generateChunk(chunkX, chunkZ) {
    var seedRand = rand.create(seed + ':' + chunkX + ':' + chunkZ);
    var chunk = new Chunk();
    for (var x = 0; x < 16; x++) {
      for (var z = 0; z < 16; z++) {
        var bedrockheighttop = 1 + seedRand(4);
        var bedrockheightbottom = 1 + seedRand(4);
        for (var y = 0; y < 128; y++) {
          // Nether only goes up to 128
          var block = undefined;
          var data = undefined;

          if (y < bedrockheightbottom) block = 7;else if (y < level) block = 87;else if (y > 127 - bedrockheighttop) block = 7;

          var pos = new Vec3(x, y, z);
          if (block) chunk.setBlockType(pos, block);
          if (data) chunk.setBlockData(pos, data);
          // Don't need to set light data in nether
        }
      }
    }
    return chunk;
  }
  return generateChunk;
}

module.exports = generation;
//# sourceMappingURL=../../maps/lib/worldGenerations/nether.js.map


text:
using System;

namespace Memoria.Prime
{
    public static class ExtensionMethodsArray
    {
        public static ArraySegment<T> Segment<T>(this T[] array, Int32 offset)
        {
            return new ArraySegment<T>(array, offset, array.Length - offset);
        }

        public static ArraySegment<T> Segment<T>(this T[] array, Int32 offset, Int32 size)
        {
            return new ArraySegment<T>(array, offset, size);
        }
    }
}


text:
<resources>
    <string name="app_name">TagLib</string>
</resources>


text:
package com.faeris.lib;

import android.os.Handler;
import android.os.Message;
import java.lang.ref.WeakReference;

import com.faeris.lib.Fs_Application.InputBoxMessage;

public class Fs_UiEvent extends Handler {
	public final static int UIEVENT_EXIT=1;
	public final static int UIEVENT_SHOW_INPUT_BOX_DIALOG=2;
	public final static int UIEVENT_RUNNABLE=3;

	private WeakReference<Fs_Activity> m_activity;

	public Fs_UiEvent(Fs_Activity activity)
	{
		m_activity=new WeakReference<Fs_Activity>(activity);
	}

	public void handleMessage(Message msg)
	{
		switch(msg.what)
		{
			case Fs_UiEvent.UIEVENT_EXIT:
				exit(msg);
				break;
			case Fs_UiEvent.UIEVENT_SHOW_INPUT_BOX_DIALOG:
				showInputBoxDialog(msg);
				break;
			case Fs_UiEvent.UIEVENT_RUNNABLE:
				executeRunnable(msg.obj);
				break;

		}
	}
	public void executeRunnable(Object ob)
	{
		Runnable run=(Runnable)ob;
		run.run();
	}

	public void exit(Message msg)
	{
		Fs_Application.exit();
	}

	public void showInputBoxDialog(Message msg)
	{
		InputBoxMessage e_msg=(InputBoxMessage) msg.obj;
		Fs_InputBoxDialog dialog=new Fs_InputBoxDialog(
				this.m_activity.get(),
				e_msg.title,
				e_msg.content,
				e_msg.inputMode,
				e_msg.inputFlag,
				e_msg.returnType,
				e_msg.maxLength);

		dialog.show();
	}

}


text:
from common import Modules, data_strings, load_yara_rules, PEParseModule, ModuleMetadata, is_ip_or_domain

class Solar(PEParseModule):
    def __init__(self):
        md = ModuleMetadata(
            module_name="solar",
            bot_name="Solar",
            description="Botnet",
            authors=["Brian Wallace (@botnet_hunter)"],
            version="1.0.0",
            date="March 21, 2015",
            references=[]
        )
        PEParseModule.__init__(self, md)
        self.yara_rules = None

    def _generate_yara_rules(self):
        if self.yara_rules is None:
            self.yara_rules = load_yara_rules("solarbot.yara")
        return self.yara_rules

    def get_bot_information(self, file_data):
        results = {}
        c2s = set()
        ip = None
        path = None
        next_is_path = False
        start_checking = False
        for s in data_strings(file_data, 1):
            if s == "C:\\swi.txt":
                start_checking = True
            if start_checking and path is None:
                if next_is_path:
                    if s.startswith("http://"):
                        ip = None
                        path = None
                        next_is_path = False
                        continue
                    path = s
                    next_is_path = False
                elif is_ip_or_domain(s) and ip is None:
                    ip = s
                    next_is_path = True
        if ip is not None and path is not None:
            results['c2_uri'] = "http://{0}{1}".format(ip, path)
        return results

Modules.list.append(Solar())


text:
/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.jmw.konfman.model;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetails;

/**
 * Represents a user in the Konfman application
 * @author judahw
 *
 */
@Entity
@Table(name="Users")
public class User extends BaseObject implements UserDetails{
    private static final long serialVersionUID = 3257568390917667126L;

    private Long id;
    private String firstName;
    private String lastName;
    private String phone;
    private String email;
    private String password;
    private String verifyPassword;

    private String adminStatus;
    private Floor defaultFloor;
    private Date birthday;
    private String username;
    private boolean enabled = true;

    private Set<Authority> roles = new HashSet<Authority>();
	private Set<Room> administeredRooms = new HashSet<Room>();
    private List<Reservation> reservations;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getAdminStatus() {
		return adminStatus;
	}

	public void setAdminStatus(String adminStatus) {
		this.adminStatus = adminStatus;
	}

	@ManyToOne
	public Floor getDefaultFloor() {
		return defaultFloor;
	}

	public void setDefaultFloor(Floor defaultFloor) {
		this.defaultFloor = defaultFloor;
	}

    /**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the enabled
	 */
	public boolean isEnabled() {
		return enabled;
	}

	/**
	 * @param enabled the enabled value to set
	 */
	public void setEnabled(boolean enabled) {
		this.enabled = true;
	}

	/**
	 * Gets the rooms that this user can administer
	 * @return the administeredRooms
	 */
	@ManyToMany(cascade = CascadeType.ALL)
	@OrderBy("name")
    public Set<Room> getAdministeredRooms() {
		return administeredRooms;
	}

	/**
	 * Sets the rooms that this user can administer
	 * @param administeredRooms the administeredRooms to set
	 */
	public void setAdministeredRooms(Set<Room> administeredRooms) {
		this.administeredRooms = administeredRooms;
	}

	/**
	 * Adds a room to the user's set of administered rooms
	 * @param room the room to add
	 * @return true if it was added false if it already exists
	 */
	public boolean addAdministeredRoom(Room room){
		return this.administeredRooms.add(room);
	}

	/**
	 * Removes a room from the user's set of administered rooms
	 * @param room the room to remove
	 * @return true if the room was found and removed
	 */
	public boolean removeAdminsteredRoom(Room room){
		return this.administeredRooms.remove(room);
	}

	/**
     * @return Returns firstName and lastName
     */
    @Transient
	public String getFullName() {
        return lastName + ", " + firstName;
    }

    /**
     * Needed for comparison. Compares the value of the id.
     */
    public boolean equals(Object o) {
    	if (o != null){
	    	if (o.getClass().equals(User.class)) {
	    		User user = (User)o;
	    		if (user.id != null && (user.id.longValue() == id.longValue())) {
	    			return true;
	    		}
	    	}
    	}
    	return false;
    }

    /**
     * Needed for comparison. Returns the hashcode of the id object
     */
    public int hashCode() {
    	if (id != null){
    		return id.hashCode();
    	}
    	return 0;
    }

    public String toString() {
    	return firstName + " " + lastName;
    }

    /**
	 * @return the reservations
	 */
	@OneToMany(mappedBy = "user")
	@OrderBy("startDateTime")
    public List<Reservation> getReservations() {
		return reservations;
	}

	/**
	 * @param reservations the reservations to set
	 */
	public void setReservations(List<Reservation> reservations) {
		this.reservations = reservations;
	}

    /**
	 * Gets the roles that this user is assigned to.
	 * Must be eager fetched so that the user object can be used for security
	 * outside of the original transaction.
	 * @return the authorities
	 */
	@ManyToMany(fetch = FetchType.EAGER)
	public Set<Authority> getRoles() {
		return roles;
	}

	/**
	 * @param authorities the authorities to set
	 */
	public void setRoles(Set<Authority> roles) {
		this.roles = roles;
	}

	public boolean addRoll(Authority authority){
		return roles.add(authority);
	}

	public boolean removeRoll(Authority authority){
		return roles.remove(authority);
	}

	@Transient
	public GrantedAuthority[] getAuthorities() {
		GrantedAuthority[] grantedAuthorities = new GrantedAuthority[0];
		return roles.toArray(grantedAuthorities);
	}

	@Transient
	public boolean isAccountNonExpired() {
		return true;
	}

	@Transient
	public boolean isAccountNonLocked() {
		return enabled;
	}

	@Transient
	public boolean isCredentialsNonExpired() {
		return true;
	}

	/**
	 * Sets variable to contain the confirmation password during a password change.
	 * @param verifyPassword the verifyPassword to set
	 */
	public void setVerifyPassword(String verifyPassword) {
		this.verifyPassword = verifyPassword;
	}

	/**
	 * Gets variable containing the confirmation password during a password change.
	 * @return the verifyPassword
	 */
	@Transient
	public String getVerifyPassword() {
		if (verifyPassword == null){
			return password;
		}
		return verifyPassword;
	}
}


text:
package org.jgroups.util;

import java.io.IOException;
import java.net.*;
import java.nio.channels.ServerSocketChannel;
import java.util.Map;

/**
 * Factory to create various types of sockets. For socket creation, a service name can be passed as argument:
 * an implementation could look up a service description (e.g. port) and create the socket, ignoring the passed port and
 * possibly also the bind address.

 * Ephemeral ports can be created by passing 0 as port, or (if the port is ignored), an implementation could pass in
 * a special service name (e.g. "EPHEMERAL"), this is implementation dependent.

 * The socket creation methods have the same parameter lists as the socket constructors, e.g.
 * {@link #createServerSocket(String, int, int)} is the same as {@link java.net.ServerSocket#ServerSocket(int, int)}.
 * @author Bela Ban
 */
public interface SocketFactory {
    Socket createSocket(String service_name) throws IOException;
    Socket createSocket(String service_name, String host, int port) throws IOException;
    Socket createSocket(String service_name, InetAddress address, int port) throws IOException;
    Socket createSocket(String service_name, String host, int port, InetAddress localAddr, int localPort) throws IOException;
    Socket createSocket(String service_name, InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException;

    ServerSocket createServerSocket(String service_name) throws IOException;
    ServerSocket createServerSocket(String service_name, int port) throws IOException;
    ServerSocket createServerSocket(String service_name, int port, int backlog) throws IOException;
    ServerSocket createServerSocket(String service_name, int port, int backlog, InetAddress bindAddr) throws IOException;

    @SuppressWarnings("UnusedParameters")
    default ServerSocketChannel createServerSocketChannel(String service_name) throws IOException {
        return ServerSocketChannel.open();
    }

    default ServerSocketChannel createServerSocketChannel(String service_name, int port) throws IOException {
        return createServerSocketChannel(service_name).bind(new InetSocketAddress(port));
    }

    default ServerSocketChannel createServerSocketChannel(String service_name, int port, int backlog) throws IOException {
        return createServerSocketChannel(service_name).bind(new InetSocketAddress(port), backlog);
    }

    default ServerSocketChannel createServerSocketChannel(String service_name, int port, int backlog, InetAddress bindAddr) throws IOException {
        return createServerSocketChannel(service_name).bind(new InetSocketAddress(bindAddr, port), backlog);
    }

    DatagramSocket createDatagramSocket(String service_name) throws SocketException;
    DatagramSocket createDatagramSocket(String service_name, SocketAddress bindaddr) throws SocketException;
    DatagramSocket createDatagramSocket(String service_name, int port) throws SocketException;
    DatagramSocket createDatagramSocket(String service_name, int port, InetAddress laddr) throws SocketException;

    MulticastSocket createMulticastSocket(String service_name) throws IOException;
    MulticastSocket createMulticastSocket(String service_name, int port) throws IOException;
    MulticastSocket createMulticastSocket(String service_name, SocketAddress bindaddr) throws IOException;

    void close(Socket sock) throws IOException;
    void close(ServerSocket sock) throws IOException;
    void close(DatagramSocket sock);

    /**
     * Returns all open sockets. This method can be used to list or close all open sockets.
     * @return A map of open sockets; keys are Sockets, ServerSockets, DatagramSockets or MulticastSockets, values are
     * the service names.
     */
    Map<Object,String> getSockets();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="@dimen/dp_20" />

            <gradient
                android:angle="90"
                android:centerColor="@color/color_progress_bg"
                android:centerX="0.75"
                android:endColor="@color/color_progress_bg"
                android:startColor="@color/color_progress_bg" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip
            android:clipOrientation="vertical"
            android:gravity="bottom" >
            <shape>
                <corners android:radius="@dimen/dp_20" />

                <gradient
                    android:angle="90"
                    android:centerColor="@color/color_progress"
                    android:centerX="0.75"
                    android:endColor="@color/color_progress"
                    android:startColor="@color/color_progress" />
            </shape>
        </clip>
    </item>

</layer-list>


text:
/*
    Parallel reduction

    This sample shows how to perform a reduction operation on an array of values
    to produce a single value.

    Reductions are a very common computation in parallel algorithms.  Any time
    an array of values needs to be reduced to a single value using a binary
    associative operator, a reduction can be used.  Example applications include
    statistics computaions such as mean and standard deviation, and image
    processing applications such as finding the total luminance of an
    image.

    This code performs sum reductions, but any associative operator such as
    min() or max() could also be used.

    It assumes the input size is a power of 2.

    COMMAND LINE ARGUMENTS

    "--shmoo":         Test performance for 1 to 32M elements with each of the 7 different kernels
    "--n=<N>":         Specify the number of elements to reduce (default 1048576)
    "--threads=<N>":   Specify the number of threads per block (default 128)
    "--kernel=<N>":    Specify which kernel to run (0-6, default 6)
    "--maxblocks=<N>": Specify the maximum number of thread blocks to launch (kernel 6 only, default 64)
    "--cpufinal":      Read back the per-block results and do final sum of block sums on CPU (default false)
    "--cputhresh=<N>": The threshold of number of blocks sums below which to perform a CPU final reduction (default 1)
    "-type=<T>":       The datatype for the reduction, where T is "int", "float", or "double" (default int)
*/

// CUDA Runtime
#include <cuda_runtime.h>

// Utilities and system includes
//#include <helper_cuda.h>
//#include <helper_functions.h>
#include <algorithm>

// includes, project
#include "reduction.h"
#include <stdio.h>

enum ReduceType
{
    REDUCE_INT,
    REDUCE_FLOAT,
    REDUCE_DOUBLE
};

////////////////////////////////////////////////////////////////////////////////
// declaration, forward
bool runTest(int argc, char **argv, ReduceType datatype);

#define MAX_BLOCK_DIM_SIZE 65535

#ifdef WIN32
#define strcasecmp strcmpi
#endif

extern "C"
bool isPow2(unsigned int x)
{
    return ((x&(x-1))==0);
}

////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
    printf("%s Starting...\n\n", argv[0]);

    char *typeChoice = 0;
    //getCmdLineArgumentString(argc, (const char **) argv, "type", &typeChoice);

    ReduceType datatype = REDUCE_INT;

    /*if (0 != typeChoice)
    {
        if (!strcasecmp(typeChoice, "float"))
        {
            datatype = REDUCE_FLOAT;
        }
        else if (!strcasecmp(typeChoice, "double"))
        {
            datatype = REDUCE_DOUBLE;
        }
        else
        {
            datatype = REDUCE_INT;
        }
    }*/

    /*cudaDeviceProp deviceProp;
    deviceProp.major = 1;
    deviceProp.minor = 0;
    int minimumComputeVersion = 10;

    if (datatype == REDUCE_DOUBLE)
    {
        deviceProp.minor = 3;
        minimumComputeVersion = 13;
    }*/

    //int dev;

    //dev = findCudaDevice(argc, (const char **)argv);

    //checkCudaErrors(cudaGetDeviceProperties(&deviceProp, dev));

    /*if ((deviceProp.major * 10 + deviceProp.minor) >= minimumComputeVersion)
    {
        printf("Using Device %d: %s\n\n", dev, deviceProp.name);
        checkCudaErrors(cudaSetDevice(dev));
    }
    else
    {
        printf("Error: the selected device does not support the minimum compute capability of %d.%d.\n\n",
               minimumComputeVersion / 10, minimumComputeVersion % 10);

        cudaDeviceReset();
        exit(EXIT_FAILURE);
    }*/

    printf("Reducing array of type %s\n\n", typeChoice);

    bool bResult = false;

    /*switch (datatype)
    {
        default:
        case REDUCE_INT:
            bResult = runTest<int>(argc, argv, datatype);
            break;

        case REDUCE_FLOAT:
            bResult = runTest<float>(argc, argv, datatype);
            break;

        case REDUCE_DOUBLE:*/
    bResult = runTest(argc, argv, datatype);
            /*break;
    }*/

    cudaDeviceReset();
    printf(bResult ? "Test passed\n" : "Test failed!\n");
}

////////////////////////////////////////////////////////////////////////////////
//! Compute sum reduction on CPU
//! We use Kahan summation for an accurate sum of large arrays.
//! http://en.wikipedia.org/wiki/Kahan_summation_algorithm
//!
//! @param data       pointer to input data
//! @param size       number of input data elements
////////////////////////////////////////////////////////////////////////////////
template<class T>
T reduceCPU(T *data, int size)
{
    T sum = data[0];
    T c = (T)0.0;

    for (int i = 1; i < size; i++)
    {
        T y = data[i] - c;
        T t = sum + y;
        c = (t - sum) - y;
        sum = t;
    }

    return sum;
}

unsigned int nextPow2(unsigned int x)
{
    --x;
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    return ++x;
}

#ifndef MIN
#define MIN(x,y) ((x < y) ? x : y)
#endif

////////////////////////////////////////////////////////////////////////////////
// Compute the number of threads and blocks to use for the given reduction kernel
// For the kernels >= 3, we set threads / block to the minimum of maxThreads and
// n/2. For kernels < 3, we set to the minimum of maxThreads and n.  For kernel
// 6, we observe the maximum specified number of blocks, because each thread in
// that kernel can process a variable number of elements.
////////////////////////////////////////////////////////////////////////////////
void getNumBlocksAndThreads(int whichKernel, int n, int maxBlocks, int maxThreads, int &blocks, int &threads)
{

    //get device capability, to avoid block/grid size excceed the upbound
    //cudaDeviceProp prop;
    //int device;
    //checkCudaErrors(cudaGetDevice(&device));
    //checkCudaErrors(cudaGetDeviceProperties(&prop, device));

    if (whichKernel < 3)
    {
        threads = (n < maxThreads) ? nextPow2(n) : maxThreads;
        blocks = (n + threads - 1) / threads;
    }
    else
    {
        threads = (n < maxThreads*2) ? nextPow2((n + 1)/ 2) : maxThreads;
        blocks = (n + (threads * 2 - 1)) / (threads * 2);
    }

    /*if ((float)threads*blocks > (float)prop.maxGridSize[0] * prop.maxThreadsPerBlock)
    {
        printf("n is too large, please choose a smaller number!\n");
    }

    if (blocks > prop.maxGridSize[0])
    {
        printf("Grid size <%d> excceeds the device capability <%d>, set block size as %d (original %d)\n",
               blocks, prop.maxGridSize[0], threads*2, threads);

        blocks /= 2;
        threads *= 2;
    }*/

    if (whichKernel == 6)
    {
        blocks = MIN(maxBlocks, blocks);
    }
}

////////////////////////////////////////////////////////////////////////////////
// This function performs a reduction of the input data multiple times and
// measures the average reduction time.
////////////////////////////////////////////////////////////////////////////////
/*template <class T>
T benchmarkReduce(int  n,
                  int  numThreads,
                  int  numBlocks,
                  int  maxThreads,
                  int  maxBlocks,
                  int  whichKernel,
                  int  testIterations,
                  bool cpuFinalReduction,
                  int  cpuFinalThreshold,
                  StopWatchInterface *timer,
                  T *h_odata,
                  T *d_idata,
                  T *d_odata)
{
    T gpu_result = 0;
    bool needReadBack = true;

    //for (int i = 0; i < testIterations; ++i)
    //{
        gpu_result = 0;

        cudaDeviceSynchronize();
        sdkStartTimer(&timer);

        // execute the kernel
        reduce<T>(n, numThreads, numBlocks, whichKernel, d_idata, d_odata);

        // check if kernel execution generated an error
        getLastCudaError("Kernel execution failed");

        if (cpuFinalReduction)
        {
            // sum partial sums from each block on CPU
            // copy result from device to host
            //checkCudaErrors(cudaMemcpy(h_odata, d_odata, numBlocks*sizeof(T), cudaMemcpyDeviceToHost));
            cudaMemcpy(h_odata, d_odata, numBlocks*sizeof(T), cudaMemcpyDeviceToHost);

            for (int i=0; i<numBlocks; i++)
            {
                gpu_result += h_odata[i];
            }

            needReadBack = false;
        }
        else
        {
            // sum partial block sums on GPU
            int s=numBlocks;
            int kernel = whichKernel;

            while (s > cpuFinalThreshold)
            {
                int threads = 0, blocks = 0;
                getNumBlocksAndThreads(kernel, s, maxBlocks, maxThreads, blocks, threads);

                reduce<T>(s, threads, blocks, kernel, d_odata, d_odata);

                if (kernel < 3)
                {
                    s = (s + threads - 1) / threads;
                }
                else
                {
                    s = (s + (threads*2-1)) / (threads*2);
                }
            }

            if (s > 1)
            {
                // copy result from device to host
                checkCudaErrors(cudaMemcpy(h_odata, d_odata, s * sizeof(T), cudaMemcpyDeviceToHost));

                for (int i=0; i < s; i++)
                {
                    gpu_result += h_odata[i];
                }

                needReadBack = false;
            }
        }

        cudaDeviceSynchronize();
        sdkStopTimer(&timer);
    }

    if (needReadBack)
    {
        // copy final sum from device to host
        checkCudaErrors(cudaMemcpy(&gpu_result, d_odata, sizeof(T), cudaMemcpyDeviceToHost));
    }

    return gpu_result;
}*/

////////////////////////////////////////////////////////////////////////////////
// This function calls benchmarkReduce multiple times for a range of array sizes
// and prints a report in CSV (comma-separated value) format that can be used for
// generating a "shmoo" plot showing the performance for each kernel variation
// over a wide range of input sizes.
////////////////////////////////////////////////////////////////////////////////
/*template <class T>
void shmoo(int minN, int maxN, int maxThreads, int maxBlocks, ReduceType datatype)
{
    // create random input data on CPU
    unsigned int bytes = maxN * sizeof(T);

    T *h_idata = (T *) malloc(bytes);

    for (int i = 0; i < maxN; i++)
    {
        // Keep the numbers small so we don't get truncation error in the sum
        if (datatype == REDUCE_INT)
        {
            h_idata[i] = (T)(rand() & 0xFF);
        }
        else
        {
            h_idata[i] = (rand() & 0xFF) / (T)RAND_MAX;
        }
    }

    int maxNumBlocks = MIN(maxN / maxThreads, MAX_BLOCK_DIM_SIZE);

    // allocate mem for the result on host side
    T *h_odata = (T *) malloc(maxNumBlocks*sizeof(T));

    // allocate device memory and data
    T *d_idata = NULL;
    T *d_odata = NULL;

    checkCudaErrors(cudaMalloc((void **) &d_idata, bytes));
    checkCudaErrors(cudaMalloc((void **) &d_odata, maxNumBlocks*sizeof(T)));

    // copy data directly to device memory
    checkCudaErrors(cudaMemcpy(d_idata, h_idata, bytes, cudaMemcpyHostToDevice));
    checkCudaErrors(cudaMemcpy(d_odata, h_idata, maxNumBlocks*sizeof(T), cudaMemcpyHostToDevice));

    // warm-up
    for (int kernel = 0; kernel < 7; kernel++)
    {
        reduce<T>(maxN, maxThreads, maxNumBlocks, kernel, d_idata, d_odata);
    }

    int testIterations = 100;

    StopWatchInterface *timer = 0;
    sdkCreateTimer(&timer);

    // print headers
    printf("Time in milliseconds for various numbers of elements for each kernel\n\n\n");
    printf("Kernel");

    for (int i = minN; i <= maxN; i *= 2)
    {
        printf(", %d", i);
    }

    for (int kernel = 0; kernel < 7; kernel++)
    {
        printf("\n%d", kernel);

        for (int i = minN; i <= maxN; i *= 2)
        {
            sdkResetTimer(&timer);
            int numBlocks = 0;
            int numThreads = 0;
            getNumBlocksAndThreads(kernel, i, maxBlocks, maxThreads, numBlocks, numThreads);

            float reduceTime;

            if (numBlocks <= MAX_BLOCK_DIM_SIZE)
            {
                benchmarkReduce(i, numThreads, numBlocks, maxThreads, maxBlocks, kernel,
                                testIterations, false, 1, timer, h_odata, d_idata, d_odata);
                reduceTime =  sdkGetAverageTimerValue(&timer);
            }
            else
            {
                reduceTime = -1.0;
            }

            printf(", %.5f", reduceTime);
        }
    }

    // cleanup
    sdkDeleteTimer(&timer);
    free(h_idata);
    free(h_odata);

    //checkCudaErrors(cudaFree(d_idata));
    //checkCudaErrors(cudaFree(d_odata));
    cudaFree(d_idata);
    cudaFree(d_odata);
}*/

////////////////////////////////////////////////////////////////////////////////
// The main function whihc runs the reduction test.
////////////////////////////////////////////////////////////////////////////////
bool
runTest(int argc, char **argv, ReduceType datatype)
{
    //int size = 1<<24;    // number of elements to reduce
    int size = 64 * 256;    // number of elements to reduce
    int maxThreads = 256;  // number of threads per block
    int whichKernel = 6;
    int maxBlocks = 64;
    bool cpuFinalReduction = false;
    int cpuFinalThreshold = 1;

    /*if (checkCmdLineFlag(argc, (const char **) argv, "n"))
    {
        size = getCmdLineArgumentInt(argc, (const char **) argv, "n");
    }

    if (checkCmdLineFlag(argc, (const char **) argv, "threads"))
    {
        maxThreads = getCmdLineArgumentInt(argc, (const char **) argv, "threads");
    }

    if (checkCmdLineFlag(argc, (const char **) argv, "kernel"))
    {
        whichKernel = getCmdLineArgumentInt(argc, (const char **) argv, "kernel");
    }

    if (checkCmdLineFlag(argc, (const char **) argv, "maxblocks"))
    {
        maxBlocks = getCmdLineArgumentInt(argc, (const char **) argv, "maxblocks");
    }*/

    printf("%d elements\n", size);
    printf("%d threads (max)\n", maxThreads);

    //cpuFinalReduction = checkCmdLineFlag(argc, (const char **) argv, "cpufinal");

    /*if (checkCmdLineFlag(argc, (const char **) argv, "cputhresh"))
    {
        cpuFinalThreshold = getCmdLineArgumentInt(argc, (const char **) argv, "cputhresh");
    }*/

    //bool runShmoo = checkCmdLineFlag(argc, (const char **) argv, "shmoo");

    /*if (runShmoo)
    {
        shmoo<T>(1, 33554432, maxThreads, maxBlocks, datatype);
    }
    else
    {*/
        // create random input data on CPU
        unsigned int bytes = size * sizeof(int);

        int *h_idata = (int *) malloc(bytes);

#ifdef _SYM
        klee_make_symbolic(h_idata, bytes, "h_idata_input");
#else
        for (int i=0; i<size; i++)
        {
            // Keep the numbers small so we don't get truncation error in the sum
                h_idata[i] = (int)(rand() & 0xFF);
        }
#endif

        int numBlocks = maxBlocks;
        int numThreads = maxThreads;

        if (numBlocks == 1)
        {
            cpuFinalThreshold = 1;
        }

        // allocate mem for the result on host side
        int *h_odata = (int *) malloc(numBlocks*sizeof(int));

        printf("%d blocks\n\n", numBlocks);

        // allocate device memory and data
        int *d_idata = NULL;
        int *d_odata = NULL;

        //checkCudaErrors(cudaMalloc((void **) &d_idata, bytes));
        //checkCudaErrors(cudaMalloc((void **) &d_odata, numBlocks*sizeof(T)));
        cudaMalloc((void **) &d_idata, bytes);
        cudaMalloc((void **) &d_odata, numBlocks*sizeof(int));

        // copy data directly to device memory
        //checkCudaErrors(cudaMemcpy(d_idata, h_idata, bytes, cudaMemcpyHostToDevice));
        //checkCudaErrors(cudaMemcpy(d_odata, h_idata, numBlocks*sizeof(T), cudaMemcpyHostToDevice));
        cudaMemcpy(d_idata, h_idata, bytes, cudaMemcpyHostToDevice);
        cudaMemcpy(d_odata, h_idata, numBlocks*sizeof(int), cudaMemcpyHostToDevice);

        unsigned int i = 0;
#ifdef _RED0
        // warm-up
        i = 0;
        numBlocks = maxBlocks;
        numThreads = maxThreads;
        //getNumBlocksAndThreads(i, size, maxBlocks, maxThreads, numBlocks, numThreads);
        reduce<int>(size, numThreads, numBlocks, i, d_idata, d_odata);
#elif defined _RED1
        i = 1;
        numBlocks = maxBlocks;
        numThreads = maxThreads;
        //getNumBlocksAndThreads(i, size, maxBlocks, maxThreads, numBlocks, numThreads);
        reduce<int>(size, numThreads, numBlocks, i, d_idata, d_odata);
#elif defined _RED2
        i = 2;
        numBlocks = maxBlocks;
        numThreads = maxThreads;
        //getNumBlocksAndThreads(i, size, maxBlocks, maxThreads, numBlocks, numThreads);
        reduce<int>(size, numThreads, numBlocks, i, d_idata, d_odata);
#elif defined _RED3
        i = 3;
        numBlocks = maxBlocks/2;
        numThreads = maxThreads;
        //getNumBlocksAndThreads(i, size, maxBlocks, maxThreads, numBlocks, numThreads);
        reduce<int>(size, numThreads, numBlocks, i, d_idata, d_odata);
#elif defined _RED4
        i = 4;
        numBlocks = maxBlocks/2;
        numThreads = maxThreads;
        getNumBlocksAndThreads(i, size, maxBlocks, maxThreads, numBlocks, numThreads);
        reduce<int>(size, numThreads, numBlocks, i, d_idata, d_odata);
#elif defined _RED5
        i = 5;
        numBlocks = maxBlocks/2;
        numThreads = maxThreads;
        //getNumBlocksAndThreads(i, size, maxBlocks, maxThreads, numBlocks, numThreads);
        reduce<int>(size, numThreads, numBlocks, i, d_idata, d_odata);
#else
        i = 6;
        numBlocks = maxBlocks/2;
        numThreads = maxThreads;
        //getNumBlocksAndThreads(i, size, maxBlocks, maxThreads, numBlocks, numThreads);
        reduce<int>(size, numThreads, numBlocks, i, d_idata, d_odata);
#endif

        //StopWatchInterface *timer = 0;
        //sdkCreateTimer(&timer);

        //T gpu_result = 0;

        //gpu_result = benchmarkReduce<T>(size, numThreads, numBlocks, maxThreads, maxBlocks,
        //                                whichKernel, testIterations, cpuFinalReduction,
        //                                cpuFinalThreshold, timer,
        //                                h_odata, d_idata, d_odata);

        //double reduceTime = sdkGetAverageTimerValue(&timer) * 1e-3;
        //printf("Reduction, Throughput = %.4f GB/s, Time = %.5f s, Size = %u Elements, NumDevsUsed = %d, Workgroup = %u\n",
        //       1.0e-9 * ((double)bytes)/reduceTime, reduceTime, size, 1, numThreads);

        // compute reference solution
        //T cpu_result = reduceCPU<T>(h_idata, size);

        double threshold = 1e-12;
        double diff = 0;

        /*if (datatype == REDUCE_INT)
        {
            printf("\nGPU result = %d\n", gpu_result);
            //printf("CPU result = %d\n\n", cpu_result);
        }
        else
        {
            printf("\nGPU result = %f\n", gpu_result);
            //printf("CPU result = %f\n\n", cpu_result);

            if (datatype == REDUCE_FLOAT)
            {
                threshold = 1e-8 * size;
            }

            diff = fabs((double)gpu_result - (double)cpu_result);
        }*/

        // cleanup
        //sdkDeleteTimer(&timer);
        free(h_idata);
        free(h_odata);

        //checkCudaErrors(cudaFree(d_idata));
        //checkCudaErrors(cudaFree(d_odata));
        cudaFree(d_idata);
        cudaFree(d_odata);

        /*if (datatype == REDUCE_INT)
        {
            return (gpu_result == cpu_result);
        }
        else
        {
            return (diff < threshold);
        }*/
    //}

    return true;
}


text:
@interface AnalyticsService : NSObject

+(void)didFinishLaunching:(NSDictionary*)launchOptions;
+(void)event:(NSString*)name;

@end


text:
{% from 'message_box.html' import message_box %}

{% macro render_regform_info(regform) %}

        {% if regform.is_scheduled and (not regform.has_started or regform.end_dt) %}

                        {% if regform.is_open %}

                                {% trans %}Registration is open{% endtrans %}

                        {% else %}

                                {% if regform.has_ended %}
                                    {% trans %}Opened{% endtrans %}
                                {% else %}
                                    {% trans %}Opens{% endtrans %}
                                {% endif %}

                                {{ regform.start_dt|format_date(timezone=regform.event.tzinfo) }}

                        {% endif %}

                            {% if regform.is_open %}
                                {% trans %}Deadline{% endtrans %}
                            {% elif regform.has_ended %}
                                {% trans %}Closed{% endtrans %}
                            {% else %}
                                {% trans %}Closes{% endtrans %}
                            {% endif %}

                            {% if regform.end_dt %}
                                {{ regform.end_dt|format_date(timezone=regform.event.tzinfo) }}
                            {% else %}
                                {% trans %}Not specified{% endtrans %}
                            {% endif %}

        {% endif %}
        {% if regform.base_price -%}

                        {% trans %}Registration fee{% endtrans %}

{{ regform.render_base_price() }}

        {%- endif %}
        {% if regform.contact_info %}

                        {% trans %}Contact info{% endtrans %}

{{ regform.contact_info }}

        {% endif %}

    {% if regform.introduction %}
        {{ message_box('info', regform.introduction | markdown) }}
    {% endif %}
{% endmacro %}


text:
'use strict';

import * as vscode from 'vscode';

export default class Provider implements vscode.TextDocumentContentProvider {
    static scheme = 'http';

    provideTextDocumentContent(uri: vscode.Uri):string {
        console.log(uri);
        return `
                <style>
                    body, iframe {
                        width: 100%;
                        height: 100%;
                    }
                    body {
                        background-color: red;
                    }
                </style>
				<body>
                    <div style="width:100%;height:1000px;background-color:green;">
					<iframe src="http://www.baidu.com/"/>
                    </div>
				</body>`;
    }
}


text:
            <?php echo $this->session->flashdata('notif'); ?>

 Playlist Videos

                        <form method="GET" action="<?php echo base_url('auth/playlist/search');?>">

                              <a href="<?php echo base_url('auth/playlist/add?source=add&utf8=✓') ?>" class = "btn btn-default" type = "button">
                                 Tambah

                                <input type = "text" name = "q" class = "typeahead tt-query" placeholder="Masukkan kata kunci dan enter" autocomplete="off" id="playlist">
                                <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">

                              <button class = "btn btn-default" type = "submit">
                                  Search
                              </button>

                        </form>

                            No.
                             NAMA PLAYIST
                             JUMLAH VIDEO
                             OPTIONS

                        <?php
                        if($playlist != NULL):
                        $no = $this->uri->segment('4') + 1;
                        foreach($playlist->result() as $hasil):

                            $jml = $this->db->query("SELECT COUNT(playlist_id) as jml FROM tbl_videos WHERE playlist_id='$hasil->id_playlist'")->row();

                        ?>

                                <?php echo $no++; ?>
                                <?php echo $hasil->nama_playlist ?>
                                <?php echo $jml->jml ?>

                                    <a class='badge badge-success' style="font-family: Roboto;font-weight: 400;background-color: #358420;" data-toggle="tooltip" data-placement="top" title="Edit" href='<?php echo base_url() ?>auth/playlist/edit/<?php echo $this->encryption->encode($hasil->id_playlist) ?>'> Edit
                                    <a class='badge badge-danger' style="font-family: Roboto;font-weight: 400;background-color: #842020;" data-toggle="tooltip" data-placement="top" title="Delete ?" href='<?php echo base_url() ?>auth/playlist/delete/<?php echo $this->encryption->encode($hasil->id_playlist) ?>'> Delete

                            <?php
                        endforeach;
                        ?>

                    <?php echo $paging ?>
                    <?php else : ?>

                             Warning!  Data tidak ada didatabase

                            <a  href="<?php echo base_url('auth/playlist?source=reload&utf8=✓') ?>" class="btn btn-danger btn-reset btn-fill" id="load" data-loading-text=" Reloading..."> Reload Page

                    <?php endif; ?>


text:
var TreatmentIndexApp = BaseIndexApp.extend({

    el: $('#treatment_index_app_canvass'),

    customInitialization: function(options){
        this.collection = new TreatmentCollection([])
        this.indexUrl = options.indexUrl;
    },

    getItemView : function(specialization) {
        return new TreatmentsTranslationCollectionItemView({
            model: specialization,
            indexUrl: this.indexUrl
        });
    }
});