text:
from vt_manager_kvm.controller.actions.ActionController import ActionController
from vt_manager_kvm.controller.drivers.VTDriver import VTDriver
from vt_manager_kvm.models.Action import Action
from vt_manager_kvm.models.VirtualMachine import VirtualMachine
import xmlrpclib, threading, logging, copy
from vt_manager_kvm.communication.utils.XmlHelper import XmlHelper
from vt_manager_kvm.models.resourcesHash import resourcesHash

class InformationDispatcher():

	@staticmethod
	def listResources(remoteHashValue, projectUUID = 'None', sliceUUID ='None'):
		logging.debug("Enter listResources")
		infoRspec = XmlHelper.getSimpleInformation()
		servers = VTDriver.getAllServers()
		baseVM = copy.deepcopy(infoRspec.response.information.resources.server[0].virtual_machine[0])
		if not servers:
			logging.debug("No VTServers available")
			infoRspec.response.information.resources.server.pop()
			resourcesString = XmlHelper.craftXmlClass(infoRspec)
			localHashValue = str(hash(resourcesString))
		else:
			for sIndex, server in enumerate(servers):
				if(sIndex == 0):
					baseServer = copy.deepcopy(infoRspec.response.information.resources.server[0])
				if(sIndex != 0):
					newServer = copy.deepcopy(baseServer)
					infoRspec.response.information.resources.server.append(newServer)

				InformationDispatcher.__ServerModelToClass(server, infoRspec.response.information.resources.server[sIndex] )
				if (projectUUID is not 'None'):
					vms = server.getVMs(projectId = projectUUID)
				else:
					vms = server.getVMs()
				if not vms:
					logging.debug("No VMs available")
					if infoRspec.response.information.resources.server[sIndex].virtual_machine:
						infoRspec.response.information.resources.server[sIndex].virtual_machine.pop()
				elif (sliceUUID is not 'None'):
					vms = vms.filter(sliceId = sliceUUID)
					if not vms:
						logging.error("No VMs available")
						infoRspec.response.information.resources.server[sIndex].virtual_machine.pop()
				for vIndex, vm in enumerate(vms):
					if (vIndex != 0):
						newVM = copy.deepcopy(baseVM)
						infoRspec.response.information.resources.server[sIndex].virtual_machine.append(newVM)
					InformationDispatcher.__VMmodelToClass(vm, infoRspec.response.information.resources.server[sIndex].virtual_machine[vIndex])

			resourcesString =   XmlHelper.craftXmlClass(infoRspec)
			localHashValue = str(hash(resourcesString))
		try:
			rHashObject =  resourcesHash.objects.get(projectUUID = projectUUID, sliceUUID = sliceUUID)
			rHashObject.hashValue = localHashValue
			rHashObject.save()
		except:
			rHashObject = resourcesHash(hashValue = localHashValue, projectUUID= projectUUID, sliceUUID = sliceUUID)
			rHashObject.save()

		if remoteHashValue == rHashObject.hashValue:
			return localHashValue, ''
		else:
			return localHashValue, resourcesString

	@staticmethod
	def listVMTemplatesInfo(serverUUID):
	#def listVMTemplatesInfo(serverUUID, callbackURL):
		logging.debug("Enter listVMTemplatesInfo")
		server = VTDriver.getServerByUUID(serverUUID)
		xmlrpc_server = xmlrpclib.Server(server.getAgentURL())
		templates_info = xmlrpc_server.list_vm_templates(server.getAgentPassword())
		#templates_info = xmlrpc_server.list_vm_templates(callbackURL, server.getAgentPassword())
		return str(templates_info)

        @staticmethod
        def forceListActiveVMs(serverID='None', vmID='None'):
                if serverID != 'None':
                    server = VTDriver.getServerById(serverID)
                    vtam_vms = server.getVMs()
                else:
                    if vmID != 'None':
                        servers = VTDriver.getAllServers()
                        vtam_vms = list()
                        for server in servers:
                            vtam_vms = server.getVMs(id=int(vmID))
                            if vtam_vms:
                                vmID = vtam_vms[0].getUUID()
                                break
                        if not vtam_vms:
                            raise Exception("VM not found")
                xmlrpc_server = xmlrpclib.Server(server.getAgentURL())
                # Handle safely the connection against the agent
                try:
                    server_active_vms = xmlrpc_server.force_list_active_vms(server.getAgentPassword(), vmID)
                    updated_vms = list()
                    for vm in vtam_vms:
                        if vm.getUUID() in server_active_vms.keys():
                            vm.setState("running")
                            vm.save()
                        else:
                            # XXX: avoiding "on queue" and "unknown" states to avoid bad management
                            #if vm.getState() in ['deleting...', 'failed', 'on queue', 'unknown']:
                            if vm.getState() in ["deleting...", "failed"]:
                                child = vm.getChildObject()
                                server = vm.Server.get()
                                #Action.objects.all().filter(objectUUID = vm.uuid).delete()
                                server.deleteVM(vm)
                                # Keep actions table up-to-date after each deletion
                                vm_uuids = [ vm.uuid for vm in VirtualMachine.objects.all() ]
                                Action.objects.all().exclude(objectUUID__in = vm_uuids).delete()
                            elif vm.getState() in ["running", "starting...", "stopping..."] :
                                vm.setState("stopped")
                                vm.save()
                            else:
                                continue
                except:
                    server_active_vms = dict()
                return server_active_vms

	@staticmethod
	def __ServerModelToClass(sModel, sClass ):
		sClass.name = sModel.getName()
		#XXX: CHECK THIS
		sClass.id = sModel.id
		sClass.uuid = sModel.getUUID()
		sClass.operating_system_type = sModel.getOSType()
		sClass.operating_system_distribution = sModel.getOSDistribution()
		sClass.operating_system_version = sModel.getOSVersion()
		sClass.virtualization_type = sModel.getVirtTech()
		ifaces = sModel.getNetworkInterfaces()
		for ifaceIndex, iface in enumerate(ifaces):
			if ifaceIndex != 0:
				newInterface = copy.deepcopy(sClass.interfaces.interface[0])
				sClass.interfaces.interface.append(newInterface)
			if iface.isMgmt:
				sClass.interfaces.interface[ifaceIndex].ismgmt = True
			else:
				sClass.interfaces.interface[ifaceIndex].ismgmt = False
			sClass.interfaces.interface[ifaceIndex].name = iface.name
			sClass.interfaces.interface[ifaceIndex].switch_id= iface.switchID
			sClass.interfaces.interface[ifaceIndex].switch_port = iface.port

	@staticmethod
	def __VMmodelToClass(VMmodel, VMxmlClass):

		VMxmlClass.name = VMmodel.getName()
		VMxmlClass.uuid = VMmodel.getUUID()
		VMxmlClass.status = VMmodel.getState()
		VMxmlClass.project_id = VMmodel.getProjectId()
		VMxmlClass.slice_id = VMmodel.getSliceId()
		VMxmlClass.project_name = VMmodel.getProjectName()
		VMxmlClass.slice_name = VMmodel.getSliceName()
		VMxmlClass.operating_system_type = VMmodel.getOSType()
		VMxmlClass.operating_system_version = VMmodel.getOSVersion()
		VMxmlClass.operating_system_distribution = VMmodel.getOSDistribution()
		VMxmlClass.virtualization_type = VMmodel.Server.get().getVirtTech()
		VMxmlClass.server_id = VMmodel.Server.get().getUUID()
		VMxmlClass.xen_configuration.hd_setup_type = VMmodel.getHdSetupType()
		VMxmlClass.xen_configuration.hd_origin_path = VMmodel.getHdOriginPath()
		VMxmlClass.xen_configuration.virtualization_setup_type = VMmodel.getVirtualizationSetupType()
		VMxmlClass.xen_configuration.memory_mb = VMmodel.getMemory()
		ActionController.PopulateNetworkingParams(VMxmlClass.xen_configuration.interfaces.interface, VMmodel)


text:
This addon provides an implementation of [emberjs/rfcs#65](https://github.com/emberjs/rfcs/blob/master/text/0065-deprecation-warning-handlers.md) (added to Ember in [emberjs/ember.js#11833](https://github.com/emberjs/ember.js/pull/11833) and released in Ember v2.1.0) that can be used with versions of Ember prior to v2.1.0.

This polyfill will be useful for other tooling related addons or app developers that want to add custom deprecation handlers.

## Contributing

### Installation

* `git clone <repository-url>` this repository
* `cd ember-debug-handlers-polyfill`
* `yarn install`

### Running

* `ember serve`
* Visit your app at [http://localhost:4200](http://localhost:4200).

### Running Tests

* `yarn test` (Runs `ember try:each` to test your addon against multiple Ember versions)
* `ember test`
* `ember test --server`

### Building

* `ember build`

For more information on using ember-cli, visit [https://ember-cli.com/](https://ember-cli.com/).

redpajama_set_name: RedPajamaGithub


text:
INTRA_API = "https://intra-api.etna-alternance.net"
ETNA_API = "https://auth.etna-alternance.net"
AUTH_URL = "https://auth.etna-alternance.net/login"
MODULE_API = "https://modules-api.etna-alternance.net"
GSA_API = "https://gsa-api.etna-alternance.net"
TICKET_API = "https://tickets.etna-alternance.net/api"
ACHIEVEMENTS_API = "https://achievements.etna-alternance.net/api"

IDENTITY_URL = ETNA_API + "/identity"
USER_INFO_URL = ETNA_API + "/api/users/{user_id}"
USER_PROMO_URL = INTRA_API + "/promo"
GRADES_URL = INTRA_API + "/terms/{promo_id}/students/{login}/marks"
NOTIF_URL = INTRA_API + "/students/{login}/informations"
ACTIVITY_URL = MODULE_API + "/students/{login}/currentactivities"
PICTURE_URL = ETNA_API + "/api/users/{login}/photo"
SEARCH_URL = MODULE_API + "/students/{login}/search"
ACTIVITIES_URL = MODULE_API + "/{module_id}/activities"
GROUPS_URL = INTRA_API + "/sessions/{module_id}/project/{project_id}/groups"
PROMOTION_URL = INTRA_API + "/trombi/{promo_id}"
GSA_EVENTS_URL = GSA_API + "/students/{login}/events"
GSA_LOGS_URL = GSA_API + "/students/{login}/logs"

EVENTS_URL = INTRA_API + "/students/{login}/events?end={end_date}&start={start_date}"
DECLARATION_URL = INTRA_API + "/modules/{module_id}/declareLogs"
DECLARATIONS_URL = GSA_API + "/students/{login}/declarations"

CONVERSATIONS_URL = INTRA_API + "/users/{user_id}/conversations"

TICKET_URL = TICKET_API + "/tasks/{task_id}.json"
TICKETS_URL = TICKET_API + "/tasks.json"

ACHIEVEMENTS_URL = ACHIEVEMENTS_API + "/users/{login}/achievements"


text:
/**
 * @file usart.c
 *
 * @brief
 * Provides USART input / output functions.
 *
 * By default functions for using both USART0 and USART1 is available with
 * buffered input and output. Each USART can be disabled by defining
 * NO_USART[n]_SUPPORT where n is either 0 or one 1. These must be defined at
 * compile time.
 */

#include <avr/interrupt.h>
#include <avr/io.h>
#include <stdbool.h>     // for bool
#include <stddef.h>      // for size_t
#include <stdint.h>      // for uint8_t, uint32_t, uint16_t
#include <stdio.h>       // for FILE, NULL, stdin, stdout

#include "usart.h"
#include "utils.h"       // for HIGH_BYTE, LOW_BYTE

enum usart_charSelect_t {
	USART_CHAR_5BIT = 0x00,
	USART_CHAR_6BIT = 0x01,
	USART_CHAR_7BIT = 0x02,
	USART_CHAR_8BIT = 0x03,
	USART_CHAR_9BIT = 0x07
};

#ifndef NO_USART0_SUPPORT
#include "ringbuffer.h"  // for ringbuffer_t, rb_init, rb_pop, rb_push, etc

	static volatile ringbuffer_t usart0_rb_in;
	static volatile ringbuffer_t usart0_rb_out;

	FILE usart0_io = FDEV_SETUP_STREAM(usart0_putc, usart0_getc, _FDEV_SETUP_RW);
	FILE usart0_byte_output = FDEV_SETUP_STREAM(usart0_putbyte, NULL, _FDEV_SETUP_WRITE);
#endif

#ifndef NO_USART1_SUPPORT
	static volatile ringbuffer_t usart1_rb_in;
	static volatile ringbuffer_t usart1_rb_out;

	FILE usart1_io = FDEV_SETUP_STREAM(usart1_putc, usart1_getc, _FDEV_SETUP_RW);
	FILE usart1_byte_output = FDEV_SETUP_STREAM(usart1_putbyte, NULL, _FDEV_SETUP_WRITE);
#endif

/**
 * Convert a given baud-rate to UBRR prescalar.
 * @param  baudrate Target baud-rate
 * @param  mode     UART operation mode
 * @return          UBRR prescalar
 */
static inline uint16_t uart_baud2ubrr(const uint32_t baudrate, enum usart_operationModes_t mode){
	uint16_t ubrr_val;
	switch (mode) {
		case USART_MODE_ASYNC_NORMAL:
			ubrr_val = ((F_CPU / (baudrate * 16UL))) - 1;
			break;
		case USART_MODE_ASYNC_DOUBLE:
			ubrr_val = ((F_CPU / (baudrate * 8UL))) - 1;
			break;
		case USART_MODE_SYNC_MASTER:
			ubrr_val = ((F_CPU / (baudrate * 2UL))) - 1;
			break;
		default:
			ubrr_val = 0;
			break;
	}
	return ubrr_val;
}

/**
 * @name USART0
 * Functions for sending and receiving on USART0
 * @{
 */
#ifndef NO_USART0_SUPPORT

/**
 * Set up the USART with defaults values.
 * Enables RX and TX 1 stop bit with 8bit char size in async normal mode. if a
 * zero value baudrate is give it will default to 115200.
 * @param baudrate the desired baudrate
 */
int usart0_init(uint32_t baudrate, uint8_t* in_buf, size_t in_size, uint8_t* out_buf, size_t out_size) {
	if (baudrate == 0) {
		baudrate = 115200;
	}

	int rc;

	rc = rb_init((ringbuffer_t*)&usart0_rb_in, in_buf, in_size);
	if (rc != 0) return rc;
	USART0_ENABLE_RX_INTERRUPT();

	rc = rb_init((ringbuffer_t*)&usart0_rb_out, out_buf, out_size);
	if (rc != 0) return rc;

	//Enable TXen and RXen
	USART0_ENABLE_RX();
	USART0_ENABLE_TX();

	USART0_SET_1_STOP_BIT();
	USART0_SET_CHAR_SIZE(USART_CHAR_8BIT);

	// Baud rate
	usart0_setBaudrate(baudrate, USART_MODE_ASYNC_NORMAL);

	stdout = stdin = &usart0_io;
	return rc;
}

/**
 * Set USART baud-rate and operation mode.
 * @param baudrate baud-rate that the USART will use
 * @param mode     USART operation mode
 */
void usart0_setBaudrate(const uint32_t baudrate,
						enum usart_operationModes_t mode){
	switch (mode) {
		case USART_MODE_ASYNC_NORMAL: USART0_SET_MODE_ASYNC(); break;
		case USART_MODE_ASYNC_DOUBLE: USART0_SET_MODE_ASYNC(); break;
		case USART_MODE_SYNC_MASTER: USART0_SET_MODE_SYNC(); break;
	}

	const uint16_t prescale = uart_baud2ubrr(baudrate, mode);

	UBRR0L = LOW_BYTE(prescale);
	UBRR0H = HIGH_BYTE(prescale);
}

/**
 * Check the input buffer for new data.
 * @return  true if it as data. Else false
 */
bool usart0_has_data(void){
	return !rb_isEmpty(&usart0_rb_in);
}

/**
 * Returns the number of bytes in input buffer.
 * @return size_t number of bytes.
 */
size_t usart0_input_buffer_bytes(void) {
	return rb_bytesUsed(&usart0_rb_in);
}

/**
 * Returns the number of bytes in output buffer.
 * @return size_t number of bytes.
 */
size_t usart0_output_buffer_bytes(void) {
	return rb_bytesUsed(&usart0_rb_out);
}

/**
 * Get a byte from USART. This call is alway blocking. if input buffer is
 * enabled use usart[N]_hasData() to check if data is available.
 * @return  received byte
 */
int usart0_getc(FILE *stream) {
	char data;
	while (!usart0_has_data());
	rb_pop((ringbuffer_t*)&usart0_rb_in, (uint8_t*)&data);
	return (int)data;
}

int usart0_putbyte(char c, FILE *stream) {
	// Wait for free space in buffer
	while (rb_isFull(&usart0_rb_out));
	rb_push((ringbuffer_t*)&usart0_rb_out, c);

	USART0_ENABLE_UDRE_INTERRUPT();
	return 0;
}

/**
 * Put a byte on USART. unless USART0_NON_UNIX_LIKE_LINE_ENDINGS is defined this
 * will put a '\r' before every '\n' to mimic Unix like line endings.
 * @param  c Byte to transmit
 * @return   positive if success
 */
int usart0_putc(char c, FILE *stream) {
#ifndef USART0_NON_UNIX_LIKE_LINE_ENDINGS
	if (c == '\n') {
		usart0_putbyte('\r', stream);
	}
#endif
	usart0_putbyte(c, stream);
	return 0;
}

ISR(USART0_RX_vect){
	uint8_t data = UDR0;
	//!< @TODO should we not check if the rb is full here!?
	rb_push((ringbuffer_t*)&usart0_rb_in, data);
}

ISR(USART0_UDRE_vect){
	uint8_t data;
	if (rb_pop((ringbuffer_t*)&usart0_rb_out, &data) == 0) {
		UDR0 = data;
	} else {
		// output buffer is empty so disable UDRE interrupt flag
		USART0_DISABLE_UDRE_INTERRUPT();
	}
}

#endif /* NO_USART0_SUPPORT */
/** @} */

/**
 * @name USART1
 * Functions for sending and receiving on USART1
 * @{
 */
#ifndef NO_USART1_SUPPORT

/**
 * Set up the USART with defaults values.
 * Enables RX and TX 1 stop bit with 8bit char size in async normal mode. if a
 * zero value baudrate is give it will default to 115200.
 * @param baudrate the desired baudrate
 */
int usart1_init(uint32_t baudrate, uint8_t* in_buf, size_t in_size, uint8_t* out_buf, size_t out_size) {
	if (baudrate == 0) {
		baudrate = 115200;
	}

	int rc;

	rc = rb_init((ringbuffer_t*)&usart1_rb_in, in_buf, in_size);
	if (rc != 0) return rc;
	USART1_ENABLE_RX_INTERRUPT();

	rc = rb_init((ringbuffer_t*)&usart1_rb_out, out_buf, out_size);
	if (rc != 0) return rc;

	//Enable TXen and RXen
	USART1_ENABLE_RX();
	USART1_ENABLE_TX();

	USART1_SET_1_STOP_BIT();
	USART1_SET_CHAR_SIZE(USART_CHAR_8BIT);

	// Baud rate
	usart1_setBaudrate(baudrate, USART_MODE_ASYNC_NORMAL);

	stdout = stdin = &usart1_io;
	return rc;
}

/**
 * Set USART baud-rate and operation mode.
 * @param baudrate baud-rate that the USART will use
 * @param mode     USART operation mode
 */
void usart1_setBaudrate(const uint32_t baudrate,
						enum usart_operationModes_t mode){
	switch (mode) {
		case USART_MODE_ASYNC_NORMAL: USART1_SET_MODE_ASYNC(); break;
		case USART_MODE_ASYNC_DOUBLE: USART1_SET_MODE_ASYNC(); break;
		case USART_MODE_SYNC_MASTER: USART1_SET_MODE_SYNC(); break;
	}

	const uint16_t prescale = uart_baud2ubrr(baudrate, mode);

	UBRR1L = LOW_BYTE(prescale);
	UBRR1H = HIGH_BYTE(prescale);
}

/**
 * Check the input buffer for new data.
 * @return  true if it as data. Else false
 */
bool usart1_has_data(void){
	return !rb_isEmpty(&usart1_rb_in);
}

/**
 * Returns the number of bytes in input buffer.
 * @return size_t number of bytes.
 */
size_t usart1_input_buffer_bytes(void) {
	return rb_bytesUsed(&usart1_rb_in);
}

/**
 * Returns the number of bytes in output buffer.
 * @return size_t number of bytes.
 */
size_t usart1_output_buffer_bytes(void) {
	return rb_bytesUsed(&usart1_rb_out);
}

/**
 * Get a byte from USART. This call is alway blocking. if input buffer is
 * enabled use usart[N]_hasData() to check if data is available.
 * @return  received byte
 */
int usart1_getc(FILE *stream) {
	char data = 0;
	while (!usart1_has_data());
	rb_pop((ringbuffer_t*)&usart1_rb_in, (uint8_t*)&data);
	return (int)data;
}

int usart1_putbyte(char b, FILE *stream) {
	// Wait for free space in buffer
	while (rb_isFull(&usart1_rb_out));
	rb_push((ringbuffer_t*)&usart1_rb_out, b);

	USART1_ENABLE_UDRE_INTERRUPT();
	return 0;
}

/**
 * Put a byte on USART. unless USART1_NON_UNIX_LIKE_LINE_ENDINGS is defined this
 * will put a '\r' before every '\n' to mimic Unix like line endings.
 * @param  c Byte to transmit
 * @return   positive if success
 */
int usart1_putc(char c, FILE *stream) {
	if (c == '\n') {
		usart1_putbyte('\r', stream);
	}
	usart1_putbyte(c, stream);
	return 0;
}

ISR(USART1_RX_vect){
	uint8_t data = UDR1;
	rb_push((ringbuffer_t*)&usart1_rb_in, data);
}

ISR(USART1_UDRE_vect){
	uint8_t data;
	if (rb_pop((ringbuffer_t*)&usart1_rb_out, &data) == 0) {
		UDR1 = data;
	} else {
		// output buffer is empty so disable UDRE interrupt flag
		USART1_DISABLE_UDRE_INTERRUPT();
	}
}

#endif /* NO_USART1_SUPPORT */
/** @} */


text:
CF11+ Member Functions allow variables of certain CFML data types to be treated as objects with functions. Invoking a member function on the object (the variable) allows you to skip passing the variable into the function because it already has a reference to the value.
The use of member functions often lead to more concise and readable code.

For instance, consider the following headless function:

    ArrayAppend(empArr, emp)

Using a member function it can be written as:

    empArr.append(emp)

Where `empArr` is a reference to an instance of a CFArray class (possibly a variable created with arrayNew).

The following example depicts the new usage of member functions:

    <cfscript>
        //The old way
        var myArray = ArrayNew(1);
        ArrayAppend(myArray, "objec_new");
        ArraySort(myArray, "ASC");

        // The new way
        myArray.append("objec_new");
        myArray.sort("ASC");

        // The new way
        var myProductObject = createObject("java", "myJavaclass");
        myjavaList = myProductObject.getProductList();
        myjavaList.add("newProduct"); // Java API

        myjavaList.append("newProduct"); // CF API
        myjavaList.sort("ASC");
    </cfscript>

Member functions for ColdFusion data types

Member functions for the following data types are supported:

- Array
- String
- List
- Struct
- Date
- Spreadsheet
- XML
- Query
- Image

## Array member functions

- ArrayAppend : `someVar.append()`
- ArrayAvg : `someVar.avg()`
- ArrayClear : `someVar.clear()`
- ArrayContains : `someVar.contains()`
- ArrayDelete : `someVar.delete()`
- ArrayDeleteAt : `someVar.deleteAt()`
- ArrayEach : `someVar.each()`
- ArrayFilter : `someVar.filter()`
- ArrayFind : `someVar.find()`
- ArrayFindAll : `someVar.findAll()`
- ArrayFindAllNoCase : `someVar.findAllNoCase()`
- ArrayFindNoCase : `someVar.findNoCase()`
- ArrayInsertAt : `someVar.insertAt()`
- ArrayIsDefined : `someVar.isDefined()`
- ArrayIsEmpty : `someVar.isEmpty()`
- ArrayLen : `someVar.len()`
- ArrayMap : `someVar.map()`
- ArrayMax : `someVar.max()`
- ArrayMin : `someVar.min()`
- ArrayPrepend : `someVar.prepend()`
- ArrayReduce : `someVar.reduce()`
- ArrayResize : `someVar.resize()`
- ArraySet : `someVar.set()`
- ArraySlice : `someVar.slice()`
- ArraySort : `someVar.sort()`
- ArraySum : `someVar.sum()`
- ArraySwap : `someVar.swap()`
- ArrayToList : `someVar.toList()`

## String member functions

- CJustify : `someVar.cJustify()`
- Compare : `someVar.compare()`
- CompareNoCase : `someVar.compareNocase()`
- Find : `someVar.find()`
- FindNoCase : `someVar.findNoCase()`
- FindOneOf : `someVar.findOneOf()`
- GetToken : `someVar.getToken()`
- Insert : `someVar.insert()`
- LCase : `someVar.lCase()`
- LJustify : `someVar.lJustify()`
- Left : `someVar.left()`
- Len : `someVar.len()`
- Mid : `someVar.mid()`
- RJustify : `someVar.rJustify()`
- RTrim : `someVar.trim()`
- RemoveChars : `someVar.removeChars()`
- RepeatString : `someVar.repeatString()`
- Replace : `someVar.replace()`
- ReplaceList : `someVar.replaceList()`
- ReplaceNoCase : `someVar.replaceNocase()`
- Reverse : `someVar.reverse()`
- Right : `someVar.right()`
- SpanExcluding : `someVar.spanExcluding()`
- SpanIncluding : `someVar.spanIncluding()`
- StripCR : `someVar.stripCR()`
- Trim : `someVar.trim()`
- UCase : `someVar.uCase()`
- Wrap : `someVar.wrap()`
- Decrypt : `someVar.Decrypt()`
- Encrypt : `someVar.Encrypt()`
- BinaryDecode : `someVar.BinaryDecode()`
- BinaryEncode : `someVar.BinaryEncode()`
- CharsetDecode : `someVar.CharsetDecode()`
- CharsetEncode : `someVar.CharsetEncode()`
- URLDecode : `someVar.URLDecode()`
- URLEncodedFormat : `someVar.URLEncodedFormat()`
- HTMLEditFormat : `someVar.HTMLEditFormat()`
- HTMLCodeFormat : `someVar.HTMLCodeFormat()`
- ParagraphFormat : `someVar.ParagraphFormat()`
- JSStringFormat : `someVar.JSStringFormat()`
- XmlFormat : `someVar.XmlFormat()`
- FormatBaseN : `someVar.FormatBaseN()`
- HTMLEditFormat : `someVar.HTMLEditFormat()`
- HTMLCodeFormat : `someVar.HTMLCodeFormat()`
- ParagraphFormat : `someVar.ParagraphFormat()`
- ToBinary : `someVar.ToBinary()`
- ToString : `someVar.ToString()`
- ToBase64 : `someVar.ToBase64()`
- Val : `someVar.Val()`
- GenerateSecretKey : `someVar.GenerateSecretKey()`
- Hash : `someVar.Hash()`
- REFind : `someVar.REFind()`
- REFindNoCase : `someVar.REFindNoCase()`
- REMatch : `someVar.REMatch()`
- REMatchNoCase : `someVar.REMatchNoCase()`
- REReplace : `someVar.REReplace()`
- REReplaceNoCase : `someVar.REReplaceNoCase()`
- ReplaceList : `someVar.ReplaceList()`
- LSParseEuroCurrency : `someVar.LSParseEuroCurrency()`
- LSParseDateTime : `someVar.LSParseDateTime()`
- LSIsCurrency : `someVar.LSIsCurrency()`
- LSIsDate : `someVar.LSIsDate()`
- LSIsNumeric : `someVar.LSIsNumeric()`
- LSParseCurrency : `someVar.LSParseCurrency()`
- LSParseNumber : `someVar.LSParseNumber()`
- ParseDateTime : `someVar.ParseDateTime()`

## List member functions

- ListAppend : `someVar.listAppend()`
- ListChangeDelims : `someVar.listChangeDelims()`
- ListContains : `someVar.listContains()`
- ListContainsNoCase : `someVar.listContainsNoCase()`
- ListDeleteAt : `someVar.listDeleteAt()`
- ListEach : `someVar.listEach()`
- ListFind : `someVar.listFind()`
- ListFindNoCase : `someVar.listFindNoCase()`
- ListFirst : `someVar.listFirst()`
- ListGetAt : `someVar.listGetAt()`
- ListInsertAt : `someVar.listInsertAt()`
- ListLast : `someVar.listLast()`
- ListLen : `someVar.listLen()`
- ListMap : `someVar.listMap()`
- ListPrepend : `someVar.listPrepend()`
- ListQualify : `someVar.listQualify()`
- ListReduce : `someVar.listReduce()`
- ListRest : `someVar.listRest()`
- ListSetAt : `someVar.listSetAt()`
- ListSort : `someVar.listSort()`
- ListToArray : `someVar.listToArray()`
- ListValueCount : `someVar.listValueCount()`
- ListValueCountNoCase : `someVar.listValueCountNoCase()`

## Struct member functions

- StructIsEmpty : `someVar.isEmpty()`
- StructAppend : `someVar.append()`
- StructClear : `someVar.clear()`
- StructCopy : `someVar.copy()`
- StructCount : `someVar.count()`
- StructDelete : `someVar.delete()`
- StructFind : `someVar.find()`
- StructFindValue : `someVar.findValue()`
- StructUpdate : `someVar.update()`
- StructSort : `someVar.sort()`
- StructInsert : `someVar.insert()`
- StructEach : `someVar.each()`
- StructKeyArray : `someVar.keyArray()`
- StructKeyExists : `someVar.keyExists()`
- StructKeyList : `someVar.keyList()`

## Date member functions

- CreateODBCDate : `someVar.createODBCDate()`
- CreateODBCDateTime : `someVar.createODBCDateTime()`
- DateDiff : `someVar.diff()`
- CreateODBCTime : `someVar.createODBCTime()`
- LSDateFormat : `someVar.lsDateFormat()`
- DatePart : `someVar.datepart()`
- DaysInYear : `someVar.daysIn`
- Second : `someVar.second()`
- Minute : `someVar.minute()`
- Hour : `someVar.hour()`
- Day : `someVar.day()`
- Week : `someVar.week()`
- Month : `someVar.month()`
- Quarter : `someVar.quarter()`
- Year : `someVar.year()`
- DaysInMonth : `someVar.daysInMonth()`
- DayOfWeek : `someVar.dayOfweek()`
- DayOfYear : `someVar.dayOfYear()`
- FirstDayOfMonth : `someVar.firstDayOfMonth()`
- DateTimeFormat : `someVar.dateTimeFormat()`
- TimeFormat : `someVar.timeFormat()`
- DateFormat : `someVar.dateFormat()`
- DateAdd : `someVar.add()`
- DateConvert : `someVar.convert()`

## Image member functions

- ImageGetWidth : `someVar.getWidth()`
- ImageSetDrawingColor : `someVar.setDrawingColor()`
- ImageGetBufferedImage : `someVar.getBufferedImage()`
- ImageTranslateDrawingAxis : `someVar.translateDrawingAxis()`
- ImageSetDrawingStroke : `someVar.setDrawingStroke()`
- ImageNegative : `someVar.negative()`
- ImageCopy : `someVar.copy()`
- ImageDrawRect : `someVar.drawRect()`
- ImageCrop : `someVar.crop()`
- ImageGetHeight : `someVar.getHeight()`
- ImageGetIPTCTag : `someVar.getIPTCTag()`
- ImageDrawOval : `someVar.drawOval()`
- ImageSharpen : `someVar.sharpen()`
- ImageOverlay : `someVar.overlay()`
- ImageGetEXIFTag : `someVar.getEXIFTag()`
- ImageDrawBeveledRect : `someVar.drawBeveledRect()`
- ImageAddBorder : `someVar.addBorder()`
- ImageShear : `someVar.shear()`
- ImageInfo : `someVar.info()`
- ImagePaste : `someVar.paste()`
- ImageDrawArc : `someVar.drawArc()`
- ImageShearDrawingAxis : `someVar.shearDrawingAxis()`
- ImageDrawRoundRect : `someVar.drawRoundRect()  `
- ImageGrayscale : `someVar.grayscale()`
- ImageSetDrawingTransparency : `someVar.setDrawingTransparency()`
- ImageScaleToFit : `someVar.scaleToFit()`
- ImageClearRect : `someVar.clearRect()`
- ImageTranslate : `someVar.translate()`
- ImageFlip : `someVar.flip()`
- ImageWriteBase64 : `someVar.writeBase64()`
- ImageSetBackgroundColor : `someVar.setBackgroundColor()`
- ImageDrawLine : `someVar.drawLine()`
- ImageDrawQuadraticCurve : `someVar.drawQuadraticCurve()`
- ImageRotate : `someVar.rotate()`
- ImageGetBlob : `someVar.getBlob()`
- ImageWrite : `someVar.write()`
- ImageBlur : `someVar.blur()`
- ImageRotateDrawingAxis : `someVar.rotateDrawingAxis()`
- ImageSetAntialiasing : `someVar.setAntialiasing()`
- ImageDrawPoint : `someVar.drawPoint()`
- ImageDrawCubicCurve : `someVar.drawCubicCurve()`
- ImageXORDrawingMode : `someVar.xorDrawingMode()`
- ImageDrawText : `someVar.drawText()`
- ImageDrawLines : `someVar.drawLines()`
- ImageResize : `someVar.resize()`

## Spreadsheet member functions

- SpreadsheetDeleteRow : `someVar.deleteRow()`
- SpreadsheetFormatColumn : `someVar.formatColumn()`
- SpreadsheetShiftRows : `someVar.shiftRows()`
- SpreadsheetCreateSheet : `someVar.createSheet()`
- SpreadsheetReadBinary : `someVar.readBinary()`
- SpreadsheetWrite : `someVar.write()`
- SpreadsheetAddRow : `someVar.addRow()`
- SpreadsheetShiftColumns : `someVar.shiftColumns()`
- SpreadsheetGetCellFormula : `someVar.getCellFormula()`
- SpreadsheetDeleteColumns : `someVar.deleteColumns()`
- SpreadsheetAddFreezePane : `someVar.addFreezePane()`
- SpreadsheetDeleteColumn : `someVar.deleteColumn()`
- SpreadsheetSetCellComment : `someVar.setCellComment()`
- SpreadsheetSetActiveSheetNumber : `someVar.setActiveSheetNumber()`
- SpreadsheetSetHeader : `someVar.setHeader()`
- SpreadsheetAddSplitPane : `someVar.addSplitPane()`
- SpreadsheetMergeCells : `someVar.mergeCells()`
- SpreadsheetFormatRows : `someVar.formatRows()`
- SpreadsheetGetCellComment : `someVar.getCellComment()`
- SpreadsheetGetCellValue : `someVar.getCellValue()`
- SpreadsheetAddInfo : `someVar.addInfo()`
- SpreadsheetSetCellValue : `someVar.setCellValue()`
- SpreadsheetSetFooter : `someVar.setFooter()`
- SpreadsheetRemoveSheet : `someVar.removeSheet()`
- SpreadsheetSetRowHeight : `someVar.setRowHeight()`
- SpreadsheetSetActiveSheet : `someVar.setActiveSheet()`
- SpreadsheetFormatCellRange : `someVar.formatCellRange()`
- SpreadsheetFormatCell : `someVar.formatCell()`
- SpreadsheetAddRows : `someVar.addRows()`
- SpreadsheetFormatColumns : `someVar.formatColumns()`
- SpreadsheetAddImage : `someVar.addImage()`
- SpreadsheetSetCellFormula : `someVar.setCellFormula()`
- SpreadsheetAddColumn : `someVar.addColumn()`
- SpreadsheetDeleteRows : `someVar.deleteRows()`
- SpreadsheetSetColumnWidth : `someVar.setColumnWidth()`
- SpreadsheetFormatRow : `someVar.formatRow()`
- SpreadsheetInfo : `someVar.info()`

## XML member functions

- XmlTransform : `someVar.transform()`
- XmlGetNodeType : `someVar.getNodeType()`
- XmlChildPos : `someVar.childPos()`
- XmlElemNew : `someVar.elemNew()`
- XmlSearch : `someVar.search()`

## Query member functions

- QueryAddColumn : `someVar.addColumn()`
- QueryGetResult : `someVar.getResult()`
- QueryGetRow : `someVar.getRow()`
- QueryConvertForGrid : `someVar.convertForGrid()`
- QuerySetCell : `someVar.setCell()`
- QueryAddRow : `someVar.addRow()`

When using Query.cfc, you get your results from the execution by using:

- `someVar.getResult()`

Member Functions can also be chained, for example:

    s="the";
    s = s.listAppend("quick brown fox", " ")
         .listAppend("jumps over the lazy dog", " ")
         .ucase()
         .reverse();

result: `GOD YZAL EHT REVO SPMUJ XOF NWORB KCIUQ EHT`

# Important Note on a potential Member Function Gotcha

Some member functions [might fall into underlying Java methods][note] if the strict ColdFusion syntax is not followed.

[note]: https://bugbase.adobe.com/index.cfm?event=bug&id=3753710


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;

namespace LibPearDataPoint
{
    /// <summary>
    /// A static class providing a simple interface to datapoint service
    /// </summary>
    internal static class DataPointServiceClient
    {
        /// <summary>
        /// Gets dataitem from a service
        /// </summary>
        /// <param name="endpoint">endpoint from which the dataitem should be taken</param>
        /// <param name="name">name of the requested dataitem</param>
        /// <returns></returns>
        internal static DataItem GetDataItem(IPEndPoint endpoint, string name)
        {
            if(!Utils.IsNameValid(name))
            {
                // invalid name was requested
                Trace.WriteLine(string.Format("GetDataItem: Ivalid name {0}", name ?? "null"));
                return null;
            }

            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    socket.Connect(endpoint);
                    socket.NoDelay = true;

                    using (var networkStream = new NetworkStream(socket))
                    using (var streamWriter = new StreamWriter(networkStream))
                    using (var streamReader = new StreamReader(networkStream))
                    {
                        streamWriter.AutoFlush = true;
                        streamWriter.WriteLine("{0};{1}", GlobalConstants.Commands.Get, name);
                        var receivedData = streamReader.ReadLine();

                        if (string.IsNullOrWhiteSpace(receivedData))
                        {
                            Trace.WriteLine("received empty response");
                            return null;
                        }

                        if (receivedData.StartsWith("OK")) // ok message was received
                        {
                            var data = receivedData.Split(';');
                            if (data.Length < 3)
                            {
                                Trace.WriteLine(string.Format("Response format incorrect {0}", receivedData));
                                return null;
                            }

                            DateTime dateTime;
                            if (!DateTime.TryParse(data[1], out dateTime))
                            {
                                Trace.WriteLine(string.Format("Could not parse datetime from response: {0}", receivedData));
                                return null;
                            }

                            var strings = new List<string>();
                            for (var i = 2; i < data.Length; i++)
                            {
                                strings.Add(data[i]);
                            }

                            // if value consisted of semicollons, then it would be put back together after separation
                            var value = string.Join(";", data.Skip(2));

                            // complete dataitem is returned
                            return new DataItem
                            {
                                IsLocal = false,
                                IsReliable = true,
                                LastUpdateTime = dateTime,
                                Name = name,
                                Value = value
                            };
                        }

                        var errorMessageData = receivedData.Split(';');
                        if (errorMessageData.Length == 1)
                        {
                            Trace.WriteLine("Unknown Error when getting dataitem");
                            return null;
                        }

                        if (errorMessageData.Length == 2)
                        {
                            Trace.WriteLine(string.Format("Error when getting dataitem: {0}", errorMessageData[1]));
                            return null;
                        }

                        Trace.WriteLine(string.Format("Response format incorrect {0}", receivedData));
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception when getting item {0} from {1} (Exception: {2})", name ?? string.Empty, endpoint, ex.Message));
                return null;
            }
        }

        /// <summary>
        /// Updates distant dataitem
        /// </summary>
        /// <param name="endpoint">enpoint where the dataitem iterface service is provided</param>
        /// <param name="name">name of the dataitem to be updated</param>
        /// <param name="value">new value of the dataitem</param>
        /// <returns></returns>
        internal static bool UpdateDataItem(IPEndPoint endpoint, string name, string value)
        {
            if (!Utils.IsNameValid(name))
            {
                // invalid name was requested
                Trace.WriteLine(string.Format("UpdateDataItem: Ivalid name {0}", name ?? "null"));
                return false;
            }

            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    socket.Connect(endpoint);
                    socket.NoDelay = true;

                    using (var networkStream = new NetworkStream(socket))
                    using (var streamWriter = new StreamWriter(networkStream))
                    using (var streamReader = new StreamReader(networkStream))
                    {
                        streamWriter.AutoFlush = true;
                        streamWriter.WriteLine("{0};{1};{2}", GlobalConstants.Commands.Update, name, value);
                        var receivedData = streamReader.ReadLine();

                        if (string.IsNullOrWhiteSpace(receivedData))
                        {
                            Trace.WriteLine("received empty response");
                            return false;
                        }

                        if (receivedData.StartsWith("OK")) // ok message was received
                        {
                            return true;
                        }

                        var errorMessageData = receivedData.Split(';');
                        if (errorMessageData.Length <= 1)
                        {
                            Trace.WriteLine("Unknown Error when updating dataitem");
                            return false;
                        }

                        if (errorMessageData.Length == 2)
                        {
                            Trace.WriteLine(string.Format("Error when updating dataitem: {0}", errorMessageData[1]));
                            return false;
                        }

                        Trace.WriteLine(string.Format("Response format incorrect {0}", receivedData));
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception when updating item {0} from {1} (Exception: {2})", name ?? string.Empty, endpoint, ex.Message));
                return false;
            }
        }

        /// <summary>
        /// This method informs the service, that there was an updata of subscribed data
        /// </summary>
        /// <param name="endpoint">enpoint where the dataitem iterface service is provided</param>
        /// <param name="data item name">updated dataitem name</param>
        /// <param name="data item value">updated dataitem value</param>
        /// <returns>true if update was successful</returns>
        internal static bool ChangeEvent(IPEndPoint endpoint, string name, string value)
        {
            if (!Utils.IsNameValid(name))
            {
                // invalid dataitem
                Trace.WriteLine(string.Format("UpdateDataItem: Ivalid name {0}", name ?? "null"));
                return false;
            }

            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    socket.Connect(endpoint);
                    socket.NoDelay = true;

                    using (var networkStream = new NetworkStream(socket))
                    using (var streamWriter = new StreamWriter(networkStream))
                    using (var streamReader = new StreamReader(networkStream))
                    {
                        streamWriter.AutoFlush = true;
                        streamWriter.WriteLine("{0};{1};{2}", GlobalConstants.Commands.ChangeEvent, name, value);
                        var receivedData = streamReader.ReadLine();

                        if (string.IsNullOrWhiteSpace(receivedData))
                        {
                            Trace.WriteLine("received empty response");
                            return false;
                        }

                        if (receivedData.StartsWith("OK")) // ok message was received
                        {
                            return true;
                        }

                        var errorMessageData = receivedData.Split(';');
                        if (errorMessageData.Length <= 1)
                        {
                            Trace.WriteLine("Unknown Error when informing about change of dataitem");
                            return false;
                        }

                        if (errorMessageData.Length == 2)
                        {
                            Trace.WriteLine(string.Format("Error when informing about change of dataitem: {0}", errorMessageData[1]));
                            return false;
                        }

                        Trace.WriteLine(string.Format("Response format incorrect {0}", receivedData));
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception when informing about change of item {0} from {1} (Exception: {2})", name ?? string.Empty, endpoint, ex.Message));
                return false;
            }
        }

        /// <summary>
        /// Subscribe to dataitem in distant endpoint
        /// </summary>
        /// <param name="endpoint">dataitem origin</param>
        /// <param name="name">name of the dataitem</param>
        /// <returns>true if success</returns>
        internal static bool Subscribe(IPEndPoint endpoint, string name)
        {
            if (!Utils.IsNameValid(name))
            {
                // invalid dataitem
                Trace.WriteLine(string.Format("UpdateDataItem: Ivalid name {0}", name ?? "null"));
                return false;
            }

            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    socket.Connect(endpoint);
                    socket.NoDelay = true;

                    using (var networkStream = new NetworkStream(socket))
                    using (var streamWriter = new StreamWriter(networkStream))
                    using (var streamReader = new StreamReader(networkStream))
                    {
                        streamWriter.AutoFlush = true;
                        streamWriter.WriteLine("{0};{1};{2}", GlobalConstants.Commands.Subscribe, name, Pear.ServicePort);
                        var receivedData = streamReader.ReadLine();

                        if (string.IsNullOrWhiteSpace(receivedData))
                        {
                            Trace.WriteLine("received empty response");
                            return false;
                        }

                        if (receivedData.StartsWith("OK")) // ok message was received
                        {
                            return true;
                        }

                        var errorMessageData = receivedData.Split(';');
                        if (errorMessageData.Length <= 1)
                        {
                            Trace.WriteLine("Unknown Error when subscribing to dataitem");
                            return false;
                        }

                        if (errorMessageData.Length == 2)
                        {
                            Trace.WriteLine(string.Format("Error when subscribing to dataitem: {0}", errorMessageData[1]));
                            return false;
                        }

                        Trace.WriteLine(string.Format("Response format incorrect {0}", receivedData));
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception when subscribing to item {0} from {1} (Exception: {2})", name ?? string.Empty, endpoint, ex.Message));
                return false;
            }
        }

        /// <summary>
        /// Pinging service - connectivity check
        /// </summary>
        /// <param name="endpoint">service endpoint</param>
        /// <returns>true if success</returns>
        internal static bool Ping(IPEndPoint endpoint)
        {
            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    socket.Connect(endpoint);
                    socket.NoDelay = true;

                    using (var networkStream = new NetworkStream(socket))
                    using (var streamWriter = new StreamWriter(networkStream))
                    using (var streamReader = new StreamReader(networkStream))
                    {
                        streamWriter.AutoFlush = true;
                        streamWriter.WriteLine("{0};0", GlobalConstants.Commands.Ping);
                        var receivedData = streamReader.ReadLine();

                        if (string.IsNullOrWhiteSpace(receivedData))
                        {
                            Trace.WriteLine("received empty response");
                            return false;
                        }

                        if (receivedData.StartsWith("OK")) // ok message was received
                        {
                            return true;
                        }

                        var errorMessageData = receivedData.Split(';');
                        if (errorMessageData.Length <= 1)
                        {
                            Trace.WriteLine("Unknown Error when pinging");
                            return false;
                        }

                        if (errorMessageData.Length == 2)
                        {
                            Trace.WriteLine(string.Format("Error when pinging: {0}", errorMessageData[1]));
                            return false;
                        }

                        Trace.WriteLine(string.Format("Response format incorrect {0}", receivedData));
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception when pinging: {0}", ex.Message));
                return false;
            }
        }
    }
}


text:
"""
:Abstract: Given an abundance table, calculate pairwise Spearman's Rho of the columns.
:Date: 02/15/2017
:Author: Akshay Paropkari
"""

import sys
import argparse
from traceback import format_exc
from time import localtime, strftime
from itertools import combinations
from phylotoast.util import parse_map_file, gather_categories
from phylotoast.biom_calc import arcsine_sqrt_transform as ast, relative_abundance
importerrors = set()
try:
    import biom
except ImportError:
    importerrors.add("biom")
try:
    import numpy as np
except ImportError:
    importerrors.add("numpy")
try:
    from multiprocessing import Pool, current_process
except ImportError:
    importerrors.add("multiprocessing")
try:
    from statsmodels.sandbox.stats.multicomp import fdrcorrection0 as FDR
except ImportError:
    importerrors.add("statsmodels")
try:
    from scipy.stats import rankdata, spearmanr as Spearman, kendalltau as KendallTau
except ImportError:
    importerrors.add("scipy")
if len(importerrors) > 0:
    for err in importerrors:
        print("Please install missing module: {}".format(err))
    sys.exit()

def calc_corr(otu_combos, gather_categories, abd_data):
    """This function calculates the pairwise spearman correlation for each group."""
    starttime = strftime("%x | %X".format(localtime))
    print("{0} | Core-{1}".format(starttime, current_process().name.split("-")[1]))
    result = []
    for combo in otu_combos:
        list1 = []
        list2 = []
        otu1 = combo[0]
        otu2 = combo[1]
        for cat in gather_categories.keys():
            for sid in gather_categories[cat].sids:
                list1.append(abd_data[sid][otu1])
                list2.append(abd_data[sid][otu2])
        try:
            assert len(list1) == len(list2)
        except AssertionError:
            sys.exit("Abundance array lengths do not match.")
        rho_corr, rho_p_val = Spearman(rankdata(list1, "ordinal"),
                                       rankdata(list2, "ordinal"))
        result.append(["Spearman", cat, otu1, otu2, rho_corr, rho_p_val])
        kendall_corr, kendall_p_val = KendallTau(rankdata(list1, "ordinal"),
                                                 rankdata(list2, "ordinal"))
        result.append(["Kendall", cat, otu1, otu2, kendall_corr, kendall_p_val])
    return result

def calc_corr_helper(args):
    """Helper function to use Pool.map() one-argument worker functions."""
    return calc_corr(*args)

def run_fdr(result_list):
    """Run BH FDR correction on correlation results."""
    try:
        assert all(isinstance(x, list) for x in result_list) is True
    except AssertionError:
        sys.exit("Data format for FDR Correction not compatible. Please check.")
    else:
        p_vals = [entry[-1] for entry in result_list]
        hypothesis, pvals_corrected = FDR(p_vals)
        idx_to_retain = np.where(np.array(pvals_corrected) < 0.05)[0].tolist()
        print("{} correlations removed through multiple test correction."
              .format(len(result_list) - len(idx_to_retain)))
    updated_result = []
    for idx in idx_to_retain:
        updated_p_val = pvals_corrected[idx]
        updated_result.append((result_list[idx][0], result_list[idx][1],
                               result_list[idx][2], result_list[idx][3],
                               result_list[idx][4], updated_p_val,))
    return updated_result

def program_options():
    """Function to house the user inputs."""
    parser = argparse.ArgumentParser(
        description=("Given an abundance table, calculate and return FDR corrected "
                     "significant pairwise Spearman's Rho."))
    parser.add_argument("in_biomf", help="Input abundance file containing OTU names as "
                        "columns and SampleIDs as rows. Ideally, this is the output from "
                        "biom_relative_abundance.py script.")
    parser.add_argument("map_fnh", help="Mapping file associated with input BIOM file.")
    parser.add_argument("category_column", help="Column name from mapping file which is "
                        "associated with categories.")
    parser.add_argument("out_fnh", help="Path and name to output correlation matrix file."
                        " The format for the tab-separated file will be: Category -> "
                        "Variable -> by Variable -> Correlation")
    return parser.parse_args()

def main():
    args = program_options()

    try:
        biomf = biom.load_table(args.in_biomf)
    except IOError as ioe:
        sys.exit("Error with input BIOM format file: {}".format(ioe))
    else:
        rel_abd = relative_abundance(biomf)
        ast_rel_abd = ast(rel_abd)
        # Get pairwise combinations of OTUs
        otu_combos = list(combinations(biomf.ids("observation"), 2))

    try:
        mheader, mdata = parse_map_file(args.map_fnh)
    except IOError as ioe:
        sys.exit("Error with input mapping file: {}".format(ioe))
    else:
        # Gather sampleID categories
        sid_cat = gather_categories(mdata, mheader, [args.category_column])

    # Create arguments for helper function to be supplied to multiprocessing pool.map()
    chunksize = 10000
    jobs = [(otu_combos[x:x+chunksize], sid_cat, ast_rel_abd,)
            for x in xrange(0, len(otu_combos), chunksize)]
    print("{0} jobs created.".format(len(jobs)))

    # Start multiprocessing jobs
    try:
        print("Starting map_async()...")
        pool = Pool()
        res = pool.map_async(calc_corr_helper, jobs)
        pool.close()
        pool.join()
    except Exception:
        sys.exit("Error while calculating correlations\n{}".format(format_exc()))
    else:
        s_rho_calc = []
        k_tau_calc = []
        for r in res.get():
            for s in r:
                if s[0] == "Spearman":
                    s_rho_calc.append(s)
                else:
                    k_tau_calc.append(s)

    # Get FDR corrected correlation results
    print("Running FDR correction on {} Spearman's Rho.".format(len(s_rho_calc)))
    fdr_corr_s_rho = run_fdr(s_rho_calc)
    print("Running FDR correction on {} Kendall Tau.".format(len(k_tau_calc)))
    fdr_corr_k_tau = run_fdr(k_tau_calc)

    # Consolidate correlation results
    k_kos = {(e[2], e[3],) for e in fdr_corr_k_tau}
    s_kos = {(f[2], f[3],) for f in fdr_corr_s_rho}
    final_kos = s_kos & k_kos
    print("{0} elements from KendallTau\n{1} elements from SpearmanRho\n{2} elements are "
          "common to both.".format(len(k_kos), len(s_kos), len(final_kos)))
    final_fdr_corr_results = [cdata[1:] for cdata in fdr_corr_s_rho
                              if (cdata[2], cdata[3],) in final_kos]

    # Write our results to file
    with open(args.out_fnh, "w") as outf:
        outf.write("Category\tVariable\tby Variable\tCorrelation\tp value\n")
        for k in final_fdr_corr_results:
            outf.write("{0}\t{1}\t{2}\t{3}\t{4}\n".format(k[0], k[1], k[2], k[3], k[4]))

if __name__ == "__main__":
    sys.exit(main())


text:
#import <Foundation/Foundation.h>

#import <Parse/PFRelation.h>

@class PFDecoder;

@interface PFRelation (Private)

+ (PFRelation *)relationForObject:(PFObject *)parent forKey:(NSString *)key;
+ (PFRelation *)relationWithTargetClass:(NSString *)targetClass;
+ (PFRelation *)relationFromDictionary:(NSDictionary *)dictionary withDecoder:(PFDecoder *)decoder;
- (void)ensureParentIs:(PFObject *)someParent andKeyIs:(NSString *)someKey;
- (NSDictionary *)encodeIntoDictionary;
- (BOOL)_hasKnownObject:(PFObject *)object;
- (void)_addKnownObject:(PFObject *)object;
- (void)_removeKnownObject:(PFObject *)object;

@end


text:
Initializers
================

All ruby files in this directory are loaded by ActionFramework at runtime after your settings and routes were loaded.

You can put database connection initializers in here for example.


text:
<?php

namespace Kunstmaan\MultiDomainBundle\Helper;

use Doctrine\ORM\EntityManagerInterface;
use Kunstmaan\AdminBundle\Helper\AdminRouteHelper;
use Kunstmaan\AdminBundle\Helper\DomainConfiguration as BaseDomainConfiguration;
use Kunstmaan\NodeBundle\Entity\Node;
use Symfony\Component\HttpFoundation\RequestStack;

class DomainConfiguration extends BaseDomainConfiguration
{
    const OVERRIDE_HOST = '_override_host';
    const SWITCH_HOST = '_switch_host';

    /**
     * @var array
     */
    protected $hosts;

    /**
     * @var array
     */
    protected $aliases = [];

    /**
     * @var AdminRouteHelper
     */
    protected $adminRouteHelper;

    /** @var array */
    private $rootNodeCache = [];

    /** @var EntityManagerInterface */
    private $em;

    public function __construct(RequestStack $requestStack, bool $multilanguage, string $defaultLocale, string $requiredLocales, AdminRouteHelper $adminRouteHelper, EntityManagerInterface $em, array $hosts)
    {
        parent::__construct($requestStack, $multilanguage, $defaultLocale, $requiredLocales);

        $this->adminRouteHelper = $adminRouteHelper;
        $this->hosts = $hosts;
        $this->em = $em;

        foreach ($this->hosts as $host => $hostInfo) {
            if (isset($hostInfo['aliases'])) {
                foreach ($hostInfo['aliases'] as $alias) {
                    $this->aliases[$alias] = $host;
                }
            }
        }
    }

    /**
     * @return string
     */
    public function getHost()
    {
        if ($this->hasHostOverride()) {
            return $this->getHostOverride();
        }

        $host = parent::getHost();
        if (isset($this->aliases[$host])) {
            $host = $this->aliases[$host];
        }

        return $host;
    }

    /**
     * @return array
     */
    public function getHosts()
    {
        return array_keys($this->hosts);
    }

    /**
     * @return string
     */
    public function getDefaultLocale()
    {
        $host = $this->getHost();
        if (isset($this->hosts[$host]['default_locale'])) {
            return $this->hosts[$host]['default_locale'];
        }

        return parent::getDefaultLocale();
    }

    /**
     * @param string|null $host
     *
     * @return bool
     */
    public function isMultiLanguage($host = null)
    {
        $host = $this->getRealHost($host);

        if (isset($this->hosts[$host])) {
            $hostInfo = $this->hosts[$host];

            return 'multi_lang' === $hostInfo['type'];
        }

        return parent::isMultiLanguage();
    }

    /**
     * @param string|null $host
     *
     * @return array
     */
    public function getFrontendLocales($host = null)
    {
        $host = $this->getRealHost($host);

        if (isset($this->hosts[$host]['locales'])) {
            return array_keys($this->hosts[$host]['locales']);
        }

        return parent::getBackendLocales();
    }

    /**
     * @param string|null $host
     *
     * @return array
     */
    public function getBackendLocales($host = null)
    {
        $host = $this->getRealHost($host);

        if (isset($this->hosts[$host]['locales'])) {
            return array_values($this->hosts[$host]['locales']);
        }

        return parent::getBackendLocales();
    }

    /**
     * @return bool
     */
    public function isMultiDomainHost()
    {
        $host = $this->getHost();

        return isset($this->hosts[$host]);
    }

    /**
     * Fetch the root node for the current host
     *
     * @param string|null $host
     *
     * @return Node|null
     */
    public function getRootNode($host = null)
    {
        if (!$this->isMultiDomainHost()) {
            return parent::getRootNode();
        }

        $host = $this->getRealHost($host);
        if (null === $host) {
            return null;
        }

        if (!array_key_exists($host, $this->rootNodeCache)) {
            $internalName = $this->hosts[$host]['root'];
            $nodeRepo = $this->em->getRepository(Node::class);
            $this->rootNodeCache[$host] = $nodeRepo->getNodeByInternalName($internalName);
        }

        return $this->rootNodeCache[$host];
    }

    /**
     * Return (optional) extra config settings for the current host
     */
    public function getExtraData()
    {
        $host = $this->getHost();

        if (!isset($this->hosts[$host]['extra'])) {
            return parent::getExtraData();
        }

        return $this->hosts[$host]['extra'];
    }

    /**
     * Return (optional) extra config settings for the locales for the current host
     */
    public function getLocalesExtraData()
    {
        $host = $this->getHost();

        if (!isset($this->hosts[$host]['locales_extra'])) {
            return parent::getLocalesExtraData();
        }

        return $this->hosts[$host]['locales_extra'];
    }

    /**
     * @return bool
     */
    protected function hasHostOverride()
    {
        $request = $this->getMasterRequest();

        return !\is_null($request) &&
        $this->adminRouteHelper->isAdminRoute($request->getRequestUri()) &&
        $request->hasPreviousSession() &&
        $request->getSession()->has(self::OVERRIDE_HOST);
    }

    /**
     * @return bool
     */
    public function hasHostSwitched()
    {
        $request = $this->getMasterRequest();

        return !\is_null($request) &&
        $this->adminRouteHelper->isAdminRoute($request->getRequestUri()) &&
        $request->hasPreviousSession() &&
        $request->getSession()->has(self::SWITCH_HOST);
    }

    /**
     * @return string|null
     */
    protected function getHostOverride()
    {
        if (null !== ($request = $this->getMasterRequest()) && $request->hasPreviousSession()) {
            return $request->getSession()->get(self::OVERRIDE_HOST);
        }

        return null;
    }

    /**
     * @return array
     */
    public function getHostSwitched()
    {
        $request = $this->getMasterRequest();

        $host = $this->getHost();

        if ($this->hasHostSwitched()) {
            $host = $request->getSession()->get(self::SWITCH_HOST);
        }

        return $this->hosts[$host];
    }

    /**
     * @return array
     */
    public function getFullHostConfig()
    {
        return $this->hosts;
    }

    /**
     * @param string|null $host
     *
     * @return array
     */
    public function getFullHost($host = null)
    {
        $host = $this->getRealHost($host);

        if ($host && isset($this->hosts[$host])) {
            return $this->hosts[$host];
        }

        return null;
    }

    /**
     * @param string|int $id
     *
     * @return array
     */
    public function getFullHostById($id)
    {
        foreach ($this->hosts as $host => $parameters) {
            if (!isset($parameters['id']) || $parameters['id'] !== $id) {
                continue;
            }

            return $parameters;
        }

        return null;
    }

    /**
     * @param string|null $host
     *
     * @return string|null
     */
    public function getHostBaseUrl($host = null)
    {
        $config = $this->getFullHost($host);

        if (!is_array($config)) {
            return null;
        }

        return sprintf('%s://%s', $config['protocol'], $config['host']);
    }

    /**
     * @param string|null $host
     *
     * @return string|null
     */
    private function getRealHost($host = null)
    {
        if (!$host) {
            $host = $this->getHost();
        }

        return $host;
    }
}


text:
using System;
using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serializers;
using SageOneApi.Interfaces;
using SageOneApi.Models;

namespace SageOneApi.Requests
{
    public class CustomerNoteRequest:RequestBase, ICustomerNoteRequest
    {
        public CustomerNoteRequest(IRestClient client, string apiKey, int companyId) : base(client, apiKey, companyId) { }

        public CustomerNote Get(int id)
        {
            var response = _client.Execute<CustomerNote>(new RestRequest(string.Format("CustomerNote/Get/{0}?apikey={1}&companyid={2}", id, _apiKey, _companyId), Method.GET));
            return response.Data;
        }

        public PagingResponse<CustomerNote> Get(string filter = "", int skip = 0)
        {
            var url = string.Format("CustomerNote/Get?apikey={0}&companyid={1}", _apiKey, _companyId);

            if (!string.IsNullOrEmpty(filter))
                url = string.Format("CustomerNote/Get?apikey={0}&companyid={1}&$filter={2}", _apiKey, _companyId, filter);

            if (skip > 0)
                url += "&$skip=" + skip;

            var request = new RestRequest(url, Method.GET);
            request.RequestFormat = DataFormat.Json;

            var response = _client.Execute(request);
            JsonDeserializer deserializer = new JsonDeserializer();

            return deserializer.Deserialize<PagingResponse<CustomerNote>>(response);
        }

        public CustomerNote Save(CustomerNote customerNote)
        {
            var url = string.Format("CustomerNote/Save?apikey={0}&companyid={1}", _apiKey, _companyId);
            var request = new RestRequest(url, Method.POST) { JsonSerializer = new JsonSerializer() };
            request.RequestFormat = DataFormat.Json;
            request.AddBody(customerNote);
            var response = _client.Execute<CustomerNote>(request);
            return response.Data;
        }

        public bool Delete(int id)
        {
            var url = string.Format("CustomerNote/Delete/{0}?apikey={1}&companyid={2}", id, _apiKey, _companyId);
            var response = _client.Execute<CustomerNote>(new RestRequest(url, Method.DELETE));
            return response.ResponseStatus == ResponseStatus.Completed;
        }
    }
}


text:
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module Data.SBV.Compilers.CodeGen where

import Control.Monad.Trans
import Control.Monad.State.Lazy
import Control.Applicative       (Applicative)
import Data.Char                 (toLower, isSpace)
import Data.List                 (nub, isPrefixOf, intercalate, (\\))
import System.Directory          (createDirectory, doesDirectoryExist, doesFileExist)
import System.FilePath           ((</>))
import Text.PrettyPrint.HughesPJ (Doc, vcat)
import qualified Text.PrettyPrint.HughesPJ as P (render)

import Data.SBV.BitVectors.Data

-- | Abstract over code generation for different languages
class CgTarget a where
  targetName :: a -> String
  translate  :: a -> CgConfig -> String -> CgState -> Result -> CgPgmBundle

-- | Options for code-generation.
data CgConfig = CgConfig {
          cgRTC         :: Bool               -- ^ If 'True', perform run-time-checks for index-out-of-bounds or shifting-by-large values etc.
        , cgInteger     :: Maybe Int          -- ^ Bit-size to use for representing SInteger (if any)
        , cgReal        :: Maybe CgSRealType  -- ^ Type to use for representing SReal (if any)
        , cgDriverVals  :: [Integer]          -- ^ Values to use for the driver program generated, useful for generating non-random drivers.
        , cgGenDriver   :: Bool               -- ^ If 'True', will generate a driver program
        , cgGenMakefile :: Bool               -- ^ If 'True', will generate a makefile
        }

-- | Default options for code generation. The run-time checks are turned-off, and the driver values are completely random.
defaultCgConfig :: CgConfig
defaultCgConfig = CgConfig { cgRTC = False, cgInteger = Nothing, cgReal = Nothing, cgDriverVals = [], cgGenDriver = True, cgGenMakefile = True }

-- | Abstraction of target language values
data CgVal = CgAtomic SW
           | CgArray  [SW]

-- | Code-generation state
data CgState = CgState {
          cgInputs       :: [(String, CgVal)]
        , cgOutputs      :: [(String, CgVal)]
        , cgReturns      :: [CgVal]
        , cgPrototypes   :: [String]    -- extra stuff that goes into the header
        , cgDecls        :: [String]    -- extra stuff that goes into the top of the file
        , cgLDFlags      :: [String]    -- extra options that go to the linker
        , cgFinalConfig  :: CgConfig
        }

-- | Initial configuration for code-generation
initCgState :: CgState
initCgState = CgState {
          cgInputs       = []
        , cgOutputs      = []
        , cgReturns      = []
        , cgPrototypes   = []
        , cgDecls        = []
        , cgLDFlags      = []
        , cgFinalConfig  = defaultCgConfig
        }

-- | The code-generation monad. Allows for precise layout of input values
-- reference parameters (for returning composite values in languages such as C),
-- and return values.
newtype SBVCodeGen a = SBVCodeGen (StateT CgState Symbolic a)
                   deriving (Applicative, Functor, Monad, MonadIO, MonadState CgState)

-- | Reach into symbolic monad from code-generation
liftSymbolic :: Symbolic a -> SBVCodeGen a
liftSymbolic = SBVCodeGen . lift

-- | Reach into symbolic monad and output a value. Returns the corresponding SW
cgSBVToSW :: SBV a -> SBVCodeGen SW
cgSBVToSW = liftSymbolic . sbvToSymSW

-- | Sets RTC (run-time-checks) for index-out-of-bounds, shift-with-large value etc. on/off. Default: 'False'.
cgPerformRTCs :: Bool -> SBVCodeGen ()
cgPerformRTCs b = modify (\s -> s { cgFinalConfig = (cgFinalConfig s) { cgRTC = b } })

-- | Sets number of bits to be used for representing the 'SInteger' type in the generated C code.
-- The argument must be one of @8@, @16@, @32@, or @64@. Note that this is essentially unsafe as
-- the semantics of unbounded Haskell integers becomes reduced to the corresponding bit size, as
-- typical in most C implementations.
cgIntegerSize :: Int -> SBVCodeGen ()
cgIntegerSize i
  | i `notElem` [8, 16, 32, 64]
  = error $ "SBV.cgIntegerSize: Argument must be one of 8, 16, 32, or 64. Received: " ++ show i
  | True
  = modify (\s -> s { cgFinalConfig = (cgFinalConfig s) { cgInteger = Just i }})

-- | Possible mappings for the 'SReal' type when translated to C. Used in conjunction
-- with the function 'cgSRealType'. Note that the particular characteristics of the
-- mapped types depend on the platform and the compiler used for compiling the generated
-- C program. See <http://en.wikipedia.org/wiki/C_data_types> for details.
data CgSRealType = CgFloat      -- ^ @float@
                 | CgDouble     -- ^ @double@
                 | CgLongDouble -- ^ @long double@
                 deriving Eq

-- | 'Show' instance for 'cgSRealType' displays values as they would be used in a C program
instance Show CgSRealType where
  show CgFloat      = "float"
  show CgDouble     = "double"
  show CgLongDouble = "long double"

-- | Sets the C type to be used for representing the 'SReal' type in the generated C code.
-- The setting can be one of C's @"float"@, @"double"@, or @"long double"@, types, depending
-- on the precision needed. Note that this is essentially unsafe as the semantics of
-- infinite precision SReal values becomes reduced to the corresponding floating point type in
-- C, and hence it is subject to rounding errors.
cgSRealType :: CgSRealType -> SBVCodeGen ()
cgSRealType rt = modify (\s -> s {cgFinalConfig = (cgFinalConfig s) { cgReal = Just rt }})

-- | Should we generate a driver program? Default: 'True'. When a library is generated, it will have
-- a driver if any of the contituent functions has a driver. (See 'compileToCLib'.)
cgGenerateDriver :: Bool -> SBVCodeGen ()
cgGenerateDriver b = modify (\s -> s { cgFinalConfig = (cgFinalConfig s) { cgGenDriver = b } })

-- | Should we generate a Makefile? Default: 'True'.
cgGenerateMakefile :: Bool -> SBVCodeGen ()
cgGenerateMakefile b = modify (\s -> s { cgFinalConfig = (cgFinalConfig s) { cgGenMakefile = b } })

-- | Sets driver program run time values, useful for generating programs with fixed drivers for testing. Default: None, i.e., use random values.
cgSetDriverValues :: [Integer] -> SBVCodeGen ()
cgSetDriverValues vs = modify (\s -> s { cgFinalConfig = (cgFinalConfig s) { cgDriverVals = vs } })

-- | Adds the given lines to the header file generated, useful for generating programs with uninterpreted functions.
cgAddPrototype :: [String] -> SBVCodeGen ()
cgAddPrototype ss = modify (\s -> let old = cgPrototypes s
                                      new = if null old then ss else old ++ [""] ++ ss
                                  in s { cgPrototypes = new })

-- | Adds the given lines to the program file generated, useful for generating programs with uninterpreted functions.
cgAddDecl :: [String] -> SBVCodeGen ()
cgAddDecl ss = modify (\s -> let old = cgDecls s
                                 new = if null old then ss else old ++ [""] ++ ss
                             in s { cgDecls = new })

-- | Adds the given words to the compiler options in the generated Makefile, useful for linking extra stuff in.
cgAddLDFlags :: [String] -> SBVCodeGen ()
cgAddLDFlags ss = modify (\s -> s { cgLDFlags = cgLDFlags s ++ ss })

-- | Creates an atomic input in the generated code.
cgInput :: SymWord a => String -> SBVCodeGen (SBV a)
cgInput nm = do r <- liftSymbolic forall_
                sw <- cgSBVToSW r
                modify (\s -> s { cgInputs = (nm, CgAtomic sw) : cgInputs s })
                return r

-- | Creates an array input in the generated code.
cgInputArr :: SymWord a => Int -> String -> SBVCodeGen [SBV a]
cgInputArr sz nm
  | sz < 1 = error $ "SBV.cgInputArr: Array inputs must have at least one element, given " ++ show sz ++ " for " ++ show nm
  | True   = do rs <- liftSymbolic $ mapM (const forall_) [1..sz]
                sws <- mapM cgSBVToSW rs
                modify (\s -> s { cgInputs = (nm, CgArray sws) : cgInputs s })
                return rs

-- | Creates an atomic output in the generated code.
cgOutput :: SymWord a => String -> SBV a -> SBVCodeGen ()
cgOutput nm v = do _ <- liftSymbolic (output v)
                   sw <- cgSBVToSW v
                   modify (\s -> s { cgOutputs = (nm, CgAtomic sw) : cgOutputs s })

-- | Creates an array output in the generated code.
cgOutputArr :: SymWord a => String -> [SBV a] -> SBVCodeGen ()
cgOutputArr nm vs
  | sz < 1 = error $ "SBV.cgOutputArr: Array outputs must have at least one element, received " ++ show sz ++ " for " ++ show nm
  | True   = do _ <- liftSymbolic (mapM output vs)
                sws <- mapM cgSBVToSW vs
                modify (\s -> s { cgOutputs = (nm, CgArray sws) : cgOutputs s })
  where sz = length vs

-- | Creates a returned (unnamed) value in the generated code.
cgReturn :: SymWord a => SBV a -> SBVCodeGen ()
cgReturn v = do _ <- liftSymbolic (output v)
                sw <- cgSBVToSW v
                modify (\s -> s { cgReturns = CgAtomic sw : cgReturns s })

-- | Creates a returned (unnamed) array value in the generated code.
cgReturnArr :: SymWord a => [SBV a] -> SBVCodeGen ()
cgReturnArr vs
  | sz < 1 = error $ "SBV.cgReturnArr: Array returns must have at least one element, received " ++ show sz
  | True   = do _ <- liftSymbolic (mapM output vs)
                sws <- mapM cgSBVToSW vs
                modify (\s -> s { cgReturns = CgArray sws : cgReturns s })
  where sz = length vs

-- | Representation of a collection of generated programs.
data CgPgmBundle = CgPgmBundle (Maybe Int, Maybe CgSRealType) [(FilePath, (CgPgmKind, [Doc]))]

-- | Different kinds of "files" we can produce. Currently this is quite "C" specific.
data CgPgmKind = CgMakefile [String]
               | CgHeader [Doc]
               | CgSource
               | CgDriver

-- | Is this a driver program?
isCgDriver :: CgPgmKind -> Bool
isCgDriver CgDriver = True
isCgDriver _        = False

-- | Is this a make file?
isCgMakefile :: CgPgmKind -> Bool
isCgMakefile CgMakefile{} = True
isCgMakefile _            = False

-- | A simple way to print bundles, mostly for debugging purposes.
instance Show CgPgmBundle where
   show (CgPgmBundle _ fs) = intercalate "\n" $ map showFile fs
    where showFile :: (FilePath, (CgPgmKind, [Doc])) -> String
          showFile (f, (_, ds)) =  "== BEGIN: " ++ show f ++ " ================\n"
                                ++ render' (vcat ds)
                                ++ "== END: " ++ show f ++ " =================="

-- | Generate code for a symbolic program, returning a Code-gen bundle, i.e., collection
-- of makefiles, source code, headers, etc.
codeGen :: CgTarget l => l -> CgConfig -> String -> SBVCodeGen () -> IO CgPgmBundle
codeGen l cgConfig nm (SBVCodeGen comp) = do
   (((), st'), res) <- runSymbolic' CodeGen $ runStateT comp initCgState { cgFinalConfig = cgConfig }
   let st = st' { cgInputs       = reverse (cgInputs st')
                , cgOutputs      = reverse (cgOutputs st')
                }
       allNamedVars = map fst (cgInputs st ++ cgOutputs st)
       dupNames = allNamedVars \\ nub allNamedVars
   unless (null dupNames) $
        error $ "SBV.codeGen: " ++ show nm ++ " has following argument names duplicated: " ++ unwords dupNames
   return $ translate l (cgFinalConfig st) nm st res

-- | Render a code-gen bundle to a directory or to stdout
renderCgPgmBundle :: Maybe FilePath -> CgPgmBundle -> IO ()
renderCgPgmBundle Nothing        bundle                = print bundle
renderCgPgmBundle (Just dirName) (CgPgmBundle _ files) = do
        b <- doesDirectoryExist dirName
        unless b $ do putStrLn $ "Creating directory " ++ show dirName ++ ".."
                      createDirectory dirName
        dups <- filterM (\fn -> doesFileExist (dirName </> fn)) (map fst files)
        goOn <- case dups of
                  [] -> return True
                  _  -> do putStrLn $ "Code generation would override the following " ++ (if length dups == 1 then "file:" else "files:")
                           mapM_ (\fn -> putStrLn ('\t' : fn)) dups
                           putStr "Continue? [yn] "
                           resp <- getLine
                           return $ map toLower resp `isPrefixOf` "yes"
        if goOn then do mapM_ renderFile files
                        putStrLn "Done."
                else putStrLn "Aborting."
  where renderFile (f, (_, ds)) = do let fn = dirName </> f
                                     putStrLn $ "Generating: " ++ show fn ++ ".."
                                     writeFile fn (render' (vcat ds))

-- | An alternative to Pretty's 'render', which might have "leading" white-space in empty lines. This version
-- eliminates such whitespace.
render' :: Doc -> String
render' = unlines . map clean . lines . P.render
  where clean x | all isSpace x = ""
                | True          = x


text:
from tulip import *
import tulipplugins

class FilterCCbySize(tlp.Algorithm):
	def __init__(self, context):
		tlp.Algorithm.__init__(self, context)
		self.addIntegerParameter("size", "the degree we want to compare with", "5", True)
		self.addBooleanParameter("delete", "delete the nodes", "false", False)
		self.addStringCollectionParameter("operator", "the comparison operator (d op length)", "<;<=;==;!=;>;>=;",True)

	def check(self):
		return (True, "")

	def run(self):
		size = self.dataSet["size"]
		delete = self.dataSet["delete"]
		operator = self.dataSet["operator"].getCurrentString()

		selectedCC = []
		ccList = tlp.ConnectedTest.computeConnectedComponents(self.graph)
		for cc in ccList:

			d = len(cc)

			if operator == ">":
				if d > size:
					selectedCC.append(cc)

			if operator == ">=":
				if d >= size:
					selectedCC.append(cc)

			if operator == "<":
				if d < size:
					selectedCC.append(cc)

			if operator == "<=":
				if d <= size:
					selectedCC.append(cc)

			if operator == "==":
				if d == size:
					selectedCC.append(cc)

			if operator == "!=":
				if d != size:
					selectedCC.append(cc)

		if delete:
			for cc in selectedCC:
				graph.delNodes(cc)
		else:
			vS = self.graph["viewSelection"]
			for cc in selectedCC:
				for n in cc:
					vS[n] = True
		return True

# The line below does the magic to register the plugin to the plugin database
# and updates the GUI to make it accessible through the menus.
tulipplugins.registerPluginOfGroup("FilterCCbySize", "Filter Connected Components by Size", "Benjamin Renoust", "27/05/2015", "Filter Connected Components by Size", "1.0", "Filter")


text:
namespace RavenDBReplicationSample.Sample
{
    using System.Collections.Generic;
    using System.Configuration;
    using Dto;
    using RavenAccess;

    /// <summary>
    /// Example class showing how to interact with RavenDB.
    /// </summary>
    public static class Replication
    {
        private const string REPLICATION_DESTINATIONS_ID = "Raven/Replication/Destinations";

        /// <summary>
        /// Shows how to delete all records that mach a specific query in RavenDB
        /// </summary>
        internal static void SetupReplicationDestination()
        {
            var session = RavenSession.OpenSession();

            var allAlbums = session.Load<ReplicationDestinations>(REPLICATION_DESTINATIONS_ID);

            allAlbums.Destinations = new List<Destination>
                {
                    new Destination
                        {
                            Url = ConfigurationManager.ConnectionStrings["RavenDBReplicated"].ConnectionString
                        }
                };

            session.SaveChanges();

            RavenSession.SaveAndCloseSession(session);
        }
    }
}


text:
<?php
require_once( 'auth_REST_SOAP.php' );

use cascade_ws_AOHS      as aohs;
use cascade_ws_constants as c;
use cascade_ws_asset     as a;
use cascade_ws_property  as p;
use cascade_ws_utility   as u;
use cascade_ws_exception as e;

try
{
    $site_name = "about-test";
    $cascade->getAsset( a\Folder::TYPE, "_cascade", $site_name )->
        setShouldBeIndexed( false )->
        setShouldBePublished( false )->
        edit();
    $cascade->getAsset( a\Folder::TYPE, "_extra", $site_name )->
        setShouldBeIndexed( false )->
        setShouldBePublished( true )->
        edit();

    u\DebugUtility::dumpRESTCommands( $service );
}
catch( \Exception $e )
{
    echo S_PRE . $e . E_PRE;
}
catch( \Error $er )
{
    echo S_PRE . $er . E_PRE;
}
?>


text:
'use strict';

/**
 * @ignore
 * @suppress {duplicate}
 */
var fs = require('fs');

/**
 * @ignore
 * @suppress {duplicate}
 */
var util = require('util');

/**
 * @ignore
 * @suppress {duplicate}
 */
var mkdirp = /** @type {function(string, Object, function(Error))} */ (require('mkdirp'));

/**
 * @ignore
 * @suppress {duplicate}
 */
var Q = require('q');

/**
 * @ignore
 * @suppress {duplicate}
 */
var Compiler = /** @type {function(new:Compiler): undefined} */ (require('./Compiler.js'));

/**
 * @ignore
 * @suppress {duplicate}
 */
var ClosureCompiler = /** @type {function(new:ClosureCompiler): undefined} */ (require('./ClosureCompiler.js'));

/**
 * @ignore
 * @suppress {duplicate}
 */
var CCCache = /** @type {function(new:CCCache, string): undefined} */ (require('./CCCache.js'));

/**
 * The constructor function for {@link CachingCompiler}.
 *
 * @classdesc This class is wrapper for the Google Closure Compiler that additionaly caches previous results. In case a
 *            cached result is available no compilation is required otheriwse the Google Closure Compiler is used to
 *            generate the sources. Finally the JavaScript code is returned as a result.
 *
 * @constructor
 *
 * @extends Compiler
 *
 * @param {!string} cacheFolder A folder path where CCBuild stores all cached content.
 */
function CachingCompiler (cacheFolder) {
    this._closureCompiler = new ClosureCompiler();
    this._cache = new CCCache(cacheFolder);
}

util.inherits(CachingCompiler, Compiler);

/**
 * Compiles a compilation unit and returns the JavaScript code as result. In case a cached result is available no
 * compilation is required otheriwse the Google Closure Compiler is used to generate the sources. Finally the JavaScript
 * code is returned as a result.
 *
 * @override
 *
 * @returns {QPromise<CompilationResult>} A promise holding the compilation result.
 * @param {!CompilerConfiguration} compilationUnit The compiler configuration for the current compilation unit.
 *
 * @throws {Error} Thrown if compilationUnit is of a wrong type.
 */
CachingCompiler.prototype.compile = function (compilationUnit) {
    var self = this;
    var compilationResult;
    return this._createCacheFolderIfRequired()
        .then(function () {
            return self._cache.get(compilationUnit);
        })
        .catch(function (err) {
            return self._closureCompiler.compile(compilationUnit)
                .then(function (_compilationResult) {
                    compilationResult = _compilationResult;
                })
                .then(function () {
                    return self._cache.write(compilationUnit, compilationResult)
                        .then(function () {
                            return self._cache.persist();
                        })
                        .then(function () {
                            return compilationResult;
                        })
                        .catch(function (err) {
                            return compilationResult;
                        });
                });
        });
};

/**
 * Create the cache folder in case it does not exist yet.
 *
 * @private
 *
 * @returns {QPromise} A resolved promise in case the cache folder was created successful or did already exist.
 *                     A rejected promise holding an error object in case the cache folder could not be created.
 */
CachingCompiler.prototype._createCacheFolderIfRequired = function () {
    var self = this;
    var deferred = Q.defer();
    mkdirp(this._cache.getCacheFolder(), {mode: 0o775}, function (errMkdirp) {
        if (errMkdirp && /** @type {{code: string}} */ (errMkdirp).code === 'EEXIST') {
            fs.stat(self._cache.getCacheFolder(), function (errStat, stats) {
                if (errStat) {
                    deferred.reject(errStat);
                } else {
                    if (!stats.isDirectory()) {
                        deferred.reject(new Error('The cache folder ' + self._cache.getCacheFolder() + ' is not a ' +
                                                  'directory'));
                    } else {
                        fs.access(self._cache.getCacheFolder(), fs.R_OK | fs.W_OK | fs.X_OK, function (errAccess) {
                            if (errAccess) {
                                deferred.reject(errAccess);
                            } else {
                                deferred.resolve();
                            }
                        });
                    }
                }
            });
        } else if (errMkdirp) {
            deferred.reject(errMkdirp);
        } else {
            deferred.resolve();
        }
    });
    return deferred.promise;
};

module.exports = CachingCompiler;


text:
Introduction
---------
Yii-Phpass is a simple wrapper for [Phpass 0.3](http://www.openwall.com/phpass/)
in the [Yii Framework](http://www.yiiframework.com/)

###Requirements

* Yii 1.0 or above
* PHP 5.3 or PHP with Suhosin Patch *strongly* recommended

###Installation

* Extract the release file under `protected/extensions/phpass`
* Add a line to your configuration file to import the extension:
```
'import'=>array(
    ...
    'application.extensions.phpass.*',
),
```
* Add to your main.php file within your Yii project, inside the component array:
```
'components'=>array(
    'hasher'=>array (
        'class'=>'Phpass',
        'hashPortable'=>false,
        'hashCostLog2'=>8,
    ),
),
```

###Usage

Access the Phpass object:
```
Yii::app()->hasher
```

For a New Password:
```
$theirHashToStore = Yii::app()->hasher->hashPassword($theirPassword);
```

Authenticate an Existing Password:
```
$isValid = Yii::app()->hasher->checkPassword($theirPassword, $theirStoredHash);
```

License
---------
Modified BSD License
[https://github.com/gtcode/Yii-Phpass](https://github.com/gtcode/Yii-Phpass)


text:
package com.moonlightpixels.jrpg.legacy.map;

import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.moonlightpixels.jrpg.legacy.graphics.GraphicsService;

import java.io.Serializable;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public final class MapLayer {
    private static final EntitiesToRenderComparator ENTITIES_TO_RENDER_COMPARATOR = new EntitiesToRenderComparator();

    private final int layerIndex;
    private final TiledMapRenderer mapRenderer;
    private final List<TiledMapTileLayer> backgroundLayers = new LinkedList<>();
    private final List<TiledMapTileLayer> foregroundLayers = new LinkedList<>();
    private TiledMapTileLayer collisionLayer;

    public MapLayer(final int layerIndex, final TiledMapRenderer mapRenderer) {
        this.layerIndex = layerIndex;
        this.mapRenderer = mapRenderer;
    }

    public void addBackgroundLayer(final TiledMapTileLayer tileLayer) {
        backgroundLayers.add(tileLayer);
    }

    public void addForegroundLayer(final TiledMapTileLayer tileLayer) {
        foregroundLayers.add(tileLayer);
    }

    public TiledMapTileLayer getCollisionLayer() {
        return collisionLayer;
    }

    public void setCollisionLayer(final TiledMapTileLayer collisionLayer) {
        this.collisionLayer = collisionLayer;
    }

    public void render(final GraphicsService graphicsService, final List<Entity> entities) {
        backgroundLayers.forEach(mapRenderer::renderTileLayer);

        entities
            .stream()
            .filter(entity -> entity.getLocation().getMapLayer() == layerIndex)
            .sorted(ENTITIES_TO_RENDER_COMPARATOR)
            .forEach(entity -> entity.render(graphicsService));

        foregroundLayers.forEach(mapRenderer::renderTileLayer);
    }

    public boolean isCollision(final TileCoordinate coordinate) {
        if (collisionLayer != null) {
            final TiledMapTileLayer.Cell cell = collisionLayer.getCell(coordinate.getX(), coordinate.getY());
            if (cell != null) {
                return true;
            }
        }

        return false;
    }

    public boolean isBackground(final String layerName) {
        return backgroundLayers.stream().anyMatch(layer -> layerName.equals(layer.getName()));
    }

    private static class EntitiesToRenderComparator implements Comparator<Entity>, Serializable {
        private static final long serialVersionUID = 8367751493774593999L;

        @Override
        public int compare(final Entity left, final Entity right) {
            // sort in descending order by Y position
            return Float.compare(right.getPositionY(), left.getPositionY());
        }
    }
}


text:
static char * doubleToString(Object * obj) {
	Double * d = (Double * ) obj;
	char buffer[64];
	snprintf(buffer, sizeof(buffer), "%g", d->value);
	return strdup(buffer);
}

ObjectVTable DoubleVTable = {
	.name = "Double",

	.parent = NULL,
	.toString = doubleToString,
	.free = NULL,
};

Double * newDouble(Collector *c, double d) {
	Double * result = malloc(sizeof(Double));
	if (!result) return NULL;
	result->object.vt = &DoubleVTable;
	result->value = d;
	if (!collectorIntern(c, (Object *) result)) goto fail;
	return result;
fail:
	free(result);
	return NULL;
}


text:
namespace search
{

void GetStreetNameAsKey(string const & name, string & res);

class FeatureLoader
{
  Index const * m_pIndex;
  Index::FeaturesLoaderGuard * m_pGuard;

  void CreateLoader(MwmSet::MwmId const & mwmId);

public:
  FeatureLoader(Index const * pIndex);
  ~FeatureLoader();

  void Load(FeatureID const & id, FeatureType & f);
  void Free();

  template <class ToDo> void ForEachInRect(m2::RectD const & rect, ToDo toDo);
};

struct ParsedNumber
{
  string m_fullN;
  int m_startN, m_endN;

public:
  /// @todo Pass correct "American" notation flag.
  ParsedNumber(string const & number, bool american = false);

  inline string const & GetNumber() const { return m_fullN; }
  inline bool IsOdd() const { return (m_startN % 2 == 1); }
  inline int GetIntNumber() const { return m_startN; }

  bool IsIntersect(ParsedNumber const & number, int offset = 0) const;
};

class House
{
  ParsedNumber m_number;
  m2::PointD m_point;

public:
  House(string const & number, m2::PointD const & point)
    : m_number(number), m_point(point)
  {
  }

  inline string const & GetNumber() const { return m_number.GetNumber(); }
  inline int GetIntNumber() const { return m_number.GetIntNumber(); }
  inline m2::PointD const & GetPosition() const { return m_point; }

  /// @return \n
  /// -1 - no match;
  ///  0 - full match;
  ///  1 - integer number match with odd (even).
  ///  2 - integer number match.
  int GetMatch(ParsedNumber const & number) const;
  bool GetNearbyMatch(ParsedNumber const & number) const;
};

struct HouseProjection
{
  House const * m_house;
  m2::PointD m_proj;
  double m_distance;
  /// Distance in mercator, from street beginning to projection on street
  double m_streetDistance;
  /// false - to the left, true - to the right from projection segment
  bool m_projectionSign;

  inline bool IsOdd() const { return (m_house->GetIntNumber() % 2 == 1); }

  struct LessDistance
  {
    bool operator() (HouseProjection const * p1, HouseProjection const * p2) const
    {
      return p1->m_distance < p2->m_distance;
    }
  };

  class EqualHouse
  {
    House const * m_house;
  public:
    EqualHouse(House const * h) : m_house(h) {}
    bool operator() (HouseProjection const * p) const { return m_house == p->m_house; }
  };
};

// many features combines to street
class Street
{
  string m_name;
  string m_processedName;

public:
  void SetName(string const & name);

  vector<m2::PointD> m_points;
  vector<HouseProjection> m_houses;
  double m_length;      /// Length in mercator
  int m_number;         /// Some ordered number after merging
  bool m_housesReaded;

  Street() : m_length(0.0), m_number(-1), m_housesReaded(false) {}

  void Reverse();
  void SortHousesProjection();

  /// Get limit rect for street with ortho offset to the left and right.
  m2::RectD GetLimitRect(double offsetMeters) const;

  inline static bool IsSameStreets(Street const * s1, Street const * s2)
  {
    return s1->m_processedName == s2->m_processedName;
  }

  inline string const & GetDbgName() const { return m_processedName; }
  inline string const & GetName() const { return m_name; }
};

class MergedStreet
{
  double m_length;
public:
  deque<Street *> m_cont;

  MergedStreet() : m_length(0.0) {}

  string const & GetDbgName() const;
  string const & GetName() const;
  bool IsHousesReaded() const;
  void FinishReadingHouses();

  HouseProjection const * GetHousePivot(bool isOdd, bool & sign) const;

  struct GreaterLength
  {
    bool operator() (MergedStreet const & s1, MergedStreet const & s2) const
    {
      return (s1.m_length > s2.m_length);
    }
  };

  inline void Swap(MergedStreet & s)
  {
    m_cont.swap(s.m_cont);
    std::swap(m_length, s.m_length);
  }

public:
  struct Index
  {
    size_t s, h;
    Index() : s(0), h(0) {}
  };

  inline Index Begin() const
  {
    Index i;
    Next(i);
    return i;
  }
  inline void Inc(Index & i) const
  {
    ++i.h;
    Next(i);
  }
  inline bool IsEnd(Index const & i) const
  {
    return i.s == m_cont.size();
  }
  inline HouseProjection const & Get(Index const & i) const
  {
    ASSERT(!IsEnd(i), ());
    return m_cont[i.s]->m_houses[i.h];
  }

private:
  void Erase(Index & i);
  void Next(Index & i) const;
};

inline void swap(MergedStreet & s1, MergedStreet & s2)
{
  s1.Swap(s2);
}

struct HouseResult : public IndexedValueBase<1>
{
  House const * m_house;
  MergedStreet const * m_street;

  HouseResult(House const * house, MergedStreet const * street)
    : m_house(house), m_street(street)
  {}

  inline bool operator<(HouseResult const & a) const { return m_house < a.m_house; }
  inline bool operator==(HouseResult const & a) const { return m_house == a.m_house; }

  m2::PointD const & GetOrg() const { return m_house->GetPosition(); }
};

inline string DebugPrint(HouseResult const & r)
{
  return r.m_house->GetNumber() + ", " + r.m_street->GetName();
}

class HouseDetector
{
  FeatureLoader m_loader;

  typedef map<FeatureID, Street *> StreetMapT;
  StreetMapT m_id2st;
  typedef map<FeatureID, House *> HouseMapT;
  HouseMapT m_id2house;

  vector<pair<m2::PointD, Street *> > m_end2st;
  vector<MergedStreet> m_streets;

  double m_metres2Mercator;
  int m_streetNum;
  double m_houseOffsetM;

  typedef pair<Street *, bool> StreetPtr;
  StreetPtr FindConnection(Street const * st, bool beg) const;
  void MergeStreets(Street * st);

  template <class ProjectionCalcT>
  void ReadHouse(FeatureType const & f, Street * st, ProjectionCalcT & calc);
  void ReadHouses(Street * st, double offsetMeters);

  void SetMetres2Mercator(double factor);

  double GetApprLengthMeters(int index) const;

public:
  HouseDetector(Index const * pIndex);
  ~HouseDetector();

  int LoadStreets(vector<FeatureID> const & ids);
  /// @return number of different joined streets.
  int MergeStreets();

  static int const DEFAULT_OFFSET_M = 200;
  void ReadAllHouses(double offsetMeters = DEFAULT_OFFSET_M);

  void GetHouseForName(string const & houseNumber, vector<HouseResult> & res);

  void ClearCaches();
  void ClearUnusedStreets(vector<FeatureID> const & ids);
};

}


text:
module FishtreeApi
  module Services
    class Deal
      def initialize(access_token)
        @access_token = access_token
      end

      def status_check
        @access_token.get('/deals/status_check').parsed
      end

      def links
        FishtreeApi::Services::Deal::Link.new(@access_token)
      end

      def index(opts = {})
        params = URI.encode opts.map { |k, v| "#{k}=#{v}" }.join('&')
        data = @access_token.get("/deals/?#{params}").parsed
        deals = []
        data['deals'].each do |deal|
          deals << DealDto.new(deal)
        end
        return PaginationDto.new(data), deals
      end

      def show(opts = {})
        deal_id = get_deal_id opts
        params = URI.encode opts.map { |k, v| "#{k}=#{v}" }.join('&')
        deal = @access_token.get("/deals/find?#{params}") if deal_id.nil?
        deal = @access_token.get("/deals/#{deal_id}?#{params}") unless deal_id.nil?
        return DealDto.new(deal.parsed['deal']) if deal.status == 200
        deal.parsed
      end

      def create(opts = {})
        deal = @access_token.post('/deals/', { body: opts.to_json, headers: { 'Content-Type' => 'application/json' } })
        return DealDto.new(deal.parsed['deal']) if deal.status == 201
        deal.parsed
      end

      def update(opts = {})
        deal_id = opts[:deal][:id]
        deal = @access_token.put("/deals/#{deal_id}", { body: opts.to_json, headers: { 'Content-Type' => 'application/json' } })
        return DealDto.new(deal.parsed['deal']) if deal.status == 200
        deal.parsed
      end

      def destroy(id)
        @access_token.delete("/deals/#{id}").parsed
      end

      def show_all(opts = {})
        data = @access_token.get('/deals/all', params: opts).parsed
        deals = []
        data['deals'].each do |deal|
          deals << DealDto.new(deal)
        end
        deals
      end

      # NOTE: no access token required to use this endpoint
      def districts
        deals = []
        begin
          data = Net::HTTP.get(URI("#{FishtreeApi.configuration.auth_site}/deals/deals_list"))
          data = JSON.parse(data)
          data['deals'].each do |deal|
            deals << DealDto.new(deal)
          end
        rescue StandardError
        end
        deals
      end

      def schools(opts = {})
        data = @access_token.get('/deals/schools', params: opts).parsed
        schools = []
        data['schools'].each do |school|
          schools << SchoolDto.new(school)
        end
        schools
      end

      private

      def get_deal_id(opts)
        id = opts[:id]
        opts.delete(:id)
        id
      end
    end
  end
end


text:
require 'spec_helper'
require_relative '../../../../apps/api/controllers/quizzes/update'

describe Api::Controllers::Quizzes::Update do
  let(:quiz) { Factory.create_quiz }
  let(:action) { Api::Controllers::Quizzes::Update.new }
  let(:params) { { id: quiz.id, quiz: { name: "new-test-name" } } }

  it 'is successful' do
    response = action.call(params)
    response[0].must_equal 201
  end
end