text:
define([
	"intern!object",
	"intern/chai!assert",
	"delite/register",
	"delite/HasDropDown",
	"delite/Widget",
	"../functional/helpers"
], function (registerSuite, assert, register, HasDropDown, Widget, helpers) {
	var container;

	// ------------
	// Test widgets.  Also used by functional/HasDropDown.html.   Could share the code between them.

	var Menu = register("d-hasdropdown-menu", [HTMLElement, Widget], {
		choice1: "1",
		choice2: "2",
		choice3: "3",

		render: function () {
			this.className = "choice";

			this.on("click", this.emit.bind(this, "change"));

			for (var i = 1; i < 4; i++) {
				this.innerHTML += "
choice #" + this["choice" + i] + "
";
			}
		}
	});

	// A button that shows a popup
	var SimpleDropDownButton = register("simple-drop-down-button", [HTMLButtonElement, HasDropDown], {
		label: "",
		_setLabelAttr: function (val) {
			this.textContent = val;
			this._set("label", val);
		},

		loadDropDown: function () {
			if (!this._dropDown) {
				this._dropDown = new this.dropDownConstructor({
					className: this.dropDownClass || "basic-dropdown"
				});
				if (this.id) {
					this._dropDown.id = this.id + "_popup";
				}
			}

			return this._dropDown;
		}
	});

	registerSuite({
		name: "HasDropDown",
		setup: function () {
			container = document.createElement("div");
			document.body.appendChild(container);
		},

		// Note: most of the HasDropDown tests are in tests/functional

		basic: function () {
			// basic drop down with menu
			var sdd = new SimpleDropDownButton({
				id: "dd",
				label: "basic",
				dropDownConstructor: Menu,
				focusOnPointerOpen: false	// traditionally you only focus drop down menus when opened by the keyboard
			}).placeAt(container);

			return sdd.openDropDown().then(function () {
				var popup = document.getElementById("dd_popup");
				assert(helpers.isVisible(popup), "visible");

				sdd.closeDropDown();
				assert.isFalse(helpers.isVisible(popup), "not visible");
			});
		},

		detach: function () {
			// basic drop down with menu
			var sdd = new SimpleDropDownButton({
				id: "dd2",
				label: "detach",
				dropDownConstructor: Menu,
				focusOnPointerOpen: false	// traditionally you only focus drop down menus when opened by the keyboard
			}).placeAt(container);

			return sdd.openDropDown().then(function () {
				var popup = document.getElementById("dd2_popup");
				assert(helpers.isVisible(popup), "visible");

				sdd.closeDropDown();
				assert.isFalse(helpers.isVisible(popup), "not visible");

				sdd.parentNode.removeChild(sdd);
				register.deliver();
				assert.isFalse(document.body.contains(popup), "removeChild() detaches popup too");

				container.appendChild(sdd);
				return sdd.openDropDown().then(function () {
					assert(document.body.contains(popup), "openDropDown() reattaches popup");
					assert(helpers.isVisible(popup), "visible");
				});
			});
		},

		teardown: function () {
			container.parentNode.removeChild(container);
		}
	});
});


text:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="robots" content="index, follow, all" />
        <title>Thelia\Core\Event\Image | </title>
                    <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css">
                            </head>
        </html>

redpajama_set_name: RedPajamaGithub


text:
Pull requests are more than welcome! There are very few rules, and here they
are:

- Write [beautiful commit messages](http://chris.beams.io/posts/git-commit/).
- JavaScript code adheres to the [Airbnb style
  guide](https://github.com/airbnb/javascript).
- HTML attributes should be on separate lines, and indented, like this:

```html
<!-- bad -->
<my-custom-element id="special" class="snowflake" animation-status={{animationStatus}}></my-custom-element>

<!-- good -->
<my-custom-element
  id="special"
  class="snowflake"
  animation-status={{animationStatus}}>
</my-custom-element>
```


text:
WordPress Fauxgo

## Fight the Fake Logo (Fauxgo)

Friends don't let friends use the wrong WordPress logo. If you see one of these in the wild, please gun it down.


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- 基于@Aspect切面的驱动器 -->
    <aop:aspectj-autoproxy/>

    <bean class="com.cenyol.example.model.aspectj.PerformanceImpl"/>

    <!-- 要记得把切面类也配置到bean容器中,不然待会怎么调用 -->
    <bean id="audience" class="com.cenyol.example.model.aspectj.Audience" />

    <!-- 通过xml定义切面 -->
    <aop:config>
        <aop:aspect ref="audience">
            <aop:pointcut id="perform"
                expression="execution(* com.cenyol.example.model.aspectj.Performance.perform(..))" />

            <aop:before method="silenceCellPhones"
                pointcut-ref="perform"/>

            <aop:before method="takeSeats"
                pointcut-ref="perform"/>

            <aop:after-returning method="applause"
                pointcut="execution(* com.cenyol.example.model.aspectj.Performance.perform(..))"/>

            <aop:after-throwing method="demandRefund"
                pointcut="execution(* com.cenyol.example.model.aspectj.Performance.perform(..))"/>
        </aop:aspect>
    </aop:config>

</beans>


text:
namespace statemachinecreator::gui {

FWD_SMART_P(ISceneController)

}


text:
package main;

import java.util.Scanner;

public class QuadraticEquationRoots
{

	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);

		System.out.print("Enter a, b, and c: ");
		double a = input.nextDouble();
		double b = input.nextDouble();
		double c = input.nextDouble();

		double discriminant = (b * b) - (4 * a * c);

		if (discriminant < 0)
		{
			System.out.println("The equation has no roots");
		}
		else
		{
			double root1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);

			if (discriminant == 0)
			{
				System.out.println("The root is " + root1);
			}
			else
			{
				double root2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a);
				System.out.println("The roots are " + root1 + " and " + root2);
			}
		}

		input.close();
	}

}


text:
package jteller;

import jteller.stubs.Perro;

import org.junit.Test;

public class TellerAcceptanceTests {

	@Test
	public void queEmiteInforme() {
		System.out.println(new Teller(Perro.class).tell());
	}
}


text:
The Game Cleaner feature deletes resources that you're not using in your game. Specifically, it deletes resources that used to be a part of your game (you deleted them from the app),
but for whatever reason, still exist in your game's folder.

## How to Run the Game Cleaner

The Game Cleaner is located in the app's main menu via **Debug > Game > Cleanup Unused Files...**.

> We recommend backing up your game before using this feature.

## Notes

> This feature **DOES NOT REDUCE THE FINAL SIZE OF YOUR EXPORTED GAMES**.
>
> This feature only affects the on-disk size of the game.


text:
package net.spy.memcached.vbucket;

import net.spy.memcached.vbucket.config.Bucket;

public interface ConfigurationProvider {

    /**
     * Connects to the REST service and retrieves the bucket configuration from the first pool available
     * @param bucketname bucketname
     * @return vbucket configuration
     * @throws ConfigurationException
     */
    Bucket getBucketConfiguration(String bucketname) throws ConfigurationException;

    /**
     * Subscribes for configuration updates
     * @param bucketName bucket name to receive configuration for
     * @param rec reconfigurable that will receive updates
     * @throws ConfigurationException
     */
    void subscribe(String bucketName, Reconfigurable rec) throws ConfigurationException;

    /**
     * Unsubscribe from updates on a given bucket and given reconfigurable
     * @param vbucketName bucket name
     * @param rec reconfigurable
     */
    void unsubscribe(String vbucketName, Reconfigurable rec);

    /**
     * Shutdowns a monitor connections to the REST service
     */
    void shutdown();

    /**
     * Retrieves a default bucket name i.e. 'default'
     * @return
     */
    String getAnonymousAuthBucket();
}


text:
  #include "common.h"

  AtNode *createInstanceNode(nodeData &nodata, userData * ud, int i);

#endif


text:
import IECore

import Gaffer
import GafferUI

class BoxPlugValueWidget( GafferUI.PlugValueWidget ) :

	def __init__( self, plug, **kw ) :

		self.__column = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Vertical, spacing=4 )

		GafferUI.PlugValueWidget.__init__( self, self.__column, plug, **kw )

		with self.__column :
			GafferUI.PlugValueWidget.create( plug["min"] )
			GafferUI.PlugValueWidget.create( plug["max"] )

	def setPlug( self, plug ) :

		assert( len( plug ) == len( self.getPlug() ) )

		GafferUI.PlugValueWidget.setPlug( self, plug )

		self.__column[0].setPlug( plug["min"] )
		self.__column[1].setPlug( plug["max"] )

	def setHighlighted( self, highlighted ) :

		GafferUI.PlugValueWidget.setHighlighted( self, highlighted )

		for c in self.__column :
			c.setHighlighted( highlighted )

	def setReadOnly( self, readOnly ) :

		if readOnly == self.getReadOnly() :
			return

		GafferUI.PlugValueWidget.setReadOnly( self, readOnly )

		for c in self.__column :
			c.setReadOnly( readOnly )

	def childPlugValueWidget( self, childPlug, lazy=True ) :

		for w in self.__column :
			if childPlug.isSame( w.getPlug() ) :
				return w

		return None

	def _updateFromPlug( self ) :

		pass

GafferUI.PlugValueWidget.registerType( Gaffer.Box2fPlug, BoxPlugValueWidget )
GafferUI.PlugValueWidget.registerType( Gaffer.Box3fPlug, BoxPlugValueWidget )
GafferUI.PlugValueWidget.registerType( Gaffer.Box2iPlug, BoxPlugValueWidget )
GafferUI.PlugValueWidget.registerType( Gaffer.Box3iPlug, BoxPlugValueWidget )


text:
Rails.application.routes.draw do
  mount SpecScoreRegistry::Engine => "/registry"
end


text:
describe 'When deploying' do
  let(:deploy_manager) do
    Slipway::DeployManager.new(args: {}, options: [],
                               app_envs: Slipway::AppEnv.build_envs)
  end

  it 'should run a basic deploy' do
    expect(deploy_manager.deploy!).to include('** Deploy Successful! **')
  end
end


text:
XVEMGUM ;DJB/VGL**Scroll Messages [2/24/99 10:39am];2017-08-15  12:49 PM
 ;;14.1;VICTORY PROG ENVIRONMENT;;Aug 16, 2017
 ; Original Code authored by David J. Bolduc 1985-2005
 ;
MSG(NUM,PAUSE) ;Messages
 ;NUM=Subroutine number  PAUSE=Pause screen
 Q:$G(NUM)'>0
 S DX=0,DY=XVVT("S2")+XVVT("FT")-2
 D CURSOR^XVEMKU1(DX,DY,1),@NUM
 S DX=0,DY=DY+1 I $G(PAUSE) X XVVS("CRSR") D PAUSE^XVEMKU(0)
 Q
 ;====================================================================
1 W $C(7),"Enter number from left hand column." Q
2 W $C(7),"This node is not viewable." Q
3 W $C(7),"Node not viewable. Isn't in standard Fileman format." Q
4 W $C(7),"You don't have access. See Help option." Q
5 W $C(7),"You can't use this option while reverse video is active." Q
6 W $C(7),"No editing while ",$S($G(FLAGVPE)["VEDD":"VEDD",1:"VRR")," is running" Q
7 W $C(7),"You can't edit in an alternate session." Q
8 W $C(7),"You're already doing a code search!?" Q
9 W $C(7),"There is no data to be searched" Q
10 W $C(7),"Only 1 Alternate Session allowed." Q
11 W $C(7),"No Alternate Session allowed when ",$S($G(FLAGVPE)["VEDD":"VEDD",1:"VRR")," is running" Q
12 W $C(7),"Invalid. This node already exists." Q
13 W $C(7),"Subscript is greater than 127 characters" Q
14 W $C(7),"You may not edit a null node" Q
15 W $C(7),"Invalid selection ('%' Node)." Q
16 W $C(7),"Invalid selection (File of files not viewable)." Q
17 W $C(7),"This is not a valid node." Q
18 W $C(7),"VA Filemanager must be present to run this option." Q
19 W "Enter number from left hand column, or a range of numbers (Ex: 3-5)" Q
20 W $C(7),"Invalid range" Q
21 W "Enter new node to hold SAved code. Hit <TAB> to quit." Q
22 W $C(7),"No code has been saved." Q
23 W $C(7),"You may NOT edit the subscript of a node that has decendents" Q
24 W "After editing a range of nodes, exit and reenter VGL to see your changes." Q
25 W "No control characters found." Q
26 W "This node has control characters. Use SC to strip them out before editing." Q


text:
module Facts
  module Freebsd
    module Memory
      module Swap
        class UsedBytes
          FACT_NAME = 'memory.swap.used_bytes'

          def call_the_resolver
            fact_value = Facter::Resolvers::Freebsd::SwapMemory.resolve(:used_bytes)
            Facter::ResolvedFact.new(FACT_NAME, fact_value)
          end
        end
      end
    end
  end
end


text:
#ifndef CLICK_AVERAGECOUNTER_HH
#define CLICK_AVERAGECOUNTER_HH
#include <click/element.hh>
#include <click/ewma.hh>
#include <click/atomic.hh>
#include <click/timer.hh>
CLICK_DECLS

/*
 * =c
 * AverageCounter([IGNORE])
 * =s counters
 * measures historical packet count and rate
 * =d
 *
 * Passes packets unchanged from its input to its
 * output, maintaining statistics information about
 * packet count and packet rate using a strict average.
 *
 * The rate covers only the time between the first and
 * most recent packets.
 *
 * IGNORE, by default, is 0. If it is greater than 0,
 * the first IGNORE number of seconds are ignored in
 * the count.
 *
 * =h count read-only
 * Returns the number of packets that have passed through since the last reset.
 *
 * =h byte_count read-only
 * Returns the number of packets that have passed through since the last reset.
 *
 * =h rate read-only
 * Returns packet arrival rate.
 *
 * =h byte_rate read-only
 * Returns packet arrival rate in bytes per second.  (Beware overflow!)
 *
 * =h reset write-only
 * Resets the count and rate to zero.
 */

class AverageCounter : public Element { public:

    AverageCounter();
    ~AverageCounter();

    const char *class_name() const		{ return "AverageCounter"; }
    const char *port_count() const		{ return PORTS_1_1; }
    int configure(Vector<String> &, ErrorHandler *);

    uint32_t count() const			{ return _count; }
    uint32_t byte_count() const			{ return _byte_count; }
    uint32_t first() const			{ return _first; }
    uint32_t last() const			{ return _last; }
    uint32_t ignore() const			{ return _ignore; }
    void reset();

    int initialize(ErrorHandler *);
    void add_handlers();

    Packet *simple_action(Packet *);

  private:

    atomic_uint32_t _count;
    atomic_uint32_t _byte_count;
    atomic_uint32_t _first;
    atomic_uint32_t _last;
    atomic_uint32_t _first_count;
    uint32_t _ignore;

};

CLICK_ENDDECLS
#endif


text:
group web_setter;

license() ::=<<
$!
Copyright 2012 Brian Hawkins
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.
!$
>>

convertMap ::= [
	"byte":"Byte",
	"int":"Int",
	"long":"Long",
	"boolean":"Boolean",
	"String":"String",
	"double":"Double",
	"byte[]":"Bytes",
	"java.math.BigDecimal":"BigDecimal",
	"java.sql.Date":"Date",
	"java.sql.Timestamp":"Timestamp",
	"java.util.UUID":"UUID",
	default:"null"
	]

fkeyConstraint(keyset) ::=<<
CONSTRAINT $keyset.constraintName$ FOREIGN KEY ($keyset.keys:{key | "$key.name$"}; separator=", "$)
	REFERENCES $keyset.tableName$ ($keyset.keys:{key | "$key.foreignTableColumnName$"}; separator=", "$)$if(keyset.hasOnDelete)$ ON DELETE $keyset.onDelete$$endif$$if(keyset.hasOnUpdate)$ ON UPDATE $keyset.onUpdate$$endif$
>>

tableCreate(table) ::= <<
CREATE TABLE $table.name$ (
	$table.columns:{col | "$col.name$" $col.sQLType$ $if(col.defaultSet)$DEFAULT '$col.default$'$endif$ $if(!col.allowNull)$NOT $endif$NULL}; separator=",\n"$$if(table.hasPrimaryKey)$,
	PRIMARY KEY ($table.primaryKeys:{key | "$key.name$"}; separator=", "$)$endif$$if(table.hasForeignKey)$,
	$table.foreignKeys:fkeyConstraint(); separator=",\n"$
	$endif$$if(table.hasUniqueColumns)$,
	$table.uniqueColumnSets:{colset | UNIQUE ($colset:{col | "$col.name$"}; separator=", "$)}; separator=",\n"$
	$endif$
	)

>>

class() ::= <<
/**
	Class added by WebFieldSetterPlugin
	This class provides a means to automatically set field data from a web post
*/
public static class WebFieldSetter
	{
	java.util.BitSet m_setFields = new java.util.BitSet();
	java.util.Map<String, String> m_fieldNames = new java.util.HashMap<String, String>();
	org.agileclick.genorm.plugins.web.WebFieldConverter m_converter;

	protected void init()
		{
		m_converter = new org.agileclick.genorm.plugins.web.DefaultWebFieldConverter();
		$columns:{col | m_fieldNames.put(COL_$col.nameCaps$, COL_$col.nameCaps$);
}$
		}

	/**
		You can override this method if you want to set default values
	*/
	protected String getFieldValue($table.className$ obj, String col, java.util.Map<String, String[]> data)
		{
		String[] values = data.get(m_fieldNames.get(col));
		String value = null;

		if (values != null && values.length >= 1)
			value = values[0];

		return (value);
		}

	public WebFieldSetter()
		{
		init();
		m_setFields.set(0, NUMBER_OF_COLUMNS);
		}

	/**
		Use this constructor to provide a list of field data meta.  The list of
		field meta is used as a filter, only meta listed will have their fields
		set.
	*/
	public WebFieldSetter(GenOrmFieldMeta... metaList)
		{
		init();
		for (GenOrmFieldMeta meta : metaList)
			m_setFields.set(meta.getDirtyFlag());
		}

	/**
		Sets the field converter to be used to convert string values from a post
		into values that can be set on the object.  If no converter is provided
		genorm.plugins.web.DefaultWebFieldConverter is used.

		@param converter Converter to use when setting fields.
	*/
	public WebFieldSetter setWebFieldConverter(org.agileclick.genorm.plugins.web.WebFieldConverter converter)
		{
		m_converter = converter;
		return (this);
		}

	$columns:{col | /**
	Sets the paramter name for the column $col.name$.  This name will be the expected
	key in data map in the call to setFields.
	The default is '$col.name$'
*/
public WebFieldSetter set$col.methodName$Field(String fieldName)
	{
	m_fieldNames.put(COL_$col.nameCaps$, fieldName);
	return (this);
	}

}$

	/**
		Sets the fields on obj with the values in data according to the filter
		that was specified in the constructor.
	*/
	public $table.className$ setFields($table.className$ obj, java.util.Map<String, String[]> data)
		{
		$columns:{col | if (m_setFields.get($col.nameCaps$_FIELD_META.getDirtyFlag()))
	{
	String value = getFieldValue(obj, COL_$col.nameCaps$, data);

	obj.set$col.methodName$(m_converter.to$convertMap.(col.type)$(COL_$col.nameCaps$, value));
	}

}$
		return (obj);
		}
	}

>>


text:
//Library descriptions:
//Needed to cache rooms on update routines
var fs = require('fs');
//Cause you know, express.js
var express = require('express');
//utilization
var app = express();
//We need this for requests
var http = require('http').Server(app);
//Sockets for the server
var io = require('socket.io')(http);

var get = require('http');

//stores the rooms and their properties
var rooms = {};

//rewrite of easier to manage room hastable values
//Hastable of room example
/*{
  description: 'description'
  duration: 'duration'
  password: 'password'
  chatLog: []
  users: []
}
*/

//BEGIN UPDATE ROUTINE MANAGER
//Workaround heroku's 1 hr idle period
setInterval(function() {
    get.get("http://www.stubz.tk");
}, 300000);

//END UPDATE ROUTINE

//TODO : Clean up files and folders, both are only here to easily develop the client
  app.use(express.static(__dirname + '/CleanClient'));
  app.use(express.static(__dirname + '/public'));

//BEGIN REQUEST HANDLER
  app.get('/chat', function(req, res){
        if(req.query.renewRoom != null){
            rooms[removeQuotes(req.query.renewRoom)].duration = 24;
            console.log("Renewing room "  + removeQuotes(req.query.renewRoom));
            res.sendFile(__dirname + '/renew.html');
            return;
        }

        if(req.query.createRoom != null){
          createRoom(removeQuotes(req.query.createRoom),
            removeQuotes(req.query.description),
            removeQuotes(req.query.lifetime));
            //Redirect the user to the room they just created
            res.statusCode = 302;
            res.setHeader("Location", '/chat?room=' + req.query.createRoom + '"');
            res.end();
        }
        res.sendFile(__dirname + '/CleanClient/CleanClient.html');
  });

  app.get('/', function(req, res){
      res.sendFile(__dirname + '/home.html');
  });

  app.get('/new', function(req, res){
      res.sendFile(__dirname + '/config.html');
  });

  //END REQUEST HANDLER

    //TODO remove createroom default
    createRoomSpecial('developer', 'Need help? Welcome to the developer chat room! ' +
    'Here I test out new features ' +
    'that are in development');
    createRoomSpecial('terminal', 'this is the admin console');
    createRoomSpecial('webapps', 'Welcome fellow redditors! Hope you enjoy this web application and leave a review in the comments');
    expirationManager();

//BEGIN CHAT SOCKET HANDLER
  io.on('connection', function(socket){
    socket.on('UserConnectionAttempt', function(room, nickname){
      //Meaningless debug
      if(room == null || nickname == null){
        return;
      }

      if(!hastableContains(rooms, room)){
        socket.emit('UserConnectionFailed', "roomNonExistant");
        return;
      }

      if(rooms[room] == null)
        return;

      if(rooms[room].users.indexOf(nickname) > -1){
        socket.emit('UserConnectionFailed', "nicknameExists");
        return;
      }
      console.log('User ' + nickname + ' is attempting to connect to ' +
        'room ' + room);

      socket.join(room);
      //Tell the room who has walked in ;)
      sendServerMessage(nickname + " has joined room " + room, room);
      io.to(room).emit('userJoin', nickname);
      //Chat logs, users, description
      socket.emit('init', rooms[room].chatLog, rooms[room].users, rooms[room].description);
      //get userList array and push
      rooms[room].users.push(nickname);

      socket.on('disconnect', function(){
        //if the room was already destroyed
        if(rooms[room].users == null)
          return;

        var userList = rooms[room].users;
        userList = removeElement(nickname, userList);
        rooms[room].users = userList;
        io.to(room).emit('userLeave', userList, nickname);
      });
    });
    socket.on('OnChatMessage', function(room, message, nickname){
      sendChatMessage(message, room, nickname);
      //Administrator commands, accessable only from the specified network
      //as well as the specified room
      if((room == "terminal" && socket.request.headers['x-forwarded-for'] == "24.44.9.139") || socket.handshake.address =="127.0.0.1"){
        var args = message.split("|");
        switch(args[0]){
          case '/sendToAll':
            console.log('Broadcasting ' + args[1] + ' to all rooms');
            for(var room in rooms){
              sendServerMessage(args[1], room);
            }
            break;
          case '/save':
            console.log('Begining update routine');
            for(var room in rooms){
              sendServerMessage('All chatlogs and rooms will now be saved ' +
              'prepare for server update', room);
            }
            var lineOne = "";

            for(var room in rooms){
              lineOne += room + ":" + rooms[room].description + ";";
            }

            sendChatMessage(lineOne, 'terminal', 'Server');
            break;
          case '/dispose':
            console.log('Disposing of all save chatlogs and rooms');
            for(var room in rooms){
              sendServerMessage('The update is finished. All chatlogs ' +
              'have been disposed of', room);
            }
            if(fs.exists(__dirname + "/tmp/vars.txt")){
            fs.unlink(__dirname + "/tmp/vars.txt", function (err) {
              if (err) throw err;
              console.log('Successfully deleted update cache');
            });
            }
            break;
          case '/renew':
            renew(args[1]);
            break;
          default:
            console.log(message);
            break;
        }
      }
    });

  });

  //END CHAT SOCKET HANDLER
//process.env.PORT is used by heroku to specify
//what port to run the webapp on
  http.listen(process.env.PORT || 5000, function(){
    console.log('listening on port 5000');
  });

  function createRoom(mRoom, mDescription, mExpiration){
    if(mExpiration > 48)
    mExpiration = 48;

    if(hastableContains(rooms, mRoom))
      return;

    console.log('Creating new room ' + mRoom);
    var roomData = {
      description: mDescription,
      duration: mExpiration,
      password: 'password',
      chatLog: [],
      users: []
    };
    rooms[mRoom] = roomData;
  }

  function createRoomSpecial(mRoom, mDescription){

    if(hastableContains(rooms, mRoom))
      return;

    console.log('Creating new special room ' + mRoom);
    var roomData = {
      description: mDescription,
      duration: 999999999999999,
      password: 'password',
      chatLog: [],
      users: []
    };
    rooms[mRoom] = roomData;
  }

  function removeElement(target, array){
    var i = array.indexOf(target);
    if(i != -1) {
      array.splice(i, 1);
    }
    return array;
  }

  function expirationManager(){
    console.log('Creating a new instance of the expirationManager');
    setInterval(function(){
      console.log('Running the expiration cycle');
      for (var key in rooms) {
        rooms[key].duration -= 1;
        if(rooms[key].duration <= 0){
          console.log("Room " + key + " has expired");
          io.emit()
          delete rooms[key];
          io.to(key).emit('OnRoomExpire');
        }
        else if(rooms[key].duration == 2){
          console.log('Room '  + key + ' is now renewable');
          io.to(key).emit('canRenew');
        }
      };
      //remove two more 0s
    }, 600000);
  }

  function sendServerMessage(message, room){
    io.to(room).emit('serverMessage', message);
  }

  function sendChatMessage(message, room, nickname){
    var timestamp = getTimestamp();
    //console.log(nickname + ' : ' + message + ' @ ' + timestamp);
    io.to(room).emit('chatMessage', message, nickname, timestamp);
    rooms[room].chatLog.push(message + "," + nickname + "," + timestamp);
  }

  function getTimestamp(){
    return new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
  }

  function hastableContains(hastable, value){
    return value in hastable;
  }

  function removeQuotes(string){
    if(string == null)
      return;

   return string.replace(new RegExp('"', 'g'), '');
  }

  function renew(data){
      console.log("Resuming update process...");

        var b = data.split(';');

        //-1 accounts for the dead line at the end of every file ;
        for(var i = 0; i < b.length - 1; i++){
          var splits = b[i].split(':');
          createRoom(splits[0], splits[1], 48);
        }
      console.log('Update routine complete. You may now dispose ' +
      'of the contents in the tmp folder');
  }


text:
package org.apache.cassandra.cql3.validation.operations;

import java.util.UUID;

import org.junit.Test;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.dht.OrderPreservingPartitioner;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.locator.TokenMetadata;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.schema.SchemaKeyspaceTables;
import org.apache.cassandra.cql3.CQLTester;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.dht.OrderPreservingPartitioner;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.locator.TokenMetadata;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.FBUtilities;

import static java.lang.String.format;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class AlterTest extends CQLTester
{
    @Test
    public void testAddList() throws Throwable
    {
        createTable("CREATE TABLE %s (id text PRIMARY KEY, content text);");
        alterTable("ALTER TABLE %s ADD myCollection list<text>;");
        execute("INSERT INTO %s (id, content , myCollection) VALUES ('test', 'first test', ['first element']);");

        assertRows(execute("SELECT * FROM %s;"), row("test", "first test", list("first element")));
    }

    @Test
    public void testDropList() throws Throwable
    {
        createTable("CREATE TABLE %s (id text PRIMARY KEY, content text, myCollection list<text>);");
        execute("INSERT INTO %s (id, content , myCollection) VALUES ('test', 'first test', ['first element']);");
        alterTable("ALTER TABLE %s DROP myCollection;");

        assertRows(execute("SELECT * FROM %s;"), row("test", "first test"));
    }

    @Test
    public void testAddMap() throws Throwable
    {
        createTable("CREATE TABLE %s (id text PRIMARY KEY, content text);");
        alterTable("ALTER TABLE %s ADD myCollection map<text, text>;");
        execute("INSERT INTO %s (id, content , myCollection) VALUES ('test', 'first test', { '1' : 'first element'});");

        assertRows(execute("SELECT * FROM %s;"), row("test", "first test", map("1", "first element")));
    }

    @Test
    public void testDropMap() throws Throwable
    {
        createTable("CREATE TABLE %s (id text PRIMARY KEY, content text, myCollection map<text, text>);");
        execute("INSERT INTO %s (id, content , myCollection) VALUES ('test', 'first test', { '1' : 'first element'});");
        alterTable("ALTER TABLE %s DROP myCollection;");

        assertRows(execute("SELECT * FROM %s;"), row("test", "first test"));
    }

    @Test
    public void testDropListAndAddListWithSameName() throws Throwable
    {
        createTable("CREATE TABLE %s (id text PRIMARY KEY, content text, myCollection list<text>);");
        execute("INSERT INTO %s (id, content , myCollection) VALUES ('test', 'first test', ['first element']);");
        alterTable("ALTER TABLE %s DROP myCollection;");
        alterTable("ALTER TABLE %s ADD myCollection list<text>;");
        assertRows(execute("SELECT * FROM %s;"), row("test", "first test", null));
        execute("UPDATE %s set myCollection = ['second element'] WHERE id = 'test';");
        assertRows(execute("SELECT * FROM %s;"), row("test", "first test", list("second element")));
    }

    @Test
    public void testDropListAndAddMapWithSameName() throws Throwable
    {
        createTable("CREATE TABLE %s (id text PRIMARY KEY, content text, myCollection list<text>);");
        execute("INSERT INTO %s (id, content , myCollection) VALUES ('test', 'first test', ['first element']);");
        alterTable("ALTER TABLE %s DROP myCollection;");

        assertInvalid("ALTER TABLE %s ADD myCollection map<int, int>;");
    }

    @Test
    public void testDropWithTimestamp() throws Throwable
    {
        createTable("CREATE TABLE %s (id int, c1 int, v1 int, todrop int, PRIMARY KEY (id, c1));");
        for (int i = 0; i < 5; i++)
            execute("INSERT INTO %s (id, c1, v1, todrop) VALUES (?, ?, ?, ?) USING TIMESTAMP ?", 1, i, i, i, 10000L * i);

        // flush is necessary since otherwise the values of `todrop` will get discarded during
        // alter statement
        flush(true);
        alterTable("ALTER TABLE %s DROP todrop USING TIMESTAMP 20000;");
        alterTable("ALTER TABLE %s ADD todrop int;");
        execute("INSERT INTO %s (id, c1, v1, todrop) VALUES (?, ?, ?, ?) USING TIMESTAMP ?", 1, 100, 100, 100, 30000L);
        assertRows(execute("SELECT id, c1, v1, todrop FROM %s"),
                   row(1, 0, 0, null),
                   row(1, 1, 1, null),
                   row(1, 2, 2, null),
                   row(1, 3, 3, 3),
                   row(1, 4, 4, 4),
                   row(1, 100, 100, 100));
    }

    @Test
    public void testDropAddWithDifferentKind() throws Throwable
    {
        createTable("CREATE TABLE %s (a int, b int, c int, d int static, PRIMARY KEY (a, b));");

        alterTable("ALTER TABLE %s DROP c;");
        alterTable("ALTER TABLE %s DROP d;");

        assertInvalidMessage("Cannot re-add previously dropped column 'c' of kind STATIC, incompatible with previous kind REGULAR",
                             "ALTER TABLE %s ADD c int static;");

        assertInvalidMessage("Cannot re-add previously dropped column 'd' of kind REGULAR, incompatible with previous kind STATIC",
                             "ALTER TABLE %s ADD d int;");
    }

    @Test
    public void testDropStaticWithTimestamp() throws Throwable
    {
        createTable("CREATE TABLE %s (id int, c1 int, v1 int, todrop int static, PRIMARY KEY (id, c1));");
        for (int i = 0; i < 5; i++)
            execute("INSERT INTO %s (id, c1, v1, todrop) VALUES (?, ?, ?, ?) USING TIMESTAMP ?", 1, i, i, i, 10000L * i);

        // flush is necessary since otherwise the values of `todrop` will get discarded during
        // alter statement
        flush(true);
        alterTable("ALTER TABLE %s DROP todrop USING TIMESTAMP 20000;");
        alterTable("ALTER TABLE %s ADD todrop int static;");
        execute("INSERT INTO %s (id, c1, v1, todrop) VALUES (?, ?, ?, ?) USING TIMESTAMP ?", 1, 100, 100, 100, 30000L);
        // static column value with largest timestmap will be available again
        assertRows(execute("SELECT id, c1, v1, todrop FROM %s"),
                   row(1, 0, 0, 4),
                   row(1, 1, 1, 4),
                   row(1, 2, 2, 4),
                   row(1, 3, 3, 4),
                   row(1, 4, 4, 4),
                   row(1, 100, 100, 4));
    }

    @Test
    public void testDropMultipleWithTimestamp() throws Throwable
    {
        createTable("CREATE TABLE %s (id int, c1 int, v1 int, todrop1 int, todrop2 int, PRIMARY KEY (id, c1));");
        for (int i = 0; i < 5; i++)
            execute("INSERT INTO %s (id, c1, v1, todrop1, todrop2) VALUES (?, ?, ?, ?, ?) USING TIMESTAMP ?", 1, i, i, i, i, 10000L * i);

        // flush is necessary since otherwise the values of `todrop1` and `todrop2` will get discarded during
        // alter statement
        flush(true);
        alterTable("ALTER TABLE %s DROP (todrop1, todrop2) USING TIMESTAMP 20000;");
        alterTable("ALTER TABLE %s ADD todrop1 int;");
        alterTable("ALTER TABLE %s ADD todrop2 int;");

        execute("INSERT INTO %s (id, c1, v1, todrop1, todrop2) VALUES (?, ?, ?, ?, ?) USING TIMESTAMP ?", 1, 100, 100, 100, 100, 40000L);
        assertRows(execute("SELECT id, c1, v1, todrop1, todrop2 FROM %s"),
                   row(1, 0, 0, null, null),
                   row(1, 1, 1, null, null),
                   row(1, 2, 2, null, null),
                   row(1, 3, 3, 3, 3),
                   row(1, 4, 4, 4, 4),
                   row(1, 100, 100, 100, 100));
    }

    @Test
    public void testChangeStrategyWithUnquotedAgrument() throws Throwable
    {
        createTable("CREATE TABLE %s (id text PRIMARY KEY);");

        assertInvalidSyntaxMessage("no viable alternative at input '}'",
                                   "ALTER TABLE %s WITH caching = {'keys' : 'all', 'rows_per_partition' : ALL};");
    }

    @Test
    // tests CASSANDRA-7976
    public void testAlterIndexInterval() throws Throwable
    {
        String tableName = createTable("CREATE TABLE IF NOT EXISTS %s (id uuid, album text, artist text, data blob, PRIMARY KEY (id))");
        ColumnFamilyStore cfs = Keyspace.open(KEYSPACE).getColumnFamilyStore(tableName);

        alterTable("ALTER TABLE %s WITH min_index_interval=256 AND max_index_interval=512");
        assertEquals(256, cfs.metadata().params.minIndexInterval);
        assertEquals(512, cfs.metadata().params.maxIndexInterval);

        alterTable("ALTER TABLE %s WITH caching = {}");
        assertEquals(256, cfs.metadata().params.minIndexInterval);
        assertEquals(512, cfs.metadata().params.maxIndexInterval);
    }

    /**
     * Migrated from cql_tests.py:TestCQL.create_alter_options_test()
     */
    @Test
    public void testCreateAlterKeyspaces() throws Throwable
    {
        assertInvalidThrow(SyntaxException.class, "CREATE KEYSPACE ks1");
        assertInvalidThrow(ConfigurationException.class, "CREATE KEYSPACE ks1 WITH replication= { 'replication_factor' : 1 }");

        String ks1 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'SimpleStrategy', 'replication_factor' : 1 }");
        String ks2 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'SimpleStrategy', 'replication_factor' : 1 } AND durable_writes=false");

        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes FROM system_schema.keyspaces"),
                   row(KEYSPACE, true),
                   row(KEYSPACE_PER_TEST, true),
                   row(ks1, true),
                   row(ks2, false));

        schemaChange("ALTER KEYSPACE " + ks1 + " WITH replication = { 'class' : 'NetworkTopologyStrategy', '" + DATA_CENTER + "' : 1 } AND durable_writes=False");
        schemaChange("ALTER KEYSPACE " + ks2 + " WITH durable_writes=true");

        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                   row(KEYSPACE, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                   row(KEYSPACE_PER_TEST, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                   row(ks1, false, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "1")),
                   row(ks2, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")));

        execute("USE " + ks1);

        assertInvalidThrow(ConfigurationException.class, "CREATE TABLE cf1 (a int PRIMARY KEY, b int) WITH compaction = { 'min_threshold' : 4 }");

        execute("CREATE TABLE cf1 (a int PRIMARY KEY, b int) WITH compaction = { 'class' : 'SizeTieredCompactionStrategy', 'min_threshold' : 7 }");
        assertRows(execute("SELECT table_name, compaction FROM system_schema.tables WHERE keyspace_name='" + ks1 + "'"),
                   row("cf1", map("class", "org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy",
                                  "min_threshold", "7",
                                  "max_threshold", "32")));
    }

    @Test
    public void testCreateAlterNetworkTopologyWithDefaults() throws Throwable
    {
        TokenMetadata metadata = StorageService.instance.getTokenMetadata();
        metadata.clearUnsafe();
        InetAddressAndPort local = FBUtilities.getBroadcastAddressAndPort();
        InetAddressAndPort remote = InetAddressAndPort.getByName("127.0.0.4");
        metadata.updateHostId(UUID.randomUUID(), local);
        metadata.updateNormalToken(new OrderPreservingPartitioner.StringToken("A"), local);
        metadata.updateHostId(UUID.randomUUID(), remote);
        metadata.updateNormalToken(new OrderPreservingPartitioner.StringToken("B"), remote);

        // With two datacenters we should respect anything passed in as a manual override
        String ks1 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1, '" + DATA_CENTER_REMOTE + "': 3}");

        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(KEYSPACE, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(KEYSPACE_PER_TEST, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(ks1, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "1", DATA_CENTER_REMOTE, "3")));

        // Should be able to remove data centers
        schemaChange("ALTER KEYSPACE " + ks1 + " WITH replication = { 'class' : 'NetworkTopologyStrategy', '" + DATA_CENTER + "' : 0, '" + DATA_CENTER_REMOTE + "': 3 }");

        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(KEYSPACE, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(KEYSPACE_PER_TEST, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(ks1, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER_REMOTE, "3")));

        // The auto-expansion should not change existing replication counts; do not let the user shoot themselves in the foot
        schemaChange("ALTER KEYSPACE " + ks1 + " WITH replication = { 'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1 } AND durable_writes=True");

        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(KEYSPACE, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(KEYSPACE_PER_TEST, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(ks1, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "1", DATA_CENTER_REMOTE, "3")));

        // The keyspace should be fully functional
        execute("USE " + ks1);

        assertInvalidThrow(ConfigurationException.class, "CREATE TABLE tbl1 (a int PRIMARY KEY, b int) WITH compaction = { 'min_threshold' : 4 }");

        execute("CREATE TABLE tbl1 (a int PRIMARY KEY, b int) WITH compaction = { 'class' : 'SizeTieredCompactionStrategy', 'min_threshold' : 7 }");

        assertRows(execute("SELECT table_name, compaction FROM system_schema.tables WHERE keyspace_name='" + ks1 + "'"),
                   row("tbl1", map("class", "org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy",
                                  "min_threshold", "7",
                                  "max_threshold", "32")));
        metadata.clearUnsafe();
    }

    @Test
    public void testCreateSimpleAlterNTSDefaults() throws Throwable
    {
        TokenMetadata metadata = StorageService.instance.getTokenMetadata();
        metadata.clearUnsafe();
        InetAddressAndPort local = FBUtilities.getBroadcastAddressAndPort();
        InetAddressAndPort remote = InetAddressAndPort.getByName("127.0.0.4");
        metadata.updateHostId(UUID.randomUUID(), local);
        metadata.updateNormalToken(new OrderPreservingPartitioner.StringToken("A"), local);
        metadata.updateHostId(UUID.randomUUID(), remote);
        metadata.updateNormalToken(new OrderPreservingPartitioner.StringToken("B"), remote);

        // Let's create a keyspace first with SimpleStrategy
        String ks1 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'SimpleStrategy', 'replication_factor' : 2}");

        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(KEYSPACE, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(KEYSPACE_PER_TEST, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(ks1, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "2")));

        // Now we should be able to ALTER to NetworkTopologyStrategy directly from SimpleStrategy without supplying replication_factor
        schemaChange("ALTER KEYSPACE " + ks1 + " WITH replication = { 'class' : 'NetworkTopologyStrategy'}");

        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(KEYSPACE, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(KEYSPACE_PER_TEST, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(ks1, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "2", DATA_CENTER_REMOTE, "2")));

        schemaChange("ALTER KEYSPACE " + ks1 + " WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 3}");
        schemaChange("ALTER KEYSPACE " + ks1 + " WITH replication = { 'class' : 'NetworkTopologyStrategy', 'replication_factor': 2}");

        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(KEYSPACE, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(KEYSPACE_PER_TEST, true, map("class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")),
                                        row(ks1, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "2", DATA_CENTER_REMOTE, "2")));
    }

    @Test
    public void testDefaultRF() throws Throwable
    {
        TokenMetadata metadata = StorageService.instance.getTokenMetadata();
        metadata.clearUnsafe();
        InetAddressAndPort local = FBUtilities.getBroadcastAddressAndPort();
        InetAddressAndPort remote = InetAddressAndPort.getByName("127.0.0.4");
        metadata.updateHostId(UUID.randomUUID(), local);
        metadata.updateNormalToken(new OrderPreservingPartitioner.StringToken("A"), local);
        metadata.updateHostId(UUID.randomUUID(), remote);
        metadata.updateNormalToken(new OrderPreservingPartitioner.StringToken("B"), remote);

        DatabaseDescriptor.setDefaultKeyspaceRF(3);

        //ensure default rf is being taken into account during creation, and user can choose to override the default
        String ks1 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'SimpleStrategy' }");
        String ks2 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'SimpleStrategy', 'replication_factor' : 2 }");
        String ks3 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'NetworkTopologyStrategy' }");
        String ks4 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'NetworkTopologyStrategy', 'replication_factor' : 2 }");

        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(ks1, true, map("class","org.apache.cassandra.locator.SimpleStrategy","replication_factor", Integer.toString(DatabaseDescriptor.getDefaultKeyspaceRF()))),
                                        row(ks2, true, map("class","org.apache.cassandra.locator.SimpleStrategy","replication_factor", "2")),
                                        row(ks3, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER,
                                                           Integer.toString(DatabaseDescriptor.getDefaultKeyspaceRF()), DATA_CENTER_REMOTE, Integer.toString(DatabaseDescriptor.getDefaultKeyspaceRF()))),
                                        row(ks4, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "2", DATA_CENTER_REMOTE, "2")));

        //ensure alter keyspace does not default to default rf unless altering from NTS to SS
        //no change alter
        schemaChange("ALTER KEYSPACE " + ks4 + " WITH durable_writes=true");
        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(ks4, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "2", DATA_CENTER_REMOTE, "2")));
        schemaChange("ALTER KEYSPACE " + ks4 + " WITH replication={ 'class' : 'NetworkTopologyStrategy' }");
        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(ks4, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "2", DATA_CENTER_REMOTE, "2")));

        // change from SS to NTS
        // without specifying RF
        schemaChange("ALTER KEYSPACE " + ks2 + " WITH replication={ 'class' : 'NetworkTopologyStrategy' } AND durable_writes=true");
        // verify that RF of SS is retained
        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(ks2, true, map("class","org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "2", DATA_CENTER_REMOTE, "2")));
        // with specifying RF
        schemaChange("ALTER KEYSPACE " + ks1 + " WITH replication={ 'class' : 'NetworkTopologyStrategy', 'replication_factor': '1' } AND durable_writes=true");
        // verify that explicitly mentioned RF is taken into account
        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(ks1, true, map("class","org.apache.cassandra.locator.NetworkTopologyStrategy", DATA_CENTER, "1", DATA_CENTER_REMOTE, "1")));

        // change from NTS to SS
        // without specifying RF
        schemaChange("ALTER KEYSPACE " + ks4 + " WITH replication={ 'class' : 'SimpleStrategy' } AND durable_writes=true");
        // verify that default RF is taken into account
        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(ks4, true, map("class","org.apache.cassandra.locator.SimpleStrategy","replication_factor", Integer.toString(DatabaseDescriptor.getDefaultKeyspaceRF()))));
        // with specifying RF
        schemaChange("ALTER KEYSPACE " + ks3 + " WITH replication={ 'class' : 'SimpleStrategy', 'replication_factor' : '1' } AND durable_writes=true");
        // verify that explicitly mentioned RF is taken into account
        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(ks3, true, map("class","org.apache.cassandra.locator.SimpleStrategy","replication_factor", "1")));

        // verify updated default does not effect existing keyspaces
        // create keyspaces
        String ks5 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'SimpleStrategy' }");
        String ks6 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'NetworkTopologyStrategy' }");
        String oldRF = Integer.toString(DatabaseDescriptor.getDefaultKeyspaceRF());
        // change default
        DatabaseDescriptor.setDefaultKeyspaceRF(2);
        // verify RF of existing keyspaces
        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(ks5, true, map("class","org.apache.cassandra.locator.SimpleStrategy","replication_factor", oldRF)));
        assertRowsIgnoringOrderAndExtra(execute("SELECT keyspace_name, durable_writes, replication FROM system_schema.keyspaces"),
                                        row(ks6, true, map("class", "org.apache.cassandra.locator.NetworkTopologyStrategy",
                                                           DATA_CENTER, oldRF, DATA_CENTER_REMOTE, oldRF)));

        //clean up config change
        DatabaseDescriptor.setDefaultKeyspaceRF(1);

        //clean up keyspaces
        execute(String.format("DROP KEYSPACE IF EXISTS %s", ks1));
        execute(String.format("DROP KEYSPACE IF EXISTS %s", ks2));
        execute(String.format("DROP KEYSPACE IF EXISTS %s", ks3));
        execute(String.format("DROP KEYSPACE IF EXISTS %s", ks4));
        execute(String.format("DROP KEYSPACE IF EXISTS %s", ks5));
        execute(String.format("DROP KEYSPACE IF EXISTS %s", ks6));
    }

    @Test
    public void testMinimumRF() throws Throwable
    {
        DatabaseDescriptor.setDefaultKeyspaceRF(3);
        DatabaseDescriptor.setMinimumKeyspaceRF(2);

        String ks1 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'SimpleStrategy' }");
        String ks2 = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'NetworkTopologyStrategy' }");

        assertAlterTableThrowsException(ConfigurationException.class,
                                        String.format("Replication factor cannot be less than minimum_keyspace_rf (%s), found %s", DatabaseDescriptor.getMinimumKeyspaceRF(), "1"),
                                        String.format("ALTER KEYSPACE %s WITH replication={ 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", ks1));
        assertAlterTableThrowsException(ConfigurationException.class,
                                        String.format("Replication factor cannot be less than minimum_keyspace_rf (%s), found %s", DatabaseDescriptor.getMinimumKeyspaceRF(), "1"),
                                        String.format("ALTER KEYSPACE %s WITH replication={ 'class' : 'NetworkTopologyStrategy', '" + DATA_CENTER + "' : '1' }", ks2));

        //clean up config change
        DatabaseDescriptor.setMinimumKeyspaceRF(0);
        DatabaseDescriptor.setDefaultKeyspaceRF(1);

        //clean up keyspaces
        execute(String.format("DROP KEYSPACE IF EXISTS %s", ks1));
        execute(String.format("DROP KEYSPACE IF EXISTS %s", ks2));
    }

    /**
     * Test {@link ConfigurationException} thrown when altering a keyspace to invalid DC option in replication configuration.
     */
    @Test
    public void testAlterKeyspaceWithNTSOnlyAcceptsConfiguredDataCenterNames() throws Throwable
    {
        // Create a keyspace with expected DC name.
        createKeyspace("CREATE KEYSPACE %s WITH replication = {'class' : 'NetworkTopologyStrategy', '" + DATA_CENTER + "' : 2 }");

        // try modifying the keyspace
        assertAlterKeyspaceThrowsException(ConfigurationException.class,
                                           "Unrecognized strategy option {INVALID_DC} passed to NetworkTopologyStrategy for keyspace " + currentKeyspace(),
                                           "ALTER KEYSPACE %s WITH replication = { 'class' : 'NetworkTopologyStrategy', 'INVALID_DC' : 2 }");

        alterKeyspace("ALTER KEYSPACE %s WITH replication = {'class' : 'NetworkTopologyStrategy', '" + DATA_CENTER + "' : 3 }");

        // Mix valid and invalid, should throw an exception
        assertAlterKeyspaceThrowsException(ConfigurationException.class,
                                           "Unrecognized strategy option {INVALID_DC} passed to NetworkTopologyStrategy for keyspace " + currentKeyspace(),
                                           "ALTER KEYSPACE %s WITH replication={ 'class' : 'NetworkTopologyStrategy', '" + DATA_CENTER + "' : 2 , 'INVALID_DC': 1}");
    }

    @Test
    public void testAlterKeyspaceWithMultipleInstancesOfSameDCThrowsSyntaxException() throws Throwable
    {
        // Create a keyspace
        createKeyspace("CREATE KEYSPACE %s WITH replication = {'class' : 'NetworkTopologyStrategy', '" + DATA_CENTER + "' : 2}");

        // try modifying the keyspace
        assertAlterTableThrowsException(SyntaxException.class,
                                        "",
                                        "ALTER KEYSPACE %s WITH replication = {'class' : 'NetworkTopologyStrategy', '" + DATA_CENTER + "' : 2, '" + DATA_CENTER + "' : 3 }");
        alterKeyspace("ALTER KEYSPACE %s WITH replication = {'class' : 'NetworkTopologyStrategy', '" + DATA_CENTER + "' : 3}");
    }

    /**
     * Test for bug of 5232,
     * migrated from cql_tests.py:TestCQL.alter_bug_test()
     */
    @Test
    public void testAlterStatementWithAdd() throws Throwable
    {
        createTable("CREATE TABLE %s (id int PRIMARY KEY, t text)");

        execute("UPDATE %s SET t = '111' WHERE id = 1");

        alterTable("ALTER TABLE %s ADD l list<text>");
        assertRows(execute("SELECT * FROM %s"),
                   row(1, null, "111"));

        alterTable("ALTER TABLE %s ADD m map<int, text>");
        assertRows(execute("SELECT * FROM %s"),
                   row(1, null, null, "111"));
    }

    /**
     * Test for 7744,
     * migrated from cql_tests.py:TestCQL.downgrade_to_compact_bug_test()
     */
    @Test
    public void testDowngradeToCompact() throws Throwable
    {
        createTable("create table %s (k int primary key, v set<text>)");
        execute("insert into %s (k, v) VALUES (0, {'f'})");
        flush();
        alterTable("alter table %s drop v");
        alterTable("alter table %s add v1 int");
    }

    @Test(expected = InvalidRequestException.class)
    public void testDropFixedAddVariable() throws Throwable
    {
        createTable("create table %s (k int, c int, v int, PRIMARY KEY (k, c))");
        execute("alter table %s drop v");
        execute("alter table %s add v varint");
    }

    @Test(expected = InvalidRequestException.class)
    public void testDropFixedCollectionAddVariableCollection() throws Throwable
    {
        createTable("create table %s (k int, c int, v list<int>, PRIMARY KEY (k, c))");
        execute("alter table %s drop v");
        execute("alter table %s add v list<varint>");
    }

    @Test(expected = InvalidRequestException.class)
    public void testDropSimpleAddComplex() throws Throwable
    {
        createTable("create table %s (k int, c int, v set<text>, PRIMARY KEY (k, c))");
        execute("alter table %s drop v");
        execute("alter table %s add v blob");
    }

    @Test(expected = SyntaxException.class)
    public void renameToEmptyTest() throws Throwable
    {
        createTable("CREATE TABLE %s (k int, c1 int, v int, PRIMARY KEY (k, c1))");
        execute("ALTER TABLE %s RENAME c1 TO \"\"");
    }

    @Test
    // tests CASSANDRA-9565
    public void testDoubleWith() throws Throwable
    {
        String[] stmts = { "ALTER KEYSPACE WITH WITH DURABLE_WRITES = true",
                           "ALTER KEYSPACE ks WITH WITH DURABLE_WRITES = true" };

        for (String stmt : stmts) {
            assertAlterTableThrowsException(SyntaxException.class, "no viable alternative at input 'WITH'", stmt);
        }
    }

    @Test
    public void testAlterTableWithCompression() throws Throwable
    {
        createTable("CREATE TABLE %s (a text, b int, c int, primary key (a, b))");

        assertRows(execute(format("SELECT compression FROM %s.%s WHERE keyspace_name = ? and table_name = ?;",
                                  SchemaConstants.SCHEMA_KEYSPACE_NAME,
                                  SchemaKeyspaceTables.TABLES),
                           KEYSPACE,
                           currentTable()),
                   row(map("chunk_length_in_kb", "16", "class", "org.apache.cassandra.io.compress.LZ4Compressor")));

        alterTable("ALTER TABLE %s WITH compression = { 'class' : 'SnappyCompressor', 'chunk_length_in_kb' : 32 };");

        assertRows(execute(format("SELECT compression FROM %s.%s WHERE keyspace_name = ? and table_name = ?;",
                                  SchemaConstants.SCHEMA_KEYSPACE_NAME,
                                  SchemaKeyspaceTables.TABLES),
                           KEYSPACE,
                           currentTable()),
                   row(map("chunk_length_in_kb", "32", "class", "org.apache.cassandra.io.compress.SnappyCompressor")));

        alterTable("ALTER TABLE %s WITH compression = { 'class' : 'LZ4Compressor', 'chunk_length_in_kb' : 64 };");

        assertRows(execute(format("SELECT compression FROM %s.%s WHERE keyspace_name = ? and table_name = ?;",
                                  SchemaConstants.SCHEMA_KEYSPACE_NAME,
                                  SchemaKeyspaceTables.TABLES),
                           KEYSPACE,
                           currentTable()),
                   row(map("chunk_length_in_kb", "64", "class", "org.apache.cassandra.io.compress.LZ4Compressor")));

        alterTable("ALTER TABLE %s WITH compression = { 'class' : 'LZ4Compressor', 'min_compress_ratio' : 2 };");

        assertRows(execute(format("SELECT compression FROM %s.%s WHERE keyspace_name = ? and table_name = ?;",
                                  SchemaConstants.SCHEMA_KEYSPACE_NAME,
                                  SchemaKeyspaceTables.TABLES),
                           KEYSPACE,
                           currentTable()),
                   row(map("chunk_length_in_kb", "16", "class", "org.apache.cassandra.io.compress.LZ4Compressor", "min_compress_ratio", "2.0")));

        alterTable("ALTER TABLE %s WITH compression = { 'class' : 'LZ4Compressor', 'min_compress_ratio' : 1 };");

        assertRows(execute(format("SELECT compression FROM %s.%s WHERE keyspace_name = ? and table_name = ?;",
                                  SchemaConstants.SCHEMA_KEYSPACE_NAME,
                                  SchemaKeyspaceTables.TABLES),
                           KEYSPACE,
                           currentTable()),
                   row(map("chunk_length_in_kb", "16", "class", "org.apache.cassandra.io.compress.LZ4Compressor", "min_compress_ratio", "1.0")));

        alterTable("ALTER TABLE %s WITH compression = { 'class' : 'LZ4Compressor', 'min_compress_ratio' : 0 };");

        assertRows(execute(format("SELECT compression FROM %s.%s WHERE keyspace_name = ? and table_name = ?;",
                                  SchemaConstants.SCHEMA_KEYSPACE_NAME,
                                  SchemaKeyspaceTables.TABLES),
                           KEYSPACE,
                           currentTable()),
                   row(map("chunk_length_in_kb", "16", "class", "org.apache.cassandra.io.compress.LZ4Compressor")));

        alterTable("ALTER TABLE %s WITH compression = { 'class' : 'SnappyCompressor', 'chunk_length_in_kb' : 32 };");
        alterTable("ALTER TABLE %s WITH compression = { 'enabled' : 'false'};");

        assertRows(execute(format("SELECT compression FROM %s.%s WHERE keyspace_name = ? and table_name = ?;",
                                  SchemaConstants.SCHEMA_KEYSPACE_NAME,
                                  SchemaKeyspaceTables.TABLES),
                           KEYSPACE,
                           currentTable()),
                   row(map("enabled", "false")));

        assertAlterTableThrowsException(ConfigurationException.class,
                                        "Missing sub-option 'class' for the 'compression' option.",
                                        "ALTER TABLE %s WITH  compression = {'chunk_length_in_kb' : 32};");

        assertAlterTableThrowsException(ConfigurationException.class,
                                        "The 'class' option must not be empty. To disable compression use 'enabled' : false",
                                        "ALTER TABLE %s WITH  compression = { 'class' : ''};");

        assertAlterTableThrowsException(ConfigurationException.class,
                                        "If the 'enabled' option is set to false no other options must be specified",
                                        "ALTER TABLE %s WITH compression = { 'enabled' : 'false', 'class' : 'SnappyCompressor'};");

        assertAlterTableThrowsException(ConfigurationException.class,
                                        "The 'sstable_compression' option must not be used if the compression algorithm is already specified by the 'class' option",
                                        "ALTER TABLE %s WITH compression = { 'sstable_compression' : 'SnappyCompressor', 'class' : 'SnappyCompressor'};");

        assertAlterTableThrowsException(ConfigurationException.class,
                                        "The 'chunk_length_kb' option must not be used if the chunk length is already specified by the 'chunk_length_in_kb' option",
                                        "ALTER TABLE %s WITH compression = { 'class' : 'SnappyCompressor', 'chunk_length_kb' : 32 , 'chunk_length_in_kb' : 32 };");

        assertAlterTableThrowsException(ConfigurationException.class,
                                        "Invalid negative min_compress_ratio",
                                        "ALTER TABLE %s WITH compression = { 'class' : 'SnappyCompressor', 'min_compress_ratio' : -1 };");

        assertAlterTableThrowsException(ConfigurationException.class,
                                        "min_compress_ratio can either be 0 or greater than or equal to 1",
                                        "ALTER TABLE %s WITH compression = { 'class' : 'SnappyCompressor', 'min_compress_ratio' : 0.5 };");
    }

    private void assertAlterKeyspaceThrowsException(Class<? extends Throwable> clazz, String msg, String stmt)
    {
        assertThrowsException(clazz, msg, () -> {alterKeyspaceMayThrow(stmt);});
    }

    private void assertAlterTableThrowsException(Class<? extends Throwable> clazz, String msg, String stmt)
    {
        assertThrowsException(clazz, msg, () -> {alterTableMayThrow(stmt);});
    }

    private static void assertThrowsException(Class<? extends Throwable> clazz, String msg, CheckedFunction function)
    {
        try
        {
            function.apply();
            fail("An error should havee been thrown but was not.");
        }
        catch (Throwable e)
        {
            assertTrue("Unexpected exception type (expected: " + clazz + ", value: " + e.getClass() + ")",
                       clazz.isAssignableFrom(e.getClass()));
            assertTrue("Expecting the error message to contains: '" + msg + "' but was " + e.getMessage(), e.getMessage().contains(msg));
        }
    }

    /**
     * Test for CASSANDRA-13337. Checks that dropping a column when a sstable contains only data for that column
     * works properly.
     */
    @Test
    public void testAlterDropEmptySSTable() throws Throwable
    {
        createTable("CREATE TABLE %s(k int PRIMARY KEY, x int, y int)");

        execute("UPDATE %s SET x = 1 WHERE k = 0");

        flush();

        execute("UPDATE %s SET x = 1, y = 1 WHERE k = 0");

        flush();

        alterTable("ALTER TABLE %s DROP x");

        compact();

        assertRows(execute("SELECT * FROM %s"), row(0, 1));
    }

    /**
     * Similarly to testAlterDropEmptySSTable, checks we don't return empty rows from queries (testAlterDropEmptySSTable
     * tests the compaction case).
     */
    @Test
    public void testAlterOnlyColumnBehaviorWithFlush() throws Throwable
    {
        testAlterOnlyColumnBehaviorWithFlush(true);
        testAlterOnlyColumnBehaviorWithFlush(false);
    }

    private void testAlterOnlyColumnBehaviorWithFlush(boolean flushAfterInsert) throws Throwable
    {
        createTable("CREATE TABLE %s(k int PRIMARY KEY, x int, y int)");

        execute("UPDATE %s SET x = 1 WHERE k = 0");

        assertRows(execute("SELECT * FROM %s"), row(0, 1, null));

        if (flushAfterInsert)
            flush();

        alterTable("ALTER TABLE %s DROP x");

        assertEmpty(execute("SELECT * FROM %s"));
    }

    @Test
    public void testAlterTypeUsedInPartitionKey() throws Throwable
    {
        // frozen UDT used directly in a partition key
        String  type1 = createType("CREATE TYPE %s (v1 int)");
        String table1 = createTable("CREATE TABLE %s (pk frozen<" + type1 + ">, val int, PRIMARY KEY(pk));");

        // frozen UDT used in a frozen UDT used in a partition key
        String  type2 = createType("CREATE TYPE %s (v1 frozen<" + type1 + ">, v2 frozen<" + type1 + ">)");
        String table2 = createTable("CREATE TABLE %s (pk frozen<" + type2 + ">, val int, PRIMARY KEY(pk));");

        // frozen UDT used in a frozen collection used in a partition key
        String table3 = createTable("CREATE TABLE %s (pk frozen<list<frozen<" + type1 + ">>>, val int, PRIMARY KEY(pk));");

        // assert that ALTER fails and that the error message contains all the names of the table referencing it
        assertInvalidMessage(table1, format("ALTER TYPE %s.%s ADD v2 int;", keyspace(), type1));
        assertInvalidMessage(table2, format("ALTER TYPE %s.%s ADD v2 int;", keyspace(), type1));
        assertInvalidMessage(table3, format("ALTER TYPE %s.%s ADD v2 int;", keyspace(), type1));
    }

    @Test
    public void testAlterDropCompactStorageDisabled() throws Throwable
    {
        DatabaseDescriptor.setEnableDropCompactStorage(false);

        createTable("CREATE TABLE %s (k text, i int, PRIMARY KEY (k, i)) WITH COMPACT STORAGE");

        assertInvalidMessage("DROP COMPACT STORAGE is disabled. Enable in cassandra.yaml to use.", "ALTER TABLE %s DROP COMPACT STORAGE");
    }

    /**
     * Test for CASSANDRA-14564
     */
    @Test
    public void testAlterByAddingColumnToCompactTableShouldFail() throws Throwable
    {
        createTable("CREATE TABLE %s (a int, b int, PRIMARY KEY (a, b)) WITH COMPACT STORAGE");
        assertInvalidMessage("Cannot add new column to a COMPACT STORAGE table",
                             "ALTER TABLE %s ADD column1 text");
    }
}


text:
<?php
namespace Craft;

class AmCommandService extends BaseApplicationComponent
{
    private $_settings;
    private $_returnTitle;
    private $_returnMessage;
    private $_returnUrl;
    private $_returnUrlWindow;
    private $_returnAction;
    private $_returnCommands;
    private $_deleteCurrentCommand = false;
    private $_reverseSorting = false;
    private $_returnHtml = false;

    /**
     * Get all available commands.
     *
     * @param array $settings
     *
     * @return array
     */
    public function getCommands($settings)
    {
        $this->_settings = $settings;

        $commands = array();
        // Add content commands
        $commands = $this->_getContentCommands($commands);
        // Add global commands
        $commands = $this->_getGlobalCommands($commands);
        // Add user commands
        $commands = $this->_getUserCommands($commands);
        // Add search commands
        $commands = $this->_getSearchCommands($commands);
        // Add settings commands
        $commands = $this->_getSettingCommands($commands);
        // Add other plugin's commands
        $pluginCommands = craft()->plugins->call('addCommands');
        foreach ($pluginCommands as $pluginCommand) {
            foreach ($pluginCommand as $command) {
                $commands[] = $command;
            }
        }
        // Return the commands nicely sorted
        return json_encode($this->_sortCommands($commands));
    }

    /**
     * Trigger a command that was called through ajax.
     *
     * @param string $command   Command as function name.
     * @param string $service   [Optional] Which service should be called instead.
     * @param array  $variables [Optional] The optional variables.
     *
     * @return mixed False on error otherwise JSON with commands.
     */
    public function triggerCommand($command, $service, $variables)
    {
        if ($service !== false) {
            if (! method_exists(craft()->$service, $command)) {
                return false;
            }
            $commandResult = craft()->$service->$command($variables);
        }
        else {
            if (! method_exists($this, $command)) {
                return false;
            }
            $commandResult = $this->$command($variables);
        }

        // Treat the result as a new list of commands
        if (is_array($commandResult)) {
            if ($service == 'amCommand_search') {
                return $commandResult;
            }
            return $this->_sortCommands($commandResult);
        }
        else {
            return $commandResult;
        }
    }

    /**
     * Set title that'll be returned after a command was executed.
     *
     * @param string $title
     */
    public function setReturnTitle($title)
    {
        $this->_returnTitle = $title;
    }

    /**
     * Get the return title.
     *
     * @return bool|string
     */
    public function getReturnTitle()
    {
        return isset($this->_returnTitle) ? $this->_returnTitle : false;
    }

    /**
     * Set a message that'll be shown to the user after a command was executed.
     *
     * @param string $message
     */
    public function setReturnMessage($message)
    {
        $this->_returnMessage = $message;
    }

    /**
     * Get the return message.
     *
     * @return int|string
     */
    public function getReturnMessage()
    {
        return isset($this->_returnMessage) ? $this->_returnMessage : false;
    }

    /**
     * Set an URL to redirect to after executing a command.
     *
     * @param string $url
     * @param bool   $newWindow [Optional] Whether to redirect in a new window.
     */
    public function setReturnUrl($url, $newWindow = false)
    {
        $this->_returnUrl = $url;
        $this->_returnUrlWindow = $newWindow;
    }

    /**
     * Get the return URL.
     *
     * @return int|string
     */
    public function getReturnUrl()
    {
        return isset($this->_returnUrl) ? array('url' => $this->_returnUrl, 'newWindow' => $this->_returnUrlWindow) : false;
    }

    /**
     * Set an action that'll be returned after a command was executed.
     *
     * @param string $tabs         Text above the search field.
     * @param string $searchText   Text in the search field.
     * @param string $callback     Which callback should be called.
     * @param string $service      In which service the callback is callable.
     * @param array  $variables    [Optional] Variables for the callback.
     * @param bool   $asynchronous [Optional] Whether the action should be submitted asynchronously.
     * @param bool   $realtime     [Optional] Whether this action should be submitted while the user types in the search field.
     */
    public function setReturnAction($tabs, $searchText, $callback, $service, $variables = array(), $asynchronous = true, $realtime = false)
    {
        $this->_returnAction = array(
            'tabs'       => $tabs,
            'searchText' => $searchText,
            'call'       => $callback,
            'service'    => $service,
            'vars'       => $variables,
            'async'      => $asynchronous,
            'realtime'   => $realtime
        );
    }

    /**
     * Get the return action.
     *
     * @return int|array
     */
    public function getReturnAction()
    {
        return isset($this->_returnAction) ? $this->_returnAction : false;
    }

    /**
     * Set command that'll be returned after a command was executed.
     *
     * Note: You can use this to overwrite the normal command's result.
     *
     * @param array $commands
     */
    public function setReturnCommands($commands)
    {
        $this->_returnCommands = $commands;
    }

    /**
     * Get the return commands.
     *
     * @return bool|array
     */
    public function getReturnCommands()
    {
        return isset($this->_returnCommands) ? $this->_sortCommands($this->_returnCommands) : false;
    }

    /**
     * Delete the command when the result is returned.
     */
    public function deleteCurrentCommand()
    {
        $this->_deleteCurrentCommand = true;
    }

    /**
     * Get the current command delete status.
     *
     * @return bool
     */
    public function getDeleteStatus()
    {
        return $this->_deleteCurrentCommand;
    }

    /**
     * Whether the palette should reverse the commands's sorting.
     *
     * @param bool $value
     */
    public function setReverseSorting($value)
    {
        $this->_reverseSorting = $value;
    }

    /**
     * Whether the palette will have HTML returned.
     *
     * @param bool $value
     */
    public function setReturnHtml($value)
    {
        $this->_returnHtml = $value;
    }

    /**
     * Get the return html.
     *
     * @return bool
     */
    public function getReturnHtml()
    {
        return is_bool($this->_returnHtml) ? $this->_returnHtml : false;
    }

    /**
     * Order the commands by name.
     *
     * @param array $commands
     *
     * @return array
     */
    private function _sortCommands($commands)
    {
        $reverseSorting = $this->_reverseSorting;
        usort($commands, function($a, $b) use ($reverseSorting) {
            return $reverseSorting ? strnatcmp($b['name'], $a['name']) : strnatcmp($a['name'], $b['name']);
        });

        // Add necessary keys for fuzzy sort
        foreach ($commands as &$command) {
            if (! isset($command['info'])) {
                $command['info'] = '';
            }
        }

        return $commands;
    }

    /**
     * Get useful content commands.
     *
     * @param array $currentCommands
     *
     * @return array
     */
    private function _getContentCommands($currentCommands)
    {
        // Duplicate entry command
        $entrySegment = craft()->request->getSegment(1) == 'entries';
        $entryId = current(explode('-', craft()->request->getSegment(3)));
        if ($entrySegment && is_numeric($entryId)) {
            $entry = craft()->entries->getEntryById($entryId);
            if ($entry) {
                $entrySection = $entry->getSection();

                // We don't want to duplicate Single type entries
                if ($entrySection->type != SectionType::Single) {
                    $currentCommands[] = array(
                        'name'    => Craft::t('Content') . ': ' . Craft::t('Duplicate entry'),
                        'info'    => Craft::t('Duplicate the current entry.'),
                        'call'    => 'duplicateEntry',
                        'service' => 'amCommand_entries',
                        'vars'    => array(
                            'entryId' => $entryId,
                            'locale'  => craft()->request->getSegment(-1),
                        ),
                        'icon'    => array(
                            'type' => 'font',
                            'content' => 'section',
                        )
                    );
                }
                $currentCommands[] = array(
                    'name'    => Craft::t('Content') . ': ' . Craft::t('Compare entry version'),
                    'info'    => Craft::t('Compare the current entry with older versions.'),
                    'call'    => 'compareEntryVersion',
                    'service' => 'amCommand_entries',
                    'vars'    => array(
                        'entryId' => $entryId,
                        'locale'  => craft()->request->getSegment(-1),
                    ),
                    'icon'    => array(
                        'type' => 'font',
                        'content' => 'section',
                    )
                );
            }
        }

         // New, edit and delete commands
        if (craft()->userSession->isAdmin() || craft()->sections->getTotalEditableSections() > 0) {
            $currentCommands[] = array(
                'name'    => Craft::t('Content') . ': ' . Craft::t('New entry'),
                'info'    => Craft::t('Create a new entry in one of the available sections.'),
                'more'    => true,
                'call'    => 'newEntry',
                'service' => 'amCommand_entries',
                'icon'    => array(
                    'type' => 'font',
                    'content' => 'section',
                )
            );
            $currentCommands[] = array(
                'name'    => Craft::t('Content') . ': ' . Craft::t('Edit entries'),
                'info'    => Craft::t('Edit an entry in one of the available sections.'),
                'more'    => true,
                'call'    => 'editEntries',
                'service' => 'amCommand_entries',
                'icon'    => array(
                    'type' => 'font',
                    'content' => 'section',
                )
            );
            $currentCommands[] = array(
                'name'    => Craft::t('Content') . ': ' . Craft::t('Delete entries'),
                'info'    => Craft::t('Delete an entry in one of the available sections.'),
                'more'    => true,
                'call'    => 'deleteEntries',
                'service' => 'amCommand_entries',
                'vars'    => array(
                    'deleteAll' => false
                ),
                'icon'    => array(
                    'type' => 'font',
                    'content' => 'section',
                )
            );
            if (craft()->userSession->isAdmin()) {
                $currentCommands[] = array(
                    'name'    => Craft::t('Content') . ': ' . Craft::t('Delete all entries'),
                    'info'    => Craft::t('Delete all entries in one of the available sections.'),
                    'more'    => true,
                    'call'    => 'deleteEntries',
                    'service' => 'amCommand_entries',
                    'vars'    => array(
                        'deleteAll' => true
                    ),
                    'icon'    => array(
                        'type' => 'font',
                        'content' => 'section',
                    )
                );
            }
        }

        return $currentCommands;
    }

    /**
     * Get useful globals commands.
     *
     * @param array $currentCommands
     *
     * @return array
     */
    private function _getGlobalCommands($currentCommands)
    {
        if (craft()->userSession->isAdmin() || craft()->globals->getTotalEditableSets() > 0) {
            $currentCommands[] = array(
                'name'    => Craft::t('Globals') . ': ' . Craft::t('Edit'),
                'more'    => true,
                'call'    => 'editGlobals',
                'service' => 'amCommand_globals',
                'icon'    => array(
                    'type' => 'font',
                    'content' => 'globe',
                )
            );
        }

        return $currentCommands;
    }

    /**
     * Get useful user commands.
     *
     * @param array $currentCommands
     *
     * @return array
     */
    private function _getUserCommands($currentCommands)
    {
        $currentCommands[] = array(
            'name'    => Craft::t('Dashboard'),
            'url'     => UrlHelper::getUrl('dashboard'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'gauge',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Sign out'),
            'info' => Craft::t('End current session.'),
            'url'  => UrlHelper::getUrl('logout')
        );
        $currentCommands[] = array(
            'name' => Craft::t('My Account'),
            'url'  => UrlHelper::getUrl('myaccount')
        );
        if (craft()->userSession->isAdmin() || craft()->userSession->getUser()->can('editUsers')) {
            $currentCommands[] = array(
                'name'    => Craft::t('Users') . ': ' . Craft::t('New user'),
                'info'    => Craft::t('Create a user.'),
                'url'     => UrlHelper::getUrl('users/new'),
                'icon'    => array(
                    'type' => 'font',
                    'content' => 'users',
                )
            );
            $currentCommands[] = array(
                'name'    => Craft::t('Users') . ': ' . Craft::t('Edit users'),
                'info'    => Craft::t('Edit a user.'),
                'more'    => true,
                'call'    => 'editUser',
                'service' => 'amCommand_users',
                'icon'    => array(
                    'type' => 'font',
                    'content' => 'users',
                )
            );
            $currentCommands[] = array(
                'name'    => Craft::t('Users') . ': ' . Craft::t('Delete users'),
                'info'    => Craft::t('Delete a user other than your own.'),
                'more'    => true,
                'call'    => 'deleteUser',
                'service' => 'amCommand_users',
                'icon'    => array(
                    'type' => 'font',
                    'content' => 'users',
                )
            );
            if (craft()->userSession->isAdmin()) {
                $currentCommands[] = array(
                    'name'    => Craft::t('Users') . ': ' . Craft::t('Login as user'),
                    'info'    => Craft::t('Log in as a different user, and navigate to their dashboard.'),
                    'more'    => true,
                    'call'    => 'loginUser',
                    'service' => 'amCommand_users',
                    'icon'    => array(
                        'type' => 'font',
                        'content' => 'users',
                    )
                );
            }
        }

        return $currentCommands;
    }

    /**
     * Get useful search commands.
     *
     * @param array $currentCommands
     *
     * @return array
     */
    private function _getSearchCommands($currentCommands)
    {
        // Site searches
        $currentCommands[] = array(
            'name'    => Craft::t('Search on {option}', array('option' => 'Craft')),
            'info'    => 'https://craftcms.com',
            'more'    => true,
            'call'    => 'searchOptionCraft',
            'service' => 'amCommand_search',
            'icon'    => array(
                'type' => 'font',
                'content' => 'search',
            )
        );
        $currentCommands[] = array(
            'name'    => Craft::t('Search on {option}', array('option' => 'StackExchange')),
            'info'    => 'http://craftcms.stackexchange.com',
            'more'    => true,
            'call'    => 'searchOptionStackExchange',
            'service' => 'amCommand_search',
            'icon'    => array(
                'type' => 'font',
                'content' => 'search',
            )
        );

        // Element searches
        if (is_array($this->_settings->elementSearchElementTypes)) {
            foreach ($this->_settings->elementSearchElementTypes as $elementType => $submittedInfo) {
                if (isset($submittedInfo['enabled']) && $submittedInfo['enabled'] === '1') {
                    $actualElementType = craft()->elements->getElementType($elementType);
                    $currentCommands[] = array(
                        'name'    => Craft::t('Search for {option}', array('option' => $actualElementType->getName())),
                        'more'    => true,
                        'call'    => 'searchOptionElementType',
                        'service' => 'amCommand_search',
                        'vars'    => array(
                            'elementType' => $elementType
                        ),
                        'icon'    => array(
                            'type' => 'font',
                            'content' => 'search',
                        )
                    );
                }
            }
        }

        return $currentCommands;
    }

    /**
     * Get useful settings.
     *
     * @param array $currentCommands
     *
     * @return array
     */
    private function _getSettingCommands($currentCommands)
    {
        if (! craft()->userSession->isAdmin()) {
            return $currentCommands;
        }

        $currentCommands[] = array(
            'name'    => Craft::t('Tasks'),
            'info'    => Craft::t('Manage Craft tasks.'),
            'more'    => true,
            'call'    => 'taskCommands',
            'service' => 'amCommand_tasks',
            'icon'    => array(
                'type' => 'font',
                'content' => 'settings',
            )
        );
        $currentCommands[] = array(
            'name'    => Craft::t('Tools'),
            'info'    => Craft::t('Use one of the most used tools.'),
            'more'    => true,
            'call'    => 'listTools',
            'service' => 'amCommand_tools',
            'icon'    => array(
                'type' => 'font',
                'content' => 'settings',
            )
        );
        $currentCommands[] = array(
            'name'    => Craft::t('Settings') . ': ' . Craft::t('New') . '...',
            'info'    => Craft::t('Add something new in the settings...'),
            'more'    => true,
            'call'    => 'createNewSetting',
            'service' => 'amCommand_settings',
            'icon'    => array(
                'type' => 'font',
                'content' => 'settings',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Settings') . ': ' . Craft::t('Fields'),
            'url'  => UrlHelper::getUrl('settings/fields'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'field',
            )
        );
        $currentCommands[] = array(
            'name'    => Craft::t('Settings') . ': ' . Craft::t('Fields') . ' - ' . Craft::t('Edit'),
            'more'    => true,
            'call'    => 'editFields',
            'service' => 'amCommand_settings',
            'icon'    => array(
                'type' => 'font',
                'content' => 'field',
            )
        );
        $currentCommands[] = array(
            'name'    => Craft::t('Settings') . ': ' . Craft::t('Fields') . ' - ' . Craft::t('Duplicate'),
            'more'    => true,
            'call'    => 'duplicateFields',
            'service' => 'amCommand_settings',
            'icon'    => array(
                'type' => 'font',
                'content' => 'field',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Settings') . ': ' . Craft::t('Sections'),
            'url'  => UrlHelper::getUrl('settings/sections'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'section',
            )
        );
        $currentCommands[] = array(
            'name'    => Craft::t('Settings') . ': ' . Craft::t('Sections') . ' - ' . Craft::t('Edit'),
            'more'    => true,
            'call'    => 'editSections',
            'service' => 'amCommand_settings',
            'icon'    => array(
                'type' => 'font',
                'content' => 'section',
            )
        );
        $currentCommands[] = array(
            'name'    => Craft::t('Settings') . ': ' . Craft::t('Sections') . ' - ' . Craft::t('Edit entry type'),
            'more'    => true,
            'call'    => 'editSectionEntryTypes',
            'service' => 'amCommand_settings',
            'icon'    => array(
                'type' => 'font',
                'content' => 'section',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Settings') . ': ' . Craft::t('Globals'),
            'url'  => UrlHelper::getUrl('settings/globals'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'settings',
            )
        );
        $currentCommands[] = array(
            'name'    => Craft::t('Settings') . ': ' . Craft::t('Globals') . ' - ' . Craft::t('Global Sets'),
            'more'    => true,
            'call'    => 'editGlobalSets',
            'service' => 'amCommand_settings',
            'icon'    => array(
                'type' => 'font',
                'content' => 'settings',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Settings') . ': ' . Craft::t('Users'),
            'url'  => UrlHelper::getUrl('settings/users'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'settings',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Settings') . ': ' . Craft::t('Routes'),
            'url'  => UrlHelper::getUrl('settings/routes'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'routes',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Settings') . ': ' . Craft::t('Categories'),
            'url'  => UrlHelper::getUrl('settings/categories'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'settings',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Settings') . ': ' . Craft::t('Assets'),
            'url'  => UrlHelper::getUrl('settings/assets'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'settings',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Settings') . ': ' . Craft::t('Locales'),
            'url'  => UrlHelper::getUrl('settings/locales'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'language',
            )
        );
        $currentCommands[] = array(
            'name' => Craft::t('Settings') . ': ' . Craft::t('Plugins'),
            'url'  => UrlHelper::getUrl('settings/plugins'),
            'icon'    => array(
                'type' => 'font',
                'content' => 'plugin',
            )
        );
        $currentCommands[] = array(
            'name'    => Craft::t('Settings') . ': ' . Craft::t('Plugin settings'),
            'more'    => true,
            'call'    => 'getSettingsUrl',
            'service' => 'amCommand_plugins',
            'icon'    => array(
                'type' => 'font',
                'content' => 'plugin',
            )
        );

        return $currentCommands;
    }
}


text:
layout: post
title: '22: Project Make Something'
audioURL: e022-make-a-project
categories: episodes
excerpt_separator: <!--more-->
---

Taking a break from the compiler project, but only for now. I feel the need to excerise a bit more of the of the productive side. I've had this idea, for a long, long time. And have basicly been building it in my head for the last year.

<!--more-->

<!-- TOC -->

* [Project: Just do it already](#project-just-do-it-already)
* [Where it all when wrong the midterm](#where-it-all-when-wrong-the-midterm)
  * [Realign Expectations, Rethinking learning this stuff](#realign-expectations-rethinking-learning-this-stuff)
  * [Rebooting ?](#rebooting-)
* [Picks](#picks)
* [Resources](#resources)
* [Follow](#follow)

<!-- /TOC -->

## Project: Just do it already

* Run code in MirrorCode and transpile JS code to AST and compare to answer stored at AST.
* But the first part is to incorporate the editor, CodeMirrior, and capture the input. That would be the definition of success.

1. Init app, get it running
2. Split page into 50% using CSS Grid, bc fancy
3. Put CodeMirror onto page with Elm

* The Problem. I need to apply the instance of CodeMirror to the div with id "CodeEditor"
* After Importing CodeMirror, Embedding the Elm app on the root id tag
* my "CodeEditor" element is nowhere to be found.

* Ports
* Ellie as a template

4. Capture coding input and output
5. Evaluate that JS, safely?

## Where it all when wrong the midterm

* Passed or Failed
* Totally failed at this one.
* Apply the instance of CodeMirror to the element ID after Elm creates the content
* Request Animation Frame?? Nope, no idea?
* The rabbit hole, Elm and Ports
* Me, Elm, and Compile failures
*

### Realign Expectations, Rethinking learning this stuff

* Ok, so it's a larger project
* I don't have a good grasp on Elm
* Core Mission of this Podcast
* LOL, 1 point for attendance
* Pipe Operator, ??
* A bit disheartened with my progress
* A little concerned effort v progress
* Remember learning React and Redux? That was a beast
  * but it was in JS, which was still C style object programming
  * now it's functional, is it the paridigm that i'm struggling with ?

### Rebooting ?

* Elm multi-files ? This was a bit of a struggle
* Braking down the problem into small enough chunks ?
*

## Picks

* [Functional to wasm](https://github.com/appcypher/astro)

  * Astro is a
    * statically-typed language that
    * compiles to native code and WebAssembly,
    * has no GC,
    * has a syntax similar to Python,
    * provides full type inference, and
    * has first-class support for data-race-free concurrency.

* [Teach yourself CS](https://teachyourselfcs.com/)

  * If you're a self-taught engineer or bootcamp grad, you owe it to yourself to learn computer science. Thankfully, you can give yourself a world-class CS education without investing years and a small fortune in a degree program 💸.

* [Welcome to Engineering's CS1 - SELF PACED!](https://lagunita.stanford.edu/login?next=%2Fdashboard)
  * Welcome to a public, self-paced version of Stanford's undergraduate course on Compilers. All course content is now available.

## Resources

* [Yep, more Elm Town!](https://elmtown.github.io/2016/11/07/js-in-elm-town-episode-4.html)
* [An implementation using requestAnimationFrame()](https://stackoverflow.com/questions/38952724/how-to-coordinate-rendering-with-port-interactions-elm-0-17)
* [Life of a File](https://www.youtube.com/watch?v=XpDsk374LDE)

## Follow

* JavaScript to Elm
  * Twitter: [@jstoelm](https://twitter.com/jstoelm)
  * Email: [hello@jstoelm.com](mailto:hello@jstoelm.com)
* Jesse Tomchak
  * Twitter: [@jtomchak](https://twitter.com/jtomchak)


text:
import { Component, OnInit } from '@angular/core';
import { AcctService } from '../../services/acct/acct.service';

@Component({
  selector: 'app-new-item',
  templateUrl: './new-item.component.html',
  styleUrls: ['./new-item.component.css']
})
export class NewItemComponent implements OnInit {

  username = this.acctService.username;
  constructor(private acctService: AcctService) { }

  ngOnInit() {
  }

  isLoggedIn(): boolean {
    return this.acctService.isLoggedIn();
  }

}