text:
import argparse
import os
import os.path
import shutil
import subprocess
import sys
import stat
import tempfile

# How to patch libxml2 in Chromium:
#
# 1. Write a .patch file and add it to third_party/libxml/chromium.
# 2. Apply the patch in src: patch -p1 <../chromium/foo.patch
# 3. Add the patch to the list of patches in this file.
# 4. Update README.chromium with the provenance of the patch.
# 5. Upload a change with the modified documentation, roll script,
#    patch, applied patch and any other relevant changes like
#    regression tests. Go through the usual review and commit process.
#
# How to roll libxml2 in Chromium:
#
# Prerequisites:
#
# 1. Check out Chromium somewhere on Linux, Mac and Windows.
# 2. On Linux:
#    a. sudo apt-get install libicu-dev
#    b. git clone https://github.com/GNOME/libxml2.git somewhere
# 3. On Mac, install these packages with brew:
#      autoconf automake libtool pkgconfig icu4c
#
#    Important! Before running roll.py, set these environmental variables so the
#    configure script can find ICU:
#      export LDFLAGS="-L/path/to/homebrew/opt/icu4c/lib"
#      export CPPFLAGS="-I/path/to/homebrew/opt/icu4c/include"
#      export PKG_CONFIG_PATH="/path/to/homebrew/opt/icu4c/lib/pkgconfig"
#
# Procedure:
#
# Warning: This process is destructive. Run it on a clean branch.
#
# 1. On Linux, in the libxml2 repo directory:
#    a. git remote update origin
#    b. git checkout origin/master
#
#    This will be the upstream version of libxml you are rolling to.
#
# 2. On Linux, in the Chromium src director:
#    a. third_party/libxml/chromium/roll.py --linux /path/to/libxml2
#
#    If this fails, it may be a patch no longer applies. Reset to
#    head; modify the patch files, this script, and
#    README.chromium; then commit the result and run it again.
#
#    b. Upload a CL, but do not Start Review.
#
# 2. On Windows, in the Chromium src directory:
#    a. git cl patch <Gerrit Issue ID>
#    b. third_party\libxml\chromium\roll.py --win32
#    c. git cl upload
#
# 3. On Mac, in the Chromium src directory:
#    a. git cl patch <Gerrit Issue ID>
#    b. third_party/libxml/chromium/roll.py --mac
#    c. Make and commit any final changes to README.chromium, BUILD.gn, etc.
#    d. git cl upload
#    e. Complete the review as usual

PATCHES = [
    # TODO(dcheng): reach out upstream to see what's going on here.
    'revert-non-recursive-xml-parsing.patch',
    'chromium-issue-599427.patch',
    'chromium-issue-628581.patch',
    'libxml2-2.9.4-security-xpath-nodetab-uaf.patch',
    'chromium-issue-708434.patch',
    # TODO(dcheng): Merge this back upstream.
    'add-missing-ifdef-in-xml-reader.patch',
]

# See libxml2 configure.ac and win32/configure.js to learn what
# options are available. We include every option here to more easily track
# changes from one version to the next, and to be sure we only include what
# we need.
# These two sets of options should be in sync. You can check the
# generated #defines in (win32|mac|linux)/include/libxml/xmlversion.h to confirm
# this.
# We would like to disable python but it introduces a host of build errors
SHARED_XML_CONFIGURE_OPTIONS = [
    # These options are turned ON
    ('--with-html', 'html=yes'),
    ('--with-icu', 'icu=yes'),
    ('--with-output', 'output=yes'),
    ('--with-push', 'push=yes'),
    ('--with-python', 'python=yes'),
    ('--with-reader', 'reader=yes'),
    ('--with-sax1', 'sax1=yes'),
    ('--with-tree', 'tree=yes'),
    ('--with-writer', 'writer=yes'),
    ('--with-xpath', 'xpath=yes'),
    # These options are turned OFF
    ('--without-c14n', 'c14n=no'),
    ('--without-catalog', 'catalog=no'),
    ('--without-debug', 'xml_debug=no'),
    ('--without-docbook', 'docb=no'),
    ('--without-ftp', 'ftp=no'),
    ('--without-http', 'http=no'),
    ('--without-iconv', 'iconv=no'),
    ('--without-iso8859x', 'iso8859x=no'),
    ('--without-legacy', 'legacy=no'),
    ('--without-lzma', 'lzma=no'),
    ('--without-mem-debug', 'mem_debug=no'),
    ('--without-modules', 'modules=no'),
    ('--without-pattern', 'pattern=no'),
    ('--without-regexps', 'regexps=no'),
    ('--without-run-debug', 'run_debug=no'),
    ('--without-schemas', 'schemas=no'),
    ('--without-schematron', 'schematron=no'),
    ('--without-threads', 'threads=no'),
    ('--without-valid', 'valid=no'),
    ('--without-xinclude', 'xinclude=no'),
    ('--without-xptr', 'xptr=no'),
    ('--without-zlib', 'zlib=no'),
]

# These options are only available in configure.ac for Linux and Mac.
EXTRA_NIX_XML_CONFIGURE_OPTIONS = [
    '--without-fexceptions',
    '--without-minimum',
    '--without-readline',
    '--without-history',
]

# These options are only available in win32/configure.js for Windows.
EXTRA_WIN32_XML_CONFIGURE_OPTIONS = [
    'trio=no',
    'walker=no',
]

XML_CONFIGURE_OPTIONS = (
    [option[0] for option in SHARED_XML_CONFIGURE_OPTIONS] +
    EXTRA_NIX_XML_CONFIGURE_OPTIONS)

XML_WIN32_CONFIGURE_OPTIONS = (
    [option[1] for option in SHARED_XML_CONFIGURE_OPTIONS] +
    EXTRA_WIN32_XML_CONFIGURE_OPTIONS)

FILES_TO_REMOVE = [
    'src/DOCBparser.c',
    'src/HACKING',
    'src/INSTALL',
    'src/INSTALL.libxml2',
    'src/MAINTAINERS',
    'src/Makefile.in',
    'src/Makefile.win',
    'src/README.cvs-commits',
    # This is unneeded "legacy" SAX API, even though we enable SAX1.
    'src/SAX.c',
    'src/VxWorks',
    'src/autogen.sh',
    'src/autom4te.cache',
    'src/bakefile',
    'src/build_glob.py',
    'src/c14n.c',
    'src/catalog.c',
    'src/compile',
    'src/config.guess',
    'src/config.sub',
    'src/configure',
    'src/chvalid.def',
    'src/debugXML.c',
    'src/depcomp',
    'src/doc',
    'src/example',
    'src/genChRanges.py',
    'src/global.data',
    'src/include/libxml/Makefile.in',
    'src/include/libxml/xmlversion.h',
    'src/include/libxml/xmlwin32version.h',
    'src/include/libxml/xmlwin32version.h.in',
    'src/include/Makefile.in',
    'src/install-sh',
    'src/legacy.c',
    'src/libxml2.doap',
    'src/ltmain.sh',
    'src/m4',
    'src/macos/libxml2.mcp.xml.sit.hqx',
    'src/missing',
    'src/optim',
    'src/os400',
    'src/python',
    'src/relaxng.c',
    'src/result',
    'src/rngparser.c',
    'src/schematron.c',
    'src/test',
    'src/testOOM.c',
    'src/testOOMlib.c',
    'src/testOOMlib.h',
    'src/trio.c',
    'src/trio.h',
    'src/triop.h',
    'src/triostr.c',
    'src/triostr.h',
    'src/vms',
    'src/win32/VC10/config.h',
    'src/win32/wince',
    'src/xinclude.c',
    'src/xlink.c',
    'src/xml2-config.in',
    'src/xmlcatalog.c',
    'src/xmllint.c',
    'src/xmlmodule.c',
    'src/xmlregexp.c',
    'src/xmlschemas.c',
    'src/xmlschemastypes.c',
    'src/xpointer.c',
    'src/xstc',
    'src/xzlib.c',
]

THIRD_PARTY_LIBXML_SRC = 'third_party/libxml/src'

class WorkingDir(object):
    """"Changes the working directory and resets it on exit."""
    def __init__(self, path):
        self.prev_path = os.getcwd()
        self.path = path

    def __enter__(self):
        os.chdir(self.path)

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_value:
            print('was in %s; %s before that' % (self.path, self.prev_path))
        os.chdir(self.prev_path)

def git(*args):
    """Runs a git subcommand.

    On Windows this uses the shell because there's a git wrapper
    batch file in depot_tools.

    Arguments:
        args: The arguments to pass to git.
    """
    command = ['git'] + list(args)
    subprocess.check_call(command, shell=(os.name == 'nt'))

def remove_tracked_and_local_dir(path):
    """Removes the contents of a directory from git, and the filesystem.

    Arguments:
        path: The path to remove.
    """
    remove_tracked_files([path])
    shutil.rmtree(path, ignore_errors=True)
    os.mkdir(path)

def remove_tracked_files(files_to_remove):
    """Removes tracked files from git.

    Arguments:
        files_to_remove: The files to remove.
    """
    files_to_remove = [f for f in files_to_remove if os.path.exists(f)]
    if files_to_remove:
        git('rm', '-rf', *files_to_remove)

def sed_in_place(input_filename, program):
    """Replaces text in a file.

    Arguments:
        input_filename: The file to edit.
        program: The sed program to perform edits on the file.
    """
    # OS X's sed requires -e
    subprocess.check_call(['sed', '-i', '-e', program, input_filename])

def check_copying(full_path_to_third_party_libxml_src):
    path = os.path.join(full_path_to_third_party_libxml_src, 'COPYING')
    if not os.path.exists(path):
        return
    with open(path) as f:
        s = f.read()
        if 'GNU' in s:
            raise Exception('check COPYING')

def prepare_libxml_distribution(src_path, libxml2_repo_path, temp_dir):
    """Makes a libxml2 distribution.

    Args:
        src_path: The path to the Chromium checkout.
        libxml2_repo_path: The path to the local clone of the libxml2 repo.
        temp_dir: A temporary directory to stage the distribution to.

    Returns: A tuple of commit hash and full path to the archive.
    """
    # If it was necessary to push from a distribution prepared upstream,
    # this is the point to inject it: Return the version string and the
    # distribution tar file.

    # The libxml2 repo we're pulling changes from should not have
    # local changes. This *should* be a commit that's publicly visible
    # in the upstream repo; reviewers should check this.
    check_clean(libxml2_repo_path)

    temp_config_path = os.path.join(temp_dir, 'config')
    os.mkdir(temp_config_path)
    temp_src_path = os.path.join(temp_dir, 'src')
    os.mkdir(temp_src_path)

    with WorkingDir(libxml2_repo_path):
        commit = subprocess.check_output(
            ['git', 'log', '-n', '1', '--pretty=format:%H', 'HEAD'])
        subprocess.check_call(
            'git archive HEAD | tar -x -C "%s"' % temp_src_path,
            shell=True)
    with WorkingDir(temp_src_path):
        os.remove('.gitignore')
        for patch in PATCHES:
            print('applying %s' % patch)
            subprocess.check_call(
                'patch -p1 --fuzz=0 < %s' % os.path.join(
                    src_path, THIRD_PARTY_LIBXML_SRC, '..', 'chromium', patch),
                shell=True)

    with WorkingDir(temp_config_path):
        print('../src/autogen.sh %s' % XML_CONFIGURE_OPTIONS)
        subprocess.check_call(['../src/autogen.sh'] + XML_CONFIGURE_OPTIONS)
        subprocess.check_call(['make', 'dist-all'])

        # Work out what it is called
        tar_file = subprocess.check_output(
            '''awk '/PACKAGE =/ {p=$3} /VERSION =/ {v=$3} '''
            '''END {printf("%s-%s.tar.gz", p, v)}' Makefile''',
            shell=True)
        return commit, os.path.abspath(tar_file)

def roll_libxml_linux(src_path, libxml2_repo_path):
    with WorkingDir(src_path):
        # Export the upstream git repo.
        try:
            temp_dir = tempfile.mkdtemp()
            print('temporary directory: %s' % temp_dir)

            commit, tar_file = prepare_libxml_distribution(
                src_path, libxml2_repo_path, temp_dir)

            # Remove all of the old libxml to ensure only desired cruft
            # accumulates
            remove_tracked_and_local_dir(THIRD_PARTY_LIBXML_SRC)

            # Update the libxml repo and export it to the Chromium tree
            with WorkingDir(THIRD_PARTY_LIBXML_SRC):
                subprocess.check_call(
                    'tar xzf %s --strip-components=1' % tar_file,
                    shell=True)
        finally:
            shutil.rmtree(temp_dir)

        with WorkingDir(THIRD_PARTY_LIBXML_SRC):
            # Put the version number is the README file
            sed_in_place('../README.chromium',
                         's/Version: .*$/Version: %s/' % commit)

            with WorkingDir('../linux'):
                subprocess.check_call(
                    ['../src/autogen.sh'] + XML_CONFIGURE_OPTIONS)
                check_copying(os.getcwd())
                sed_in_place('config.h', 's/#define HAVE_RAND_R 1//')

            # Add *everything*
            with WorkingDir('../src'):
                git('add', '*')
                git('commit', '-am', '%s libxml, linux' % commit)
    print('Now push to Windows and run steps there.')

def roll_libxml_win32(src_path):
    with WorkingDir(src_path):
        # Run the configure script.
        with WorkingDir(os.path.join(THIRD_PARTY_LIBXML_SRC, 'win32')):
            subprocess.check_call(
                ['cscript', '//E:jscript', 'configure.js', 'compiler=msvc'] +
                XML_WIN32_CONFIGURE_OPTIONS)

            # Add and commit the result.
            shutil.move('VC10/config.h', '../../win32/config.h')
            git('add', '../../win32/config.h')
            shutil.move('../include/libxml/xmlversion.h',
                        '../../win32/include/libxml/xmlversion.h')
            git('add', '../../win32/include/libxml/xmlversion.h')
            git('commit', '-m', 'Windows')
            git('clean', '-f')
    print('Now push to Mac and run steps there.')

def roll_libxml_mac(src_path):
    full_path_to_third_party_libxml = os.path.join(
        src_path, THIRD_PARTY_LIBXML_SRC, '..')

    with WorkingDir(os.path.join(full_path_to_third_party_libxml, 'mac')):
        subprocess.check_call(['autoreconf', '-i', '../src'])
        os.chmod('../src/configure',
                 os.stat('../src/configure').st_mode | stat.S_IXUSR)
        subprocess.check_call(['../src/configure'] + XML_CONFIGURE_OPTIONS)
        sed_in_place('config.h', 's/#define HAVE_RAND_R 1//')

    with WorkingDir(full_path_to_third_party_libxml):
        commit = subprocess.check_output(['awk', '/Version:/ {print $2}',
                                          'README.chromium'])
        remove_tracked_files(FILES_TO_REMOVE)
        commit_message = 'Roll libxml to %s' % commit
        git('commit', '-am', commit_message)
    print('Now upload for review, etc.')

def check_clean(path):
    with WorkingDir(path):
        status = subprocess.check_output(['git', 'status', '-s'])
        if len(status) > 0:
            raise Exception('repository at %s is not clean' % path)

def main():
    src_dir = os.getcwd()
    if not os.path.exists(os.path.join(src_dir, 'third_party')):
        print('error: run this script from the Chromium src directory')
        sys.exit(1)

    parser = argparse.ArgumentParser(
        description='Roll the libxml2 dependency in Chromium')
    platform = parser.add_mutually_exclusive_group(required=True)
    platform.add_argument('--linux', action='store_true')
    platform.add_argument('--win32', action='store_true')
    platform.add_argument('--mac', action='store_true')
    parser.add_argument(
        'libxml2_repo_path',
        type=str,
        nargs='?',
        help='The path to the local clone of the libxml2 git repo.')
    args = parser.parse_args()

    if args.linux:
        libxml2_repo_path = args.libxml2_repo_path
        if not libxml2_repo_path:
            print('Specify the path to the local libxml2 repo clone.')
            sys.exit(1)
        libxml2_repo_path = os.path.abspath(libxml2_repo_path)
        roll_libxml_linux(src_dir, libxml2_repo_path)
    elif args.win32:
        roll_libxml_win32(src_dir)
    elif args.mac:
        roll_libxml_mac(src_dir)

if __name__ == '__main__':
    main()


text:
<?xml version="1.0" encoding="utf-8"?>
<resources targetOsVersion="10.0.0" majorVersion="1">
  <packaging>
    <autoResourcePackage qualifier="Language" />
    <autoResourcePackage qualifier="Scale" />
    <autoResourcePackage qualifier="DXFeatureLevel" />
  </packaging>
  <index root="\" startIndexAt="C:\Users\thefa\Documents\Git\MobileApp-Dev2\Arkanoid\Arkanoid\bin\x86\Release\ilc\resources.pri">
    <default>
      <qualifier name="Language" value="en-US" />
      <qualifier name="Contrast" value="standard" />
      <qualifier name="Scale" value="200" />
      <qualifier name="HomeRegion" value="001" />
      <qualifier name="TargetSize" value="256" />
      <qualifier name="LayoutDirection" value="LTR" />
      <qualifier name="DXFeatureLevel" value="DX9" />
      <qualifier name="Configuration" value="" />
      <qualifier name="AlternateForm" value="" />
      <qualifier name="Platform" value="UAP" />
    </default>
    <indexer-config type="PRI" />
  </index>
</resources>

redpajama_set_name: RedPajamaGithub


text:
package com.tnovoselec.beautifulweather.ui.painter;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PointF;
import android.graphics.RectF;

public class MoonPainter implements IconPainter {

  Paint paint;
  Path path;
  private int screenW, screenH;
  private float X, Y;
  PathPoints[] pathPoints;
  float m = 0;
  float radius;
  boolean clockwise = true;
  float a = 0, b = 0, c = 0, d = 0;

  int strokeColor;
  int bgColor;

  @Override
  public void init(int strokeColor, int bgColor) {

    this.strokeColor = strokeColor;
    this.bgColor = bgColor;

    paint = new Paint();
    paint.setColor(strokeColor);
    paint.setStyle(Paint.Style.STROKE);
    paint.setAntiAlias(true);
    paint.setStrokeCap(Paint.Cap.ROUND);

  }

  @Override
  public void paint(Canvas canvas) {
    canvas.drawColor(bgColor);

    paint.setStrokeWidth((float) (0.02083 * screenW));

    path = new Path();

    RectF rectF1 = new RectF();

    if (!clockwise) {//Anticlockwise rotation

      // First arc of the Moon.
      rectF1.set(X - radius, Y - radius, X + radius, Y + radius);
      path.addArc(rectF1, 65 - (m / 2), 275);

      pathPoints = getPoints(path);

      a = pathPoints[999].getX();
      b = pathPoints[999].getY();
      c = pathPoints[0].getX();
      d = pathPoints[0].getY();

      PointF P1c1 = cubic2Points(a, b, c, d, true);
      PointF P1c2 = cubic2Points(a, b, c, d, false);

      // Second arc of the Moon in opposite face.
      path.moveTo(a, b);
      path.cubicTo(P1c1.x, P1c1.y, P1c2.x, P1c2.y, c, d);

      canvas.drawPath(path, paint);

      m = m + 1.5f;

      if (m >= 100) {
        m = 0;
        clockwise = !clockwise;
      }

    } else {//Clockwise rotation

      // First arc of the Moon.
      rectF1.set(X - radius, Y - radius, X + radius, Y + radius);
      path.addArc(rectF1, 15 + (m / 2), 275);

      pathPoints = getPoints(path);

      a = pathPoints[999].getX();
      b = pathPoints[999].getY();
      c = pathPoints[0].getX();
      d = pathPoints[0].getY();

      PointF P1c1 = cubic2Points(a, b, c, d, true);
      PointF P1c2 = cubic2Points(a, b, c, d, false);

      // Second arc of the Moon in opposite face.
      path.moveTo(a, b);
      path.cubicTo(P1c1.x, P1c1.y, P1c2.x, P1c2.y, c, d);

      canvas.drawPath(path, paint);

      m = m + 1.5f;

      if (m >= 100) {
        m = 0;
        clockwise = !clockwise;
      }

    }

  }

  @Override
  public void onSizeChanged(int w, int h, int oldw, int oldh) {
    screenW = w;
    screenH = h;

    X = screenW / 2;
    Y = (screenH / 2);

    radius = (int) (0.2458 * screenW);
  }

  // Class for fetching path coordinates.
  class PathPoints {

    float x, y;

    public PathPoints(float x, float y) {
      this.x = x;
      this.y = y;
    }

    public float getX() {
      return x;
    }

    public float getY() {
      return y;
    }
  }

  // Used to fetch points from given path.
  private PathPoints[] getPoints(Path path) {

    //Size of 1000 indicates that, 1000 points
    // would be extracted from the path
    PathPoints[] pointArray = new PathPoints[1000];
    PathMeasure pm = new PathMeasure(path, false);
    float length = pm.getLength();
    float distance = 0f;
    float speed = length / 1000;
    int counter = 0;
    float[] aCoordinates = new float[2];

    while ((distance < length) && (counter < 1000)) {
      pm.getPosTan(distance, aCoordinates, null);
      pointArray[counter] = new PathPoints(aCoordinates[0], aCoordinates[1]);
      counter++;
      distance = distance + speed;
    }

    return pointArray;
  }

  private PointF cubic2Points(float x1, float y1, float x2, float y2, boolean left) {

    PointF result = new PointF(0, 0);
    // finding center point between the coordinates
    float dy = y2 - y1;
    float dx = x2 - x1;
    // calculating angle and the distance between center and the two points
    float dangle = (float) ((Math.atan2(dy, dx) - Math.PI / 2f));
    float sideDist = (float) -0.6 * (float) Math.sqrt(dx * dx + dy * dy); //square

    if (left) {
      //point from center to the left
      result.x = (int) (Math.cos(dangle) * sideDist + x1);
      result.y = (int) (Math.sin(dangle) * sideDist + y1);

    } else {
      //point from center to the right
      result.x = (int) (Math.cos(dangle) * sideDist + x2);
      result.y = (int) (Math.sin(dangle) * sideDist + y2);
    }

    return result;
  }
}


text:
struct PP_Var stringVarErrorMessageType;
struct PP_Var stringVarErrorBenchmarkUnspecified;
struct PP_Var stringVarErrorBenchmarkType;
struct PP_Var stringVarErrorBenchmarkValue;
struct PP_Var stringVarErrorDatatypeUnspecified;
struct PP_Var stringVarErrorDatatypeType;
struct PP_Var stringVarErrorDatatypeValue;
struct PP_Var stringVarErrorSizeUnspecified;
struct PP_Var stringVarErrorSizeType;
struct PP_Var stringVarErrorSizeValue;

struct PP_Var stringVarBenchmark;
struct PP_Var stringVarDatatype;
struct PP_Var stringVarSize;
struct PP_Var stringVarTime;
struct PP_Var stringVarFLOPS;
struct PP_Var stringVarBandwidth;

struct PP_Var stringVarSingle;
struct PP_Var stringVarDouble;
struct PP_Var stringVarComplexSingle;
struct PP_Var stringVarComplexDouble;

#define VAR_FROM_UTF8_LITERAL(interface, literal) \
	interface->VarFromUtf8(literal, sizeof(literal) - 1);

void stringVarsInit() {
	stringVarErrorMessageType = VAR_FROM_UTF8_LITERAL(varInterface, "Message is not of dictionary type");
	stringVarErrorBenchmarkUnspecified = VAR_FROM_UTF8_LITERAL(varInterface, "Benchmark is not specified");
	stringVarErrorBenchmarkType = VAR_FROM_UTF8_LITERAL(varInterface, "Benchmark is not of string type");
	stringVarErrorBenchmarkValue = VAR_FROM_UTF8_LITERAL(varInterface, "Invalid benchmark name");
	stringVarErrorDatatypeUnspecified = VAR_FROM_UTF8_LITERAL(varInterface, "Datatype is not specified");
	stringVarErrorDatatypeType = VAR_FROM_UTF8_LITERAL(varInterface, "Datatype is not of string type");
	stringVarErrorDatatypeValue = VAR_FROM_UTF8_LITERAL(varInterface, "Invalid datatype name");
	stringVarErrorSizeUnspecified = VAR_FROM_UTF8_LITERAL(varInterface, "Size is not specified");
	stringVarErrorSizeType = VAR_FROM_UTF8_LITERAL(varInterface, "Size is not of integer type");
	stringVarErrorSizeValue = VAR_FROM_UTF8_LITERAL(varInterface, "Size is negative or zero");

	stringVarBenchmark = VAR_FROM_UTF8_LITERAL(varInterface, "benchmark");
	stringVarDatatype = VAR_FROM_UTF8_LITERAL(varInterface, "datatype");
	stringVarSize = VAR_FROM_UTF8_LITERAL(varInterface, "size");
	stringVarTime = VAR_FROM_UTF8_LITERAL(varInterface, "time");
	stringVarFLOPS = VAR_FROM_UTF8_LITERAL(varInterface, "FLOPS");
	stringVarBandwidth = VAR_FROM_UTF8_LITERAL(varInterface, "bandwidth");
}

void stringVarsRelease() {
	varInterface->Release(stringVarErrorMessageType);
	varInterface->Release(stringVarErrorBenchmarkUnspecified);
	varInterface->Release(stringVarErrorBenchmarkType);
	varInterface->Release(stringVarErrorBenchmarkValue);
	varInterface->Release(stringVarErrorDatatypeUnspecified);
	varInterface->Release(stringVarErrorDatatypeType);
	varInterface->Release(stringVarErrorDatatypeValue);
	varInterface->Release(stringVarErrorSizeUnspecified);
	varInterface->Release(stringVarErrorSizeType);
	varInterface->Release(stringVarErrorSizeValue);

	varInterface->Release(stringVarBenchmark);
	varInterface->Release(stringVarDatatype);
	varInterface->Release(stringVarSize);
	varInterface->Release(stringVarTime);
	varInterface->Release(stringVarFLOPS);
	varInterface->Release(stringVarBandwidth);

	varInterface->Release(stringVarSingle);
	varInterface->Release(stringVarDouble);
	varInterface->Release(stringVarComplexSingle);
	varInterface->Release(stringVarComplexDouble);
}


text:
#ifndef IIO_ADC_AD7606_H_
#define IIO_ADC_AD7606_H_

/*
 * TODO: struct ad7606_platform_data needs to go into include/linux/iio
 */

/**
 * struct ad7606_platform_data - platform/board specific information
 * @default_os:		default oversampling value {0, 2, 4, 8, 16, 32, 64}
 * @default_range:	default range +/-{5000, 10000} mVolt
 * @gpio_convst:	number of gpio connected to the CONVST pin
 * @gpio_reset:		gpio connected to the RESET pin, if not used set to -1
 * @gpio_range:		gpio connected to the RANGE pin, if not used set to -1
 * @gpio_os0:		gpio connected to the OS0 pin, if not used set to -1
 * @gpio_os1:		gpio connected to the OS1 pin, if not used set to -1
 * @gpio_os2:		gpio connected to the OS2 pin, if not used set to -1
 * @gpio_frstdata:	gpio connected to the FRSTDAT pin, if not used set to -1
 * @gpio_stby:		gpio connected to the STBY pin, if not used set to -1
 */

struct ad7606_platform_data {
	unsigned int			default_os;
	unsigned int			default_range;
	unsigned int			gpio_convst;
	unsigned int			gpio_reset;
	unsigned int			gpio_range;
	unsigned int			gpio_os0;
	unsigned int			gpio_os1;
	unsigned int			gpio_os2;
	unsigned int			gpio_frstdata;
	unsigned int			gpio_stby;
};

/**
 * struct ad7606_chip_info - chip specific information
 * @name:		identification string for chip
 * @int_vref_mv:	the internal reference voltage
 * @channels:		channel specification
 * @num_channels:	number of channels
 */

struct ad7606_chip_info {
	const char			*name;
	u16				int_vref_mv;
	const struct iio_chan_spec	*channels;
	unsigned int			num_channels;
};

/**
 * struct ad7606_state - driver instance specific data
 */

struct ad7606_state {
	struct device			*dev;
	const struct ad7606_chip_info	*chip_info;
	struct ad7606_platform_data	*pdata;
	struct regulator		*reg;
	struct work_struct		poll_work;
	wait_queue_head_t		wq_data_avail;
	const struct ad7606_bus_ops	*bops;
	unsigned int			range;
	unsigned int			oversampling;
	bool				done;
	void __iomem			*base_address;

	/*
	 * DMA (thus cache coherency maintenance) requires the
	 * transfer buffers to live in their own cache lines.
	 */

	unsigned short			data[8] ____cacheline_aligned;
};

struct ad7606_bus_ops {
	/* more methods added in future? */
	int (*read_block)(struct device *, int, void *);
};

struct iio_dev *ad7606_probe(struct device *dev, int irq,
			      void __iomem *base_address, unsigned int id,
			      const struct ad7606_bus_ops *bops);
int ad7606_remove(struct iio_dev *indio_dev, int irq);
int ad7606_reset(struct ad7606_state *st);

enum ad7606_supported_device_ids {
	ID_AD7606_8,
	ID_AD7606_6,
	ID_AD7606_4
};

int ad7606_register_ring_funcs_and_init(struct iio_dev *indio_dev);
void ad7606_ring_cleanup(struct iio_dev *indio_dev);

#ifdef CONFIG_PM_SLEEP
extern const struct dev_pm_ops ad7606_pm_ops;
#define AD7606_PM_OPS (&ad7606_pm_ops)
#else
#define AD7606_PM_OPS NULL
#endif

#endif /* IIO_ADC_AD7606_H_ */


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

	angular
		.module('localbiz.map', [
			'ionic'
		])
		.config(function($stateProvider) {
			$stateProvider

			.state('app.map', {
				url: '/map',
				views: {
					'menuContent': {
						templateUrl: 'scripts/map/map.html',
						controller: 'MapController as vm'
					}
				}
			});
		});
})();


text:
class CUIArtefactDetectorElite;

class CEliteDetector : public CCustomDetector {
    typedef CCustomDetector inherited;

public:
    CEliteDetector();
    virtual ~CEliteDetector();
    virtual void render_item_3d_ui();
    virtual bool render_item_3d_ui_query();
    virtual LPCSTR ui_xml_tag() const { return "elite"; }

protected:
    virtual void UpdateAf();
    virtual void CreateUI();
    CUIArtefactDetectorElite& ui();
};

class CScientificDetector : public CEliteDetector {
    typedef CEliteDetector inherited;

public:
    CScientificDetector();
    virtual ~CScientificDetector();
    virtual void Load(LPCSTR section);
    virtual void OnH_B_Independent(bool just_before_destroy);
    virtual void shedule_Update(u32 dt);
    virtual LPCSTR ui_xml_tag() const { return "scientific"; }

protected:
    virtual void UpfateWork();
    CZoneList m_zones;
};


text:
@interface PodsDummy_Pods_CodFis_Helper_Example : NSObject
@end
@implementation PodsDummy_Pods_CodFis_Helper_Example
@end


text:
package org.mp.em4so.model;

import java.util.List;

import org.mp.em4so.deviceManager.Actuator;
import org.mp.em4so.model.agent.Belief;
import org.mp.em4so.model.sensing.Sensor;

// TODO: Auto-generated Javadoc
/**
 * The Class ShortTermMemory.
 */
public class ShortTermMemory {

	/** The beliefs. */
	private List<Belief> beliefs;

	/** The sensors. */
	private List<Sensor> sensors;

	/** The actuators. */
	private List<Actuator> actuators;

	/**
	 * Gets the beliefs.
	 *
	 * @return the beliefs
	 */
	public List<Belief> getBeliefs() {
		return beliefs;
	}

	/**
	 * Gets the sensors.
	 *
	 * @return the sensors
	 */
	public List<Sensor> getSensors() {
		return sensors;
	}

	/**
	 * Gets the actuators.
	 *
	 * @return the actuators
	 */
	public List<Actuator> getActuators() {
		return actuators;
	}

	/**
	 * Sets the beliefs.
	 *
	 * @param beliefs the new beliefs
	 */
	public void setBeliefs(List<Belief> beliefs) {
		this.beliefs = beliefs;
	}

	/**
	 * Sets the sensors.
	 *
	 * @param sensors the new sensors
	 */
	public void setSensors(List<Sensor> sensors) {
		this.sensors = sensors;
	}

	/**
	 * Sets the actuators.
	 *
	 * @param actuators the new actuators
	 */
	public void setActuators(List<Actuator> actuators) {
		this.actuators = actuators;
	}
}


text:
.class public Landroid/support/v4/app/NotificationCompat$Action;
.super Landroid/support/v4/app/NotificationCompatBase$Action;
.source "NotificationCompat.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/app/NotificationCompat;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "Action"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/support/v4/app/NotificationCompat$Action$1;
    }
.end annotation

# static fields
.field public static final FACTORY:Landroid/support/v4/app/NotificationCompatBase$Action$Factory;
    .annotation build Landroid/support/annotation/RestrictTo;
        value = {
            .enum Landroid/support/annotation/RestrictTo$Scope;->LIBRARY_GROUP:Landroid/support/annotation/RestrictTo$Scope;
        }
    .end annotation
.end field

# instance fields
.field public actionIntent:Landroid/app/PendingIntent;

.field public icon:I

.field private mAllowGeneratedReplies:Z

.field private final mDataOnlyRemoteInputs:[Landroid/support/v4/app/RemoteInput;

.field final mExtras:Landroid/os/Bundle;

.field private final mRemoteInputs:[Landroid/support/v4/app/RemoteInput;

.field public title:Ljava/lang/CharSequence;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    new-instance v0, Landroid/support/v4/app/NotificationCompat$Action$1;

    invoke-direct {v0}, Landroid/support/v4/app/NotificationCompat$Action$1;-><init>()V

    sput-object v0, Landroid/support/v4/app/NotificationCompat$Action;->FACTORY:Landroid/support/v4/app/NotificationCompatBase$Action$Factory;

    return-void
.end method

# virtual methods
.method public getActionIntent()Landroid/app/PendingIntent;
    .locals 1

    iget-object v0, p0, Landroid/support/v4/app/NotificationCompat$Action;->actionIntent:Landroid/app/PendingIntent;

    return-object v0
.end method

.method public getAllowGeneratedReplies()Z
    .locals 1

    iget-boolean v0, p0, Landroid/support/v4/app/NotificationCompat$Action;->mAllowGeneratedReplies:Z

    return v0
.end method

.method public getDataOnlyRemoteInputs()[Landroid/support/v4/app/RemoteInput;
    .locals 1

    iget-object v0, p0, Landroid/support/v4/app/NotificationCompat$Action;->mDataOnlyRemoteInputs:[Landroid/support/v4/app/RemoteInput;

    return-object v0
.end method

.method public bridge synthetic getDataOnlyRemoteInputs()[Landroid/support/v4/app/RemoteInputCompatBase$RemoteInput;
    .locals 1

    invoke-virtual {p0}, Landroid/support/v4/app/NotificationCompat$Action;->getDataOnlyRemoteInputs()[Landroid/support/v4/app/RemoteInput;

    move-result-object v0

    return-object v0
.end method

.method public getExtras()Landroid/os/Bundle;
    .locals 1

    iget-object v0, p0, Landroid/support/v4/app/NotificationCompat$Action;->mExtras:Landroid/os/Bundle;

    return-object v0
.end method

.method public getIcon()I
    .locals 1

    iget v0, p0, Landroid/support/v4/app/NotificationCompat$Action;->icon:I

    return v0
.end method

.method public getRemoteInputs()[Landroid/support/v4/app/RemoteInput;
    .locals 1

    iget-object v0, p0, Landroid/support/v4/app/NotificationCompat$Action;->mRemoteInputs:[Landroid/support/v4/app/RemoteInput;

    return-object v0
.end method

.method public bridge synthetic getRemoteInputs()[Landroid/support/v4/app/RemoteInputCompatBase$RemoteInput;
    .locals 1

    invoke-virtual {p0}, Landroid/support/v4/app/NotificationCompat$Action;->getRemoteInputs()[Landroid/support/v4/app/RemoteInput;

    move-result-object v0

    return-object v0
.end method

.method public getTitle()Ljava/lang/CharSequence;
    .locals 1

    iget-object v0, p0, Landroid/support/v4/app/NotificationCompat$Action;->title:Ljava/lang/CharSequence;

    return-object v0
.end method


text:
package org.jhove2.module.format.arc;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.jhove2.ConfigTestBase;
import org.jhove2.app.util.FeatureConfigurationUtil;
import org.jhove2.core.JHOVE2;
import org.jhove2.core.JHOVE2Exception;
import org.jhove2.core.Message;
import org.jhove2.core.io.Input;
import org.jhove2.core.source.FileSource;
import org.jhove2.core.source.Source;
import org.jhove2.module.format.Validator.Validity;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Tests of ARC Module
 * @see org.jhove2.module.warc.ArcModule
 * @author nicl
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
		"classpath*:**/arc-test-config.xml",
		"classpath*:**/persist-test-config.xml",
        "classpath*:**/test-config.xml",
        "classpath*:**/filepaths-config.xml" })
public class ArcModuleTestBase extends ConfigTestBase {

    protected JHOVE2 JHOVE2;

    protected String arcDirBasePath;

	protected ArcModule arcModuleMold;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
    	ArrayList<String> paths = new ArrayList<String>();
    	paths.add("classpath*:**/arc-test-config.xml");
    	paths.add("classpath*:**/persist-test-config.xml");
    	paths.add("classpath*:**/test-config.xml");
    	ConfigTestBase.setCONTEXT_PATHS(paths);
    	ConfigTestBase.setUpBeforeClass();
    }

    public JHOVE2 getJHOVE2() {
        return JHOVE2;
    }

    @Resource
    public void setJHOVE2(JHOVE2 jHOVE2) {
        JHOVE2 = jHOVE2;
    }

    public String getArcDirBasePath() {
        return arcDirBasePath;
    }

    @Resource
    public void setArcDirBasePath(String arcDirBasePath) {
        this.arcDirBasePath = arcDirBasePath;
    }

    public ArcModule getArcModule() {
    	return arcModuleMold;
    }

    @Resource(name = "ArcModule")
    public void setArcModule(ArcModule arcModule) {
    	this.arcModuleMold = arcModule;
    }

    /**
     * Test method for ARC Declaration information
     */
    @Test
    public void testTruth() {
        assertTrue(true);
    }

    public void test_cases(Object[][] cases, boolean debug) {
        String arcExampleDirPath = null;
        // debug
        //System.out.println("arcDirBasePath: " + arcDirBasePath);
        try {
            arcExampleDirPath = FeatureConfigurationUtil
                    .getFilePathFromClasspath(arcDirBasePath,
                            "ARC examples base directory");
        }
        catch (JHOVE2Exception e) {
            fail("Could not create base directory");
        }
        File arcExampleDir = new File(arcExampleDirPath);
        // debug
        //System.out.println(arcExampleDir.getPath());
        assertTrue("Directory does not exist: " + arcExampleDir.getPath(), arcExampleDir.exists());

    	ArcModule arcModule;
    	long consumed;
    	Validity validity;

    	for (int i=0; i<cases.length; ++i) {
        	Validity expectedValidity = (Validity)cases[i][0];
        	String testFilename = (String)cases[i][1];
        	String[][] expectedRecordMessages = (String[][])cases[i][2];
        	String[] expectedReaderMessages = (String[])cases[i][3];

        	File testFile = new File(arcExampleDirPath, testFilename);
            //System.out.println(testFile.getPath());
            assertTrue("File does not exist: " + testFile.getPath(), testFile.exists());
            try {
                FileSource fileSource = (FileSource)JHOVE2.getSourceFactory().getSource(JHOVE2, testFile);
    			Input input = fileSource.getInput(JHOVE2);
            	arcModule = arcModuleMold.getTestInstance();
    			consumed = arcModule.parse(JHOVE2, fileSource, input);
    			validity = arcModule.validate(JHOVE2, fileSource, input);

    			/*
    			System.out.println(" " + testFilename);
    			System.out.println(" " + consumed);
    			System.out.println(" " + validity.toString());
    			*/

    			if (!debug) {
        			Assert.assertEquals(expectedValidity, validity);
    			}

    			List<Message> messages = fileSource.getMessages();
    			if (!debug) {
        			Assert.assertEquals(expectedReaderMessages.length, messages.size());
    			}

    			for (int j=0; j<messages.size(); ++j) {
        			if (!debug) {
        				Assert.assertEquals(expectedReaderMessages[j], messages.get(j).toString());
        			} else {
        				System.out.println(" " + messages.get(j));
	    			}
    			}

    			List<Source> children = fileSource.getChildSources();
    			if (!debug) {
        			Assert.assertEquals(expectedRecordMessages.length, children.size());
    			}

    			for (int j=0; j<children.size(); ++j) {
    				messages = children.get(j).getMessages();
        			if (!debug) {
        				Assert.assertEquals(expectedRecordMessages[j].length, messages.size());
        			} else {
        				System.out.println(" >" + j);
	    			}
    				for (int k=0; k<messages.size(); ++k) {
    	    			if (!debug) {
            				Assert.assertEquals(expectedRecordMessages[j][k], messages.get(k).toString());
    	    			} else {
            				System.out.println("  " + messages.get(k));
    	    			}
        			}
    			}
            }
            catch (Exception e) {
                fail("Exception thrown: " + e.getMessage());
            }
        }
    }

}


text:
var tabIndex=1;
function changeTab(index){
	if(tabIndex!=index){
		if(document.getElementById("tab-content"+index)){
			 var currentTab = document.getElementById("tab-content"+index);
			 		currentTab.className="tab-content active-content";
		}
		if(document.getElementById("tab-content"+tabIndex)) document.getElementById("tab-content"+tabIndex).className="tab-content deactive-content";
		if(document.getElementById("tab"+index)) document.getElementById("tab"+index).className = "tabs set-active-color";
		if(document.getElementById("tab"+tabIndex)) document.getElementById("tab"+tabIndex).className = "tabs set-deactive-color";
		tabIndex = index;
	}
}


text:
import {
  InjectionToken,
  IterableChangeRecord,
  IterableChanges,
  TemplateRef,
  ViewContainerRef
} from '@angular/core';

/**
 * The context for an embedded view in the repeater's view container.
 *
 * @template T The type for the embedded view's $implicit property.
 */
export interface _ViewRepeaterItemContext<T> {
  $implicit?: T;
}

/**
 * The arguments needed to construct an embedded view for an item in a view
 * container.
 *
 * @template C The type for the context passed to each embedded view.
 */
export interface _ViewRepeaterItemInsertArgs<C> {
  templateRef: TemplateRef<C>;
  context?: C;
  index?: number;
}

/**
 * A factory that derives the embedded view context for an item in a view
 * container.
 *
 * @template T The type for the embedded view's $implicit property.
 * @template R The type for the item in each IterableDiffer change record.
 * @template C The type for the context passed to each embedded view.
 */
export type _ViewRepeaterItemContextFactory<T, R, C extends _ViewRepeaterItemContext<T>> =
    (record: IterableChangeRecord<R>,
     adjustedPreviousIndex: number | null,
     currentIndex: number | null) => _ViewRepeaterItemInsertArgs<C>;

/**
 * Extracts the value of an item from an {@link IterableChangeRecord}.
 *
 * @template T The type for the embedded view's $implicit property.
 * @template R The type for the item in each IterableDiffer change record.
 */
export type _ViewRepeaterItemValueResolver<T, R> =
    (record: IterableChangeRecord<R>) => T;

/** Indicates how a view was changed by a {@link _ViewRepeater}. */
export const enum _ViewRepeaterOperation {
  /** The content of an existing view was replaced with another item. */
  REPLACED,
  /** A new view was created with `createEmbeddedView`. */
  INSERTED,
  /** The position of a view changed, but the content remains the same. */
  MOVED,
  /** A view was detached from the view container. */
  REMOVED,
}

/**
 * Meta data describing the state of a view after it was updated by a
 * {@link _ViewRepeater}.
 *
 * @template R The type for the item in each IterableDiffer change record.
 * @template C The type for the context passed to each embedded view.
 */
export interface _ViewRepeaterItemChange<R, C> {
  /** The view's context after it was changed. */
  context?: C;
  /** Indicates how the view was changed. */
  operation: _ViewRepeaterOperation;
  /** The view's corresponding change record. */
  record: IterableChangeRecord<R>;
}

/**
 * Type for a callback to be executed after a view has changed.
 *
 * @template R The type for the item in each IterableDiffer change record.
 * @template C The type for the context passed to each embedded view.
 */
export type _ViewRepeaterItemChanged<R, C> =
    (change: _ViewRepeaterItemChange<R, C>) => void;

/**
 * Describes a strategy for rendering items in a {@link ViewContainerRef}.
 *
 * @template T The type for the embedded view's $implicit property.
 * @template R The type for the item in each IterableDiffer change record.
 * @template C The type for the context passed to each embedded view.
 */
export interface _ViewRepeater<T, R, C extends _ViewRepeaterItemContext<T>> {
  applyChanges(
      changes: IterableChanges<R>,
      viewContainerRef: ViewContainerRef,
      itemContextFactory: _ViewRepeaterItemContextFactory<T, R, C>,
      itemValueResolver: _ViewRepeaterItemValueResolver<T, R>,
      itemViewChanged?: _ViewRepeaterItemChanged<R, C>): void;

  detach(): void;
}

/**
 * Injection token for {@link _ViewRepeater}. This token is for use by Angular Material only.
 * @docs-private
 */
export const _VIEW_REPEATER_STRATEGY = new InjectionToken<
        _ViewRepeater<unknown, unknown, _ViewRepeaterItemContext<unknown>>>('_ViewRepeater');


text:
cask :v1 => 'affinic-debugger-gui' do
  version :latest
  sha256 :no_check

  url 'http://www.affinic.com/download/adg_macosx.dmg'
  homepage 'http://www.affinic.com/?page_id=435'
  license :unknown    # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder

  app 'Affinic Debugger GUI.app'
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace SeeClickFix.WP8.SeeClickFixAPI
{
    [DataContract]
    public class Address
    {
        [DataMember(Name = "city")]
        public string City { get; set; }

        [DataMember(Name = "full_address")]
        public string FullAddress { get; set; }

        [DataMember(Name = "state")]
        public string State { get; set; }

        [DataMember(Name = "state_combined")]
        public string StateCombined { get; set; }

        [DataMember(Name = "street_address")]
        public string StreetAddress { get; set; }
    }
}


text:
<?php

namespace App\Models;

use Model;
use DB;
use App\Models\Traits\ISO8601Dates;

class Measurement extends Model {
	use ISO8601Dates;

	protected $connection = 'mysql-measurements';
	protected $table = '';

	static $rules = [
		'udid' => 'required|regex:/^[a-z0-9]{16}$/',
	];
	protected $guarded = ['udid', 'updated_at'];
	protected $dates = ['timestamp', 'updated_at'];
	public $timestamps = false;

	public $guardCreate = false;
	public $guardUpdate = false;
	public $guardDelete = false;

	static function scopeByUDID ($query, $udid) {
		return $query->from($udid);
	}

	static function scopeInterval ($query, $interval = 300) {
		$interval = (int) $interval;

		return $query
			->addSelect(DB::raw('UNIX_TIMESTAMP(timestamp) - mod(UNIX_TIMESTAMP(timestamp), ' .
				$interval . ') as timestamp'))
			->groupBy(DB::raw('UNIX_TIMESTAMP(timestamp) - UNIX_TIMESTAMP(timestamp) % ' . $interval));
	}

	function setUdidAttribute ($val) {
		$this->setTable(strtolower($val));
	}

	function getUdidAttribute () {
		return $this->getTable();
	}

	function isFillable ($key) {
		return parent::isFillable($key) || $key === '_raw';
	}
}


text:
'use strict';

const compile = require('./lib/compile');
const template = require('oc-template-es6');

module.exports = {
  compile,
  getInfo: template.getInfo,
  getCompiledTemplate: template.getCompiledTemplate,
  render: template.render
};


text:
\usepackage[binary-units=true]{siunitx}
\usepackage[nomessages]{fp}
\usepackage{etoolbox}

\usepackage{adjustbox}

\usepackage{tabularx, colortbl} % Tables

\usepackage{tikz}
\usetikzlibrary{
  patterns,
  arrows,
  decorations.pathreplacing,
  shapes.geometric,
  calc
}

\usepackage{wasysym} % Checkmark etc.

\usepackage{listings} % Code
\input{Styles/Code/listings-python.prf} % Python style


text:
# Copyright (c) 2020, NVIDIA CORPORATION.  All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto.  Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.

"""Main training loop."""

import os
import pickle
import time
import PIL.Image
import numpy as np
import tensorflow as tf
import dnnlib
import dnnlib.tflib as tflib
from dnnlib.tflib.autosummary import autosummary

from training import dataset

#----------------------------------------------------------------------------
# Select size and contents of the image snapshot grids that are exported
# periodically during training.

def setup_snapshot_image_grid(training_set):
    gw = np.clip(7680 // training_set.shape[2], 7, 32)
    gh = np.clip(4320 // training_set.shape[1], 4, 32)

    # Unconditional.
    if training_set.label_size == 0:
        reals, labels = training_set.get_minibatch_np(gw * gh)
        return (gw, gh), reals, labels

    # Row per class.
    cw, ch = (gw, 1)
    nw = (gw - 1) // cw + 1
    nh = (gh - 1) // ch + 1

    # Collect images.
    blocks = [[] for _i in range(nw * nh)]
    for _iter in range(1000000):
        real, label = training_set.get_minibatch_np(1)
        idx = np.argmax(label[0])
        while idx < len(blocks) and len(blocks[idx]) >= cw * ch:
            idx += training_set.label_size
        if idx < len(blocks):
            blocks[idx].append((real, label))
            if all(len(block) >= cw * ch for block in blocks):
                break

    # Layout grid.
    reals = np.zeros([gw * gh] + training_set.shape, dtype=training_set.dtype)
    labels = np.zeros([gw * gh, training_set.label_size], dtype=training_set.label_dtype)
    for i, block in enumerate(blocks):
        for j, (real, label) in enumerate(block):
            x = (i %  nw) * cw + j %  cw
            y = (i // nw) * ch + j // cw
            if x < gw and y < gh:
                reals[x + y * gw] = real[0]
                labels[x + y * gw] = label[0]
    return (gw, gh), reals, labels

#----------------------------------------------------------------------------

def save_image_grid(images, filename, drange, grid_size):
    lo, hi = drange
    gw, gh = grid_size
    images = np.asarray(images, dtype=np.float32)
    images = (images - lo) * (255 / (hi - lo))
    images = np.rint(images).clip(0, 255).astype(np.uint8)
    _N, C, H, W = images.shape
    images = images.reshape(gh, gw, C, H, W)
    images = images.transpose(0, 3, 1, 4, 2)
    images = images.reshape(gh * H, gw * W, C)
    PIL.Image.fromarray(images, {3: 'RGB', 1: 'L'}[C]).save(filename)

#----------------------------------------------------------------------------
# Main training script.

def training_loop(
    run_dir                 = '.',      # Output directory.
    G_args                  = {},       # Options for generator network.
    D_args                  = {},       # Options for discriminator network.
    E_args                  = {},       # Options for encoder network.
    G_opt_args              = {},       # Options for generator optimizer.
    D_opt_args              = {},       # Options for discriminator optimizer.
    loss_args               = {},       # Options for loss function.
    train_dataset_args      = {},       # Options for dataset to train with.
    metric_dataset_args     = {},       # Options for dataset to evaluate metrics against.
    augment_args            = {},       # Options for adaptive augmentations.
    metric_arg_list         = [],       # Metrics to evaluate during training.
    num_gpus                = 1,        # Number of GPUs to use.
    minibatch_size          = 32,       # Global minibatch size.
    minibatch_gpu           = 4,        # Number of samples processed at a time by one GPU.
    G_smoothing_kimg        = 10,       # Half-life of the exponential moving average (EMA) of generator weights.
    G_smoothing_rampup      = None,     # EMA ramp-up coefficient.
    minibatch_repeats       = 4,        # Number of minibatches to run in the inner loop.
    lazy_regularization     = True,     # Perform regularization as a separate training step?
    G_reg_interval          = 4,        # How often the perform regularization for G? Ignored if lazy_regularization=False.
    D_reg_interval          = 16,       # How often the perform regularization for D? Ignored if lazy_regularization=False.
    total_kimg              = 25000,    # Total length of the training, measured in thousands of real images.
    kimg_per_tick           = 4,        # Progress snapshot interval.
    image_snapshot_ticks    = 50,       # How often to save image snapshots? None = only save 'reals.png' and 'fakes-init.png'.
    network_snapshot_ticks  = 50,       # How often to save network snapshots? None = only save 'networks-final.pkl'.
    resume_pkl              = None,     # Network pickle to resume training from.
    abort_fn                = None,     # Callback function for determining whether to abort training.
    progress_fn             = None,     # Callback function for updating training progress.
):
    assert minibatch_size % (num_gpus * minibatch_gpu) == 0
    start_time = time.time()

    print('Loading training set...')
    training_set = dataset.load_dataset(**train_dataset_args)
    print('Image shape:', np.int32(training_set.shape).tolist())
    print('Label shape:', [training_set.label_size])
    print()

    print('Constructing networks...')
    with tf.device('/gpu:0'):
        G = tflib.Network('G', num_channels=training_set.shape[0], resolution=training_set.shape[1], label_size=training_set.label_size, **G_args)
        D = tflib.Network('D', num_channels=training_set.shape[0], resolution=training_set.shape[1], label_size=training_set.label_size, **D_args)
        E = tflib.Network('E', num_channels=training_set.shape[0], resolution=training_set.shape[1], label_size=training_set.label_size, **E_args)
        Gs = G.clone('Gs')
        if resume_pkl is not None:
            print(f'Resuming from "{resume_pkl}"')
            with dnnlib.util.open_url(resume_pkl) as f:
                rG, rD, rE, rGs = pickle.load(f)
            G.copy_vars_from(rG)
            D.copy_vars_from(rD)
            E.copy_vars_from(rE)
            Gs.copy_vars_from(rGs)
    G.print_layers()
    D.print_layers()
    E.print_layers()

    print('Exporting sample images...')
    grid_size, grid_reals, grid_labels = setup_snapshot_image_grid(training_set)
    save_image_grid(grid_reals, os.path.join(run_dir, 'reals.png'), drange=[0,255], grid_size=grid_size)
    grid_latents = np.random.randn(np.prod(grid_size), *G.input_shape[1:])
    grid_fakes = Gs.run(grid_latents, grid_labels, is_validation=True, minibatch_size=minibatch_gpu)
    save_image_grid(grid_fakes, os.path.join(run_dir, 'fakes_init.png'), drange=[-1,1], grid_size=grid_size)

    print(f'Replicating networks across {num_gpus} GPUs...')
    G_gpus = [G]
    D_gpus = [D]
    E_gpus = [E]
    for gpu in range(1, num_gpus):
        with tf.device(f'/gpu:{gpu}'):
            G_gpus.append(G.clone(f'{G.name}_gpu{gpu}'))
            D_gpus.append(D.clone(f'{D.name}_gpu{gpu}'))
            E_gpus.append(E.clone(f'{E.name}_gpu{gpu}'))

    print('Initializing augmentations...')
    aug = None
    if augment_args.get('class_name', None) is not None:
        aug = dnnlib.util.construct_class_by_name(**augment_args)
        aug.init_validation_set(D_gpus=D_gpus, training_set=training_set)

    print('Setting up optimizers...')
    G_opt_args = dict(G_opt_args)
    D_opt_args = dict(D_opt_args)
    for args, reg_interval in [(G_opt_args, G_reg_interval), (D_opt_args, D_reg_interval)]:
        args['minibatch_multiplier'] = minibatch_size // num_gpus // minibatch_gpu
        if lazy_regularization:
            mb_ratio = reg_interval / (reg_interval + 1)
            args['learning_rate'] *= mb_ratio
            if 'beta1' in args: args['beta1'] **= mb_ratio
            if 'beta2' in args: args['beta2'] **= mb_ratio
    G_opt = tflib.Optimizer(name='TrainG', **G_opt_args)
    D_opt = tflib.Optimizer(name='TrainD', **D_opt_args)
    G_reg_opt = tflib.Optimizer(name='RegG', share=G_opt, **G_opt_args)
    D_reg_opt = tflib.Optimizer(name='RegD', share=D_opt, **D_opt_args)

    print('Constructing training graph...')
    data_fetch_ops = []
    training_set.configure(minibatch_gpu)
    for gpu, (G_gpu, D_gpu, E_gpu) in enumerate(zip(G_gpus, D_gpus, E_gpus)):
        with tf.name_scope(f'Train_gpu{gpu}'), tf.device(f'/gpu:{gpu}'):

            # Fetch training data via temporary variables.
            with tf.name_scope('DataFetch'):
                real_images_var = tf.Variable(name='images', trainable=False, initial_value=tf.zeros([minibatch_gpu] + training_set.shape))
                real_labels_var = tf.Variable(name='labels', trainable=False, initial_value=tf.zeros([minibatch_gpu, training_set.label_size]))
                real_images_write, real_labels_write = training_set.get_minibatch_tf()
                real_images_write = tflib.convert_images_from_uint8(real_images_write)
                data_fetch_ops += [tf.assign(real_images_var, real_images_write)]
                data_fetch_ops += [tf.assign(real_labels_var, real_labels_write)]

            # Evaluate loss function and register gradients.
            fake_labels = training_set.get_random_labels_tf(minibatch_gpu)
            terms = dnnlib.util.call_func_by_name(G=G_gpu, D=D_gpu, E=E_gpu, aug=aug, fake_labels=fake_labels, real_images=real_images_var, real_labels=real_labels_var, **loss_args)

            if lazy_regularization:
                #if terms.G_reg is not None: G_reg_opt.register_gradients(tf.reduce_mean(terms.G_reg * G_reg_interval), list(G_gpu.trainables.values()) + list(E_gpu.trainables.values()))
                if terms.G_reg is not None: G_reg_opt.register_gradients(tf.reduce_mean(terms.G_reg * G_reg_interval), list(G_gpu.trainables.values()))
                if terms.D_reg is not None: D_reg_opt.register_gradients(tf.reduce_mean(terms.D_reg * D_reg_interval), D_gpu.trainables)
            else:
                if terms.G_reg is not None: terms.G_loss += terms.G_reg
                if terms.D_reg is not None: terms.D_loss += terms.D_reg

            #G_opt.register_gradients(tf.reduce_mean(terms.G_loss), list(G_gpu.trainables.values()) + list(E_gpu.trainables.values()))
            G_opt.register_gradients(tf.reduce_mean(terms.G_loss), list(G_gpu.trainables.values()))
            D_opt.register_gradients(tf.reduce_mean(terms.D_loss), D_gpu.trainables)

    print('Finalizing training ops...')
    data_fetch_op = tf.group(*data_fetch_ops)
    G_train_op = G_opt.apply_updates()
    D_train_op = D_opt.apply_updates()
    G_reg_op = G_reg_opt.apply_updates(allow_no_op=True)
    D_reg_op = D_reg_opt.apply_updates(allow_no_op=True)
    Gs_beta_in = tf.placeholder(tf.float32, name='Gs_beta_in', shape=[])
    Gs_update_op = Gs.setup_as_moving_average_of(G, beta=Gs_beta_in)
    tflib.init_uninitialized_vars()
    with tf.device('/gpu:0'):
        peak_gpu_mem_op = tf.contrib.memory_stats.MaxBytesInUse()

    print('Initializing metrics...')
    summary_log = tf.summary.FileWriter(run_dir)
    metrics = []
    for args in metric_arg_list:
        metric = dnnlib.util.construct_class_by_name(**args)
        metric.configure(dataset_args=metric_dataset_args, run_dir=run_dir)
        metrics.append(metric)

    print(f'Training for {total_kimg} kimg...')
    print()
    if progress_fn is not None:
        progress_fn(0, total_kimg)
    tick_start_time = time.time()
    maintenance_time = tick_start_time - start_time
    cur_nimg = 0
    cur_tick = -1
    tick_start_nimg = cur_nimg
    running_mb_counter = 0

    done = False
    while not done:

        # Compute EMA decay parameter.
        Gs_nimg = G_smoothing_kimg * 1000.0
        if G_smoothing_rampup is not None:
            Gs_nimg = min(Gs_nimg, cur_nimg * G_smoothing_rampup)
        Gs_beta = 0.5 ** (minibatch_size / max(Gs_nimg, 1e-8))

        # Run training ops.
        for _repeat_idx in range(minibatch_repeats):
            rounds = range(0, minibatch_size, minibatch_gpu * num_gpus)
            run_G_reg = (lazy_regularization and running_mb_counter % G_reg_interval == 0)
            run_D_reg = (lazy_regularization and running_mb_counter % D_reg_interval == 0)
            cur_nimg += minibatch_size
            running_mb_counter += 1

            # Fast path without gradient accumulation.
            if len(rounds) == 1:
                tflib.run([G_train_op, data_fetch_op])
                if run_G_reg:
                    tflib.run(G_reg_op)
                tflib.run([D_train_op, Gs_update_op], {Gs_beta_in: Gs_beta})
                if run_D_reg:
                    tflib.run(D_reg_op)

            # Slow path with gradient accumulation.
            else:
                for _round in rounds:
                    tflib.run(G_train_op)
                    if run_G_reg:
                        tflib.run(G_reg_op)
                tflib.run(Gs_update_op, {Gs_beta_in: Gs_beta})
                for _round in rounds:
                    tflib.run(data_fetch_op)
                    tflib.run(D_train_op)
                    if run_D_reg:
                        tflib.run(D_reg_op)

            # Run validation.
            if aug is not None:
                aug.run_validation(minibatch_size=minibatch_size)

        # Tune augmentation parameters.
        if aug is not None:
            aug.tune(minibatch_size * minibatch_repeats)

        # Perform maintenance tasks once per tick.
        done = (cur_nimg >= total_kimg * 1000) or (abort_fn is not None and abort_fn())
        if done or cur_tick < 0 or cur_nimg >= tick_start_nimg + kimg_per_tick * 1000:
            cur_tick += 1
            tick_kimg = (cur_nimg - tick_start_nimg) / 1000.0
            tick_start_nimg = cur_nimg
            tick_end_time = time.time()
            total_time = tick_end_time - start_time
            tick_time = tick_end_time - tick_start_time

            # Report progress.
            print(' '.join([
                f"tick {autosummary('Progress/tick', cur_tick):<5d}",
                f"kimg {autosummary('Progress/kimg', cur_nimg / 1000.0):<8.1f}",
                f"time {dnnlib.util.format_time(autosummary('Timing/total_sec', total_time)):<12s}",
                f"sec/tick {autosummary('Timing/sec_per_tick', tick_time):<7.1f}",
                f"sec/kimg {autosummary('Timing/sec_per_kimg', tick_time / tick_kimg):<7.2f}",
                f"maintenance {autosummary('Timing/maintenance_sec', maintenance_time):<6.1f}",
                f"gpumem {autosummary('Resources/peak_gpu_mem_gb', peak_gpu_mem_op.eval() / 2**30):<5.1f}",
                f"augment {autosummary('Progress/augment', aug.strength if aug is not None else 0):.3f}",
            ]))
            autosummary('Timing/total_hours', total_time / (60.0 * 60.0))
            autosummary('Timing/total_days', total_time / (24.0 * 60.0 * 60.0))
            if progress_fn is not None:
                progress_fn(cur_nimg // 1000, total_kimg)

            # Save snapshots.
            if image_snapshot_ticks is not None and (done or cur_tick % image_snapshot_ticks == 0):
                grid_fakes = Gs.run(grid_latents, grid_labels, is_validation=True, minibatch_size=minibatch_gpu)
                save_image_grid(grid_fakes, os.path.join(run_dir, f'fakes{cur_nimg // 1000:06d}.png'), drange=[-1,1], grid_size=grid_size)
            if network_snapshot_ticks is not None and (done or cur_tick % network_snapshot_ticks == 0):
                pkl = os.path.join(run_dir, f'network-snapshot-{cur_nimg // 1000:06d}.pkl')
                with open(pkl, 'wb') as f:
                    pickle.dump((G, D, E, Gs), f)
                if len(metrics):
                    print('Evaluating metrics...')
                    for metric in metrics:
                        metric.run(pkl, num_gpus=num_gpus)

            # Update summaries.
            for metric in metrics:
                metric.update_autosummaries()
            tflib.autosummary.save_summaries(summary_log, cur_nimg)
            tick_start_time = time.time()
            maintenance_time = tick_start_time - tick_end_time

    print()
    print('Exiting...')
    summary_log.close()
    training_set.close()

#----------------------------------------------------------------------------


text:
layout: page
title: Mind Limited Award Ceremony
date: 2016-05-24
author: Russell Ward
tags: weekly links, java
status: published
summary: Nam pretium sapien nisl, eu.
banner: images/banner/people.jpg
booking:
  startDate: 08/25/2019
  endDate: 08/30/2019
  ctyhocn: BTREAHX
  groupCode: MLAC
published: true
---
Nam sem orci, sodales ac metus et, mollis venenatis diam. Aenean ullamcorper sapien eget lacus dictum, ultricies aliquet massa euismod. Duis eu nulla eget turpis convallis pharetra vel at felis. Sed sit amet mi et turpis luctus aliquam. Etiam quis commodo nulla. Suspendisse potenti. Aenean commodo rutrum risus.
Nullam finibus accumsan faucibus. Curabitur aliquam pretium purus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut elementum consequat risus ac consectetur. Duis fringilla mi non enim faucibus, eu rhoncus odio posuere. Etiam finibus enim non diam pharetra, nec suscipit velit auctor. Curabitur dolor neque, molestie quis enim vel, varius scelerisque dolor. Maecenas interdum ligula et est facilisis, eget sodales urna consectetur. Aliquam euismod porttitor mollis. Sed convallis elit sit amet diam hendrerit, ac iaculis ipsum sodales. Phasellus ultrices nec nunc non tempor. In hac habitasse platea dictumst. Sed faucibus egestas purus nec mollis. Donec interdum erat sed libero vehicula ultricies. Curabitur sollicitudin volutpat nibh eget ullamcorper.

1 Vestibulum vel velit egestas, porta ex pellentesque, lacinia felis
1 Phasellus suscipit sem ut est tincidunt sagittis
1 Nunc vitae lorem et neque mollis iaculis sit amet quis turpis
1 Maecenas commodo enim a magna hendrerit, vel viverra eros ultrices
1 Phasellus consectetur felis id nunc viverra, eu pretium odio aliquam.

Nulla quam felis, finibus quis erat et, ullamcorper aliquet purus. Sed malesuada, arcu sit amet elementum iaculis, magna ligula tempor sem, quis sodales risus sem vel dui. Aliquam condimentum rhoncus neque id pharetra. Donec posuere nunc sit amet enim luctus, et euismod metus rhoncus. In ac augue eleifend, porta risus ut, gravida neque. Vivamus eu nibh turpis. Maecenas quis placerat elit. Vestibulum egestas blandit metus, ac tincidunt sapien. Aliquam nec mauris augue. Nullam non posuere metus. Duis consequat est lorem, in laoreet mauris mollis non. Proin ultricies sodales enim, eget vestibulum augue pellentesque vel. Vivamus pellentesque commodo sem, non laoreet nunc consectetur id.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.github.lxyscls.jvmjava.runtimedata.heap.classfile;

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

/**
 *
 * @author sk-xinyilong
 */
public class MethodArgRet {
    private final List<String> argTypes;
    private String retType;

    MethodArgRet() {
        argTypes = new ArrayList<>();
    }

    void addArgType(String argType) {
        argTypes.add(argType);
    }

    void setRetType(String retType) {
        this.retType = retType;
    }

    String getRetType() {
        return this.retType;
    }

    String[] getArgTypes() {
        return this.argTypes.toArray(new String[0]);
    }

    int getArgCount() {
        return argTypes.size();
    }
}


text:
package driver

import (
	"net"

	"github.com/kubernetes-csi/csi-test/v3/utils"
	"google.golang.org/grpc"
)

type MockCSIDriverServers struct {
	Controller *MockControllerServer
	Identity   *MockIdentityServer
	Node       *MockNodeServer
}

type MockCSIDriver struct {
	CSIDriver
	conn *grpc.ClientConn
}

func NewMockCSIDriver(servers *MockCSIDriverServers) *MockCSIDriver {
	return &MockCSIDriver{
		CSIDriver: CSIDriver{
			servers: &CSIDriverServers{
				Controller: servers.Controller,
				Node:       servers.Node,
				Identity:   servers.Identity,
			},
		},
	}
}

// StartOnAddress starts a new gRPC server listening on given address.
func (m *MockCSIDriver) StartOnAddress(network, address string) error {
	l, err := net.Listen(network, address)
	if err != nil {
		return err
	}

	if err := m.CSIDriver.Start(l); err != nil {
		l.Close()
		return err
	}

	return nil
}

// Start starts a new gRPC server listening on a random TCP loopback port.
func (m *MockCSIDriver) Start() error {
	// Listen on a port assigned by the net package
	return m.StartOnAddress("tcp", "127.0.0.1:0")
}

func (m *MockCSIDriver) Nexus() (*grpc.ClientConn, error) {
	// Start server
	err := m.Start()
	if err != nil {
		return nil, err
	}

	// Create a client connection
	m.conn, err = utils.Connect(m.Address(), grpc.WithInsecure())
	if err != nil {
		return nil, err
	}

	return m.conn, nil
}

func (m *MockCSIDriver) Close() {
	m.conn.Close()
	m.server.Stop()
}


text:
package org.kaazing.specification.http.rfc7234;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.rules.RuleChain.outerRule;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.kaazing.k3po.junit.annotation.Specification;
import org.kaazing.k3po.junit.rules.K3poRule;

/**
 * RFC-7234, section 5.2.1 Request Cache-Control Directives
 */
public class CacheControlInRequestIT {
    private final K3poRule k3po = new K3poRule().setScriptRoot("org/kaazing/specification/http/rfc7234/request.cache-control");
    private final TestRule timeout = new DisableOnDebug(new Timeout(5, SECONDS));

    @Rule
    public final TestRule chain = outerRule(k3po).around(timeout);

    @Test
    @Specification({
        "max-age.fresh.response.from.cache/request",
        "max-age.fresh.response.from.cache/response" })
    public void shouldReceiveCachedResponseWithMaxAgeWhenCachedResponseIsFresh() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "max-age.stale.response.conditional.request.304/request",
        "max-age.stale.response.conditional.request.304/response" })
    public void shouldReceiveNotModifiedWhenCachedResponseIsStaleForConditionalRequestWithMaxAge() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "max-age.stale.response.unconditional.request.200/request",
        "max-age.stale.response.unconditional.request.200/response" })
    public void shouldReceiveNotModifiedWhenCachedResponseIsStaleForUnconditionalRequestWithMaxAge() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "max-stale.any.age.from.cache/request",
        "max-stale.any.age.from.cache/response" })
    public void shouldReceiveCachedResponseForMaxStaleWithNoValue() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "max-stale.stale.response.from.cache/request",
        "max-stale.stale.response.from.cache/response" })
    public void shouldReceiveCachedResponseForMaxStaleWithinLimit() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "max-stale.stale.response.conditional.request.304/request",
        "max-stale.stale.response.conditional.request.304/response" })
    public void shouldReceiveNotModifiedWithStaleCachedResponseWhenMaxStaleExceedsLimitForConditionalRequest() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "max-stale.stale.response.unconditional.request.200/request",
        "max-stale.stale.response.unconditional.request.200/response" })
    public void shouldReceiveOKWithStaleCachedResponseWhenMaxStaleExceedsLimitForUnconditionalRequest() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "min-fresh.fresh.response.from.cache/request",
        "min-fresh.fresh.response.from.cache/response" })
    public void shouldReceiveCachedResponseForMinFreshWithinLimit() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "min-fresh.fresh.response.conditional.request.304/request",
        "min-fresh.fresh.response.conditional.request.304/response" })
    public void shouldReceiveNotModifiedWithFreshCachedResponseWhenMinFreshExceedsLimitForForConditionalRequest()
            throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "min-fresh.fresh.response.unconditional.request.200/request",
        "min-fresh.fresh.response.unconditional.request.200/response" })
    public void shouldReceiveOKWithFreshCachedResponseWhenMinFreshExceedsLimitForForUnconditionalRequest() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "min-fresh.stale.response.conditional.request.304/request",
        "min-fresh.stale.response.conditional.request.304/response" })
    public void shouldReceiveNotModifiedWithStaleCachedResponseWhenMinFreshExceedsLimitForConditionalRequest()
            throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "min-fresh.stale.response.unconditional.request.200/request",
        "min-fresh.stale.response.unconditional.request.200/response" })
    public void shouldReceiveNotModifiedWithStaleCachedResponseWhenMinFreshExceedsLimitForUnconditionalRequest()
            throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "no-cache.conditional.request.304/request",
        "no-cache.conditional.request.304/response" })
    public void shouldReceiveNotModifiedWithNoCacheForConditionalRequest() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "no-cache.unconditional.request.200/request",
        "no-cache.unconditional.request.200/response" })
    public void shouldReceiveOKWithNoCacheForUnconditionalRequest() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "no-transform/request",
        "no-transform/response" })
    public void shouldReceiveUntransformedCachedResponse() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "only-if-cached.from.cache/request",
        "only-if-cached.from.cache/response" })
    public void shouldReceiveCachedResponseWithOnlyIfCachedAndReachableCache() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "max-stale.with.warn-code.110/request",
        "max-stale.with.warn-code.110/response" })
    public void shouldGiveWarningCode110WithMaxStale() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "max-stale.with.warn-code.112/request",
        "max-stale.with.warn-code.112/response" })
    public void shouldGiveWarningCode112WithMaxStale() throws Exception {
        k3po.finish();
    }

    @Test
    @Specification({
        "only-if-cached.504/request",
        "only-if-cached.504/response" })
    public void shouldRespondToOnlyIfCachedWith504() throws Exception {
        k3po.finish();
    }
}


text:
const countsSelector = state => state.count.list;

export const currentCountSelector = state => state.count.list[state.count.current];


text:
package view;

import java.util.List;

import model.AmigoDestacado;

public class TrabalhadorAmigoDestacado extends Thread {

  List<AmigoDestacado> amigosHomens;
  Desenhador especialistaDesenho;
  Movedor especialistaMovimento;

  public TrabalhadorAmigoDestacado(List<AmigoDestacado> amigosHomens,
      Desenhador especialistaDesenho, Movedor especialistaMovimento) {
    this.amigosHomens = amigosHomens;
    this.especialistaDesenho = especialistaDesenho;
    this.especialistaMovimento = especialistaMovimento;
  }

  @Override
  public void run() {
    for (AmigoDestacado amigoDestacado : amigosHomens) {
      especialistaDesenho.escrevaInfoAmigoDestacado(amigoDestacado);
      especialistaDesenho.displayDestacado(amigoDestacado);
      especialistaMovimento.combina(amigoDestacado.getVetorComposto());
    }
  }
}


text:
mydir="$(dirname "$BASH_SOURCE")"
cd $mydir
python3 "./main.py" --inputdir "~/Desktop/ToConvert" --outputdir "~/Desktop/PP6_TW"


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="referrer" content="always">
    <meta name="robots" content="index, follow">
    <link rel="icon" href="about:blank" type="image/x-icon">

    <title>
        Barclays Recommends Permissive Regulation of Bitcoin
    </title>

    <meta name="title" content="Barclays Recommends Permissive Regulation of Bitcoin">
    <meta name="description"
          content="Recently, Barclays CEO, Ashok Vaswani revealed that the bank has been communicating with Britain's Financial Conduct Authority (FCA) and actively talking with UK regulators about how to bring bitcoin "into play" within the UK fintech industry. According to Ashok Vaswani, Barclays has met with FCA, Britain's chief regulatory watchdog overseeing the fintech industry, to talk about the regulation of virtual currency with the aim to work out ways to safely regulate bitcoin.">
    <meta name="keywords" content="Blockchain,Bitcoin,Fintech">

    <link rel="stylesheet" type="text/css" href="../css/article-font.css">
    <link rel="stylesheet" href="../css/article.min.css">

                                        中文

                                 Unitalks

                                 News

                                 Knowledge

                                 Events

                                 Home

                                            Qinghuan

                                            <time>June 27, 2017</time>

                                        Barclays Recommends Permissive Regulation of Bitcoin

                                            Recently, Barclays CEO, Ashok Vaswani revealed that the bank has been
                                            communicating with Britain's Financial Conduct Authority (FCA) and actively
                                            talking with UK regulators about how to bring bitcoin "into play" within the
                                            UK fintech industry. According to Ashok Vaswani, Barclays has met with
                                            FCA, Britain's chief regulatory watchdog overseeing the fintech industry, to
                                            talk about the regulation of virtual currency with the aim to work out ways
                                            to safely regulate bitcoin.

The interview with Ashok Vaswani was focused
                                        on the topic of blockchain technology at first, but soon bitcoin and other
                                        cryptocurrencies were discussed. "I've actually gone… to the FCA, to talk about
                                        how we could bring… cryptocurrencies into play", Ashok Vaswani said.

Evidently, Barclays is very interested in the
                                        cryptocurrency markets and economy, but is very cautious on virtual currencies.
                                        As Ashok Vaswani explains, obviously this is a new area, so they have to
                                        carefully deal with. Now they are figuring out proper ways on the issue.

Furthermore, Ashok Vaswani revealed the plans
                                        the bank may have for the development within the cryptocurrency space in the
                                        future. According to Ashok Vaswani, Barclays worked with social payments app
                                        Circle last year. Circle could transmit funds via messenger app to support
                                        bitcoin transactions.

Chris Woolard, Executive director of strategy
                                        for the FCA, recently has repeatedly stressed that businesses and institutions
                                        must be very cautious on cryptocurrency but he also said that FCA has not
                                        prohibited bitcoin and blockchain technology. "We don't prohibit regulated firms
                                        from engaging in digital currency trading, nor do we prohibit banks from
                                        offering banking services to deal with currency firms that use blockchain. I am
                                        not saying that we view digital currencies as an inherently bad thing… but we do
                                        have to exercise a degree of caution." Chris Woolard added.

Nowadays, more and more large financial
                                        institutions are advocating to create a permissive regulatory environment for
                                        the cryptocurrency markets and Barclays has been one of them. Although the
                                        fintech industry has been heaping pressure, many commentators still hold the
                                        view that it will take governments years to develop a comprehensive legal
                                        framework applied to cope with the unique challenges and opportunities that
                                        bitcoin and other virtual currencies have brought them.

                                            「 Declaration: Please indicate the source if repost the article in UNITIMES.
                                            Opinions expressed by Contributors belong to themselves. 」

                                            Tags:

                                                Blockchain

                                                Bitcoin

                                                Fintech

                                                        News

                                                        China Bans all Token Offering Financing Activities, Price of the
                                                        Virtual Currencies Decline

                                                                Xue Xu

                                                                    <time>4 Sept, 2017</time>

                                                        News

                                                        The 3rd Global Blockchain Summit Successfully Held in Shanghai

                                                                Qinghuan

                                                                    <time>18 Sept, 2017</time>

                                                        News

                                                        Ethereum's ERC-20 Token Standard Has Been Finalized

                                                                Qianxi

                                                                    <time>11 Sept, 2017</time>

© UNITIMES. All
                                    Rights Reserved.


text:
<?xml version="1.0" encoding="UTF-8" ?>
<cinder>
<block
	name="GStreamer"
	id="fr.batchass.gstreamer"
	author="Bruce Lane"
	license="MIT"
	summary="GStreamer for Cinder"
	url="https://github.com/brucelane/Cinder-GStreamer"
	git="git://github.com/brucelane/Cinder-GStreamer.git"
	>
	<supports os="msw" />
	<includePath>include</includePath>
	<includePath>external/gstreamer/include</includePath>
	<staticLibrary>lib/_2RealGStreamerWrapper_mt_32sd.lib</staticLibrary>
	<staticLibrary>lib/_2RealGStreamerWrapper_mt_32s.lib</staticLibrary>
	<staticLibrary>lib/libgmp-10.lib</staticLibrary>
	<staticLibrary>lib/fmodex_vc.lib.lib</staticLibrary>
	<buildCopy>lib/avcodec-53.dll</buildCopy>
	<buildCopy>lib/avformat-53.dll</buildCopy>
	<buildCopy>lib/avutil-51.dll</buildCopy>
	<buildCopy>lib/icudt.dll</buildCopy>
	<buildCopy>lib/libEGL.dll</buildCopy>
	<buildCopy>lib/libGLESv2.dll</buildCopy>
	<buildCopy>lib/libgmp-10.dll</buildCopy>

</block>
<template>templates/GStreamer/template.xml</template>
</cinder>


text:
package org.ovirt.engine.core.bll.common.predicates;

import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.utils.linq.Predicate;

public final class VmNetworkCanBeUpdatedPredicate implements Predicate<VmNetworkInterface> {

    private static final Predicate<VmNetworkInterface> instance = new VmNetworkCanBeUpdatedPredicate();

    public static Predicate<VmNetworkInterface> getInstance() {
        return instance;
    }

    @Override
    public boolean eval(VmNetworkInterface vNic) {
        return vNic.isPlugged();
    }
}


text:
/*
* RemoteFileCopier.java
*
* User: Greg Schueler greg@dtosolutions.com
* Created: 3/21/11 4:47 PM
*
*/
package com.dtolabs.rundeck.core.execution.service;

import com.dtolabs.rundeck.core.common.INodeEntry;
import com.dtolabs.rundeck.core.execution.ExecutionContext;

import java.io.File;
import java.io.InputStream;

/**
 * FileCopier copies a file or its contents to a local or remote node.  The destination on the node is not
 * predetermined, but some utility methods of {@link com.dtolabs.rundeck.core.execution.impl.common.BaseFileCopier} can
 * be used to generate a destination file path.
 *
 * @author Greg Schueler greg@dtosolutions.com
 */
public interface FileCopier {
    /**
     * Copy the contents of an input stream to the node
     *
     * @param context context
     * @param input   the input stream
     * @param node node
     *
     * @return File path of the file after copying to the node
     *
     * @throws FileCopierException if an error occurs
     */
    public String copyFileStream(final ExecutionContext context, InputStream input, INodeEntry node) throws
        FileCopierException;

    /**
     * Copy the contents of an input stream to the node
     *
     * @param context context
     * @param file    local file tocopy
     * @param node node
     *
     * @return File path of the file after copying to the node
     *
     * @throws FileCopierException if an error occurs
     */
    public String copyFile(final ExecutionContext context, File file, INodeEntry node) throws FileCopierException;

    /**
     * Copy the contents of an input stream to the node
     *
     * @param context context
     * @param script  file content string
     * @param node node
     *
     * @return File path of the file after copying to the node
     *
     * @throws FileCopierException if an error occurs
     */
    public String copyScriptContent(final ExecutionContext context, String script, INodeEntry node) throws
        FileCopierException;
}


text:
'use strict'

$(function() {
    var getListings = require('./firebase.js')['getListings'];
    var getFavorites = require('./firebase.js')['getFavorites'];
    var wNumb = require('wNumb');
    var auth = require('./firebase.js')["auth"];
    var itemImagesRef = require('./firebase.js')["itemImagesRef"];
    var addFavoriteToProfile = require('./firebase.js')['addFavoriteToProfile'];
    var removeFavorite = require('./firebase.js')['removeFavorite'];
    var getFavoriteObjects = require('./firebase.js')['getFavoriteObjects'];
    var getImage = require('./firebase.js')['getImage'];
    var initializeMessage = require('./firebase.js')['initializeMessage'];
    var getItemsById = require('./firebase.js')['getItemsById'];
    var getUserInfoProper = require('./firebase.js')['getUserInfoProper'];

    var favoriteTemplate = $('#favorite-template');
    $('#message-popup-confirmation').hide();

    var showFavoritesInSidebar = function(favorites) {
        var str = $('#favorite-template').text();
        var compiled = _.template(str);

        $('#favorite-holder').empty();
        $('#favorite-holder').append(compiled({favorites: favorites}));

        for (var i = 0; i < favorites.length; i += 1) {
            (function (x) {
                getImage(favorites[x]['id'] + '/imageOne', function(url) {
                    let tagToAdd = ".favorite-image img:eq(" + x  + " )";
                    $(tagToAdd).attr({src: url});
                });
            })(i);
        }
    };

    auth.onAuthStateChanged(function(user) {
        if (user && !user.isAnonymous && $(favoriteTemplate).length > 0) {
            getFavoriteObjects(showFavoritesInSidebar);
            $("#find-favorite-logged-in").css('display', 'block');
            $("#find-favorite-logged-out").css('display', 'none');

            // favorite icon highlight/changes
            $('body').on('mouseenter', '.find-result-favorite-image', function() {
                $(this).attr('src', '../media/ic_heart_hover.png');
                $(this).css('opacity', 1);
            }).on('mouseout', '.find-result-favorite-image', function() {
                if (!this.favorited) {
                    $(this).attr('src', '../media/ic_heart.png');
                    $(this).css('opacity', '0.3');
                }
            }).on('click', '.find-result-favorite-image', function() {
                this.favorited = this.favorited || false;
                if (!this.favorited) {
                    $(this).attr('src', '../media/ic_heart_hover.png');
                    addFavoriteToProfile(auth.currentUser.uid, $(this).attr('uid'));
                    getFavoriteObjects(showFavoritesInSidebar);

                } else {
                    $(this).attr('src', '../media/ic_heart.png');
                    removeFavorite($(this).attr('uid'));
                    getFavoriteObjects(showFavoritesInSidebar);
                }
                this.favorited = !this.favorited;
            });
        } else {
            $("#find-favorite-logged-in").css('display', 'none');
            $("#find-favorite-logged-out").css('display', 'block');
        }
    });

    var newSearch = function(currentItems, keywords = [], tags = [], hubs = [], priceRange = []) {
        Promise.resolve(currentItems).then(function(itemList) {

            console.log(hubs);
            console.log(keywords);
            console.log(tags);
            console.log(priceRange);
            var str = $('#find-results-template').text();
            var compiled = _.template(str);
            var imagePaths = [];
            var filteredItemList = {};

            for (var item in itemList) {
                var currentItem = itemList[item];
                var itemID = currentItem['id'];
                var itemDescription = currentItem['description'].toLowerCase();
                var itemTitle = currentItem['title'].toLowerCase();
                var itemPrice = parseInt(currentItem['price'])
                imagePaths.push(itemID);

                if (hubs.length > 0 && !hubs.some(hub => currentItem['hubs'].includes(hub))) {
                    continue;
                }

                if (tags.length > 0 && !tags.some(tag => currentItem['tags'].includes(tag))) {
                    continue;
                }

                if (keywords.length > 0 && (!keywords.some(key => itemTitle.includes(key)) &&
                    !keywords.some(key => itemDescription.includes(key)))) {
                        continue
                }

                if (itemPrice < priceRange[0] || itemPrice > priceRange[1]) {
                    continue;
                }

                filteredItemList[itemID] = currentItem
            }

            $("#find-content-presearch").hide()
            $('#find-results-holder').empty();
            $('#find-results-holder').append(compiled({filteredItemList: filteredItemList}));

            getFavorites(showFavoritesInSearches);

            for (var i = 0; i < imagePaths.length; i += 1) {
                (function (x) {
                    getImage(imagePaths[x] + '/imageOne', function(url) {
                        $("#" + imagePaths[x]).attr({src: url});
                    });
                })(i);
            }
        });
    };

    function updateSliderRange (min, max) {
        slider[0].noUiSlider.updateOptions({
            start: [min, max]
        });
    }

    var showItemsBasedOnHash = function() {
        if (location.hash.length > 0) {
            let hashKeys = location.hash.split('?');
            let key = hashKeys[0].split("=")[1];
            let hubs = hashKeys[1].split("=")[1];
            let tags = hashKeys[2].split("=")[1];

            if (tags.length === 0) {
                tags = [];
            } else {
                tags = tags.split(',');
            }

            if (key.length === 0) {
                key = [];
            } else {
                key = key.split(',');
            }

            if (hubs.length === 0) {
                hubs = [];
            } else {
                hubs = hubs.split(',');
            }

            let priceRange = [parseInt(hashKeys[3].split("=")[1]), parseInt(hashKeys[4].split("=")[1])];
            updateSliderRange(priceRange[0], priceRange[1]);

            $("#find-keywords").val(key.join(" "));
            $('#find-tags').textext()[0].tags().addTags(tags);

            newSearch(getListings(), key, tags, hubs, priceRange);
        }
    }

    var slider = $("#search-slider");
    if (window.location.pathname === "/find/find.html") {
        // Add dropdown hub selector
        $('select').material_select();
        // add slider
        noUiSlider.create(slider[0], {
            start: [1, 500],
            connect: true,
            step: 1,
            tooltips: true,
            format: wNumb({
                decimals: 0,
                thousand: ',',
                prefix: '$',
            }),
            range: {
                'min': 1,
                'max': 3000
            }
        });

        slider[0].noUiSlider.get()

        // add autofill tags
        var findTags = $('#find-tags');
        findTags.textext({plugins : 'tags autocomplete'})
            .bind('getSuggestions', function(e, data){
                var list = [
                        'Table',
                        'Desk',
                        'Computer',
                        'Electronics',
                        'iPhone',
                        'Cell-Phone',
                        'Apple',
                        'Macbook',
                        'Chair',
                        'Leather',
                        'Clothing',
                        'Bedroom',
                        'Bathroom',
                        'Couch',
                        'Kitchen',
                        'Living-Room',
                        'Dinner-Table'
                    ],
                    textext = $(e.target).textext()[0],
                    query = (data ? data.query : '') || '';

                $(this).trigger('setSuggestions',{
                    result : textext.itemManager().filter(list, query) }
                );
        });

        showItemsBasedOnHash();
    }

    var showFavoritesInSearches = function(currentFavorites) {
        $('.find-result-favorite-image').each(function() {
            var  currentImageID = $(this).attr('uid');
            if(currentFavorites && currentFavorites[currentImageID]) {
                $(this).attr('src', '../media/ic_heart_hover.png');
                $(this).css('opacity', 1);
                this.favorited = true;

            }

        });
    };

    $("#find-search-button").click(function () {
        let query = "key=";
        let keywords = $("#find-keywords").val().toLowerCase().trim().split(/\s+/);
        let hubs = $("#find-hubs").val();
        let tags = $('#find-tags').textext()[0].tags()._formData;
        let priceRange = slider[0].noUiSlider.get();

        for (let i = 0; i < priceRange.length; i += 1) {
            priceRange[i] = parseInt(priceRange[i].replace(/[^0-9.]/g, ''));
        }

        for (let i = 0; i < tags.length; i += 1) {
            tags[i] = tags[i].toLowerCase();
        }

        query += `${keywords}?hub=${hubs}?tags=${tags}?priceMin=${priceRange[0]}?priceMax=${priceRange[1]}`;
        location.hash = query;

        newSearch(getListings(), keywords, tags, hubs, priceRange);
    });

    $('.close-button').click(function () {
        $('#message-popup').animate({
            opacity: 0,
            'z-index': -100
        }, 100);
    });

    let newMessageId;
    let newMessageImagePath;

    $('body').on('click', '.card-contact', function () {
        let parentDiv = $(this).parent().parent();
        let imageDiv = parentDiv[0].children[2];
        newMessageImagePath = $(imageDiv)[0].children[0].src;
        newMessageId = $(imageDiv)[0].children[0].id;

        $('#message-popup').css('z-index', '100').animate({
            opacity: 1
        }, 50);
    });

    $('#message-popup-send-button').click(function() {
        let newMessageSellerId;
        let newMessageContent = $($(this).parent()[0].children[2]).val();

        Promise.resolve(getItemsById([newMessageId]))
            .then(function(items) {

                for (let item in items) {
                    newMessageSellerId = items[item].uid;
                }

                return Promise.all([getUserInfoProper(newMessageSellerId),
                    getUserInfoProper(auth.currentUser.uid)]);
            })
            .then(function(results) {
                let currentUser = results[1];
                let otherUser = results[0]
                let myUsername = currentUser['username'];
                let otherUsername = otherUser['username'];
                initializeMessage(auth.currentUser.uid, newMessageSellerId,
                    newMessageId, newMessageImagePath, newMessageContent, otherUsername, myUsername);

                $('#message-popup-content').fadeOut(500);

                setTimeout(function () {
                    $('#message-popup-inner').css({
                        'display': 'flex',
                        'align-items': 'center',
                        'justify-content': 'center'
                    });
                    $('#message-popup-confirmation').fadeIn();
                }, 500);

            })
    });

});


text:
<?php
require_once dirname(__FILE__) . '/CoordinateTransformationLibrary/src/coordinatetransformation/positions/RT90Position.php';
require_once dirname(__FILE__) . '/CoordinateTransformationLibrary/src/coordinatetransformation/positions/SWEREF99Position.php';
require_once dirname(__FILE__) . '/CoordinateTransformationLibrary/src/coordinatetransformation/positions/WGS84Position.php';

$all = json_decode(file_get_contents('coord.json'));
foreach($all as $key => $station)
	{
		if(isset($all[$key]->position->wgs84) == FALSE)
		  {
		  $position = new RT90Position($all[$key]->position->rt90->x, $all[$key]->position->rt90->y);
		  $wgs84 = $position->toWGS84();
		  $all[$key]->position->wgs84 = new stdClass;
		  $all[$key]->position->wgs84->lat = $wgs84->getLatitude();
		  $all[$key]->position->wgs84->long = $wgs84->getLongitude();
		  }
	}
file_put_contents('coord-wgs84.json',json_encode($all));
?>