text:
PdfWriterService
================

###Summary

Simple WCF service that has a few versioned endpoints, including an added method for returning a
very simple PDF file. The service is meant to demonstrate how you would up-version a WCF service
when you make changes to the schema or parameters.

###Credits

* [Atlas](http://nuget.org/packages/Atlas)
  Which made hosting a client and a service application in on project a lot easier.
* [PdfSharp](https://nuget.org/packages/PdfSharp)
  Made writing a very rudamentary PDF file super easy.

###End of File


text:
layout: page
title: Reef Inc. Trade Fair
date: 2016-05-24
author: Stephen Pierce
tags: weekly links, java
status: published
summary: Sed laoreet suscipit lacus, ac suscipit purus ornare nec. Pellentesque.
banner: images/banner/people.jpg
booking:
  startDate: 01/17/2017
  endDate: 01/18/2017
  ctyhocn: EGLPSHX
  groupCode: RITF
published: true
---
Nam leo eros, ultrices sit amet turpis ut, faucibus auctor nibh. Suspendisse tincidunt euismod urna ut ultrices. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas pellentesque fermentum arcu, ac lobortis metus dapibus sed. Morbi cursus aliquet enim et maximus. Proin lacus sapien, convallis quis rhoncus sit amet, consectetur quis libero. Praesent venenatis nec libero ultrices faucibus. Nulla at massa velit. Curabitur suscipit semper sodales.
In hac habitasse platea dictumst. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed vitae efficitur purus, et vestibulum sem. In rutrum volutpat ante non aliquet. Pellentesque sed feugiat neque, id porttitor ex. Vestibulum est libero, consequat sit amet leo eu, semper lobortis ante. Ut interdum commodo massa, sit amet pretium ligula pretium id. Sed molestie lorem felis, at convallis turpis tincidunt ac. Maecenas blandit semper arcu in varius. Sed lacinia magna eu lorem vulputate efficitur. Maecenas sed ornare quam. Mauris ornare varius mi at vulputate.

* Quisque sit amet nulla fringilla, vulputate dui ac, condimentum leo
* Maecenas et lacus id quam scelerisque eleifend
* Cras consequat enim sed justo scelerisque, sit amet pulvinar urna faucibus
* Pellentesque pellentesque nisi in turpis tempus, non sagittis enim porttitor.

Aliquam eu turpis odio. Phasellus malesuada sollicitudin imperdiet. In eget turpis in lacus venenatis efficitur in nec massa. Ut rhoncus ultrices eros vitae ultrices. Sed felis ipsum, feugiat convallis magna quis, dapibus fermentum arcu. Aliquam luctus cursus molestie. Morbi volutpat sapien vitae augue varius, eget viverra justo ornare. Pellentesque sit amet tincidunt lectus. In luctus nunc id blandit ultrices.

redpajama_set_name: RedPajamaGithub


text:
test(function() {
  var wsocket = CreateWebSocket(false, false);
  assert_throws_dom("INVALID_STATE_ERR", function() {
    wsocket.send("Message to send")
  });
}, "Send data on a WebSocket before connection is opened - INVALID_STATE_ERR is returned")


text:
package com.coderevisited.patterns.abstractfactory.impl.bmw;

import com.coderevisited.patterns.abstractfactory.impl.*;

/**
 * User :  Suresh
 * Date :  06/08/15
 * Version : v1
 */
public class BMWCarPartsFactory implements CarPartsFactory {
    @Override
    public Tyre createTyre() {
        return new BMWTyre();
    }

    @Override
    public Engine createEngine() {
        return new BMWEngine();
    }

    @Override
    public Interior createInterior() {
        return new BMWInterior();
    }

    @Override
    public Exterior createExterior() {
        return new BMWExterior();
    }
}


text:
package com.gilmour.model;

public class Activity {

	private String desc;

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}
}


text:
/**
 * @author Vladimir Kozhin
 * @license MIT
 */

'use strict';

const Jii = require('../BaseJii');
const InvalidParamException = require('../exceptions/InvalidParamException');
const _isArray = require('lodash/isArray');
const _each = require('lodash/each');
const _has = require('lodash/has');
const ModelSchema = require('../data/ModelSchema');

class TableSchema extends ModelSchema {

    preInit() {
        /**
         * @var array foreign keys of this table. Each array element is of the following structure:
         *
         * ~~~
         * {
         *  0: 'ForeignTableName',
         *  fk1: 'pk1',  // pk1 is in foreign table
         *  fk2: 'pk2',  // if composite foreign key
         * }
         * ~~~
         */
        this.foreignKeys = null;

        /**
         * @var {string} sequence name for the primary key. Null if no sequence.
         */
        this.sequenceName = null;

        /**
         * @var {string} the full name of this table, which includes the schema name prefix, if any.
         * Note that if the schema name is the same as the [[Schema::defaultSchema|default schema name]],
         * the schema name will not be included.
         */
        this.fullName = null;

        /**
         * @var {string} the name of this table. The schema name is not included. Use [[fullName]] to get the name with schema name prefix.
         */
        this.name = null;

        super.preInit(...arguments);
    }

    /**
     * Manually specifies the primary key for this table.
     * @param {string|string[]} keys the primary key (can be composite)
     * @throws InvalidParamException if the specified key cannot be found in the table.
     */
    fixPrimaryKey(keys) {
        if (!_isArray(keys)) {
            keys = [keys];
        }

        this.primaryKey = keys;

        _each(this.columns, column => {
            column.isPrimaryKey = false;
        });

        _each(keys, key => {
            if (_has(this.columns, key)) {
                this.columns[key].isPrimaryKey = true;
            } else {
                throw new InvalidParamException('Primary key `key` cannot be found in table `' + key + '`.');
            }
        });
    }

}
module.exports = TableSchema;


text:
package org.iq80.leveldb.util;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.function.Function;

import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.iq80.leveldb.util.PureJavaCrc32C.mask;
import static org.iq80.leveldb.util.PureJavaCrc32C.unmask;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;

public class PureJavaCrc32CTest
{
    @Test(dataProvider = "crcs")
    public void testCrc(int expectedCrc, byte[] data)
    {
        assertEquals(expectedCrc, computeCrc(data));
    }

    @DataProvider(name = "crcs")
    public Object[][] data()
    {
        return new Object[][] {
                new Object[] {0x8a9136aa, arrayOf(32, (byte) 0)},
                new Object[] {0x62a8ab43, arrayOf(32, (byte) 0xff)},
                new Object[] {0x46dd794e, arrayOf(32, position -> (byte) position.intValue())},
                new Object[] {0x113fdb5c, arrayOf(32, position -> (byte) (31 - position))},
                new Object[] {0xd9963a56, arrayOf(new int[] {
                        0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                        0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
                        0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00,
                        0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})}
        };
    }

    @Test
    public void testProducesDifferentCrcs()
            throws UnsupportedEncodingException
    {
        assertFalse(computeCrc("a".getBytes(US_ASCII)) == computeCrc("foo".getBytes(US_ASCII)));
    }

    @Test
    public void testComposes()
            throws UnsupportedEncodingException
    {
        PureJavaCrc32C crc = new PureJavaCrc32C();
        crc.update("hello ".getBytes(US_ASCII), 0, 6);
        crc.update("world".getBytes(US_ASCII), 0, 5);

        assertEquals(crc.getIntValue(), computeCrc("hello world".getBytes(US_ASCII)));
    }

    @Test
    public void testMask()
            throws UnsupportedEncodingException
    {
        PureJavaCrc32C crc = new PureJavaCrc32C();
        crc.update("foo".getBytes(US_ASCII), 0, 3);

        assertEquals(crc.getMaskedValue(), mask(crc.getIntValue()));
        assertFalse(crc.getIntValue() == crc.getMaskedValue(), "crc should not match masked crc");
        assertFalse(crc.getIntValue() == mask(crc.getMaskedValue()), "crc should not match double masked crc");
        assertEquals(crc.getIntValue(), unmask(crc.getMaskedValue()));
        assertEquals(crc.getIntValue(), unmask(unmask(mask(crc.getMaskedValue()))));
    }

    private static int computeCrc(byte[] data)
    {
        PureJavaCrc32C crc = new PureJavaCrc32C();
        crc.update(data, 0, data.length);
        return crc.getIntValue();
    }

    private static byte[] arrayOf(int size, byte value)
    {
        byte[] result = new byte[size];
        Arrays.fill(result, value);
        return result;
    }

    @SuppressWarnings("ConstantConditions")
    private static byte[] arrayOf(int size, Function<Integer, Byte> generator)
    {
        byte[] result = new byte[size];
        for (int i = 0; i < result.length; ++i) {
            result[i] = generator.apply(i);
        }

        return result;
    }

    private static byte[] arrayOf(int[] bytes)
    {
        byte[] result = new byte[bytes.length];
        for (int i = 0; i < result.length; ++i) {
            result[i] = (byte) bytes[i];
        }

        return result;
    }
}


text:
RSpec::Matchers.define :contain_datapoint_eeml_for_version do |eeml_version|
  match do |xml|
    hash = datapoint_as_(:hash)
    environment = xml.at_xpath("//xmlns:environment")
    datapoint = environment.at_xpath("//xmlns:data").at_xpath("xmlns:datapoints")
    value = datapoint.at_xpath("xmlns:value")
    value.content.should == hash["value"]
    value.attributes["at"].value.should == hash["at"].iso8601(6)
  end

  failure_message_for_should do |xml|
    "expected #{xml} to describe eeml version #{eeml_version}"
  end
end


text:
__author__ = 'Sukrit'
import pandas as pd
import csv

f = open('../output/both_journal_list.txt', 'r') #reading list of journals present in Aminer and Elesevier
x = f.readlines()
f.close()
bothjs = []

for line in x:
    bothjs.append(line.rstrip()) # list of common journals, removing '\n'

# OUR SNIP
our_SNIP = pd.read_csv('../output/SNIP_all_journals.csv',usecols=[1,3]) # reading SNIP values calculated by US
our_SNIP.sort_values('Jname',inplace = True) #sorting alphabetically

our_SNIP = our_SNIP[ our_SNIP['SNIP'] != 0 ]
our_SNIP2 = pd.DataFrame()
our_SNIP2 = our_SNIP2.append(our_SNIP,ignore_index = True) #resetting index value

our_SNIP = our_SNIP2

oSNIPnames = our_SNIP['Jname']
#print our_SNIP

# SNIP

SNIP = pd.read_csv("../data/journal_SNIP_values.csv")

journals = SNIP['Source Title'] #taking only 'Source Title' column
SNIPlist = []

'''
for jname in oSNIPnames :
    for name in journals :
        if jname == name :
            SNIPlist.append(jname)

'''

SNIP_2 = pd.DataFrame()

#now we corroborate SNIP values.

for name in oSNIPnames :
        SNIP_2 = SNIP_2.append(SNIP[ SNIP['Source Title'] == name ],ignore_index = True) # copy all SNIP/IPP values for which we have citations in Aminer

#print SNIP_2

SNIP_2010 = SNIP_2[['Source Title','2010 SNIP']].copy() # copying 'Source Title' and '2010 SNIP' columns to new df

SNIP_2010 = SNIP_2010.fillna(0) # replacing NaN values with 0

#print SNIP_2010

#print our_SNIP

xarray = []
xarray2 = []
yarray = []
yarray2 = []
names = []

for name in oSNIPnames :
    a = our_SNIP['SNIP'][ our_SNIP['Jname']== name ].values
    b = SNIP_2010['2010 SNIP'][ SNIP_2010['Source Title'] == name ].values
    #if ( a != 0 and a <10 and b != 0 and b < 10 and a > 0.01 ) :
    if ( a != 0 and b!= 0 ) :
        xarray.append(our_SNIP['SNIP'][our_SNIP['Jname']== name ].values)
        yarray.append(SNIP_2010['2010 SNIP'][SNIP_2010['Source Title'] == name ].values)
        names.append(name)

yarray = [float(i) for i in yarray]
for item in yarray :
    yarray2.append(item)

xarray = [float(i) for i in xarray]
for item in xarray :
    xarray2.append(item)

print len(xarray)
print len(yarray)
print len(names)
print "\n\n"
data = [names,xarray,yarray]

with open('../data/SNIP_ourSNIP_ALL.csv','wb') as f:
    out = csv.writer(f, delimiter=',',quoting=csv.QUOTE_ALL)
    out.writerows(zip(*data))


text:
import logging
from OpenSSL import SSL

logger = logging.getLogger(__name__)

METHOD_SSLv3 = 'SSLv3'
METHOD_TLS = 'TLS'
METHOD_TLSv10 = 'TLSv1.0'
METHOD_TLSv11 = 'TLSv1.1'
METHOD_TLSv12 = 'TLSv1.2'

openssl_methods = {
    METHOD_TLS:    SSL.SSLv23_METHOD,                   # protocol negotiation (recommended)
    METHOD_SSLv3:  SSL.SSLv3_METHOD,                    # SSL 3 (NOT recommended)
    METHOD_TLSv10: SSL.TLSv1_METHOD,                    # TLS 1.0 only
    METHOD_TLSv11: getattr(SSL, 'TLSv1_1_METHOD', 5),   # TLS 1.1 only
    METHOD_TLSv12: getattr(SSL, 'TLSv1_2_METHOD', 6),   # TLS 1.2 only
}

# ClientTLSOptions requires a recent-enough version of Twisted
try:

    # taken from twisted/twisted/internet/_sslverify.py
    try:
        from OpenSSL.SSL import SSL_CB_HANDSHAKE_DONE, SSL_CB_HANDSHAKE_START
    except ImportError:
        SSL_CB_HANDSHAKE_START = 0x10
        SSL_CB_HANDSHAKE_DONE = 0x20

    from twisted.internet._sslverify import (ClientTLSOptions,
                                             _maybeSetHostNameIndication,
                                             verifyHostname,
                                             VerificationError)

    class ScrapyClientTLSOptions(ClientTLSOptions):
        # same as Twisted's ClientTLSOptions,
        # except that VerificationError is caught
        # and doesn't close the connection
        def _identityVerifyingInfoCallback(self, connection, where, ret):
            if where & SSL_CB_HANDSHAKE_START:
                _maybeSetHostNameIndication(connection, self._hostnameBytes)
            elif where & SSL_CB_HANDSHAKE_DONE:
                try:
                    verifyHostname(connection, self._hostnameASCII)
                except VerificationError as e:
                    logger.warning(
                        'Remote certificate is not valid for hostname "{}"; {}'.format(
                            self._hostnameASCII, e))

except ImportError:
    # ImportError should not matter for older Twisted versions
    # as the above is not used in the fallback ScrapyClientContextFactory
    pass


text:
package io.github.jonestimd.finance.domain.transaction;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

import io.github.jonestimd.finance.domain.TestDomainUtils;
import io.github.jonestimd.finance.domain.TestSequence;
import io.github.jonestimd.finance.domain.account.Account;
import io.github.jonestimd.finance.domain.asset.Security;

public class TransactionDetailBuilder {
    private Long id;
    private Long relatedId;
    private TransactionCategory category;
    private String memo;
    private BigDecimal amount = BigDecimal.ONE;
    private Security security;
    private BigDecimal shares;
    private Transaction transaction;
    private static Random RANDOM = new Random();

    public TransactionDetailBuilder reset() {
        id = null;
        relatedId = null;
        amount = BigDecimal.ONE;
        security = null;
        return this;
    }

    public TransactionDetailBuilder nextId() {
        this.id = TestSequence.nextId();
        this.relatedId = TestSequence.nextId();
        return this;
    }

    public TransactionDetailBuilder category(String code) {
        this.category = new TransactionCategory(code);
        return this;
    }

    public TransactionDetailBuilder memo(String memo) {
        this.memo = memo;
        return this;
    }

    public TransactionDetailBuilder amount(BigDecimal amount) {
        this.amount = amount;
        return this;
    }

    public TransactionDetailBuilder security(Security security) {
        this.security = security;
        return this;
    }

    public TransactionDetailBuilder shares(BigDecimal shares) {
        this.shares = shares;
        return this;
    }

    public TransactionDetailBuilder onTransaction() {
        transaction = new TransactionBuilder().nextId().get();
        return this;
    }

    public TransactionDetailBuilder onTransaction(Date date) {
        transaction = new TransactionBuilder().nextId().date(date).get();
        return this;
    }

    public TransactionDetail get() {
        return build(id, amount, security, shares);
    }

    private TransactionDetail build(Long detailId, BigDecimal detailAmount, Security security, BigDecimal shares) {
        TransactionDetail transactionDetail = TestDomainUtils.create(TransactionDetail.class, detailId);
        transactionDetail.setMemo(memo);
        transactionDetail.setCategory(category);
        transactionDetail.setAmount(detailAmount);
        transactionDetail.setExchangeAsset(security);
        transactionDetail.setAssetQuantity(shares);
        transactionDetail.setTransaction(transaction);
        return transactionDetail;
    }

    public TransactionDetail persistedTransfer() {
        TransactionDetail transactionDetail = get();
        transactionDetail.setRelatedDetail(build(relatedId, amount.negate(), null, null));
        transactionDetail.getRelatedDetail().setTransaction(new TransactionBuilder().nextId().get());
        return transactionDetail;
    }

    public TransactionDetail newTransfer() {
        return newTransfer(RANDOM.nextLong());
    }

    public TransactionDetail newTransfer(long accountId) {
        return newTransfer(new Account(accountId));
    }

    public TransactionDetail newTransfer(Account account) {
        TransactionDetail transactionDetail = get();
        transactionDetail.setRelatedDetail(build(null, amount.negate(), null, null));
        transactionDetail.getRelatedDetail().setTransaction(new TransactionBuilder().account(account).get());
        return transactionDetail;
    }
}


text:
"""
Important environment variables
-------------------------------

The Pydoop setup looks in a number of default paths for what it
needs.  If necessary, you can override its behaviour or provide an
alternative path by exporting the environment variables below::

  JAVA_HOME, e.g., /opt/sun-jdk
  HADOOP_HOME, e.g., /opt/hadoop

Other relevant environment variables include::

  HADOOP_VERSION, e.g., 2.7.4 (override Hadoop's version string).
"""
from __future__ import print_function

import sys
import time
import os
import glob
import shutil
import subprocess
import itertools
import tempfile

SETUPTOOLS_MIN_VER = '3.3'

import setuptools
from pkg_resources import parse_version  # included in setuptools
print('using setuptools version', setuptools.__version__)
if parse_version(setuptools.__version__) < parse_version(SETUPTOOLS_MIN_VER):
    raise RuntimeError(
        'setuptools minimum required version: %s' % SETUPTOOLS_MIN_VER
    )

# bug: http://bugs.python.org/issue1222585
# workaround: http://stackoverflow.com/questions/8106258
from distutils.sysconfig import get_config_var
_UNWANTED_OPTS = frozenset(['-Wstrict-prototypes'])
os.environ['OPT'] = ' '.join(
    _ for _ in get_config_var('OPT').strip().split() if _ not in _UNWANTED_OPTS
)

from setuptools import setup, find_packages, Extension
from distutils.command.build import build
from distutils.command.build_ext import build_ext
from distutils.command.clean import clean
from distutils.errors import DistutilsSetupError, CompileError
from distutils import log

import pydoop
import pydoop.utils.jvm as jvm

JAVA_HOME = jvm.get_java_home()
JVM_LIB_PATH, JVM_LIB_NAME = jvm.get_jvm_lib_path_and_name(JAVA_HOME)

HADOOP_HOME = pydoop.hadoop_home()
HADOOP_VERSION_INFO = pydoop.hadoop_version_info()

VERSION_FN = "VERSION"
GIT_REV_FN = "GIT_REV"
EXTRA_COMPILE_ARGS = ["-Wno-write-strings"]  # http://bugs.python.org/issue6952

# properties file.  Since the source is in the root dir, filename = basename
PROP_FN = PROP_BN = pydoop.__propfile_basename__

CONSOLE_SCRIPTS = ['pydoop = pydoop.app.main:main']
if sys.version_info[0] == 3:
    CONSOLE_SCRIPTS.append('pydoop3 = pydoop.app.main:main')
else:
    CONSOLE_SCRIPTS.append('pydoop2 = pydoop.app.main:main')

# ---------
# UTILITIES
# ---------

def rm_rf(path, dry_run=False):
    """
    Remove a file or directory tree.

    Won't throw an exception, even if the removal fails.
    """
    log.info("removing %s" % path)
    if dry_run:
        return
    try:
        if os.path.isdir(path) and not os.path.islink(path):
            shutil.rmtree(path)
        else:
            os.remove(path)
    except OSError:
        pass

def mtime(fn):
    return os.stat(fn).st_mtime

def must_generate(target, prerequisites):
    try:
        return max(mtime(p) for p in prerequisites) > mtime(target)
    except OSError:
        return True

def get_version_string():
    try:
        with open(VERSION_FN) as f:
            return f.read().strip()
    except IOError:
        raise DistutilsSetupError("failed to read version info")

def write_config(filename="pydoop/config.py"):
    prereq = PROP_FN
    if must_generate(filename, [prereq]):
        props = pydoop.read_properties(PROP_FN)
        with open(filename, "w") as fo:
            fo.write("# GENERATED BY setup.py\n")
            for k in sorted(props):
                fo.write("%s = %r\n" % (k, props[k]))

def get_git_rev():
    if os.path.isfile(GIT_REV_FN):
        with open(GIT_REV_FN) as f:
            return f.read().strip()
    try:
        return subprocess.check_output(
            ['git', 'rev-parse', 'HEAD'],
            universal_newlines=True
        ).rstrip('\n')
    except (OSError, subprocess.CalledProcessError):
        return None

def write_version(filename="pydoop/version.py"):
    if must_generate(filename, [VERSION_FN, GIT_REV_FN]):
        with open(filename, "w") as f:
            f.write("# GENERATED BY setup.py\n")
            f.write("version = %r\n" % (get_version_string(),))
            f.write("git_rev = %r\n" % (get_git_rev(),))

EXTENSION_MODULES = [
    Extension(
        'pydoop.native_core_hdfs',
        include_dirs=jvm.get_include_dirs() + [
            'src/libhdfs',
            'src/libhdfs/include',
            'src/libhdfs/os/posix',
        ],
        libraries=jvm.get_libraries(),
        library_dirs=[JAVA_HOME + "/Libraries", JVM_LIB_PATH],
        sources=list(itertools.chain(
            glob.iglob('src/libhdfs/*.c'),
            glob.iglob('src/libhdfs/common/*.c'),
            glob.iglob('src/libhdfs/os/posix/*.c'),
            glob.iglob('src/native_core_hdfs/*.cc')
        )),
        define_macros=jvm.get_macros(),
        extra_compile_args=EXTRA_COMPILE_ARGS,
        extra_link_args=['-Wl,-rpath,%s' % JVM_LIB_PATH]
    ),
    Extension(
        'pydoop.sercore',
        sources=[os.path.join('src/serialize', x) for x in [
            'sermodule.cc', 'flow.cc', 'command.cc',
            'serialization.cc', 'SerialUtils.cc', 'StringUtils.cc'
        ]],
        undef_macros=["NDEBUG"],  # FIXME
        extra_compile_args=EXTRA_COMPILE_ARGS + ["-O3"]
    )
]

# ------------
# BUILD ENGINE
# ------------

class JavaLib(object):

    def __init__(self):
        self.jar_name = pydoop.jar_name()
        self.classpath = pydoop.hadoop_classpath()
        self.java_files = glob.glob(
            "src/it/crs4/pydoop/mapreduce/pipes/*.java"
        ) + ["src/it/crs4/pydoop/NoSeparatorTextOutputFormat.java"]
        self.dependencies = glob.glob('lib/*.jar')
        self.properties = [(
            os.path.join("it/crs4/pydoop/mapreduce/pipes", PROP_BN),
            PROP_FN
        )]

class JavaBuilder(object):

    def __init__(self, build_temp, build_lib):
        self.build_temp = build_temp
        self.build_lib = build_lib
        self.java_libs = [JavaLib()]

    def run(self):
        log.info("hadoop_home: %r" % (HADOOP_HOME,))
        log.info("hadoop_version: '%s'" % HADOOP_VERSION_INFO)
        log.info("java_home: %r" % (JAVA_HOME,))
        for jlib in self.java_libs:
            self.__build_java_lib(jlib)

    def __build_java_lib(self, jlib):
        package_path = os.path.join(self.build_lib, "pydoop")
        compile_cmd = "javac"
        if jlib.classpath:
            classpath = [jlib.classpath]
            for src in jlib.dependencies:
                dest = os.path.join(package_path, os.path.basename(src))
                shutil.copyfile(src, dest)
                classpath.append(dest)
            compile_cmd += " -classpath %s" % (':'.join(classpath))
        else:
            log.warn(
                "WARNING: could not set classpath, java code may not compile"
            )
        class_dir = os.path.join(
            self.build_temp, "pipes"
        )
        jar_path = os.path.join(package_path, jlib.jar_name)
        if not os.path.exists(class_dir):
            os.mkdir(class_dir)
        compile_cmd += " -d '%s'" % class_dir
        log.info("Compiling Java classes")
        for f in jlib.java_files:
            compile_cmd += " %s" % f
        ret = os.system(compile_cmd)
        if ret:
            raise DistutilsSetupError(
                "Error compiling java component.  Command: %s" % compile_cmd
            )
        log.info("Copying properties file")
        for p in jlib.properties:
            prop_file_dest = os.path.join(class_dir, p[0])
            shutil.copyfile(p[1], prop_file_dest)
        log.info("Making Jar: %s", jar_path)
        package_cmd = "jar -cf %(jar_path)s -C %(class_dir)s ./it" % {
            'jar_path': jar_path, 'class_dir': class_dir
        }
        log.info("Packaging Java classes")
        log.info("Command: %s", package_cmd)
        ret = os.system(package_cmd)
        if ret:
            raise DistutilsSetupError(
                "Error packaging java component.  Command: %s" % package_cmd
            )

class BuildPydoopExt(build_ext):

    def __have_better_tls(self):
        log.info("checking for TLS support")
        test_code = "int main(void) { static __thread int i = 0; return i; }"
        wd = tempfile.mkdtemp(prefix="pydoop_")
        test_src = os.path.join(wd, "temp.c")
        with open(test_src, "w") as f:
            f.write(test_code)
        try:
            self.compiler.compile([test_src], output_dir=wd)
        except CompileError:
            ret = False
        else:
            ret = True
        shutil.rmtree(wd)
        return ret

    # called for each extension, after compiler has been set up
    def build_extension(self, ext):
        if ext.name == "pydoop.native_core_hdfs":
            if self.__have_better_tls():
                ext.define_macros.append(("HAVE_BETTER_TLS", None))
            try:
                # too many warnings in libhdfs
                self.compiler.compiler_so.remove("-Wsign-compare")
            except (AttributeError, ValueError):
                pass
        build_ext.build_extension(self, ext)

class BuildPydoop(build):

    def build_java(self):
        jb = JavaBuilder(self.build_temp, self.build_lib)
        jb.run()

    def create_tmp(self):
        if not os.path.exists(self.build_temp):
            os.mkdir(self.build_temp)
        if not os.path.exists(self.build_lib):
            os.mkdir(self.build_lib)

    def clean_up(self):
        shutil.rmtree(self.build_temp)

    def run(self):
        if HADOOP_VERSION_INFO.tuple < (2,):
            raise RuntimeError('Hadoop v1 is not supported')
        # `is_local` requires running the local hadoop executable.
        # Don't move this call into other methods of the class that
        # may be called while executing other commands (e.g., clean)
        if HADOOP_VERSION_INFO.is_local():
            raise pydoop.LocalModeNotSupported()
        write_version()
        write_config()
        shutil.copyfile(PROP_FN, os.path.join("pydoop", PROP_BN))
        build.run(self)
        try:
            self.create_tmp()
            self.build_java()
        finally:
            # On NFS, if we clean up right away we have issues with
            # NFS handles being still in the directory trees to be
            # deleted.  So, we sleep a bit and then delete
            time.sleep(0.5)
            self.clean_up()
        log.info("Build finished")

class Clean(clean):

    def run(self):
        clean.run(self)
        garbage_list = [
            "build",
            "dist",
            "pydoop.egg-info",
            "pydoop/config.py",
            "pydoop/version.py",
            "examples/avro/java/target",
            "examples/avro/java/project/project",
            "examples/avro/java/project/target",
            "examples/avro/py/to_from_avro",
        ]
        for p in garbage_list:
            rm_rf(p, self.dry_run)
        self._clean_examples()

    @staticmethod
    def _clean_examples():
        for root, _, files in os.walk('examples'):
            if 'Makefile' in files:
                subprocess.call(["make", "-C", root, "clean"])

setup(
    name="pydoop",
    version=get_version_string(),
    description=pydoop.__doc__.strip().splitlines()[0],
    long_description=pydoop.__doc__.lstrip(),
    author=pydoop.__author__,
    author_email=pydoop.__author_email__,
    url=pydoop.__url__,
    download_url="https://pypi.python.org/pypi/pydoop",
    install_requires=['setuptools>=%s' % SETUPTOOLS_MIN_VER],
    extras_require={
        'avro': [
            'avro>=1.7.4;python_version<"3"',
            'avro-python3>=1.7.4;python_version>="3"',
        ],
    },
    packages=find_packages(exclude=['test', 'test.*']),
    package_data={"pydoop": [PROP_FN]},
    cmdclass={
        "build": BuildPydoop,
        "build_ext": BuildPydoopExt,
        "clean": Clean
    },
    entry_points={'console_scripts': CONSOLE_SCRIPTS},
    platforms=["Linux"],
    ext_modules=EXTENSION_MODULES,
    license="Apache-2.0",
    keywords=["hadoop", "mapreduce"],
    classifiers=[
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3.5",
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: POSIX :: Linux",
        "Topic :: Software Development :: Libraries :: Application Frameworks",
        "Intended Audience :: Developers",
    ],
    data_files=[
        ('config', ['README.md']),
    ],
    zip_safe=False,
)


text:
var global_registers_writable = 0;
describe("Global registers", function() {
  describe('writable', function() {
    it("should reject target", function() {
      var global = Function('return this;')();
      expect(global_registers_writable).toBe(0);
      expect(global.global_registers_writable).toBe(0);
      Object.defineProperty(global, 'global_registers_writable', {
        writable: false
      });
      global_registers_writable = 1;
      expect(global_registers_writable).toBe(0);
    });
  });
});


text:
<?xml version="1.0" ?>

<project name="libphonenumber" default="compile">
  <property name="libphonenumber.src.dir" value="libphonenumber/src"/>
  <property name="libphonenumber.test.dir" value="libphonenumber/test"/>
  <property name="geocoder.src.dir" value="geocoder/src"/>
  <property name="geocoder.test.dir" value="geocoder/test"/>
  <property name="build.dir" value="build"/>
  <property name="classes.dir" value="${build.dir}/classes"/>
  <property name="jar.dir" value="${build.dir}/jar"/>
  <property name="lib.dir" value="lib"/>
  <property name="report.dir" value="${build.dir}/junitreport"/>
  <property name="resources.dir" value="../resources"/>
  <property name="javascript.dir" value="../javascript"/>
  <property name="build.tools.jar"
      value="../tools/java/java-build/target/java-build-1.0-SNAPSHOT-jar-with-dependencies.jar"/>

  <path id="classpath">
    <fileset dir="${lib.dir}" includes="**/*.jar"/>
  </path>
  <path id="test.classpath">
    <pathelement location="${classes.dir}"/>
    <pathelement location="${lib.dir}/junit/junit-4.8.1.jar"/>
    <pathelement location="${jar.dir}/${ant.project.name}-test.jar"/>
    <fileset dir="${lib.dir}">
      <include name="**/*.jar"/>
    </fileset>
  </path>

  <target name="build-phone-metadata">
    <exec executable="java">
      <arg value="-jar" />
      <arg value="${build.tools.jar}"/>
      <arg value="BuildMetadataProtoFromXml"/>
      <arg value="--input-file=${resources.dir}/PhoneNumberMetadata.xml"/>
      <arg value="--output-dir=${libphonenumber.src.dir}/com/google/i18n/phonenumbers"/>
      <arg value="--data-prefix=data/PhoneNumberMetadataProto"/>
      <arg value="--mapping-class=CountryCodeToRegionCodeMap"/>
      <arg value="--copyright=2010"/>
      <arg value="--lite-build=false"/>
    </exec>
  </target>

  <target name="build-short-metadata">
    <exec executable="java">
      <arg value="-jar" />
      <arg value="${build.tools.jar}"/>
      <arg value="BuildMetadataProtoFromXml"/>
      <arg value="--input-file=${resources.dir}/ShortNumberMetadata.xml"/>
      <arg value="--output-dir=${libphonenumber.src.dir}/com/google/i18n/phonenumbers"/>
      <arg value="--data-prefix=data/ShortNumberMetadataProto"/>
      <arg value="--mapping-class=ShortNumbersRegionCodeSet"/>
      <arg value="--copyright=2013"/>
      <arg value="--lite-build=false"/>
    </exec>
  </target>

  <target name="build-test-metadata">
    <exec executable="java">
      <arg value="-jar" />
      <arg value="${build.tools.jar}"/>
      <arg value="BuildMetadataProtoFromXml"/>
      <arg value="--input-file=${resources.dir}/PhoneNumberMetadataForTesting.xml"/>
      <arg value="--output-dir=${libphonenumber.test.dir}/com/google/i18n/phonenumbers"/>
      <arg value="--data-prefix=data/PhoneNumberMetadataProtoForTesting"/>
      <arg value="--mapping-class=CountryCodeToRegionCodeMapForTesting"/>
      <arg value="--copyright=2010"/>
      <arg value="--lite-build=false"/>
    </exec>
  </target>

  <target name="build-alternate-metadata">
    <exec executable="java">
      <arg value="-jar" />
      <arg value="${build.tools.jar}"/>
      <arg value="BuildMetadataProtoFromXml"/>
      <arg value="--input-file=${resources.dir}/PhoneNumberAlternateFormats.xml"/>
      <arg value="--output-dir=${libphonenumber.src.dir}/com/google/i18n/phonenumbers"/>
      <arg value="--data-prefix=data/PhoneNumberAlternateFormatsProto"/>
      <arg value="--mapping-class=AlternateFormatsCountryCodeSet"/>
      <arg value="--copyright=2012"/>
      <arg value="--lite-build=false"/>
    </exec>
  </target>

  <target name="build-geo-data">
    <exec executable="java">
      <arg value="-jar" />
      <arg value="${build.tools.jar}"/>
      <arg value="GenerateAreaCodeData"/>
      <arg value="${resources.dir}/geocoding/"/>
      <arg value="geocoder/src/com/google/i18n/phonenumbers/geocoding/data"/>
    </exec>
  </target>

  <target name="build-geo-test-data">
    <exec executable="java">
      <arg value="-jar" />
      <arg value="${build.tools.jar}"/>
      <arg value="GenerateAreaCodeData"/>
      <arg value="${resources.dir}/test/geocoding/"/>
      <arg value="geocoder/test/com/google/i18n/phonenumbers/geocoding/testing_data"/>
    </exec>
  </target>

  <target name="build-js-metadata">
    <exec executable="java">
      <arg value="-jar" />
      <arg value="${build.tools.jar}"/>
      <arg value="BuildMetadataJsonFromXml"/>
      <arg value="${resources.dir}/PhoneNumberMetadata.xml"/>
      <arg value="${javascript.dir}/i18n/phonenumbers/metadata.js"/>
    </exec>
    <exec executable="java">
      <arg value="-jar" />
      <arg value="${build.tools.jar}"/>
      <arg value="BuildMetadataJsonFromXml"/>
      <arg value="${resources.dir}/PhoneNumberMetadata.xml"/>
      <arg value="${javascript.dir}/i18n/phonenumbers/metadatalite.js"/>
      <arg value="true"/> <!-- Lite metadata. -->
    </exec>
    <exec executable="java">
      <arg value="-jar" />
      <arg value="${build.tools.jar}"/>
      <arg value="BuildMetadataJsonFromXml"/>
      <arg value="${resources.dir}/PhoneNumberMetadataForTesting.xml"/>
      <arg value="${javascript.dir}/i18n/phonenumbers/metadatafortesting.js"/>
    </exec>
  </target>

  <target name="compile" description="Compile Java source."
          depends="build-phone-metadata,build-short-metadata,build-alternate-metadata,build-geo-data">
    <mkdir dir="${classes.dir}"/>
    <javac srcdir="${libphonenumber.src.dir};${geocoder.src.dir}"
           destdir="${classes.dir}" classpathref="classpath" includeAntRuntime="false"/>
    <javac srcdir="${libphonenumber.test.dir};${geocoder.test.dir}"
           destdir="${classes.dir}" classpathref="classpath" debug="on"
           includeAntRuntime="false"/>
  </target>

  <target name="jar" depends="compile">
    <mkdir dir="${jar.dir}"/>
    <jar destfile="${jar.dir}/${ant.project.name}.jar">
      <fileset dir="${classes.dir}">
        <include name="**/*.class"/>
        <exclude name="**/*Test*"/>
        <exclude name="**/BuildMetadata*"/>
        <exclude name="**/geocoding/*"/>
      </fileset>
      <fileset dir="${libphonenumber.src.dir}">
        <include name="**/PhoneNumberMetadataProto*"/>
        <include name="**/PhoneNumberAlternateFormatsProto*"/>
        <include name="**/ShortNumberMetadataProto*"/>
      </fileset>
    </jar>
    <jar destfile="${jar.dir}/offline-geocoder.jar">
      <fileset dir="${classes.dir}">
        <include name="**/geocoding/*.class"/>
        <exclude name="**/*Test*"/>
        <exclude name="**/geocoding/GenerateAreaCodeData*"/>
      </fileset>
      <fileset dir="${geocoder.src.dir}">
        <include name="**/geocoding/data/*"/>
      </fileset>
    </jar>
  </target>

  <target name="test-jar"
          depends="compile,build-test-metadata,build-geo-test-data">
    <mkdir dir="${jar.dir}"/>
    <jar destfile="${jar.dir}/${ant.project.name}-test.jar">
      <fileset dir="${classes.dir}">
        <include name="**/*.class"/>
        <exclude name="**/*Test*"/>
      </fileset>
      <fileset dir="${libphonenumber.src.dir}">
        <include name="**/PhoneNumberMetadataProto*"/>
        <include name="**/PhoneNumberAlternateFormatsProto*"/>
        <include name="**/ShortNumberMetadataProto*"/>
      </fileset>
      <fileset dir="${libphonenumber.test.dir}">
        <include name="**/PhoneNumberMetadataProtoForTesting*"/>
      </fileset>
      <fileset dir="${geocoder.test.dir}">
        <include name="**/geocoding/testing_data/*"/>
      </fileset>
    </jar>
  </target>

  <target name="junit" depends="test-jar">
    <mkdir dir="${report.dir}"/>
    <junit printsummary="yes"
        failureProperty="test.failed" errorProperty="test.failed">
      <classpath refid="test.classpath"/>
      <formatter type="xml"/>
      <batchtest fork="no" todir="${report.dir}">
        <fileset dir="${libphonenumber.test.dir}" includes="**/*Test.java"/>
      </batchtest>
      <batchtest fork="no" todir="${report.dir}">
        <fileset dir="${geocoder.test.dir}" includes="**/*Test.java"/>
      </batchtest>
    </junit>
    <fail message="Tests failed. Run 'ant junitreport' for more info."
        if="test.failed"/>
  </target>

  <target name="junitreport">
    <junitreport todir="${report.dir}">
      <fileset dir="${report.dir}" includes="TEST-*.xml"/>
        <report todir="${report.dir}"/>
    </junitreport>
  </target>

  <target name="testname" unless="test">
    <fail message="You must run this target with -Dtest=TestName"/>
  </target>

  <target name="test" depends="test-jar, testname">
    <junit printsummary="withOutAndErr">
      <classpath refid="test.classpath"/>
      <formatter type="plain" usefile="false"/>
      <batchtest fork="no">
        <fileset dir="${libphonenumber.test.dir}" includes="**/*${test}.java"/>
        <fileset dir="${geocoder.test.dir}" includes="**/*${test}.java"/>
      </batchtest>
    </junit>
  </target>

  <target name="clean" description="Remove generated files.">
    <delete dir="${build.dir}"/>
  </target>

  <target name="clean-build" depends="clean,jar"/>
</project>


text:
IMPLEMENT_CONOBJECT( VSpawnSphereGroup );
//-----------------------------------------------------------------------------

VSpawnSphereGroup::VSpawnSphereGroup( void )
{
    setLabel( "SpawnSphereGroup" );
};


text:
package org.wso2.siddhi.core.util.parser;

import org.wso2.siddhi.core.aggregation.AggregationRuntime;
import org.wso2.siddhi.core.config.SiddhiAppContext;
import org.wso2.siddhi.core.event.state.MetaStateEvent;
import org.wso2.siddhi.core.event.state.populater.StateEventPopulatorFactory;
import org.wso2.siddhi.core.event.stream.MetaStreamEvent;
import org.wso2.siddhi.core.event.stream.MetaStreamEvent.EventType;
import org.wso2.siddhi.core.executor.VariableExpressionExecutor;
import org.wso2.siddhi.core.query.QueryRuntime;
import org.wso2.siddhi.core.query.input.stream.StreamRuntime;
import org.wso2.siddhi.core.query.input.stream.join.JoinStreamRuntime;
import org.wso2.siddhi.core.query.input.stream.single.SingleStreamRuntime;
import org.wso2.siddhi.core.query.output.callback.OutputCallback;
import org.wso2.siddhi.core.query.output.ratelimit.OutputRateLimiter;
import org.wso2.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter;
import org.wso2.siddhi.core.query.selector.QuerySelector;
import org.wso2.siddhi.core.table.Table;
import org.wso2.siddhi.core.util.ExceptionUtil;
import org.wso2.siddhi.core.util.SiddhiConstants;
import org.wso2.siddhi.core.util.lock.LockSynchronizer;
import org.wso2.siddhi.core.util.lock.LockWrapper;
import org.wso2.siddhi.core.util.parser.helper.QueryParserHelper;
import org.wso2.siddhi.core.util.statistics.LatencyTracker;
import org.wso2.siddhi.core.window.Window;
import org.wso2.siddhi.query.api.annotation.Element;
import org.wso2.siddhi.query.api.definition.AbstractDefinition;
import org.wso2.siddhi.query.api.exception.DuplicateDefinitionException;
import org.wso2.siddhi.query.api.execution.query.Query;
import org.wso2.siddhi.query.api.execution.query.input.handler.StreamHandler;
import org.wso2.siddhi.query.api.execution.query.input.stream.JoinInputStream;
import org.wso2.siddhi.query.api.execution.query.input.stream.SingleInputStream;
import org.wso2.siddhi.query.api.execution.query.output.stream.OutputStream;
import org.wso2.siddhi.query.api.util.AnnotationHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Class to parse {@link QueryRuntime}
 */
public class QueryParser {

    /**
     * Parse a query and return corresponding QueryRuntime.
     *
     * @param query                    query to be parsed.
     * @param siddhiAppContext         associated Siddhi app context.
     * @param streamDefinitionMap      keyvalue containing user given stream definitions.
     * @param tableDefinitionMap       keyvalue containing table definitions.
     * @param windowDefinitionMap      keyvalue containing window definition map.
     * @param aggregationDefinitionMap keyvalue containing aggregation definition map.
     * @param tableMap                 keyvalue containing event tables.
     * @param aggregationMap           keyvalue containing aggrigation runtimes.
     * @param windowMap                keyvalue containing event window map.
     * @param lockSynchronizer         Lock synchronizer for sync the lock across queries.
     * @param queryIndex               query index to identify unknown query by number
     * @return queryRuntime
     */
    public static QueryRuntime parse(Query query, SiddhiAppContext siddhiAppContext,
                                     Map<String, AbstractDefinition> streamDefinitionMap,
                                     Map<String, AbstractDefinition> tableDefinitionMap,
                                     Map<String, AbstractDefinition> windowDefinitionMap,
                                     Map<String, AbstractDefinition> aggregationDefinitionMap,
                                     Map<String, Table> tableMap,
                                     Map<String, AggregationRuntime> aggregationMap, Map<String, Window> windowMap,
                                     LockSynchronizer lockSynchronizer,
                                     String queryIndex) {
        List<VariableExpressionExecutor> executors = new ArrayList<VariableExpressionExecutor>();
        QueryRuntime queryRuntime;
        Element nameElement = null;
        LatencyTracker latencyTracker = null;
        LockWrapper lockWrapper = null;
        try {
            nameElement = AnnotationHelper.getAnnotationElement("info", "name",
                    query.getAnnotations());
            String queryName = null;
            if (nameElement != null) {
                queryName = nameElement.getValue();
            } else {
                queryName = "query_" + queryIndex + "_" + UUID.randomUUID().toString();
            }
            latencyTracker = QueryParserHelper.getLatencyTracker(siddhiAppContext, queryName,
                    SiddhiConstants.METRIC_INFIX_QUERIES);
            OutputStream.OutputEventType outputEventType = query.getOutputStream().getOutputEventType();
            boolean outputExpectsExpiredEvents = false;
            if (outputEventType != OutputStream.OutputEventType.CURRENT_EVENTS) {
                outputExpectsExpiredEvents = true;
            }
            StreamRuntime streamRuntime = InputStreamParser.parse(query.getInputStream(),
                    siddhiAppContext, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap,
                    aggregationDefinitionMap, tableMap, windowMap, aggregationMap, executors, latencyTracker,
                    outputExpectsExpiredEvents, queryName);
            QuerySelector selector = SelectorParser.parse(query.getSelector(), query.getOutputStream(),
                    siddhiAppContext, streamRuntime.getMetaComplexEvent(), tableMap, executors, queryName);
            boolean isWindow = query.getInputStream() instanceof JoinInputStream;
            if (!isWindow && query.getInputStream() instanceof SingleInputStream) {
                for (StreamHandler streamHandler : ((SingleInputStream) query.getInputStream()).getStreamHandlers()) {
                    if (streamHandler instanceof org.wso2.siddhi.query.api.execution.query.input.handler.Window) {
                        isWindow = true;
                        break;
                    }
                }
            }

            Element synchronizedElement = AnnotationHelper.getAnnotationElement("synchronized",
                    null, query.getAnnotations());
            if (synchronizedElement != null) {
                if (!("false".equalsIgnoreCase(synchronizedElement.getValue()))) {
                    lockWrapper = new LockWrapper(""); // Query LockWrapper does not need a unique
                    // id since it will
                    // not be passed to the LockSynchronizer.
                    lockWrapper.setLock(new ReentrantLock());   // LockWrapper does not have a default lock
                }
            } else {
                if (isWindow || !(streamRuntime instanceof SingleStreamRuntime)) {
                    if (streamRuntime instanceof JoinStreamRuntime) {
                        // If at least one Window is involved in the join, use the LockWrapper of that window
                        // for the query as well.
                        // If join is between two EventWindows, sync the locks of the LockWrapper of those windows
                        // and use either of them for query.
                        MetaStateEvent metaStateEvent = (MetaStateEvent) streamRuntime.getMetaComplexEvent();
                        MetaStreamEvent[] metaStreamEvents = metaStateEvent.getMetaStreamEvents();

                        if (metaStreamEvents[0].getEventType() == EventType.WINDOW &&
                                metaStreamEvents[1].getEventType() == EventType.WINDOW) {
                            LockWrapper leftLockWrapper = windowMap.get(metaStreamEvents[0]
                                    .getLastInputDefinition().getId()).getLock();
                            LockWrapper rightLockWrapper = windowMap.get(metaStreamEvents[1]
                                    .getLastInputDefinition().getId()).getLock();

                            if (!leftLockWrapper.equals(rightLockWrapper)) {
                                // Sync the lock across both wrappers
                                lockSynchronizer.sync(leftLockWrapper, rightLockWrapper);
                            }
                            // Can use either leftLockWrapper or rightLockWrapper since both of them will hold the
                            // same lock internally
                            // If either of their lock is updated later, the other lock also will be update by the
                            // LockSynchronizer.
                            lockWrapper = leftLockWrapper;
                        } else if (metaStreamEvents[0].getEventType() == EventType.WINDOW) {
                            // Share the same wrapper as the query lock wrapper
                            lockWrapper = windowMap.get(metaStreamEvents[0].getLastInputDefinition().getId())
                                    .getLock();
                        } else if (metaStreamEvents[1].getEventType() == EventType.WINDOW) {
                            // Share the same wrapper as the query lock wrapper
                            lockWrapper = windowMap.get(metaStreamEvents[1].getLastInputDefinition().getId())
                                    .getLock();
                        } else {
                            // Join does not contain any Window
                            lockWrapper = new LockWrapper("");  // Query LockWrapper does not need a unique
                            // id since
                            // it will not be passed to the LockSynchronizer.
                            lockWrapper.setLock(new ReentrantLock());   // LockWrapper does not have a default lock
                        }

                    } else {
                        lockWrapper = new LockWrapper("");
                        lockWrapper.setLock(new ReentrantLock());
                    }
                }
            }

            OutputRateLimiter outputRateLimiter = OutputParser.constructOutputRateLimiter(
                    query.getOutputStream().getId(), query.getOutputRate(),
                    query.getSelector().getGroupByList().size() != 0, isWindow,
                    siddhiAppContext.getScheduledExecutorService(), siddhiAppContext, queryName);
            if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
                selector.setBatchingEnabled(false);
            }
            siddhiAppContext.addEternalReferencedHolder(outputRateLimiter);

            OutputCallback outputCallback = OutputParser.constructOutputCallback(query.getOutputStream(),
                    streamRuntime.getMetaComplexEvent().getOutputStreamDefinition(), tableMap, windowMap,
                    siddhiAppContext, !(streamRuntime instanceof SingleStreamRuntime), queryName);

            QueryParserHelper.reduceMetaComplexEvent(streamRuntime.getMetaComplexEvent());
            QueryParserHelper.updateVariablePosition(streamRuntime.getMetaComplexEvent(), executors);
            QueryParserHelper.initStreamRuntime(streamRuntime, streamRuntime.getMetaComplexEvent(), lockWrapper,
                    queryName);
            selector.setEventPopulator(StateEventPopulatorFactory.constructEventPopulator(streamRuntime
                    .getMetaComplexEvent()));
            queryRuntime = new QueryRuntime(query, siddhiAppContext, streamRuntime, selector, outputRateLimiter,
                    outputCallback, streamRuntime.getMetaComplexEvent(), lockWrapper != null, queryName);

            if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
                selector.setBatchingEnabled(false);
                ((WrappedSnapshotOutputRateLimiter) outputRateLimiter)
                        .init(streamRuntime.getMetaComplexEvent().getOutputStreamDefinition().getAttributeList().size(),
                                selector.getAttributeProcessorList(), streamRuntime.getMetaComplexEvent());
            }
            outputRateLimiter.init(siddhiAppContext, lockWrapper, queryName);

        } catch (DuplicateDefinitionException e) {
            if (nameElement != null) {
                throw new DuplicateDefinitionException(e.getMessageWithOutContext() + ", when creating query " +
                        nameElement.getValue(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(),
                        siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
            } else {
                throw new DuplicateDefinitionException(e.getMessage(), e, e.getQueryContextStartIndex(),
                        e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
            }
        } catch (Throwable t) {
            ExceptionUtil.populateQueryContext(t, query, siddhiAppContext);
            throw t;
        }
        return queryRuntime;
    }

}


text:
class Staff::ProgramsController < Staff::Base
  def index
    @programs = Program.listing.page(params[:page])
  end

  def show
    @program = Program.listing.find(params[:id])
  end

  def new
    @program_form = Staff::ProgramForm.new
  end

  def edit
    @program_form = Staff::ProgramForm.new(Program.find(params[:id]))
  end

  def create
    @program_form = Staff::ProgramForm.new
    @program_form.assign_attributes(params[:form])
    @program_form.program.registrant = current_staff_member
    if @program_form.save
      flash.notice = 'プログラムを登録しました。'
      redirect_to action: 'index'
    else
      flash.now.alert = '入力に誤りがあります。'
      render action: 'new'
    end
  end

  def update
    @program_form = Staff::ProgramForm.new(Program.find(params[:id]))
    @program_form.assign_attributes(params[:form])
    if @program_form.save
      flash.notice = 'プログラムを更新しました。'
      redirect_to action: 'index'
    else
      flash.now.alert = '入力に誤りがあります。'
      render action: 'edit'
    end
  end

  def destroy
    program = Program.find(params[:id])
    if program.deletable?
      program.destroy!
      flash.notice = 'プログラムを削除しました。'
    else
      flash.alert = 'このプログラムは申し込みがあるため、削除できません。'
    end
    redirect_to :staff_programs
  end

  def entries
    entries_form = Staff::EntriesForm.new(Program.find(params[:id]))
    entries_form.assign_attributes(params[:form])
    entries_form.save
    flash.notice = 'プログラム申し込みのフラグを更新しました。'
    redirect_to :staff_programs
  end
end


text:
#include "util/sexpr/option_declarations.h"
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "kernel/find_fn.h"
#include "kernel/inductive/inductive.h"
#include "library/util.h"
#include "library/trace.h"
#include "library/app_builder.h"
#include "library/private.h"
#include "library/constants.h"
#include "library/annotation.h"
#include "library/inverse.h"
#include "library/replace_visitor.h"
#include "library/aux_definition.h"
#include "library/scope_pos_info_provider.h"
#include "library/compiler/vm_compiler.h"
#include "library/tactic/defeq_simplifier.h"
#include "library/equations_compiler/equations.h"
#include "library/equations_compiler/util.h"

#ifndef LEAN_DEFAULT_EQN_COMPILER_DSIMP
#define LEAN_DEFAULT_EQN_COMPILER_DSIMP false
#endif

#ifndef LEAN_DEFAULT_EQN_COMPILER_LEMMAS
#define LEAN_DEFAULT_EQN_COMPILER_LEMMAS true
#endif

#ifndef LEAN_DEFAULT_EQN_COMPILER_ZETA
#define LEAN_DEFAULT_EQN_COMPILER_ZETA false
#endif

namespace lean {
static name * g_eqn_compiler_dsimp  = nullptr;
static name * g_eqn_compiler_lemmas = nullptr;
static name * g_eqn_compiler_zeta   = nullptr;

static bool get_eqn_compiler_dsimp(options const & o) {
    return o.get_bool(*g_eqn_compiler_dsimp, LEAN_DEFAULT_EQN_COMPILER_DSIMP);
}

static bool get_eqn_compiler_lemmas(options const & o) {
    return o.get_bool(*g_eqn_compiler_lemmas, LEAN_DEFAULT_EQN_COMPILER_LEMMAS);
}

static bool get_eqn_compiler_zeta(options const & o) {
    return o.get_bool(*g_eqn_compiler_zeta, LEAN_DEFAULT_EQN_COMPILER_ZETA);
}

[[ noreturn ]] void throw_ill_formed_eqns() {
    throw exception("ill-formed match/equations expression");
}

static optional<pair<expr, unsigned>> get_eqn_fn_and_arity(expr e) {
    while (is_lambda(e))
        e = binding_body(e);
    if (!is_equation(e) && !is_no_equation(e)) throw_ill_formed_eqns();
    if (is_no_equation(e)) {
        return optional<pair<expr, unsigned>>();
    } else {
        expr const & lhs = equation_lhs(e);
        expr const & fn  = get_app_fn(lhs);
        lean_assert(is_local(fn));
        return optional<pair<expr, unsigned>>(fn, get_app_num_args(lhs));
    }
}

static expr consume_fn_prefix(expr eq, buffer<expr> const & fns) {
    for (unsigned i = 0; i < fns.size(); i++) {
        if (!is_lambda(eq)) throw_ill_formed_eqns();
        eq = binding_body(eq);
    }
    return instantiate_rev(eq, fns);
}

unpack_eqns::unpack_eqns(type_context & ctx, expr const & e):
    m_locals(ctx) {
    lean_assert(is_equations(e));
    m_src = e;
    buffer<expr> eqs;
    unsigned num_fns = equations_num_fns(e);
    to_equations(e, eqs);
    /* Extract functions. */
    lean_assert(eqs.size() > 0);
    expr eq = eqs[0];
    for (unsigned i = 0; i < num_fns; i++) {
        if (!is_lambda(eq)) throw_ill_formed_eqns();
        if (!closed(binding_domain(eq))) throw_ill_formed_eqns();
        m_fns.push_back(m_locals.push_local(binding_name(eq), binding_domain(eq)));
        eq = binding_body(eq);
    }
    /* Extract equations */
    unsigned eqidx = 0;
    for (unsigned fidx = 0; fidx < num_fns; fidx++) {
        m_eqs.push_back(buffer<expr>());
        buffer<expr> & fn_eqs = m_eqs.back();
        if (eqidx >= eqs.size()) throw_ill_formed_eqns();
        expr eq = consume_fn_prefix(eqs[eqidx], m_fns);
        fn_eqs.push_back(eq);
        eqidx++;
        if (auto p = get_eqn_fn_and_arity(eq)) {
            if (p->first != m_fns[fidx]) throw_ill_formed_eqns();
            unsigned arity = p->second;
            m_arity.push_back(arity);
            while (eqidx < eqs.size()) {
                expr eq = consume_fn_prefix(eqs[eqidx], m_fns);
                if (auto p = get_eqn_fn_and_arity(eq)) {
                    if (p->first == m_fns[fidx]) {
                        if (p->second != arity) throw_ill_formed_eqns();
                        fn_eqs.push_back(eq);
                        eqidx++;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        } else {
            /* noequation, guess arity using type of function */
            expr type = ctx.infer(m_fns[fidx]);
            unsigned arity = 0;
            while (is_pi(type)) {
                arity++;
                type = binding_body(type);
            }
            if (arity == 0) throw_ill_formed_eqns();
            m_arity.push_back(arity);
        }
    }
    if (eqs.size() != eqidx) throw_ill_formed_eqns();
    lean_assert(m_arity.size() == m_fns.size());
    lean_assert(m_eqs.size() == m_fns.size());
}

expr unpack_eqns::update_fn_type(unsigned fidx, expr const & type) {
    expr new_fn = m_locals.push_local(local_pp_name(m_fns[fidx]), type);
    m_fns[fidx] = new_fn;
    return new_fn;
}

expr unpack_eqns::repack() {
    buffer<expr> new_eqs;
    for (buffer<expr> const & fn_eqs : m_eqs) {
        for (expr const & eq : fn_eqs) {
            new_eqs.push_back(m_locals.ctx().mk_lambda(m_fns, eq));
        }
    }
    return update_equations(m_src, new_eqs);
}

unpack_eqn::unpack_eqn(type_context & ctx, expr const & eqn):
    m_src(eqn), m_locals(ctx) {
    expr it = eqn;
    while (is_lambda(it)) {
        expr d = instantiate_rev(binding_domain(it), m_locals.as_buffer().size(), m_locals.as_buffer().data());
        m_vars.push_back(m_locals.push_local(binding_name(it), d, binding_info(it)));
        it = binding_body(it);
    }
    it = instantiate_rev(it, m_locals.as_buffer().size(), m_locals.as_buffer().data());
    if (!is_equation(it)) throw_ill_formed_eqns();
    m_nested_src = it;
    m_lhs = equation_lhs(it);
    m_rhs = equation_rhs(it);
}

expr unpack_eqn::add_var(name const & n, expr const & type) {
    m_modified_vars = true;
    m_vars.push_back(m_locals.push_local(n, type));
    return m_vars.back();
}

expr unpack_eqn::repack() {
    if (!m_modified_vars &&
        equation_lhs(m_nested_src) == m_lhs &&
        equation_rhs(m_nested_src) == m_rhs) return m_src;
    expr new_eq = copy_tag(m_nested_src, mk_equation(m_lhs, m_rhs));
    return copy_tag(m_src, m_locals.ctx().mk_lambda(m_vars, new_eq));
}

bool is_recursive_eqns(type_context & ctx, expr const & e) {
    unpack_eqns ues(ctx, e);
    for (unsigned fidx = 0; fidx < ues.get_num_fns(); fidx++) {
        buffer<expr> const & eqns = ues.get_eqns_of(fidx);
        for (expr const & eqn : eqns) {
            expr it = eqn;
            while (is_lambda(it)) {
                it = binding_body(it);
            }
            if (!is_equation(it) && !is_no_equation(it)) throw_ill_formed_eqns();
            if (is_equation(it)) {
                expr const & rhs = equation_rhs(it);
                if (find(rhs, [&](expr const & e, unsigned) {
                            if (is_local(e)) {
                                for (unsigned fidx = 0; fidx < ues.get_num_fns(); fidx++) {
                                    if (mlocal_name(e) == mlocal_name(ues.get_fn(fidx)))
                                        return true;
                                }
                            }
                            return false;
                        })) {
                    return true;
                }
            }
        }
    }
    return false;
}

class erase_inaccessible_annotations_fn : public replace_visitor {
    virtual expr visit_macro(expr const & e) override {
        if (is_inaccessible(e)) {
            return visit(get_annotation_arg(e));
        } else {
            return replace_visitor::visit_macro(e);
        }
    }
};

expr erase_inaccessible_annotations(expr const & e) {
    return erase_inaccessible_annotations_fn()(e);
}

list<expr> erase_inaccessible_annotations(list<expr> const & es) {
    return map(es, [&](expr const & e) { return erase_inaccessible_annotations(e); });
}

static pair<environment, name> mk_def_name(environment const & env, bool is_private, name const & c) {
    if (is_private) {
        unsigned h = 31;
        if (auto pinfo = get_pos_info_provider()) {
            h = hash(pinfo->get_some_pos().first, pinfo->get_some_pos().second);
            char const * fname = pinfo->get_file_name();
            h = hash_str(strlen(fname), fname, h);
        }
        return add_private_name(env, c, optional<unsigned>(h));
    } else {
        return mk_pair(env, c);
    }
}

static void throw_mk_aux_definition_error(local_context const & lctx, name const & c, expr const & type, expr const & value, exception & ex) {
    sstream strm;
    strm << "equation compiler failed to create auxiliary declaration '" << c << "'";
    if (contains_let_local_decl(lctx, type) || contains_let_local_decl(lctx, value)) {
        strm << ", auxiliary declaration has references to let-declarations (possible solution: use 'set_option eqn_compiler.zeta true')";
    }
    throw nested_exception(strm, ex);
}

pair<environment, expr> mk_aux_definition(environment const & env, options const & opts, metavar_context const & mctx, local_context const & lctx,
                                          bool is_private, bool is_lemma, bool is_noncomputable,
                                          name const & c, expr const & type, expr const & value) {
    lean_trace("eqn_compiler", tout() << "declaring auxiliary definition\n" << c << " : " << type << "\n";);
    environment new_env = env;
    expr new_type       = type;
    expr new_value      = value;
    bool zeta           = get_eqn_compiler_zeta(opts);
    if (zeta) {
        new_type  = zeta_expand(lctx, new_type);
        new_value = zeta_expand(lctx, new_value);
    }
    name new_c;
    std::tie(new_env, new_c) = mk_def_name(env, is_private, c);
    expr r;
    try {
        std::tie(new_env, r) = is_lemma ?
            mk_aux_lemma(new_env, mctx, lctx, new_c, new_type, new_value) :
            mk_aux_definition(new_env, mctx, lctx, new_c, new_type, new_value);
    } catch (exception & ex) {
        throw_mk_aux_definition_error(lctx, c, new_type, new_value, ex);
    }
    if (!is_lemma && !is_noncomputable) {
        try {
            declaration d = new_env.get(new_c);
            new_env = vm_compile(new_env, d);
        } catch (exception & ex) {
            throw nested_exception(sstream() << "equation compiler failed to generate bytecode for "
                                   << "auxiliary declaration '" << c << "'", ex);
        }
    }
    return mk_pair(new_env, r);
}

static unsigned g_eqn_sanitizer_token;

static environment add_equation_lemma(environment const & env, options const & opts, metavar_context const & mctx, local_context const & lctx,
                                      bool is_private, name const & c, expr const & type, expr const & value) {
    environment new_env = env;
    name new_c;
    std::tie(new_env, new_c) = mk_def_name(env, is_private, c);
    expr r;
    expr new_type  = type;
    bool use_dsimp = get_eqn_compiler_dsimp(opts);
    if (use_dsimp) {
        try {
            type_context ctx(env, opts, mctx, lctx, transparency_mode::None);
            rfl_lemmas_ptr lemmas = get_rfl_lemmas(env, g_eqn_sanitizer_token);
            new_type = defeq_simplify(ctx, *lemmas, type);
        } catch (defeq_simplifier_exception & ex) {
            throw nested_exception("equation compiler failed to simplify type of automatically generated lemma using "
                                   "defeq simplifier "
                                   "(possible solution: disable simplification step using `set_option eqn_compiler.dsimp false`), "
                                   "defeq simplifier error message:\n", ex);
        }
    }
    expr new_value = value;
    bool zeta      = get_eqn_compiler_zeta(opts);
    if (zeta) {
        new_type   = zeta_expand(lctx, new_type);
        new_value  = zeta_expand(lctx, new_value);
    }
    try {
        std::tie(new_env, r) = mk_aux_definition(new_env, mctx, lctx, new_c, new_type, new_value);
    } catch (exception & ex) {
        throw_mk_aux_definition_error(lctx, c, new_type, new_value, ex);
    }
    return new_env;
}

static expr whnf_ite(type_context & ctx, expr const & e) {
    return ctx.whnf_pred(e, [&](expr const & e) {
            expr const & fn = get_app_fn(e);
            return !is_constant(fn, get_ite_name());
        });
}

/* Return true iff `lhs` is of the form (@ite (x = y) s A t e).
   If the result is true, then the ite args are stored in `ite_args`. */
static bool is_ite_eq(expr const & lhs, buffer<expr> & ite_args) {
    expr const & fn = get_app_args(lhs, ite_args);
    return is_constant(fn, get_ite_name()) && ite_args.size() == 5 && is_eq(ite_args[0]);
}

/* Try to find (H : not c) at Hs */
static optional<expr> find_if_neg_hypothesis(type_context & ctx, expr const & c, buffer<expr> const & Hs) {
    for (expr const & H : Hs) {
        expr H_type = ctx.infer(H);
        expr arg;
        if (is_not(ctx.env(), H_type, arg) && ctx.is_def_eq(c, arg)) {
            return some_expr(H);
        }
    }
    return none_expr();
}

/*
  If `e` is of the form

      (@eq.rec B (f (g (f a))) C (h (g (f a))) (f a) (f_g_eq (f a))

  such that

      f_g_eq : forall x, f (g x) = x

  and there is a lemma

      g_f_eq : forall x, g (f x) = x

  Return (h a) and a proof that (e = h a)

  The proof is of the form

  @eq.rec
     A
     a
     (fun x : A, (forall H : f x = f a, @eq.rec B (f x) C (h x) (f a) H = h a))
     (fun H : f a = f a, eq.refl (h a))
     (g (f a))
     (eq.symm (g_f_eq a))
     (f_g_eq a)
*/
static optional<expr_pair> prove_eq_rec_invertible(type_context & ctx, expr const & e) {
    buffer<expr> rec_args;
    expr rec_fn = get_app_args(e, rec_args);
    if (!is_constant(rec_fn, get_eq_rec_name()) || rec_args.size() != 6) return optional<expr_pair>();
    expr B      = rec_args[0];
    expr from   = rec_args[1]; /* (f (g (f a))) */
    expr C      = rec_args[2];
    expr minor  = rec_args[3]; /* (h (g (f a))) */
    expr to     = rec_args[4]; /* (f a) */
    expr major  = rec_args[5]; /* (f_g_eq (f a)) */
    if (!is_app(from) || !is_app(minor)) return optional<expr_pair>();
    if (!ctx.is_def_eq(app_arg(from), app_arg(minor))) return optional<expr_pair>();
    expr h     = app_fn(minor);
    expr g_f_a = app_arg(from);
    if (!is_app(g_f_a) || !ctx.is_def_eq(app_arg(g_f_a), to)) return optional<expr_pair>();
    expr g     = get_app_fn(g_f_a);
    if (!is_constant(g)) return optional<expr_pair>();
    expr f_a   = to;
    if (!is_app(f_a)) return optional<expr_pair>();
    expr f     = get_app_fn(f_a);
    expr a     = app_arg(f_a);
    if (!is_constant(f)) return optional<expr_pair>();
    optional<inverse_info> info = has_inverse(ctx.env(), const_name(f));
    if (!info || info->m_inv != const_name(g)) return optional<expr_pair>();
    name g_f_name = info->m_lemma;
    optional<inverse_info> info_inv = has_inverse(ctx.env(), const_name(g));
    if (!info_inv || info_inv->m_inv != const_name(f)) return optional<expr_pair>();
    buffer<expr> major_args;
    expr f_g_eq = get_app_args(major, major_args);
    if (!is_constant(f_g_eq) || major_args.empty() || !ctx.is_def_eq(f_a, major_args.back())) return optional<expr_pair>();
    if (const_name(f_g_eq) != info_inv->m_lemma) return optional<expr_pair>();

    expr A          = ctx.infer(a);
    level A_lvl     = get_level(ctx, A);
    expr h_a        = mk_app(h, a);
    expr refl_h_a   = mk_eq_refl(ctx, h_a);
    expr f_a_eq_f_a = mk_eq(ctx, f_a, f_a);
    /* (fun H : f a = f a, eq.refl (h a)) */
    expr pr_minor   = mk_lambda("_H", f_a_eq_f_a, refl_h_a);
    type_context::tmp_locals aux_locals(ctx);
    expr x          = aux_locals.push_local("_x", A);
    /* Remark: we cannot use mk_app(f, x) in the following line.
       Reason: f may have implicit arguments. So, app_fn(f_x) is not equal to f in general,
       and app_fn(f_a) is f + implicit arguments. */
    expr f_x        = mk_app(app_fn(f_a), x);
    expr f_x_eq_f_a = mk_eq(ctx, f_x, f_a);
    expr H          = aux_locals.push_local("_H", f_x_eq_f_a);
    expr h_x        = mk_app(h, x);
    /* (@eq.rec B (f x) C (h x) (f a) H) */
    expr eq_rec2    = mk_app(rec_fn, {B, f_x, C, h_x, f_a, H});
    /* (@eq.rec B (f x) C (h x) (f a) H) = h a */
    expr eq_rec2_eq = mk_eq(ctx, eq_rec2, h_a);
    /* (fun x : A, (forall H : f x = f a, @eq.rec B (f x) C (h x) (f a) H = h a)) */
    expr pr_motive  = ctx.mk_lambda(x, ctx.mk_pi(H, eq_rec2_eq));
    expr g_f_eq_a   = mk_app(ctx, g_f_name, a);
    /* (eq.symm (g_f_eq a)) */
    expr pr_major   = mk_eq_symm(ctx, g_f_eq_a);
    expr pr         = mk_app(mk_constant(get_eq_rec_name(), {mk_level_zero(), A_lvl}),
                             {A, a, pr_motive, pr_minor, g_f_a, pr_major, major});

    return optional<expr_pair>(mk_pair(h_a, pr));
}

static expr prove_eqn_lemma_core(type_context & ctx, buffer<expr> const & Hs, expr const & lhs, expr const & rhs) {
    buffer<expr> ite_args;
    expr new_lhs = whnf_ite(ctx, lhs);
    if (is_ite_eq(new_lhs, ite_args)) {
        expr const & c = ite_args[0];
        expr c_lhs, c_rhs;
        lean_verify(is_eq(c, c_lhs, c_rhs));
        if (auto H = find_if_neg_hypothesis(ctx, c, Hs)) {
            expr lhs_else = ite_args[4];
            expr A        = ite_args[2];
            level A_lvl   = get_level(ctx, A);
            expr H1       = mk_app(mk_constant(get_if_neg_name(), {A_lvl}), {c, ite_args[1], *H, A, ite_args[3], lhs_else});
            expr H2       = prove_eqn_lemma_core(ctx, Hs, lhs_else, rhs);
            return mk_app(mk_constant(get_eq_trans_name(), {A_lvl}), {A, lhs, lhs_else, rhs, H1, H2});
        } else if (ctx.is_def_eq(c_lhs, c_rhs)) {
            expr H = mk_eq_refl(ctx, c_lhs);
            expr lhs_then = ite_args[3];
            expr A        = ite_args[2];
            level A_lvl   = get_level(ctx, A);
            expr H1       = mk_app(mk_constant(get_if_pos_name(), {A_lvl}), {c, ite_args[1], H, A, lhs_then, ite_args[4]});
            expr H2       = prove_eqn_lemma_core(ctx, Hs, lhs_then, rhs);
            expr eq_trans = mk_constant(get_eq_trans_name(), {A_lvl});
            return mk_app(eq_trans, {A, lhs, lhs_then, rhs, H1, H2});
        }
    }

    if (optional<expr_pair> p = prove_eq_rec_invertible(ctx, new_lhs)) {
        expr new_new_lhs = p->first;
        expr H1          = p->second;
        expr H2          = prove_eqn_lemma_core(ctx, Hs, new_new_lhs, rhs);
        return mk_eq_trans(ctx, H1, H2);
    }

    if (ctx.is_def_eq(lhs, rhs)) {
        return mk_eq_refl(ctx, rhs);
    }

    throw exception("equation compiler failed to prove equation lemma (workaround: "
                    "disable lemma generation using `set_option eqn_compiler.lemmas false`)");
}

static expr prove_eqn_lemma(type_context & ctx, buffer<expr> const & Hs, expr const & lhs, expr const & rhs) {
    expr body = prove_eqn_lemma_core(ctx, Hs, lhs, rhs);
    return ctx.mk_lambda(Hs, body);
}

environment mk_equation_lemma(environment const & env, options const & opts, metavar_context const & mctx, local_context const & lctx,
                              name const & f_name, unsigned eqn_idx, bool is_private,
                              buffer<expr> const & Hs, expr const & lhs, expr const & rhs) {
    if (!get_eqn_compiler_lemmas(opts)) return env;
    type_context ctx(env, opts, mctx, lctx, transparency_mode::Semireducible);
    expr type     = ctx.mk_pi(Hs, mk_eq(ctx, lhs, rhs));
    expr proof    = prove_eqn_lemma(ctx, Hs, lhs, rhs);
    name eqn_name = name(name(f_name, "equations"), "eqn").append_after(eqn_idx);
    return add_equation_lemma(env, opts, mctx, lctx, is_private, eqn_name, type, proof);
}

void initialize_eqn_compiler_util() {
    register_trace_class("eqn_compiler");
    register_trace_class(name{"debug", "eqn_compiler"});
    g_eqn_compiler_dsimp  = new name{"eqn_compiler", "dsimp"};
    g_eqn_compiler_lemmas = new name{"eqn_compiler", "lemmas"};
    g_eqn_compiler_zeta   = new name{"eqn_compiler", "zeta"};
    register_bool_option(*g_eqn_compiler_dsimp, LEAN_DEFAULT_EQN_COMPILER_DSIMP,
                         "(equation compiler) use defeq simplifier to cleanup types of "
                         "automatically synthesized equational lemmas");
    register_bool_option(*g_eqn_compiler_lemmas, LEAN_DEFAULT_EQN_COMPILER_LEMMAS,
                         "(equation compiler) generate equation lemmas and induction principle");
    register_bool_option(*g_eqn_compiler_zeta, LEAN_DEFAULT_EQN_COMPILER_ZETA,
                         "(equation compiler) apply zeta-expansion (expand references to let-declarations) before creating auxiliary definitions.");
    g_eqn_sanitizer_token = register_defeq_simp_attribute("eqn_sanitizer");
}

void finalize_eqn_compiler_util() {
    delete g_eqn_compiler_dsimp;
    delete g_eqn_compiler_lemmas;
}
}


text:
import {
  definePlugin,
  progressBarPlugin,
} from './plugins';

const config = {
  devtool: '',
  plugins: [
    progressBarPlugin({
      name: 'Server',
      production: true,
    }),
    definePlugin({
      PRODUCTION: JSON.stringify(true),
    }),
  ],
  watch: false,
};

export default config;


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>Psalms 62 (ASV)</title>
<link href="../../../build/mobile.css" rel="stylesheet" />

American Standard VersionPsalms 62<
=
>

Psalm 62

For the Chief Musician; after the manner of Jeduthun. A Psalm of David.

1 My soul waiteth in silence for God only:

From him cometh my salvation.

2 He only is my rock and my salvation:

He is my high tower; I shall not be greatly moved.

3 How long will ye set upon a man,

That ye may slay him, all of you,

Like a leaning wall, like a tottering fence?

4 They only consult to thrust him down from his dignity;

They delight in lies;

They bless with their mouth, but they curse inwardly.
[Selah

5 My soul, wait thou in silence for God only;

For my expectation is from him.

6 He only is my rock and my salvation:

He is my high tower; I shall not be moved.

7 With God is my salvation and my glory:

The rock of my strength, and my refuge, is in God.

8 Trust in him at all times, ye people;

Pour out your heart before him:

God is a refuge for us.
[Selah

9 Surely men of low degree are vanity, and men of high degree are a lie:

In the balances they will go up;

They are together lighter than vanity.

10 Trust not in oppression,

And become not vain in robbery:

If riches increase, set not your heart thereon.

11 God hath spoken once,

Twice have I heard this,

That power belongeth unto God.

12 Also unto thee, O Lord, belongeth lovingkindness;

For thou renderest to every man according to his work.

<
=
>


text:
using EED.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EED.Service.Controller.Project
{
    public interface IProjectServiceController
    {
        IEnumerable<ElectionType> FindAllElectionTypes();
        IEnumerable<JurisdictionType> FindAllJurisdictionTypes();
        IEnumerable<ElectionProject> FindAllProjectsFromUser();
        ElectionProject FindProject(int id);
        IEnumerable<ElectionProject> FilterProjects(IEnumerable<ElectionProject> projects,
            string searchText);
        void SaveProject(ElectionProject project);
        void DeleteProject(ElectionProject project);
    }
}


text:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">2</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management
        <property name="current_session_context_class">thread</property> -->

        <!-- Disable the second-level cache  org.springframework.orm.hibernate4.SpringSessionContext  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!--<property name="current_session_context_class">thread</property>-->

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">never</property>
    </session-factory>

</hibernate-configuration>


text:
namespace Moses
{

class FFState;

namespace Syntax
{

struct PVertex;
struct SHyperedge;

// A vertex in the search hypergraph.
//
// Important: a SVertex owns its incoming SHyperedge objects and its FFState
// objects and will delete them on destruction.
struct SVertex {
  ~SVertex();

  SHyperedge *best;
  std::vector<SHyperedge*> recombined;
  const PVertex *pvertex;
  std::vector<FFState*> states;
};

}  // Syntax
}  // Moses


text:
const React = require('react');
const ReactDOM = require('react-dom');
const ajaxApi = require('../../util/ajaxApi');
const treeData = require('../../util/TreeData');
const TreeView = require('../../componets/edit/TreeView');
const ListTable = require("../../componets/list/ListTable");
const _ = require('lodash');
var header =[{code:'index',name:'#',style:{width:'2%',textAlign:'center',verticalAlign:'middle'}},
            {code:'code',name:'項目編號',style:{width:'20%',verticalAlign:'middle'}},
            {code:'item',name:'項目名稱',style:{width:'45%',verticalAlign:'middle'}},
            {code:'unit',name:'單位',style:{width:'12%',textAlign:'center',verticalAlign:'middle'}},
            {code:'contractPrice',name:'單價',style:{width:'13%',verticalAlign:'middle'}},
            {code:'rightAdd',name:'',style:{width:'8%',textAlign:'center',verticalAlign:'middle'}}]

var Categories = React.createClass({
  getInitialState: function() {
   return {
     categories:[],
     categoriesDetail:[],
     dataTree:null,
     chooseItems:[]
   };
 },
 componentDidMount: function() {
   var type = "node";
   ajaxApi.categoriesDao("getBycType",{cType:type},function(items){
      var dataTree = treeData.initWithParentCode(items,'code');
      this.setState({categories:items,dataTree:dataTree});
   }.bind(this));
 },
  render(){
    var categories = this.state.categories;
    var dataTree = this.state.dataTree;
    var editNode = this.state.editNode;
    if(!dataTree){
      dataTree = treeData.initWithParentCode(categories,'code');
    }
    var categoriesDetail = this.state.categoriesDetail;
    return (

編碼

            <TreeView dataTree={dataTree} paddingLeft={10} selectNodeView={this._handleSelectNodeView} setTree={this._handleSetTree}/>

選擇

            <ListTable datas={categoriesDetail} header={header}  isRanderPagger='false'/>

    )
  },
  _handleSetTree(tree){
    this.setState({dataTree:tree});
  },
  _handleSelectNodeView(node){
    var code = node.data.code;
    ajaxApi.categoriesDetaileDao("getByCategoriesCode",{code:code},function(items){
       this.setState({categoriesDetail:items});
    }.bind(this));
  },

});

module.exports = Categories;


text: TODO: Move to separate github repo


text:
#include "kaa/http/HttpResponse.hpp"

#if defined(KAA_DEFAULT_BOOTSTRAP_HTTP_CHANNEL) || \
    defined(KAA_DEFAULT_OPERATION_HTTP_CHANNEL) || \
    defined(KAA_DEFAULT_LONG_POLL_CHANNEL)

#include <cstring>
#include <cstdlib>
#include <cstdint>
#include "kaa/common/exception/KaaException.hpp"

namespace kaa {

HttpResponse::HttpResponse(const char *data, std::size_t len) : statusCode_(0)
{
    if (data == nullptr || len < HTTP_VERSION_OFFSET + 5) {
        throw KaaException("Empty response was given");
    }
    parseResponse(data, len);
}

HttpResponse::HttpResponse(const std::string& data) : statusCode_(0)
{
    if (data.length() < HTTP_VERSION_OFFSET + 5) {
        throw KaaException("Empty response was given");
    }
    parseResponse(data.c_str(), data.length());
}

std::string HttpResponse::getHeaderField(const std::string& name) const
{
    auto it = header_.find(name);
    return it != header_.end() ? it->second : std::string();
}

SharedBody HttpResponse::getBody() const
{
    return body_;
}

int HttpResponse::getStatusCode() const
{
    return statusCode_;
}

void HttpResponse::parseResponse(const char *data, std::size_t len)
{
    const char *cursor = data;
    cursor += HTTP_VERSION_OFFSET;
    std::string code(cursor, 3);
    statusCode_ = static_cast<int>(std::strtol(code.c_str(), nullptr, 10));
    cursor = strstr(data, "\r\n") + 2;

    bool headerProcessed = false;
    while (!headerProcessed) {
        auto sep = strchr(cursor, ':');
        std::string name(cursor, sep - cursor);
        cursor = sep + 2;
        auto end = strstr(cursor, "\r\n");
        std::string value(cursor, end - cursor);
        cursor = end + 2;
        header_.insert(std::make_pair(name, value));
        if (strstr(cursor, "\r\n") == cursor) {
            cursor += 2;
            headerProcessed = true;
        }
    }
    auto it = header_.find("Content-Length");
    if (it != header_.end()) {
        auto len = std::strtol(it->second.c_str(), nullptr, 10);
        if (len > 0) {
            body_.first.reset(new std::uint8_t[len]);
            body_.second = len;
            memcpy(body_.first.get(), cursor, len);
        }
    }
}

}

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<!--dimens.xml-->
<resources>
    <dimen name="btn_fab_size">56dp</dimen>
    <dimen name="btn_fab_margins">16dp</dimen>
    <dimen name="default_elevation">8dp</dimen>
    <dimen name="comment_avatar_size">56dp</dimen>
    <dimen name="user_profile_avatar_size">88dp</dimen>
    <dimen name="global_menu_avatar_size">64dp</dimen>
    <dimen name="publish_photo_thumbnail_size">96dp</dimen>

    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for VMwareDvsLacpGroupSpec complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="VMwareDvsLacpGroupSpec">
 *   <complexContent>
 *     <extension base="{urn:vim25}DynamicData">
 *       <sequence>
 *         <element name="lacpGroupConfig" type="{urn:vim25}VMwareDvsLacpGroupConfig"/>
 *         <element name="operation" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VMwareDvsLacpGroupSpec", propOrder = {
    "lacpGroupConfig",
    "operation"
})
public class VMwareDvsLacpGroupSpec
    extends DynamicData
{

    @XmlElement(required = true)
    protected VMwareDvsLacpGroupConfig lacpGroupConfig;
    @XmlElement(required = true)
    protected String operation;

    /**
     * Gets the value of the lacpGroupConfig property.
     *
     * @return
     *     possible object is
     *     {@link VMwareDvsLacpGroupConfig }
     *
     */
    public VMwareDvsLacpGroupConfig getLacpGroupConfig() {
        return lacpGroupConfig;
    }

    /**
     * Sets the value of the lacpGroupConfig property.
     *
     * @param value
     *     allowed object is
     *     {@link VMwareDvsLacpGroupConfig }
     *
     */
    public void setLacpGroupConfig(VMwareDvsLacpGroupConfig value) {
        this.lacpGroupConfig = value;
    }

    /**
     * Gets the value of the operation property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getOperation() {
        return operation;
    }

    /**
     * Sets the value of the operation property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setOperation(String value) {
        this.operation = value;
    }

}


text:
// This file was automatically generated by lister-gen

package v1alpha1

// VerticalPodAutoscalerListerExpansion allows custom methods to be added to
// VerticalPodAutoscalerLister.
type VerticalPodAutoscalerListerExpansion interface{}

// VerticalPodAutoscalerNamespaceListerExpansion allows custom methods to be added to
// VerticalPodAutoscalerNamespaceLister.
type VerticalPodAutoscalerNamespaceListerExpansion interface{}

// VerticalPodAutoscalerCheckpointListerExpansion allows custom methods to be added to
// VerticalPodAutoscalerCheckpointLister.
type VerticalPodAutoscalerCheckpointListerExpansion interface{}

// VerticalPodAutoscalerCheckpointNamespaceListerExpansion allows custom methods to be added to
// VerticalPodAutoscalerCheckpointNamespaceLister.
type VerticalPodAutoscalerCheckpointNamespaceListerExpansion interface{}


text:
from dd import *
from gen_feats import *
from util import *


text: Awesome Resources for becoming data scientist.


text:
package com.amazonaws.services.simplesystemsmanagement.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * OpsEntity JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class OpsEntityJsonUnmarshaller implements Unmarshaller<OpsEntity, JsonUnmarshallerContext> {

    public OpsEntity unmarshall(JsonUnmarshallerContext context) throws Exception {
        OpsEntity opsEntity = new OpsEntity();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Id", targetDepth)) {
                    context.nextToken();
                    opsEntity.setId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Data", targetDepth)) {
                    context.nextToken();
                    opsEntity.setData(new MapUnmarshaller<String, OpsEntityItem>(context.getUnmarshaller(String.class), OpsEntityItemJsonUnmarshaller
                            .getInstance()).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return opsEntity;
    }

    private static OpsEntityJsonUnmarshaller instance;

    public static OpsEntityJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new OpsEntityJsonUnmarshaller();
        return instance;
    }
}


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 Classes;

/**
 *
 * @author jncor
 */
public class Shelf
{
    private String id;
    private String location;

    Shelf()
    {

    }

    public String getID() { return id; }
    public String getLocation() { return location; }
}


text:
<?php
require_once './common/config.php';
require_once './common/functions.php';
require_once './common/Gexf.class.php';
?>

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

        <title>TCAT :: Source / hashtag co-occurence</title>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

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

TCAT :: Source / hashtag co-occurence

        <?php

        validate_all_variables();
        $filename = get_filename_for_export("sourceHashtag", '', 'gexf');
        $collation = current_collation();

		//print_r($_GET);

        $sql = "SELECT LOWER(t.source COLLATE $collation) AS source, LOWER(h.text COLLATE $collation) AS hashtag FROM ";
        $sql .= $esc['mysql']['dataset'] . "_tweets t, " . $esc['mysql']['dataset'] . "_hashtags h ";
        $where = "t.id = h.tweet_id AND ";
        $sql .= sqlSubset($where);

        $sqlresults = mysql_query($sql);

		while ($res = mysql_fetch_assoc($sqlresults)) {

			$res['source'] = preg_replace("/<.+>/U", "", $res['source']);
			$res['source'] = preg_replace("/[ \s\t]+/", " ", $res['source']);
			$res['source'] = trim($res['source']);

			if(!isset($sourcesHashtags[$res['source']][$res['hashtag']])) {
				 $sourcesHashtags[$res['source']][$res['hashtag']] = 0;
			}
			$sourcesHashtags[$res['source']][$res['hashtag']]++;
        }

        $gexf = new Gexf();
        $gexf->setTitle("source-hashtag " . $filename);
        $gexf->setEdgeType(GEXF_EDGE_UNDIRECTED);
        $gexf->setCreator("tools.digitalmethods.net");
        foreach ($sourcesHashtags as $source => $hashtags) {
            foreach ($hashtags as $hashtag => $frequency) {
                $node1 = new GexfNode($source);
                $node1->addNodeAttribute("type", 'source', $type = "string");
                $gexf->addNode($node1);
                $node2 = new GexfNode($hashtag);
                $node2->addNodeAttribute("type", 'hashtag', $type = "string");
                $gexf->addNode($node2);
                $edge_id = $gexf->addEdge($node1, $node2, $frequency);
            }
        }

        $gexf->render();

        file_put_contents($filename, $gexf->gexfFile);

        echo '<fieldset class="if_parameters">';

        echo '<legend>Your network (GEXF) file</legend>';

        echo '
' . $filename . '
';

        echo '</fieldset>';
        ?>


text:
```html
<template>
  <ion-list>
    <ion-radio-group value="biff">
      <ion-list-header>
        <ion-label>Name</ion-label>
      </ion-list-header>

      <ion-item>
        <ion-label>Biff</ion-label>
        <ion-radio slot="start" value="biff"></ion-radio>
      </ion-item>

      <ion-item>
        <ion-label>Griff</ion-label>
        <ion-radio slot="start" value="griff"></ion-radio>
      </ion-item>

      <ion-item>
        <ion-label>Buford</ion-label>
        <ion-radio slot="start" value="buford"></ion-radio>
      </ion-item>
    </ion-radio-group>
  </ion-list>
</template>

<script>
import {
  IonItem,
  IonLabel,
  IonList,
  IonListHeader,
  IonRadio,
  IonRadioGroup
} from '@ionic/vue';
import { defineComponent } from 'vue';

export default defineComponent({
  components: {
    IonItem,
    IonLabel,
    IonList,
    IonListHeader,
    IonRadio,
    IonRadioGroup
  }
});
</script>
```


text:
$LOAD_PATH.unshift File.expand_path("../lib", File.dirname(__FILE__))

require 'rspec'
require 'labor'


text:
/* Axis lines */
.axis path, line {
    fill: none;
    stroke: #222222;
    shape-rendering: crispEdges;
}
/* Style for the xaxis */
.xaxis {
  font-size: 12px;
  font-family: sans-serif;
}
/* Style for the yaxis */
.yaxis {
  font-size: 12px;
  font-family: sans-serif
}


text:
class XSoft

  #
  # one of possible softwares for NASA rover
  # this one works with three signals: L, R or M
  # M - move forward; L - turn left; R - turn right
  #

  # allowed signals from Houston
  PROTOCOL = ['M', 'L', 'R']

  def initialize(rover)
    @rover = rover
  end

  # act properly to the received signal
  # makes the interpret method only API (public method) to a rover
  def interpret(signal)
    raise "signal not supported: #{signal}" unless PROTOCOL.include?(signal)

    case signal
    when 'M' then move
    when 'L', 'R' then turn(signal)
    end
  end

  private

  # depending if signal is left or right
  # set previous or next direction as a new one
  def turn(direction)
    turn_value = (direction == "L") ? -1 : 1
    new_face_index = (Rover::DIRECTIONS.index(@rover.face)+turn_value) % Rover::DSIZE
    set_face(Rover::DIRECTIONS[new_face_index])
  end

  # move left, right, forward or backwards depending on rover's face
  def move
    x, y = @rover.x, @rover.y

    new_location = case @rover.face
                   when 'N' then [x, y+1]
                   when 'E' then [x+1, y]
                   when 'S' then [x, y-1]
                   when 'W' then [x-1, y]
                   else raise 'no turn'
    end

    set_location(new_location)
    return self
  end

  # changes the information about the position of a rover
  def set_location(new_coordinates)
    @rover.x, @rover.y = new_coordinates
  end

  # changes the information about the turn of a rover
  def set_face(direction)
    @rover.face = direction
  end
end


text:
ALTER TABLE structuredevent ADD COLUMN IF NOT EXISTS resourceCrn VARCHAR(255);

ALTER TABLE recipe RENAME COLUMN crn TO resourceCrn;
ALTER TABLE imagecatalog RENAME COLUMN crn TO resourceCrn;
ALTER TABLE blueprint RENAME COLUMN crn TO resourceCrn;

-- //@UNDO
-- SQL to undo the change goes here.

ALTER TABLE structuredevent DROP COLUMN IF EXISTS resourceCrn;

ALTER TABLE recipe RENAME COLUMN resourceCrn TO crn;
ALTER TABLE imagecatalog RENAME COLUMN resourceCrn TO crn;
ALTER TABLE blueprint RENAME COLUMN resourceCrn TO crn;