text:
.class public Landroid/support/v17/leanback/transition/TransitionListener;
.super Ljava/lang/Object;
.source "TransitionListener.java"

# annotations
.annotation build Landroid/support/annotation/RestrictTo;
    value = {
        .enum Landroid/support/annotation/RestrictTo$Scope;->LIBRARY_GROUP:Landroid/support/annotation/RestrictTo$Scope;
    }
.end annotation

# instance fields
.field protected mImpl:Ljava/lang/Object;

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onTransitionCancel(Ljava/lang/Object;)V
    .locals 0

    return-void
.end method

.method public onTransitionEnd(Ljava/lang/Object;)V
    .locals 0

    return-void
.end method

.method public onTransitionPause(Ljava/lang/Object;)V
    .locals 0

    return-void
.end method

.method public onTransitionResume(Ljava/lang/Object;)V
    .locals 0

    return-void
.end method

.method public onTransitionStart(Ljava/lang/Object;)V
    .locals 0

    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
package rui.coder.foundation.jdk8.date;

import org.junit.jupiter.api.Test;

import java.time.Duration;

/**
 * @author 赵睿
 */
class DurationTest {

    @Test
    void ofMinutes() {
        System.out.println(Duration.ofMinutes(10));
    }

}


text:
#else

	#include "sdk_player.h"
	#include "items.h"
	#include "sdk_basegrenade_projectile.h"

#endif

#define GRENADE_TIMER	3.0f //Seconds

IMPLEMENT_NETWORKCLASS_ALIASED( SDKGrenade, DT_SDKGrenade )

BEGIN_NETWORK_TABLE(CSDKGrenade, DT_SDKGrenade)
END_NETWORK_TABLE()

BEGIN_PREDICTION_DATA( CSDKGrenade )
END_PREDICTION_DATA()

LINK_ENTITY_TO_CLASS( weapon_grenade, CSDKGrenade );
PRECACHE_WEAPON_REGISTER( weapon_grenade );

#ifdef GAME_DLL

#define GRENADE_MODEL "models/Weapons/w_eq_fraggrenade_thrown.mdl"

class CGrenadeProjectile : public CBaseGrenadeProjectile
{
public:
	DECLARE_CLASS( CGrenadeProjectile, CBaseGrenadeProjectile );

	// Overrides.
public:
	virtual void Spawn()
	{
		SetModel( GRENADE_MODEL );
		BaseClass::Spawn();
	}

	virtual void Precache()
	{
		PrecacheModel( GRENADE_MODEL );
		BaseClass::Precache();
	}

	// Grenade stuff.
public:

	static CGrenadeProjectile* Create(
		const Vector &position,
		const QAngle &angles,
		const Vector &velocity,
		const AngularImpulse &angVelocity,
		CBaseCombatCharacter *pOwner,
		float timer )
	{
		CGrenadeProjectile *pGrenade = (CGrenadeProjectile*)CBaseEntity::Create( "grenade_projectile", position, angles, pOwner );

		// Set the timer for 1 second less than requested. We're going to issue a SOUND_DANGER
		// one second before detonation.

		pGrenade->SetDetonateTimerLength( 1.5 );
		pGrenade->SetAbsVelocity( velocity );
		pGrenade->SetupInitialTransmittedGrenadeVelocity( velocity );
		pGrenade->SetThrower( pOwner );

		pGrenade->SetGravity( BaseClass::GetGrenadeGravity() );
		pGrenade->SetFriction( BaseClass::GetGrenadeFriction() );
		pGrenade->SetElasticity( BaseClass::GetGrenadeElasticity() );

		pGrenade->m_flDamage = 100;
		pGrenade->m_DmgRadius = pGrenade->m_flDamage * 3.5f;
		pGrenade->ChangeTeam( pOwner->GetTeamNumber() );
		pGrenade->ApplyLocalAngularVelocityImpulse( angVelocity );

		// make NPCs afaid of it while in the air
		pGrenade->SetThink( &CGrenadeProjectile::DangerSoundThink );
		pGrenade->SetNextThink( gpGlobals->curtime );

		return pGrenade;
	}
};

LINK_ENTITY_TO_CLASS( grenade_projectile, CGrenadeProjectile );
PRECACHE_WEAPON_REGISTER( grenade_projectile );

BEGIN_DATADESC( CSDKGrenade )
END_DATADESC()

void CSDKGrenade::EmitGrenade( Vector vecSrc, QAngle vecAngles, Vector vecVel, AngularImpulse angImpulse, CBasePlayer *pPlayer )
{
	CGrenadeProjectile::Create( vecSrc, vecAngles, vecVel, angImpulse, pPlayer, GRENADE_TIMER );
}

#endif


text:
package net.qldarch.web.resource;

import javax.ws.rs.FormParam;
import javax.ws.rs.Path;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

@Path("/contribute")
public class ContributeResource {
    public static Logger logger = LoggerFactory.getLogger(ContributeResource.class);

    @POST
    public Response contribute(
            @FormParam("firstName") String firstName,
            @FormParam("lastName") String lastName,
            @FormParam("email") String email,
            @FormParam("comment") String comment,
            @FormParam("sendMeNewsletter") String sendMeNewsletter) {
        logger.info("Contribution from " + email);

        try {
        	String host = "smtp.uq.edu.au";
        	String to = email;
        	String from = "no-reply@qldarch.net";
        	Properties properties = System.getProperties();
        	properties.setProperty("mail.smtp.host", host);

        	Session session = Session.getDefaultInstance(properties);
        	MimeMessage message = new MimeMessage(session);
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        	message.setFrom(new InternetAddress(from));

        	message.setSubject("Contribution");
        	message.setText(firstName + "\n" + lastName + "\n" +
                    email + "\n" + sendMeNewsletter + "\n" + comment);
        	Transport.send(message);
            logger.info("Contribution forwarded on.");

	        return Response.ok().build();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	        logger.info("Problem Sending Email", e);
	        return Response.serverError().build();
		}
    }
}


text:
'use strict';

module.exports = function(grunt) {
	// Project configuration.
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		jshint: {
			options: {
				jshintrc: '.jshintrc',
			},
			all: [
				'Gruntfile.js',
				'tasks/*.js',
			],
		},
		checkwpversion: {
			options:{
				readme: 'tests/fixtures/readme.txt',
				plugin: 'tests/fixtures/my-plugin.php',
			},
			plugin_equals_stable: {
			    version1: 'plugin',
			    version2: 'readme',
				compare: '==',
			},
			plugin_equals_package: {
			    version1: 'plugin',
			    version2: '<%= pkg.version %>',
				compare: '==',
			},
		}
	});

	// Actually load this plugin's task(s).
	grunt.loadTasks('tasks');

	// These plugins provide necessary tasks.
	grunt.loadNpmTasks('grunt-contrib-jshint');

	// By default, lint and run all tests.
	grunt.registerTask('default', ['jshint']);
};


text:
package tests.i2026;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

import io.jooby.apt.MvcModuleCompilerRunner;
import io.jooby.test.MockContext;
import io.jooby.test.MockRouter;

public class Issue2026 {

  @Test
  public void shouldGenerateWriteMethodSignature() throws Exception {
    new MvcModuleCompilerRunner(new C2026())
        .example(Expected2026.class)
        .module(
            app -> {
              MockRouter router = new MockRouter(app);
              MockContext ctx = new MockContext();
              assertEquals("TODO...", router.get("/api/todo", ctx).value().toString());
            });
  }
}


text:
#include <stdio.h>

#include "fann.h"

int main()
{
	const unsigned int num_layers = 3;
	const unsigned int num_neurons_hidden = 96;
	const float desired_error = (const float) 0.001;
	struct fann *ann;
	struct fann_train_data *train_data, *test_data;

	unsigned int i = 0;

	printf("Creating network.\n");

	train_data = fann_read_train_from_file("../datasets/robot.train");

	ann = fann_create_standard(num_layers,
					  train_data->num_input, num_neurons_hidden, train_data->num_output);

	printf("Training network.\n");

	fann_set_training_algorithm(ann, FANN_TRAIN_INCREMENTAL);
	fann_set_learning_momentum(ann, 0.4f);

	fann_train_on_data(ann, train_data, 3000, 10, desired_error);

	printf("Testing network.\n");

	test_data = fann_read_train_from_file("../datasets/robot.test");

	fann_reset_MSE(ann);
	for(i = 0; i < fann_length_train_data(test_data); i++)
	{
		fann_test(ann, test_data->input[i], test_data->output[i]);
	}
	printf("MSE error on test data: %f\n", fann_get_MSE(ann));

	printf("Saving network.\n");

	fann_save(ann, "robot_float.net");

	printf("Cleaning up.\n");
	fann_destroy_train(train_data);
	fann_destroy_train(test_data);
	fann_destroy(ann);

	return 0;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/multimeter_coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <View
        android:id="@+id/shadow"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black"
        android:alpha="0"/>

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

</androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
/**
 *
 */
package chapter1AdvancedClassDesign.chapter1_5Enums.enumDetails;

/**
 * @author tkurt
 * Date: Mar 28, 2016 4:46:20 PM
 *
 */
public class App {

	public static void main(String[] args) {

		// See how is working for DaysAdvanceEnum.
		DaysAdvanceEnum[] daysArray = DaysAdvanceEnum.values();
		for(DaysAdvanceEnum day : daysArray){
			day.printOpenHourse();
		}

		System.out.println();

		// See how is working for DaysInAbstractShape.
		DaysInAbstractShape[] daysArrayInAbstractStyle = DaysInAbstractShape.values();
		for (DaysInAbstractShape abstractDay : daysArrayInAbstractStyle) {
					abstractDay.printHours();
					abstractDay.printNightHoursIfOpens();
		}

	}

}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding model 'SMS'
        db.create_table('sms_sms', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('couch_id', self.gf('django.db.models.fields.CharField')(max_length=126, null=True, db_index=True)),
            ('domain', self.gf('django.db.models.fields.CharField')(max_length=126, null=True, db_index=True)),
            ('date', self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True)),
            ('couch_recipient_doc_type', self.gf('django.db.models.fields.CharField')(max_length=126, null=True, db_index=True)),
            ('couch_recipient', self.gf('django.db.models.fields.CharField')(max_length=126, null=True, db_index=True)),
            ('phone_number', self.gf('django.db.models.fields.CharField')(max_length=126, null=True, db_index=True)),
            ('direction', self.gf('django.db.models.fields.CharField')(max_length=1, null=True)),
            ('text', self.gf('django.db.models.fields.TextField')(null=True)),
            ('raw_text', self.gf('django.db.models.fields.TextField')(null=True)),
            ('datetime_to_process', self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True)),
            ('processed', self.gf('django.db.models.fields.NullBooleanField')(default=True, db_index=True)),
            ('num_processing_attempts', self.gf('django.db.models.fields.IntegerField')(default=0, null=True)),
            ('queued_timestamp', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('processed_timestamp', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('error', self.gf('django.db.models.fields.NullBooleanField')(default=False)),
            ('system_error_message', self.gf('django.db.models.fields.TextField')(null=True)),
            ('billed', self.gf('django.db.models.fields.NullBooleanField')(default=False)),
            ('domain_scope', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('ignore_opt_out', self.gf('django.db.models.fields.NullBooleanField')(default=False)),
            ('backend_api', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('backend_id', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('system_phone_number', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('backend_message_id', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('workflow', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('chat_user_id', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('xforms_session_couch_id', self.gf('django.db.models.fields.CharField')(max_length=126, null=True, db_index=True)),
            ('invalid_survey_response', self.gf('django.db.models.fields.NullBooleanField')(default=False)),
            ('reminder_id', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('location_id', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('fri_message_bank_lookup_completed', self.gf('django.db.models.fields.NullBooleanField')(default=False)),
            ('fri_message_bank_message_id', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('fri_id', self.gf('django.db.models.fields.CharField')(max_length=126, null=True)),
            ('fri_risk_profile', self.gf('django.db.models.fields.CharField')(max_length=1, null=True)),
        ))
        db.send_create_signal('sms', ['SMS'])

    def backwards(self, orm):

        # Deleting model 'SMS'
        db.delete_table('sms_sms')

    models = {
        'sms.phonenumber': {
            'Meta': {'object_name': 'PhoneNumber'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'phone_number': ('django.db.models.fields.CharField', [], {'max_length': '30', 'unique': 'True', 'null': 'False', 'db_index': 'True'}),
            'send_sms': ('django.db.models.fields.BooleanField', [], {'null': 'False', 'default': 'True'}),
            'send_ivr': ('django.db.models.fields.BooleanField', [], {'null': 'False', 'default': 'True'}),
            'can_opt_in': ('django.db.models.fields.BooleanField', [], {'null': 'False', 'default': 'True'}),
        },
        'sms.sms': {
            'Meta': {'object_name': 'SMS'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'couch_id': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True', 'db_index': 'True'}),
            'domain': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True', 'db_index': 'True'}),
            'date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
            'couch_recipient_doc_type': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True', 'db_index': 'True'}),
            'couch_recipient': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True', 'db_index': 'True'}),
            'phone_number': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True', 'db_index': 'True'}),
            'direction': ('django.db.models.fields.CharField', [], {'max_length': '1', 'null': 'True'}),
            'text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
            'raw_text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
            'datetime_to_process': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
            'processed': ('django.db.models.fields.NullBooleanField', [], {'default': 'True', 'db_index': 'True'}),
            'num_processing_attempts': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True'}),
            'queued_timestamp': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'processed_timestamp': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'error': ('django.db.models.fields.NullBooleanField', [], {'default': 'False'}),
            'system_error_message': ('django.db.models.fields.TextField', [], {'null': 'True'}),
            'billed': ('django.db.models.fields.NullBooleanField', [], {'default': 'False'}),
            'domain_scope': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'ignore_opt_out': ('django.db.models.fields.NullBooleanField', [], {'default': 'False'}),
            'backend_api': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'backend_id': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'system_phone_number': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'backend_message_id': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'workflow': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'chat_user_id': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'xforms_session_couch_id': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True', 'db_index': 'True'}),
            'invalid_survey_response': ('django.db.models.fields.NullBooleanField', [], {'default': 'False'}),
            'reminder_id': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'location_id': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'fri_message_bank_lookup_completed': ('django.db.models.fields.NullBooleanField', [], {'default': 'False'}),
            'fri_message_bank_message_id': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'fri_id': ('django.db.models.fields.CharField', [], {'max_length': '126', 'null': 'True'}),
            'fri_risk_profile': ('django.db.models.fields.CharField', [], {'max_length': '1', 'null': 'True'}),
        },
    }

    complete_apps = ['sms']


text: Open source hardware platform for Bluetooth hacking


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.browserservices.permissiondelegation;

import android.net.Uri;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.components.content_settings.ContentSettingValues;
import org.chromium.components.content_settings.ContentSettingsType;
import org.chromium.components.embedder_support.util.Origin;

/**
 * Provides Trusted Web Activity Client App permissions for native. The C++ counterpart is the
 * {@code installed_webapp_bridge.h}.
 *
 * Lifecycle: All methods are static.
 * Thread safety: Methods will only be called on the UI thread.
 * Native: Requires native to be loaded.
 */
public class InstalledWebappBridge {
    private static long sNativeInstalledWebappProvider;

    /**
     * A POD class to store the combination of a permission setting and the origin the permission is
     * relevant for.
     *
     * It would make more sense for this to be a subclass of
     * {@link InstalledWebappPermissionManager} or a top level class. Unfortunately for the JNI
     * tool to be able to handle passing a class over the JNI boundary the class either needs to be
     * in this file or imported explicitly. Our presubmits don't like explicitly importing classes
     * that we don't need to, so it's easier to just let the class live here.
     */
    static class Permission {
        public final Origin origin;
        public final @ContentSettingValues int setting;

        public Permission(Origin origin, @ContentSettingValues int setting) {
            this.origin = origin;
            this.setting = setting;
        }
    }

    public static void notifyPermissionsChange(@ContentSettingsType int type) {
        if (sNativeInstalledWebappProvider == 0) return;

        InstalledWebappBridgeJni.get().notifyPermissionsChange(
                sNativeInstalledWebappProvider, type);
    }

    public static void runPermissionCallback(
            long callback, @ContentSettingValues int settingValue) {
        if (callback == 0) return;

        InstalledWebappBridgeJni.get().runPermissionCallback(callback, settingValue);
    }

    @CalledByNative
    private static void setInstalledWebappProvider(long provider) {
        sNativeInstalledWebappProvider = provider;
    }

    @CalledByNative
    private static Permission[] getPermissions(@ContentSettingsType int type) {
        return InstalledWebappPermissionManager.get().getPermissions(type);
    }

    @CalledByNative
    private static String getOriginFromPermission(Permission permission) {
        return permission.origin.toString();
    }

    @CalledByNative
    private static int getSettingFromPermission(Permission permission) {
        return permission.setting;
    }

    @CalledByNative
    private static void decidePermission(@ContentSettingsType int type, String originUrl,
            String lastCommittedUrl, long callback) {
        Origin origin = Origin.create(Uri.parse(originUrl));
        if (origin == null) {
            runPermissionCallback(callback, ContentSettingValues.BLOCK);
            return;
        }
        switch (type) {
            case ContentSettingsType.GEOLOCATION:
                PermissionUpdater.get().getLocationPermission(origin, lastCommittedUrl, callback);
                break;
            case ContentSettingsType.NOTIFICATIONS:
                PermissionUpdater.get().requestNotificationPermission(
                        origin, lastCommittedUrl, callback);
                break;
            default:
                throw new IllegalStateException("Unsupported permission type.");
        }
    }

    @NativeMethods
    interface Natives {
        void notifyPermissionsChange(long provider, int type);
        void runPermissionCallback(long callback, @ContentSettingValues int settingValue);
    }
}


text:
package com.edinarobotics.zeke.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.command.WaitCommand;

public class AutonomousCommand extends CommandGroup {

    public AutonomousCommand(boolean twoBallAuto) {
        if (twoBallAuto) {
            CommandGroup driveSubsequence = new CommandGroup();
            driveSubsequence.addSequential(new WaitCommand(0.75));
            driveSubsequence.addSequential(new DriveXTimeCommand(0.5, 0.35));

            this.addSequential(new ShootingSequenceCommand(false));
            this.addParallel(new LowerShooterAfterWaitCommand(1.5));
            this.addParallel(driveSubsequence);
            this.addSequential(new RunCollectorCommand(3.5, true));
            this.addSequential(new ShootingSequenceCommand(false));
            this.addParallel(new LowerShooterAfterWaitCommand(1.5));
            this.addSequential(new WaitCommand(0.5));
            this.addSequential(new DriveXTimeCommand(3.5, 0.35));
        } else {
            this.addSequential(new ShootingSequenceCommand(false));
            this.addParallel(new LowerShooterAfterWaitCommand(1.5));
            this.addSequential(new WaitCommand(0.5));
            this.addSequential(new DriveXTimeCommand(3.5, 0.35));
        }
    }
}


text:
/*
 * Changes for GemFireXD distributed data platform (some marked by "GemStone changes")
 *
 * Portions Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You
 * may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License. See accompanying
 * LICENSE file.
 */

package org.apache.derbyTesting.functionTests.tests.jdbcapi;

import java.io.File;
import java.security.AccessController;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestCase;
import org.apache.derbyTesting.junit.DatabasePropertyTestSetup;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.TestConfiguration;

import junit.framework.Test;
import junit.framework.TestSuite;

/**
*
* This test tests java.sql.Driver methods.
* Right now it just tests acceptsURL and some attributes
* Not tested in this test:
*   - Tests for getPropertyInfo
*   - tests for connection attributes
*/

public class DriverTest extends BaseJDBCTestCase {

    // DERBY-618 - Database name with spaces
    private static String DB_NAME_WITH_SPACES = "db name with spaces";

    /**
     * Set of additional databases for tests that
     * require a one-off database. The additional
     * database decorator wraps all the tests and phases.
     * They are only created if a test opens a
     * connection against them. In hard upgrade the test
     * must explictly upgrade the database.
     * The databases are shutdown at the end of each phase.
     */
    static final String[] ADDITIONAL_DBS = {
        DB_NAME_WITH_SPACES,
        "testcreatedb1",
        "testcreatedb2",
        "testcreatedb3",
        "'wombat'"
    };

    public DriverTest(String name) {
        super(name);
    }

    public static Test suite() {
        // java.sql.Driver is not supported with JSR169, so return empty suite
        if (JDBC.vmSupportsJSR169())
        {
            return new TestSuite(
                "DriverTest tests java.sql.Driver, not supported with JSR169");
        }
        TestSuite suite = new TestSuite("DriverTest");
        suite.addTest(baseSuite("DriverTest:embedded"));
            suite.addTest(TestConfiguration.clientServerDecorator(
                baseSuite("DriverTest:client")));
        return suite;
    }

    private static Test baseSuite(String name) {

        TestSuite suite = new TestSuite("DriverTest");
        setBaseProps(suite, new DriverTest("testDriverCompliantVersion"));
        setBaseProps(suite, new DriverTest("testAcceptsURL"));
        setBaseProps(suite, new DriverTest("testEmbeddedAttributes"));
        setBaseProps(suite, new DriverTest("testClientAttributes"));
        setBaseProps(suite, new DriverTest("testClientURL"));
        setBaseProps(suite, new DriverTest("testDbNameWithSpaces"));

        return suite;
    }

    private static void setBaseProps(TestSuite suite, Test test)
    {
        Properties dbprops = new Properties();

        // Use DatabasePropertyTestSetup to add some settings.
        // DatabasePropertyTestSetup uses SET_DATABASE_PROPERTY
        // so users are added at database level.
        // Note, that authentication is not switched on.
        dbprops.setProperty("gemfirexd.infolog.append", "true");
        dbprops.setProperty("gemfirexd.debug.true", "AuthenticationTrace");
        dbprops.setProperty("gemfirexd.user.APP", "xxxx");
        dbprops.setProperty("gemfirexd.user.testuser", "testpass");
        test = new DatabasePropertyTestSetup (test, dbprops, true);
        suite.addTest(test);
    }

    public void tearDown() throws Exception {
        // attempt to get rid of any left-over trace files
        AccessController.doPrivileged(new java.security.PrivilegedAction() {
            public Object run() {
                for (int i=0 ; i < 2 ; i++)
                {
                    String traceFileName = "trace" + (i+1) + ".out";
                    File traceFile = new File(traceFileName);
                    if (traceFile.exists())
                    {
                        // if it exists, attempt to get rid of it
                        traceFile.delete();
                    }
                }
                removeDatabases();
                return null;
            }

            // attempt to get rid of any databases.
            void removeDatabases()
            {
                for ( int i=0 ; i<ADDITIONAL_DBS.length ; i++)
                {
                    String dbName = ADDITIONAL_DBS[i];
                    //TestConfiguration config = TestConfiguration.getCurrent();
                    dbName = dbName.replace('/', File.separatorChar);
                    String dsh = BaseTestCase.getSystemProperty("gemfirexd.system.home");
                    if (dsh == null) {
                        fail("not implemented");
                    } else {
                        dbName = dsh + File.separator + dbName;
                    }
                    removeDirectory(dbName);
                }
            }

            void removeDirectory(String path)
            {
                final File dir = new File(path);
                removeDir(dir);
            }

            private void removeDir(File dir) {

                // Check if anything to do!
                // Database may not have been created.
                if (!dir.exists())
                    return;

                String[] list = dir.list();

                // Some JVMs return null for File.list() when the
                // directory is empty.
                if (list != null) {
                    for (int i = 0; i < list.length; i++) {
                        File entry = new File(dir, list[i]);

                        if (entry.isDirectory()) {
                            removeDir(entry);
                        } else {
                            entry.delete();
                            //assertTrue(entry.getPath(), entry.delete());
                        }
                    }
                }
                dir.delete();
                //assertTrue(dir.getPath(), dir.delete());
            }
        });
        super.tearDown();
    }

    /**
     * Load the driver and check java.sql.Driver.jdbcCompliant() and
     * driver.get*Version
     * @throws Exception
     */
    public void testDriverCompliantVersion() throws Exception
    {
        String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
        String url = TestConfiguration.getCurrent().getJDBCUrl(dbName);

        loadDriver();
        String defaultdburl = url + ";create=true";

        // Test that we loaded the right driver by making a connection
        Driver driver = DriverManager.getDriver(defaultdburl);
        Properties props = new Properties();
        props.put("user", "testuser");
        props.put("password", "testpass");
        Connection conn = DriverManager.getConnection(defaultdburl, props);
        // Driver should be jdbc compliant.
        assertTrue(driver.jdbcCompliant());

        // compare driver.get*Version() with DatabaseMetadata.getDriver*Version.
        DatabaseMetaData dbmd = conn.getMetaData();

        assertEquals(dbmd.getDriverMajorVersion(), driver.getMajorVersion());
        assertEquals(dbmd.getDriverMinorVersion(), driver.getMinorVersion());

        conn.close();
    }

    /**
     * Check that drivers accept the correct urls and reject those for other supported drivers.
     *
     * @throws SQLException, Exception
     */
    public void testAcceptsURL() throws SQLException, Exception {
        String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
        String orgurl = TestConfiguration.getCurrent().getJDBCUrl(dbName);

        loadDriver();
        String defaultdburl = orgurl + ";create=true";

        // Test that we loaded the right driver by making a connection
        Driver driver = DriverManager.getDriver(defaultdburl);

        int  frameworkOffset;
        int EMBEDDED_OFFSET = 0;
        int DERBYNETCLIENT_OFFSET = 1;
        if (usingDerbyNetClient())
            frameworkOffset = DERBYNETCLIENT_OFFSET;
        else // assume (usingEmbedded())
            frameworkOffset = EMBEDDED_OFFSET;

        // URLS to check.  New urls need to also be added to the acceptsUrl table
        //GemStone changes BEGIN
        //String EMBEDDED_URL = "jdbc:derby:";
        String EMBEDDED_URL = "jdbc:gemfirexd:";
        // GemStone changes END
        String INVALID_URL = "jdbc:db2j:";
        String hostName = TestConfiguration.getCurrent().getHostName();
        int port = TestConfiguration.getCurrent().getPort();
        String CLIENT_URL =
            "jdbc:derby://"+hostName+":"+port+"/"+dbName+";create=true";

        String[] urls = new String[]
        {
            EMBEDDED_URL,
            CLIENT_URL,
            INVALID_URL,
        };

        // Table that shows whether tested urls should return true for
        // acceptsURL under the given framework
        // The acceptsURLTable uses  the frameworkOffset column int he table
        // to check for valid results for each framework
        boolean[][] acceptsURLTable = new boolean[][]
        {
        // Framework/url      EMBEDDED     DERBYNETCLIENT
        /* EMBEDDED_URL*/  {   true      ,  false        },
        /* CLIENT_URL  */  {   false     ,  true         },
        /* INVALID_URL */  {   false     ,  false        }
        };

        for (int u = 0; u < urls.length;u++)
        {
            String url = urls[u];
            boolean expectedAcceptance = acceptsURLTable[u][frameworkOffset];
            boolean actualAcceptance = driver.acceptsURL(url);
            assertEquals(expectedAcceptance, actualAcceptance);
        }
    }

    /**
     * Tests that embedded attributes can be specified in either url or info
     * argument to connect
     * DERBY-530. Only valid for embedded driver and client.
     */
    public void testEmbeddedAttributes() throws SQLException
    {
        // JCC can't take embedded attributes in info or as normal url
        // attributes, so not tested here.
        if (usingDB2Client())
            return;

        String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
        String protocol =
            TestConfiguration.getCurrent().getJDBCClient().getUrlBase();
        if (usingDerbyNetClient())
            protocol = protocol + TestConfiguration.getCurrent().getHostName()
            + ":" + TestConfiguration.getCurrent().getPort() + "/";
        String url = TestConfiguration.getCurrent().getJDBCUrl(dbName);

        Properties info = new Properties();
        // create attribute as property
        info.setProperty("create","true");
        // networkserver / DerbyNetClient tags on create to url
        if (usingEmbedded())
            assertConnect(true, protocol + "testcreatedb1", info);
        else
            assertConnect(false, protocol + "testcreatedb1", info);

        // create attribute in url
        if (usingEmbedded())
            assertConnect(false, protocol + "testcreatedb2;create=true", null);
        else
            assertConnect(true, protocol + "testcreatedb2;create=true", null);

        // user/password in properties
        info.clear();
        info.setProperty("user","APP");
        info.setProperty("password", "xxxx");
        if (usingEmbedded())
            assertConnect(true, url, info);
        else
            assertConnect(false, url, info);

        // user/password  in url
        assertConnect(false,
            url + ";user=testuser;password=testpass", null);

        // user in url, password in property
        info.clear();
        info.setProperty("password","testpass");
        assertConnect(false, url + ";user=testusr",info);

        // different users in url and in properties. URL is the winner
        info.clear();
        info.setProperty("user","APP");
        info.setProperty("password","xxxx");
        assertConnect(false,
            url + ";user=testuser;password=testpass", null);

        // shutdown with properties
        info.clear();
        info.setProperty("shutdown","true");
        try {
            assertConnect(false, protocol + "testcreatedb1", info);
        } catch (SQLException se)
        {
            assertSQLState("08006", se);
        }

        // shutdown using url
        try {
            assertConnect(
                false, protocol + "testcreatedb2;shutdown=true", null);
        } catch (SQLException se)
        {
            assertSQLState("08006", se);
        }
    }

    /**
     * Tests that client side attributes cann be specified in either url or
     * as info argument to connect.
     * DERBY-530.
     */
    public void testClientAttributes() throws SQLException
    {
        if (!usingDerbyNetClient())
            return;

        String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
        String url = TestConfiguration.getCurrent().getJDBCUrl(dbName);

        Properties info = new Properties();
        String traceFile = "trace1.out";

        // traceFile attribute in url
        assertConnect(true, url + ";traceFile=" + traceFile, info);

        traceFile = "trace2.out";
        // traceFile attribute in property
        info.setProperty("traceFile",traceFile);
        assertConnect(false, url, info);
        assertTraceFilesExist();
        shutdownDB(url + ";shutdown=true", null);

        // Derby-974: test that connection sees default properties as well
        info.setProperty("create","true");
        Properties infoWithDefaults = new Properties(info);

        url = TestConfiguration.getCurrent().getJDBCUrl("testcreatedb3");
        assertConnect(false, url, infoWithDefaults);

        shutdownDB(url+";shutdown=true", null);

    }

    /**
     * Check that trace files exist
     */
    private static void assertTraceFilesExist()
    {

        AccessController.doPrivileged(new java.security.PrivilegedAction() {
            public Object run() {
                for (int i=0 ; i < 2 ; i++)
                {
                    String traceFileName = "trace" + (i+1) + ".out";
                    File traceFile = new File(traceFileName);
                    //System.out.println("user.dir=" + System.getProperty("user.dir"));
                    //System.out.println("fullpath = " + traceFile.getAbsolutePath());
                        assertTrue(traceFile.exists());
                }
                return null;
            }
        });
    }

    /**
     * Tests client URLs to see connection is successful or the correct exception is thrown.
     */
    public void testClientURL() throws SQLException {
        if (!usingDerbyNetClient())
            return;

        String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
        String protocol =
            TestConfiguration.getCurrent().getJDBCClient().getUrlBase();
        if (usingDerbyNetClient())
            protocol = protocol + TestConfiguration.getCurrent().getHostName()
            + ":" + TestConfiguration.getCurrent().getPort() + "/";

        Properties info = null;     //test with null Properties object

        String CLIENT_CREATE_URL_WITH_COLON1 =
            protocol + dbName + ":create=true";
        //String CLIENT_CREATE_URL_WITH_COLON2 = protocol + DERBY_SYSTEM_HOME +
        //   File.separator + dbName + ":create=true";
        // String CLIENT_CREATE_URL_WITH_DOUBLE_QUOTES1 =
        //     protocol + "\"" + dbName + "\";create=true";
        // String CLIENT_CREATE_URL_WITH_DOUBLE_QUOTES2 = protocol + "\"" +
        //     DERBY_SYSTEM_HOME + File.separator + dbName + "\";create=true";
        // String CLIENT_CREATE_URL_WITH_SINGLE_QUOTES1 = protocol + "'" +
        //     DERBY_SYSTEM_HOME + File.separator + dbName + "';create=true";
        String CLIENT_CREATE_URL_WITH_SINGLE_QUOTES2 =
            protocol + "'" + dbName + "';create=true";

        String CLIENT_SHUT_URL_WITH_SINGLE_QUOTES2 =
            protocol + "'" + dbName + "';shutdown=true";

        //Client URLS
        String[] clientCreateUrls = new String[]
        {
            CLIENT_CREATE_URL_WITH_COLON1,
            //CLIENT_URL_WITH_COLON2,
            //CLIENT_URL_WITH_DOUBLE_QUOTES1,
            //CLIENT_URL_WITH_DOUBLE_QUOTES2,
            //CLIENT_URL_WITH_SINGLE_QUOTES1,
            CLIENT_CREATE_URL_WITH_SINGLE_QUOTES2
        };

        for (int i = 0; i < clientCreateUrls.length;i++)
        {
            String url = clientCreateUrls[i];
            try{
                if (url.equals(CLIENT_CREATE_URL_WITH_COLON1))
                {
                    Driver driver = DriverManager.getDriver(url);
                    assertNull(driver.connect(url,info));
                }
                else
                    assertConnect(true, url, info);
            }
            catch(SQLException se){
                fail ("did not expect an exception");
            }
        }
        // shutdown the databases, which should get rid of all open connections
        // currently, there's only the one; otherwise, this could be done in
        // a loop.
        shutdownDB(
            CLIENT_SHUT_URL_WITH_SINGLE_QUOTES2 + ";shutdown=true", null);
    }

    /**
     * Tests URL with spaces in database name to check create and connect works.
     * (DERBY-618). Make sure that the specified database gets created. We need
     * to check this because even without the patch for DERBY-618, no exception
     * gets thrown when we try to connect to a database name with spaces.
     * Instead, client driver extracts the database name as the string before
     * the first occurence of space separator. Hence the database which gets
     * created is wrong. e.g, if we specified database name as
     * "db name with spaces", the database that got created by client driver
     * was "db", which was wrong. We can check this by checking the correct URL
     * is returned by call to conn.getMetaData().getURL(). This is currently
     * checked inside the testConnect method. We do not explicilty check the
     * database directory creation since this check fails in remote server
     * testing.
     *
     * @throws SQLException
     */
    public void testDbNameWithSpaces() throws SQLException {

        Properties info = null;
        String url = null;

        String protocol =
            TestConfiguration.getCurrent().getJDBCClient().getUrlBase();
        if (usingDerbyNetClient())
            protocol = protocol + TestConfiguration.getCurrent().getHostName()
            + ":" + TestConfiguration.getCurrent().getPort() + "/";
        else if (usingDB2Client())
            protocol = protocol + "net:" +
            TestConfiguration.getCurrent().getHostName() + ":" +
            TestConfiguration.getCurrent().getPort() + "/";

        url = protocol + DB_NAME_WITH_SPACES + ";create=true";
        String shuturl = protocol + DB_NAME_WITH_SPACES + ";shutdown=true";

        assertConnect(false, url, null);
        shutdownDB(shuturl, null);
    }

    /**
     * Do java.sql.Driver.connect(String url, Properties info call)
     *
     * @param expectUrlEqualsGetUrl boolean indicating embedded would
     *                  expect the url passed in to equal metadata.getURL()
     * @param url       url to pass to Driver.connect()
     * @param info      properties to pass to Driver.Connect()
     *
     * @throws SQLException on error.
     */
    private static void assertConnect(
        boolean expectUrlEqualsGetUrl, String url, Properties info)
    throws SQLException
    {
        Driver driver = DriverManager.getDriver(url);

        Connection conn = driver.connect(url, info);
        assertNotNull(conn);

        if (expectUrlEqualsGetUrl)
            assertEquals(url, conn.getMetaData().getURL());
        else
            assertNotSame(url, conn.getMetaData().getURL());
        ResultSet rs =
            conn.createStatement().executeQuery("VALUES(CURRENT SCHEMA)");
        rs.next();
        assertEquals(
            rs.getString(1), conn.getMetaData().getUserName().toUpperCase());
        rs.close();
        conn.close();
        return;
    }

    /**
     * use this method to shutdown databases in an effort to release
     * any locks they may be holding
     */
    private static void shutdownDB(String url, Properties info) throws SQLException {

        Driver driver = DriverManager.getDriver(url);
        try {
            driver.connect(url, info);
        } catch (SQLException se) {
            assertSQLState("08006", se);
        }
    }

    /**
       Load the appropriate driver for the current framework
     */
    private static void loadDriver()
    {
        String driverClass =
            TestConfiguration.getCurrent().getJDBCClient().getJDBCDriverName();
        try {
            Class.forName(driverClass).newInstance();
        } catch (Exception e) {
            fail ("could not instantiate driver");
        }
    }
}


text:
<customView xmlns="http://labkey.org/data/xml/queryCustomView">
    <columns>
        <column name="Id"/>
        <column name="Relationship"/>
        <column name="Sibling"/>
        <column name="Sibling/Dataset/Demographics/gender">
            <properties>
                <property name="columnTitle" value="Sibling Gender"/>
            </properties>
        </column>
        <column name="Sibling/Dataset/Demographics/calculated_status">
            <properties>
                <property name="columnTitle" value="Sibling Status"/>
            </properties>
        </column>
        <column name="SiblingDam"/>
        <column name="SiblingSire"/>
   </columns>
   <sorts>
       <sort column="Id" />
   </sorts>
</customView>


text:
<meta http-equiv="Content-Language" content="en-us">
<meta name="GENERATOR" content="Microsoft FrontPage 12.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Introducing Wintermute Engine Development Kit</title>
<link rel="stylesheet" type="text/css" href="../styles.css">

Introducing Wintermute Engine Development Kit

Introduction

Welcome! Wintermute Engine Development Kit is a
set of tools for creating and running graphical adventure games. The kit
includes the runtime interpreter (Wintermute Engine, or WME) and GUI editors for
managing and creating the game content (WME tools) as well as this
documentation, demonstrational data and prefabricated templates.

Where to start

The WME documentation is divided into several sections. There's the
Inside a game chapter, which describes the various
game objects and principles. It also includes the
Scene tutorial, which describes the creation of a game scene step by step;
you should read that one first.

Next large section is the Scripting chapter,
which includes scripting basics and also a complete
reference guide for the game objects.

Essential resources on the web

Whenever you need further assistance, visit the
WME Forum, the primary
support channel.
Also be sure to visit
WME Resource Center, an online
archive of articles, tutorials, links etc.

metamorphium's excellent
WME Book is available online. While this documentation is
mostly a reference guide, the WME Book will teach you many concepts in a
readable and fun way. Be sure to check the
WME
Book Online.

General information about the engine

WME features

WME architecture

System requirements

Supported file formats

[Version 1.10.1 beta, July 19 2012]


text:
package org.wso2.andes.server.logging;

public class NullRootMessageLogger extends AbstractRootMessageLogger
{

    @Override
    public boolean isMessageEnabled(LogActor actor, LogSubject subject, String logHeirarchy)
    {
        return false;
    }

    @Override
    public boolean isMessageEnabled(LogActor actor, String logHierarchy)
    {
        return false;
    }

    public void rawMessage(String message, String logHierarchy)
    {
        // drop message
    }

    public void rawMessage(String message, Throwable throwable, String logHierarchy)
    {
        // drop message
    }
}


text:
import pytest
from django.urls import reverse
from rest_framework.status import HTTP_200_OK, HTTP_302_FOUND

from auth.tests.factories import UserFactory
from projects.models import ProjectPermission
from projects.views.projects.tests import setup, login, user_permissions_test_manage

@pytest.mark.django_db
def test_user_permissions_for_project_manage_access():
    user, organization, project, client = setup()
    user_permissions_test_manage(
        view='projects:manage_access',
        client=client,
        user=user,
        organization=organization,
        project=project,
        args=[project.pk]
    )

@pytest.mark.django_db
def test_project_manage_access():
    user, organization, project, client = setup()
    # Add superuser so the other user can be seen.
    user.is_superuser = True
    user.save()
    project.add_manage(user)
    assert login(client, user)

    other_user = UserFactory()

    # Valid create case
    assert project.can_create(other_user) == False
    response = client.post(
        path=reverse('projects:manage_access', args=[project.pk]),
        data={
            'can_create_{0}'.format(other_user.pk): True,
        },
        follow=True
    )
    assert response.redirect_chain[0][0] == reverse('projects:manage_access', args=[project.pk])
    assert response.redirect_chain[0][1] == HTTP_302_FOUND
    assert project.can_create(other_user) == True

    # Remove Create
    response = client.post(
        path=reverse('projects:manage_access', args=[project.pk]),
        data={
            'none_{0}'.format(other_user.pk): True,
        },
        follow=True
    )
    assert response.redirect_chain[0][0] == reverse('projects:manage_access', args=[project.pk])
    assert response.redirect_chain[0][1] == HTTP_302_FOUND
    assert project.can_create(other_user) == False

    # Valid invite case
    assert project.can_invite(other_user) == False
    response = client.post(
        path=reverse('projects:manage_access', args=[project.pk]),
        data={
            'can_invite_{0}'.format(other_user.pk): True,
        },
        follow=True
    )
    assert response.redirect_chain[0][0] == reverse('projects:manage_access', args=[project.pk])
    assert response.redirect_chain[0][1] == HTTP_302_FOUND
    assert project.can_invite(other_user) == True

    # Remove invite
    response = client.post(
        path=reverse('projects:manage_access', args=[project.pk]),
        data={
            'none_{0}'.format(other_user.pk): True,
        },
        follow=True
    )
    assert response.redirect_chain[0][0] == reverse('projects:manage_access', args=[project.pk])
    assert response.redirect_chain[0][1] == HTTP_302_FOUND
    assert project.can_invite(other_user) == False

    # Valid manage case
    assert project.can_manage(other_user) == False
    response = client.post(
        path=reverse('projects:manage_access', args=[project.pk]),
        data={
            'can_manage_{0}'.format(other_user.pk): True,
        },
        follow=True
    )
    assert response.redirect_chain[0][0] == reverse('projects:manage_access', args=[project.pk])
    assert response.redirect_chain[0][1] == HTTP_302_FOUND
    assert project.can_manage(other_user) == True

    # Remove manage
    response = client.post(
        path=reverse('projects:manage_access', args=[project.pk]),
        data={
            'none_{0}'.format(other_user.pk): True,
        },
        follow=True
    )
    assert response.redirect_chain[0][0] == reverse('projects:manage_access', args=[project.pk])
    assert response.redirect_chain[0][1] == HTTP_302_FOUND
    assert project.can_manage(other_user) == False

@pytest.mark.django_db
def test_project_manage_access_no_data():
    user, organization, project, client = setup()
    project.add_manage(user)
    assert login(client, user)

    # Send an invalid payload
    response = client.post(
        path=reverse('projects:manage_access', args=[project.pk]),
        data={
        },
        follow=True
    )
    assert response.status_code == HTTP_200_OK


text:
package hr.fer.zemris.vhdllab.applets.editor.schema2.model.commands;

import hr.fer.zemris.vhdllab.applets.editor.schema2.enums.EErrorTypes;
import hr.fer.zemris.vhdllab.applets.editor.schema2.enums.EPropertyChange;
import hr.fer.zemris.vhdllab.applets.editor.schema2.exceptions.InvalidCommandOperationException;
import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ICommand;
import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ICommandResponse;
import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaComponent;
import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaInfo;
import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaWire;
import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.Caseless;
import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.ChangeTuple;
import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.SchemaError;
import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.SchemaPort;
import hr.fer.zemris.vhdllab.applets.editor.schema2.model.CommandResponse;

public class PlugWireCommand implements ICommand {

	/* static fields */
	public static final String COMMAND_NAME = "ConnectWireCommand";

	/* private fields */
	private Caseless cmpname, wirename, portname;

	/* ctors */

	public PlugWireCommand(Caseless componentName, Caseless schemaWireName, Caseless schemaPortName) {
		cmpname = componentName;
		wirename = schemaWireName;
		portname = schemaPortName;
	}

	/* methods */

	public String getCommandName() {
		return COMMAND_NAME;
	}

	public boolean isUndoable() {
		return false;
	}

	public ICommandResponse performCommand(ISchemaInfo info) {
		ISchemaComponent cmp = info.getComponents().fetchComponent(cmpname);

		if (cmp == null) return new CommandResponse(new SchemaError(EErrorTypes.NONEXISTING_COMPONENT_NAME,
				"Component with name '" + cmpname.toString() + "' could not be found."));
		if (cmp.isInvalidated()) return new CommandResponse(
				new SchemaError(EErrorTypes.COMPONENT_INVALIDATED, "Component with name '" +
						cmpname.toString() + "' is invalidated."));

		ISchemaWire wire = info.getWires().fetchWire(wirename);

		if (wire == null) return new CommandResponse(new SchemaError(EErrorTypes.NONEXISTING_WIRE_NAME,
				"Wire with name '" + wirename.toString() + "' could not be found."));

		SchemaPort port = cmp.getSchemaPort(portname);

		if (port == null) return new CommandResponse(new SchemaError(EErrorTypes.NONEXISTING_PORT_NAME,
				"Port '" + portname.toString() + "' could not be found on component '" + cmpname.toString() + "'."));

		if (!Caseless.isNullOrEmpty(port.getMapping())) return new CommandResponse(new SchemaError(EErrorTypes.MAPPING_ERROR,
				"Port '" + portname.toString() + "' already mapped to wire '" + port.getMapping().toString() + "'."));

		port.setMapping(wire.getName());

		return new CommandResponse(new ChangeTuple(EPropertyChange.CANVAS_CHANGE));
	}

	public ICommandResponse undoCommand(ISchemaInfo info)
			throws InvalidCommandOperationException
	{
		ISchemaComponent cmp = info.getComponents().fetchComponent(cmpname);

		if (cmp == null) return new CommandResponse(new SchemaError(EErrorTypes.NONEXISTING_COMPONENT_NAME,
				"Component with name '" + cmpname.toString() + "' could not be found."));

		ISchemaWire wire = info.getWires().fetchWire(wirename);

		if (wire == null) return new CommandResponse(new SchemaError(EErrorTypes.NONEXISTING_WIRE_NAME,
				"Wire with name '" + wirename.toString() + "' could not be found."));

		SchemaPort port = cmp.getSchemaPort(portname);

		if (port == null) return new CommandResponse(new SchemaError(EErrorTypes.NONEXISTING_PORT_NAME,
				"Port '" + portname.toString() + "' could not be found on component '" + cmpname.toString() + "'."));

		if (port.getMapping() == null) return new CommandResponse(new SchemaError(EErrorTypes.MAPPING_ERROR,
				"Port '" + portname.toString() + "' not mapped to anything - cannot undo."));

		port.setMapping(null);

		return new CommandResponse(new ChangeTuple(EPropertyChange.CANVAS_CHANGE));
	}

}


text:
package org.eclipse.ceylon.compiler.java.codegen;

import static org.eclipse.ceylon.compiler.java.codegen.AbstractTransformer.isPinnedType;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.ceylon.compiler.typechecker.tree.Node;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree;
import org.eclipse.ceylon.compiler.typechecker.tree.Visitor;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.AnyAttribute;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.AttributeArgument;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.AttributeSetterDefinition;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.ForComprehensionClause;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.ForIterator;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.FunctionArgument;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.FunctionalParameterDeclaration;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.LazySpecifierExpression;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.MethodArgument;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.PatternIterator;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.SpecifierExpression;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.SpecifierStatement;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.StatementOrArgument;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.Term;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.ValueIterator;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.Variable;
import org.eclipse.ceylon.compiler.typechecker.tree.TreeUtil;
import org.eclipse.ceylon.model.loader.JvmBackendUtil;
import org.eclipse.ceylon.model.typechecker.context.TypeCache;
import org.eclipse.ceylon.model.typechecker.model.Class;
import org.eclipse.ceylon.model.typechecker.model.ClassOrInterface;
import org.eclipse.ceylon.model.typechecker.model.Declaration;
import org.eclipse.ceylon.model.typechecker.model.Function;
import org.eclipse.ceylon.model.typechecker.model.FunctionOrValue;
import org.eclipse.ceylon.model.typechecker.model.Functional;
import org.eclipse.ceylon.model.typechecker.model.Parameter;
import org.eclipse.ceylon.model.typechecker.model.Setter;
import org.eclipse.ceylon.model.typechecker.model.Type;
import org.eclipse.ceylon.model.typechecker.model.TypeParameter;
import org.eclipse.ceylon.model.typechecker.model.TypedDeclaration;
import org.eclipse.ceylon.model.typechecker.model.Value;

public abstract class BoxingDeclarationVisitor extends Visitor {

    protected abstract boolean isCeylonBasicType(Type type);
    protected abstract boolean isNull(Type type);
    protected abstract boolean isObject(Type type);
    protected abstract boolean isCallable(Type type);

    /**
     * Depends on:
     * - type arguments and their declarations
     * - the chain of refined declarations
     * - erasure of the selected refined declaration
     * Does not depend on boxing/erased/untrusted
     */
    protected abstract TypedDeclaration getRefinedDeclarationForWideningRules(TypedDeclaration typedDeclaration);

    /**
     * Depends on:
     * - union/intersection declaration
     * - class being erased to Object by a list of cases
     * - type parameter bounds being erased to Object by a list of cases
     * Does not depend on boxing/erased/untrusted
     */
    protected abstract boolean hasErasure(Type type);

    /**
     * Depends on:
     * - union/intersection declaration
     * - class being erased to Object by a list of cases
     * Does not depend on boxing/erased/untrusted
     */
    protected abstract boolean willEraseToObject(Type type);

    /**
     * Depends on the type arguments being:
     * - erased union/intersections based on their declarations
     * - variance info
     * - nothing types
     * - qualified types
     * Does not depend on boxing/erased/untrusted
     */
    protected abstract boolean isRaw(Type type);

    /**
     * Depends on:
     * - type arguments and their declarations
     * - the chain of refined declarations
     * - erasure of the selected refined declaration
     * Does not depend on boxing/untrusted
     */
    protected abstract boolean isWideningTypedDeclaration(TypedDeclaration typedDeclaration);

    /**
     * Depends on:
     * - isRaw
     * - class being erased to Object by a list of cases
     * - the inheritance change with isRaw
     * - inter-dependent type parameters
     * Does not depend on boxing/erased/untrusted
     */
    protected abstract boolean hasSubstitutedBounds(Type type);

    /**
     * This is used to keep track of some optimisations we do, such as inlining the following shortcuts:
     * class X() extends T(){ m = function() => e; } and we need to be able to map back the lambda with
     * the method it specifies, for boxing and all
     */
    private Map<Function,Function> optimisedMethodSpecifiersToMethods = new HashMap<Function, Function>();

    // This is mostly just for testing purposes. Using -Dceylon.compiler.forceBoxedLocals=true
    // on the command line you can force all locals to be boxed (instead of the default unboxed)
    private static final boolean forceBoxedLocals = Boolean.getBoolean("ceylon.compiler.forceBoxedLocals");

    @Override
    public void visit(FunctionArgument that) {
        super.visit(that);
        that.getDeclarationModel().setUnboxed(false);
    }

    @Override
    public void visit(MethodArgument that) {
        super.visit(that);
        that.getDeclarationModel().setUnboxed(false);
    }

    @Override
    public void visit(Tree.MethodDeclaration that) {
        super.visit(that);
        Function model = that.getDeclarationModel();
        visitMethod(that.getDeclarationModel(), that);
        SpecifierExpression specifierExpression = that.getSpecifierExpression();
        // See ClassTransformer.transformSpecifiedMethodBody for this logic
        if(model != null
                && model.isMember()
                && specifierExpression != null
                && specifierExpression.getExpression() != null){
            boolean isLazy = specifierExpression instanceof Tree.LazySpecifierExpression;
            Term term = TreeUtil.unwrapExpressionUntilTerm(specifierExpression.getExpression());
            if (!isLazy && term instanceof Tree.FunctionArgument) {
                // this is inlined for member methods, so the term should inherit our boxing specs
                Function specifierModel = ((Tree.FunctionArgument)term).getDeclarationModel();
                if(specifierModel != null){
                    specifierModel.setUnboxed(model.getUnboxed());
                }
            }
        }
    }

    @Override
    public void visit(Tree.MethodDefinition that) {
        super.visit(that);
        visitMethod(that.getDeclarationModel(), that);
    }

    private void visitMethod(Function method, Node that) {
        boxMethod(method, that);
        rawTypedDeclaration(method);
        setErasureState(method);
    }

    @Override
    public void visit(FunctionalParameterDeclaration that) {
        if (Strategy.createMethod(that.getParameterModel())) {
            // Box the functional parameter as if it were a method
            visitMethod((Function)that.getParameterModel().getModel(), that);
            // Visit the parameters of the functional parameter
            that.visitChildren(this);
        } else {
            super.visit(that);
        }
    }

    private void setErasureState(TypedDeclaration decl) {
        // deal with invalid input
        if(decl == null)
            return;

        Type type = decl.getType();
        boolean erased = false;
        boolean untrusted = false;
        if(type != null){
            if(hasErasure(type) || hasSubstitutedBounds(type) || type.isTypeConstructor()){
                erased = true;
            }
            if(decl.isActual()
                    && decl.getContainer() instanceof ClassOrInterface){
                TypedDeclaration refinedDeclaration = getRefinedDeclarationForWideningRules(decl);
                if(refinedDeclaration != null
                        && refinedDeclaration != decl
                        && decl.getUntrustedType() == null){
                    // make sure the refined decl is set before we look at it
                    setErasureState(refinedDeclaration);
                }
                // make sure we did not lose type information due to non-widening
                if(isWideningTypedDeclaration(decl)){
                    // widening means not trusting the type, otherwise we end up thinking that the type is
                    // something it's not and regular erasure rules don't apply there
                    untrusted = true;
                    erased = true;
                }
            }
        }
        decl.setTypeErased(erased);
        if (isPinnedType(decl)) {
            untrusted = true;
        }
        decl.setUntrustedType(untrusted);
    }

    private void rawTypedDeclaration(TypedDeclaration decl) {
        // deal with invalid input
        if(decl == null)
            return;

        Type type = decl.getType();
        if(type != null){
            if(isRaw(type)) {
                if (type.isCached()) {
                    Type clone = type.clone();
                    clone.setRaw(true);
                    decl.setType(clone);
                } else {
                    type.setRaw(true);
                }
            }
        }
    }

    private void boxMethod(Function method, Node that) {
        // deal with invalid input
        if(method == null)
            return;
        Declaration refined = CodegenUtil.getTopmostRefinedDeclaration(method, optimisedMethodSpecifiersToMethods);
        // deal with invalid input
        if(refined == null
                || (!(refined instanceof Function)))
            return;
        TypedDeclaration refinedMethod = (TypedDeclaration)refined;
        if (method.getName() != null) {
            // A Callable, which never have primitive parameters
            setBoxingState(method, refinedMethod, that);
        } else {
            // Anonymous methods are always boxed
            method.setUnboxed(false);
        }
    }

    private void setBoxingState(TypedDeclaration declaration, TypedDeclaration refinedDeclaration, Node that) {
        Type type = declaration.getType();
        if(type == null){
            // an error must have already been reported
            return;
        }
        // fetch the real refined declaration if required
        if (Decl.equal(declaration, refinedDeclaration)
                && declaration instanceof FunctionOrValue
                && ((FunctionOrValue)declaration).isParameter()
                && declaration.getContainer() instanceof Class){
            // maybe it is really inherited from a field?
            FunctionOrValue methodOrValueForParam = (FunctionOrValue)declaration;
            if(methodOrValueForParam != null){
                // make sure we get the refined version of that member
                refinedDeclaration = (TypedDeclaration) methodOrValueForParam.getRefinedDeclaration();
            }
        }

        // inherit underlying type constraints
        if(!Decl.equal(refinedDeclaration, declaration)){
            // simple case
            if(type.getUnderlyingType() == null
                && refinedDeclaration.getType() != null) {
                if (type.isCached()) {
                    type = type.clone();
                }
                type.setUnderlyingType(refinedDeclaration.getType().getUnderlyingType());
                declaration.setType(type);
            }
            // special case for variadics
            if(Decl.isValueParameter(refinedDeclaration)){
                Parameter parameter = ((FunctionOrValue) refinedDeclaration).getInitializerParameter();
                if(parameter.isSequenced()){
                    // inherit the underlying type of the iterated type
                    Type refinedIteratedType = refinedDeclaration.getType().getTypeArgumentList().get(0);
                    if(refinedIteratedType.getUnderlyingType() != null){
                        Type ourIteratedType = type.getTypeArgumentList().get(0);
                        if(ourIteratedType.getUnderlyingType() == null){
                            if (ourIteratedType.isCached()) {
                                ourIteratedType = ourIteratedType.clone();
                            }
                            ourIteratedType.setUnderlyingType(refinedIteratedType.getUnderlyingType());
                            type.getTypeArgumentList().set(0, ourIteratedType);
                            // make sure we remove those types from the cache otherwise UGLY things happen
                            TypeCache cache = type.getDeclaration().getUnit().getCache();
                            if(cache != null){
                                cache.remove(ourIteratedType);
                                cache.remove(type);
                            }
                        }
                    }
                }
            }
        }

        // abort if our boxing state has already been set
        if(declaration.getUnboxed() != null)
            return;

        // functional parameter return values are always boxed if we're not creating a method for them
        if(declaration instanceof Function
                && ((Function)declaration).isParameter()
                && !JvmBackendUtil.createMethod((Function)declaration)){
            declaration.setUnboxed(false);
            return;
        }

        if (!Decl.equal(refinedDeclaration, declaration)) {
            // make sure refined declarations have already been set
            if(refinedDeclaration.getUnboxed() == null)
                setBoxingState(refinedDeclaration, refinedDeclaration, that);
            // inherit
            declaration.setUnboxed(refinedDeclaration.getUnboxed());
        } else if (declaration instanceof Function
                && Strategy.useBoxedVoid((Function)declaration)
                && !(refinedDeclaration.getTypeDeclaration() instanceof TypeParameter)
                && !CodegenUtil.isContainerFunctionalParameter(refinedDeclaration)
                && !(refinedDeclaration instanceof Functional && Decl.isMpl((Functional)refinedDeclaration))){
            declaration.setUnboxed(false);
        } else if((isCeylonBasicType(type) || Decl.isUnboxedVoid(declaration))
           && !(refinedDeclaration.getTypeDeclaration() instanceof TypeParameter)
           && (refinedDeclaration.getContainer() instanceof Declaration == false || !CodegenUtil.isContainerFunctionalParameter(refinedDeclaration))
           && !(refinedDeclaration instanceof Functional && Decl.isMpl((Functional)refinedDeclaration))){
            boolean unbox = !forceBoxedLocals || !(declaration instanceof Value) || !Decl.isLocal(declaration) || Decl.isParameter(declaration) || Decl.isTransient(declaration);
            // if we're a synthetic variable with unchecked nulls, don't force the null check
            // until it's used later by user code
            if(declaration.getOriginalDeclaration() != null
                    && declaration.hasUncheckedNullType())
                unbox = false;
            declaration.setUnboxed(unbox);
        } else if (Decl.isValueParameter(declaration)
                && CodegenUtil.isContainerFunctionalParameter(declaration)
                && JvmBackendUtil.createMethod((FunctionOrValue)declaration.getContainer())) {
            Function functionalParameter = (Function)declaration.getContainer();
            TypedDeclaration refinedFrom = (TypedDeclaration)CodegenUtil.getTopmostRefinedDeclaration(functionalParameter, optimisedMethodSpecifiersToMethods);
            if (Decl.equal(refinedFrom, functionalParameter) ) {
                // Don't consider Anything to be unboxed, since this is a parameter
                // not a method return type (where void would be considered unboxed).
                if (declaration.getUnit().getAnythingType().isExactly(declaration.getType())
                        || declaration.getUnit().isOptionalType(declaration.getType())) {
                    declaration.setUnboxed(false);
                } else {
                    declaration.setUnboxed(true);
                }
            } else {
                // make sure refined declarations have already been set
                if(refinedFrom.getUnboxed() == null)
                    setBoxingState(refinedFrom, refinedFrom, that);
                // inherit
                declaration.setUnboxed(refinedFrom.getUnboxed());
            }
        } else {
            declaration.setUnboxed(false);
        }

        // Any "@boxed" or "@unboxed" compiler annotation overrides
        boxFromAnnotation(declaration, that);
    }

    private void boxAttribute(TypedDeclaration declaration, Node that) {
        // deal with invalid input
        if(declaration == null)
            return;
        TypedDeclaration refinedDeclaration = null;
        refinedDeclaration = (TypedDeclaration)CodegenUtil.getTopmostRefinedDeclaration(declaration, optimisedMethodSpecifiersToMethods);
        // deal with invalid input
        if(refinedDeclaration == null)
            return;
        setBoxingState(declaration, refinedDeclaration, that);
    }

    private void boxFromAnnotation(TypedDeclaration declaration, Node that) {
        // Let's see if the attribute has a "boxed" or "unboxed" annotation
        // and set its state accordingly. NB this is not checked for validity!
        if(that instanceof StatementOrArgument) {
            if(CodegenUtil.hasCompilerAnnotation((StatementOrArgument)that, "boxed")) {
                declaration.setUnboxed(false);
            } else if(CodegenUtil.hasCompilerAnnotation((StatementOrArgument)that, "unboxed")) {
                declaration.setUnboxed(true);
            }
        }
    }

    @Override
    public void visit(Tree.Parameter that) {
        super.visit(that);
        TypedDeclaration declaration = that.getParameterModel().getModel();
        visitAttributeOrParameter(declaration, that);
    }

    @Override
    public void visit(Tree.ValueParameterDeclaration that) {
        super.visit(that);
    }

    @Override
    public void visit(AnyAttribute that) {
        super.visit(that);
        TypedDeclaration declaration = that.getDeclarationModel();
        visitAttributeOrParameter(declaration, that);
    }

    private void visitAttributeOrParameter(TypedDeclaration declaration, Node that) {
        boxAttribute(declaration, that);
        rawTypedDeclaration(declaration);
        setErasureState(declaration);
    }

    @Override
    public void visit(AttributeDeclaration that) {
        if(that.getSpecifierOrInitializerExpression() != null
                && that.getDeclarationModel() != null
                && that.getType() instanceof Tree.ValueModifier
                && that.getDeclarationModel().getType().equals(that.getSpecifierOrInitializerExpression().getExpression().getTypeModel())){
            that.getDeclarationModel().setType(that.getDeclarationModel().getType().withoutUnderlyingType());
        }
        super.visit(that);
    }

    @Override
    public void visit(AttributeArgument that) {
        super.visit(that);
        boxAttribute(that.getDeclarationModel(), that);
    }

    @Override
    public void visit(AttributeSetterDefinition that) {
        super.visit(that);
        Setter declaration = that.getDeclarationModel();
        // deal with invalid input
        if(declaration == null)
            return;
        // To determine boxing for a setter we use its parameter
        TypedDeclaration paramDeclaration = declaration.getParameter().getModel();
        boxAttribute(paramDeclaration, that);
        // Now copy the settings from the parameter to the setter itself
        declaration.setUnboxed(paramDeclaration.getUnboxed());
        // Then we check if there are any overriding compiler annotations
        boxFromAnnotation(declaration, that);
        // And finally we copy the setting back again to make sure they're really the same
        paramDeclaration.setUnboxed(declaration.getUnboxed());
    }

    @Override
    public void visit(Variable that) {
        super.visit(that);
        TypedDeclaration declaration = that.getDeclarationModel();
        // deal with invalid input
        if(declaration == null)
            return;
        setBoxingState(declaration, declaration, that);
        rawTypedDeclaration(declaration);
        setErasureState(declaration);
    }

    @Override
    public void visit(SpecifierStatement that) {
        TypedDeclaration declaration = that.getDeclaration();
        Function optimisedDeclaration = null;
        // make sure we detect the shortcut refinement inlining cases
        if(declaration instanceof Function){
            if(that.getSpecifierExpression() != null
                    && that.getSpecifierExpression() instanceof LazySpecifierExpression == false){
                Tree.Term term = TreeUtil.unwrapExpressionUntilTerm(that.getSpecifierExpression().getExpression());
                if(term != null
                        && term instanceof Tree.FunctionArgument){
                    optimisedDeclaration = ((Tree.FunctionArgument)term).getDeclarationModel();
                    this.optimisedMethodSpecifiersToMethods.put(optimisedDeclaration, (Function) declaration);
                }
            }
        }
        try{
            super.visit(that);
        }finally{
            if(optimisedDeclaration != null)
                this.optimisedMethodSpecifiersToMethods.remove(optimisedDeclaration);
        }
        if(declaration == null)
            return;
        if(declaration instanceof Function){
            visitMethod((Function) declaration, that);
        }else if(declaration instanceof Value)
            visitAttributeOrParameter(declaration, that);
    }

    @Override
    public void visit(ForComprehensionClause that) {
        super.visit(that);
        // sort of a hack, because normal visiting rules would declare iterator variables to be potentially
        // unboxed, but the implementation always boxes them for now, so override it after we visit the comprehension
        ForIterator iter = that.getForIterator();
        if (iter instanceof ValueIterator) {
            // The exception to the "always boxed for now" rule is Java arrays
            Type typeModel = iter.getSpecifierExpression().getExpression().getTypeModel();
            ((ValueIterator) iter).getVariable().getDeclarationModel().setUnboxed(
                    (iter.getUnit().isJavaArrayType(typeModel) && ((ValueIterator) iter).getVariable().getDeclarationModel().getType().isSubtypeOf(iter.getUnit().getObjectType())));
        } else if (iter instanceof PatternIterator) {
            boxPattern(((PatternIterator) iter).getPattern());
        }
    }

    private void boxPattern(Tree.Pattern pattern) {
        if (pattern instanceof Tree.KeyValuePattern) {
            boxPattern(((Tree.KeyValuePattern)pattern).getKey());
            boxPattern(((Tree.KeyValuePattern)pattern).getValue());
        } else if (pattern instanceof Tree.TuplePattern) {
            for (Tree.Pattern p : ((Tree.TuplePattern)pattern).getPatterns()) {
                boxPattern(p);
            }
        } else if (pattern instanceof Tree.VariablePattern) {
            ((Tree.VariablePattern)pattern).getVariable().getDeclarationModel().setUnboxed(false);
        } else {
            throw BugException.unhandledNodeCase(pattern);
        }
    }

    @Override
    public void visit(Tree.TypeParameterDeclaration that) {
        super.visit(that);
        TypeParameter typeParameter = that.getDeclarationModel();
        if(typeParameter != null){
            visitTypeParameter(typeParameter);
        }
    }

    private void visitTypeParameter(TypeParameter typeParameter) {
        if(typeParameter.hasNonErasedBounds() != null)
            return;
        for(Type pt : typeParameter.getSatisfiedTypes()){
            if(!willEraseToObject(pt)){
                typeParameter.setNonErasedBounds(true);
                return;
            }
        }
        typeParameter.setNonErasedBounds(false);
        return;
    }

    // The following are not really necessary under normal circumstances,
    // they explicitly set what is already set by default, but when using
    // the -Dceylon.compiler.forceBoxedLocals option they are needed

    @Override
    public void visit(ValueIterator that) {
        super.visit(that);
        // The variable in a for over a Range is always unboxed
        if (that.getVariable() != null && that.getSpecifierExpression().getExpression().getTerm() instanceof Tree.RangeOp) {
            that.getVariable().getDeclarationModel().setUnboxed(true);
        }
    }
}


text:
"use strict";
var MetricsGatherer_1 = require("MetricsGatherer");
var NodeEvents;
(function (NodeEvents) {
    var DEBUG = true;
    /**
     * Calling this will walk the components in the provided node and if the component has the eventName as function
     * on it, will call it.  Ideally, this will be replaced by the native Atomic sendEvent/subscribeToEvent, but this works for now.
     * Additionally, if a component has a function called "onAny", that will be called with the event name
     * @method
     * @param {Node} node the node to trigger the event on
     * @param {string} eventName the name of the event to call
     * @param {Any} args arguments to pass on through to the event handler
     * @return {Array} an array of all the results, if there are any, otherwise an empty array
     */
    function trigger(node, eventName, data) {
        if (DEBUG) {
            MetricsGatherer_1.default.start(eventName);
        }
        var results = [];
        var components = node.getComponents("JSComponent");
        var _loop_1 = function() {
            var component = components[c];
            // Look for the the doAction method and call it if it exists
            if (component && typeof component["doAction"] === "function") {
                setImmediate(function () {
                    component["doAction"].apply(component, [eventName, data]);
                });
            }
        };
        for (var c = 0, cLen = components.length; c < cLen; c++) {
            _loop_1();
        }
    }
    NodeEvents.trigger = trigger;
    /**
     * Calling this will walk the components in the provided node and if the component has the eventName as function
     * on it, will call it.  Ideally, this will be replaced by the native Atomic sendEvent/subscribeToEvent, but this works for now.
     * Additionally, if a component has a function called "onAny", that will be called with the event name
     * @method
     * @param {Node} node the node to trigger the event on
     * @param {string} eventName the name of the event to call
     * @param {Any} args arguments to pass on through to the event handler
     * @return {Array} an array of all the results, if there are any, otherwise an empty array
     */
    function triggerSync(node, eventName, data) {
        if (DEBUG) {
            MetricsGatherer_1.default.start(eventName);
        }
        var results = [];
        var components = node.getComponents("JSComponent");
        for (var c = 0, cLen = components.length; c < cLen; c++) {
            var component = components[c];
            // Look for the the doAction method and call it if it exists
            if (component && typeof component["doAction"] === "function") {
                var r = component["doAction"].apply(component, [eventName, data]);
                // Capture the results
                if (typeof (r) !== "undefined") {
                    results.push(r);
                }
            }
        }
        return results;
    }
    NodeEvents.triggerSync = triggerSync;
})(NodeEvents || (NodeEvents = {}));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = NodeEvents;


text:
package fyj.engine.core;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;

public class MainView extends GLSurfaceView {

	private static final String LOG_TAG = MainView.class.getSimpleName();

	private MyRenderer myRenderer;

	public MainView(Context context) {
		super(context);
		requestFocus();
		setEGLConfigChooser(new MultisampleConfigChooser());
		myRenderer = new MyRenderer(context);
		setRenderer(myRenderer);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		return myRenderer.keyEvent(event);

		/*
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			switch (event.getKeyCode()) {
			case KeyEvent.KEYCODE_DPAD_LEFT:

				break;
			case KeyEvent.KEYCODE_DPAD_RIGHT:

				break;
			case KeyEvent.KEYCODE_DPAD_UP:

				break;
			case KeyEvent.KEYCODE_DPAD_DOWN:

				break;
			default:
				return false;
			}
			queueEvent(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub

				}
			});
			return true;
		}

		return false;
		*/
	}

	public void createMenu(Menu menu) {
		myRenderer.createMenu(menu);
	}

	public void onMenuItemSelected(MenuItem item) {
		myRenderer.onMenuItemSelected(item);
	}

}


text:
<?php
namespace Edu\Cnm\Flek\Test;

use Edu\Cnm\Flek\{
	Image, Profile, Genre
};

// grab the class under scrutiny
require_once("FlekTest.php");

//grab the class
require_once(dirname(__DIR__) . "/public_html/php/classes/autoload.php");

/**
 * Full PHPUnit test for the Image class
 *
 * This is a complete PHPUnit test of the Image class. It is complete because *ALL* mySQL/PDO enabled methods
 * are tested for both invalid and valid inputs.
 *
 * @see Image
 * @author Diane Peshlakai <dpeshlakai3@cnm.edu>
 */
class ImageTest extends FlekTest {

	/*
	 * description of the uploaded image
	 * @var string $valid_imagedescription
	 */
	protected $VALID_IMAGEDESCRIPTION = "Image test is still passing!";
	/*
	 * secure url of the image
	 * @var string $VALID_IMAGESECUREURL
	 */
	protected $VALID_IMAGESECUREURL = "DKJFKFKJ34245435";

	/*
	 * public id for the image uploaded
	 * @var string $VALID_IMAGEPUBLICID
	 */
	protected $VALID_IMAGEPUBLICID = "DKJF23409340939404040";

	/*
	 * genre id for image uploaded
	 * @var int $VALID_IMAGEGENREID
	 */
	protected $genre = null;
	/*
		protected $VALID_IMAGEGENREID2 = null;*/

	/**
	 * profile that creates image; this is for the foreign key relations
	 * @var PROFILE profile
	 **/
	protected $profile = null;

	protected $image = null;

	private $hash;

	private $salt;

	/**
	 * create dependent objects before running each test
	 **/
	public final function setUp() {
		//run the default setUp() method first
		parent::setup();

		$this->VALID_PROFILEACCESSTOKEN = bin2hex(random_bytes(16));
		$this->VALID_PROFILEACTIVATIONTOKEN = bin2hex(random_bytes(16));
		$password = "abc123";
		$salt = bin2hex(random_bytes(32));
		$hash = hash_pbkdf2("sha256", $password, $this->salt, 262144);

		$this->profile = new Profile(null, "csosa4", "foo@bar.com", "Rio, Rancho", "test is passing", $hash, $salt, "01234567890", "01234567890123456789012345678901");
		$this->profile->insert($this->getPDO());

		//	$this->image = new Image(null, "csosa4", "foo@bar.com", "Rio, Rancho", "test is passing", $this->hash, $this->salt, "01234567890", "01234567890123456789012345678901");
		//	$this->profile->insert($this->getPDO());//

		$this->genre = new Genre (null, "modern");
		$this->genre->insert($this->getPDO());
	}

	/**
	 * test inserting a valid Image and verify that the actual mySQL data matches
	 *
	 *
	 **/
	public function testInsertValidImage() {
		//count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("image");

		//create a new image and insert to into mySQL
		$image = new Image(null, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION, $this->VALID_IMAGESECUREURL, $this->VALID_IMAGEPUBLICID);

		$image->insert($this->getPDO());

		//grab the data from mySQL and enforce the fields match our expectations
		$pdoImage = Image::getImageByImageId($this->getPDO(), $image->getImageId());

		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("image"));
		$this->assertEquals($pdoImage->getImageGenreId(), $this->genre->getGenreId());
		$this->assertEquals($pdoImage->getImageProfileId(), $this->profile->getProfileId());
		$this->assertEquals($pdoImage->getImageDescription(), $this->VALID_IMAGEDESCRIPTION);
		$this->assertEquals($pdoImage->getImageSecureUrl(), $this->VALID_IMAGESECUREURL);
		$this->assertEquals($pdoImage->getImagePublicId(), $this->VALID_IMAGEPUBLICID);
		/*$this->assertEquals($pdoImage->getImageGenreId(), $this->genre->getGenreId());*/
	}

	/**
	 * test inserting a image that already exists
	 *
	 * @expectedException PDOException
	 */
	public function testInsertInvalidImage() {
		//create a image with a non null image id and watch it fail
		$image = new Image(ImageTest::INVALID_KEY, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION,
			$this->VALID_IMAGESECUREURL, $this->VALID_IMAGEPUBLICID);
		$image->insert($this->getPDO());

	}

	/**
	 * test inserting a image, editing it and then updating it
	 */
	public function testUpdateValidImage() {
		//count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("image");
		//create a new Image and insert to into mySQL
		$image = new Image(null, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION,
			$this->VALID_IMAGEPUBLICID, $this->VALID_IMAGESECUREURL);

		$image->insert($this->getPDO());

		$image->setImageGenreId($this->genre->getGenreId());
		$image->setImageProfileId($this->profile->getProfileId()
		);
		$image->setImageDescription($this->VALID_IMAGEDESCRIPTION);
		$image->setImageSecureUrl($this->VALID_IMAGESECUREURL);
		$image->setImagePublicId($this->VALID_IMAGEPUBLICID);

		//edit the Image and update it in mySQL
		$image->update($this->getPDO());

		//grab the data from mySQL and enforce the fields match our expectations
		$pdoImage = Image::getImageByImageId($this->getPDO(), $image->getImageId());
		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("image"));
		$this->assertEquals($pdoImage->getImageGenreId(), $this->genre->getGenreId());
		$this->assertEquals($pdoImage->getImageProfileId(), $this->profile->getProfileId());
		$this->assertEquals($pdoImage->getImageDescription(), $this->VALID_IMAGEDESCRIPTION);
		$this->assertEquals($pdoImage->getImageSecureUrl(), $this->VALID_IMAGESECUREURL);
		$this->assertEquals($pdoImage->getImagePublicId(), $this->VALID_IMAGEPUBLICID);

	}

	/**
	 * test updating a Image that already exists
	 *
	 * @expectedException PDOException
	 */
	public function testUpdateInvalidImage() {
		//create a Image, try to update it without actually updating it and watch it fail
		$image = new Image(null, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION, $this->VALID_IMAGESECUREURL, $this
			->VALID_IMAGEPUBLICID);
		$image->update($this->getPDO());
	}

	/**
	 * test creating a Image and then deleting it
	 */
	public function testDeleteValidImage() {
		//count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("image");

		//create a new Image and insert to into mySQL
		$image = new Image(null, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION, $this->VALID_IMAGESECUREURL,
			$this->VALID_IMAGEPUBLICID);
		$image->insert($this->getPDO());

		//delete the Image from mySQL
		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("image"));
		$image->delete($this->getPDO());

		//grab the data from mySQL and enforce the Tweet does not exist
		$pdoImage = Image::getImageByImageId($this->getPDO(), $image->getImageId());
		$this->assertNull($pdoImage);
		$this->assertEquals($numRows, $this->getConnection()->getRowCount("image"));

	}

	/**
	 * test deleting a Image that does not exist
	 *
	 * @expectedException PDOException
	 */
	public function testDeleteInvalidImage() {
		//create a Image and try to delete it without actually inserting it
		$image = new Image(null, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION, $this->VALID_IMAGESECUREURL,
			$this->VALID_IMAGEPUBLICID);
		$image->delete($this->getPDO());
	}

	public function testGetImageByImageProfileId() {
		//count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("image");
		//create a new Image and insert to into mySQL
		$image = new Image(null, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION, $this->VALID_IMAGESECUREURL,
			$this->VALID_IMAGEPUBLICID, null);
		$image->insert($this->getPDO());

		//grab the data from mySQL and enforce the fields to match our expectations
		$pdoImages = Image::getImageByImageProfileId($this->getPDO(), $image->getImageProfileId());
		foreach($pdoImages as $pdoImage) {
			$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("image"));
			$this->assertEquals($pdoImage->getImageGenreId(),
				$this->genre->getGenreId());
			$this->assertEquals($pdoImage->getImageProfileId(),
				$this->profile->getProfileId());
			$this->assertEquals($pdoImage->getImageDescription(),
				$this->VALID_IMAGEDESCRIPTION);
			$this->assertEquals($pdoImage->getImageSecureUrl(),
				$this->VALID_IMAGESECUREURL);
			$this->assertEquals($pdoImage->getImagePublicId(),
				$this->VALID_IMAGEPUBLICID);
		}
	}

	/**
	 * test getting images by Profile Id
	 *
	 */

	/**
	 * test inserting a Image and regrabbing it from mySQL
	 */
	public function testGetValidImageByImageId() {
		//count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("image");
		//create a new Image and insert to into mySQL
		$image = new Image(null, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION, $this->VALID_IMAGESECUREURL,
			$this->VALID_IMAGEPUBLICID, null);
		$image->insert($this->getPDO());

		//grab the data from mySQL and enforce the fields to match our expectations
		$pdoImage = Image::getImageByImageId($this->getPDO(), $image->getImageId());
		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("image"));
		$this->assertEquals($pdoImage->getImageGenreId(),
			$this->genre->getGenreId());
		$this->assertEquals($pdoImage->getImageProfileId(),
			$this->profile->getProfileId());
		$this->assertEquals($pdoImage->getImageDescription(),
			$this->VALID_IMAGEDESCRIPTION);
		$this->assertEquals($pdoImage->getImageSecureUrl(),
			$this->VALID_IMAGESECUREURL);
		$this->assertEquals($pdoImage->getImagePublicId(),
			$this->VALID_IMAGEPUBLICID);

	}

	/**
	 * test grabbing a Image that does not exist
	 */
	public function testGetInvalidImageByImageId() {
		//grab a profile id that exceeds the maxiumum allowable image profile id
		$image = Image::getImageByImageId($this->getPDO(), FlekTest::INVALID_KEY);
		$this->assertNull($image);
	}

	/**
	 * test grabbing a Image by Image description
	 */
	public function testGetValidImageByImageDescription() {
		//count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("image");

		//create a new Image and insert to into mySQL
		$image = new Image(null, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION, $this->VALID_IMAGESECUREURL,
			$this->VALID_IMAGEPUBLICID);
		$image->insert($this->getPDO());
		//grab the data from mySQL and enforce the fields match our expectations
		$results = Image::getImageByImageDescription($this->getPDO(), $image->getImageDescription());
		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("image"));
		$this->assertCount(1, $results);
		$this->assertContainsOnlyInstancesOf("Edu\\Cnm\\Flek\\Image", $results);

		/**
		 * grab the result from the array and validate it
		 */
		$pdoImage = $results[0];
		$this->assertEquals($pdoImage->getImageGenreId(), $this->genre->getGenreId());
		$this->assertEquals($pdoImage->getImageProfileId(), $this->profile->getProfileId());
		$this->assertEquals($pdoImage->getImageDescription(), $this->VALID_IMAGEDESCRIPTION);
		$this->assertEquals($pdoImage->getImageSecureUrl(), $this->VALID_IMAGESECUREURL);
		$this->assertEquals($pdoImage->getImagePublicId(), $this->VALID_IMAGEPUBLICID);

	}

	/**
	 * test grabbing a Image by description that does not exist
	 */
	public function testGetInvalidImageByImageDescription() {
		//grab a image by searching for content that does not exist
		$image = Image::getImageByImageDescription($this->getPDO(), "there will be nothing");
		$this->assertCount(0, $image);
	}

	/**
	 * test grabbing all Images
	 */
	public function testGetAllValidImages() {
		//count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("image");

		//create a new Image and insert to into mySQL
		$image = new Image(null, $this->genre->getGenreId(), $this->profile->getProfileId(), $this->VALID_IMAGEDESCRIPTION, $this->VALID_IMAGESECUREURL,
			$this->VALID_IMAGEPUBLICID);
		$image->insert($this->getPDO());

		//grab the data from myQL and enforced the field match our expectations
		$results = Image::getAllImages($this->getPDO());
		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("image"));
		$this->assertCount(1, $results);
		$this->assertContainsOnlyInstancesOf("Edu\\Cnm\\Flek\\Image", $results);

		//grab the result from the array and validate it
		$pdoImage = $results[0];

		$this->assertEquals($pdoImage->getImageProfileId(), $this->profile->getProfileId());
		$this->assertEquals($pdoImage->getImageDescription(), $this->VALID_IMAGEDESCRIPTION);
		$this->assertEquals($pdoImage->getImageSecureUrl(), $this->VALID_IMAGESECUREURL);
		$this->assertEquals($pdoImage->getImagePublicId(), $this->VALID_IMAGEPUBLICID);

	}
}